<?php
declare(strict_types=1);

header('Content-Type: application/json');

/*
|--------------------------------------------------------------------------
| Debug Log
|--------------------------------------------------------------------------

file_put_contents(
    __DIR__ . '/create_order_debug.log',
    "HIT\n" . print_r($_POST, true) . "\n",
    FILE_APPEND
);
*/
require_once __DIR__ . '/../pages/dbInfo.php';
require_once __DIR__ . '/../pages/dbFunctions.php';

/*
|--------------------------------------------------------------------------
| Helpers
|--------------------------------------------------------------------------
*/
function isYes($val): bool {
    return strtolower(trim((string)$val)) === 'yes';
}

function RandomNumber(int $length): string {
    $out = '';
    for ($i = 0; $i < $length; $i++) {
        $out .= random_int(0, 9);
    }
    return $out;
}

function GenRandomString(int $length = 10): string {
    $chars = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
    $out = '';
    for ($i = 0; $i < $length; $i++) {
        $out .= $chars[random_int(0, strlen($chars) - 1)];
    }
    return $out;
}

function generateUniqueToken(): string {
    return hash('sha256', time() . bin2hex(random_bytes(16)));
}

/*
|--------------------------------------------------------------------------
| Method Check
|--------------------------------------------------------------------------
*/
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    echo json_encode([
        'status' => false,
        'message' => 'Unauthorized access'
    ]);
    exit;
}

/*
|--------------------------------------------------------------------------
| Input
|--------------------------------------------------------------------------
*/
$customer_mobile = $_POST['customer_mobile'] ?? '';
$user_token      = $_POST['user_token'] ?? '';
$amount          = $_POST['amount'] ?? '';
$order_id        = $_POST['order_id'] ?? '';
$redirect_url    = $_POST['redirect_url'] ?? '';
$remark1         = $_POST['remark1'] ?? '';
$remark2         = $_POST['remark2'] ?? '';

if ($amount === '' || $order_id === '' || $user_token === '') {
    echo json_encode([
        'status' => false,
        'message' => 'Required parameters missing'
    ]);
    exit;
}

/*
|--------------------------------------------------------------------------
| Check duplicate order
|--------------------------------------------------------------------------
*/
$check = getXbyY("SELECT id FROM orders WHERE order_id='$order_id' AND user_token='$user_token'");
if (!empty($check)) {
    echo json_encode([
        'status' => false,
        'message' => 'Order ID already exists'
    ]);
    exit;
}

/*
|--------------------------------------------------------------------------
| Fetch User
|--------------------------------------------------------------------------
*/
$user = getXbyY("SELECT * FROM users WHERE user_token='$user_token' LIMIT 1");
if (empty($user)) {
    echo json_encode([
        'status' => false,
        'message' => 'Invalid user token'
    ]);
    exit;
}

$user = $user[0];
$user_id = (int)$user['id'];

if ($user['expiry'] < date('Y-m-d')) {
    echo json_encode([
        'status' => false,
        'message' => 'Your plan has expired'
    ]);
    exit;
}

$byteTxn = 'BYTE' . random_int(1000, 9999) . time();
$now = date('Y-m-d H:i:s');
$server = $_SERVER['SERVER_NAME'] ?? '24payicon.in';

/*
|--------------------------------------------------------------------------
| Gateway Selection (PRIORITY ORDER)
|--------------------------------------------------------------------------
*/
if (isYes($user['paytm_connected'])) {

    $link_token = generateUniqueToken();
    setXbyY("INSERT INTO payment_links (link_token, order_id, created_at)
             VALUES ('$link_token','$order_id','$now')");

    $gateway_txn = uniqid();
    $paytm_ref   = GenRandomString() . time();

    setXbyY("INSERT INTO orders
        (paytm_txn_ref, gateway_txn, amount, order_id, status, user_token,
         customer_mobile, redirect_url, method, byteTransactionId,
         create_date, remark1, remark2, user_id)
        VALUES
        ('$paytm_ref','$gateway_txn','$amount','$order_id','PENDING','$user_token',
         '$customer_mobile','$redirect_url','Paytm','$byteTxn',
         '$now','$remark1','$remark2','$user_id')");

    echo json_encode([
        'status' => true,
        'message' => 'Order Created Successfully',
        'result' => [
            'orderId' => $order_id,
            'payment_url' => "https://$server/payment3/instant-pay/$link_token"
        ]
    ]);
    exit;
}

if (isYes($user['bharatpe_connected'])) {

    $link_token = generateUniqueToken();
    setXbyY("INSERT INTO payment_links (link_token, order_id, created_at)
             VALUES ('$link_token','$order_id','$now')");

    $gateway_txn = uniqid();

    setXbyY("INSERT INTO orders
        (gateway_txn, amount, order_id, status, user_token,
         customer_mobile, redirect_url, method, byteTransactionId,
         create_date, remark1, remark2, user_id)
        VALUES
        ('$gateway_txn','$amount','$order_id','PENDING','$user_token',
         '$customer_mobile','$redirect_url','Bharatpe','$byteTxn',
         '$now','$remark1','$remark2','$user_id')");

    echo json_encode([
        'status' => true,
        'message' => 'Order Created Successfully',
        'result' => [
            'orderId' => $order_id,
            'payment_url' => "https://$server/payment4/instant-pay/$link_token"
        ]
    ]);
    exit;
}

if (isYes($user['googlepay_connected'])) {

    $link_token = generateUniqueToken();
    setXbyY("INSERT INTO payment_links (link_token, order_id, created_at)
             VALUES ('$link_token','$order_id','$now')");

    $gateway_txn = uniqid();

    setXbyY("INSERT INTO orders
        (gateway_txn, amount, order_id, status, user_token,
         customer_mobile, redirect_url, method, byteTransactionId,
         create_date, remark1, remark2, user_id)
        VALUES
        ('$gateway_txn','$amount','$order_id','PENDING','$user_token',
         '$customer_mobile','$redirect_url','Googlepay','$byteTxn',
         '$now','$remark1','$remark2','$user_id')");

    echo json_encode([
        'status' => true,
        'message' => 'Order Created Successfully',
        'result' => [
            'orderId' => $order_id,
            'payment_url' => "https://$server/payment5/instant-pay/$link_token"
        ]
    ]);
    exit;
}

/*
|--------------------------------------------------------------------------
| FINAL FALLBACK (NO BLANK RESPONSE EVER)
|--------------------------------------------------------------------------
*/
echo json_encode([
    'status' => false,
    'message' => 'No payment gateway linked for this user'
]);
exit;
