<?php
/*
 * Copyright (c) 2018-2021 Atipay, (https://www.atipay.net)

 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 * */



if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    require_once __DIR__ . '/../../../init.php';
    require_once __DIR__ . '/../../../includes/gatewayfunctions.php';
    require_once  __DIR__ . '/fn.atipay.php';

    $token_params = $_POST;
    unset($token_params['submit']);
    $gatewayModuleName = basename(__FILE__, '.php');
    $gatewayParams = getGatewayVariables($gatewayModuleName);

    $redirect_url = $token_params['redirectUrl'];
    $redirect_url = $redirect_url .  '/modules/gateways/callback/' . $gatewayModuleName . '.php';

    $currency = $gatewayParams['siteCurrency'];
    $apiKey = $gatewayParams['apiKey'];

    $invoice_id = $token_params['invoiceNumber'];
    $invoice_data = fn_atipay_get_invoice($invoice_id);

    $amount = $invoice_data['total'];
    if ($currency == 'T'){
        $amount = intval($amount * 10);
    }else{
        $amount = intval($amount);
    }

    $token_params['amount'] = $amount;
    $token_params['apiKey'] = $apiKey;
    $token_params['redirectUrl'] = $redirect_url;


    $token_response = fn_atipay_get_token($token_params);
    if ($token_response['success'] == 1){
       $form =  fn_atipay_redirect_to_psp_form($token_response['token']);
       echo $form;
    }else{
        $back_url = $gatewayParams['systemurl'] . "viewinvoice.php?id=$invoice_id&paymentfailed=true";
        header("Location: $back_url");
    }
}else{
    die('Do not support GET method.');
}