<?php
// File: subscription_handler.php (Final Fix)

require_once 'session_init.php'; 
require_once 'db.php';
require_once 'phonepe_config.php';

// --- 1. ROBUST SESSION CHECK ---
if (!isset($_SESSION['registration_data']) || !isset($_SESSION['registration_data']['subscription_pack_id'])) {
    header("Location: register.php?error=session_expired");
    exit();
}
$registration_data = $_SESSION['registration_data'];
$pack_id = $registration_data['subscription_pack_id'];

// --- 2. Fetch Pack Details from DB ---
$stmt_pack = $conn->prepare("SELECT id, price, pack_name, duration_days FROM subscription_packs WHERE id = ?");
$stmt_pack->bind_param("i", $pack_id);
$stmt_pack->execute();
$pack_result = $stmt_pack->get_result();
$pack = $pack_result->fetch_assoc();
$stmt_pack->close();
if (!$pack) {
    header("Location: register.php?error=invalid_pack");
    exit();
}
$amount_in_rupees = $pack['price'];

// --- 3. Prepare Data for DB & PhonePe ---
$merchantTransactionId = "UCF-SUB-" . uniqid(); 

$data_to_store = $registration_data;
$data_to_store['pack_details'] = $pack; 
$serialized_data = serialize($data_to_store); 

// --- 4. Save to 'pending_registrations' table ---
try {
    $stmt_pending = $conn->prepare("INSERT INTO pending_registrations (merchant_transaction_id, registration_data) VALUES (?, ?)");
    $stmt_pending->bind_param("ss", $merchantTransactionId, $serialized_data);
    $stmt_pending->execute();
    $stmt_pending->close();
} catch (Exception $e) {
    error_log("Pending registration insert failed: " . $e->getMessage());
    header('Location: register.php?error=dberror');
    exit();
}

// --- 5. ⭐️ FIX: Save to session AND build URL ---
// This is the "belt and suspenders" approach
$_SESSION['phonepe_txnid'] = $merchantTransactionId; // Fallback
unset($_SESSION['registration_data']);
session_write_close(); // Save the session

// --- 6. Prepare PhonePe Payload ---
$amount_in_paise = $amount_in_rupees * 100;

// This is the URL the user's browser will be sent to.
$redirect_url = "https://unitedculturalforum.com/payment_status.php?txn_id=" . $merchantTransactionId;

// This is the URL PhonePe's server will ping.
$callback_url = "https://unitedculturalforum.com/subscription_callback.php"; // Server webhook

$payload = [
    'merchantId' => $PHONEPE_MERCHANT_ID,
    'merchantTransactionId' => $merchantTransactionId,
    'merchantUserId' => $registration_data['username'],
    'amount' => $amount_in_paise,
    'redirectUrl' => $redirect_url,
    'redirectMode' => 'GET', // Use GET
    'callbackUrl' => $callback_url, 
    'mobileNumber' => $registration_data['phone'] ?? '9999999999',
    'paymentInstrument' => [ 'type' => 'PAY_PAGE' ],
];
// --- END OF FIX ---

// --- 7. Create Hash and Make cURL Request ---
$base64_payload = base64_encode(json_encode($payload));
$hash_string = $base64_payload . $PHONEPE_PAY_ENDPOINT . $PHONEPE_SALT_KEY;
$sha256_hash = hash('sha256', $hash_string);
$x_verify_header = $sha256_hash . '###' . $PHONEPE_SALT_INDEX;

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $PHONEPE_HOST_URL . $PHONEPE_PAY_ENDPOINT);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode(['request' => $base64_payload]));
curl_setopt($ch, CURLOPT_HTTPHEADER, [
    'Content-Type: application/json',
    'X-VERIFY: ' . $x_verify_header,
]);

$response = curl_exec($ch);
$http_status = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);

$json_response = json_decode($response, true);

// --- 8. Redirect user to PhonePe ---
if ($http_status == 200 && isset($json_response['success']) && $json_response['success'] === true) {
    // This is PhonePe's payment page URL
    $payment_page_url = $json_response['data']['instrumentResponse']['redirectInfo']['url'];
    header('Location: ' . $payment_page_url);
    exit();
} else {
    error_log("PhonePe Initiation Error: " . $response);
    header('Location: register.php?error=payment_init_failed');
    exit();
}
?>