<?php
require 'includes/db.php';

$ref = $_GET['ref'] ?? '';
$callback = $_GET['callback'] ?? '';

if (empty($ref) || empty($callback)) {
    die("Invalid request.");
}

// Fetch the transaction
$stmt = $pdo->prepare("SELECT * FROM transactions WHERE reference = ?");
$stmt->execute([$ref]);
$txn = $stmt->fetch();

if (!$txn) {
    die("Transaction not found.");
}

?>

<!DOCTYPE html>
<html>
<head>
    <title>Mock Payment Gateway</title>
    <link rel="stylesheet" href="assets/css/bootstrap.min.css">
</head>
<body class="container text-center p-5">
    <h2>Payment of ₹<?= $txn['amount'] ?></h2>
    <p>Reference: <strong><?= $txn['reference'] ?></strong></p>

    <form method="POST" class="d-inline">
        <input type="hidden" name="ref" value="<?= $ref ?>">
        <input type="hidden" name="callback" value="<?= $callback ?>">
        <button name="action" value="success" class="btn btn-success btn-lg me-3">Pay Now</button>
    </form>
    
    <form method="POST" class="d-inline">
        <input type="hidden" name="ref" value="<?= $ref ?>">
        <input type="hidden" name="callback" value="<?= $callback ?>">
        <button name="action" value="fail" class="btn btn-danger btn-lg">Cancel</button>
    </form>
</body>
</html>

<?php
// Handle POST result
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action'])) {
    $action = $_POST['action'];
    $ref = $_POST['ref'];
    $callback = $_POST['callback'];

    // Update transaction status
    $newStatus = $action === 'success' ? 'success' : 'failed';
    $update = $pdo->prepare("UPDATE transactions SET status = ? WHERE reference = ?");
    $update->execute([$newStatus, $ref]);

    // On success, also update user balance
    if ($newStatus === 'success') {
        // Get transaction details again
        $txn = $pdo->prepare("SELECT * FROM transactions WHERE reference = ?");
        $txn->execute([$ref]);
        $txn = $txn->fetch();

        if ($txn) {
            $add = $pdo->prepare("UPDATE users SET balance = balance + ? WHERE id = ?");
            $add->execute([$txn['amount'], $txn['user_id']]);
        }
    }

    // Redirect to the merchant callback URL
    header("Location: $callback?status=$newStatus&ref=$ref");
    exit;
}
?>
