<?php
require_once __DIR__ . '/includes/config.php';
require_once __DIR__ . '/includes/database.php';

$pdo = getDatabaseConnection();

$preselectedSlug = $_GET['event'] ?? '';

// Fetch all published events
$stmt = $pdo->query("SELECT * FROM events WHERE status = 'PUBLISHED' ORDER BY createdAt DESC");
$events = $stmt->fetchAll(PDO::FETCH_ASSOC);

$error = null;
$successData = null;

if (isset($_GET['success']) && isset($_GET['regId'])) {
    $regId = $_GET['regId'];
    try {
        $regStmt = $pdo->prepare("
            SELECT r.*, e.title, e.eventDate, e.venue, p.amount, p.razorpayPaymentId 
            FROM registrations r 
            JOIN events e ON r.eventId = e.id 
            LEFT JOIN payments p ON p.registrationId = r.id 
            WHERE r.registrationId = ?
        ");
        $regStmt->execute([$regId]);
        $reg = $regStmt->fetch(PDO::FETCH_ASSOC);
        if ($reg) {
            $successData = [
                'registrationId' => $reg['registrationId'],
                'fullName' => $reg['fullName'],
                'email' => $reg['email'],
                'amount' => $reg['amount'],
                'paymentId' => $reg['razorpayPaymentId'],
                'event' => [
                    'title' => $reg['title'],
                    'eventDate' => $reg['eventDate'],
                    'venue' => $reg['venue']
                ]
            ];
        }
    } catch (PDOException $e) {
        error_log("Load Success Data Error: " . $e->getMessage());
    }
}

function formatCurrency($amt) { return $amt == 0 ? 'Free' : '₹' . number_format($amt); }
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Register - <?= APP_NAME ?></title>
    <link rel="stylesheet" href="<?= APP_URL ?>/assets/css/style.css">
    <script src="https://unpkg.com/lucide@latest"></script>
    <script>
        const eventsData = <?= json_encode($events) ?>;
        
        function updateEventDetails() {
            const select = document.getElementById('event-select');
            const detailsDiv = document.getElementById('event-details');
            if(!select.value) {
                detailsDiv.classList.add('hidden');
                return;
            }
            const evt = eventsData.find(e => e.id === select.value);
            if(evt) {
                detailsDiv.classList.remove('hidden');
                document.getElementById('evt-date').textContent = evt.eventDate;
                document.getElementById('evt-venue').textContent = evt.venue;
                document.getElementById('evt-fee').textContent = evt.registrationFee == 0 ? 'Free' : '₹' + parseFloat(evt.registrationFee).toLocaleString();
            }
        }
    </script>
</head>
<body class="bg-slate-950 text-slate-200 antialiased selection:bg-cyan-500/30 selection:text-cyan-200 min-h-screen">
    <?php include __DIR__ . '/includes/navbar.php'; ?>

    <?php if ($successData): ?>
    <div class="min-h-screen bg-background text-slate-100 py-16 px-4 flex items-center justify-center relative overflow-hidden font-tech">
        <div class="absolute top-1/2 left-1/2 -translate-x-1/2 -translate-y-1/2 w-[600px] h-[600px] bg-gradient-to-tr from-cyan-500/20 to-purple-600/20 rounded-full blur-[140px] pointer-events-none"></div>

        <div class="max-w-xl w-full glass-panel p-8 md:p-10 rounded-3xl border border-cyan-500/30 text-center relative z-10 shadow-2xl">
            <div class="w-16 h-16 rounded-full bg-cyan-500/10 border border-cyan-500/30 text-cyan-400 flex items-center justify-center mx-auto mb-6">
                <i data-lucide="check-circle" class="w-10 h-10"></i>
            </div>

            <h2 class="text-3xl font-extrabold text-slate-100 mb-2 font-heading-cyber">Registration Initiated!</h2>
            <p class="text-slate-400 text-sm mb-6">
                You have successfully registered for <span class="text-cyan-400 font-bold"><?= htmlspecialchars($successData['event']['title']) ?></span>.
            </p>

            <div class="p-6 rounded-2xl bg-slate-900/80 border border-white/10 text-left space-y-3 mb-8">
                <div class="flex items-center justify-between border-b border-white/10 pb-3">
                    <span class="text-xs text-slate-400 uppercase tracking-wider font-semibold">Registration ID</span>
                    <span class="text-xl font-mono font-bold text-cyan-400 bg-cyan-500/10 px-3 py-1 rounded-md border border-cyan-500/30">
                        <?= htmlspecialchars($successData['registrationId']) ?>
                    </span>
                </div>

                <div class="grid grid-cols-2 gap-4 text-xs text-slate-300 pt-2">
                    <div>
                        <span class="text-slate-500 block">Participant</span>
                        <span class="font-semibold"><?= htmlspecialchars($successData['fullName']) ?></span>
                    </div>
                    <div>
                        <span class="text-slate-500 block">Email</span>
                        <span class="font-semibold"><?= htmlspecialchars($successData['email']) ?></span>
                    </div>
                    <div>
                        <span class="text-slate-500 block">Event Date</span>
                        <span class="font-semibold"><?= htmlspecialchars($successData['event']['eventDate']) ?></span>
                    </div>
                    <div>
                        <span class="text-slate-500 block">Venue</span>
                        <span class="font-semibold"><?= htmlspecialchars($successData['event']['venue']) ?></span>
                    </div>
                    <?php if (!empty($successData['paymentId'])): ?>
                    <div>
                        <span class="text-slate-500 block">Transaction ID</span>
                        <span class="font-semibold font-mono text-[10px] text-cyan-400"><?= htmlspecialchars($successData['paymentId']) ?></span>
                    </div>
                    <div>
                        <span class="text-slate-500 block">Amount Paid</span>
                        <span class="font-semibold text-emerald-400">₹<?= number_format($successData['amount'], 2) ?></span>
                    </div>
                    <?php endif; ?>
                </div>
            </div>

            <div class="mb-6 p-4 rounded-xl bg-cyan-500/10 border border-cyan-500/30 text-cyan-400 text-xs flex items-center justify-center gap-2 font-mono-cyber">
                <i data-lucide="camera" class="w-4 h-4 shrink-0 text-cyan-400"></i>
                <span>IMPORTANT: Please take a screenshot or snapshot of this receipt for your reference!</span>
            </div>

            <div class="flex flex-col sm:flex-row gap-4">
                <a href="<?= APP_URL ?>/events" class="flex-1 py-3.5 rounded-xl glass-panel text-slate-300 font-semibold hover:border-cyan-400 text-sm text-center">
                    Browse More Events
                </a>
                <a href="<?= APP_URL ?>/attendance/scan.php?regId=<?= htmlspecialchars($successData['registrationId']) ?>" class="flex-1 py-3.5 rounded-xl bg-gradient-to-r from-cyan-500 to-blue-600 text-slate-950 font-bold text-sm shadow-glow flex items-center justify-center gap-2">
                    View Attendance Desk <i data-lucide="ticket" class="w-4 h-4"></i>
                </a>
            </div>
        </div>
    </div>
    <?php else: ?>
    <div class="min-h-screen bg-background text-slate-100 pb-12 px-4 sm:px-6 lg:px-8 relative font-tech pt-36 md:pt-48">
        <div class="max-w-3xl mx-auto relative z-10">
            <a href="<?= APP_URL ?>/events" class="inline-flex items-center gap-2 text-sm text-slate-400 hover:text-cyan-400 mb-8 transition-colors">
                <i data-lucide="arrow-left" class="w-4 h-4"></i> Back to Events
            </a>

            <div class="glass-panel p-8 md:p-10 rounded-3xl border border-white/10 shadow-2xl">
                <div class="inline-flex items-center gap-2 px-3 py-1 rounded-full bg-cyan-500/10 border border-cyan-500/30 text-cyan-400 text-xs font-semibold uppercase mb-4 font-mono-cyber">
                    <i data-lucide="sparkles" class="w-3.5 h-3.5"></i> No Account Login Needed
                </div>

                <h1 class="text-3xl font-extrabold text-slate-100 mb-2 font-heading-cyber">Event Registration Form</h1>
                <p class="text-slate-400 text-sm mb-8">
                    Complete your details below to instantly receive your official Supernova 2.0 Registration ID.
                </p>

                <div id="error-container" class="hidden mb-6 p-4 rounded-xl bg-red-500/10 border border-red-500/30 text-red-400 text-sm flex items-center gap-3">
                    <i data-lucide="alert-circle" class="w-5 h-5 shrink-0"></i>
                    <span id="error-message"></span>
                </div>

                <form id="registration-form" class="space-y-6">
                    <!-- Event Selector -->
                    <div>
                        <label class="block text-xs font-semibold text-slate-300 uppercase mb-2 font-mono-cyber">Select Event</label>
                        <select name="eventId" id="event-select" required onchange="updateEventDetails()" class="w-full px-4 py-3 rounded-xl bg-slate-900/80 border border-white/10 text-slate-100 focus:outline-none focus:border-cyan-400 text-sm">
                            <?php foreach ($events as $evt): ?>
                            <option value="<?= htmlspecialchars($evt['id']) ?>" <?= $preselectedSlug === $evt['slug'] ? 'selected' : '' ?>>
                                <?= htmlspecialchars($evt['title']) ?> (<?= htmlspecialchars($evt['category']) ?>) — <?= formatCurrency($evt['registrationFee']) ?>
                            </option>
                            <?php endforeach; ?>
                        </select>
                    </div>

                    <!-- Selected Event Brief Card -->
                    <div id="event-details" class="p-4 rounded-2xl bg-cyan-500/5 border border-cyan-500/20 flex flex-wrap items-center justify-between gap-4 text-xs">
                        <div class="flex items-center gap-4">
                            <div class="flex items-center gap-1.5 text-slate-300">
                                <i data-lucide="calendar" class="w-4 h-4 text-cyan-400"></i>
                                <span id="evt-date">-</span>
                            </div>
                            <div class="flex items-center gap-1.5 text-slate-300">
                                <i data-lucide="map-pin" class="w-4 h-4 text-cyan-400"></i>
                                <span id="evt-venue">-</span>
                            </div>
                        </div>
                        <span class="font-bold text-cyan-400 text-sm" id="evt-fee">-</span>
                    </div>

                    <!-- Standard Fields -->
                    <div class="grid grid-cols-1 sm:grid-cols-2 gap-4">
                        <div>
                            <label class="block text-xs font-semibold text-slate-300 uppercase mb-2 font-mono-cyber">Full Name *</label>
                            <div class="relative">
                                <i data-lucide="user" class="w-4 h-4 absolute left-3 top-1/2 -translate-y-1/2 text-slate-500"></i>
                                <input type="text" name="fullName" id="name-input" required placeholder="Enter your full name" pattern="[a-zA-Z\s\.]+" class="w-full pl-10 pr-4 py-3 rounded-xl bg-slate-900/80 border border-white/10 text-slate-100 placeholder-slate-600 focus:outline-none focus:border-cyan-400 text-sm" />
                            </div>
                        </div>

                        <div>
                            <label class="block text-xs font-semibold text-slate-300 uppercase mb-2 font-mono-cyber">Email Address *</label>
                            <div class="relative">
                                <i data-lucide="mail" class="w-4 h-4 absolute left-3 top-1/2 -translate-y-1/2 text-slate-500"></i>
                                <input type="email" name="email" id="email-input" required placeholder="yourname@gmail.com" class="w-full pl-10 pr-4 py-3 rounded-xl bg-slate-900/80 border border-white/10 text-slate-100 placeholder-slate-600 focus:outline-none focus:border-cyan-400 text-sm" />
                            </div>
                        </div>

                        <div>
                            <label class="block text-xs font-semibold text-slate-300 uppercase mb-2 font-mono-cyber">Mobile Number *</label>
                            <div class="relative">
                                <i data-lucide="phone" class="w-4 h-4 absolute left-3 top-1/2 -translate-y-1/2 text-slate-500"></i>
                                <input type="text" name="mobileNumber" id="mobile-input" required placeholder="10-digit mobile number" maxlength="10" pattern="\d{10}" class="w-full pl-10 pr-4 py-3 rounded-xl bg-slate-900/80 border border-white/10 text-slate-100 placeholder-slate-600 focus:outline-none focus:border-cyan-400 text-sm" />
                            </div>
                        </div>

                        <div>
                            <label class="block text-xs font-semibold text-slate-300 uppercase mb-2 font-mono-cyber">City *</label>
                            <div class="relative">
                                <i data-lucide="map" class="w-4 h-4 absolute left-3 top-1/2 -translate-y-1/2 text-slate-500"></i>
                                <input type="text" name="city" id="city-input" required placeholder="e.g. Mumbai, Pune, Delhi" pattern="[a-zA-Z\s]+" class="w-full pl-10 pr-4 py-3 rounded-xl bg-slate-900/80 border border-white/10 text-slate-100 placeholder-slate-600 focus:outline-none focus:border-cyan-400 text-sm" />
                            </div>
                        </div>
                    </div>

                    <div>
                        <label class="block text-xs font-semibold text-slate-300 uppercase mb-2 font-mono-cyber">College / Organization *</label>
                        <div class="relative">
                            <i data-lucide="building" class="w-4 h-4 absolute left-3 top-1/2 -translate-y-1/2 text-slate-500"></i>
                            <input type="text" name="college" id="college-input" required placeholder="Enter college or institution name" pattern="[a-zA-Z\s\.,\-\/\&\(\)]+" class="w-full pl-10 pr-4 py-3 rounded-xl bg-slate-900/80 border border-white/10 text-slate-100 placeholder-slate-600 focus:outline-none focus:border-cyan-400 text-sm" />
                        </div>
                    </div>

                    <button type="submit" id="submit-btn" class="w-full py-4 rounded-xl bg-gradient-to-r from-cyan-500 to-blue-600 hover:from-cyan-400 hover:to-blue-500 text-slate-950 font-extrabold text-base transition-all shadow-glow flex items-center justify-center font-mono-cyber">
                        <span id="btn-text">Complete Registration</span>
                    </button>
                </form>
            </div>
        </div>
    </div>

    <script src="https://checkout.razorpay.com/v1/checkout.js"></script>
    <script>
        document.addEventListener('DOMContentLoaded', () => {
            updateEventDetails();

            const form = document.getElementById('registration-form');
            if (!form) return;

            const submitBtn = document.getElementById('submit-btn');
            const btnText = document.getElementById('btn-text');
            const errorContainer = document.getElementById('error-container');
            const errorMessage = document.getElementById('error-message');
            const mobileInput = document.getElementById('mobile-input');
            const nameInput = document.getElementById('name-input');
            const emailInput = document.getElementById('email-input');
            const cityInput = document.getElementById('city-input');
            const collegeInput = document.getElementById('college-input');

            if (mobileInput) {
                mobileInput.addEventListener('input', (e) => {
                    e.target.value = e.target.value.replace(/\D/g, '');
                });
            }

            if (nameInput) {
                nameInput.addEventListener('input', (e) => {
                    e.target.value = e.target.value.replace(/[^a-zA-Z\s\.]/g, '');
                });
            }

            if (emailInput) {
                emailInput.addEventListener('input', (e) => {
                    e.target.value = e.target.value.replace(/[^a-zA-Z0-9\@\.\_\-\+]/g, '');
                });
            }

            if (cityInput) {
                cityInput.addEventListener('input', (e) => {
                    e.target.value = e.target.value.replace(/[^a-zA-Z\s]/g, '');
                });
            }

            if (collegeInput) {
                collegeInput.addEventListener('input', (e) => {
                    e.target.value = e.target.value.replace(/[^a-zA-Z\s\.\,\-\/\&\(\)]/g, '');
                });
            }

            form.addEventListener('submit', async (e) => {
                e.preventDefault();

                // Validate fields
                const mobileNumber = form.querySelector('input[name="mobileNumber"]').value;
                const fullName = form.querySelector('input[name="fullName"]').value;
                const email = form.querySelector('input[name="email"]').value;
                const city = form.querySelector('input[name="city"]').value;
                const college = form.querySelector('input[name="college"]').value;

                if (!/^\d{10}$/.test(mobileNumber)) {
                    showError('Mobile number must be exactly 10 digits and contain only numbers.');
                    return;
                }

                if (!/^[a-zA-Z\s\.]+$/.test(fullName)) {
                    showError('Full name must contain only alphabets, spaces, or periods.');
                    return;
                }

                if (!/^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/.test(email)) {
                    showError('Invalid email format. Only alphabets, numbers, and symbols like @, ., _, -, + are allowed.');
                    return;
                }

                if (!/^[a-zA-Z\s]+$/.test(city)) {
                    showError('City must contain only alphabets and spaces.');
                    return;
                }

                if (!/^[a-zA-Z\s\.\,\-\/\&\(\)]+$/.test(college)) {
                    showError('College / Organization must contain only alphabets, spaces, and standard punctuation (no numbers).');
                    return;
                }

                // Clear errors
                errorContainer.classList.add('hidden');
                errorMessage.textContent = '';

                // Disable button & change text
                submitBtn.disabled = true;
                btnText.textContent = 'Processing...';

                // Collect form data
                const formData = {
                    eventId: document.getElementById('event-select').value,
                    fullName: form.querySelector('input[name="fullName"]').value,
                    email: form.querySelector('input[name="email"]').value,
                    mobileNumber: form.querySelector('input[name="mobileNumber"]').value,
                    city: form.querySelector('input[name="city"]').value,
                    college: form.querySelector('input[name="college"]').value
                };

                try {
                    // Step 1: Create Order
                    const orderResponse = await fetch('<?= APP_URL ?>/create_order.php', {
                        method: 'POST',
                        headers: { 'Content-Type': 'application/json', 'X-CSRF-Token': '<?= csrf_token() ?>' },
                        body: JSON.stringify(formData)
                    });

                    const orderResult = await orderResponse.json();

                    if (!orderResponse.ok) {
                        throw new Error(orderResult.error || 'Failed to initialize order.');
                    }

                    // Step 2: Check if free event
                    if (orderResult.isFree) {
                        window.location.href = `<?= APP_URL ?>/register.php?success=1&regId=${orderResult.registrationId}`;
                        return;
                    }

                    // Step 3: Trigger Razorpay Checkout
                    const options = {
                        key: orderResult.keyId,
                        amount: orderResult.amount,
                        currency: 'INR',
                        name: '<?= APP_NAME ?>',
                        description: 'Event Registration Fee',
                        order_id: orderResult.razorpayOrderId,
                        prefill: {
                            name: formData.fullName,
                            email: formData.email,
                            contact: formData.mobileNumber
                        },
                        notes: orderResult.registrationDetails,
                        theme: {
                            color: '#06b6d4'
                        },
                        handler: async function (response) {
                            btnText.textContent = 'Verifying Payment...';
                            try {
                                // Step 4: Verify payment on server
                                const verifyResponse = await fetch('<?= APP_URL ?>/verify_payment.php', {
                                    method: 'POST',
                                    headers: { 'Content-Type': 'application/json', 'X-CSRF-Token': '<?= csrf_token() ?>' },
                                    body: JSON.stringify({
                                        razorpay_payment_id: response.razorpay_payment_id,
                                        razorpay_order_id: response.razorpay_order_id,
                                        razorpay_signature: response.razorpay_signature,
                                        registrationDetails: orderResult.registrationDetails
                                    })
                                });

                                const verifyResult = await verifyResponse.json();

                                if (!verifyResponse.ok) {
                                    throw new Error(verifyResult.error || 'Payment verification failed.');
                                }

                                // Redirect to success confirmation
                                window.location.href = `<?= APP_URL ?>/register.php?success=1&regId=${verifyResult.registrationId}`;
                            } catch (verifyErr) {
                                showError(verifyErr.message);
                            }
                        },
                        modal: {
                            ondismiss: function () {
                                submitBtn.disabled = false;
                                btnText.textContent = 'Complete Registration';
                            }
                        }
                    };

                    const rzp = new Razorpay(options);
                    rzp.on('payment.failed', function (resp) {
                        showError(resp.error.description || 'Payment transaction failed.');
                    });
                    rzp.open();

                } catch (err) {
                    showError(err.message);
                }
            });

            function showError(message) {
                errorContainer.classList.remove('hidden');
                errorMessage.textContent = message;
                submitBtn.disabled = false;
                btnText.textContent = 'Complete Registration';
            }
        });
    </script>
    <?php endif; ?>

    <?php include __DIR__ . '/includes/footer.php'; ?>
    <script>
        lucide.createIcons();
    </script>
</body>
</html>
