<?php
require('./academia/mobilePayment.php');
require_once("./config/QueryBuilder.php");
require_once("./networkPaymentGateway/NetworkPaymentGateway.php");   
// use PaymentGateways\Network\NetworkGateway;                 
$networkObj = new NetworkGateway();
$classObject = new MobilePayment();
$queryBuilder = new QueryBuilder($conn);
$logQuery = "SELECT * FROM information_schema.tables WHERE table_schema =  '".$db_name."' AND table_name = 'mobile_payment' LIMIT 1";
$select = mysqli_query($conn, $logQuery);
$result = array(
    'success' => false,
    'message' => 'Something went wrong'
);
if (mysqli_num_rows($select) > 0)
{
    if(!isset($_POST['onlinePaymentId']))
    {
        $_POST = json_decode(file_get_contents("php://input"), true);
    }
    $activeGateway = isset($_POST['activeGateway']) ? trim($_POST['activeGateway']) : '';
    $onlinePaymentId = isset($_POST['onlinePaymentId']) ? trim($_POST['onlinePaymentId']) : '';
    $academyLocationId = isset($_POST['academyLocationId']) ? trim($_POST['academyLocationId']) : '';
    $amount = isset($_POST['amount']) ? trim($_POST['amount']) : '';
    $name = isset($_POST['name']) ? trim($_POST['name']) : '';
    $email = isset($_POST['email']) ? trim($_POST['email']) : '';
    $phoneNo = isset($_POST['mobNo']) ? trim($_POST['mobNo']) : '';
    $applicantId = isset($_POST['applicantId']) ? trim($_POST['applicantId']) : '';
    $studentId = isset($_POST['studentId']) ? trim($_POST['studentId']) : '';
    $code = isset($_POST['code']) ? trim($_POST['code']) : '';    
    $txnId = $_POST['txn_id'] = $onlinePaymentId.'-'.time().rand(101,200);

    if(($onlinePaymentId && $academyLocationId && $amount && $amount > 0) && ($applicantId || $studentId) && $code && $txnId)
    {
        $sql = "SELECT * FROM `mobile_payment` WHERE onlinePaymentId = '".$onlinePaymentId."'";
        $select = mysqli_query($conn, $sql);
        if(mysqli_num_rows($select) == 0)
        {
            $merchantDetails = $classObject->getMerchantDetailsByAl($academyLocationId);                    
            if($merchantDetails == 'ACCESS_TOKEN')
            {
                $result = array(
                    'success' => false,
                    'message' => 'Server Error'
                );
            }
            else if($merchantDetails == 'No_DATA')
            {
                $result = array(
                    'success' => false,
                    'message' => 'Configuration Issue'
                );
            }
            else
            {
                $paymentDate = date('Y-m-d H:i:s');
                $query = "INSERT INTO mobile_payment (onlinePaymentId,txnId,gatewayConfig,paymentStatus,paymentDate,receiptStatus,amount,name,email,phoneNo,applicantId,studentId,code,paymentOption,formSubmissionStatus,academyLocationId,notificationResponse,paymentRequest) VALUES ('" . $onlinePaymentId . "','".$txnId."','','Initiate', '".$paymentDate."','', '".$amount."', '".$name."', '".$email."', '".$phoneNo."', '".$applicantId."', '".$studentId."', '".$code."', '".$activeGateway."','0', '".$academyLocationId."','','')";
                
                mysqli_query($conn, $query);
                $paymentId = mysqli_insert_id($conn);
                   
                if($paymentId)
                {
                    if($activeGateway == 'network')
                    {
                       
                        $gatewayJSON = <<<GATEWAYJSON
                                        {
                                            "authApiKey": "{$merchantDetails['username']}",
                                            "outletId": "{$merchantDetails['password']}",
                                            "environment": "{$merchantDetails['environment']}",
                                            "currencyCode": "{$merchantDetails['currencyCode']}"
                                        }
                                        GATEWAYJSON;
                        $updateData = ['gatewayConfig'=> $gatewayJSON,'currency' => $merchantDetails['currencyCode']];
                        $where = ['id'=> $paymentId];
                        $result = $queryBuilder->update('mobile_payment',$updateData,$where);

                        $data = $queryBuilder->selectById('mobile_payment','*',$where);
                        $result = $networkObj->createOrder($data);
                    }
                    else
                    {
                        $result = array(
                            'success' => false,
                            'message' => 'gateway not configured'
                        );
                    }
                   
                }else{
                    $result = array(
                        'success' => false,
                        'message' => 'Something went wrong'
                    );
                }

             
            }
        }
        else
        {
            $result = array(
                'success' => false,
                'message' => 'Transaction already exist'
            );
        }
    }
    else
    {
        $result = array(
            'success' => false,
            'message' => 'Invalid Parameter'
        );
    }
}
else
{
    $result = array(
        'success' => false,
        'message' => 'Mobile data functionality not implemented'
    );
}
echo trim(json_encode($result));