<?php
require_once __DIR__ . '/includes/auth.php';
requireLogin();

if (!isset($_GET['booking_id'])) {
    header('Location: book-services.php');
    exit();
}

$booking_id = (int) $_GET['booking_id'];
$conn = getDBConnection();
$stmt = $conn->prepare("
    SELECT b.*, s.name as service_name, u.name as user_name, u.email
    FROM bookings b
    JOIN services s ON b.service_id = s.id
    JOIN users u ON b.user_id = u.id
    WHERE b.id = ? AND b.user_id = ?
");
$stmt->bind_param('ii', $booking_id, $_SESSION['user_id']);
$stmt->execute();
$result = $stmt->get_result();
$booking = $result->fetch_assoc();
$stmt->close();
$conn->close();

if (!$booking) {
    header('Location: book-services.php');
    exit();
}
?>
<!DOCTYPE html>
<html lang='en'>
<head>
    <meta charset='UTF-8'>
    <meta name='viewport' content='width=device-width, initial-scale=1.0'>
    <title>Payment - Oldage Home</title>
    <link href='https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css' rel='stylesheet'>
    <link rel='stylesheet' href='https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css'>
    <link href='https://fonts.googleapis.com/css2?family=Poppins:wght@300;400;500;600;700&display=swap' rel='stylesheet'>
    <link rel='stylesheet' href='css/style.css'>
</head>
<body>
    <?php include 'includes/header.php'; ?>

    <section class='py-5'>
        <div class='container'>
            <div class='row justify-content-center'>
                <div class='col-lg-8'>
                    <div class='card shadow'>
                        <div class='card-body p-5'>
                            <h2 class='mb-4'>Complete Your Payment</h2>

                            <div class='card mb-4'>
                                <div class='card-header'><h5 class='mb-0'>Booking Summary</h5></div>
                                <div class='card-body'>
                                    <div class='row'>
                                        <div class='col-md-6'>
                                            <p><strong>Service:</strong> <?php echo htmlspecialchars($booking['service_name']); ?></p>
                                            <p><strong>Date:</strong> <?php echo date('F j, Y', strtotime($booking['booking_date'])); ?></p>
                                            <p><strong>Time:</strong> <?php echo date('g:i A', strtotime($booking['booking_time'])); ?></p>
                                        </div>
                                        <div class='col-md-6'>
                                            <p><strong>Customer:</strong> <?php echo htmlspecialchars($booking['user_name']); ?></p>
                                            <p><strong>Email:</strong> <?php echo htmlspecialchars($booking['email']); ?></p>
                                            <?php if ($booking['notes']): ?>
                                            <p><strong>Notes:</strong> <?php echo htmlspecialchars($booking['notes']); ?></p>
                                            <?php endif; ?>
                                        </div>
                                    </div>
                                    <hr>
                                    <div class='d-flex justify-content-between'>
                                        <strong>Total Amount:</strong>
                                        <strong class='text-primary'>$<?php echo number_format($booking['total_amount'], 2); ?></strong>
                                    </div>
                                </div>
                            </div>

                            <form id='payment-form'>
                                <div class='row'>
                                    <div class='col-md-6 mb-3'>
                                        <label for='cardholder-name' class='form-label'>Cardholder Name *</label>
                                        <input type='text' class='form-control' id='cardholder-name' placeholder='John Doe' required>
                                    </div>
                                    <div class='col-md-6 mb-3'>
                                        <label for='billing-address' class='form-label'>Billing Address *</label>
                                        <input type='text' class='form-control' id='billing-address' placeholder='123 Main St' required>
                                    </div>
                                </div>
                                <div class='row'>
                                    <div class='col-md-6 mb-3'>
                                        <label for='card-number' class='form-label'>Card Number *</label>
                                        <input type='text' class='form-control' id='card-number' placeholder='4242 4242 4242 4242' required>
                                    </div>
                                    <div class='col-md-3 mb-3'>
                                        <label for='expiry' class='form-label'>Expiry *</label>
                                        <input type='text' class='form-control' id='expiry' placeholder='12/34' required>
                                    </div>
                                    <div class='col-md-3 mb-3'>
                                        <label for='cvv' class='form-label'>CVV *</label>
                                        <input type='text' class='form-control' id='cvv' placeholder='123' required>
                                    </div>
                                </div>

                                <div class='alert alert-info'>
                                    <i class='fas fa-credit-card me-2'></i>
                                    Demo payment mode is enabled. You can use any test-looking card details, such as <strong>4242 4242 4242 4242</strong>.
                                </div>

                                <div id='card-errors' role='alert' class='text-danger mb-3'></div>

                                <div class='d-grid'>
                                    <button type='submit' class='btn btn-primary btn-lg' id='submit-payment'>
                                        <span id='button-text'>Pay $<?php echo number_format($booking['total_amount'], 2); ?></span>
                                        <div class='spinner-border spinner-border-sm ms-2 d-none' role='status'><span class='visually-hidden'>Loading...</span></div>
                                    </button>
                                </div>
                            </form>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </section>

    <script>
    const form = document.getElementById('payment-form');
    const submitButton = document.getElementById('submit-payment');
    const buttonText = document.getElementById('button-text');
    const spinner = submitButton.querySelector('.spinner-border');
    const errorBox = document.getElementById('card-errors');

    form.addEventListener('submit', async (event) => {
        event.preventDefault();
        errorBox.textContent = '';
        submitButton.disabled = true;
        buttonText.textContent = 'Processing...';
        spinner.classList.remove('d-none');

        const cardholderName = document.getElementById('cardholder-name').value.trim();
        const billingAddress = document.getElementById('billing-address').value.trim();
        const cardNumber = document.getElementById('card-number').value.trim();
        const expiry = document.getElementById('expiry').value.trim();
        const cvv = document.getElementById('cvv').value.trim();

        if (!cardholderName || !billingAddress || !cardNumber || !expiry || !cvv) {
            errorBox.textContent = 'Please fill in all required payment fields.';
            submitButton.disabled = false;
            buttonText.textContent = 'Pay $<?php echo number_format($booking['total_amount'], 2); ?>';
            spinner.classList.add('d-none');
            return;
        }

        try {
            const response = await fetch('process-payment.php', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({
                    payment_method_id: 'demo_card',
                    booking_id: <?php echo $booking_id; ?>,
                    amount: <?php echo $booking['total_amount'] * 100; ?>,
                    cardholder_name: cardholderName,
                    billing_address: billingAddress,
                    card_number: cardNumber,
                    expiry: expiry,
                    cvv: cvv
                })
            });

            const result = await response.json();

            if (result.success) {
                window.location.href = 'payment-success.php?booking_id=' + <?php echo $booking_id; ?>;
            } else {
                errorBox.textContent = result.error || 'Payment failed. Please try again.';
                submitButton.disabled = false;
                buttonText.textContent = 'Pay $<?php echo number_format($booking['total_amount'], 2); ?>';
                spinner.classList.add('d-none');
            }
        } catch (error) {
            errorBox.textContent = 'An error occurred. Please try again.';
            submitButton.disabled = false;
            buttonText.textContent = 'Pay $<?php echo number_format($booking['total_amount'], 2); ?>';
            spinner.classList.add('d-none');
        }
    });
    </script>

    <?php include 'includes/footer.php'; ?>
    <script src='https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js'></script>
    <script src='js/main.js'></script>
</body>
</html>

