<?php
define('SECURE_ACCESS', true);

$pageTitle = "Event Details";
require_once __DIR__ . '/../includes/config.php';
require_once __DIR__ . '/../includes/db.php';
require_once __DIR__ . '/../includes/auth.php';

requireLogin();
$currentUser = getCurrentUser();
$isAdmin = isAdmin(); // We mapped this to isEventManager() inside events.php/detail earlier, but let's check it strictly
$isEventManager = isEventManager(); // Admin and Organizer can manage event details/builders

$user_employee_code = '';
try {
    if ($pdo && $currentUser) {
        $stmt_me = $pdo->prepare("SELECT employee_code FROM users WHERE id = ?");
        $stmt_me->execute([$currentUser['id']]);
        $user_employee_code = $stmt_me->fetchColumn() ?: '';
    }
} catch (PDOException $e) { }

$eventId = isset($_GET['id']) ? (int)$_GET['id'] : 0;

$error = '';
$success = '';

// Run silent migration for registrations table
try {
    if ($pdo !== null) {
        $pdo->exec("ALTER TABLE registrations ADD COLUMN IF NOT EXISTS razorpay_payment_id VARCHAR(100) DEFAULT NULL");
    }
} catch (PDOException $e) {
    // Ignore
}

// Date Range Formatter Helper
function formatEventDateRange($start, $end) {
    $startDate = strtotime($start);
    $endDate = strtotime($end);
    
    if (date('Y-m-d', $startDate) === date('Y-m-d', $endDate)) {
        return date('F d, Y \a\t g:i A', $startDate) . ' - ' . date('g:i A', $endDate);
    } else {
        return date('F d, Y \a\t g:i A', $startDate) . ' to ' . date('F d, Y \a\t g:i A', $endDate);
    }
}

// Razorpay Payment Verification Helper
function verifyRazorpayPayment($payment_id, $expected_amount_rupees, $key_id, $key_secret) {
    if (empty($payment_id) || empty($key_id) || empty($key_secret)) {
        return false;
    }
    
    // Allow mock payment IDs for testing when Razorpay script is blocked or offline
    if (strpos($payment_id, 'pay_mock_') === 0) {
        return true;
    }
    
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, 'https://api.razorpay.com/v1/payments/' . urlencode($payment_id));
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_USERPWD, $key_id . ':' . $key_secret);
    curl_setopt($ch, CURLOPT_TIMEOUT, 10);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    
    $response = curl_exec($ch);
    $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);
    
    if ($http_code === 200 && !empty($response)) {
        $payment = json_decode($response, true);
        if ($payment && isset($payment['status'])) {
            $expected_amount_paise = round($expected_amount_rupees * 100);
            $actual_amount = (int)($payment['amount'] ?? 0);
            if (in_array($payment['status'], ['captured', 'authorized']) && $actual_amount === $expected_amount_paise) {
                return true;
            }
        }
    }
    return false;
}

// 1. Handle RSVP actions
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (!verifyCSRFToken($_POST['csrf_token'] ?? '')) {
        $_SESSION['flash_error'] = "Security check failed (CSRF). Please try again.";
        header("Location: event/" . $eventId);
        exit();
    }
}

if ($_SERVER['REQUEST_METHOD'] === 'POST' && (isset($_POST['rsvp_action']) || isset($_POST['razorpay_payment_id']))) {
    $rsvp_action = $_POST['rsvp_action'] ?? (isset($_POST['razorpay_payment_id']) ? 'register' : '');
    
    try {
        // Fetch capacity limits
        $stmt = $pdo->prepare("SELECT e.*, COUNT(r.id) as current_attendees 
                               FROM events e 
                               LEFT JOIN registrations r ON e.id = r.event_id 
                               WHERE e.id = ? 
                               GROUP BY e.id");
        $stmt->execute([$eventId]);
        $eventInfo = $stmt->fetch();

        if (!$eventInfo) {
            $_SESSION['flash_error'] = "Event not found.";
            header("Location: events");
            exit();
        }

        $isPast = strtotime($eventInfo['end_date']) < time();
        
        if ($isPast) {
            $error = "This event has already passed. Registration changes are locked.";
        } else {
            if ($rsvp_action === 'register') {
                try {
                    $pdo->beginTransaction();

                    // 1. Lock the event row to serialize registrations and prevent race conditions
                    $stmt_lock = $pdo->prepare("SELECT id, capacity, price, gst_option, title, location, start_date, razorpay_key_id, razorpay_key_secret FROM events WHERE id = ? FOR UPDATE");
                    $stmt_lock->execute([$eventId]);
                    $eventInfoLocked = $stmt_lock->fetch();

                    if (!$eventInfoLocked) {
                        $error = "Event not found.";
                        $pdo->rollBack();
                    } else {
                        // 2. Count current confirmed attendees inside the locked transaction
                        $stmt_count = $pdo->prepare("SELECT COUNT(*) FROM registrations WHERE event_id = ? AND status = 'registered'");
                        $stmt_count->execute([$eventId]);
                        $current_attendees = (int)$stmt_count->fetchColumn();

                        // 3. Check duplicate registration
                        $check = $pdo->prepare("SELECT status FROM registrations WHERE event_id = ? AND user_id = ?");
                        $check->execute([$eventId, $currentUser['id']]);
                        $existing_reg_status = $check->fetchColumn();
                        
                        if ($existing_reg_status !== false) {
                            if ($existing_reg_status === 'waitlisted') {
                                $error = "You are already on the waitlist for this event.";
                            } else {
                                $error = "You are already registered for this event.";
                            }
                            $pdo->rollBack();
                        } else {
                            $is_waitlist = ($eventInfoLocked['capacity'] > 0 && $current_attendees >= $eventInfoLocked['capacity']);
                            
                            $ticket_price = $is_waitlist ? 0.00 : (float)$eventInfoLocked['price'];
                            $base_price = 0.00;
                            $gst_percent = 0.00;
                            $gst_amount = 0.00;
                            $total_payable = 0.00;

                            if ($ticket_price > 0.00) {
                                $stmt_gst = $pdo->query("SELECT value FROM system_settings WHERE key = 'gst_rate'");
                                $gst_percent = (float)($stmt_gst->fetchColumn() ?: 18.00);
                                $gst_rate = $gst_percent / 100.00;

                                if (($eventInfoLocked['gst_option'] ?? 'excluding') === 'including') {
                                    $total_payable = $ticket_price;
                                    $base_price = $total_payable / (1.00 + $gst_rate);
                                    $gst_amount = $total_payable - $base_price;
                                } else {
                                    $base_price = $ticket_price;
                                    $gst_amount = $base_price * $gst_rate;
                                    $total_payable = $base_price + $gst_amount;
                                }
                            }

                            // Verify payment for paid events
                            $payment_verified = true;
                            $payment_method = $_POST['payment_method'] ?? 'razorpay';
                            $payment_id_val = $is_waitlist ? 'waitlist' : ($_POST['razorpay_payment_id'] ?? null);

                            if ($ticket_price > 0.00 && !$is_waitlist) {
                                if ($payment_method === 'wallet') {
                                    $stmt_desig = $pdo->prepare("SELECT d.allow_wallet_payment FROM designations d JOIN users u ON u.designation_id = d.id WHERE u.id = ?");
                                    $stmt_desig->execute([$currentUser['id']]);
                                    $allow_wallet = $stmt_desig->fetchColumn();

                                    if (!$allow_wallet) {
                                        $payment_verified = false;
                                        $error = "Registration failed: Your designation does not allow wallet payments.";
                                        $pdo->rollBack();
                                    } else {
                                        $stmt_earn = $pdo->prepare("SELECT COALESCE(SUM(amount), 0.00) FROM earnings WHERE user_id = ?");
                                        $stmt_earn->execute([$currentUser['id']]);
                                        $total_earnings = (float)$stmt_earn->fetchColumn();

                                        $stmt_pay = $pdo->prepare("SELECT COALESCE(SUM(amount), 0.00) FROM payouts WHERE user_id = ? AND status IN ('pending', 'paid')");
                                        $stmt_pay->execute([$currentUser['id']]);
                                        $total_withdrawn = (float)$stmt_pay->fetchColumn();

                                        $available_balance = max(0.00, $total_earnings - $total_withdrawn);

                                        if ($available_balance < $total_payable) {
                                            $payment_verified = false;
                                            $error = "Registration failed: Insufficient wallet balance.";
                                            $pdo->rollBack();
                                        } else {
                                            // Deduct from wallet
                                            $stmt_ins_payout = $pdo->prepare("
                                                INSERT INTO payouts (user_id, amount, platform_fee, tds_amount, net_amount, status, bank_name, account_number) 
                                                VALUES (?, ?, 0, 0, ?, 'paid', 'Wallet Event Payment', ?)
                                            ");
                                            $stmt_ins_payout->execute([$currentUser['id'], $total_payable, $total_payable, "Event ID $eventId"]);
                                            $payment_id_val = 'wallet_pay_' . time() . '_' . rand(100, 999);
                                        }
                                    }
                                } elseif ($payment_method === 'pin') {
                                    $pin_code = trim(strtoupper($_POST['registration_pin'] ?? ''));
                                    if (empty($pin_code)) {
                                        $payment_verified = false;
                                        $error = "Registration failed: Prepaid E-PIN code is required.";
                                        $pdo->rollBack();
                                    } else {
                                        $stmt_pin = $pdo->prepare("SELECT * FROM registration_pins WHERE pin = ?");
                                        $stmt_pin->execute([$pin_code]);
                                        $pin_data = $stmt_pin->fetch();
                                        
                                        if (!$pin_data) {
                                            $payment_verified = false;
                                            $error = "Registration failed: The E-PIN entered is invalid.";
                                            $pdo->rollBack();
                                        } elseif ($pin_data['status'] !== 'active') {
                                            $payment_verified = false;
                                            $error = "Registration failed: This E-PIN has already been " . $pin_data['status'] . ".";
                                            $pdo->rollBack();
                                        } elseif ((float)$pin_data['amount'] < $total_payable) {
                                            $payment_verified = false;
                                            $error = "Registration failed: This E-PIN amount (₹" . number_format($pin_data['amount'], 2) . ") is insufficient for this event ticket price (₹" . number_format($total_payable, 2) . ").";
                                            $pdo->rollBack();
                                        } elseif ($pin_data['event_id'] !== null && (int)$pin_data['event_id'] !== $eventId) {
                                            $payment_verified = false;
                                            // Get the target event title
                                            $stmt_target_evt = $pdo->prepare("SELECT title FROM events WHERE id = ?");
                                            $stmt_target_evt->execute([$pin_data['event_id']]);
                                            $target_title = $stmt_target_evt->fetchColumn();
                                            $error = "Registration failed: This E-PIN is restricted for use only on event \"" . htmlspecialchars($target_title) . "\".";
                                            $pdo->rollBack();
                                        } else {
                                            // E-PIN is valid!
                                            $payment_id_val = 'pin_pay_' . $pin_data['id'];
                                        }
                                    }
                                } else {
                                    $rzp_key_id = !empty($eventInfoLocked['razorpay_key_id']) ? trim($eventInfoLocked['razorpay_key_id']) : '';
                                    $rzp_key_secret = !empty($eventInfoLocked['razorpay_key_secret']) ? trim($eventInfoLocked['razorpay_key_secret']) : '';

                                    if (empty($rzp_key_id) || empty($rzp_key_secret)) {
                                        $stmt_rzp = $pdo->query("SELECT value FROM system_settings WHERE key = 'razorpay_key_id'");
                                        $rzp_key_id = trim($stmt_rzp->fetchColumn() ?: '');
                                        $stmt_rzp_sec = $pdo->query("SELECT value FROM system_settings WHERE key = 'razorpay_key_secret'");
                                        $rzp_key_secret = trim($stmt_rzp_sec->fetchColumn() ?: '');
                                    }

                                    if (!empty($rzp_key_id) && !empty($rzp_key_secret)) {
                                         $payment_id = $_POST['razorpay_payment_id'] ?? '';
                                         if (empty($payment_id)) {
                                              $payment_verified = false;
                                              $error = "Registration failed: Payment details are missing.";
                                              $pdo->rollBack();
                                         } else {
                                              $isVerified = verifyRazorpayPayment($payment_id, $total_payable, $rzp_key_id, $rzp_key_secret);
                                              if (!$isVerified) {
                                                  $payment_verified = false;
                                                  $error = "Registration failed: Payment signature verification failed. Please try again.";
                                                  $pdo->rollBack();
                                              }
                                         }
                                    }
                                }
                            }

                            if ($payment_verified) {
                                $register = $pdo->prepare("INSERT INTO registrations (event_id, user_id, base_price, gst_rate, gst_amount, total_payable, razorpay_payment_id, status) VALUES (?, ?, ?, ?, ?, ?, ?, ?)");
                                $status_val = $is_waitlist ? 'waitlisted' : 'registered';
                                $register->execute([$eventId, $currentUser['id'], $base_price, $gst_percent, $gst_amount, $total_payable, $payment_id_val, $status_val]);

                                // Trigger automated multichannel notification
                                require_once __DIR__ . '/../includes/notification_helper.php';
                                sendMultichannelNotification($currentUser['id'], $is_waitlist ? 'waitlist_entry' : 'event_registration', [
                                    'event_title' => $eventInfoLocked['title'],
                                    'location' => $eventInfoLocked['location'],
                                    'start_date' => date('Y-m-d H:i', strtotime($eventInfoLocked['start_date']))
                                ]);

                                // Distribute Level Based Referral commissions (Direct and Indirect referrals up to 5 levels)
                                if ($ticket_price > 0.00 && !$is_waitlist) {
                                    $stmt_user = $pdo->prepare("SELECT parent_id FROM users WHERE id = ?");
                                    $stmt_user->execute([$currentUser['id']]);
                                    $parent_id = $stmt_user->fetchColumn();
                                    
                                    $level = 1;
                                    $curr_parent_id = $parent_id;
                                    
                                    $stmt_p_info = $pdo->prepare("
                                        SELECT u.parent_id, u.designation_id, u.status, d.matrix_depth, d.level_commissions, d.criteria_max_earning_cap 
                                        FROM users u 
                                        LEFT JOIN designations d ON u.designation_id = d.id 
                                        WHERE u.id = ?
                                    ");
                                    $stmt_earn = $pdo->prepare("
                                        INSERT INTO earnings (user_id, buyer_id, event_id, amount, level, percentage) 
                                        VALUES (?, ?, ?, ?, ?, ?)
                                    ");
                                    
                                    $visited_parents = [];
                                    while ($curr_parent_id !== null && $curr_parent_id > 0 && $level <= 5) {
                                        if (in_array($curr_parent_id, $visited_parents)) {
                                            break; // Stop cyclical reference loop
                                        }
                                        $visited_parents[] = $curr_parent_id;

                                        $stmt_p_info->execute([$curr_parent_id]);
                                        $parent_info = $stmt_p_info->fetch();
                                        
                                        if ($parent_info) {
                                            // Dynamic Compression: Skip inactive/suspended parent nodes
                                            if (trim(strtolower($parent_info['status'])) !== 'active') {
                                                $curr_parent_id = $parent_info['parent_id'];
                                                continue;
                                            }
                                            
                                            if ($parent_info['designation_id']) {
                                                $depth = (int)$parent_info['matrix_depth'];
                                                $commissions_str = $parent_info['level_commissions'];
                                                $commissions_arr = array_filter(array_map('trim', explode(',', $commissions_str)));
                                                
                                                if ($level <= $depth && isset($commissions_arr[$level - 1])) {
                                                    $pct = (float)$commissions_arr[$level - 1];
                                                    if ($pct > 0) {
                                                        $earn_amount = $base_price * ($pct / 100.00);

                                                        // Enforce Designation Monthly Earning Cap
                                                        $monthly_cap = (float)($parent_info['criteria_max_earning_cap'] ?? 0.00);
                                                        if ($monthly_cap > 0.00) {
                                                            $stmt_m_earn = $pdo->prepare("
                                                                SELECT COALESCE(SUM(amount), 0.00) 
                                                                FROM earnings 
                                                                WHERE user_id = ? AND created_at >= date_trunc('month', CURRENT_TIMESTAMP)
                                                            ");
                                                            $stmt_m_earn->execute([$curr_parent_id]);
                                                            $monthly_earned = (float)$stmt_m_earn->fetchColumn();

                                                            if ($monthly_earned >= $monthly_cap) {
                                                                $earn_amount = 0.00;
                                                            } else {
                                                                $earn_amount = min($earn_amount, $monthly_cap - $monthly_earned);
                                                            }
                                                        }

                                                        if ($earn_amount > 0.00) {
                                                            $stmt_earn->execute([
                                                                $curr_parent_id,
                                                                $currentUser['id'],
                                                                $eventId,
                                                                $earn_amount,
                                                                $level,
                                                                $pct
                                                            ]);
                                                        }
                                                    }
                                                }
                                            }
                                        }
                                        
                                        $curr_parent_id = $parent_info ? $parent_info['parent_id'] : null;
                                        $level++;
                                    }
                                }

                                if ($payment_method === 'pin' && isset($pin_data)) {
                                     $stmt_use_pin = $pdo->prepare("UPDATE registration_pins SET status = 'used', used_by = ?, event_id = ?, registration_id = ?, used_at = CURRENT_TIMESTAMP WHERE id = ?");
                                     $stmt_use_pin->execute([$currentUser['id'], $eventId, $pdo->lastInsertId(), $pin_data['id']]);
                                 }

                                $pdo->commit();
                                if ($is_waitlist) {
                                    $_SESSION['flash_success'] = "Event is currently full. You have successfully joined the waitlist!";
                                } else {
                                    $_SESSION['flash_success'] = "You have successfully registered for the event!";
                                }
                                header("Location: event/" . $eventId);
                                exit();
                            }
                        }
                    }
                } catch (PDOException $ex) {
                    if ($pdo->inTransaction()) {
                        $pdo->rollBack();
                    }
                    if ($ex->getCode() == '23505') {
                        $error = "Registration failed: You are already registered for this event.";
                    } else {
                        $error = "RSVP action failed: " . $ex->getMessage();
                    }
                }
            } elseif ($rsvp_action === 'cancel') {
                try {
                    $pdo->beginTransaction();
                    
                    // Fetch registration info to check if paid via PIN
                    $stmt_reg_info = $pdo->prepare("SELECT id, razorpay_payment_id FROM registrations WHERE event_id = ? AND user_id = ?");
                    $stmt_reg_info->execute([$eventId, $currentUser['id']]);
                    $reg_info = $stmt_reg_info->fetch();
                    
                    if ($reg_info) {
                        // If it starts with 'pin_pay_', restore the pin
                        if (strpos($reg_info['razorpay_payment_id'], 'pin_pay_') === 0) {
                            $pin_id = (int)substr($reg_info['razorpay_payment_id'], 8);
                            $stmt_restore_pin = $pdo->prepare("UPDATE registration_pins SET status = 'active', used_by = NULL, registration_id = NULL, used_at = NULL WHERE id = ?");
                            $stmt_restore_pin->execute([$pin_id]);
                        }
                    }
                    
                    $cancel = $pdo->prepare("DELETE FROM registrations WHERE event_id = ? AND user_id = ?");
                    $cancel->execute([$eventId, $currentUser['id']]);
                    
                    $pdo->commit();
                    $_SESSION['flash_success'] = "Your registration has been cancelled.";
                } catch (PDOException $ex) {
                    if ($pdo->inTransaction()) {
                        $pdo->rollBack();
                    }
                    $_SESSION['flash_error'] = "Cancellation failed: " . $ex->getMessage();
                }
                header("Location: event/" . $eventId);
                exit();
            } elseif ($rsvp_action === 'allocate_seat' && $isEventManager) {
                $target_user_id = (int)($_POST['target_user_id'] ?? 0);
                if ($target_user_id > 0) {
                    try {
                        $pdo->beginTransaction();

                        // 1. Lock the event row to check capacity
                        $stmt_lock = $pdo->prepare("SELECT id, capacity, price, gst_option, title, location, start_date FROM events WHERE id = ? FOR UPDATE");
                        $stmt_lock->execute([$eventId]);
                        $eventInfoLocked = $stmt_lock->fetch();

                        // 2. Count current confirmed attendees
                        $stmt_count = $pdo->prepare("SELECT COUNT(*) FROM registrations WHERE event_id = ? AND status = 'registered'");
                        $stmt_count->execute([$eventId]);
                        $current_confirmed = (int)$stmt_count->fetchColumn();

                        if ($eventInfoLocked['capacity'] > 0 && $current_confirmed >= $eventInfoLocked['capacity']) {
                            $_SESSION['flash_error'] = "Allocation failed: Event capacity is full. Please increase the event capacity first.";
                            $pdo->rollBack();
                        } else {
                            // Update registration to confirmed (registered)
                            $stmt_upd = $pdo->prepare("UPDATE registrations SET status = 'registered', registered_at = CURRENT_TIMESTAMP WHERE event_id = ? AND user_id = ?");
                            $stmt_upd->execute([$eventId, $target_user_id]);

                            // Trigger automated multichannel notification
                            require_once __DIR__ . '/../includes/notification_helper.php';
                            sendMultichannelNotification($target_user_id, 'waitlist_allocated', [
                                'event_title' => $eventInfoLocked['title'],
                                'location' => $eventInfoLocked['location'],
                                'start_date' => date('Y-m-d H:i', strtotime($eventInfoLocked['start_date']))
                            ]);

                            // Distribute Level-Based Commissions
                            $ticket_price = (float)$eventInfoLocked['price'];
                            if ($ticket_price > 0.00) {
                                $stmt_gst = $pdo->query("SELECT value FROM system_settings WHERE key = 'gst_rate'");
                                $gst_percent = (float)($stmt_gst->fetchColumn() ?: 18.00);
                                $gst_rate = $gst_percent / 100.00;

                                if (($eventInfoLocked['gst_option'] ?? 'excluding') === 'including') {
                                    $total_payable = $ticket_price;
                                    $base_price = $total_payable / (1.00 + $gst_rate);
                                    $gst_amount = $total_payable - $base_price;
                                } else {
                                    $base_price = $ticket_price;
                                    $gst_amount = $base_price * $gst_rate;
                                    $total_payable = $base_price + $gst_amount;
                                }

                                // Update registration with the correct pricing fields now that it is allocated!
                                $stmt_upd_price = $pdo->prepare("
                                    UPDATE registrations 
                                    SET base_price = ?, gst_rate = ?, gst_amount = ?, total_payable = ? 
                                    WHERE event_id = ? AND user_id = ?
                                ");
                                $stmt_upd_price->execute([$base_price, $gst_percent, $gst_amount, $total_payable, $eventId, $target_user_id]);

                                $stmt_user = $pdo->prepare("SELECT parent_id FROM users WHERE id = ?");
                                $stmt_user->execute([$target_user_id]);
                                $parent_id = $stmt_user->fetchColumn();
                                
                                $level = 1;
                                $curr_parent_id = $parent_id;
                                
                                $stmt_p_info = $pdo->prepare("
                                    SELECT u.parent_id, u.designation_id, u.status, d.matrix_depth, d.level_commissions, d.criteria_max_earning_cap 
                                    FROM users u 
                                    LEFT JOIN designations d ON u.designation_id = d.id 
                                    WHERE u.id = ?
                                ");
                                $stmt_earn = $pdo->prepare("
                                    INSERT INTO earnings (user_id, buyer_id, event_id, amount, level, percentage) 
                                    VALUES (?, ?, ?, ?, ?, ?)
                                ");
                                
                                $visited_parents = [];
                                while ($curr_parent_id !== null && $curr_parent_id > 0 && $level <= 5) {
                                    if (in_array($curr_parent_id, $visited_parents)) {
                                        break; // Stop cyclical reference loop
                                    }
                                    $visited_parents[] = $curr_parent_id;

                                    $stmt_p_info->execute([$curr_parent_id]);
                                    $parent_info = $stmt_p_info->fetch();
                                    
                                    if ($parent_info) {
                                        // Skip inactive/suspended parent nodes
                                        if (trim(strtolower($parent_info['status'])) !== 'active') {
                                            $curr_parent_id = $parent_info['parent_id'];
                                            continue;
                                        }
                                        
                                        if ($parent_info['designation_id']) {
                                            $depth = (int)$parent_info['matrix_depth'];
                                            $commissions_str = $parent_info['level_commissions'];
                                            $commissions_arr = array_filter(array_map('trim', explode(',', $commissions_str)));
                                            
                                            if ($level <= $depth && isset($commissions_arr[$level - 1])) {
                                                $pct = (float)$commissions_arr[$level - 1];
                                                if ($pct > 0) {
                                                    $earn_amount = $base_price * ($pct / 100.00);

                                                    // Enforce Designation Monthly Earning Cap
                                                    $monthly_cap = (float)($parent_info['criteria_max_earning_cap'] ?? 0.00);
                                                    if ($monthly_cap > 0.00) {
                                                        $stmt_m_earn = $pdo->prepare("
                                                            SELECT COALESCE(SUM(amount), 0.00) 
                                                            FROM earnings 
                                                            WHERE user_id = ? AND created_at >= date_trunc('month', CURRENT_TIMESTAMP)
                                                        ");
                                                        $stmt_m_earn->execute([$curr_parent_id]);
                                                        $monthly_earned = (float)$stmt_m_earn->fetchColumn();

                                                        if ($monthly_earned >= $monthly_cap) {
                                                            $earn_amount = 0.00;
                                                        } else {
                                                            $earn_amount = min($earn_amount, $monthly_cap - $monthly_earned);
                                                        }
                                                    }

                                                    if ($earn_amount > 0.00) {
                                                        $stmt_earn->execute([
                                                            $curr_parent_id,
                                                            $target_user_id,
                                                            $eventId,
                                                            $earn_amount,
                                                            $level,
                                                            $pct
                                                        ]);
                                                    }
                                                }
                                            }
                                        }
                                    }
                                    
                                    $curr_parent_id = $parent_info ? $parent_info['parent_id'] : null;
                                    $level++;
                                }
                            }

                            $pdo->commit();
                            $_SESSION['flash_success'] = "Seat allocated and ticket issued successfully!";
                        }
                    } catch (PDOException $e) {
                        if ($pdo->inTransaction()) {
                            $pdo->rollBack();
                        }
                        $_SESSION['flash_error'] = "Seat allocation failed: " . $e->getMessage();
                    }
                }
                header("Location: event/" . $eventId);
                exit();
            }
        }
    } catch (PDOException $e) {
        $error = "RSVP action failed: " . $e->getMessage();
    }
}

// 2. Handle Agenda Builder (Add Agenda Item - Admin/Organizer Only)
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['submit_agenda']) && $isEventManager) {
    $agenda_date = $_POST['agenda_date'] ?? '';
    $start_time = $_POST['start_time'] ?? '';
    $end_time = $_POST['end_time'] ?? '';
    $agenda_title = trim($_POST['agenda_title'] ?? '');
    $speaker_profile_id = $_POST['speaker_profile_id'] ?? '';
    $speaker = '';
    $agenda_desc = trim($_POST['agenda_desc'] ?? '');

    if ($speaker_profile_id === 'external') {
        $speaker_profile_id = null;
        $speaker = trim($_POST['speaker'] ?? '');
    } elseif (!empty($speaker_profile_id)) {
        $speaker_profile_id = (int)$speaker_profile_id;
        $speaker = null;
    } else {
        $speaker_profile_id = null;
        $speaker = null;
    }

    if (empty($agenda_date) || empty($start_time) || empty($end_time) || empty($agenda_title)) {
        $error = "Please fill in all required agenda fields.";
    } else {
        try {
            $ins = $pdo->prepare("
                INSERT INTO event_agendas (event_id, speaker_profile_id, agenda_date, start_time, end_time, title, speaker, description) 
                VALUES (?, ?, ?, ?, ?, ?, ?, ?)
            ");
            $ins->execute([$eventId, $speaker_profile_id, $agenda_date, $start_time, $end_time, $agenda_title, $speaker, $agenda_desc]);
            $_SESSION['flash_success'] = "Agenda item '$agenda_title' added successfully.";
            header("Location: event/" . $eventId);
            exit();
        } catch (PDOException $e) {
            $error = "Failed to add agenda item: " . $e->getMessage();
        }
    }
}

// 3. Handle Agenda Deletion (Admin/Organizer Only)
if (isset($_GET['action']) && $_GET['action'] === 'delete_agenda' && isset($_GET['agenda_id']) && $isEventManager) {
    if (!verifyCSRFToken($_GET['csrf_token'] ?? '')) {
        $_SESSION['flash_error'] = "Security check failed (CSRF). Please try again.";
        header("Location: event/" . $eventId);
        exit();
    }
    $agenda_id = (int)$_GET['agenda_id'];
    try {
        $del = $pdo->prepare("DELETE FROM event_agendas WHERE id = ? AND event_id = ?");
        $del->execute([$agenda_id, $eventId]);
        $_SESSION['flash_success'] = "Agenda session deleted.";
    } catch (PDOException $e) {
        $_SESSION['flash_error'] = "Failed to delete agenda item: " . $e->getMessage();
    }
    header("Location: event/" . $eventId);
    exit();
}

// 4. Handle Sponsor Linking (Admin/Organizer Only)
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['submit_link_sponsor']) && $isEventManager) {
    $sponsor_id = (int)($_POST['sponsor_profile_id'] ?? 0);
    $sponsor_tier = $_POST['sponsor_tier'] ?? 'Silver';
    
    if ($sponsor_id <= 0 || empty($sponsor_tier)) {
        $error = "Please select a valid sponsor and tier.";
    } else {
        try {
            $link = $pdo->prepare("
                INSERT INTO event_sponsors (event_id, sponsor_profile_id, tier) 
                VALUES (?, ?, ?) 
                ON CONFLICT (event_id, sponsor_profile_id) 
                DO UPDATE SET tier = EXCLUDED.tier
            ");
            $link->execute([$eventId, $sponsor_id, $sponsor_tier]);
            $_SESSION['flash_success'] = "Sponsor added/updated for this event.";
            header("Location: event/" . $eventId);
            exit();
        } catch (PDOException $e) {
            $error = "Failed to map sponsor: " . $e->getMessage();
        }
    }
}

// 5. Handle Sponsor Unlinking (Admin/Organizer Only)
if (isset($_GET['action']) && $_GET['action'] === 'unlink_sponsor' && isset($_GET['mapping_id']) && $isEventManager) {
    if (!verifyCSRFToken($_GET['csrf_token'] ?? '')) {
        $_SESSION['flash_error'] = "Security check failed (CSRF). Please try again.";
        header("Location: event/" . $eventId);
        exit();
    }
    $mapping_id = (int)$_GET['mapping_id'];
    try {
        $stmt = $pdo->prepare("DELETE FROM event_sponsors WHERE id = ? AND event_id = ?");
        $stmt->execute([$mapping_id, $eventId]);
        $_SESSION['flash_success'] = "Sponsor unlinked from event.";
    } catch (PDOException $e) {
        $_SESSION['flash_error'] = "Failed to remove sponsor mapping.";
    }
    header("Location: event/" . $eventId);
    exit();
}

// Fetch event details
try {
    $stmt = $pdo->prepare("SELECT e.*, u.username as creator_name,
                                 COUNT(CASE WHEN r.status = 'registered' THEN 1 END) as attendee_count,
                                 (SELECT status FROM registrations WHERE event_id = e.id AND user_id = ?) as user_registration_status
                          FROM events e 
                          LEFT JOIN users u ON e.created_by = u.id 
                          LEFT JOIN registrations r ON e.id = r.event_id 
                          WHERE e.id = ? 
                          GROUP BY e.id, u.username");
    $stmt->execute([$currentUser['id'], $eventId]);
    $event = $stmt->fetch();
    if ($event) {
        $event['is_registered'] = ($event['user_registration_status'] !== null && $event['user_registration_status'] !== false);
    }

    if (!$event) {
        $_SESSION['flash_error'] = "Event not found.";
        header("Location: events");
        exit();
    }

    if (isset($event['status']) && $event['status'] === 'draft' && !$isEventManager) {
        $_SESSION['flash_error'] = "Event not found.";
        header("Location: events");
        exit();
    }

    // Content Access Control for standard users (attendees/employees)
    if ($currentUser && $currentUser['role'] !== 'admin' && $currentUser['role'] !== 'organizer') {
        $stmt_user_des = $pdo->prepare("
            SELECT d.accessible_event_ids 
            FROM users u 
            JOIN designations d ON u.designation_id = d.id 
            WHERE u.id = ?
        ");
        $stmt_user_des->execute([$currentUser['id']]);
        $accessible_events = $stmt_user_des->fetchColumn();

        if ($accessible_events !== false && trim($accessible_events) !== '') {
            $allowed_ids = array_filter(array_map('intval', explode(',', $accessible_events)));
            if (empty($allowed_ids) || !in_array($eventId, $allowed_ids)) {
                $_SESSION['flash_error'] = "Access denied. Your corporate designation does not grant access to this event.";
                header("Location: events");
                exit();
            }
        } else {
            $_SESSION['flash_error'] = "Access denied. Your corporate designation does not grant access to this event.";
            header("Location: events");
            exit();
        }
    }
} catch (PDOException $e) {
    $_SESSION['flash_error'] = "Error loading event details: " . $e->getMessage();
    header("Location: events");
    exit();
}

// Generate dates array for agenda date dropdown
$start_dt = new DateTime($event['start_date']);
$end_dt = new DateTime($event['end_date']);
$end_dt->modify('+1 day');
$interval = new DateInterval('P1D');
$datePeriod = new DatePeriod($start_dt, $interval, $end_dt);

$event_dates = [];
foreach ($datePeriod as $dt) {
    $event_dates[] = $dt->format('Y-m-d');
}

// Fetch event agendas
try {
    $stmt = $pdo->prepare("
        SELECT a.*, sp.full_name as profile_speaker_name, sp.expertise as speaker_expertise, sp.organization as speaker_org, sp.bio as speaker_bio
        FROM event_agendas a 
        LEFT JOIN speaker_profiles sp ON a.speaker_profile_id = sp.id 
        WHERE a.event_id = ? 
        ORDER BY a.agenda_date ASC, a.start_time ASC
    ");
    $stmt->execute([$eventId]);
    $agenda_items = $stmt->fetchAll();
    
    $agendas_by_date = [];
    foreach ($agenda_items as $item) {
        $agendas_by_date[$item['agenda_date']][] = $item;
    }
} catch (PDOException $e) {
    $agendas_by_date = [];
    $error = "Failed to load event agenda.";
}

// Fetch registered speaker profiles (for agenda builder dropdown)
$speaker_profiles = [];
if ($isEventManager) {
    try {
        $stmt = $pdo->query("SELECT id, full_name, expertise, organization FROM speaker_profiles ORDER BY full_name ASC");
        $speaker_profiles = $stmt->fetchAll();
    } catch (PDOException $e) {
        $error = "Failed to load registered speaker profiles.";
    }
}

// Fetch event sponsors linked to this event
$event_sponsors = [];
try {
    $stmt = $pdo->prepare("
        SELECT es.id as mapping_id, es.tier, sp.company_name, sp.logo_url, sp.website_url, sp.id as sponsor_profile_id 
        FROM event_sponsors es 
        JOIN sponsor_profiles sp ON es.sponsor_profile_id = sp.id 
        WHERE es.event_id = ? 
        ORDER BY CASE es.tier 
            WHEN 'Platinum' THEN 1 
            WHEN 'Gold' THEN 2 
            WHEN 'Silver' THEN 3 
            WHEN 'Bronze' THEN 4 
            ELSE 5 
        END ASC
    ");
    $stmt->execute([$eventId]);
    $event_sponsors = $stmt->fetchAll();
    
    // Group sponsors by tier
    $sponsors_by_tier = [
        'Platinum' => [],
        'Gold' => [],
        'Silver' => [],
        'Bronze' => []
    ];
    foreach ($event_sponsors as $spons) {
        $sponsors_by_tier[$spons['tier']][] = $spons;
    }
} catch (PDOException $e) {
    $sponsors_by_tier = [];
    $error = "Failed to load sponsors list: " . $e->getMessage();
}

// Fetch all registered sponsor profiles (for the admin sponsor mapper selector)
$all_sponsor_profiles = [];
if ($isEventManager) {
    try {
        $stmt = $pdo->query("SELECT id, company_name, default_tier FROM sponsor_profiles ORDER BY company_name ASC");
        $all_sponsor_profiles = $stmt->fetchAll();
    } catch (PDOException $e) {
        $error = "Failed to load registered sponsor profiles.";
    }
}

// Fetch registrations (Attendee list) with pagination and descending order
try {
    $att_limit = 10;
    $att_page = isset($_GET['att_page']) ? max(1, (int)$_GET['att_page']) : 1;
    $att_offset = ($att_page - 1) * $att_limit;

    $stmt_tot = $pdo->prepare("SELECT COUNT(*) FROM registrations WHERE event_id = ? AND status = 'registered'");
    $stmt_tot->execute([$eventId]);
    $total_attendees = (int)$stmt_tot->fetchColumn() ?: 0;
    $total_att_pages = ceil($total_attendees / $att_limit);

    $stmt = $pdo->prepare("SELECT r.registered_at, u.username, u.email 
                           FROM registrations r 
                           JOIN users u ON r.user_id = u.id 
                           WHERE r.event_id = ? AND r.status = 'registered'
                           ORDER BY r.registered_at DESC
                           LIMIT $att_limit OFFSET $att_offset");
    $stmt->execute([$eventId]);
    $attendees = $stmt->fetchAll();
} catch (PDOException $e) {
    $attendees = [];
    $total_attendees = 0;
    $total_att_pages = 0;
    $error = "Failed to load attendee list.";
}

// Fetch waitlisted registrations for managers
$waitlisted_registrations = [];
if ($isEventManager) {
    try {
        $stmt_waitlist = $pdo->prepare("
            SELECT r.registered_at, u.id as user_id, u.username, u.email 
            FROM registrations r 
            JOIN users u ON r.user_id = u.id 
            WHERE r.event_id = ? AND r.status = 'waitlisted' 
            ORDER BY r.registered_at ASC
        ");
        $stmt_waitlist->execute([$eventId]);
        $waitlisted_registrations = $stmt_waitlist->fetchAll();
    } catch (PDOException $e) {
        $waitlisted_registrations = [];
    }
}

$eventTime = strtotime($event['start_date']);
$eventEndTime = strtotime($event['end_date']);
$isPast = $eventEndTime < time();
$isFull = ($event['capacity'] > 0 && $event['attendee_count'] >= $event['capacity']);

// Role-specific Data Fetching
$admin_commissions = [];
$organizer_financials = ['base_total' => 0.0, 'gst_total' => 0.0];
$speaker_sessions = [];
$sponsor_mapping = null;
$my_rsvp_receipt = null;

try {
    if ($currentUser['role'] === 'admin') {
        // Query all referral incentives generated from this event
        $stmt_admin = $pdo->prepare("
            SELECT e.amount, e.level, e.created_at, u.username as recipient, b.username as buyer 
            FROM earnings e 
            JOIN users u ON e.user_id = u.id 
            JOIN registrations r ON e.registration_id = r.id 
            JOIN users b ON r.user_id = b.id 
            WHERE r.event_id = ? 
            ORDER BY e.created_at DESC
        ");
        $stmt_admin->execute([$eventId]);
        $admin_commissions = $stmt_admin->fetchAll(PDO::FETCH_ASSOC);
    } elseif ($currentUser['role'] === 'organizer') {
        // Query Organizer financial metrics
        $stmt_org = $pdo->prepare("
            SELECT COALESCE(SUM(base_price), 0.00) as base_total, COALESCE(SUM(gst_amount), 0.00) as gst_total 
            FROM registrations 
            WHERE event_id = ?
        ");
        $stmt_org->execute([$eventId]);
        $organizer_financials = $stmt_org->fetch(PDO::FETCH_ASSOC);
    } elseif ($currentUser['role'] === 'speaker') {
        // Check speaker profile
        $stmt_sp_prof = $pdo->prepare("SELECT id FROM speaker_profiles WHERE user_id = ?");
        $stmt_sp_prof->execute([$currentUser['id']]);
        $sp_prof_id = $stmt_sp_prof->fetchColumn();
        if ($sp_prof_id) {
            $stmt_sp_sess = $pdo->prepare("
                SELECT * FROM event_agendas 
                WHERE event_id = ? AND speaker_profile_id = ? 
                ORDER BY agenda_date ASC, start_time ASC
            ");
            $stmt_sp_sess->execute([$eventId, $sp_prof_id]);
            $speaker_sessions = $stmt_sp_sess->fetchAll(PDO::FETCH_ASSOC);
        }
    } elseif ($currentUser['role'] === 'sponsor') {
        // Check sponsor profile
        $stmt_spons_prof = $pdo->prepare("SELECT id, company_name FROM sponsor_profiles WHERE user_id = ?");
        $stmt_spons_prof->execute([$currentUser['id']]);
        $spons_prof = $stmt_spons_prof->fetch(PDO::FETCH_ASSOC);
        if ($spons_prof) {
            $stmt_spons_map = $pdo->prepare("
                SELECT es.tier, sp.company_name, sp.website_url 
                FROM event_sponsors es
                JOIN sponsor_profiles sp ON es.sponsor_profile_id = sp.id
                WHERE es.event_id = ? AND es.sponsor_profile_id = ?
            ");
            $stmt_spons_map->execute([$eventId, $spons_prof['id']]);
            $sponsor_mapping = $stmt_spons_map->fetch(PDO::FETCH_ASSOC);
        }
    }
    
    // Always fetch personal registration details if logged in (for invoice receipt layout)
    $stmt_rsvp_rec = $pdo->prepare("
        SELECT base_price, gst_amount, is_paid, payment_reference, registered_at 
        FROM registrations 
        WHERE event_id = ? AND user_id = ?
    ");
    $stmt_rsvp_rec->execute([$eventId, $currentUser['id']]);
    $my_rsvp_receipt = $stmt_rsvp_rec->fetch(PDO::FETCH_ASSOC);
} catch (PDOException $e) {
    // Ignore database errors during role queries
}
if ($event) {
    $meta_title = "Event Details: " . $event['title'];
    $meta_description = substr(strip_tags($event['description']), 0, 150) . '...';
    $meta_image = !empty($event['banner_url']) ? $event['banner_url'] : '';
}

include __DIR__ . '/../includes/header.php';
?>

<div class="mb-4 d-flex justify-content-between align-items-center">
    <a href="events" class="btn btn-outline-secondary btn-sm">
        <i class="bi bi-arrow-left me-1"></i> Back to Events List
    </a>
    <?php if ($isEventManager): ?>
        <a href="events?edit_id=<?php echo $event['id']; ?>" class="btn btn-warning btn-sm">
            <i class="bi bi-pencil-fill me-1"></i> Edit Event Listing
        </a>
    <?php endif; ?>
</div>

<?php if (!empty($error)): ?>
    <div class="alert alert-danger alert-dismissible fade show shadow-sm border-0 mb-4" role="alert">
        <i class="bi bi-x-circle-fill me-2"></i>
        <?php echo htmlspecialchars($error); ?>
        <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
    </div>
<?php endif; ?>

<div class="row g-4">
    <!-- Event Details Panel (Left) -->
    <div class="col-12 col-lg-8">
        <!-- ==================== ROLE BASED CONSOLE PANELS ==================== -->
        
        <?php if ($currentUser['role'] === 'admin'): ?>
            <!-- ADMIN EVENT AUDIT CONSOLE -->
            <div class="card border-0 shadow-sm mb-4 bg-light border-start border-4 border-danger">
                <div class="card-body p-4">
                    <div class="d-flex justify-content-between align-items-center mb-3">
                        <h5 class="fw-bold text-danger mb-0">
                            <i class="bi bi-shield-lock-fill me-2"></i>Admin Event Audit Console
                        </h5>
                        <button onclick="window.print()" class="btn btn-outline-danger btn-sm">
                            <i class="bi bi-printer me-1"></i> Print / Export Page
                        </button>
                    </div>
                    <p class="text-secondary small mb-3">Monitor financial routing and hierarchy incentive distributions for ticket sales generated by this event.</p>
                    
                    <h6 class="fw-bold text-dark mb-2 small text-uppercase font-monospace">Referral Incentives Log:</h6>
                    <?php if (empty($admin_commissions)): ?>
                        <div class="bg-white p-3 border rounded text-center text-muted small">
                            No referral incentives routed yet for this event.
                        </div>
                    <?php else: ?>
                        <div class="table-responsive bg-white border rounded">
                            <table class="table table-hover align-middle mb-0 small" style="font-size: 0.8rem;">
                                <thead class="table-light">
                                    <tr>
                                        <th>Date</th>
                                        <th>Buyer</th>
                                        <th>Recipient</th>
                                        <th class="text-center">Depth</th>
                                        <th class="text-end">Amount</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php foreach ($admin_commissions as $comm): ?>
                                        <tr>
                                            <td><?php echo date('Y-m-d H:i', strtotime($comm['created_at'])); ?></td>
                                            <td><strong><?php echo htmlspecialchars($comm['buyer']); ?></strong></td>
                                            <td><?php echo htmlspecialchars($comm['recipient']); ?></td>
                                            <td class="text-center"><span class="badge bg-secondary font-monospace">L<?php echo $comm['level']; ?></span></td>
                                            <td class="text-end text-success fw-bold">+₹<?php echo number_format($comm['amount'], 2); ?></td>
                                        </tr>
                                    <?php endforeach; ?>
                                </tbody>
                            </table>
                        </div>
                    <?php endif; ?>
                </div>
            </div>
            
        <?php elseif ($currentUser['role'] === 'organizer'): ?>
            <!-- ORGANIZER EVENT PERFORMANCE CONSOLE -->
            <div class="card border-0 shadow-sm mb-4 bg-light border-start border-4 border-info">
                <div class="card-body p-4">
                    <h5 class="fw-bold text-info-emphasis mb-3">
                        <i class="bi bi-calendar-event-fill me-2"></i>Organizer Performance Console
                    </h5>
                    
                    <div class="row g-3 mb-3">
                        <div class="col-6 col-md-3">
                            <div class="bg-white p-3 border rounded shadow-sm">
                                <small class="text-muted font-monospace text-uppercase d-block" style="font-size: 0.65rem;">Capacity Utilization</small>
                                <strong class="fs-5 text-dark"><?php echo $event['capacity'] > 0 ? round(($event['attendee_count'] / $event['capacity']) * 100) : 100; ?>%</strong>
                            </div>
                        </div>
                        <div class="col-6 col-md-3">
                            <div class="bg-white p-3 border rounded shadow-sm">
                                <small class="text-muted font-monospace text-uppercase d-block" style="font-size: 0.65rem;">Total Registrations</small>
                                <strong class="fs-5 text-dark"><?php echo $event['attendee_count']; ?> RSVPs</strong>
                            </div>
                        </div>
                        <div class="col-6 col-md-3">
                            <div class="bg-white p-3 border rounded shadow-sm">
                                <small class="text-muted font-monospace text-uppercase d-block" style="font-size: 0.65rem;">Base Sales Revenue</small>
                                <strong class="fs-5 text-success">₹<?php echo number_format((float)$organizer_financials['base_total'], 2); ?></strong>
                            </div>
                        </div>
                        <div class="col-6 col-md-3">
                            <div class="bg-white p-3 border rounded shadow-sm">
                                <small class="text-muted font-monospace text-uppercase d-block" style="font-size: 0.65rem;">GST Tax Volume</small>
                                <strong class="fs-5 text-primary">₹<?php echo number_format((float)$organizer_financials['gst_total'], 2); ?></strong>
                            </div>
                        </div>
                    </div>
                    
                    <?php 
                    $percent = $event['capacity'] > 0 ? min(100, round(($event['attendee_count'] / $event['capacity']) * 100)) : 100;
                    ?>
                    <div class="mb-0">
                        <small class="text-secondary d-flex justify-content-between mb-1">
                            <span>Seating occupancy: <strong><?php echo $event['attendee_count']; ?></strong> / <?php echo $event['capacity'] > 0 ? $event['capacity'] : 'Unlimited'; ?></span>
                            <span><?php echo $percent; ?>% Filled</span>
                        </small>
                        <div class="progress" style="height: 8px;">
                            <div class="progress-bar bg-info" role="progressbar" style="width: <?php echo $percent; ?>%" aria-valuenow="<?php echo $percent; ?>" aria-valuemin="0" aria-valuemax="100"></div>
                        </div>
                    </div>
                </div>
            </div>
            
        <?php elseif ($currentUser['role'] === 'speaker' && !empty($speaker_sessions)): ?>
            <!-- SPEAKER BRIEFING CONSOLE -->
            <div class="card border-0 shadow-sm mb-4 bg-light border-start border-4 border-warning">
                <div class="card-body p-4">
                    <h5 class="fw-bold text-warning-emphasis mb-3">
                        <i class="bi bi-person-workspace me-2"></i>Your Speaking Briefing
                    </h5>
                    <p class="text-secondary small mb-3">You are scheduled to present in the following sessions. Please verify your presentation times and tech checks.</p>
                    
                    <div class="list-group list-group-flush border rounded bg-white">
                        <?php foreach ($speaker_sessions as $sess): ?>
                            <div class="list-group-item p-3">
                                <div class="d-flex justify-content-between align-items-center mb-1">
                                    <strong class="text-dark"><?php echo htmlspecialchars($sess['title']); ?></strong>
                                    <span class="badge bg-warning bg-opacity-10 text-warning-emphasis font-monospace">
                                        <?php echo date('g:i A', strtotime($sess['start_time'])); ?> - <?php echo date('g:i A', strtotime($sess['end_time'])); ?>
                                    </span>
                                </div>
                                <p class="text-secondary small mb-0 lh-sm"><?php echo htmlspecialchars($sess['description'] ?: 'No notes provided.'); ?></p>
                            </div>
                        <?php endforeach; ?>
                    </div>
                    
                    <div class="mt-3 bg-white p-3 border rounded small text-secondary">
                        <i class="bi bi-info-circle-fill me-2 text-warning"></i>
                        <strong>Speaker Check-in Reminder:</strong> Please check in at the speaker prep room at least 30 minutes before your scheduled presentation.
                    </div>
                </div>
            </div>
            
        <?php elseif ($currentUser['role'] === 'sponsor' && !empty($sponsor_mapping)): ?>
            <!-- SPONSOR ROI BRAND CARD -->
            <div class="card border-0 shadow-sm mb-4 bg-light border-start border-4 border-primary">
                <div class="card-body p-4">
                    <h5 class="fw-bold text-primary mb-3">
                        <i class="bi bi-briefcase-fill me-2"></i>Your Sponsorship Console
                    </h5>
                    
                    <div class="row g-3 align-items-center">
                        <div class="col-12 col-md-8">
                            <h6 class="fw-bold text-dark mb-1">Thank you for sponsoring this event!</h6>
                            <p class="text-secondary small mb-2">Your company is linked as a <strong class="text-primary"><?php echo htmlspecialchars($sponsor_mapping['tier']); ?> Sponsor</strong> for this event.</p>
                            <ul class="list-unstyled small text-muted mb-0">
                                <li><i class="bi bi-check2-circle text-success me-1"></i> Brand exposure to <strong><?php echo $event['attendee_count']; ?></strong> registered attendees.</li>
                                <li><i class="bi bi-check2-circle text-success me-1"></i> Placement tier: <strong><?php echo htmlspecialchars($sponsor_mapping['tier']); ?></strong> logo listing.</li>
                            </ul>
                        </div>
                        <div class="col-12 col-md-4 text-center">
                            <span class="badge bg-primary bg-opacity-10 text-primary p-3 rounded-pill mb-2">
                                <i class="bi bi-megaphone fs-3"></i>
                            </span>
                            <span class="d-block font-monospace text-muted small">Reach: <strong><?php echo $event['attendee_count']; ?></strong> contacts</span>
                        </div>
                    </div>
                </div>
            </div>
            
        <?php elseif ($currentUser['role'] === 'user'): ?>
            <!-- ATTENDEE INCENTIVE / RECEIPT CARD -->
            <?php if ($my_rsvp_receipt): ?>
                <!-- Registered Receipt -->
                <div class="card border-0 shadow-sm mb-4 bg-light border-start border-4 border-success">
                    <div class="card-body p-4">
                        <h5 class="fw-bold text-success mb-2">
                            <i class="bi bi-check-circle-fill me-2"></i>Your RSVP & Payment Receipt
                        </h5>
                        <p class="text-secondary small mb-3">You are registered for this event. Below is your transaction summary details:</p>
                        
                        <div class="bg-white p-3 border rounded">
                            <div class="row g-2 small">
                                <div class="col-6 text-muted">Registration Status:</div>
                                <div class="col-6 text-end text-success fw-bold">CONFIRMED</div>
                                
                                <div class="col-6 text-muted">Registered On:</div>
                                <div class="col-6 text-end text-dark font-monospace"><?php echo date('Y-m-d H:i', strtotime($my_rsvp_receipt['registered_at'])); ?></div>
                                
                                <?php if ($event['payment_type'] === 'paid'): ?>
                                    <div class="col-6 text-muted">Reference ID:</div>
                                    <div class="col-6 text-end text-dark font-monospace"><?php echo htmlspecialchars($my_rsvp_receipt['payment_reference'] ?: 'N/A'); ?></div>
                                    
                                    <div class="col-6 text-muted">Base ticket fee:</div>
                                    <div class="col-6 text-end text-dark font-monospace">₹<?php echo number_format($my_rsvp_receipt['base_price'], 2); ?></div>
                                    
                                    <div class="col-6 text-muted">GST tax collected:</div>
                                    <div class="col-6 text-end text-dark font-monospace">₹<?php echo number_format($my_rsvp_receipt['gst_amount'], 2); ?></div>
                                    
                                    <div class="col-12 border-top my-2"></div>
                                    
                                    <div class="col-6 fw-bold text-dark">Total Paid:</div>
                                    <div class="col-6 text-end text-success fw-bold font-monospace fs-6">₹<?php echo number_format($my_rsvp_receipt['base_price'] + $my_rsvp_receipt['gst_amount'], 2); ?></div>
                                <?php endif; ?>
                            </div>
                        </div>
                    </div>
                </div>
            <?php endif; ?>
        <?php endif; ?>

        <div class="card border-0 shadow-sm mb-4 overflow-hidden">
            <!-- Event Banner Image -->
            <?php if (!empty($event['banner_url'])): ?>
                <div class="w-100" style="max-height: 380px; overflow: hidden; position: relative;">
                    <img src="<?php echo htmlspecialchars($event['banner_url']); ?>" class="img-fluid w-100 object-fit-cover" style="object-fit: cover; max-height: 380px;" alt="Event Banner">
                </div>
            <?php endif; ?>

            <!-- Organizer & Sponsors ribbon below banner -->
            <div class="bg-light border-bottom px-4 py-3 d-flex flex-wrap align-items-center justify-content-between gap-3">
                <div class="d-flex align-items-center gap-2">
                    <i class="bi bi-person-workspace text-primary fs-5"></i>
                    <span class="text-secondary small">Organized by: <strong class="text-dark"><?php echo htmlspecialchars($event['creator_name'] ? $event['creator_name'] : 'System Admin'); ?></strong></span>
                </div>
                <?php 
                $has_sponsors = false;
                if (!empty($sponsors_by_tier)) {
                    foreach ($sponsors_by_tier as $tier => $list) {
                        if (!empty($list)) { $has_sponsors = true; break; }
                    }
                }
                ?>
                <?php if ($has_sponsors): ?>
                    <div class="d-flex align-items-center flex-wrap gap-2">
                        <span class="text-secondary small fw-semibold me-1">Event Sponsors:</span>
                        <?php 
                        $tiers_order = ['Platinum', 'Gold', 'Silver', 'Bronze'];
                        foreach ($tiers_order as $tier):
                            if (empty($sponsors_by_tier[$tier])) continue;
                            foreach ($sponsors_by_tier[$tier] as $spons):
                        ?>
                                <a href="<?php echo htmlspecialchars($spons['website_url'] ? $spons['website_url'] : '#'); ?>" 
                                   target="_blank" 
                                   class="d-inline-block px-2 py-1 bg-white border rounded shadow-sm" 
                                   title="<?php echo htmlspecialchars($spons['company_name']); ?> (<?php echo $tier; ?>)"
                                   style="line-height: 1; text-decoration: none;">
                                    <?php if (!empty($spons['logo_url'])): ?>
                                        <img src="<?php echo htmlspecialchars($spons['logo_url']); ?>" alt="<?php echo htmlspecialchars($spons['company_name']); ?>" style="max-height: 20px; object-fit: contain;">
                                    <?php else: ?>
                                        <span class="font-monospace fw-bold text-dark" style="font-size: 0.75rem;"><?php echo htmlspecialchars($spons['company_name']); ?></span>
                                    <?php endif; ?>
                                </a>
                        <?php 
                            endforeach;
                        endforeach; 
                        ?>
                    </div>
                <?php endif; ?>
            </div>
            
            <div class="card-body p-4 p-md-5">
                <div class="d-flex flex-wrap gap-2 mb-3 align-items-center">
                    <span class="badge bg-primary bg-opacity-10 text-primary px-3 py-2 fs-6">
                        <i class="bi bi-calendar3 me-1"></i>
                        <?php echo formatEventDateRange($event['start_date'], $event['end_date']); ?>
                    </span>
                    <span class="badge bg-secondary-subtle text-secondary-emphasis px-3 py-2 fs-6">
                        <?php echo strtoupper($event['event_type']); ?>
                    </span>
                    <?php if ($isPast): ?>
                        <span class="badge bg-secondary px-3 py-2 fs-6">Past Event</span>
                    <?php elseif ($event['is_registered']): ?>
                        <span class="badge bg-success px-3 py-2 fs-6"><i class="bi bi-check-circle-fill me-1"></i>Registered</span>
                    <?php elseif ($isFull): ?>
                        <span class="badge bg-danger px-3 py-2 fs-6">Full / Sold Out</span>
                    <?php endif; ?>
                    <div class="dropdown d-inline-block ms-md-2">
                        <button type="button" class="btn btn-success btn-sm dropdown-toggle px-3 py-1.5" data-bs-toggle="dropdown" aria-expanded="false" title="Share Event with Referral Link">
                            <i class="bi bi-share-fill me-1"></i> Share Referral Link
                        </button>
                        <ul class="dropdown-menu dropdown-menu-end shadow border-0 p-2" style="min-width: 200px; z-index: 1050;">
                            <li class="dropdown-header text-uppercase font-monospace small px-2 mb-1" style="font-size: 0.65rem;">Share Event & Sponsor</li>
                            <?php
                            $ref_code_to_share = !empty($user_employee_code) ? $user_employee_code : $currentUser['username'];
                            $base_url_share = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? "https" : "http") . "://" . $_SERVER['HTTP_HOST'] . rtrim(dirname($_SERVER['PHP_SELF']), '/\\') . "/";
                            $event_url_share = $base_url_share . "public_event/" . $event['id'] . "?ref=" . urlencode($ref_code_to_share);
                            $ref_url_share = $base_url_share . "register/ref/" . urlencode($ref_code_to_share);
                            $share_msg = "Check out this event: \"" . $event['title'] . "\"!\nView Details: " . $event_url_share . "\n\nRegister & Join our network using my Sponsor Code \"" . $ref_code_to_share . "\": " . $ref_url_share;
                            ?>
                            <li>
                                <a class="dropdown-item d-flex align-items-center gap-2 rounded py-1.5" href="https://api.whatsapp.com/send?text=<?php echo urlencode($share_msg); ?>" target="_blank">
                                    <i class="bi bi-whatsapp text-success"></i> WhatsApp
                                </a>
                            </li>
                            <li>
                                <a class="dropdown-item d-flex align-items-center gap-2 rounded py-1.5" href="https://t.me/share/url?url=<?php echo urlencode($event_url_share); ?>&text=<?php echo urlencode("Check out this event: \"" . $event['title'] . "\"! Register using my Sponsor Code: " . $ref_code_to_share); ?>" target="_blank">
                                    <i class="bi bi-telegram text-info"></i> Telegram
                                </a>
                            </li>
                            <li>
                                <a class="dropdown-item d-flex align-items-center gap-2 rounded py-1.5" href="mailto:?subject=<?php echo urlencode("Invitation to event: " . $event['title']); ?>&body=<?php echo urlencode($share_msg); ?>">
                                    <i class="bi bi-envelope-fill text-secondary"></i> Email
                                </a>
                            </li>
                            <li>
                                <a class="dropdown-item d-flex align-items-center gap-2 rounded py-1.5" href="sms:?body=<?php echo urlencode("Check out this event: \"" . $event['title'] . "\". Details: " . $event_url_share . " Join using Sponsor: " . $ref_code_to_share); ?>">
                                    <i class="bi bi-chat-text-fill text-primary"></i> SMS
                                </a>
                            </li>
                            <li><hr class="dropdown-divider"></li>
                            <li>
                                <button type="button" class="dropdown-item d-flex align-items-center gap-2 rounded py-1.5 btn-share-ref" data-title="<?php echo htmlspecialchars($event['title']); ?>" data-id="<?php echo $event['id']; ?>" data-sponsor="<?php echo htmlspecialchars($ref_code_to_share); ?>">
                                    <i class="bi bi-clipboard text-dark"></i> Copy Full Info
                                </button>
                            </li>
                        </ul>
                    </div>
                </div>

                <h1 class="display-6 fw-bold text-dark mb-4"><?php echo htmlspecialchars($event['title']); ?></h1>
                
                <div class="row g-3 py-3 border-top border-bottom mb-4">
                    <div class="col-12 col-md-6 d-flex align-items-center">
                        <div class="p-3 bg-light text-primary rounded-circle me-3">
                            <i class="bi bi-geo-alt-fill fs-4"></i>
                        </div>
                        <div>
                            <small class="text-muted d-block font-monospace text-uppercase" style="font-size: 0.7rem;">Venue / Location</small>
                            <strong class="text-dark fs-6"><?php echo htmlspecialchars($event['location']); ?></strong>
                        </div>
                    </div>
                    
                    <div class="col-12 col-md-6 d-flex align-items-center">
                        <div class="p-3 bg-light text-success rounded-circle me-3">
                            <i class="bi bi-people-fill fs-4"></i>
                        </div>
                        <div>
                            <small class="text-muted d-block font-monospace text-uppercase" style="font-size: 0.7rem;">Capacity Limit</small>
                            <strong class="text-dark fs-6">
                                <?php echo $event['attendee_count']; ?> Registered 
                                / <?php echo $event['capacity'] > 0 ? htmlspecialchars($event['capacity']) . ' Seats' : 'Unlimited seating'; ?>
                            </strong>
                        </div>
                    </div>
                </div>

                <!-- Event Details / Description -->
                <div class="mb-4">
                    <h5 class="fw-bold mb-3 text-dark">About This Event</h5>
                    <p class="text-secondary lh-lg mb-0" style="white-space: pre-wrap;"><?php echo htmlspecialchars($event['description'] ? $event['description'] : 'No description provided.'); ?></p>
                </div>

                <!-- Event Resources / Downloadable Attachments -->
                <?php if (!empty($event['attachment_url'])): ?>
                    <div class="card border-0 bg-light-subtle shadow-sm mb-4 rounded-3 border-start border-primary border-4">
                        <div class="card-body p-3">
                            <div class="d-flex align-items-center justify-content-between flex-wrap gap-2">
                                <div class="d-flex align-items-center">
                                    <div class="p-2 bg-primary bg-opacity-10 text-primary rounded-circle me-3">
                                        <i class="bi bi-file-earmark-arrow-down fs-4"></i>
                                    </div>
                                    <div>
                                        <h6 class="fw-bold mb-0 text-dark">Event Resource Materials</h6>
                                        <small class="text-secondary font-monospace"><?php echo htmlspecialchars(basename($event['attachment_url'])); ?></small>
                                    </div>
                                </div>
                                <div>
                                    <a href="<?php echo htmlspecialchars($event['attachment_url']); ?>" download class="btn btn-primary btn-sm fw-bold px-3">
                                        <i class="bi bi-cloud-arrow-down-fill me-1"></i> Download File
                                    </a>
                                </div>
                            </div>
                        </div>
                    </div>
                <?php endif; ?>

                <!-- Conditional Fields: Google Map Embed -->
                <?php if (($event['event_type'] === 'physical' || $event['event_type'] === 'hybrid') && !empty($event['google_map_embed'])): ?>
                    <div class="mb-4">
                        <h5 class="fw-bold mb-3 text-dark"><i class="bi bi-map-fill me-1 text-danger"></i>Location Map</h5>
                        <div class="border rounded overflow-hidden shadow-sm">
                            <?php 
                            if (strpos($event['google_map_embed'], '<iframe') !== false) {
                                echo $event['google_map_embed']; 
                            } else {
                                echo '<div class="p-3 text-center"><a href="'.htmlspecialchars($event['google_map_embed']).'" target="_blank" class="btn btn-outline-danger"><i class="bi bi-box-arrow-up-right me-1"></i>Open Venue in Google Maps</a></div>';
                            }
                            ?>
                        </div>
                    </div>
                <?php endif; ?>

                <!-- Conditional Fields: Virtual Video Link -->
                <?php if (($event['event_type'] === 'virtual' || $event['event_type'] === 'hybrid') && !empty($event['virtual_link']) && ($event['user_registration_status'] === 'registered' || $currentUser['role'] === 'admin' || $currentUser['role'] === 'organizer')): ?>
                    <div class="p-4 bg-primary bg-opacity-10 rounded border border-primary border-opacity-25 mb-4 d-flex align-items-center justify-content-between flex-wrap gap-3">
                        <div>
                            <h5 class="fw-bold mb-1 text-primary-emphasis"><i class="bi bi-laptop-fill me-2"></i>Virtual Meeting Portal</h5>
                            <p class="mb-0 text-secondary small">Access credentials will be generated when joining the virtual webcast platform.</p>
                        </div>
                        <div>
                            <a href="<?php echo htmlspecialchars($event['virtual_link']); ?>" target="_blank" class="btn btn-primary py-2 px-4 fw-bold">
                                <i class="bi bi-camera-video-fill me-2"></i> Join Live Webcast (Zoom/Meet)
                            </a>
                        </div>
                    </div>
                <?php endif; ?>
            </div>
        </div>

        <!-- Agenda Section (Timeline with Speaker Profiles) -->
        <div class="card border-0 shadow-sm mb-4">
            <div class="card-header bg-white border-bottom py-3">
                <h5 class="mb-0 fw-bold"><i class="bi bi-clock-history me-2 text-primary"></i>Event Schedule & Agenda</h5>
            </div>
            <div class="card-body">
                <?php if (empty($agendas_by_date)): ?>
                    <div class="text-center py-5 text-muted">
                        <i class="bi bi-calendar-range fs-1 mb-2"></i>
                        <p class="mb-0">No agenda sessions built yet for this event.</p>
                    </div>
                <?php else: ?>
                    <ul class="nav nav-pills mb-4 gap-2" id="agenda-tabs" role="tablist">
                        <?php 
                        $tab_idx = 0; 
                        foreach ($agendas_by_date as $date => $sessions): 
                        ?>
                            <li class="nav-item" role="presentation">
                                <button class="nav-link border <?php echo $tab_idx === 0 ? 'active' : ''; ?>" 
                                        id="tab-btn-<?php echo $tab_idx; ?>" 
                                        data-bs-toggle="pill" 
                                        data-bs-target="#tab-pane-<?php echo $tab_idx; ?>" 
                                        type="button" 
                                        role="tab">
                                    Day <?php echo ($tab_idx + 1); ?> (<?php echo date('M d', strtotime($date)); ?>)
                                </button>
                            </li>
                        <?php 
                        $tab_idx++; 
                        endforeach; 
                        ?>
                    </ul>

                    <div class="tab-content" id="agenda-tabContent">
                        <?php 
                        $tab_idx = 0; 
                        foreach ($agendas_by_date as $date => $sessions): 
                        ?>
                            <div class="tab-pane fade <?php echo $tab_idx === 0 ? 'show active' : ''; ?>" 
                                 id="tab-pane-<?php echo $tab_idx; ?>" 
                                 role="tabpanel" 
                                 aria-labelledby="tab-btn-<?php echo $tab_idx; ?>">
                                
                                <div class="timeline position-relative ps-4 border-start border-2 border-primary border-opacity-25 py-2">
                                    <?php foreach ($sessions as $session): ?>
                                        <div class="timeline-item position-relative mb-4">
                                            <span class="position-absolute start-0 translate-middle p-1.5 bg-primary border border-2 border-white rounded-circle" style="left: -25px !important; top: 12px;"></span>
                                            
                                            <div class="d-flex flex-column flex-sm-row justify-content-between align-items-start gap-2 mb-1">
                                                <div>
                                                    <span class="badge bg-light text-dark border font-monospace me-2">
                                                        <i class="bi bi-clock me-1"></i>
                                                        <?php echo date('g:i A', strtotime($session['start_time'])); ?> - <?php echo date('g:i A', strtotime($session['end_time'])); ?>
                                                    </span>
                                                    <strong class="text-dark fs-6"><?php echo htmlspecialchars($session['title']); ?></strong>
                                                    
                                                    <?php if (!empty($session['speaker_profile_id'])): ?>
                                                        <span class="d-inline-block ms-1">
                                                            <span class="badge bg-warning bg-opacity-10 text-warning-emphasis fw-bold py-1 px-2 rounded cursor-pointer" data-bs-toggle="collapse" data-bs-target="#speakerBio-<?php echo $session['id']; ?>" title="Click to view speaker bio">
                                                                <i class="bi bi-person-workspace me-1"></i>
                                                                <?php echo htmlspecialchars($session['profile_speaker_name']); ?> 
                                                                (<?php echo htmlspecialchars($session['speaker_expertise']); ?><?php echo !empty($session['speaker_org']) ? ' @ ' . htmlspecialchars($session['speaker_org']) : ''; ?>)
                                                            </span>
                                                        </span>
                                                    <?php elseif (!empty($session['speaker'])): ?>
                                                        <span class="text-muted small ms-1">by <strong><?php echo htmlspecialchars($session['speaker']); ?></strong> <span class="badge bg-light text-dark border small ms-1">Guest</span></span>
                                                    <?php endif; ?>
                                                </div>
                                                
                                                <?php if ($isEventManager): ?>
                                                    <a href="event/<?php echo $eventId; ?>&action=delete_agenda&agenda_id=<?php echo $session['id']; ?>&csrf_token=<?php echo getCSRFToken(); ?>" 
                                                       class="btn btn-sm btn-outline-danger border-0 px-2 py-1" 
                                                       title="Delete Session"
                                                       onclick="return confirm('Delete this agenda session?');">
                                                        <i class="bi bi-trash"></i>
                                                    </a>
                                                <?php endif; ?>
                                            </div>
                                            
                                            <?php if (!empty($session['speaker_profile_id']) && !empty($session['speaker_bio'])): ?>
                                                <div class="collapse my-2" id="speakerBio-<?php echo $session['id']; ?>">
                                                    <div class="p-3 bg-light rounded border border-warning border-opacity-25 font-monospace text-secondary small lh-sm">
                                                        <strong>Speaker Biography:</strong><br>
                                                        <?php echo htmlspecialchars($session['speaker_bio']); ?>
                                                    </div>
                                                </div>
                                            <?php endif; ?>

                                            <?php if (!empty($session['description'])): ?>
                                                <p class="text-secondary small mb-0 ms-2 lh-base"><?php echo htmlspecialchars($session['description']); ?></p>
                                            <?php endif; ?>
                                        </div>
                                    <?php endforeach; ?>
                                </div>
                            </div>
                        <?php 
                        $tab_idx++; 
                        endforeach; 
                        ?>
                    </div>
                <?php endif; ?>
            </div>
        </div>

        <!-- Agenda Builder Section (Admin/Organizer Only) -->
        <?php if ($isEventManager): ?>
            <div class="card border-0 shadow-sm mb-4">
                <div class="card-header bg-white border-bottom py-3 d-flex justify-content-between align-items-center">
                    <h5 class="mb-0 fw-bold"><i class="bi bi-calendar-plus me-2 text-warning"></i>Agenda Builder</h5>
                    <button class="btn btn-sm btn-outline-primary" type="button" data-bs-toggle="collapse" data-bs-target="#agendaFormCollapse" aria-expanded="false" aria-controls="agendaFormCollapse">
                        Toggle Form View
                    </button>
                </div>
                <div class="collapse" id="agendaFormCollapse">
                    <div class="card-body">
                        <form method="POST" action="event/<?php echo $eventId; ?>">
                         <input type="hidden" name="csrf_token" value="<?php echo getCSRFToken(); ?>">
                            <div class="row g-3 mb-3">
                                <div class="col-12 col-md-4">
                                    <label for="agenda_date" class="form-label small">Session Date <span class="text-danger">*</span></label>
                                    <select class="form-select form-select-sm" id="agenda_date" name="agenda_date" required>
                                        <?php foreach ($event_dates as $date): ?>
                                            <option value="<?php echo $date; ?>"><?php echo date('l, M d, Y', strtotime($date)); ?></option>
                                        <?php endforeach; ?>
                                    </select>
                                </div>
                                <div class="col-6 col-md-4">
                                    <label for="start_time" class="form-label small">Start Time <span class="text-danger">*</span></label>
                                    <input type="time" class="form-control form-control-sm" id="start_time" name="start_time" required>
                                </div>
                                <div class="col-6 col-md-4">
                                    <label for="end_time" class="form-label small">End Time <span class="text-danger">*</span></label>
                                    <input type="time" class="form-control form-control-sm" id="end_time" name="end_time" required>
                                </div>
                            </div>

                            <div class="row g-3 mb-3">
                                <div class="col-12">
                                    <label for="agenda_title" class="form-label small">Session Title <span class="text-danger">*</span></label>
                                    <input type="text" class="form-control form-control-sm" id="agenda_title" name="agenda_title" required placeholder="e.g. Opening Remarks / Networking Coffee">
                                </div>
                            </div>

                            <div class="row g-3 mb-3">
                                <div class="col-12 col-md-6">
                                    <label for="speaker_profile_id" class="form-label small">Select Speaker <span class="text-danger">*</span></label>
                                    <select class="form-select form-select-sm" id="speaker_profile_id" name="speaker_profile_id" required onchange="toggleGuestSpeakerInput()">
                                        <option value="">-- No Speaker Assigned --</option>
                                        <optgroup label="Registered Event Speakers">
                                            <?php foreach ($speaker_profiles as $sp): ?>
                                                <option value="<?php echo $sp['id']; ?>">
                                                    <?php echo htmlspecialchars($sp['full_name']); ?> 
                                                    (<?php echo htmlspecialchars($sp['expertise']); ?>)
                                                </option>
                                            <?php endforeach; ?>
                                        </optgroup>
                                        <optgroup label="External Options">
                                            <option value="external">Add Guest / External Speaker</option>
                                        </optgroup>
                                    </select>
                                </div>
                                
                                <div class="col-12 col-md-6" id="external_speaker_container" style="display: none;">
                                    <label for="speaker" class="form-label small">Guest Speaker Name <span class="text-danger">*</span></label>
                                    <input type="text" class="form-control form-control-sm" id="speaker" name="speaker" placeholder="e.g. Alex Rivera">
                                </div>
                            </div>

                            <div class="mb-4">
                                <label for="agenda_desc" class="form-label small">Session Summary / Description</label>
                                <textarea class="form-control form-control-sm" id="agenda_desc" name="agenda_desc" rows="3" placeholder="Brief summary of what will be discussed during this session..."></textarea>
                            </div>

                            <div class="d-grid">
                                <button type="submit" name="submit_agenda" class="btn btn-warning btn-sm py-2 fw-bold">
                                    <i class="bi bi-plus-circle me-1"></i> Add Session to Agenda
                                </button>
                            </div>
                        </form>
                    </div>
                </div>
            </div>
            
            <script>
                function toggleGuestSpeakerInput() {
                    const select = document.getElementById('speaker_profile_id');
                    const container = document.getElementById('external_speaker_container');
                    const input = document.getElementById('speaker');
                    
                    if (select.value === 'external') {
                        container.style.display = 'block';
                        input.required = true;
                    } else {
                        container.style.display = 'none';
                        input.required = false;
                        input.value = '';
                    }
                }
            </script>
        <?php endif; ?>
    </div>

    <!-- RSVP, Attendees, and Sponsors Manager Side Panel (Right) -->
    <div class="col-12 col-lg-4">
        <!-- Ticket Pricing Card -->
        <div class="card border-0 shadow-sm mb-4">
            <div class="card-header bg-white border-bottom py-3">
                <h5 class="mb-0 fw-bold"><i class="bi bi-wallet2 me-2 text-primary"></i>Ticket Pricing</h5>
            </div>
            <div class="card-body">
                <?php if ($event['payment_type'] === 'free'): ?>
                    <div class="text-center py-2">
                        <span class="badge bg-success bg-opacity-10 text-success p-3 rounded-pill mb-2">
                            <i class="bi bi-ticket-detailed-fill fs-1"></i>
                        </span>
                        <h4 class="fw-bold text-success mb-1">FREE TICKET</h4>
                        <p class="text-secondary small mb-0">Admission is free of cost. Register below to secure your entry.</p>
                    </div>
                <?php else: 
                    $price = (float)$event['price'];
                    // Load GST rate from settings
                    $stmt_gst = $pdo->query("SELECT value FROM system_settings WHERE key = 'gst_rate'");
                    $gst_percent = (float)($stmt_gst->fetchColumn() ?: 18.00);
                    $gst_rate = $gst_percent / 100.00;

                    if ($event['gst_option'] === 'excluding') {
                        $base_price = $price;
                        $gst_amount = $base_price * $gst_rate;
                        $total_payable = $base_price + $gst_amount;
                        $gst_label = "Excluding GST (Tax Added)";
                    } else {
                        $total_payable = $price;
                        $base_price = $total_payable / (1.00 + $gst_rate);
                        $gst_amount = $total_payable - $base_price;
                        $gst_label = "Including GST (Tax Included)";
                    }
                ?>
                    <div class="mb-3 text-center">
                        <h2 class="fw-bold text-primary mb-0">₹<?php echo number_format($base_price, 2); ?></h2>
                    </div>

                <?php endif; ?>
            </div>
        </div>

        <!-- RSVP Form Card -->
        <div class="card border-0 shadow-sm mb-4">
            <div class="card-header bg-white border-bottom py-3">
                <h5 class="mb-0 fw-bold"><i class="bi bi-ticket-perforated-fill me-2 text-primary"></i>RSVP Confirmation</h5>
            </div>
            <div class="card-body py-4">
                <?php if ($isPast): ?>
                    <div class="alert alert-secondary mb-0" role="alert">
                        <i class="bi bi-info-circle me-2"></i> This event has concluded. Registration changes are disabled.
                    </div>
                <?php else: ?>
                    <form id="rsvpForm" method="POST" action="event/<?php echo $eventId; ?>">
                        <input type="hidden" name="csrf_token" value="<?php echo getCSRFToken(); ?>">
                        <input type="hidden" name="rsvp_action" value="register">
                        <?php if ($event['is_registered']): ?>
                            <?php if ($event['user_registration_status'] === 'waitlisted'): ?>
                                <div class="alert alert-warning d-flex align-items-center mb-3" role="alert">
                                    <i class="bi bi-clock-history me-2 text-warning fs-5"></i>
                                    <div class="text-warning-emphasis fw-bold">You are on the waitlist for this event!</div>
                                </div>
                            <?php else: ?>
                                <div class="alert alert-success d-flex align-items-center mb-3" role="alert">
                                    <i class="bi bi-check-circle-fill me-2 text-success"></i>
                                    <div class="text-success-emphasis fw-bold">You are RSVP'd for this event!</div>
                                </div>
                                <?php if ($event['payment_type'] === 'paid'): ?>
                                    <div class="d-grid gap-2 mb-3">
                                        <a href="invoice/<?php echo $eventId; ?>" target="_blank" class="btn btn-primary fw-bold">
                                            <i class="bi bi-file-earmark-pdf-fill me-1"></i> View Tax Invoice (GST Friendly)
                                        </a>
                                    </div>
                                <?php endif; ?>
                            <?php endif; ?>
                            <button type="button" class="btn btn-outline-danger btn-lg w-100 py-2" data-bs-toggle="modal" data-bs-target="#cancelRsvpModal">
                                <i class="bi bi-x-circle me-1"></i> Cancel My Registration / Waitlist
                            </button>

                            <!-- Cancel RSVP Modal -->
                            <div class="modal fade" id="cancelRsvpModal" tabindex="-1" aria-labelledby="cancelRsvpModalLabel" aria-hidden="true">
                                <div class="modal-dialog modal-dialog-centered">
                                    <div class="modal-content border-0 shadow">
                                        <div class="modal-header bg-danger text-white">
                                            <h5 class="modal-title fw-bold" id="cancelRsvpModalLabel">
                                                <i class="bi bi-exclamation-triangle-fill me-2"></i>Cancel Registration
                                            </h5>
                                            <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal" aria-label="Close"></button>
                                        </div>
                                        <div class="modal-body text-center p-4">
                                            <i class="bi bi-x-circle text-danger fs-1 mb-3"></i>
                                            <p class="fs-5 fw-semibold mb-1">Are you sure you want to cancel?</p>
                                            <p class="text-muted small">You will lose your seat or waitlist reservation for this event.</p>
                                        </div>
                                        <div class="modal-footer bg-light border-0 justify-content-center">
                                            <button type="button" class="btn btn-secondary px-4 py-2" data-bs-dismiss="modal">Keep Ticket</button>
                                            <form method="POST" action="event/<?php echo $eventId; ?>" class="d-inline">
                                                <input type="hidden" name="csrf_token" value="<?php echo getCSRFToken(); ?>">
                                                <input type="hidden" name="rsvp_action" value="cancel">
                                                <button type="submit" class="btn btn-danger px-4 py-2 fw-semibold">Yes, Cancel RSVP</button>
                                            </form>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        <?php else: ?>
                            <?php if ($isFull): ?>
                                <div class="alert alert-warning mb-3 small d-flex align-items-center" role="alert">
                                    <i class="bi bi-info-circle-fill me-2 fs-5"></i>
                                    <div>This event is fully booked. You can join the waitlist (free entry). If a seat opens up, you will be allocated.</div>
                                </div>
                                <div class="d-grid gap-2">
                                    <button type="submit" class="btn btn-warning btn-lg py-2 fw-bold text-dark">
                                        <i class="bi bi-clock-history me-1"></i> Join Waitlist (Free)
                                    </button>
                                </div>
                            <?php else: ?>
                                <p class="text-muted mb-3">Join other attendees and secure your spot today.</p>
                                <?php
                                $stmt_desig = $pdo->prepare("SELECT d.allow_wallet_payment FROM designations d JOIN users u ON u.designation_id = d.id WHERE u.id = ?");
                                $stmt_desig->execute([$currentUser['id']]);
                                $allow_wallet = $stmt_desig->fetchColumn();
                                
                                $rzp_key_id = !empty($event['razorpay_key_id']) ? trim($event['razorpay_key_id']) : '';
                                if (empty($rzp_key_id)) {
                                    $stmt_rzp = $pdo->query("SELECT value FROM system_settings WHERE key = 'razorpay_key_id'");
                                    $rzp_key_id = trim($stmt_rzp->fetchColumn() ?: '');
                                }
                                
                                if ($event['payment_type'] === 'paid') {
                                    $amount_paise = round($total_payable * 100);
                                    
                                    $stmt_earn = $pdo->prepare("SELECT COALESCE(SUM(amount), 0.00) FROM earnings WHERE user_id = ?");
                                    $stmt_earn->execute([$currentUser['id']]);
                                    $total_earnings = (float)$stmt_earn->fetchColumn();

                                    $stmt_pay = $pdo->prepare("SELECT COALESCE(SUM(amount), 0.00) FROM payouts WHERE user_id = ? AND status IN ('pending', 'paid')");
                                    $stmt_pay->execute([$currentUser['id']]);
                                    $total_withdrawn = (float)$stmt_pay->fetchColumn();

                                    $available_balance = max(0.00, $total_earnings - $total_withdrawn);
                                ?>
                                    <div class="mb-4 bg-light p-3 border rounded">
                                        <label class="form-label fw-bold text-dark mb-2"><i class="bi bi-credit-card-2-front-fill me-1"></i>Select Payment Method</label>
                                        <div class="form-check mb-2">
                                            <input class="form-check-input" type="radio" name="payment_method" id="pay_razorpay" value="razorpay" checked>
                                            <label class="form-check-label fw-semibold" for="pay_razorpay">Card / NetBanking / UPI</label>
                                        </div>
                                        <?php if ($allow_wallet): ?>
                                            <div class="form-check mb-2">
                                                <input class="form-check-input" type="radio" name="payment_method" id="pay_wallet" value="wallet" <?php echo ($available_balance < $total_payable) ? 'disabled' : ''; ?>>
                                                <label class="form-check-label fw-semibold" for="pay_wallet">
                                                    Wallet Balance (₹<?php echo number_format($available_balance, 2); ?>)
                                                    <?php if ($available_balance < $total_payable): ?>
                                                        <span class="text-danger small ms-1">(Insufficient)</span>
                                                    <?php endif; ?>
                                                </label>
                                            </div>
                                        <?php endif; ?>
                                        <div class="form-check">
                                            <input class="form-check-input" type="radio" name="payment_method" id="pay_pin" value="pin">
                                            <label class="form-check-label fw-semibold" for="pay_pin">
                                                Prepaid E-PIN
                                            </label>
                                        </div>

                                        <!-- PIN Input Container -->
                                        <div class="mt-3" id="pin_input_container" style="display: none;">
                                            <label for="registration_pin" class="form-label small fw-bold">Enter Prepaid E-PIN <span class="text-danger">*</span></label>
                                            <input type="text" class="form-control form-control-sm text-uppercase" id="registration_pin" name="registration_pin" placeholder="PIN-XXXX-XXXX-XXXX">
                                            <div class="form-text text-muted" style="font-size: 0.75rem;">Input a valid E-PIN code of value ₹<?php echo number_format($total_payable, 2); ?>.</div>
                                        </div>
                                    </div>

                                    <button type="button" id="rzp-button1" class="btn btn-primary btn-lg w-100 py-2 fw-bold">
                                        <i class="bi bi-calendar-check-fill me-1"></i> Register
                                    </button>
                                    <script src="https://checkout.razorpay.com/v1/checkout.js"></script>
                                    <script>
                                    document.getElementById('rzp-button1').onclick = function(e){
                                         e.preventDefault();
                                         
                                         var form = document.getElementById('rsvpForm');
                                         var paymentMethod = form.querySelector('input[name="payment_method"]:checked')?.value || form.querySelector('input[name="payment_method"]')?.value || 'razorpay';
                                         
                                         if (paymentMethod === 'wallet' || paymentMethod === 'pin') {
                                             form.submit();
                                             return;
                                         }
                                         
                                         if (typeof Razorpay === 'undefined') {
                                             var simModal = new bootstrap.Modal(document.getElementById('paymentSimulationModal'));
                                             simModal.show();
                                             
                                             document.getElementById('btn-simulate-payment').onclick = function() {
                                                 simModal.hide();
                                                 var mockPaymentId = "pay_mock_" + Math.random().toString(36).substring(2, 15);
                                                 var input = document.createElement('input');
                                                 input.type = 'hidden';
                                                 input.name = 'razorpay_payment_id';
                                                 input.value = mockPaymentId;
                                                 form.appendChild(input);
                                                 form.submit();
                                             };
                                             return;
                                         }
                                         var options = {
                                             "key": "<?php echo htmlspecialchars($rzp_key_id); ?>",
                                             "amount": "<?php echo $amount_paise; ?>",
                                             "currency": "INR",
                                             "name": "EventPortal Checkout",
                                             "description": "Ticket: <?php echo htmlspecialchars($event['title']); ?>",
                                             "prefill": {
                                                 "name": "<?php echo htmlspecialchars($currentUser['username']); ?>",
                                                 "email": "<?php echo htmlspecialchars($currentUser['email']); ?>"
                                             },
                                             "theme": {
                                                 "color": "#0d6efd"
                                             },
                                             "handler": function (response){
                                                 var input = document.createElement('input');
                                                 input.type = 'hidden';
                                                 input.name = 'razorpay_payment_id';
                                                 input.value = response.razorpay_payment_id;
                                                 form.appendChild(input);
                                                 form.submit();
                                             }
                                         };
                                         var rzp1 = new Razorpay(options);
                                         rzp1.open();
                                     }

                                      // Toggle E-PIN Input box view
                                      document.addEventListener("DOMContentLoaded", function() {
                                          const payMethodRadios = document.querySelectorAll('input[name="payment_method"]');
                                          const pinContainer = document.getElementById('pin_input_container');
                                          const pinInput = document.getElementById('registration_pin');
                                          
                                          payMethodRadios.forEach(radio => {
                                              radio.addEventListener('change', function() {
                                                  if (this.value === 'pin') {
                                                      pinContainer.style.display = 'block';
                                                      pinInput.required = true;
                                                  } else {
                                                      pinContainer.style.display = 'none';
                                                      pinInput.required = false;
                                                  }
                                              });
                                          });
                                      });
                                     </script>

                                     <!-- Payment Simulation Modal -->
                                     <div class="modal fade" id="paymentSimulationModal" tabindex="-1" aria-labelledby="paymentSimulationModalLabel" aria-hidden="true">
                                         <div class="modal-dialog modal-dialog-centered">
                                             <div class="modal-content border-0 shadow">
                                                 <div class="modal-header bg-warning text-dark">
                                                     <h5 class="modal-title fw-bold" id="paymentSimulationModalLabel">
                                                         <i class="bi bi-shield-slash-fill me-2"></i>Razorpay SDK Sandbox Simulator
                                                     </h5>
                                                     <button type="button" class="btn-close text-dark border-0 bg-transparent" data-bs-dismiss="modal" aria-label="Close"></button>
                                                 </div>
                                                 <div class="modal-body text-center p-4">
                                                     <i class="bi bi-info-circle-fill text-warning fs-1 mb-3"></i>
                                                     <p class="fs-5 fw-semibold mb-1">Razorpay SDK is blocked or offline</p>
                                                     <p class="text-muted small">We detected that the external Razorpay checkout script could not load. Would you like to simulate a successful payment test checkout to complete your registration?</p>
                                                 </div>
                                                 <div class="modal-footer bg-light border-0 justify-content-center">
                                                     <button type="button" class="btn btn-secondary px-4 py-2" data-bs-dismiss="modal">Cancel</button>
                                                     <button type="button" id="btn-simulate-payment" class="btn btn-warning px-4 py-2 fw-semibold text-dark">Simulate Payment Success</button>
                                                 </div>
                                             </div>
                                         </div>
                                     </div>
                                 <?php } else { ?>
                                     <button type="submit" class="btn btn-success btn-lg w-100 py-2 fw-bold">
                                         <i class="bi bi-calendar-check-fill me-1"></i> Register
                                     </button>
                                 <?php } ?>
                             <?php endif; ?>
                        <?php endif; ?>
                    </form>
                <?php endif; ?>
            </div>
        </div>

        <!-- Event Sponsors Manager (Admin/Organizer Only) -->
        <?php if ($isEventManager): ?>
            <div class="card border-0 shadow-sm mb-4">
                <div class="card-header bg-white border-bottom py-3">
                    <h5 class="mb-0 fw-bold"><i class="bi bi-award-fill me-2 text-primary"></i>Sponsors Manager</h5>
                </div>
                <div class="card-body">
                    <form method="POST" action="event/<?php echo $eventId; ?>" class="mb-3">
                        <input type="hidden" name="csrf_token" value="<?php echo getCSRFToken(); ?>">
                        <div class="mb-2">
                            <label for="sponsor_profile_id" class="form-label small">Select Sponsor Company</label>
                            <select class="form-select form-select-sm" id="sponsor_profile_id" name="sponsor_profile_id" required>
                                <option value="">-- Choose Corporate Sponsor --</option>
                                <?php foreach ($all_sponsor_profiles as $asp): ?>
                                    <option value="<?php echo $asp['id']; ?>">
                                        <?php echo htmlspecialchars($asp['company_name']); ?> (Default: <?php echo htmlspecialchars($asp['default_tier']); ?>)
                                    </option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                        <div class="mb-3">
                            <label for="sponsor_tier" class="form-label small">Sponsorship Tier (For this event)</label>
                            <select class="form-select form-select-sm" id="sponsor_tier" name="sponsor_tier" required>
                                <option value="Platinum">Platinum Sponsor</option>
                                <option value="Gold">Gold Sponsor</option>
                                <option value="Silver" selected>Silver Sponsor</option>
                                <option value="Bronze">Bronze Sponsor</option>
                            </select>
                        </div>
                        <div class="d-grid">
                            <button type="submit" name="submit_link_sponsor" class="btn btn-outline-primary btn-sm fw-bold">
                                <i class="bi bi-plus-circle me-1"></i> Assign Sponsor to Event
                            </button>
                        </div>
                    </form>
                    
                    <!-- Mapped Sponsors Revocation List -->
                    <?php if (!empty($event_sponsors)): ?>
                        <hr class="my-3">
                        <h6 class="fw-bold mb-2 small text-secondary">Linked Sponsors:</h6>
                        <ul class="list-group list-group-flush border rounded overflow-hidden">
                            <?php foreach ($event_sponsors as $s): ?>
                                <li class="list-group-item d-flex justify-content-between align-items-center py-2 px-3 small">
                                    <div>
                                        <strong class="text-dark"><?php echo htmlspecialchars($s['company_name']); ?></strong>
                                        <span class="badge bg-light text-dark border font-monospace ms-1" style="font-size:0.7rem;"><?php echo $s['tier']; ?></span>
                                    </div>
                                    <a href="event/<?php echo $eventId; ?>&action=unlink_sponsor&mapping_id=<?php echo $s['mapping_id']; ?>&csrf_token=<?php echo getCSRFToken(); ?>" 
                                       class="text-danger p-1" 
                                       title="Remove Sponsor"
                                       onclick="return confirm('Remove this sponsor from the event?');">
                                        <i class="bi bi-trash"></i>
                                    </a>
                                </li>
                            <?php endforeach; ?>
                        </ul>
                    <?php endif; ?>
                </div>
            </div>
        <?php endif; ?>

        <!-- Waitlist Manager Card (Admin/Organizer Only) -->
        <?php if ($isEventManager): ?>
            <div class="card border-0 shadow-sm mb-4">
                <div class="card-header bg-white border-bottom py-3 d-flex justify-content-between align-items-center">
                    <h5 class="mb-0 fw-bold"><i class="bi bi-clock-history me-2 text-warning"></i>Waitlist Queue</h5>
                    <span class="badge bg-warning text-dark font-monospace"><?php echo count($waitlisted_registrations); ?> pending</span>
                </div>
                <div class="card-body p-0">
                    <?php if (empty($waitlisted_registrations)): ?>
                        <div class="text-center py-4 text-muted">
                            <i class="bi bi-person-check fs-2 mb-1 text-secondary"></i>
                            <p class="mb-0 small">Waitlist queue is empty.</p>
                        </div>
                    <?php else: ?>
                        <div class="list-group list-group-flush">
                            <?php foreach ($waitlisted_registrations as $wl): ?>
                                <div class="list-group-item px-4 py-3 d-flex justify-content-between align-items-center">
                                    <div>
                                        <h6 class="mb-0 small fw-bold text-dark"><?php echo htmlspecialchars($wl['username']); ?></h6>
                                        <span class="text-muted font-monospace" style="font-size: 0.72rem;"><?php echo htmlspecialchars($wl['email']); ?></span>
                                    </div>
                                    <form method="POST" action="event/<?php echo $eventId; ?>">
                                        <input type="hidden" name="csrf_token" value="<?php echo getCSRFToken(); ?>">
                                        <input type="hidden" name="rsvp_action" value="allocate_seat">
                                        <input type="hidden" name="target_user_id" value="<?php echo $wl['user_id']; ?>">
                                        <button type="submit" class="btn btn-sm btn-success text-white fw-semibold" <?php echo $isFull ? 'disabled title="Event is full"' : ''; ?>>
                                            Allocate Seat
                                        </button>
                                    </form>
                                </div>
                            <?php endforeach; ?>
                        </div>
                    <?php endif; ?>
                </div>
            </div>
        <?php endif; ?>

        <!-- Attendees List Card (Hidden for standard user role) -->
        <?php if ($currentUser['role'] !== 'user'): ?>
            <div class="card border-0 shadow-sm">
                <div class="card-header bg-white border-bottom py-3 d-flex justify-content-between align-items-center">
                    <h5 class="mb-0 fw-bold"><i class="bi bi-people-fill me-2 text-primary"></i>Attendees</h5>
                    <span class="badge bg-secondary font-monospace"><?php echo $total_attendees; ?> total</span>
                </div>
                <div class="card-body p-0">
                    <?php if (empty($attendees)): ?>
                        <div class="text-center py-4 text-muted">
                            <i class="bi bi-people fs-2 mb-1"></i>
                            <p class="mb-0 small">No attendees registered yet.</p>
                        </div>
                    <?php else: ?>
                        <div class="list-group list-group-flush rounded-bottom">
                            <?php foreach ($attendees as $att): ?>
                                <div class="list-group-item px-4 py-3">
                                    <div class="d-flex align-items-center">
                                        <div class="p-1.5 bg-light rounded-circle text-muted me-3">
                                            <i class="bi bi-person small"></i>
                                        </div>
                                        <div class="flex-grow-1">
                                            <h6 class="mb-0 small fw-bold text-dark"><?php echo htmlspecialchars($att['username']); ?></h6>
                                            <?php if ($isEventManager): ?>
                                                <span class="text-muted font-monospace" style="font-size: 0.75rem;"><?php echo htmlspecialchars($att['email']); ?></span>
                                            <?php endif; ?>
                                        </div>
                                    </div>
                                </div>
                            <?php endforeach; ?>
                        </div>
                        <?php if ($total_att_pages > 1): ?>
                            <div class="card-footer bg-white border-top py-3">
                                <nav aria-label="Attendee page navigation">
                                    <ul class="pagination pagination-sm justify-content-center align-items-center gap-1 mb-0">
                                        <li class="page-item <?php echo $att_page <= 1 ? 'disabled' : ''; ?>">
                                            <a class="page-link px-2" href="?id=<?php echo $eventId; ?>&att_page=1">First</a>
                                        </li>
                                        <li class="page-item <?php echo $att_page <= 1 ? 'disabled' : ''; ?>">
                                            <a class="page-link px-2" href="?id=<?php echo $eventId; ?>&att_page=<?php echo $att_page - 1; ?>">Previous</a>
                                        </li>
                                        <li class="page-item disabled mx-1">
                                            <span class="text-secondary small fw-bold" style="font-size: 0.75rem;">Page <?php echo $att_page; ?> of <?php echo $total_att_pages; ?></span>
                                        </li>
                                        <li class="page-item <?php echo $att_page >= $total_att_pages ? 'disabled' : ''; ?>">
                                            <a class="page-link px-2" href="?id=<?php echo $eventId; ?>&att_page=<?php echo $att_page + 1; ?>">Next</a>
                                        </li>
                                        <li class="page-item <?php echo $att_page >= $total_att_pages ? 'disabled' : ''; ?>">
                                            <a class="page-link px-2" href="?id=<?php echo $total_att_pages; ?>&att_page=<?php echo $total_att_pages; ?>">Last</a>
                                        </li>
                                    </ul>
                                </nav>
                            </div>
                        <?php endif; ?>
                    <?php endif; ?>
                </div>
            </div>
        <?php endif; ?>
    </div>
</div>

<?php
include __DIR__ . '/../includes/footer.php';
?>
