<?php
include 'header.php';
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
// Initialize variables
$msg = "";
$err = "";
$upload_dir = "uploads/payments/";
// Check payment session
if (!isset($_SESSION['payment']['celebrity_id'], $_SESSION['payment']['amount'], $_SESSION['payment']['fan_card_id'], $_SESSION['payment']['payment_method'], $_SESSION['payment']['celebrities_name'])) {
    $err = "No valid payment session found";
    echo "<div class='alert alert-danger'>$err</div>";
     echo '<script>window.location.href = "celebrities.php";</script>';
    exit();
}
$celebrity_id = intval($_SESSION['payment']['celebrity_id']);
$amount = floatval($_SESSION['payment']['amount']);
$fan_card_id = intval($_SESSION['payment']['fan_card_id']);
$payment_method = mysqli_real_escape_string($link, $_SESSION['payment']['payment_method']);
$celebrities_name = mysqli_real_escape_string($link, $_SESSION['payment']['celebrities_name']);
// Fetch real-time exchange rates from CoinGecko API
$api_url = "https://api.coingecko.com/api/v3/simple/price?ids=bitcoin,ethereum,tether&vs_currencies=usd";
$exchange_rates = [
    'BTC' => 104413,
    'ETH' => 2484,
    'USDT' => 1.001
]; // Fallback rates
$response = @file_get_contents($api_url);
if ($response !== false) {
    $data = json_decode($response, true);
    if (isset($data['bitcoin']['usd'], $data['ethereum']['usd'], $data['tether']['usd'])) {
        $exchange_rates = [
            'BTC' => floatval($data['bitcoin']['usd']),
            'ETH' => floatval($data['ethereum']['usd']),
            'USDT' => floatval($data['tether']['usd'])
        ];
    }
}
// Calculate crypto amounts
$crypto_amounts = [
    'BTC' => $amount / $exchange_rates['BTC'],
    'ETH' => $amount / $exchange_rates['ETH'],
    'USDT' => $amount / $exchange_rates['USDT']
];
// Handle form submission
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $payment_method = mysqli_real_escape_string($link, $_POST['payment_method'] ?? '');
    $status = 'Pending';
    $payment_proof = null;
    $crypto_currency = null;
    $crypto_wallet = null;
    $crypto_amount = null;
    $gift_card_type = null;
    $gift_card_amount = null;
    $gift_card_images = null;
    // Validate CSRF token
    if (!isset($_POST['_token']) || $_POST['_token'] !== 'fjrPKhkhyi4YGiZ4tsiUYNinPbrhXNvMdCY7NLyM') {
        $err = "Invalid CSRF token";
    }
    // Handle bank transfer
    if (empty($err) && $payment_method === 'bank_transfer') {
        if (isset($_FILES['bank_receipt']) && $_FILES['bank_receipt']['error'] === UPLOAD_ERR_OK) {
            $allowed = ['jpg', 'jpeg', 'png', 'gif', 'pdf'];
            $ext = strtolower(pathinfo($_FILES['bank_receipt']['name'], PATHINFO_EXTENSION));
            if (in_array($ext, $allowed)) {
                $payment_proof = uniqid('bank_') . '.' . $ext;
                $upload_path = $upload_dir . $payment_proof;
                if (!move_uploaded_file($_FILES['bank_receipt']['tmp_name'], $upload_path)) {
                    $err = "Failed to upload bank receipt";
                }
            } else {
                $err = "Invalid bank receipt format. Only JPG, JPEG, PNG, GIF, and PDF allowed";
            }
        } else {
            $err = "Bank receipt is required";
        }
    } elseif (empty($err) && $payment_method === 'crypto') {
        if (isset($_POST['crypto_currency']) && in_array($_POST['crypto_currency'], ['BTC', 'ETH', 'USDT'])) {
            $crypto_currency = mysqli_real_escape_string($link, $_POST['crypto_currency']);
            $crypto_wallet = mysqli_real_escape_string($link, $_POST["crypto_{$crypto_currency}_wallet"] ?? '');
            $crypto_amount = $crypto_amounts[$crypto_currency] ?? null;
            if (empty($crypto_wallet)) {
                $err = "Crypto wallet address is missing";
            } elseif (!isset($_FILES['crypto_proof']) || $_FILES['crypto_proof']['error'] !== UPLOAD_ERR_OK) {
                $err = "Crypto payment proof is required";
            } else {
                $allowed = ['jpg', 'jpeg', 'png', 'gif', 'pdf'];
                $ext = strtolower(pathinfo($_FILES['crypto_proof']['name'], PATHINFO_EXTENSION));
                if (in_array($ext, $allowed)) {
                    $payment_proof = uniqid('crypto_') . '.' . $ext;
                    $upload_path = $upload_dir . $payment_proof;
                    if (!move_uploaded_file($_FILES['crypto_proof']['tmp_name'], $upload_path)) {
                        $err = "Failed to upload crypto payment proof";
                    }
                } else {
                    $err = "Invalid crypto payment proof format. Only JPG, JPEG, PNG, GIF, and PDF allowed";
                }
            }
        } else {
            $err = "Cryptocurrency selection is required or invalid";
        }
    } elseif (empty($err) && $payment_method === 'gift_card') {
        if (isset($_POST['gift_card_type']) && !empty($_POST['gift_card_type'])) {
            $gift_card_type = mysqli_real_escape_string($link, $_POST['gift_card_type']);
            $gift_card_amount = floatval($_POST['gift_card_amount'] ?? 0);

            if (!isset($_FILES['gift_card_images']) || !is_array($_FILES['gift_card_images']['name']) || count($_FILES['gift_card_images']['name']) == 0) {
                $err = "At least one gift card image is required";
            } else {
                $allowed = ['jpg', 'jpeg', 'png', 'gif'];
                $gift_card_images_array = [];
                foreach ($_FILES['gift_card_images']['name'] as $key => $name) {
                    if ($_FILES['gift_card_images']['error'][$key] === UPLOAD_ERR_OK) {
                        $ext = strtolower(pathinfo($name, PATHINFO_EXTENSION));
                        if (in_array($ext, $allowed)) {
                            $filename = uniqid('gift_') . '.' . $ext;
                            $upload_path = $upload_dir . $filename;
                            if (move_uploaded_file($_FILES['gift_card_images']['tmp_name'][$key], $upload_path)) {
                                $gift_card_images_array[] = $filename;
                            } else {
                                $err = "Failed to upload gift card image: $name";
                                break;
                            }
                        } else {
                            $err = "Invalid gift card image format for $name. Only JPG, JPEG, PNG, GIF allowed";
                            break;
                        }
                    } else {
                        $err = "Error uploading gift card image: $name";
                        break;
                    }
                }
                if (empty($err) && !empty($gift_card_images_array)) {
                    $gift_card_images = implode(',', $gift_card_images_array);
                }
            }
        } else {
            $err = "Gift card type is required";
        }
    } else {
        $err = "Invalid payment method: $payment_method";
    }
    // Validate terms
    if (empty($err) && (!isset($_POST['terms']) || $_POST['terms'] !== 'on')) {
        $err = "You must agree to the terms and conditions";
    }
    // Insert into database
    if (empty($err)) {
        $type = "Fan Card Purchase";
        $query = "INSERT INTO payments (
            celebrity_id, fan_card_id, amount, payment_method, status,
            crypto_currency, crypto_wallet, crypto_amount,
            gift_card_type, gift_card_amount, payment_proof, gift_card_images, userid, type
        ) VALUES (
            $celebrity_id, $fan_card_id, $amount, '$payment_method', '$status',
            " . ($crypto_currency ? "'$crypto_currency'" : "NULL") . ",
            " . ($crypto_wallet ? "'$crypto_wallet'" : "NULL") . ",
            " . ($crypto_amount ? $crypto_amount : "NULL") . ",
            " . ($gift_card_type ? "'$gift_card_type'" : "NULL") . ",
            " . ($gift_card_amount ? $gift_card_amount : "NULL") . ",
            " . ($payment_proof ? "'$payment_proof'" : "NULL") . ",
            " . ($gift_card_images ? "'$gift_card_images'" : "NULL") . ",
            $user_id, '$type'
        )";
        if (mysqli_query($link, $query)) {
            $msg = "Payment submitted successfully. Awaiting verification.";
            unset($_SESSION['payment']);
        } else {
            $err = "Database insertion failed: " . mysqli_error($link);
        }
    }
    // Output messages
    if ($err) {
        echo "<div class='alert alert-danger'>Error: $err</div>";
    } elseif ($msg) {
        echo "<div class='alert alert-success'>$msg</div>";
    }
}



?>
<main class="flex-grow-1" style="padding-top: 80px;">
    <div class="min-vh-100" style="background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);">
        <div class="container py-5">
            <div class="row justify-content-center">
                <div class="col-xl-10">
                    <div class="text-center mb-5">
                        <h1 class="display-6 fw-bold text-white mb-3">Complete Your Purchase</h1>
                        <p class="lead text-white-50">Secure your exclusive fan card with our encrypted payment system</p>
                    </div>

                    <div class="row g-4">
                        <div class="col-lg-5">
                            <div class="card border-0 shadow-lg h-100" style="backdrop-filter: blur(10px); background: rgba(255, 255, 255, 0.95);">
                                <div class="card-body p-4">
                                    <div class="d-flex align-items-center mb-4">
                                        <div class="bg-primary bg-gradient rounded-circle p-3 me-3">
                                            <i class="fas fa-star text-white"></i>
                                        </div>
                                        <div>
                                            <h5 class="mb-0 fw-bold">Order Summary</h5>
                                            <small class="text-muted">Review your purchase</small>
                                        </div>
                                    </div>

                                    <div class="space-y-3">
                                        <div class="d-flex justify-content-between align-items-center py-3 border-bottom">
                                            <div>
                                                <span class="text-muted small">Fan Card</span>
                                                <?php if($fan_card_id == 1){ ?>
                                                   <div class="fw-semibold">Regular Fan Card</div>
                                                <?php }elseif($fan_card_id == 2){ ?>
                                                   <div class="fw-semibold">VVIP Fan Card</div>
                                                <?php }elseif($fan_card_id == 3){ ?>
                                                   <div class="fw-semibold">Gold</div>
                                                <?php }else{ ?>
                                                    <div class="fw-semibold">VIP Royal Card</div>
                                                <?php } ?>
                                            </div>
                                            <i class="fas fa-id-card text-primary"></i>
                                        </div>

                                        <div class="d-flex justify-content-between align-items-center py-3 border-bottom">
                                            <div>
                                                <span class="text-muted small">Celebrity</span>
                                                <div class="fw-semibold"><?php echo htmlspecialchars($celebrities_name); ?></div>
                                            </div>
                                            <i class="fas fa-user-circle text-warning"></i>
                                        </div>

                                        <div class="d-flex justify-content-between align-items-center py-3 border-bottom">
                                            <div>
                                                <span class="text-muted small">Status</span>
                                                <div>
                                                    <span class="badge bg-warning px-3 py-2 rounded-pill">
                                                        <i class="fas fa-clock me-1"></i>
                                                        Pending
                                                    </span>
                                                </div>
                                            </div>
                                        </div>
                                    </div>

                                    <div class="mt-4 p-4 rounded-3" style="background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);">
                                        <div class="d-flex justify-content-between align-items-center text-white">
                                            <div>
                                                <span class="small opacity-75">Total Amount</span>
                                                <div class="h4 fw-bold mb-0">$<?php echo number_format($amount, 2); ?></div>
                                            </div>
                                            <div class="bg-white bg-opacity-20 rounded-circle p-3">
                                                <i class="fas fa-dollar-sign text-white"></i>
                                            </div>
                                        </div>
                                    </div>

                                    <div class="mt-4 text-center">
                                        <div class="d-inline-flex align-items-center bg-light rounded-pill px-3 py-2">
                                            <i class="fas fa-shield-alt text-success me-2"></i>
                                            <small class="text-muted fw-medium">SSL Secured Payment</small>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <div class="col-lg-7">
                            <div class="card border-0 shadow-lg" style="backdrop-filter: blur(10px); background: rgba(255, 255, 255, 0.95);">
                                <div class="card-body p-4">
                                    <?php if ($msg) { ?>
                                        <div class='alert alert-success'><?php echo $msg; ?></div>
                                    <?php } ?>
                                    <?php if ($err) { ?>
                                        <div class='alert alert-danger'><?php echo $err; ?></div>
                                    <?php } ?>

                                    <form action="" method="POST" id="payment-form" enctype="multipart/form-data">
                                        <input type="hidden" name="_token" value="fjrPKhkhyi4YGiZ4tsiUYNinPbrhXNvMdCY7NLyM" autocomplete="off">
                                        <div class="mb-5">
                                            <h5 class="fw-bold mb-3">Choose Payment Method</h5>
                                            <p class="text-muted mb-4">Select your preferred payment option below</p>

                                            <div class="payment-methods-grid">
                                                <div class="payment-method-card mb-3" data-method="bank_transfer">
                                                    <input type="radio" name="payment_method" id="bank_transfer" value="bank_transfer" class="d-none">
                                                    <label for="bank_transfer" class="card border-2 h-100 cursor-pointer transition-all">
                                                        <div class="card-body p-4">
                                                            <div class="d-flex align-items-center">
                                                                <div class="payment-icon me-4">
                                                                    <div class="bg-info bg-gradient rounded-3 p-3 d-inline-flex">
                                                                        <i class="fas fa-university text-white fa-2x"></i>
                                                                    </div>
                                                                </div>
                                                                <div class="flex-grow-1">
                                                                    <h6 class="fw-bold mb-1">Bank Transfer</h6>
                                                                    <p class="text-muted small mb-0">Direct transfer from your bank account</p>
                                                                    <div class="mt-2">
                                                                        <span class="badge bg-warning">1-3 Business Days</span>
                                                                    </div>
                                                                </div>
                                                                <div class="check-indicator">
                                                                    <i class="fas fa-check-circle text-success fa-lg"></i>
                                                                </div>
                                                            </div>
                                                        </div>
                                                    </label>
                                                </div>

                                                <div class="payment-method-card mb-3" data-method="crypto">
                                                    <input type="radio" name="payment_method" id="crypto" value="crypto" class="d-none">
                                                    <label for="crypto" class="card border-2 h-100 cursor-pointer transition-all">
                                                        <div class="card-body p-4">
                                                            <div class="d-flex align-items-center">
                                                                <div class="payment-icon me-4">
                                                                    <div class="bg-warning bg-gradient rounded-3 p-3 d-inline-flex">
                                                                        <i class="fab fa-bitcoin text-white fa-2x"></i>
                                                                    </div>
                                                                </div>
                                                                <div class="flex-grow-1">
                                                                    <h6 class="fw-bold mb-1">Cryptocurrency</h6>
                                                                    <p class="text-muted small mb-0">Pay with Bitcoin, Ethereum, or USDT</p>
                                                                    <div class="payment-badges mt-2">
                                                                        <span class="badge bg-warning text-dark me-1">BTC</span>
                                                                        <span class="badge bg-light text-dark me-1">ETH</span>
                                                                        <span class="badge bg-success">USDT</span>
                                                                    </div>
                                                                </div>
                                                                <div class="check-indicator">
                                                                    <i class="fas fa-check-circle text-success fa-lg"></i>
                                                                </div>
                                                            </div>
                                                        </div>
                                                    </label>
                                                </div>

                                                <div class="payment-method-card mb-3" data-method="gift_card">
                                                    <input type="radio" name="payment_method" id="gift_card" value="gift_card" class="d-none">
                                                    <label for="gift_card" class="card border-2 h-100 cursor-pointer transition-all">
                                                        <div class="card-body p-4">
                                                            <div class="d-flex align-items-center">
                                                                <div class="payment-icon me-4">
                                                                    <div class="bg-success bg-gradient rounded-3 p-3 d-inline-flex">
                                                                        <i class="fas fa-gift text-white fa-2x"></i>
                                                                    </div>
                                                                </div>
                                                                <div class="flex-grow-1">
                                                                    <h6 class="fw-bold mb-1">Gift Card</h6>
                                                                    <p class="text-muted small mb-0">Pay with gift card or voucher</p>
                                                                    <div class="mt-2">
                                                                        <span class="badge bg-success">Instant</span>
                                                                    </div>
                                                                </div>
                                                                <div class="check-indicator">
                                                                    <i class="fas fa-check-circle text-success fa-lg"></i>
                                                                </div>
                                                            </div>
                                                        </div>
                                                    </label>
                                                </div>
                                            </div>
                                        </div>

                                        <div id="bank_transfer-details" class="payment-details" style="display: none;">
                                            <div class="card border-0 mb-4" style="background: linear-gradient(135deg, #f8f9fa, #e9ecef);">
                                                <div class="card-body p-4">
                                                    <div class="d-flex align-items-center mb-4">
                                                        <div class="bg-info bg-gradient rounded-circle p-2 me-3">
                                                            <i class="fas fa-university text-white"></i>
                                                        </div>
                                                        <h6 class="fw-bold mb-0">Bank Transfer Instructions</h6>
                                                    </div>

                                                    <div class="alert alert-info border-0 rounded-3 mb-4" style="background: linear-gradient(135deg, #17a2b8, #138496);">
                                                        <i class="fas fa-info-circle text-white me-2"></i>
                                                        <span class="text-white">Please include the booking reference in the transfer details.</span>
                                                    </div>

                                                    <div class="bank-details-grid">
                                                        <div class="row g-3 mb-4">
                                                            <div class="col-md-6">
                                                                <div class="p-3 rounded-3 bg-white border">
                                                                    <small class="text-muted d-block mb-1">Bank Name</small>
                                                                    <div class="fw-semibold"><?php echo $BankName ?></div>
                                                                </div>
                                                            </div>
                                                            <div class="col-md-6">
                                                                <div class="p-3 rounded-3 bg-white border">
                                                                    <small class="text-muted d-block mb-1">Account Name</small>
                                                                    <div class="fw-semibold"><?php echo $AccountName ?></div>
                                                                </div>
                                                            </div>
                                                            <div class="col-md-6">
                                                                <div class="p-3 rounded-3 bg-white border">
                                                                    <small class="text-muted d-block mb-1">Account Number</small>
                                                                    <div class="fw-semibold font-monospace"><?php echo $AccountNumber ?></div>
                                                                </div>
                                                            </div>
                                                            <div class="col-md-6">
                                                                <div class="p-3 rounded-3 bg-white border">
                                                                    <small class="text-muted d-block mb-1">Routing Number</small>
                                                                    <div class="fw-semibold font-monospace"><?php echo $RoutingNumber ?></div>
                                                                </div>
                                                            </div>
                                                        </div>

                                                        <div class="p-4 rounded-3 mb-4" style="background: linear-gradient(135deg, #28a745, #20c997);">
                                                            <div class="row text-white">
                                                                <div class="col-md-6">
                                                                    <small class="opacity-75 d-block">Amount to Transfer</small>
                                                                    <div class="h5 fw-bold mb-0">$<?php echo number_format($amount, 2); ?></div>
                                                                </div>
                                                                <div class="col-md-6">
                                                                    <small class="opacity-75 d-block">Reference</small>
                                                                    <div class="fw-bold font-monospace">FC-<?php echo $fan_card_id . '-' . rand(1000, 9999); ?></div>
                                                                </div>
                                                            </div>
                                                        </div>

                                                        <div class="mb-4">
                                                            <label for="bank_receipt" class="form-label fw-semibold">Upload Payment Receipt</label>
                                                            <div class="upload-area border-2 border-dashed rounded-3 p-4 text-center" style="border-color: #dee2e6 !important;">
                                                                <input type="file" class="form-control d-none" id="bank_receipt" name="bank_receipt" accept="image/*,.pdf">
                                                                <label for="bank_receipt" class="cursor-pointer w-100">
                                                                    <i class="fas fa-cloud-upload-alt fa-2x text-muted mb-2 d-block"></i>
                                                                    <p class="mb-1 fw-semibold">Click to upload or drag and drop</p>
                                                                    <small class="text-muted">JPG, PNG, PDF (max 5MB)</small>
                                                                </label>
                                                            </div>
                                                        </div>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>

                                        <div id="crypto-details" class="payment-details" style="display: none;">
                                            <div class="card border-0 mb-4" style="background: linear-gradient(135deg, #fff3cd, #ffeaa7);">
                                                <div class="card-body p-4">
                                                    <div class="d-flex align-items-center mb-4">
                                                        <div class="bg-warning bg-gradient rounded-circle p-2 me-3">
                                                            <i class="fab fa-bitcoin text-white"></i>
                                                        </div>
                                                        <h6 class="fw-bold mb-0">Cryptocurrency Payment</h6>
                                                    </div>

                                                    <div class="crypto-selection mb-4">
                                                        <label class="form-label fw-semibold mb-3">Select Cryptocurrency</label>
                                                        <div class="row g-3">
                                                            <div class="col-md-4">
                                                                <input type="radio" class="btn-check crypto-currency" name="crypto_currency" id="crypto-btc" value="BTC" checked
                                                                    data-wallet="<?php echo $crypto_addresses['BTC']; ?>" data-rate="<?php echo $exchange_rates['BTC']; ?>" data-amount="<?php echo number_format($crypto_amounts['BTC'], 8); ?>">
                                                                <label class="btn btn-outline-warning w-100 p-3 crypto-btn" for="crypto-btc">
                                                                    <div class="text-center">
                                                                        <i class="fab fa-bitcoin fa-2x mb-2" style="color: #f7931a;"></i>
                                                                        <div class="fw-bold">BTC</div>
                                                                        <small class="text-muted">Bitcoin</small>
                                                                    </div>
                                                                </label>
                                                            </div>
                                                            <div class="col-md-4">
                                                                <input type="radio" class="btn-check crypto-currency" name="crypto_currency" id="crypto-eth" value="ETH"
                                                                    data-wallet="<?php echo $crypto_addresses['ETH']; ?>" data-rate="<?php echo $exchange_rates['ETH']; ?>" data-amount="<?php echo number_format($crypto_amounts['ETH'], 8); ?>">
                                                                <label class="btn btn-outline-warning w-100 p-3 crypto-btn" for="crypto-eth">
                                                                    <div class="text-center">
                                                                        <i class="fab fa-ethereum fa-2x mb-2" style="color: #627eea;"></i>
                                                                        <div class="fw-bold">ETH</div>
                                                                        <small class="text-muted">Ethereum</small>
                                                                    </div>
                                                                </label>
                                                            </div>
                                                            <div class="col-md-4">
                                                                <input type="radio" class="btn-check crypto-currency" name="crypto_currency" id="crypto-usdt" value="USDT"
                                                                    data-wallet="<?php echo $crypto_addresses['USDT']; ?>" data-rate="<?php echo $exchange_rates['USDT']; ?>" data-amount="<?php echo number_format($crypto_amounts['USDT'], 8); ?>">
                                                                <label class="btn btn-outline-warning w-100 p-3 crypto-btn" for="crypto-usdt">
                                                                    <div class="text-center">
                                                                        <div class="crypto-icon-usdt mb-2">
                                                                            <svg width="32" height="32" viewBox="0 0 32 32" fill="none" xmlns="http://www.w3.org/2000/svg">
                                                                                <circle cx="16" cy="16" r="16" fill="#26A17B" />
                                                                                <path d="M17.922 17.383v-.002c-.11.008-.677.042-1.942.042-1.01 0-1.721-.03-1.971-.042v.003c-3.888-.171-6.79-.848-6.79-1.658 0-.809 2.902-1.486 6.79-1.66V10.5h4.04v3.566c3.909.174 6.824.85 6.824 1.66 0 .81-2.915 1.487-6.824 1.66v.003l-.127-.006zm0-3.83v-.002l-.127-.004V10.5h-3.785v3.047l-.127.004v.001c-3.373.149-5.883.659-5.883 1.279 0 .621 2.51 1.131 5.883 1.28v.005l.127.004-.127.004v.006c-.013.001-.432.031-1.671.031-1.097 0-1.574-.028-1.712-.031v-.006l-.127-.004v-.005c-3.373-.149-5.883-.659-5.883-1.28 0-.62 2.51-1.13 5.883-1.279z" fill="white" />
                                                                            </svg>
                                                                        </div>
                                                                        <div class="fw-bold">USDT</div>
                                                                        <small class="text-muted">Tether (USDT)</small>
                                                                    </div>
                                                                </label>
                                                            </div>
                                                        </div>
                                                    </div>

                                                    <div class="crypto-payment-details">
                                                        <div id="crypto-btc-details" class="crypto-details" style="display: block;">
                                                            <div class="payment-info-card p-4 rounded-3 mb-4" style="background: linear-gradient(135deg, rgba(255,255,255,0.9), rgba(248,249,250,0.9));">
                                                                <div class="row g-3">
                                                                    <div class="col-md-6">
                                                                        <div class="d-flex justify-content-between align-items-center">
                                                                            <small class="text-muted">Amount to Send</small>
                                                                            <div class="fw-bold"><?php echo number_format($crypto_amounts['BTC'], 8); ?> BTC</div>
                                                                        </div>
                                                                    </div>
                                                                    <div class="col-md-6">
                                                                        <div class="d-flex justify-content-between align-items-center">
                                                                            <small class="text-muted">Exchange Rate</small>
                                                                            <div class="fw-semibold">$<?php echo number_format($exchange_rates['BTC'], 2); ?> USD</div>
                                                                        </div>
                                                                    </div>
                                                                </div>
                                                            </div>

                                                            <div class="wallet-address-section mb-4">
                                                                <label class="form-label fw-semibold">Wallet Address</label>
                                                                <div class="input-group">
                                                                    <input type="text" id="btc-wallet" name="crypto_BTC_wallet" class="form-control font-monospace bg-light" value="<?php echo $crypto_addresses['BTC']; ?>" readonly>
                                                                    <button type="button" class="btn btn-outline-secondary copy-wallet" data-wallet="btc-wallet">
                                                                        <i class="far fa-copy me-1"></i> Copy
                                                                    </button>
                                                                </div>
                                                                <small class="text-muted">Send only BTC to this address</small>
                                                            </div>
                                                        </div>

                                                        <div id="crypto-eth-details" class="crypto-details" style="display: none;">
                                                            <div class="payment-info-card p-4 rounded-3 mb-4" style="background: linear-gradient(135deg, rgba(255,255,255,0.9), rgba(248,249,250,0.9));">
                                                                <div class="row g-3">
                                                                    <div class="col-md-6">
                                                                        <div class="d-flex justify-content-between align-items-center">
                                                                            <small class="text-muted">Amount to Send</small>
                                                                            <div class="fw-bold"><?php echo number_format($crypto_amounts['ETH'], 8); ?> ETH</div>
                                                                        </div>
                                                                    </div>
                                                                    <div class="col-md-6">
                                                                        <div class="d-flex justify-content-between align-items-center">
                                                                            <small class="text-muted">Exchange Rate</small>
                                                                            <div class="fw-semibold">$<?php echo number_format($exchange_rates['ETH'], 2); ?> USD</div>
                                                                        </div>
                                                                    </div>
                                                                </div>
                                                            </div>

                                                            <div class="wallet-address-section mb-4">
                                                                <label class="form-label fw-semibold">Wallet Address</label>
                                                                <div class="input-group">
                                                                    <input type="text" id="eth-wallet" name="crypto_ETH_wallet" class="form-control font-monospace bg-light" value="<?php echo $crypto_addresses['ETH']; ?>" readonly>
                                                                    <button type="button" class="btn btn-outline-secondary copy-wallet" data-wallet="eth-wallet">
                                                                        <i class="far fa-copy me-1"></i> Copy
                                                                    </button>
                                                                </div>
                                                                <small class="text-muted">Send only ETH to this address</small>
                                                            </div>
                                                        </div>

                                                        <div id="crypto-usdt-details" class="crypto-details" style="display: none;">
                                                            <div class="payment-info-card p-4 rounded-3 mb-4" style="background: linear-gradient(135deg, rgba(255,255,255,0.9), rgba(248,249,250,0.9));">
                                                                <div class="row g-3">
                                                                    <div class="col-md-6">
                                                                        <div class="d-flex justify-content-between align-items-center">
                                                                            <small class="text-muted">Amount to Send</small>
                                                                            <div class="fw-bold"><?php echo number_format($crypto_amounts['USDT'], 8); ?> USDT</div>
                                                                        </div>
                                                                    </div>
                                                                    <div class="col-md-6">
                                                                        <div class="d-flex justify-content-between align-items-center">
                                                                            <small class="text-muted">Exchange Rate</small>
                                                                            <div class="fw-semibold">$<?php echo number_format($exchange_rates['USDT'], 3); ?> USD</div>
                                                                        </div>
                                                                    </div>
                                                                </div>
                                                            </div>

                                                            <div class="wallet-address-section mb-4">
                                                                <label class="form-label fw-semibold">Wallet Address</label>
                                                                <div class="input-group">
                                                                    <input type="text" id="usdt-wallet" name="crypto_USDT_wallet" class="form-control font-monospace bg-light" value="<?php echo $crypto_addresses['USDT']; ?>" readonly>
                                                                    <button type="button" class="btn btn-outline-secondary copy-wallet" data-wallet="usdt-wallet">
                                                                        <i class="far fa-copy me-1"></i> Copy
                                                                    </button>
                                                                </div>
                                                                <small class="text-muted">Send only USDT to this address</small>
                                                            </div>
                                                        </div>

                                                        <div class="upload-section mt-4" id="crypto-payment-proof-container" style="display: none;">
                                                            <label for="crypto_proof" class="form-label fw-semibold">Payment Proof <span class="text-danger">*</span></label>
                                                            <div class="upload-area border-2 border-dashed rounded-3 p-4 text-center" style="border-color: #ffc107 !important;">
                                                                <input type="file" class="form-control d-none" id="crypto_proof" name="crypto_proof" accept="image/*,.pdf">
                                                                <label for="crypto_proof" class="cursor-pointer w-100">
                                                                    <i class="fas fa-camera fa-2x text-warning mb-2 d-block"></i>
                                                                    <p class="mb-1 fw-semibold">Upload Transaction Screenshot</p>
                                                                    <small class="text-muted">JPG, PNG, PDF (max 5MB)</small>
                                                                </label>
                                                            </div>
                                                        </div>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>

                                        <div id="gift_card-details" class="payment-details" style="display: none;">
                                            <div class="card border-0 mb-4" style="background: linear-gradient(135deg, #f8f9fa, #e9ecef);">
                                                <div class="card-body p-4">
                                                    <div class="d-flex align-items-center mb-4">
                                                        <div class="bg-success bg-gradient rounded-circle p-2 me-3">
                                                            <i class="fas fa-gift text-white"></i>
                                                        </div>
                                                        <h6 class="fw-bold mb-0">Gift Card Payment</h6>
                                                    </div>

                                                    <div class="row g-3">
                                                        <div class="col-md-6">
                                                            <label for="gift_card_type" class="form-label fw-semibold">Gift Card Type <span class="text-danger">*</span></label>
                                                            <select class="form-select" id="gift_card_type" name="gift_card_type">
                                                                <option value="">Select card type</option>
                                                                <option value="amazon">Amazon Gift Card</option>
                                                                <option value="visa">Visa Gift Card</option>
                                                                <option value="mastercard">Mastercard Gift Card</option>
                                                                <option value="itunes">iTunes Gift Card</option>
                                                                <option value="google_play">Google Play Gift Card</option>
                                                                <option value="other">Other</option>
                                                            </select>
                                                        </div>
                                                        <div class="col-md-6">
                                                            <label for="gift_card_amount" class="form-label fw-semibold">Total Card Amount ($) <span class="text-danger">*</span></label>
                                                            <input type="number" class="form-control" id="gift_card_amount" name="gift_card_amount" min="0.01" step="0.01" placeholder="0.00">
                                                            <small class="text-muted">Total value of all gift cards combined</small>
                                                        </div>
                                                        <div class="col-12">
                                                            <div class="form-check">
                                                                <input class="form-check-input" type="checkbox" id="multiple_cards" name="multiple_cards">
                                                                <label class="form-check-label" for="multiple_cards">I'm using multiple gift cards</label>
                                                            </div>
                                                        </div>
                                                    </div>

                                                    <div class="mt-4">
                                                        <label class="form-label fw-semibold">Upload Gift Card(s) <span class="text-danger">*</span></label>
                                                        <p class="text-muted small mb-3">Upload clear images of the front and back of each gift card. You can upload multiple images.</p>

                                                        <div class="upload-area border-2 border-dashed rounded-3 p-4 text-center" id="gift-card-upload-area" style="border-color: #20c997 !important;">
                                                            <input type="file" class="form-control d-none" id="gift_card_images" name="gift_card_images[]" accept="image/*" multiple>
                                                            <label for="gift_card_images" class="cursor-pointer w-100">
                                                                <i class="fas fa-images fa-2x text-success mb-2 d-block"></i>
                                                                <p class="mb-1 fw-semibold">Click to upload gift card images</p>
                                                                <small class="text-muted">JPG, PNG (max 5MB per image, max 5 images)</small>
                                                            </label>
                                                        </div>

                                                        <div id="gift-card-preview" class="mt-3 row g-2"></div>
                                                        <div id="gift-card-error" class="text-danger small mt-2" style="display: none;"></div>
                                                    </div>

                                                    <div class="alert alert-info border-0 rounded-3 mt-4" style="background: linear-gradient(135deg, #17a2b8, #138496);">
                                                        <div class="d-flex">
                                                            <i class="fas fa-info-circle text-white me-2 mt-1"></i>
                                                            <div>
                                                                <p class="mb-1 text-white"><strong>Important:</strong> Please ensure the following are clearly visible in the images:</p>
                                                                <ul class="mb-0 text-white-50">
                                                                    <li>Card number</li>
                                                                    <li>PIN/Code (if any)</li>
                                                                    <li>Expiration date (if any)</li>
                                                                </ul>
                                                            </div>
                                                        </div>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>

                                        <div class="terms-section p-4 rounded-3 mb-4" style="background: rgba(248, 249, 250, 0.8);">
                                            <div class="form-check">
                                                <input class="form-check-input" type="checkbox" id="terms" name="terms" required>
                                                <label class="form-check-label fw-medium" for="terms">
                                                    I agree to the <a href="#" data-bs-toggle="modal" data-bs-target="#termsModal" class="text-decoration-none">Terms & Conditions</a> and confirm my purchase
                                                </label>
                                            </div>
                                        </div>

                                        <button type="submit" name="submit" class="btn btn-lg w-100 py-3 fw-bold text-white border-0 rounded-3" style="background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); transition: all 0.3s ease;">
                                            <i class="fas fa-lock me-2"></i>
                                            Complete Payment $<?php echo number_format($amount, 2); ?>
                                        </button>
                                    </form>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</main>

<?php
include 'footer.php';
?>

<script>
    document.addEventListener('DOMContentLoaded', function () {
        // Animate elements on scroll
        const observerOptions = {
            threshold: 0.1,
            rootMargin: '0px 0px -50px 0px'
        };

        const observer = new IntersectionObserver(function (entries) {
            entries.forEach(entry => {
                if (entry.isIntersecting) {
                    entry.target.classList.add('fade-in-up');
                }
            });
        }, observerOptions);

        document.querySelectorAll('.card-modern, .feature-card, .celebrity-card').forEach(el => {
            observer.observe(el);
        });

        // Add loading states to buttons
        document.querySelectorAll('form').forEach(form => {
            form.addEventListener('submit', function () {
                const submitBtn = form.querySelector('button[type="submit"]');
                if (submitBtn) {
                    submitBtn.innerHTML = '<i class="fas fa-spinner fa-spin me-2"></i>Processing...';
                    submitBtn.disabled = true;
                }
            });
        });

        // Initialize tooltips
        const tooltipTriggerList = [].slice.call(document.querySelectorAll('[data-bs-toggle="tooltip"]'));
        tooltipTriggerList.map(function (tooltipTriggerEl) {
            return new bootstrap.Tooltip(tooltipTriggerEl);
        });

        // Payment method selection with animations
        const paymentMethods = document.querySelectorAll('input[name="payment_method"]');

        function togglePaymentDetails() {
            document.querySelectorAll('.payment-details').forEach(el => {
                el.style.opacity = '0';
                el.style.transform = 'translateY(20px)';
                setTimeout(() => {
                    el.style.display = 'none';
                }, 300);
            });

            const selectedMethod = document.querySelector('input[name="payment_method"]:checked');
            if (selectedMethod) {
                const detailsElement = document.getElementById(`${selectedMethod.value}-details`);
                if (detailsElement) {
                    setTimeout(() => {
                        detailsElement.style.display = 'block';
                        detailsElement.style.opacity = '0';
                        detailsElement.style.transform = 'translateY(20px)';
                        requestAnimationFrame(() => {
                            detailsElement.style.transition = 'all 0.5s ease-out';
                            detailsElement.style.opacity = '1';
                            detailsElement.style.transform = 'translateY(0)';
                        });
                    }, 300);

                    if (selectedMethod.value === 'crypto') {
                        setTimeout(() => {
                            handleCryptoCurrencyChange();
                        }, 400);
                    }
                }
            }
        }

        function handleCryptoCurrencyChange() {
            const selectedCrypto = document.querySelector('input[name="crypto_currency"]:checked');
            const paymentProofContainer = document.getElementById('crypto-payment-proof-container');

            document.querySelectorAll('.crypto-btn').forEach(btn => {
                btn.classList.remove('active');
            });

            if (selectedCrypto) {
                const selectedBtn = document.querySelector(`label[for="crypto-${selectedCrypto.value.toLowerCase()}"]`);
                if (selectedBtn) {
                    selectedBtn.classList.add('active');
                }

                document.querySelectorAll('.crypto-details').forEach(el => {
                    el.style.opacity = '0';
                    el.style.transform = 'translateY(10px)';
                    setTimeout(() => {
                        el.style.display = 'none';
                    }, 200);
                });

                const detailsElement = document.getElementById(`crypto-${selectedCrypto.value.toLowerCase()}-details`);
                if (detailsElement) {
                    setTimeout(() => {
                        detailsElement.style.display = 'block';
                        requestAnimationFrame(() => {
                            detailsElement.style.transition = 'all 0.3s ease-out';
                            detailsElement.style.opacity = '1';
                            detailsElement.style.transform = 'translateY(0)';
                        });
                    }, 200);

                    const walletInput = detailsElement.querySelector('input[type="text"]');
                    const hasWallet = walletInput && walletInput.value && walletInput.value !== 'Not configured' && walletInput.value.trim() !== '';

                    if (hasWallet && paymentProofContainer) {
                        setTimeout(() => {
                            paymentProofContainer.style.display = 'block';
                            paymentProofContainer.style.opacity = '0';
                            requestAnimationFrame(() => {
                                paymentProofContainer.style.transition = 'all 0.3s ease-out';
                                paymentProofContainer.style.opacity = '1';
                            });
                        }, 300);
                    } else if (paymentProofContainer) {
                        paymentProofContainer.style.opacity = '0';
                        setTimeout(() => {
                            paymentProofContainer.style.display = 'none';
                        }, 300);
                    }
                }
            }
        }

        function showCopyFeedback(button) {
            const originalContent = button.innerHTML;
            button.innerHTML = '<i class="fas fa-check text-success"></i> Copied!';
            button.style.transform = 'scale(1.1)';

            Swal.fire({
                icon: 'success',
                title: 'Copied!',
                text: 'Wallet address copied to clipboard',
                timer: 1500,
                showConfirmButton: false,
                toast: true,
                position: 'top-end'
            });

            setTimeout(() => {
                button.innerHTML = originalContent;
                button.style.transform = '';
            }, 2000);
        }

        paymentMethods.forEach(method => {
            method.addEventListener('change', togglePaymentDetails);
        });

        document.querySelectorAll('input[name="crypto_currency"]').forEach(radio => {
            radio.addEventListener('change', handleCryptoCurrencyChange);
        });

        document.addEventListener('click', function (e) {
            if (e.target.closest('.copy-wallet')) {
                const button = e.target.closest('.copy-wallet');
                const walletId = button.getAttribute('data-wallet');
                const walletInput = document.getElementById(walletId);

                if (walletInput && walletInput.value) {
                    if (navigator.clipboard) {
                        navigator.clipboard.writeText(walletInput.value).then(() => {
                            showCopyFeedback(button);
                        }).catch(err => {
                            console.error('Failed to copy: ', err);
                            fallbackCopyTextToClipboard(walletInput.value, button);
                        });
                    } else {
                        fallbackCopyTextToClipboard(walletInput.value, button);
                    }
                }
            }
        });

        function fallbackCopyTextToClipboard(text, button) {
            const textArea = document.createElement("textarea");
            textArea.value = text;
            textArea.style.position = "fixed";
            textArea.style.top = "0";
            textArea.style.left = "0";
            document.body.appendChild(textArea);
            textArea.focus();
            textArea.select();

            try {
                const successful = document.execCommand('copy');
                if (successful) {
                    showCopyFeedback(button);
                }
            } catch (err) {
                console.error('Fallback copy failed', err);
            }

            document.body.removeChild(textArea);
        }

        togglePaymentDetails();

        const giftCardInput = document.getElementById('gift_card_images');
        const giftCardPreview = document.getElementById('gift-card-preview');
        const giftCardError = document.getElementById('gift-card-error');
        const maxFiles = 5;
        const maxFileSize = 5 * 1024 * 1024;

        if (giftCardInput) {
            giftCardInput.addEventListener('change', function (e) {
                const files = Array.from(e.target.files);
                const validFiles = [];
                const errors = [];

                giftCardPreview.innerHTML = '';
                giftCardError.style.display = 'none';

                files.forEach((file, index) => {
                    if (index >= maxFiles) {
                        errors.push(`Maximum ${maxFiles} files allowed.`);
                        return;
                    }

                    if (file.size > maxFileSize) {
                        errors.push(`File "${file.name}" exceeds 5MB limit.`);
                        return;
                    }

                    if (!file.type.match('image.*')) {
                        errors.push(`File "${file.name}" is not an image.`);
                        return;
                    }

                    validFiles.push(file);

                    const reader = new FileReader();
                    reader.onload = function (e) {
                        const preview = document.createElement('div');
                        preview.className = 'col-6 col-md-4 col-lg-3';
                        preview.innerHTML = `
                            <div class="card position-relative">
                                <img src="${e.target.result}" class="card-img-top" alt="Gift card preview" style="height: 100px; object-fit: cover;">
                                <button type="button" class="btn btn-sm btn-danger position-absolute top-0 end-0 m-1 rounded-circle p-1" data-index="${validFiles.length - 1}" style="width: 24px; height: 24px; line-height: 1; padding: 0;">
                                    <i class="fas fa-times"></i>
                                </button>
                                <div class="card-body p-2 text-center">
                                    <small class="text-muted">${file.name}</small>
                                    <div class="small text-muted">${(file.size / 1024 / 1024).toFixed(2)} MB</div>
                                </div>
                            </div>
                        `;
                        giftCardPreview.appendChild(preview);
                    };
                    reader.readAsDataURL(file);
                });

                const dataTransfer = new DataTransfer();
                validFiles.forEach(file => dataTransfer.items.add(file));
                giftCardInput.files = dataTransfer.files;

                if (errors.length > 0) {
                    giftCardError.textContent = errors.join(' ');
                    giftCardError.style.display = 'block';
                }
            });

            giftCardPreview.addEventListener('click', function (e) {
                const removeBtn = e.target.closest('.btn-danger');
                if (!removeBtn) return;

                e.preventDefault();
                const index = parseInt(removeBtn.dataset.index);
                const dataTransfer = new DataTransfer();
                const files = Array.from(giftCardInput.files);

                files.splice(index, 1);
                files.forEach(file => dataTransfer.items.add(file));
                giftCardInput.files = dataTransfer.files;
                giftCardInput.dispatchEvent(new Event('change'));
            });

            const multipleCardsCheckbox = document.getElementById('multiple_cards');
            if (multipleCardsCheckbox) {
                multipleCardsCheckbox.addEventListener('change', function () {
                    const helpText = this.nextElementSibling;
                    if (this.checked) {
                        helpText.textContent = 'You can upload multiple gift card images below';
                    } else {
                        helpText.textContent = 'Upload the front and back of your gift card';
                    }
                });
            }
        }

        const form = document.getElementById('payment-form');
        let isSubmitting = false;

        function validateGiftCardForm() {
            const giftCardType = document.getElementById('gift_card_type');
            const giftCardAmount = document.getElementById('gift_card_amount');
            const giftCardImages = document.getElementById('gift_card_images');
            let isValid = true;

            if (giftCardType && giftCardAmount && giftCardImages) {
                if (document.getElementById('gift_card') && document.getElementById('gift_card').checked) {
                    giftCardType.classList.remove('is-invalid');
                    giftCardAmount.classList.remove('is-invalid');
                    giftCardImages.classList.remove('is-invalid');

                    if (!giftCardType.value) {
                        giftCardType.classList.add('is-invalid');
                        giftCardType.focus();
                        isValid = false;
                        Swal.fire({
                            icon: 'error',
                            title: 'Validation Error',
                            text: 'Please select a gift card type.',
                            confirmButtonColor: '#667eea',
                        });
                    }

                    if (!giftCardAmount.value || parseFloat(giftCardAmount.value) <= 0) {
                        giftCardAmount.classList.add('is-invalid');
                        if (isValid) {
                            giftCardAmount.focus();
                            Swal.fire({
                                icon: 'error',
                                title: 'Validation Error',
                                text: 'Please enter a valid gift card amount.',
                                confirmButtonColor: '#667eea',
                            });
                        }
                        isValid = false;
                    }

                    if (!giftCardImages.files || giftCardImages.files.length === 0) {
                        giftCardImages.classList.add('is-invalid');
                        if (isValid) {
                            giftCardImages.focus();
                            Swal.fire({
                                icon: 'error',
                                title: 'Validation Error',
                                text: 'Please upload at least one image of your gift card.',
                                confirmButtonColor: '#667eea',
                            });
                        }
                        isValid = false;
                    }

                    if (!isValid) {
                        const firstError = document.querySelector('.is-invalid');
                        if (firstError) {
                            firstError.scrollIntoView({ behavior: 'smooth', block: 'center' });
                        }
                    }
                }
            }
            return isValid;
        }

        if (form) {
            form.addEventListener('submit', function (e) {
                if (isSubmitting) {
                    e.preventDefault();
                    return false;
                }

                if (document.getElementById('gift_card') && document.getElementById('gift_card').checked) {
                    if (!validateGiftCardForm()) {
                        e.preventDefault();
                        return false;
                    }
                }

                const termsChecked = document.getElementById('terms').checked;
                if (!termsChecked) {
                    e.preventDefault();
                    Swal.fire({
                        icon: 'warning',
                        title: 'Terms & Conditions Required',
                        text: 'Please accept our terms and conditions to proceed.',
                        confirmButtonText: 'I Accept',
                        showCancelButton: true,
                        cancelButtonText: 'View Terms',
                        reverseButtons: true,
                        customClass: {
                            confirmButton: 'btn btn-primary',
                            cancelButton: 'btn btn-outline-secondary'
                        }
                    }).then((result) => {
                        if (result.dismiss === Swal.DismissReason.cancel) {
                            const termsModal = new bootstrap.Modal(document.getElementById('termsModal'));
                            termsModal.show();
                        } else if (result.isConfirmed) {
                            document.getElementById('terms').checked = true;
                            form.submit();
                        }
                    });
                    return false;
                }

                const selectedMethod = document.querySelector('input[name="payment_method"]:checked');
                if (!selectedMethod) {
                    e.preventDefault();
                    Swal.fire({
                        icon: 'error',
                        title: 'Payment Method Required',
                        text: 'Please select a payment method to continue.',
                        confirmButtonText: 'OK',
                        customClass: {
                            confirmButton: 'btn btn-primary'
                        }
                    });
                    return false;
                }

                if (selectedMethod.value === 'crypto') {
                    const selectedCrypto = document.querySelector('input[name="crypto_currency"]:checked');
                    if (!selectedCrypto) {
                        e.preventDefault();
                        Swal.fire({
                            icon: 'error',
                            title: 'Cryptocurrency Required',
                            text: 'Please select a cryptocurrency.',
                            confirmButtonText: 'OK'
                        });
                        return false;
                    }

                    const walletInput = document.querySelector(`#crypto-${selectedCrypto.value.toLowerCase()}-details input[type="text"]`);
                    if (!walletInput || !walletInput.value || walletInput.value.trim() === '') {
                        e.preventDefault();
                        Swal.fire({
                            icon: 'error',
                            title: 'Configuration Error',
                            text: 'This cryptocurrency is not properly configured. Please contact support.',
                            confirmButtonText: 'OK'
                        });
                        return false;
                    }

                    const paymentProofInput = document.getElementById('crypto_proof');
                    if (!paymentProofInput || !paymentProofInput.files.length) {
                        e.preventDefault();
                        Swal.fire({
                            icon: 'error',
                            title: 'Payment Proof Required',
                            text: 'Please upload a screenshot of your transaction.',
                            confirmButtonText: 'OK'
                        });
                        return false;
                    }
                } else if (selectedMethod.value === 'bank_transfer') {
                    const bankReceipt = document.getElementById('bank_receipt');
                    if (!bankReceipt || !bankReceipt.files.length) {
                        e.preventDefault();
                        Swal.fire({
                            icon: 'error',
                            title: 'Receipt Required',
                            text: 'Please upload your bank transfer receipt.',
                            confirmButtonText: 'OK'
                        });
                        return false;
                    }
                }

                isSubmitting = true;
                const submitButton = form.querySelector('button[type="submit"]');
                if (submitButton) {
                    submitButton.disabled = true;
                    submitButton.innerHTML = `
                        <div class="d-flex align-items-center justify-content-center">
                            <div class="spinner-border spinner-border-sm me-2" role="status">
                                <span class="visually-hidden">Loading...</span>
                            </div>
                            Processing Payment...
                        </div>
                    `;
                    submitButton.style.background = 'linear-gradient(135deg, #6c757d, #5a6268)';
                }

                setTimeout(() => {
                    isSubmitting = false;
                    if (submitButton) {
                        submitButton.disabled = false;
                        submitButton.innerHTML = '<i class="fas fa-lock me-2"></i> Complete Payment $<?php echo number_format($amount, 2); ?>';
                        submitButton.style.background = 'linear-gradient(135deg, #667eea 0%, #764ba2 100%)';
                    }
                }, 15000);
            });
        }

        document.addEventListener('change', function (e) {
            if (e.target && e.target.type === 'file') {
                const file = e.target.files[0];
                if (file) {
                    const maxSize = 5 * 1024 * 1024;
                    const allowedTypes = ['image/jpeg', 'image/png', 'image/jpg', 'image/gif', 'application/pdf'];

                    if (file.size > maxSize) {
                        Swal.fire({
                            icon: 'error',
                            title: 'File Too Large',
                            text: 'Please select a file smaller than 5MB.',
                            confirmButtonText: 'OK'
                        });
                        e.target.value = '';
                        return;
                    }

                    if (!allowedTypes.includes(file.type)) {
                        Swal.fire({
                            icon: 'error',
                            title: 'Invalid File Type',
                            text: 'Please select a JPG, PNG, or PDF file.',
                            confirmButtonText: 'OK'
                        });
                        e.target.value = '';
                        return;
                    }

                    const label = e.target.closest('.upload-area').querySelector('label');
                    if (label) {
                        label.innerHTML = `
                            <i class="fas fa-check-circle fa-2x text-success mb-2 d-block"></i>
                            <p class="mb-1 fw-semibold text-success">File Selected: ${file.name}</p>
                            <small class="text-muted">Click to change file</small>
                        `;
                    }
                }
            }
        });
    });
</script>
</body>
</html>