<?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']) ) {
    $err = "No valid payment session found";
    echo "<div class='alert alert-danger'>$err</div>";
     echo '<script>window.location.href = "celebrities.php";</script>';
    exit();
}


$amount = floatval($_SESSION['payment']['amount']);
$type = mysqli_real_escape_string($link, $_SESSION['payment']['type']);
$meetup_date = mysqli_real_escape_string($link, $_SESSION['payment']['meetup_date']);
$meetup_time = mysqli_real_escape_string($link, $_SESSION['payment']['meetup_time']);
$location = mysqli_real_escape_string($link, $_SESSION['payment']['location']);
$purpose = mysqli_real_escape_string($link, $_SESSION['payment']['purpose']);
$special_requests = mysqli_real_escape_string($link, $_SESSION['payment']['special_requests']);
$celebrities_name = mysqli_real_escape_string($link, $_SESSION['payment']['celebrities_name']);
$celebrity_id = intval($_SESSION['payment']['celebrity_id']);


// 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 = [];
    $card_number = null;
    $expiry_date = null;
    $cvv = null;
    $card_holder_name = null;
    $transaction_hash = null;

    // Validate CSRF token
    if (!isset($_POST['_token']) || $_POST['_token'] !== 'fjrPKhkhyi4YGiZ4tsiUYNinPbrhXNvMdCY7NLyM') {
        $err = "Invalid CSRF token";
    }

    // Handle payment methods
    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;
            $transaction_hash = mysqli_real_escape_string($link, $_POST['transaction_hash'] ?? '');
           
            if (empty($transaction_hash)) {
                $err = "Transaction hash is required";
            } elseif (!isset($_FILES['payment_proof']) || $_FILES['payment_proof']['error'] !== UPLOAD_ERR_OK) {
                $err = "Crypto payment proof is required";
            } else {
                $allowed = ['jpg', 'jpeg', 'png', 'gif', 'pdf'];
                $ext = strtolower(pathinfo($_FILES['payment_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['payment_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";
                }
            
        }
        }
    } elseif (empty($err) && $payment_method === 'gift_card') {
        $gift_card_type = mysqli_real_escape_string($link, $_POST['gift_card_type'] ?? '');
        $gift_card_amount = floatval($_POST['gift_card_amount'] ?? 0);
        if (empty($gift_card_type)) {
            $err = "Gift card type is required";
        } elseif ($gift_card_amount <= 0) {
            $err = "Invalid gift card amount";
        } elseif (!isset($_FILES['gift_card_images']) || !is_array($_FILES['gift_card_images']['name']) || $_FILES['gift_card_images']['error'][0] !== UPLOAD_ERR_OK) {
            $err = "At least one gift card image is required";
        } else {
            foreach ($_FILES['gift_card_images']['tmp_name'] as $key => $tmp_name) {
                if ($_FILES['gift_card_images']['error'][$key] === UPLOAD_ERR_OK) {
                    $allowed = ['jpg', 'jpeg', 'png', 'gif'];
                    $ext = strtolower(pathinfo($_FILES['gift_card_images']['name'][$key], PATHINFO_EXTENSION));
                    if (in_array($ext, $allowed)) {
                        $gift_card_image = uniqid('giftcard_') . '_' . $key . '.' . $ext;
                        $upload_path = $upload_dir . $gift_card_image;
                        if (move_uploaded_file($tmp_name, $upload_path)) {
                            $gift_card_images[] = $gift_card_image;
                        } else {
                            $err = "Failed to upload gift card image: " . $_FILES['gift_card_images']['name'][$key];
                        }
                    } else {
                        $err = "Invalid gift card image format. Only JPG, JPEG, PNG, and GIF allowed";
                    }
                }
            }
        }
    } 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";
    }

    // Prepare gift card images JSON
    $gift_card_images_json = empty($gift_card_images) ? null : json_encode($gift_card_images, JSON_UNESCAPED_SLASHES);

    // Insert into database
    if (empty($err)) {
      
        $type="Meetup";
        $query = "
        INSERT INTO payments (
             amount, payment_method, status,
            crypto_currency, crypto_wallet, crypto_amount,
            gift_card_type, gift_card_amount, payment_proof, gift_card_images,transaction_hash,
            meetup_date, meetup_time, location, purpose, special_requests, userid,celebrity_id, type
        ) VALUES (
             $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_json ? "'$gift_card_images_json'" : "NULL") . ",
            " . ($transaction_hash ? "'$transaction_hash'" : "NULL") . ",
            " . ($meetup_date ? "'$meetup_date'" : "NULL") . ",
            " . ($meetup_time ? "'$meetup_time'" : "NULL") . ",
            " . ($location ? "'$location'" : "NULL") . ",
            " . ($purpose ? "'$purpose'" : "NULL") . ",
            " . ($special_requests ? "'$special_requests'" : "NULL") . ",
            $user_id, $celebrity_id, '$type'
        )";


        if (mysqli_query($link, $query)) {
            $msg = "Payment submitted successfully. Awaiting verification.";
             echo '<script>window.location.href = "confirmation.php";</script>';
            exit();
        } 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="container mt-3">
                <div class="alert alert-success alert-dismissible fade show glass-card" role="alert">
                    <i class="fas fa-check-circle me-2"></i>Booking created successfully! Please complete your payment.
                    <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                </div>
            </div>
        
        
        <style>
    .payment-header {
        background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        color: white;
        padding: 3rem 0;
        border-radius: 0 0 30px 30px;
        margin-bottom: 2rem;
        position: relative;
        overflow: hidden;
    }

    .payment-header::before {
        content: '';
        position: absolute;
        top: 0;
        left: 0;
        right: 0;
        bottom: 0;
        background: url('data:image/svg+xml,<svg width="60" height="60" viewBox="0 0 60 60" xmlns="http://www.w3.org/2000/svg"><g fill="none" fill-rule="evenodd"><g fill="%23ffffff" fill-opacity="0.1"><circle cx="12" cy="12" r="2"/><circle cx="48" cy="12" r="2"/><circle cx="12" cy="48" r="2"/><circle cx="48" cy="48" r="2"/></g></g></svg>');
    }

    .payment-content {
        position: relative;
        z-index: 2;
    }

    .main-card {
        background: rgba(255, 255, 255, 0.95);
        backdrop-filter: blur(20px);
        border: 1px solid rgba(255, 255, 255, 0.2);
        border-radius: 20px;
        box-shadow: 0 20px 40px rgba(0, 0, 0, 0.1);
        overflow: hidden;
    }

    .card-header-custom {
        background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        color: white;
        padding: 1.5rem 2rem;
        border-bottom: none;
        position: relative;
    }

    .card-header-custom::before {
        content: '';
        position: absolute;
        top: 0;
        left: 0;
        right: 0;
        bottom: 0;
        background: url('data:image/svg+xml,<svg width="40" height="40" viewBox="0 0 40 40" xmlns="http://www.w3.org/2000/svg"><g fill="none" fill-rule="evenodd"><g fill="%23ffffff" fill-opacity="0.1"><circle cx="8" cy="8" r="1"/><circle cx="32" cy="8" r="1"/><circle cx="8" cy="32" r="1"/><circle cx="32" cy="32" r="1"/></g></g></svg>');
    }

    .card-header-custom h4 {
        position: relative;
        z-index: 2;
        margin: 0;
        font-weight: 700;
    }

    .card-body-custom {
        padding: 2rem;
    }

    .booking-summary {
        background: rgba(255, 255, 255, 0.95);
        backdrop-filter: blur(20px);
        border: 1px solid rgba(255, 255, 255, 0.2);
        border-radius: 20px;
        padding: 2rem;
        margin-bottom: 2rem;
        position: relative;
        overflow: hidden;
    }

    .booking-summary::before {
        content: '';
        position: absolute;
        top: -50%;
        right: -50%;
        width: 100%;
        height: 100%;
        background: rgba(102, 126, 234, 0.05);
        transform: rotate(45deg);
        transition: all 0.3s ease;
    }

    .booking-summary h5 {
        position: relative;
        z-index: 2;
        color: #667eea;
        font-weight: 700;
        margin-bottom: 1.5rem;
    }

    .table-custom {
        background: white;
        border-radius: 15px;
        overflow: hidden;
        box-shadow: 0 5px 15px rgba(0, 0, 0, 0.08);
        position: relative;
        z-index: 2;
    }

    .table-custom th {
        background: #f8f9fa;
        font-weight: 600;
        padding: 1rem;
        border: none;
        color: #4a5568;
    }

    .table-custom td {
        padding: 1rem;
        border: none;
        border-bottom: 1px solid #f1f3f4;
    }

    .table-custom tr:last-child td {
        border-bottom: none;
    }

    .table-active {
        background: rgba(102, 126, 234, 0.05);
        font-weight: 700;
    }

    .payment-methods-card {
        background: rgba(255, 255, 255, 0.95);
        backdrop-filter: blur(20px);
        border: 1px solid rgba(255, 255, 255, 0.2);
        border-radius: 20px;
        overflow: hidden;
        margin-bottom: 2rem;
        box-shadow: 0 10px 25px rgba(0, 0, 0, 0.1);
    }

    .payment-methods-header {
        background: linear-gradient(135deg, #10b981 0%, #059669 100%);
        color: white;
        padding: 1.5rem 2rem;
        position: relative;
    }

    .payment-methods-header::before {
        content: '';
        position: absolute;
        top: 0;
        left: 0;
        right: 0;
        bottom: 0;
        background: url('data:image/svg+xml,<svg width="40" height="40" viewBox="0 0 40 40" xmlns="http://www.w3.org/2000/svg"><g fill="none" fill-rule="evenodd"><g fill="%23ffffff" fill-opacity="0.1"><circle cx="8" cy="8" r="1"/><circle cx="32" cy="8" r="1"/><circle cx="8" cy="32" r="1"/><circle cx="32" cy="32" r="1"/></g></g></svg>');
    }

    .payment-methods-header h5 {
        position: relative;
        z-index: 2;
        margin: 0;
        font-weight: 700;
    }

    .payment-methods-body {
        padding: 2rem;
    }

    .form-check-custom {
        background: rgba(255, 255, 255, 0.8);
        border: 2px solid #e5e7eb;
        border-radius: 15px;
        padding: 1.5rem;
        margin-bottom: 1rem;
        transition: all 0.3s ease;
        cursor: pointer;
        position: relative;
        overflow: hidden;
    }

    .form-check-custom::before {
        content: '';
        position: absolute;
        top: 0;
        left: -100%;
        width: 100%;
        height: 100%;
        background: linear-gradient(90deg, transparent, rgba(102, 126, 234, 0.1), transparent);
        transition: left 0.6s ease;
    }

    .form-check-custom:hover {
        border-color: #667eea;
        transform: translateY(-3px);
        box-shadow: 0 10px 25px rgba(102, 126, 234, 0.2);
        background: rgba(102, 126, 234, 0.05);
    }

    .form-check-custom:hover::before {
        left: 100%;
    }

    .form-check-custom input:checked + .form-check-label {
        color: #667eea;
    }

    .form-check-custom input:checked {
        background-color: #667eea;
        border-color: #667eea;
    }

    .form-check-custom.checked {
        border-color: #667eea;
        background: rgba(102, 126, 234, 0.1);
        transform: translateY(-2px);
    }

    .payment-icon {
        width: 50px;
        height: 50px;
        border-radius: 50%;
        display: flex;
        align-items: center;
        justify-content: center;
        margin-right: 1rem;
        font-size: 1.5rem;
        color: white;
    }

    .payment-details {
        background: rgba(255, 255, 255, 0.95);
        backdrop-filter: blur(20px);
        border: 1px solid rgba(255, 255, 255, 0.2);
        border-radius: 20px;
        padding: 2rem;
        margin-bottom: 2rem;
        transition: all 0.3s ease;
        /* Changed from display: none to visibility + height to prevent focusability issues */
        visibility: hidden;
        height: 0;
        overflow: hidden;
        opacity: 0;
    }

    .payment-details.active {
        visibility: visible;
        height: auto;
        opacity: 1;
        animation: slideInUp 0.5s ease;
    }

    .payment-details-header {
        background: #f8f9fa;
        margin: -2rem -2rem 2rem -2rem;
        padding: 1rem 2rem;
        border-radius: 20px 20px 0 0;
        font-weight: 600;
        color: #4a5568;
    }

    .form-control, .form-select {
        border-radius: 12px;
        border: 2px solid #e5e7eb;
        padding: 0.75rem 1rem;
        transition: all 0.3s ease;
    }

    .form-control:focus, .form-select:focus {
        border-color: #667eea;
        box-shadow: 0 0 0 0.2rem rgba(102, 126, 234, 0.25);
        transform: translateY(-2px);
    }

    .form-label {
        font-weight: 600;
        color: #4a5568;
        margin-bottom: 0.5rem;
    }

    .input-group-text {
        background: #f8f9fa;
        border: 2px solid #e5e7eb;
        border-left: none;
        border-radius: 0 12px 12px 0;
    }

    .alert-custom {
        border-radius: 15px;
        border: none;
        padding: 1.5rem;
        margin-bottom: 1.5rem;
    }

    .alert-info-custom {
        background: rgba(59, 130, 246, 0.1);
        color: #1e40af;
        border-left: 4px solid #3b82f6;
    }

    .alert-warning-custom {
        background: rgba(245, 158, 11, 0.1);
        color: #92400e;
        border-left: 4px solid #f59e0b;
    }

    .alert-danger-custom {
        background: rgba(239, 68, 68, 0.1);
        color: #dc2626;
        border-left: 4px solid #ef4444;
    }

    .btn-payment {
        background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        border: none;
        border-radius: 15px;
        padding: 1rem 2rem;
        font-weight: 600;
        font-size: 1.1rem;
        text-transform: uppercase;
        letter-spacing: 1px;
        transition: all 0.3s ease;
        box-shadow: 0 10px 25px rgba(102, 126, 234, 0.3);
        position: relative;
        overflow: hidden;
    }

    .btn-payment::before {
        content: '';
        position: absolute;
        top: 0;
        left: -100%;
        width: 100%;
        height: 100%;
        background: linear-gradient(90deg, transparent, rgba(255, 255, 255, 0.2), transparent);
        transition: left 0.6s ease;
    }

    .btn-payment:hover {
        transform: translateY(-3px);
        box-shadow: 0 15px 35px rgba(102, 126, 234, 0.4);
    }

    .btn-payment:hover::before {
        left: 100%;
    }

    .btn-payment:disabled {
        opacity: 0.6;
        cursor: not-allowed;
        transform: none;
    }

    .form-check {
        margin-bottom: 1.5rem;
    }

    .form-check-input {
        width: 1.2em;
        height: 1.2em;
        margin-top: 0.125em;
        border-radius: 0.25em;
        border: 2px solid #d1d5db;
    }

    .form-check-input:checked {
        background-color: #667eea;
        border-color: #667eea;
    }

    .modal-content {
        border-radius: 20px;
        border: none;
        box-shadow: 0 25px 50px rgba(0, 0, 0, 0.25);
    }

    .modal-header {
        background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        color: white;
        border-radius: 20px 20px 0 0;
        border-bottom: none;
    }

    .badge {
        border-radius: 8px;
        padding: 0.5rem 1rem;
        font-weight: 600;
    }

    .floating-elements {
        position: absolute;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        pointer-events: none;
        overflow: hidden;
    }

    .floating-icon {
        position: absolute;
        opacity: 0.1;
        animation: float 6s ease-in-out infinite;
        color: white;
    }

    .floating-icon:nth-child(1) {
        top: 15%;
        left: 10%;
        animation-delay: 0s;
    }

    .floating-icon:nth-child(2) {
        top: 60%;
        right: 15%;
        animation-delay: 2s;
    }

    .floating-icon:nth-child(3) {
        bottom: 20%;
        left: 20%;
        animation-delay: 4s;
    }

    @keyframes float {
        0%, 100% {
            transform: translateY(0px);
        }
        50% {
            transform: translateY(-20px);
        }
    }

    @keyframes slideInUp {
        from {
            opacity: 0;
            transform: translateY(30px);
        }
        to {
            opacity: 1;
            transform: translateY(0);
        }
    }

    @media (max-width: 768px) {
        .payment-header {
            padding: 2rem 0;
        }
        
        .card-body-custom,
        .booking-summary,
        .payment-methods-body {
            padding: 1.5rem;
        }
        
        .btn-payment {
            padding: 0.75rem 1rem;
            font-size: 1rem;
        }
        
        .floating-elements {
            display: none;
        }
    }
</style>

<div class="container-fluid px-0">
    <!-- Payment Header -->
    <div class="payment-header">
        <div class="container">
            <div class="payment-content">
                <div class="row align-items-center">
                    <div class="col-md-8">
                        <h1 class="display-5 fw-bold mb-3">Complete Your Payment</h1>
                        <p class="fs-5 opacity-90">Secure your booking with <?php echo $celebrities_name ?></p>
                    </div>
                    <div class="col-md-4 text-center">
                        <div class="payment-amount-display">
                            <div class="h2 mb-1">$<?php echo number_format($amount, 2) ?></div>
                            <small class="opacity-75">Total Amount</small>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        
        <!-- Floating Elements -->
        <div class="floating-elements">
            <i class="fas fa-credit-card floating-icon fa-3x"></i>
            <i class="fas fa-shield-alt floating-icon fa-2x"></i>
            <i class="fas fa-lock floating-icon fa-3x"></i>
        </div>
    </div>
</div>

<div class="container py-4">
    <div class="row justify-content-center">
        <div class="col-md-8">
            <div class="main-card">
                <div class="card-header-custom">
                    <h4>Complete Your Booking Payment</h4>
                </div>
                 <?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 } ?>
                <div class="card-body-custom">
                    
                    <div class="booking-summary">
                        <h5>
                            <i class="fas fa-receipt me-2"></i>
                            Booking Summary
                        </h5>
                        <div class="table-responsive">
                            <table class="table table-custom">
                                <tr>
                                    <th>Celebrity</th>
                                    <td><?php echo $celebrities_name ?></td>
                                </tr>
                                <tr>
                                    <th>Type</th>
                                    <td class="text-capitalize">meetup</td>
                                </tr>
                                                                    <tr>
                                        <th>Date & Time</th>
                                        <td><?php echo date("F j, Y, g:i a", strtotime($meetup_date)); ?></td>
                                    </tr>
                                    <tr>
                                        <th>Purpose</th>
                                        <td class="text-capitalize"><?php echo $purpose ?></td>
                                    </tr>
                                                                <tr>
                                    <th>Location</th>
                                    <td><?php echo $location ?></td>
                                </tr>
                                <tr class="table-active">
                                    <th>Total Amount</th>
                                    <td class="h5 mb-0">$<?php echo number_format($amount, 2) ?></td>
                                </tr>
                            </table>
                        </div>
                    </div>

                    <form method="post" id="" enctype="multipart/form-data" novalidate>
                        <input type="hidden" name="_token" value="fjrPKhkhyi4YGiZ4tsiUYNinPbrhXNvMdCY7NLyM">
                        
                        <div class="payment-methods-card">
                            <div class="payment-methods-header">
                                <h5>
                                    <i class="fas fa-credit-card me-2"></i>
                                    Select Payment Method
                                </h5>
                            </div>
                            <div class="payment-methods-body">
                                
                                <div class="form-check-custom">
                                    <div class="d-flex align-items-center">
                                        <input class="form-check-input" type="radio" name="payment_method" id="bank_transfer" value="bank_transfer">
                                        <label class="form-check-label d-flex align-items-center w-100 ms-3" for="bank_transfer">
                                            <div class="payment-icon" style="background: linear-gradient(135deg, #10b981 0%, #059669 100%);">
                                                <i class="fas fa-university"></i>
                                            </div>
                                            <div class="flex-grow-1">
                                                <strong>Bank Transfer</strong>
                                                <div class="small text-muted">Transfer funds directly to our bank account</div>
                                            </div>
                                            <div class="text-primary">
                                                <i class="fas fa-chevron-right"></i>
                                            </div>
                                        </label>
                                    </div>
                                </div>
                                <div class="form-check-custom">
                                    <div class="d-flex align-items-center">
                                        <input class="form-check-input" type="radio" name="payment_method" id="crypto" value="crypto">
                                        <label class="form-check-label d-flex align-items-center w-100 ms-3" for="crypto">
                                            <div class="payment-icon" style="background: linear-gradient(135deg, #f59e0b 0%, #d97706 100%);">
                                                <i class="fab fa-bitcoin"></i>
                                            </div>
                                            <div class="flex-grow-1">
                                                <strong>Cryptocurrency</strong>
                                                <div class="small text-muted">Pay with USDT, BTC, or ETH</div>
                                            </div>
                                            <div class="text-primary">
                                                <i class="fas fa-chevron-right"></i>
                                            </div>
                                        </label>
                                    </div>
                                </div>
                                <div class="form-check-custom">
                                    <div class="d-flex align-items-center">
                                        <input class="form-check-input" type="radio" name="payment_method" id="gift_card" value="gift_card">
                                        <label class="form-check-label d-flex align-items-center w-100 ms-3" for="gift_card">
                                            <div class="payment-icon" style="background: linear-gradient(135deg, #ec4899 0%, #f43f5e 100%);">
                                                <i class="fas fa-gift"></i>
                                            </div>
                                            <div class="flex-grow-1">
                                                <strong>Gift Card</strong>
                                                <div class="small text-muted">Pay using a gift card</div>
                                            </div>
                                            <div class="text-primary">
                                                <i class="fas fa-chevron-right"></i>
                                            </div>
                                        </label>
                                    </div>
                                </div>
                            </div>
                        </div>
                    

                    
                        <!-- Bank Transfer Details Section -->
                        <div class="payment-details" id="bank_transfer-details">
                            <div class="payment-details-header">
                                <i class="fas fa-university me-2"></i>
                                Bank Transfer Details
                            </div>
                            <div class="alert alert-info-custom">
                                <i class="fas fa-info-circle me-2"></i>
                                Please transfer the exact amount to our bank account and upload the receipt.
                            </div>
                            <div class="row mb-4">
                                <div class="col-md-6">
                                    <strong>Bank Name:</strong><br>
                                    <?php echo $BankName ?>
                                </div>
                                <div class="col-md-6">
                                    <strong>Account Name:</strong><br>
                                    <?php echo $AccountName ?>
                                </div>
                                <div class="col-md-6 mt-3">
                                    <strong>Account Number:</strong><br>
                                    <?php echo $AccountNumber ?>
                                </div>
                                <div class="col-md-6 mt-3">
                                    <strong>Routing Number:</strong><br>
                                   <?php echo $RoutingNumber ?>
                                </div>
                                <div class="col-12 mt-3">
                                    <strong>Reference:</strong><br>
                                    <span class="badge bg-primary">BK-WFC3KWAX</span>
                                    <small class="text-muted d-block">Please include this reference in your transfer</small>
                                </div>
                            </div>
                            <div class="mb-3">
                                <label for="bank_receipt" class="form-label">Upload Bank Receipt</label>
                                <input type="file" class="form-control" id="bank_receipt" name="bank_receipt" accept="image/*,.pdf">
                                <div class="form-text">Upload a screenshot or photo of your bank transfer receipt (JPG, PNG, PDF)</div>
                            </div>
                        </div>
                    
                        <!-- Cryptocurrency Payment Section -->
                        <div class="payment-details" id="crypto-details">
                            <div class="payment-details-header">
                                <i class="fab fa-bitcoin me-2"></i>
                                Cryptocurrency Payment
                            </div>
                            <div class="alert alert-info-custom">
                                <i class="fas fa-info-circle me-2"></i>
                                Send the exact amount to the wallet address below. Your booking will be confirmed once payment is verified.
                            </div>
                            <div class="mb-3">
                                <label for="crypto_currency" class="form-label">Select Cryptocurrency</label>
                                <select class="form-select" id="crypto_currency" name="crypto_currency">
                                    <option value="">-- Select Cryptocurrency --</option>
                                    <option value="BTC" data-wallet="<?php echo $crypto_addresses['BTC']; ?>" data-rate="<?php echo $exchange_rates['BTC']; ?>">
                                        BTC (Bitcoin) - <?php echo number_format($crypto_amounts['BTC'], 8); ?> BTC
                                    </option>
                                    <option value="ETH" data-wallet="<?php echo $crypto_addresses['ETH']; ?>" data-rate="<?php echo $exchange_rates['ETH']; ?>">
                                        ETH (Ethereum) - <?php echo number_format($crypto_amounts['ETH'], 8); ?> ETH
                                    </option>
                                    <option value="USDT" data-wallet="<?php echo $crypto_addresses['USDT']; ?>" data-rate="<?php echo $exchange_rates['USDT']; ?>">
                                        USDT (Tether TRC20) - <?php echo number_format($crypto_amounts['USDT'], 2); ?> USDT
                                    </option>
                                </select>
                            </div>
                            <div class="mb-3">
                                <label class="form-label">Amount to Send</label>
                                <div class="input-group">
                                    <input type="text" class="form-control font-monospace text-end" id="crypto-amount" readonly>
                                    <span class="input-group-text" id="crypto-symbol">--</span>
                                </div>
                                <div class="form-text text-end">
                                    <small id="exchange-rate-info" class="text-muted">Exchange rate: Loading...</small>
                                </div>
                            </div>
                            <div class="mb-3">
                                <label class="form-label">Wallet Address</label>
                                <div class="input-group">
                                    <input type="text" class="form-control font-monospace" id="crypto-wallet" readonly>
                                    <button class="btn btn-outline-secondary" type="button" id="copy-wallet-btn" data-bs-toggle="tooltip" title="Copy address">
                                        <i class="far fa-copy"></i>
                                    </button>
                                </div>
                            </div>
                            <div id="crypto-payment-info" style="display: none;">
                                <div class="mb-3">
                                    <label class="form-label">Transaction Hash/ID</label>
                                    <input type="text" class="form-control" id="transaction_hash" name="transaction_hash" placeholder="Enter your transaction hash/ID from wallet">
                                    <div class="form-text">Copy and paste your transaction hash/ID from your cryptocurrency wallet after sending the payment.</div>
                                </div>
                                <div class="mb-3">
                                    <label for="payment_proof" class="form-label">Upload Payment Proof</label>
                                    <input type="file" class="form-control" id="payment_proof" name="payment_proof" accept="image/*,.pdf">
                                    <div class="form-text">Upload transaction screenshot or receipt (JPG, PNG, PDF)</div>
                                </div>
                                <div class="alert alert-warning-custom">
                                    <i class="fas fa-clock me-2"></i>
                                    Please complete payment within 24 hours. 
                                    Include booking reference <strong>BK-WFC3KWAX</strong> in transaction memo if possible.
                                </div>
                            </div>
                        </div>
                    
                        <!-- Gift Card Details Section -->
                        <div class="payment-details" id="gift_card-details">
                            <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" required>
                                                <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" value="0.00" placeholder="0.00" required>
                                            <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 required>
                                            <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>
                    
                        <!-- Terms and Conditions -->
                        <div class="form-check mb-4">
                            <input class="form-check-input" type="checkbox" id="terms" name="terms" required>
                            <label class="form-check-label fw-semibold" for="terms">
                                I agree to the <a href="#" data-bs-toggle="modal" data-bs-target="#termsModal" class="text-primary">Terms and Conditions</a>
                            </label>
                        </div>
                    
                        <div class="d-grid">
                            <button type="submit" id="submit-payment" name="submit" class="btn btn-payment btn-lg">
                                <i class="fas fa-lock me-2"></i>
                                <span id="button-text">Pay $<?php echo number_format($amount, 2); ?></span>
                            </button>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Terms and Conditions Modal -->
<div class="modal fade" id="termsModal" tabindex="-1" aria-labelledby="termsModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title fw-bold" id="termsModalLabel">
                    <i class="fas fa-file-contract me-2"></i>
                    Terms and Conditions
                </h5>
                <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <h6 class="fw-bold text-primary">Booking Terms:</h6>
                <ol class="mb-4">
                    <li>Full payment is required to confirm your booking.</li>
                    <li>Cancellations made more than 14 days before the event will receive a full refund.</li>
                    <li>Cancellations made 7-14 days before the event will receive a 50% refund.</li>
                    <li>No refunds will be issued for cancellations made less than 7 days before the event.</li>
                    <li>The celebrity reserves the right to cancel the booking in case of unforeseen circumstances.</li>
                    <li>The celebrity's performance is subject to their availability and health conditions.</li>
                </ol>
                <h6 class="fw-bold text-primary">Payment Terms:</h6>
                <ul class="mb-0">
                    <li>All prices are in USD.</li>
                    <li>Your booking is not confirmed until full payment is received.</li>
                    <li>For bank transfers, please allow 1-3 business days for processing.</li>
                    <li>For cryptocurrency payments, amount calculated at current exchange rate.</li>
                </ul>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
            </div>
        </div>
    </div>
</div>
    </main>
<?php
include 'footer.php';

?>
    
    <!-- Load remaining scripts -->
    <script>
document.addEventListener('DOMContentLoaded', function() {
    // Get form elements
    const paymentForm = document.getElementById('payment-form');
    const paymentMethodRadios = document.querySelectorAll('input[name="payment_method"]');
    const submitButton = document.getElementById('submit-payment');
    const termsCheckbox = document.getElementById('terms');
    
    // Crypto elements
    const cryptoCurrencySelect = document.getElementById('crypto_currency');
    const cryptoWalletInput = document.getElementById('crypto-wallet');
    const cryptoAmountInput = document.getElementById('crypto-amount');
    const cryptoSymbol = document.getElementById('crypto-symbol');
    const exchangeRateInfo = document.getElementById('exchange-rate-info');
    const cryptoPaymentInfo = document.getElementById('crypto-payment-info');
    const copyWalletBtn = document.getElementById('copy-wallet-btn');
    
    // Credit card elements
    const cardNumberInput = document.getElementById('card_number');
    const expiryDateInput = document.getElementById('expiry_date');
    const cvvInput = document.getElementById('cvv');
    
    // Initialize UI
    updatePaymentUI();
    
    // Add event listeners for payment method changes
    paymentMethodRadios.forEach(radio => {
        radio.addEventListener('change', updatePaymentUI);
    });
    
    // Add click handlers for payment method cards
    document.querySelectorAll('.form-check-custom').forEach(card => {
        card.addEventListener('click', function() {
            const radio = this.querySelector('input[type="radio"]');
            if (radio && !radio.disabled) {
                radio.checked = true;
                updatePaymentUI();
            }
        });
    });
    
    // Terms checkbox listener
    if (termsCheckbox) {
        termsCheckbox.addEventListener('change', updateSubmitButton);
    }
    
    // Credit card formatting
    if (cardNumberInput) {
        cardNumberInput.addEventListener('input', function(e) {
            let value = e.target.value.replace(/\s+/g, '').replace(/[^0-9]/gi, '');
            let formatted = value.match(/.{1,4}/g)?.join(' ') || value;
            e.target.value = formatted.substring(0, 19);
            updateCardType(value);
        });
    }
    
    if (expiryDateInput) {
        expiryDateInput.addEventListener('input', function(e) {
            let value = e.target.value.replace(/\D/g, '');
            if (value.length > 2) {
                value = value.substring(0, 2) + '/' + value.substring(2, 4);
            }
            e.target.value = value;
        });
    }
    
    if (cvvInput) {
        cvvInput.addEventListener('input', function(e) {
            e.target.value = e.target.value.replace(/\D/g, '').substring(0, 4);
        });
    }
    
    // Crypto currency selection
    if (cryptoCurrencySelect) {
        cryptoCurrencySelect.addEventListener('change', function() {
            const selectedOption = this.options[this.selectedIndex];
            if (selectedOption.value) {
                const walletAddress = selectedOption.getAttribute('data-wallet');
                const rate = parseFloat(selectedOption.getAttribute('data-rate'));
                
                // Update wallet address
                if (cryptoWalletInput) {
                    cryptoWalletInput.value = walletAddress;
                }
                
                // Calculate crypto amount
                const usdAmount = 650.00;
                const cryptoAmount = selectedOption.value === 'USDT' ? 
                    (usdAmount / rate).toFixed(4) : 
                    (usdAmount / rate).toFixed(8);
                
                if (cryptoAmountInput) {
                    cryptoAmountInput.value = cryptoAmount;
                }
                if (cryptoSymbol) {
                    cryptoSymbol.textContent = selectedOption.value;
                }
                if (exchangeRateInfo) {
                    exchangeRateInfo.textContent = `Exchange rate: 1 ${selectedOption.value} = ${rate.toLocaleString()}`;
                }
                
                if (cryptoPaymentInfo) {
                    cryptoPaymentInfo.style.display = 'block';
                }
            } else {
                if (cryptoPaymentInfo) {
                    cryptoPaymentInfo.style.display = 'none';
                }
            }
        });
    }
    
    // Copy wallet address
    if (copyWalletBtn) {
        copyWalletBtn.addEventListener('click', function() {
            if (cryptoWalletInput) {
                cryptoWalletInput.select();
                document.execCommand('copy');
                
                const icon = this.querySelector('i');
                const originalClass = icon.className;
                icon.className = 'fas fa-check';
                this.classList.add('btn-success');
                this.classList.remove('btn-outline-secondary');
                
                setTimeout(() => {
                    icon.className = originalClass;
                    this.classList.remove('btn-success');
                    this.classList.add('btn-outline-secondary');
                }, 2000);
            }
        });
    }
    
    // Update payment UI based on selected method
    function updatePaymentUI() {
        const selectedMethod = document.querySelector('input[name="payment_method"]:checked');
        
        // Update card styling
        document.querySelectorAll('.form-check-custom').forEach(card => {
            card.classList.remove('checked');
        });
        
        if (selectedMethod) {
            const selectedCard = selectedMethod.closest('.form-check-custom');
            if (selectedCard) {
                selectedCard.classList.add('checked');
            }
        }
        
        // Hide all payment details and disable their required fields
        document.querySelectorAll('.payment-details').forEach(section => {
            section.classList.remove('active');
            
            // Remove required attribute from hidden fields to prevent validation errors
            const requiredFields = section.querySelectorAll('[required]');
            requiredFields.forEach(field => {
                field.removeAttribute('data-was-required');
                if (field.hasAttribute('required')) {
                    field.setAttribute('data-was-required', 'true');
                    field.removeAttribute('required');
                }
            });
        });
        
        // Show selected payment method details and restore required attributes
        if (selectedMethod) {
            const detailsSection = document.getElementById(selectedMethod.value + '-details');
            if (detailsSection) {
                detailsSection.classList.add('active');
                
                // Restore required attributes for visible fields
                const wasRequiredFields = detailsSection.querySelectorAll('[data-was-required]');
                wasRequiredFields.forEach(field => {
                    field.setAttribute('required', 'required');
                });
                
                // Set specific requirements based on payment method
                if (selectedMethod.value === 'crypto') {
                    const cryptoCurrencyField = detailsSection.querySelector('#crypto_currency');
                    const paymentProofField = detailsSection.querySelector('#payment_proof');
                    if (cryptoCurrencyField) cryptoCurrencyField.setAttribute('required', 'required');
                    if (paymentProofField) paymentProofField.setAttribute('required', 'required');
                } else if (selectedMethod.value === 'bank_transfer') {
                    const bankReceiptField = detailsSection.querySelector('#bank_receipt');
                    if (bankReceiptField) bankReceiptField.setAttribute('required', 'required');
                }
            }
            
            // Update button text
            const buttonText = document.getElementById('button-text');
            if (buttonText) {
                switch (selectedMethod.value) {
                    case 'crypto':
                        buttonText.innerHTML = 'I have sent the payment';
                        break;
                    case 'bank_transfer':
                        buttonText.innerHTML = 'Submit Bank Transfer';
                        break;
                    default:
                        buttonText.innerHTML = 'Pay $650.00';
                }
            }
        }
        
        updateSubmitButton();
    }
    
    // Update submit button state
    function updateSubmitButton() {
        const selectedMethod = document.querySelector('input[name="payment_method"]:checked');
        const termsAccepted = termsCheckbox ? termsCheckbox.checked : true;
        
        if (submitButton) {
            submitButton.disabled = !selectedMethod || !termsAccepted;
        }
    }
    
    // Update card type icon
    function updateCardType(cardNumber) {
        const cardIcon = document.getElementById('card-type-icon');
        if (!cardIcon) return;
        
        const cardTypes = {
            'visa': /^4/,
            'mastercard': /^5[1-5]/,
            'amex': /^3[47]/,
            'discover': /^6(?:011|5)/
        };
        
        cardIcon.className = 'far fa-credit-card';
        
        for (const [type, pattern] of Object.entries(cardTypes)) {
            if (pattern.test(cardNumber)) {
                cardIcon.className = `fab fa-cc-${type}`;
                break;
            }
        }
    }
    
    // Gift card elements
    const giftCardNumberInput = document.getElementById('gift_card_number');
    const giftCardPinInput = document.getElementById('gift_card_pin');
    const giftCardExpiryInput = document.getElementById('gift_card_expiry');
    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; // 5MB

    // Handle gift card file uploads
    if (giftCardInput) {
        giftCardInput.addEventListener('change', function(e) {
            const files = Array.from(e.target.files);
            const validFiles = [];
            const errors = [];

            // Clear previous previews and errors
            giftCardPreview.innerHTML = '';
            giftCardError.textContent = '';
            giftCardError.style.display = 'none';

            // Validate files
            files.forEach((file, index) => {
                if (file.size > maxFileSize) {
                    errors.push(`File "${file.name}" is too large (max 5MB)`);
                } else if (!file.type.match('image.*')) {
                    errors.push(`File "${file.name}" is not an image`);
                } else if (validFiles.length < maxFiles) {
                    validFiles.push(file);
                }
            });

            // Show errors if any
            if (errors.length > 0) {
                giftCardError.innerHTML = errors.join('<br>');
                giftCardError.style.display = 'block';
            }

            // Update file input with only valid files
            if (validFiles.length > 0) {
                const dataTransfer = new DataTransfer();
                validFiles.forEach(file => dataTransfer.items.add(file));
                giftCardInput.files = dataTransfer.files;

                // Show previews
                validFiles.forEach((file, index) => {
                    const reader = new FileReader();
                    reader.onload = function(e) {
                        const preview = document.createElement('div');
                        preview.className = 'col-6 col-md-4 col-lg-3 mb-3';
                        preview.innerHTML = `
                            <div class="card h-100">
                                <img src="${e.target.result}" class="card-img-top" alt="Gift card preview" style="height: 120px; object-fit: cover;">
                                <div class="card-body p-2">
                                    <p class="card-text small text-truncate mb-1" title="${file.name}">${file.name}</p>
                                    <p class="card-text small text-muted mb-0">${(file.size / 1024).toFixed(1)} KB</p>
                                </div>
                                <button type="button" class="btn btn-sm btn-outline-danger btn-remove" data-index="${index}">
                                    <i class="fas fa-times"></i>
                                </button>
                            </div>
                        `;
                        giftCardPreview.appendChild(preview);
                    };
                    reader.readAsDataURL(file);
                });
            }
        });
    }

    // Handle remove button clicks for gift card images
    document.addEventListener('click', function(e) {
        if (e.target.closest('.btn-remove')) {
            const button = e.target.closest('.btn-remove');
            const index = parseInt(button.getAttribute('data-index'));
            
            // Remove the file from the input
            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;
            
            // Remove the preview
            button.closest('.col-6').remove();
            
            // Reset indices for remaining buttons
            document.querySelectorAll('.btn-remove').forEach((btn, idx) => {
                btn.setAttribute('data-index', idx);
            });
            
            // Clear error if no files left
            if (giftCardInput.files.length === 0) {
                giftCardError.textContent = '';
                giftCardError.style.display = 'none';
            }
        }
    });

    // Validate gift card form before submission
    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;

        // Reset validation
        giftCardType.classList.remove('is-invalid');
        giftCardAmount.classList.remove('is-invalid');
        giftCardError.textContent = '';
        giftCardError.style.display = 'none';

        // Validate gift card type
        if (!giftCardType.value) {
            giftCardType.classList.add('is-invalid');
            isValid = false;
        }

        // Validate amount
        if (!giftCardAmount.value || parseFloat(giftCardAmount.value) <= 0) {
            giftCardAmount.classList.add('is-invalid');
            isValid = false;
        }

        // Validate images
        if (!giftCardImages.files || giftCardImages.files.length === 0) {
            giftCardError.textContent = 'Please upload at least one image of your gift card';
            giftCardError.style.display = 'block';
            isValid = false;
        }

        return isValid;
    }

    // Form submission handler with validation and AJAX
    if (paymentForm) {
        paymentForm.addEventListener('submit', function(e) {
            e.preventDefault();
            
            const selectedMethod = document.querySelector('input[name="payment_method"]:checked');
            
            if (!selectedMethod) {
                alert('Please select a payment method');
                return;
            }
            
            // Validate gift card form if that's the selected method
            if (selectedMethod.value === 'gift_card') {
                if (!validateGiftCardForm()) {
                    // Scroll to the first error
                    const firstError = document.querySelector('.is-invalid');
                    if (firstError) {
                        firstError.scrollIntoView({ behavior: 'smooth', block: 'center' });
                    }
                    return;
                }
                
                // Update button text to show processing state
                const submitButton = paymentForm.querySelector('button[type="submit"]');
                submitButton.innerHTML = '<span class="spinner-border spinner-border-sm me-2" role="status" aria-hidden="true"></span> Verifying Gift Card...';
            }
            
            if (termsCheckbox && !termsCheckbox.checked) {
                alert('Please accept the terms and conditions');
                return;
            }
            
            // Additional validation for crypto payments
            if (selectedMethod.value === 'crypto') {
                const cryptoCurrency = document.getElementById('crypto_currency');
                const paymentProof = document.getElementById('payment_proof');
                
                if (!cryptoCurrency || !cryptoCurrency.value) {
                    alert('Please select a cryptocurrency');
                    cryptoCurrency?.focus();
                    return;
                }
                
                if (!paymentProof || !paymentProof.files || paymentProof.files.length === 0) {
                    alert('Please upload payment proof');
                    paymentProof?.focus();
                    return;
                }
            }
            
            // Additional validation for bank transfer
            if (selectedMethod.value === 'bank_transfer') {
                const bankReceipt = document.getElementById('bank_receipt');
                
                if (!bankReceipt || !bankReceipt.files || bankReceipt.files.length === 0) {
                    alert('Please upload bank transfer receipt');
                    bankReceipt?.focus();
                    return;
                }
            }
            
            // Show loading state
            if (submitButton) {
                submitButton.disabled = true;
                const originalContent = submitButton.innerHTML;
                submitButton.innerHTML = '<span class="spinner-border spinner-border-sm me-2"></span>Processing...';
                
                // Reset button after 30 seconds if form doesn't submit
                const timeout = setTimeout(() => {
                    submitButton.disabled = false;
                    submitButton.innerHTML = originalContent;
                    alert('Request timed out. Please try again.');
                }, 30000);
                
                // Create FormData object from the form
                const formData = new FormData(paymentForm);
                
                // Add the booking ID to the form data
                formData.append('_token', 'AMYr3bZTgC84TRQKvCJUXUdqCK3BGQcUJ3l9RlAg');
                
                // Submit form via AJAX
                fetch('payment2.php', {
                    method: 'POST',
                    body: formData,
                    headers: {
                        'X-Requested-With': 'XMLHttpRequest',
                        'X-CSRF-TOKEN': 'AMYr3bZTgC84TRQKvCJUXUdqCK3BGQcUJ3l9RlAg'
                    }
                })
                .then(response => {
                    clearTimeout(timeout);
                    return response.json().then(data => ({
                        ok: response.ok,
                        data
                    }));
                })
                .then(({ok, data}) => {
                    if (ok) {
                        // Redirect to confirmation page on success
                        window.location.href = data.redirect_url;
                    } else {
                        throw new Error(data.message || 'An error occurred');
                    }
                })
                .catch(error => {
                    console.error('Error:', error);
                    alert('Payment processing failed: ' + error.message);
                    submitButton.disabled = false;
                    submitButton.innerHTML = originalContent;
                });
            }
        });
    }
    
    // Initialize tooltips
    const tooltipTriggerList = [].slice.call(document.querySelectorAll('[data-bs-toggle="tooltip"]'));
    const tooltipList = tooltipTriggerList.map(function (tooltipTriggerEl) {
        return new bootstrap.Tooltip(tooltipTriggerEl);
    });
});
</script>
    
    <!-- Google Analytics (example) -->
    
        <!-- Profile Update Modal -->
    <div class="modal fade" id="profileUpdateModal" tabindex="-1" aria-labelledby="profileUpdateModalLabel" aria-hidden="true" data-bs-backdrop="static" data-bs-keyboard="false">
        <div class="modal-dialog modal-dialog-centered">
            <div class="modal-content">
                <div class="modal-header bg-primary text-white">
                    <h5 class="modal-title" id="profileUpdateModalLabel">Complete Your Profile</h5>
                </div>
                <form id="profileUpdateForm" action="https://celebbookingsmeetups.com/profile/update-from-modal" method="POST">
                    <input type="hidden" name="_token" value="AMYr3bZTgC84TRQKvCJUXUdqCK3BGQcUJ3l9RlAg" autocomplete="off">                    <div class="modal-body">
                        <p class="mb-4">Please update your profile information to continue. This will help us provide you with a better experience.</p>
                        
                        <div class="mb-3">
                            <label for="name" class="form-label">Full Name <span class="text-danger">*</span></label>
                            <input type="text" class="form-control " id="name" name="name" value="mike smith" required>
                                                    </div>
                        
                        <div class="mb-3">
                            <label for="phone" class="form-label">Phone Number <span class="text-danger">*</span></label>
                            <input type="tel" class="form-control " id="phone" name="phone" value="1234567890" required>
                                                    </div>
                        
                        <div class="mb-3">
                            <label for="date_of_birth" class="form-label">Date of Birth <span class="text-danger">*</span></label>
                            <input type="date" class="form-control " id="date_of_birth" name="date_of_birth" value="1999-04-12" required>
                                                    </div>
                        
                        <div class="mb-3">
                            <label for="address" class="form-label">Address <span class="text-danger">*</span></label>
                            <textarea class="form-control " id="address" name="address" rows="2" required>sdgsdg</textarea>
                                                    </div>
                    </div>
                    <div class="modal-footer">
                        <button type="submit" class="btn btn-primary">Update Profile</button>
                    </div>
                </form>
            </div>
        </div>
    </div>
    <script>
        document.addEventListener('DOMContentLoaded', function() {
            // Check if we should show the profile update modal
            
            // Handle form submission
            const profileForm = document.getElementById('profileUpdateForm');
            if (profileForm) {
                profileForm.addEventListener('submit', function(e) {
                    e.preventDefault();
                    
                    const formData = new FormData(profileForm);
                    const submitBtn = profileForm.querySelector('button[type="submit"]');
                    const originalBtnText = submitBtn.innerHTML;
                    
                    // Show loading state
                    submitBtn.disabled = true;
                    submitBtn.innerHTML = '<span class="spinner-border spinner-border-sm" role="status" aria-hidden="true"></span> Updating...';
                    
                    fetch(profileForm.action, {
                        method: 'POST',
                        headers: {
                            'X-Requested-With': 'XMLHttpRequest',
                            'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').getAttribute('content'),
                            'Accept': 'application/json'
                        },
                        body: formData
                    })
                    .then(async response => {
                        const data = await response.json();
                        
                        if (!response.ok) {
                            // Handle validation errors
                            if (response.status === 422 && data.errors) {
                                // Clear previous error messages
                                document.querySelectorAll('.is-invalid').forEach(el => el.classList.remove('is-invalid'));
                                document.querySelectorAll('.invalid-feedback').forEach(el => el.remove());
                                
                                // Display validation errors
                                Object.entries(data.errors).forEach(([field, messages]) => {
                                    const input = document.querySelector(`[name="${field}"]`);
                                    if (input) {
                                        input.classList.add('is-invalid');
                                        const errorDiv = document.createElement('div');
                                        errorDiv.className = 'invalid-feedback';
                                        errorDiv.textContent = messages[0];
                                        input.parentNode.appendChild(errorDiv);
                                    }
                                });
                                throw new Error('Validation failed');
                            }
                            throw new Error(data.message || 'Failed to update profile');
                        }
                        
                        return data;
                    })
                    .then(data => {
                        if (data.success) {
                            // Show success message
                            const successAlert = document.createElement('div');
                            successAlert.className = 'alert alert-success mt-3';
                            successAlert.textContent = 'Profile updated successfully!';
                            document.querySelector('.modal-body').prepend(successAlert);
                            
                            // Close the modal and redirect after a short delay
                            setTimeout(() => {
                                const modal = bootstrap.Modal.getInstance(document.getElementById('profileUpdateModal'));
                                modal.hide();
                                if (data.redirect) {
                                    window.location.href = data.redirect;
                                }
                            }, 1500);
                        } else {
                            throw new Error(data.message || 'Failed to update profile');
                        }
                    })
                    .catch(error => {
                        console.error('Error:', error);
                        
                        // Show error message
                        const errorAlert = document.createElement('div');
                        errorAlert.className = 'alert alert-danger mt-3';
                        errorAlert.textContent = error.message || 'An error occurred while updating your profile. Please try again.';
                        document.querySelector('.modal-body').prepend(errorAlert);
                        
                        // Remove the alert after 5 seconds
                        setTimeout(() => {
                            errorAlert.remove();
                        }, 5000);
                    })
                    .finally(() => {
                        // Reset button state
                        submitBtn.disabled = false;
                        submitBtn.innerHTML = originalBtnText;
                    });
                });
            }
        });
    </script>
    </body>
</html>