<?php
session_start();
require_once '../library/database.php';

if (!isset($_SESSION["session_user"]) || $_SESSION["session_user"] !== TRUE) {
    header("location: " . $app_url . "/login.php");
}

$data = array(
    'status'  => false,
    'message' => '404 Not Found',
    'referenceNo' => '',
);

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    $data['message'] = 'METHOD Not Support';
    echo json_encode($data);
    return;
}

//ห้ามแก้ไขใดตรงนี้
$referenceNo = "ES" . time() . rand(111, 999);
$userid = $con->real_escape_string($_SESSION['userid']);
$account_id = $con->real_escape_string($_SESSION['account_id']);
$amount = (float)$con->real_escape_string($_POST['amount']);

$result = $con->query("SELECT * FROM donate WHERE referenceNo = '{$referenceNo}'");
if ($result->num_rows != 0) {
    echo json_encode($data);
    return;
}

$curl = curl_init();
curl_setopt_array($curl, array(
    CURLOPT_URL => 'https://api.gbprimepay.com/v3/qrcode',
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_ENCODING => '',
    CURLOPT_MAXREDIRS => 10,
    CURLOPT_TIMEOUT => 0,
    CURLOPT_FOLLOWLOCATION => true,
    CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
    CURLOPT_CUSTOMREQUEST => 'POST',
    CURLOPT_POSTFIELDS => array(
        'token' => $gbp_token,
        'amount' => $amount,
        'referenceNo' => $referenceNo,
        'backgroundUrl' => $gbp_backgroundUrl,
        'merchantDefined1' => $userid,
        'merchantDefined2' => $account_id,
    ),
));
$response = curl_exec($curl);
curl_close($curl);

if ($amount == 0) {
    $data['status'] = false;
    $data['message'] = '<div class="alert alert-danger text-center" style="font-size: 14px;font-family: none;">คุณยังไม่ได้เลือกรายการ หรือ ข้อมูลเติมเงินไม่ถูกต้อง !</div>';
} else {
	$data['status'] = true;
	$data['message'] = '<img src="data:image/png;base64,' . base64_encode($response) . '" class="img-thumbnail">';
	$data['referenceNo'] = $referenceNo;
	$con->query("INSERT INTO donate (userid,account_id,amount,status,referenceNo,created_at) VALUES ('{$userid}', {$account_id}, {$amount}, 0, '{$referenceNo}',NOW())");
}
echo json_encode($data);
