<?php
session_start();
require_once('../config.php');
require_once('config.php');
include_once __DIR__ . '/../../includes/subscription_lib.php';

$orderid = $_COOKIE['order_id_cookie'] ?? '';
$planid = $_COOKIE['planid_cookie'] ?? '';

$subscriptionPageUrl = "https://" . $_SERVER["SERVER_NAME"] . "/auth/subscription";
$dashboardUrl = "https://" . $_SERVER["SERVER_NAME"] . "/auth/dashboard";

$url = "https://" . $_SERVER["SERVER_NAME"] . "/api/check-order-status";
$postData = array(
    "user_token" => $token,
    "order_id" => $orderid
);

$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($postData));
curl_setopt($ch, CURLOPT_TIMEOUT, 30);
$response = curl_exec($ch);

if (curl_errno($ch)) {
    curl_close($ch);
    header("Location: $subscriptionPageUrl?payment_failed=1&reason=network");
    exit;
}
curl_close($ch);

$responseData = json_decode($response, true);

if (!$responseData || ($responseData["status"] ?? '') !== "COMPLETED") {
    // The status-check API itself failed - treat as failed payment, don't silently hang
    header("Location: $subscriptionPageUrl?payment_failed=1&reason=lookup");
    exit;
}

$txnStatus = $responseData["result"]["txnStatus"] ?? '';

if ($txnStatus === 'COMPLETED') {
    // Real payment succeeded - now activate the plan
    $email = $_SESSION['username'] ?? '';
    $safe_email = mysqli_real_escape_string($conn, $email);
    $userLookup = mysqli_query($conn, "SELECT id FROM users WHERE mobile = '$safe_email' LIMIT 1");
    $userRow = $userLookup ? mysqli_fetch_assoc($userLookup) : null;

    if ($userRow && activatePlanForUser($conn, $userRow['id'], $planid)) {
        header("Location: $dashboardUrl?plan_activated=1");
        exit;
    }

    // Payment succeeded but activation failed for some reason - don't lose the payment silently
    header("Location: $dashboardUrl?plan_activated=0&reason=activation_error");
    exit;

} elseif ($txnStatus === 'FAILURE') {
    header("Location: $subscriptionPageUrl?payment_failed=1");
    exit;

} else {
    // Still PENDING - send them back with a message rather than a blank/broken screen
    header("Location: $subscriptionPageUrl?payment_pending=1");
    exit;
}
