<?php
ob_start();
session_start();

global $conn;

include "config.php";
include "../config.php";
include "../function.php";

/* ---------------- USER DATA ---------------- */
$mobile = $_SESSION["username"];
$user = "SELECT * FROM users WHERE mobile = '$mobile'";
$uu = mysqli_query($conn, $user);
$userdata = mysqli_fetch_array($uu);

/* ---------------- MAIN LOGIC ---------------- */
if (!isset($_POST["amount"])) {
    die("No Data Found");
}

$amount   = $_POST["amount"];
$payfor   = $_POST["for"];
$order_id = "TEZ" . time() . rand(11111, 99999);
$url      = "https://" . $_SERVER["SERVER_NAME"] . "/api/create-order";
$remark2  = "";

setcookie("order_id_cookie", $order_id, time() + 360, "/");

$callbackurl = "https://" . $_SERVER["SERVER_NAME"] . "/auth/lib/callback";
$email       = $_SESSION["username"];
$userid      = $_SESSION["user_id"];

/* ---------------- ADD BALANCE ---------------- */
if ($payfor == "addbalance") {

    $data = [
        "customer_mobile" => $email,
        "user_token"      => $token,
        "amount"          => $amount,
        "order_id"        => $order_id,
        "redirect_url"    => $callbackurl,
        "remark1"         => $payfor,
        "remark2"         => $payfor
    ];

}

/* ---------------- PLAN / UPI ---------------- */
if (isset($_POST["upigate"]) || $payfor == "PlanRenew") {

    $planid = $_POST["planid"];
    $isVIP  = $_POST["vip_sub"];

    /* ---- Wallet Use ---- */
    if ($_POST["use_wallet"] == "yes") {

        $walletdebit = $_POST["wallet_used"];

        $esql  = "SELECT expiry,amount FROM subscription_plan WHERE id=$planid";
        $qesql = mysqli_query($conn, $esql);
        $row   = mysqli_fetch_array($qesql);

        $monthsToAdd = $row['expiry'];

        if ($amount == 0) {

            $debit = debit_balance($userid, $walletdebit, $order_id, "Plan Renew");

            if ($debit) {

                $user_sql = "SELECT expiry FROM users WHERE mobile='$email'";
                $user_q   = mysqli_query($conn, $user_sql);
                $user_r   = mysqli_fetch_array($user_q);

                $base = ($user_r['expiry'] && strtotime($user_r['expiry']) > time())
                        ? $user_r['expiry']
                        : date("Y-m-d H:i:s");

                $newExpiry = date("Y-m-d H:i:s", strtotime($base . " +$monthsToAdd months"));

                if ($isVIP == "yes") {
                    $sql = "UPDATE users SET expiry='$newExpiry', planId=$planid, tranjection_Count=0, vip_expiry='$newExpiry' WHERE mobile='$email'";
                } else {
                    $sql = "UPDATE users SET expiry='$newExpiry', planId=$planid, tranjection_Count=0 WHERE mobile='$email'";
                }

                mysqli_query($conn, $sql);

                mysqli_query($conn,
                    "INSERT INTO planorders 
                    (order_id, userid, planid, payment_date, expiry_date, utr, status, remark, userMobile, amount)
                    VALUES 
                    ('$order_id','$userid','$planid',NOW(),'$newExpiry','','SUCCESS','FromWallet','$email',$walletdebit)"
                );

                header("Location: https://" . $_SERVER["SERVER_NAME"] . "/auth/dashboard");
                exit;
            }
        }

        $remark2 = "wallet_used";
    }

    setcookie("planid_cookie", $planid, time() + 360, "/");
    setcookie("isVip_cookie", $isVIP, time() + 360, "/");

    $data = [
        "customer_mobile" => $email,
        "user_token"      => $token,
        "amount"          => $amount,
        "order_id"        => $order_id,
        "redirect_url"    => $callbackurl,
        "remark1"         => $payfor,
        "remark2"         => $remark2
    ];
}

/* ---------------- CURL REQUEST ---------------- */
$ch = curl_init();
curl_setopt_array($ch, [
    CURLOPT_URL            => $url,
    CURLOPT_POST           => true,
    CURLOPT_POSTFIELDS     => http_build_query($data),
    CURLOPT_RETURNTRANSFER => true
]);

$response = curl_exec($ch);

if (curl_errno($ch)) {
    die("CURL ERROR : " . curl_error($ch));
}
curl_close($ch);

/* ---------------- RESPONSE HANDLE ---------------- */
$json = json_decode($response, true);

if ($json && $json["status"] == true && isset($json["result"]["payment_url"])) {

    if ($payfor == "PlanRenew") {
        mysqli_query($conn,
            "INSERT INTO planorders 
            (order_id, userid, planid, payment_date, expiry_date, utr, status, remark, userMobile, amount)
            VALUES 
            ('$order_id','$userid','$planid',NOW(),DATE_ADD(NOW(),INTERVAL 30 DAY),'','PENDING','UPI','$email',$amount)"
        );
    }

    /* ✅ FINAL REDIRECT (THIS WAS BUG) */
    header("Location: " . $json["result"]["payment_url"]);
    exit;
}

/* ---------------- FAILED ---------------- */
echo "<script>
alert(" . json_encode($json["message"] ?? "Payment Error") . ");
window.history.back();
</script>";
exit;
?>
