<?php
// File: competition_payment_handler.php
require_once 'session_init.php';
require_once 'db.php';
require_once 'phonepe_config.php';

// Enable error reporting for debugging
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);

// Check if session data exists
if (!isset($_SESSION['competition_entry'])) {
    header("Location: competition.php");
    exit();
}

$entry_data = $_SESSION['competition_entry'];
$comp_id = $entry_data['competition_id'];
$amount = $entry_data['entry_fee'];
$full_name = $entry_data['name']; // matches 'name' in DB
$email = $entry_data['email'];
$phone = $entry_data['phone'];
$message = $entry_data['message'] ?? '';
$user_id = $_SESSION['user_id'] ?? NULL;

// Create Entry Record with 'Pending' status
$merchantTransactionId = "UCF-COMP-" . uniqid();
$status = 'Pending';

try {
    // Insert into competition_entries
    // Using columns: competition_id, user_id, name, email, phone, message, payment_status, merchant_transaction_id, amount_paid
    $stmt_entry = $conn->prepare("INSERT INTO competition_entries (competition_id, user_id, name, email, phone, message, payment_status, merchant_transaction_id, amount_paid) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)");
    
    // Bind parameters: i=integer, s=string, d=double
    // i (comp_id), i (user_id), s (name), s (email), s (phone), s (message), s (status), s (txn_id), d (amount)
    // Total: 9 params -> iissssssd
    $stmt_entry->bind_param("iissssssd", $comp_id, $user_id, $full_name, $email, $phone, $message, $status, $merchantTransactionId, $amount);
    
    $stmt_entry->execute();
    $entry_id = $conn->insert_id;
    $stmt_entry->close();

    // --- PAYMENT REQUIRED: Redirect to PhonePe ---
    $amount_in_paise = $amount * 100;
    
    // Use GET method in redirect URL to pass txn_id reliably
    $redirect_url = "https://unitedculturalforum.com/competition_status.php?txn_id=" . $merchantTransactionId;
    $callback_url = "https://unitedculturalforum.com/competition_callback.php";

    $payload = [
        'merchantId' => $PHONEPE_MERCHANT_ID,
        'merchantTransactionId' => $merchantTransactionId,
        'merchantUserId' => 'USER_' . ($user_id ?? uniqid()),
        'amount' => $amount_in_paise,
        'redirectUrl' => $redirect_url,
        'redirectMode' => 'GET', // ⭐️ Critical: Use GET so txn_id is in URL
        'callbackUrl' => $callback_url,
        'mobileNumber' => $phone,
        'paymentInstrument' => [ 'type' => 'PAY_PAGE' ],
    ];

    $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);
    
    if ($response === false) {
        throw new Exception("cURL Error: " . curl_error($ch));
    }
    
    $http_status = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);
    $json_response = json_decode($response, true);

    if ($http_status == 200 && isset($json_response['success']) && $json_response['success'] === true) {
        // Save txn_id to session for fallback
        $_SESSION['comp_phonepe_txnid'] = $merchantTransactionId;
        
        $payment_page_url = $json_response['data']['instrumentResponse']['redirectInfo']['url'];
        header('Location: ' . $payment_page_url);
        exit();
    } else {
        error_log("Comp Payment Init Failed: " . $response);
        header("Location: competition_register.php?id=$comp_id&error=payment_init");
        exit();
    }

} catch (Exception $e) {
    error_log("Competition Handler Error: " . $e->getMessage());
    // Redirect back with error
    header("Location: competition_register.php?id=$comp_id&error=db_error");
    exit();
}
?>