<?php

error_reporting(0);

define('ROOT_DIR', realpath(dirname(__FILE__)) . '/../');

require_once ROOT_DIR . 'pages/dbFunctions.php';
require_once ROOT_DIR . 'auth/config.php';
require_once ROOT_DIR . 'pages/dbInfo.php';

date_default_timezone_set('Asia/Kolkata');

function sendJsonResponse($status, $message) {
    header('Content-Type: application/json');
    echo json_encode(['status' => $status, 'message' => $message]);
    exit();
}

if (!isset($conn) || $conn->connect_error) {
    sendJsonResponse('error', 'Internal Server Error: Database connection failed.');
}

$link_token = filter_input(INPUT_POST, 'LINKID', FILTER_SANITIZE_SPECIAL_CHARS);

$order_id = null;
$user_token = null;

if ($link_token) {

    $sql_fetch_link_data = "SELECT order_id, user_token, created_at FROM payment_links WHERE link_token = ?";
    $stmt = $conn->prepare($sql_fetch_link_data);

    if (!$stmt) sendJsonResponse('error', 'Failed to prepare link data.');

    $stmt->bind_param('s', $link_token);
    $stmt->execute();
    $row = $stmt->get_result()->fetch_assoc();
    $stmt->close();

    if (!$row) {
        sendJsonResponse('error', 'Order ID or User Token not found.');
    }

    $order_id = $row['order_id'];
    $user_token = $row['user_token'];

} else {
    $order_id = filter_input(INPUT_POST, 'order_id', FILTER_SANITIZE_SPECIAL_CHARS);
    $user_token = filter_input(INPUT_POST, 'user_token', FILTER_SANITIZE_SPECIAL_CHARS);
}

if (empty($order_id) || empty($user_token)) {
    sendJsonResponse('error', 'Invalid Order ID or User Token.');
}

// Fetch order details
$sql_fetch_order = "SELECT amount, paytm_txn_ref, user_id, remark1, merchentMobile FROM orders WHERE order_id = ? AND user_token = ?";
$stmt = $conn->prepare($sql_fetch_order);
if (!$stmt) sendJsonResponse('error', 'Failed fetching order.');

$stmt->bind_param('ss', $order_id, $user_token);
$stmt->execute();
$order_details = $stmt->get_result()->fetch_assoc();
$stmt->close();

if (!$order_details) {
    sendJsonResponse('error', 'Order details not found.');
}

$db_amount = $order_details['amount'];
$cxrbytectxnref = $order_details['paytm_txn_ref'];
$userid = $order_details['user_id'];
$cxrremark1 = $order_details['remark1'];
$merchentMobile = $order_details['merchentMobile'];

// Fetch user callback
$sql_fetch_user_callback = "SELECT callback_url FROM users WHERE id = ?";
$stmt = $conn->prepare($sql_fetch_user_callback);
if (!$stmt) sendJsonResponse('error', 'Failed fetching callback URL.');

$stmt->bind_param('i', $userid);
$stmt->execute();
$user_row = $stmt->get_result()->fetch_assoc();
$stmt->close();

if (!$user_row) sendJsonResponse('error', 'Callback URL not found.');
$callback_url = $user_row['callback_url'];

// Fetch new API token
$sql_fetch_fc = "SELECT app_fc FROM freecharge_token WHERE user_token = ? AND phoneNumber = ?";
$stmt = $conn->prepare($sql_fetch_fc);
if (!$stmt) sendJsonResponse('error', 'Failed fetching Freecharge token.');

$stmt->bind_param('si', $user_token, $merchentMobile);
$stmt->execute();
$fc_row = $stmt->get_result()->fetch_assoc();
$stmt->close();

if (!$fc_row) sendJsonResponse('error', 'Freecharge token not found.');
$app_fc = $fc_row['app_fc'];

//
// ------------------------------------------------------------------
//  🔥 NEW OFFICIAL API (srv1070916.hstgr.cloud)
// ------------------------------------------------------------------
//

$url = "https://srv1070916.hstgr.cloud/freecharge/check_txn/";

$postFields = http_build_query([
    'appfc' => $app_fc,
    'orderid' => $cxrbytectxnref
]);

$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $postFields);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
    "content-type: application/x-www-form-urlencoded"
]);

$response = curl_exec($ch);
$curlError = curl_error($ch);
curl_close($ch);

if ($curlError) {
    sendJsonResponse('error', 'Freecharge API connection failed.');
}

$response_data = json_decode($response, true);

if (!is_array($response_data)) {
    sendJsonResponse('pending', 'Transaction Pending');
}

//
// SUCCESS RESPONSE CHECK
//
if (isset($response_data['status']) && $response_data['status'] === "SUCCESS") {

    $utr = $response_data['data']['UTR'] ?? ('43' . rand(1000000000, 9999999999));

    // Update Database
    $conn->begin_transaction();
    try {

        $update_order_query = "UPDATE orders SET status='SUCCESS', utr=? WHERE order_id=? AND user_id=?";
        $stmt = $conn->prepare($update_order_query);
        $stmt->bind_param('ssi', $utr, $order_id, $userid);
        $stmt->execute();
        $stmt->close();

        // Reset failCount
        $update_fc_query = "UPDATE freecharge_token SET failCount='0' WHERE phoneNumber=? AND user_id=?";
        $stmt = $conn->prepare($update_fc_query);
        $stmt->bind_param('si', $merchentMobile, $userid);
        $stmt->execute();
        $stmt->close();

        $conn->commit();

    } catch (Exception $e) {
        $conn->rollback();
        sendJsonResponse('error', 'DB update failed.');
    }

    // CALLBACK
    $callbackData = [
        'status' => 'SUCCESS',
        'order_id' => $order_id,
        'amount' => $db_amount,
        'utr' => $utr,
        'remark1' => $cxrremark1
    ];

    $ch = curl_init($callback_url);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($callbackData));
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_exec($ch);
    curl_close($ch);

    sendJsonResponse('success', 'Transaction Successful');
}

//
// ELSE → PENDING
//
sendJsonResponse('pending', 'Transaction Pending');

$conn->close();

?>
