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

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

requireLogin();
$currentUser = getCurrentUser();
$isAdmin = isEventManager(); // Admin and Organizer can manage events

$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) { }

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

// 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);
    }
}

// Helper to generate a Zoom-like meeting link
function generateZoomLink() {
    $meetingId = rand(1000000000, 9999999999);
    $pwd = bin2hex(random_bytes(8));
    return "https://zoom.us/j/{$meetingId}?pwd={$pwd}";
}

// Handle Delete Action (Admin/Organizer Only)
if (isset($_GET['action']) && $_GET['action'] === 'delete' && isset($_GET['id'])) {
    if (!verifyCSRFToken($_GET['csrf_token'] ?? '')) {
        $_SESSION['flash_error'] = "Security check failed (CSRF). Please try again.";
        header("Location: events");
        exit();
    }
    if (!$isAdmin) {
        $_SESSION['flash_error'] = "Unauthorized access.";
        header("Location: events");
        exit();
    }
    
    $deleteId = (int)$_GET['id'];
    try {
        // Fetch recurrence details
        $stmt_rec = $pdo->prepare("SELECT recurrence_group_id FROM events WHERE id = ?");
        $stmt_rec->execute([$deleteId]);
        $rec_group_id = $stmt_rec->fetchColumn();
        
        if ($rec_group_id && isset($_GET['delete_series']) && $_GET['delete_series'] == '1') {
            $stmt = $pdo->prepare("DELETE FROM events WHERE recurrence_group_id = ?");
            $stmt->execute([$rec_group_id]);
            $_SESSION['flash_success'] = "All occurrences in the recurring series deleted successfully.";
        } else {
            $stmt = $pdo->prepare("DELETE FROM events WHERE id = ?");
            $stmt->execute([$deleteId]);
            $_SESSION['flash_success'] = "Event deleted successfully.";
        }
    } catch (PDOException $e) {
        $_SESSION['flash_error'] = "Failed to delete event: " . $e->getMessage();
    }
    header("Location: events");
    exit();
}

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

// Handle Add Event Form (Admin/Organizer Only)
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (!verifyCSRFToken($_POST['csrf_token'] ?? '')) {
        $_SESSION['flash_error'] = "Security check failed (CSRF). Please try again.";
        header("Location: events");
        exit();
    }
}

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['submit_add'])) {
    if (!$isAdmin) {
        $error = "Unauthorized action.";
    } else {
        $title = trim($_POST['title'] ?? '');
        $description = trim($_POST['description'] ?? '');
        $status = trim($_POST['status'] ?? 'draft');
        if (!in_array($status, ['draft', 'published'])) {
            $status = 'draft';
        }
        $start_date = trim($_POST['start_date'] ?? '');
        $end_date = trim($_POST['end_date'] ?? '');
        $banner_url = trim($_POST['banner_url'] ?? '');
        $attachment_url = '';
        $event_type = $_POST['event_type'] ?? 'physical';
        $capacity = (int)($_POST['capacity'] ?? 0);
        $agenda_json = $_POST['agenda_json'] ?? '[]';
        
        $payment_type = trim($_POST['payment_type'] ?? 'free');
        $price = 0.00;
        $rzp_key_id = null;
        $rzp_key_secret = null;
        if ($payment_type === 'paid') {
            $price = (float)($_POST['price'] ?? 0.00);
            $rzp_key_id = trim($_POST['razorpay_key_id'] ?? '');
            $rzp_key_secret = trim($_POST['razorpay_key_secret'] ?? '');
            if ($rzp_key_id === '') $rzp_key_id = null;
            if ($rzp_key_secret === '') $rzp_key_secret = null;
        }
        $gst_option = trim($_POST['gst_option'] ?? 'excluding');

        // Handle File Upload for Banner securely
        if (isset($_FILES['banner_file']) && $_FILES['banner_file']['error'] === UPLOAD_ERR_OK) {
            $upload_dir = __DIR__ . '/uploads';
            if (!is_dir($upload_dir)) {
                mkdir($upload_dir, 0777, true);
            }
            
            $tmp_name = $_FILES['banner_file']['tmp_name'];
            $original_name = $_FILES['banner_file']['name'];
            $ext = strtolower(pathinfo($original_name, PATHINFO_EXTENSION));
            
            $allowed_exts = ['jpg', 'jpeg', 'png', 'gif'];
            if (in_array($ext, $allowed_exts)) {
                $finfo = finfo_open(FILEINFO_MIME_TYPE);
                $mime = finfo_file($finfo, $tmp_name);
                finfo_close($finfo);
                
                $allowed_mimes = ['image/jpeg', 'image/png', 'image/gif'];
                if (in_array($mime, $allowed_mimes)) {
                    $file_name = bin2hex(random_bytes(16)) . '.' . $ext;
                    $destination = $upload_dir . '/' . $file_name;
                    if (move_uploaded_file($tmp_name, $destination)) {
                        $banner_url = 'uploads/' . $file_name;
                    }
                }
            }
        }

        // Handle File Upload for Downloadable Attachment securely
        if (isset($_FILES['attachment_file']) && $_FILES['attachment_file']['error'] === UPLOAD_ERR_OK) {
            $upload_dir = __DIR__ . '/uploads/attachments';
            if (!is_dir($upload_dir)) {
                mkdir($upload_dir, 0755, true);
            }
            
            $tmp_name = $_FILES['attachment_file']['tmp_name'];
            $original_name = $_FILES['attachment_file']['name'];
            $ext = strtolower(pathinfo($original_name, PATHINFO_EXTENSION));
            
            $allowed_exts = ['pdf', 'doc', 'docx', 'zip', 'pptx', 'ppt', 'txt', 'xls', 'xlsx'];
            if (in_array($ext, $allowed_exts)) {
                $file_name = bin2hex(random_bytes(16)) . '.' . $ext;
                $destination = $upload_dir . '/' . $file_name;
                if (move_uploaded_file($tmp_name, $destination)) {
                    $attachment_url = 'uploads/attachments/' . $file_name;
                }
            }
        }
        
        $location = '';
        $google_map_embed = '';
        $virtual_platform = '';
        $virtual_link = '';

        if ($event_type === 'physical' || $event_type === 'hybrid') {
            $location = trim($_POST['location'] ?? '');
            $google_map_embed = trim($_POST['google_map_embed'] ?? '');
        }
        
        if ($event_type === 'virtual' || $event_type === 'hybrid') {
            $virtual_platform = $_POST['virtual_platform'] ?? '';
            
            if (isset($_POST['auto_zoom']) && $virtual_platform === 'zoom') {
                $virtual_link = generateZoomLink();
            } else {
                $virtual_link = trim($_POST['virtual_link'] ?? '');
            }

            if ($event_type === 'virtual') {
                $location = 'Online Webcast';
            }
        }

        if (empty($title) || empty($start_date) || empty($end_date) || ($event_type !== 'virtual' && empty($location))) {
            $error = "Please fill in all required fields.";
        } elseif (strtotime($start_date) > strtotime($end_date)) {
            $error = "Start Date cannot be later than End Date.";
        } else {
            try {
                $formatted_start = date('Y-m-d H:i:s', strtotime($start_date));
                $formatted_end = date('Y-m-d H:i:s', strtotime($end_date));
                
                $pdo->beginTransaction();

                // 1. Insert Event
                $is_recurring = isset($_POST['is_recurring']) && $_POST['is_recurring'] == '1';
                $recurrence_pattern = $is_recurring ? trim($_POST['recurrence_pattern'] ?? '') : null;
                $recurrence_end_date_raw = $is_recurring ? trim($_POST['recurrence_end_date'] ?? '') : null;
                $recurrence_end_date = !empty($recurrence_end_date_raw) ? date('Y-m-d H:i:s', strtotime($recurrence_end_date_raw)) : null;
                $recurrence_group_id = $is_recurring ? 'rec_' . bin2hex(random_bytes(8)) : null;

                $insert = $pdo->prepare("
                    INSERT INTO events (title, description, start_date, end_date, location, capacity, banner_url, event_type, google_map_embed, virtual_platform, virtual_link, payment_type, price, gst_option, created_by, is_recurring, recurrence_pattern, recurrence_end_date, recurrence_group_id, attachment_url, status, razorpay_key_id, razorpay_key_secret) 
                    VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
                ");
                $insert->execute([
                    $title, $description, $formatted_start, $formatted_end, 
                    $location, $capacity, $banner_url, $event_type, 
                    $google_map_embed, $virtual_platform, $virtual_link, 
                    $payment_type, $price, $gst_option,
                    $currentUser['id'],
                    $is_recurring ? 1 : 0,
                    $recurrence_pattern,
                    $recurrence_end_date,
                    $recurrence_group_id,
                    $attachment_url,
                    $status,
                    $rzp_key_id,
                    $rzp_key_secret
                ]);
                $newEventId = $pdo->lastInsertId();

                // 2. Decode & Insert Agendas
                $agenda_items = json_decode($agenda_json, true) ?: [];
                $ins_agenda = $pdo->prepare("
                    INSERT INTO event_agendas (event_id, speaker_profile_id, agenda_date, start_time, end_time, title, speaker, description) 
                    VALUES (?, ?, ?, ?, ?, ?, ?, ?)
                ");
                foreach ($agenda_items as $item) {
                    $sp_id = !empty($item['speaker_profile_id']) ? (int)$item['speaker_profile_id'] : null;
                    $sp_name = !empty($item['speaker']) ? $item['speaker'] : null;
                    $ins_agenda->execute([
                        $newEventId,
                        $sp_id,
                        $item['agenda_date'],
                        $item['start_time'],
                        $item['end_time'],
                        $item['title'],
                        $sp_name,
                        $item['description']
                    ]);
                }

                // Generate occurrences if recurring
                if ($is_recurring && !empty($recurrence_pattern) && $recurrence_end_date) {
                    $current_start = strtotime($formatted_start);
                    $current_end = strtotime($formatted_end);
                    $end_limit = strtotime($recurrence_end_date);
                    
                    $interval_str = '';
                    if ($recurrence_pattern === 'daily') {
                        $interval_str = '+1 day';
                    } elseif ($recurrence_pattern === 'weekly') {
                        $interval_str = '+1 week';
                    } elseif ($recurrence_pattern === 'monthly') {
                        $interval_str = '+1 month';
                    }
                    
                    if (!empty($interval_str)) {
                        $occurrence_count = 0;
                        while ($occurrence_count < 30) { // Limit to max 30 occurrences to prevent timeouts
                            $current_start = strtotime($interval_str, $current_start);
                            $current_end = strtotime($interval_str, $current_end);
                            
                            if ($current_start > $end_limit) {
                                break;
                            }
                            
                            $occ_start_date = date('Y-m-d H:i:s', $current_start);
                            $occ_end_date = date('Y-m-d H:i:s', $current_end);
                            
                            $insert->execute([
                                $title, $description, $occ_start_date, $occ_end_date, 
                                $location, $capacity, $banner_url, $event_type, 
                                $google_map_embed, $virtual_platform, $virtual_link, 
                                $payment_type, $price, $gst_option,
                                $currentUser['id'],
                                1,
                                $recurrence_pattern,
                                $recurrence_end_date,
                                $recurrence_group_id,
                                $attachment_url,
                                $status
                            ]);
                            $occ_event_id = $pdo->lastInsertId();
                            
                            // Duplicate agendas for this occurrence
                            foreach ($agenda_items as $item) {
                                $sp_id = !empty($item['speaker_profile_id']) ? (int)$item['speaker_profile_id'] : null;
                                $sp_name = !empty($item['speaker']) ? $item['speaker'] : null;
                                $agenda_date_shifted = date('Y-m-d', $current_start);
                                $ins_agenda->execute([
                                    $occ_event_id,
                                    $sp_id,
                                    $agenda_date_shifted,
                                    $item['start_time'],
                                    $item['end_time'],
                                    $item['title'],
                                    $sp_name,
                                    $item['description']
                                ]);
                            }
                            $occurrence_count++;
                        }
                    }
                }

                $pdo->commit();
                
                $_SESSION['flash_success'] = "Event '$title' with its schedule created successfully.";
                header("Location: events");
                exit();
            } catch (PDOException $e) {
                if ($pdo->inTransaction()) {
                    $pdo->rollBack();
                }
                $error = "Database transaction error: " . $e->getMessage();
            }
        }
    }
}

// Handle Edit Event Form (Admin/Organizer Only)
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['submit_edit'])) {
    if (!$isAdmin) {
        $error = "Unauthorized action.";
    } else {
        $editId = (int)$_POST['edit_id'];
        $title = trim($_POST['title'] ?? '');
        $status = trim($_POST['status'] ?? 'draft');
        if (!in_array($status, ['draft', 'published'])) {
            $status = 'draft';
        }
        $description = trim($_POST['description'] ?? '');
        $start_date = trim($_POST['start_date'] ?? '');
        $end_date = trim($_POST['end_date'] ?? '');
        $banner_url = trim($_POST['banner_url'] ?? '');
        $event_type = $_POST['event_type'] ?? 'physical';
        $capacity = (int)($_POST['capacity'] ?? 0);
        $agenda_json = $_POST['agenda_json'] ?? '[]';
        
        $payment_type = trim($_POST['payment_type'] ?? 'free');
        $price = 0.00;
        $rzp_key_id = null;
        $rzp_key_secret = null;
        if ($payment_type === 'paid') {
            $price = (float)($_POST['price'] ?? 0.00);
            $rzp_key_id = trim($_POST['razorpay_key_id'] ?? '');
            $rzp_key_secret = trim($_POST['razorpay_key_secret'] ?? '');
            if ($rzp_key_id === '') $rzp_key_id = null;
            if ($rzp_key_secret === '') $rzp_key_secret = null;
        }
        $gst_option = trim($_POST['gst_option'] ?? 'excluding');
        
        // Fetch existing banner & attachment URLs
        $stmt_exist = $pdo->prepare("SELECT banner_url, attachment_url FROM events WHERE id = ?");
        $stmt_exist->execute([$editId]);
        $existing = $stmt_exist->fetch(PDO::FETCH_ASSOC);
        $existing_banner = $existing['banner_url'];
        $existing_attachment = $existing['attachment_url'] ?? '';

        $attachment_url = '';

        // Handle File Upload for Banner securely
        if (isset($_FILES['banner_file']) && $_FILES['banner_file']['error'] === UPLOAD_ERR_OK) {
            $upload_dir = __DIR__ . '/uploads';
            if (!is_dir($upload_dir)) {
                mkdir($upload_dir, 0777, true);
            }
            
            $tmp_name = $_FILES['banner_file']['tmp_name'];
            $original_name = $_FILES['banner_file']['name'];
            $ext = strtolower(pathinfo($original_name, PATHINFO_EXTENSION));
            
            $allowed_exts = ['jpg', 'jpeg', 'png', 'gif'];
            if (in_array($ext, $allowed_exts)) {
                $finfo = finfo_open(FILEINFO_MIME_TYPE);
                $mime = finfo_file($finfo, $tmp_name);
                finfo_close($finfo);
                
                $allowed_mimes = ['image/jpeg', 'image/png', 'image/gif'];
                if (in_array($mime, $allowed_mimes)) {
                    $file_name = bin2hex(random_bytes(16)) . '.' . $ext;
                    $destination = $upload_dir . '/' . $file_name;
                    if (move_uploaded_file($tmp_name, $destination)) {
                        $banner_url = 'uploads/' . $file_name;
                    }
                }
            }
        }

        // Handle File Upload for Downloadable Attachment securely
        if (isset($_FILES['attachment_file']) && $_FILES['attachment_file']['error'] === UPLOAD_ERR_OK) {
            $upload_dir = __DIR__ . '/uploads/attachments';
            if (!is_dir($upload_dir)) {
                mkdir($upload_dir, 0755, true);
            }
            
            $tmp_name = $_FILES['attachment_file']['tmp_name'];
            $original_name = $_FILES['attachment_file']['name'];
            $ext = strtolower(pathinfo($original_name, PATHINFO_EXTENSION));
            
            $allowed_exts = ['pdf', 'doc', 'docx', 'zip', 'pptx', 'ppt', 'txt', 'xls', 'xlsx'];
            if (in_array($ext, $allowed_exts)) {
                $file_name = bin2hex(random_bytes(16)) . '.' . $ext;
                $destination = $upload_dir . '/' . $file_name;
                if (move_uploaded_file($tmp_name, $destination)) {
                    $attachment_url = 'uploads/attachments/' . $file_name;
                }
            }
        }

        // If no new file upload and no new URL pasted, preserve the existing banner image
        if (empty($banner_url) && !empty($existing_banner)) {
            $banner_url = $existing_banner;
        }
        if (empty($attachment_url) && !empty($existing_attachment)) {
            $attachment_url = $existing_attachment;
        }

        $location = '';
        $google_map_embed = '';
        $virtual_platform = '';
        $virtual_link = '';

        if ($event_type === 'physical' || $event_type === 'hybrid') {
            $location = trim($_POST['location'] ?? '');
            $google_map_embed = trim($_POST['google_map_embed'] ?? '');
        }
        
        if ($event_type === 'virtual' || $event_type === 'hybrid') {
            $virtual_platform = $_POST['virtual_platform'] ?? '';
            
            if (isset($_POST['auto_zoom']) && $virtual_platform === 'zoom') {
                $virtual_link = generateZoomLink();
            } else {
                $virtual_link = trim($_POST['virtual_link'] ?? '');
            }

            if ($event_type === 'virtual') {
                $location = 'Online Webcast';
            }
        }

        if (empty($title) || empty($start_date) || empty($end_date) || ($event_type !== 'virtual' && empty($location))) {
            $error = "Please fill in all required fields.";
        } elseif (strtotime($start_date) > strtotime($end_date)) {
            $error = "Start Date cannot be later than End Date.";
        } else {
            try {
                $formatted_start = date('Y-m-d H:i:s', strtotime($start_date));
                $formatted_end = date('Y-m-d H:i:s', strtotime($end_date));
                
                $pdo->beginTransaction();

                // 1. Update Core Event
                $update = $pdo->prepare("
                    UPDATE events 
                    SET title = ?, description = ?, start_date = ?, end_date = ?, location = ?, capacity = ?, 
                        banner_url = ?, event_type = ?, google_map_embed = ?, virtual_platform = ?, virtual_link = ?,
                        payment_type = ?, price = ?, gst_option = ?, attachment_url = ?, status = ?,
                        razorpay_key_id = ?, razorpay_key_secret = ?
                    WHERE id = ?
                ");
                $update->execute([
                    $title, $description, $formatted_start, $formatted_end, 
                    $location, $capacity, $banner_url, $event_type, 
                    $google_map_embed, $virtual_platform, $virtual_link, 
                    $payment_type, $price, $gst_option,
                    $attachment_url,
                    $status,
                    $rzp_key_id,
                    $rzp_key_secret,
                    $editId
                ]);

                // 2. Clear Existing Agendas
                $del_agenda = $pdo->prepare("DELETE FROM event_agendas WHERE event_id = ?");
                $del_agenda->execute([$editId]);

                // 3. Decode & Re-insert Agendas
                $agenda_items = json_decode($agenda_json, true) ?: [];
                $ins_agenda = $pdo->prepare("
                    INSERT INTO event_agendas (event_id, speaker_profile_id, agenda_date, start_time, end_time, title, speaker, description) 
                    VALUES (?, ?, ?, ?, ?, ?, ?, ?)
                ");
                foreach ($agenda_items as $item) {
                    $sp_id = !empty($item['speaker_profile_id']) ? (int)$item['speaker_profile_id'] : null;
                    $sp_name = !empty($item['speaker']) ? $item['speaker'] : null;
                    $ins_agenda->execute([
                        $editId,
                        $sp_id,
                        $item['agenda_date'],
                        $item['start_time'],
                        $item['end_time'],
                        $item['title'],
                        $sp_name,
                        $item['description']
                    ]);
                }

                $pdo->commit();
                
                $_SESSION['flash_success'] = "Event details and agendas updated successfully.";
                header("Location: events");
                exit();
            } catch (PDOException $e) {
                if ($pdo->inTransaction()) {
                    $pdo->rollBack();
                }
                $error = "Database transaction error: " . $e->getMessage();
            }
        }
    }
}

// Fetch single event for editing
$editEvent = null;
$existing_agendas = [];
if (isset($_GET['edit_id']) && $isAdmin) {
    $editId = (int)$_GET['edit_id'];
    try {
        $stmt = $pdo->prepare("SELECT * FROM events WHERE id = ?");
        $stmt->execute([$editId]);
        $editEvent = $stmt->fetch();
        
        if ($editEvent) {
            $editEvent['start_date_formatted'] = date('Y-m-d\TH:i', strtotime($editEvent['start_date']));
            $editEvent['end_date_formatted'] = date('Y-m-d\TH:i', strtotime($editEvent['end_date']));
            
            // Fetch agendas
            $stmt_agenda = $pdo->prepare("SELECT title, agenda_date, start_time, end_time, speaker_profile_id, speaker, description FROM event_agendas WHERE event_id = ? ORDER BY agenda_date ASC, start_time ASC");
            $stmt_agenda->execute([$editId]);
            $existing_agendas = $stmt_agenda->fetchAll(PDO::FETCH_ASSOC);
        }
    } catch (PDOException $e) {
        $error = "Failed to load event details.";
    }
}

// Fetch events with Search & Registrations count
$search = trim($_GET['search'] ?? '');
$query = "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 1=1";
$params = [$currentUser['id']];

// Count query builder to support pagination
$count_query = "SELECT COUNT(DISTINCT e.id) 
                FROM events e 
                LEFT JOIN users u ON e.created_by = u.id 
                WHERE 1=1";
$count_params = [];

// Content Access Control for standard users (attendees/employees)
if ($currentUser && $currentUser['role'] !== 'admin' && $currentUser['role'] !== 'organizer') {
    $query .= " AND e.status = 'published'";
    $count_query .= " AND e.status = 'published'";
    // Fetch user's designation details
    $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)) {
            $placeholders = implode(',', array_fill(0, count($allowed_ids), '?'));
            $query .= " AND e.id IN ($placeholders)";
            $count_query .= " AND e.id IN ($placeholders)";
            foreach ($allowed_ids as $id_val) {
                $params[] = $id_val;
                $count_params[] = $id_val;
            }
        } else {
            $query .= " AND 1=0";
            $count_query .= " AND 1=0";
        }
    } else {
        $query .= " AND 1=0";
        $count_query .= " AND 1=0";
    }
}

if (!empty($search)) {
    $query .= " AND (e.title ILIKE ? OR e.location ILIKE ?)";
    $params[] = "%$search%";
    $params[] = "%$search%";
    
    $count_query .= " AND (e.title ILIKE ? OR e.location ILIKE ?)";
    $count_params[] = "%$search%";
    $count_params[] = "%$search%";
}

// Pagination offset calculations
$limit = 10;
$page = isset($_GET['page']) ? max(1, (int)$_GET['page']) : 1;
$offset = ($page - 1) * $limit;
$total_records = 0;
$total_pages = 0;

try {
    // Execute count query
    $stmt_count = $pdo->prepare($count_query);
    $stmt_count->execute($count_params);
    $total_records = (int)$stmt_count->fetchColumn() ?: 0;
    $total_pages = ceil($total_records / $limit);

    // Fetch paginated records
    $query .= " GROUP BY e.id, u.username ORDER BY e.start_date ASC LIMIT $limit OFFSET $offset";
    $stmt = $pdo->prepare($query);
    $stmt->execute($params);
    $events = $stmt->fetchAll();
} catch (PDOException $e) {
    $events = [];
    $error = "Failed to load events: " . $e->getMessage();
}

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

<!-- Portal Header & Actions -->
<div class="d-flex flex-column flex-md-row justify-content-between align-items-md-center gap-3 mb-4">
    <div>
        <h1 class="h2 fw-bold text-dark mb-1">Start Here</h1>
        <p class="text-muted mb-0">Start Your Journey from here</p>
    </div>
    <?php if ($isAdmin): ?>
        <div>
            <button type="button" class="btn btn-primary px-4 py-2.5 fw-bold shadow-sm" data-bs-toggle="modal" data-bs-target="#eventModal">
                <i class="bi bi-calendar-plus me-1"></i> Create New Event
            </button>
        </div>
    <?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; ?>

<!-- Search & Filters Card -->
<div class="card border-0 shadow-sm mb-4">
    <div class="card-body py-3">
        <form method="GET" action="events" class="row g-2">
            <div class="col-12 col-md-10">
                <div class="input-group">
                    <span class="input-group-text bg-white text-muted"><i class="bi bi-search"></i></span>
                    <input type="text" class="form-control" name="search" placeholder="Search by title or location..." value="<?php echo htmlspecialchars($search); ?>">
                </div>
            </div>
            <div class="col-12 col-md-2 d-grid">
                <button type="submit" class="btn btn-outline-primary">Search</button>
            </div>
        </form>
    </div>
</div>

<!-- Event Listings Cards Grid -->
<?php if (empty($events)): ?>
    <div class="card border-0 shadow-sm py-5 text-center text-muted">
        <div class="card-body">
            <i class="bi bi-calendar2-x fs-1 mb-2"></i>
            <p class="mb-0">No events found matching search criteria.</p>
        </div>
    </div>
<?php else: ?>
<style>
/* Modern Premium Event Card Styling */
.event-card {
    border: none;
    border-radius: 16px;
    background: #ffffff;
    box-shadow: 0 4px 20px rgba(0, 0, 0, 0.03);
    transition: all 0.3s cubic-bezier(0.16, 1, 0.3, 1);
    overflow: hidden;
    display: flex;
    flex-direction: column;
    height: 100%;
}
.event-card:hover {
    transform: translateY(-6px);
    box-shadow: 0 12px 30px rgba(13, 110, 253, 0.07), 0 4px 12px rgba(0, 0, 0, 0.02);
}
.event-card-banner {
    position: relative;
    height: 190px;
    overflow: hidden;
    background: #e9ecef;
}
.event-card-img {
    width: 100%;
    height: 100%;
    object-fit: cover;
    transition: transform 0.6s cubic-bezier(0.16, 1, 0.3, 1);
}
.event-card:hover .event-card-img {
    transform: scale(1.06);
}
.event-card-date {
    position: absolute;
    top: 16px;
    right: 16px;
    z-index: 10;
    width: 52px;
    height: 56px;
    background: rgba(255, 255, 255, 0.95);
    backdrop-filter: blur(8px);
    border-radius: 12px;
    box-shadow: 0 4px 10px rgba(0, 0, 0, 0.06);
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
}
.event-card-date .month {
    font-size: 0.62rem;
    font-weight: 800;
    color: #0d6efd;
    text-transform: uppercase;
    line-height: 1;
    letter-spacing: 0.8px;
    margin-bottom: 2px;
}
.event-card-date .day {
    font-size: 1.2rem;
    font-weight: 800;
    color: #1e293b;
    line-height: 1;
}
.event-card-body {
    padding: 20px;
    flex-grow: 1;
    display: flex;
    flex-direction: column;
}
.event-card-title {
    font-size: 1.15rem;
    font-weight: 700;
    line-height: 1.4;
    margin-bottom: 12px;
}
.event-card-title a {
    color: #1e293b;
    text-decoration: none;
    transition: color 0.2s ease;
}
.event-card-title a:hover {
    color: #0d6efd;
}
.event-card-meta {
    font-size: 0.82rem;
    color: #64748b;
    margin-bottom: 8px;
    display: flex;
    align-items: center;
    gap: 8px;
}
.event-card-meta i {
    color: #0d6efd;
    font-size: 0.9rem;
}
.event-card-desc {
    font-size: 0.85rem;
    color: #475569;
    line-height: 1.5;
    margin-top: 10px;
    margin-bottom: 0;
    display: -webkit-box;
    -webkit-line-clamp: 3;
    -webkit-box-orient: vertical;
    overflow: hidden;
    text-overflow: ellipsis;
}
.event-card-footer {
    padding: 0 20px 20px 20px;
    background: transparent;
    border-top: none;
    display: flex;
    justify-content: space-between;
    align-items: center;
    gap: 8px;
}
</style>

    <div class="row g-4">
        <?php foreach ($events as $event): ?>
            <?php 
                $isPast = strtotime($event['end_date']) < time(); 
                $isFull = ($event['capacity'] > 0 && $event['attendee_count'] >= $event['capacity']);
                $bannerImg = !empty($event['banner_url']) ? $event['banner_url'] : 'https://images.unsplash.com/photo-1517245386807-bb43f82c33c4?w=600&auto=format&fit=crop';
                
                $start_ts = strtotime($event['start_date']);
                $day = date('d', $start_ts);
                $month = date('M', $start_ts);
            ?>
            <div class="col-12 col-md-6 col-xl-4">
                <div class="event-card" onclick="if(!event.target.closest('a') && !event.target.closest('button')) { window.location.href='event/<?php echo $event['id']; ?>'; }">
                    <!-- Banner Image with Badges -->
                    <div class="event-card-banner">
                        <img src="<?php echo htmlspecialchars($bannerImg); ?>" class="event-card-img" alt="Event Banner">
                        
                        <!-- Premium Calendar Badge -->
                        <div class="event-card-date">
                            <span class="month"><?php echo $month; ?></span>
                            <span class="day"><?php echo $day; ?></span>
                        </div>

                        <!-- Status and Price Overlay Badges -->
                        <div class="position-absolute top-0 start-0 p-3 d-flex flex-column gap-1.5" style="z-index: 2;">
                            <span class="badge text-white font-monospace text-uppercase" style="background: rgba(0, 0, 0, 0.55); backdrop-filter: blur(8px); font-size: 0.65rem; border: 1px solid rgba(255, 255, 255, 0.15);">
                                <?php echo strtoupper($event['event_type']); ?>
                            </span>
                            <?php if ($event['payment_type'] === 'paid'): ?>
                                <span class="badge text-white font-monospace" style="background: rgba(13, 110, 253, 0.65); backdrop-filter: blur(8px); font-size: 0.65rem; border: 1px solid rgba(255, 255, 255, 0.2);">
                                    ₹<?php echo number_format($event['price'], 2); ?> 
                                    <span style="font-size: 0.55rem;"><?php echo $event['gst_option'] === 'including' ? 'Incl.' : 'Excl.'; ?> GST</span>
                                </span>
                            <?php else: ?>
                                <span class="badge text-white font-monospace" style="background: rgba(25, 135, 84, 0.65); backdrop-filter: blur(8px); font-size: 0.65rem; border: 1px solid rgba(255, 255, 255, 0.2);">FREE</span>
                            <?php endif; ?>
                            
                            <?php if ($isAdmin): ?>
                                <?php if ($event['status'] === 'published'): ?>
                                    <span class="badge bg-success bg-opacity-75 text-white font-monospace" style="font-size: 0.65rem;"><i class="bi bi-globe me-1"></i>Published</span>
                                <?php else: ?>
                                    <span class="badge bg-warning bg-opacity-75 text-dark font-monospace" style="font-size: 0.65rem;"><i class="bi bi-file-earmark-lock me-1"></i>Draft</span>
                                <?php endif; ?>
                            <?php endif; ?>
                            <?php if ($isPast): ?>
                                <span class="badge bg-secondary bg-opacity-75" style="font-size: 0.65rem;">Past</span>
                            <?php elseif ($event['user_registration_status'] === 'registered'): ?>
                                <span class="badge bg-success" style="font-size: 0.65rem;"><i class="bi bi-check-circle me-1"></i>RSVP'd</span>
                            <?php elseif ($event['user_registration_status'] === 'waitlisted'): ?>
                                <span class="badge bg-warning text-dark" style="font-size: 0.65rem;"><i class="bi bi-clock-history me-1"></i>Waitlist</span>
                            <?php elseif ($isFull): ?>
                                <span class="badge bg-danger" style="font-size: 0.65rem;">Full</span>
                            <?php endif; ?>
                        </div>
                    </div>

                    <!-- Card Body -->
                    <div class="event-card-body">
                        <h5 class="event-card-title">
                            <a href="event/<?php echo $event['id']; ?>">
                                <?php echo htmlspecialchars($event['title']); ?>
                            </a>
                        </h5>
                        
                        <div class="event-card-meta">
                            <i class="bi bi-calendar3"></i>
                            <span><?php echo formatEventDateRange($event['start_date'], $event['end_date']); ?></span>
                        </div>

                        <div class="event-card-meta">
                            <i class="bi bi-geo-alt"></i>
                            <span class="text-truncate" style="max-width: 250px;"><?php echo htmlspecialchars($event['location']); ?></span>
                        </div>

                        <?php if ($currentUser['role'] !== 'user'): ?>
                            <div class="event-card-meta">
                                <i class="bi bi-people"></i>
                                <span><?php echo $event['attendee_count']; ?> / <?php echo $event['capacity'] > 0 ? $event['capacity'] : '&infin;'; ?> registered</span>
                            </div>
                        <?php else: ?>
                            <div class="event-card-meta">
                                <i class="bi bi-people"></i>
                                <span><?php echo $event['capacity'] > 0 ? htmlspecialchars($event['capacity']) . ' seat capacity' : 'Unlimited seats'; ?></span>
                            </div>
                        <?php endif; ?>

                        <p class="event-card-desc">
                            <?php echo htmlspecialchars(substr($event['description'], 0, 160)) . (strlen($event['description']) > 160 ? '...' : ''); ?>
                        </p>
                    </div>

                    <!-- Card Footer Actions -->
                    <div class="event-card-footer">
                        <a href="event/<?php echo $event['id']; ?>" class="btn btn-outline-primary btn-sm flex-grow-1 fw-bold rounded-pill">
                            <i class="bi bi-info-circle me-1"></i> Details
                        </a>
                        <div class="dropdown d-inline-block">
                            <button type="button" class="btn btn-outline-secondary btn-sm rounded-circle d-flex align-items-center justify-content-center" style="width: 32px; height: 32px;" data-bs-toggle="dropdown" aria-expanded="false" title="Share Event with Referral Link">
                                <i class="bi bi-share-fill" style="font-size: 0.8rem;"></i>
                            </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>
                        <?php if ($event['user_registration_status'] === 'registered' && $event['payment_type'] === 'paid'): ?>
                            <a href="invoice/<?php echo $event['id']; ?>" target="_blank" class="btn btn-outline-success btn-sm rounded-circle d-flex align-items-center justify-content-center" style="width: 32px; height: 32px;" title="Tax Invoice">
                                <i class="bi bi-file-earmark-pdf-fill" style="font-size: 0.85rem;"></i>
                            </a>
                        <?php endif; ?>
                        <?php if ($isAdmin): ?>
                            <a href="events?edit_id=<?php echo $event['id']; ?>" class="btn btn-outline-warning btn-sm rounded-circle d-flex align-items-center justify-content-center" style="width: 32px; height: 32px;" title="Edit">
                                <i class="bi bi-pencil-fill" style="font-size: 0.8rem;"></i>
                            </a>
                            <a href="events?action=delete&id=<?php echo $event['id']; ?>&csrf_token=<?php echo getCSRFToken(); ?>" class="btn btn-outline-danger btn-sm rounded-circle d-flex align-items-center justify-content-center" style="width: 32px; height: 32px;" title="Delete" onclick="return confirmRecurringDelete(event, <?php echo $event['is_recurring'] ? 'true' : 'false'; ?>, '<?php echo $event['id']; ?>', '<?php echo getCSRFToken(); ?>');">
                                <i class="bi bi-trash-fill" style="font-size: 0.8rem;"></i>
                            </a>
                        <?php endif; ?>
                    </div>
                </div>
            </div>
        <?php endforeach; ?>
    </div>

    <!-- Pagination -->
    <?php if ($total_pages > 1): ?>
        <div class="d-flex flex-column flex-md-row justify-content-between align-items-center mt-5 gap-3">
            <div class="small text-secondary font-monospace">
                Showing <?php echo $offset + 1; ?> to <?php echo min($offset + $limit, $total_records); ?> of <?php echo $total_records; ?> events
            </div>
            <nav aria-label="Page navigation">
                <ul class="pagination pagination-sm mb-0">
                    <li class="page-item <?php echo $page <= 1 ? 'disabled' : ''; ?>">
                        <a class="page-link" href="?<?php echo http_build_query(array_merge($_GET, ['page' => $page - 1])); ?>"><i class="bi bi-chevron-left"></i></a>
                    </li>
                    <?php
                    $start = max(1, $page - 2);
                    $end = min($total_pages, $page + 2);
                    for ($i = $start; $i <= $end; $i++):
                    ?>
                        <li class="page-item <?php echo $page === $i ? 'active' : ''; ?>">
                            <a class="page-link" href="?<?php echo http_build_query(array_merge($_GET, ['page' => $i])); ?>"><?php echo $i; ?></a>
                        </li>
                    <?php endfor; ?>
                    <li class="page-item <?php echo $page >= $total_pages ? 'disabled' : ''; ?>">
                        <a class="page-link" href="?<?php echo http_build_query(array_merge($_GET, ['page' => $page + 1])); ?>"><i class="bi bi-chevron-right"></i></a>
                    </li>
                </ul>
            </nav>
        </div>
    <?php endif; ?>
<?php endif; ?>

<!-- Multistep Create/Edit Event Modal Dialog (Visible to Admin/Organizer Only) -->
<?php if ($isAdmin): ?>
<div class="modal fade" id="eventModal" tabindex="-1" aria-labelledby="eventModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-lg">
        <form method="POST" action="events" id="eventForm" class="modal-content" enctype="multipart/form-data">
            <input type="hidden" name="csrf_token" value="<?php echo getCSRFToken(); ?>">
            <div class="modal-header bg-light">
                <h5 class="modal-title fw-bold" id="eventModalLabel">
                    <?php if ($editEvent): ?>
                        <i class="bi bi-calendar2-event-fill me-2 text-warning"></i>Edit Event Listing
                    <?php else: ?>
                        <i class="bi bi-calendar-plus-fill me-2 text-primary"></i>Create New Event
                    <?php endif; ?>
                </h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            
            <div class="modal-body px-4">
                <!-- Stepper Progress Bar Indicator (4 Steps) -->
                <div class="stepper mb-4 d-flex justify-content-around border-bottom pb-3">
                    <div class="step-item text-center active" id="step-badge-1" style="flex: 1;">
                        <span class="badge rounded-circle p-2 px-3 bg-primary text-white">1</span>
                        <div class="small mt-1 fw-bold">General Info</div>
                    </div>
                    <div class="step-item text-center text-muted" id="step-badge-2" style="flex: 1;">
                        <span class="badge rounded-circle p-2 px-3 bg-secondary text-white">2</span>
                        <div class="small mt-1">Schedule & Type</div>
                    </div>
                    <div class="step-item text-center text-muted" id="step-badge-3" style="flex: 1;">
                        <span class="badge rounded-circle p-2 px-3 bg-secondary text-white">3</span>
                        <div class="small mt-1">Access Details</div>
                    </div>
                    <div class="step-item text-center text-muted" id="step-badge-4" style="flex: 1;">
                        <span class="badge rounded-circle p-2 px-3 bg-secondary text-white">4</span>
                        <div class="small mt-1">Agenda Builder</div>
                    </div>
                </div>

                <?php if ($editEvent): ?>
                    <input type="hidden" name="edit_id" value="<?php echo $editEvent['id']; ?>">
                <?php endif; ?>

                <input type="hidden" name="agenda_json" id="agenda_json" value="[]">

                <!-- Step 1: General Info -->
                <div id="step-1" class="modal-step">
                    <div class="mb-3">
                        <label for="title" class="form-label">Event Title <span class="text-danger">*</span></label>
                        <input type="text" class="form-control" id="title" name="title" required placeholder="e.g. Annual Tech Meetup" value="<?php echo htmlspecialchars($editEvent['title'] ?? ''); ?>">
                        <div class="invalid-feedback">Please enter a valid title.</div>
                    </div>

                    <!-- Drag & Drop Image Zone Component -->
                    <div class="mb-3">
                        <label class="form-label">Event Banner Image</label>
                        
                        <div id="drop-zone" class="border border-2 border-dashed rounded-3 p-4 text-center bg-white cursor-pointer position-relative mb-2" style="border-color: #dee2e6 !important; transition: border-color 0.25s, background-color 0.25s;">
                            <input type="file" id="banner_file" name="banner_file" accept="image/*" class="position-absolute top-0 start-0 w-100 h-100 opacity-0 cursor-pointer" style="z-index: 5;">
                            
                            <div id="drop-zone-prompt">
                                <i class="bi bi-cloud-arrow-up-fill text-primary fs-1 mb-2 d-block"></i>
                                <span class="fw-bold">Drag and drop banner image here</span>
                                <span class="text-muted d-block small mt-1">or click to browse files</span>
                                <span class="text-muted d-block small font-monospace mt-1" style="font-size: 0.7rem;">PNG, JPG, JPEG, GIF up to 5MB</span>
                            </div>
                            
                            <div id="drop-zone-preview" style="display: none;">
                                <img id="preview-image" src="" alt="Preview" class="img-fluid rounded border shadow-sm mb-2" style="max-height: 120px; object-fit: cover;">
                                <div class="d-flex justify-content-center gap-2 align-items-center">
                                    <span class="small text-muted font-monospace" id="preview-filename"></span>
                                    <button type="button" class="btn btn-sm btn-outline-danger py-0 px-2 small" onclick="removeUploadedFile(event)"><i class="bi bi-x"></i> Remove</button>
                                </div>
                            </div>
                        </div>
                        
                        <!-- URL Fallback Option (Accordion) -->
                        <div class="accordion border-0" id="urlFallbackAccordion">
                            <div class="accordion-item border-0">
                                <h2 class="accordion-header">
                                    <button class="accordion-button collapsed py-2 px-0 bg-transparent shadow-none border-0 text-primary small" type="button" data-bs-toggle="collapse" data-bs-target="#urlFallbackCollapse" aria-expanded="false" aria-controls="urlFallbackCollapse" style="font-size: 0.8rem; min-height: 0;">
                                        Or specify an external Image URL instead
                                    </button>
                                </h2>
                                <div id="urlFallbackCollapse" class="accordion-collapse collapse" data-bs-parent="#urlFallbackAccordion">
                                    <div class="pt-2">
                                        <input type="url" class="form-control form-control-sm" id="banner_url" name="banner_url" placeholder="https://example.com/banner.jpg" value="<?php echo htmlspecialchars($editEvent['banner_url'] ?? ''); ?>">
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>

                    <div class="mb-3">
                        <label for="attachment_file" class="form-label fw-bold">Event Resource File (Downloadable)</label>
                        <input type="file" class="form-control" id="attachment_file" name="attachment_file" accept=".pdf,.doc,.docx,.zip,.pptx,.ppt,.txt,.xls,.xlsx">
                        <div class="form-text small text-muted">Upload any presentation slides, event brochures, manuals, or worksheets (PDF, DOCX, ZIP, PPTX - Max 10MB).</div>
                        <?php if (isset($editEvent) && !empty($editEvent['attachment_url'])): ?>
                            <div class="form-text text-success d-flex align-items-center mt-1">
                                <i class="bi bi-file-earmark-check-fill me-1"></i> Current Resource: 
                                <a href="<?php echo htmlspecialchars($editEvent['attachment_url']); ?>" target="_blank" class="text-success text-decoration-underline ms-1 font-monospace small">
                                    <?php echo htmlspecialchars(basename($editEvent['attachment_url'])); ?>
                                </a>
                            </div>
                        <?php endif; ?>
                    </div>

                    <div class="mb-2">
                        <label for="description" class="form-label">Event Description</label>
                        <textarea class="form-control" id="description" name="description" rows="4" placeholder="Detail the speakers, schedule, etc."><?php echo htmlspecialchars($editEvent['description'] ?? ''); ?></textarea>
                    </div>
                </div>

                <!-- Step 2: Schedule & Type -->
                <div id="step-2" class="modal-step" style="display: none;">
                    <div class="row g-3 mb-3">
                        <div class="col-12 col-sm-6">
                            <label for="start_date" class="form-label">Start Date & Time <span class="text-danger">*</span></label>
                            <input type="datetime-local" class="form-control" id="start_date" name="start_date" required value="<?php echo htmlspecialchars($editEvent['start_date_formatted'] ?? ''); ?>">
                            <div class="invalid-feedback">Please select a valid start date.</div>
                        </div>
                        <div class="col-12 col-sm-6">
                            <label for="end_date" class="form-label">End Date & Time <span class="text-danger">*</span></label>
                            <input type="datetime-local" class="form-control" id="end_date" name="end_date" required value="<?php echo htmlspecialchars($editEvent['end_date_formatted'] ?? ''); ?>">
                            <div class="invalid-feedback">Please select a valid end date.</div>
                        </div>
                    </div>

                    <div class="row g-3 mb-2">
                        <div class="col-12 col-sm-6">
                            <label for="event_type" class="form-label">Event Type <span class="text-danger">*</span></label>
                            <select class="form-select" id="event_type" name="event_type" required onchange="toggleEventFields()">
                                <option value="physical" <?php echo isset($editEvent) && $editEvent['event_type'] === 'physical' ? 'selected' : ''; ?>>Physical (In-Person)</option>
                                <option value="virtual" <?php echo isset($editEvent) && $editEvent['event_type'] === 'virtual' ? 'selected' : ''; ?>>Virtual (Online)</option>
                                <option value="hybrid" <?php echo isset($editEvent) && $editEvent['event_type'] === 'hybrid' ? 'selected' : ''; ?>>Hybrid (In-Person & Online)</option>
                            </select>
                        </div>
                        <div class="col-12 col-sm-6">
                            <label for="capacity" class="form-label">Max Seating Capacity <span class="text-muted small">(0 for unlimited)</span></label>
                            <input type="number" class="form-control" id="capacity" name="capacity" min="0" value="<?php echo htmlspecialchars($editEvent['capacity'] ?? 0); ?>">
                        </div>
                    </div>

                    <div class="row g-3 mb-2 border-top pt-2 mt-2">
                        <div class="col-12 col-sm-4">
                            <label for="payment_type" class="form-label">Pricing Type <span class="text-danger">*</span></label>
                            <select class="form-select" id="payment_type" name="payment_type" required onchange="togglePricingFields()">
                                <option value="free" <?php echo isset($editEvent) && $editEvent['payment_type'] === 'free' ? 'selected' : ''; ?>>Free Event</option>
                                <option value="paid" <?php echo isset($editEvent) && $editEvent['payment_type'] === 'paid' ? 'selected' : ''; ?>>Paid Event</option>
                            </select>
                        </div>
                        <div class="col-12 col-sm-4" id="price_container" style="<?php echo isset($editEvent) && $editEvent['payment_type'] === 'paid' ? '' : 'display: none;'; ?>">
                            <label for="price" class="form-label">Ticket Price (₹) <span class="text-danger">*</span></label>
                            <input type="number" step="0.01" class="form-control" id="price" name="price" value="<?php echo htmlspecialchars($editEvent['price'] ?? '0.00'); ?>">
                        </div>
                        <div class="col-12 col-sm-4" id="gst_container" style="<?php echo isset($editEvent) && $editEvent['payment_type'] === 'paid' ? '' : 'display: none;'; ?>">
                            <label for="gst_option" class="form-label">GST Configuration <span class="text-danger">*</span></label>
                            <select class="form-select" id="gst_option" name="gst_option">
                                <option value="excluding" <?php echo isset($editEvent) && $editEvent['gst_option'] === 'excluding' ? 'selected' : ''; ?>>Excluding GST (Tax Added)</option>
                                <option value="including" <?php echo isset($editEvent) && $editEvent['gst_option'] === 'including' ? 'selected' : ''; ?>>Including GST (Tax Included)</option>
                            </select>
                        </div>
                    </div>

                    <!-- Event Based Payment Gateway Fields -->
                    <div class="row g-3 mb-2 border-top pt-2 mt-2" id="razorpay_gateway_container" style="<?php echo isset($editEvent) && $editEvent['payment_type'] === 'paid' ? '' : 'display: none;'; ?>">
                        <div class="col-12 col-sm-6">
                            <label for="razorpay_key_id" class="form-label">Event Razorpay Key ID <span class="text-muted small">(Fallback to Global if blank)</span></label>
                            <input type="text" class="form-control" id="razorpay_key_id" name="razorpay_key_id" value="<?php echo htmlspecialchars($editEvent['razorpay_key_id'] ?? ''); ?>" placeholder="rzp_test_...">
                        </div>
                        <div class="col-12 col-sm-6">
                            <label for="razorpay_key_secret" class="form-label">Event Razorpay Key Secret <span class="text-muted small">(Fallback to Global if blank)</span></label>
                            <input type="password" class="form-control" id="razorpay_key_secret" name="razorpay_key_secret" value="<?php echo htmlspecialchars($editEvent['razorpay_key_secret'] ?? ''); ?>" placeholder="Fallback to Global Secret">
                        </div>
                    </div>

                    <div class="row g-3 mb-2 border-top pt-2 mt-2">
                        <div class="col-12 col-sm-6">
                            <label for="status" class="form-label fw-bold">Publication Status <span class="text-danger">*</span></label>
                            <select class="form-select" id="status" name="status" required>
                                <option value="draft" <?php echo isset($editEvent) && $editEvent['status'] === 'draft' ? 'selected' : ''; ?>>Draft (Hidden from Users)</option>
                                <option value="published" <?php echo isset($editEvent) && $editEvent['status'] === 'published' ? 'selected' : ''; ?>>Published (Visible to Users)</option>
                            </select>
                            <div class="form-text small text-muted">Draft events are only visible to organizers and administrators.</div>
                        </div>
                    </div>

                    <div class="row g-3 mb-2 border-top pt-2 mt-2">
                        <div class="col-12">
                            <div class="form-check form-switch py-1">
                                <input class="form-check-input" type="checkbox" role="switch" id="is_recurring" name="is_recurring" value="1" onchange="toggleRecurrenceFields()" <?php echo isset($editEvent) && $editEvent['is_recurring'] ? 'checked' : ''; ?>>
                                <label class="form-check-label fw-bold text-secondary" for="is_recurring">Set as Recurring Event</label>
                            </div>
                        </div>
                        <div class="col-12 col-sm-6 recurrence-fields" style="<?php echo isset($editEvent) && $editEvent['is_recurring'] ? '' : 'display: none;'; ?>">
                            <label for="recurrence_pattern" class="form-label">Recurrence Pattern</label>
                            <select class="form-select" id="recurrence_pattern" name="recurrence_pattern">
                                <option value="daily" <?php echo isset($editEvent) && $editEvent['recurrence_pattern'] === 'daily' ? 'selected' : ''; ?>>Daily</option>
                                <option value="weekly" <?php echo isset($editEvent) && $editEvent['recurrence_pattern'] === 'weekly' ? 'selected' : ''; ?>>Weekly</option>
                                <option value="monthly" <?php echo isset($editEvent) && $editEvent['recurrence_pattern'] === 'monthly' ? 'selected' : ''; ?>>Monthly</option>
                            </select>
                        </div>
                        <div class="col-12 col-sm-6 recurrence-fields" style="<?php echo isset($editEvent) && $editEvent['is_recurring'] ? '' : 'display: none;'; ?>">
                            <label for="recurrence_end_date" class="form-label">Recurrence End Date <span class="text-danger">*</span></label>
                            <input type="datetime-local" class="form-control" id="recurrence_end_date" name="recurrence_end_date" value="<?php echo isset($editEvent['recurrence_end_date']) ? date('Y-m-d\TH:i', strtotime($editEvent['recurrence_end_date'])) : ''; ?>">
                        </div>
                    </div>
                </div>

                <!-- Step 3: Location / Webcast Details -->
                <div id="step-3" class="modal-step" style="display: none;">
                    <!-- Physical / Hybrid Fields -->
                    <div id="physical_fields" class="p-3 bg-light rounded border border-light-subtle mb-3">
                        <h6 class="fw-bold mb-2 text-dark"><i class="bi bi-geo-alt-fill me-1 text-danger"></i> Physical Location Fields</h6>
                        <div class="mb-2">
                            <label for="location" class="form-label small">Venue Location/Address <span class="text-danger">*</span></label>
                            <input type="text" class="form-control form-control-sm" id="location" name="location" placeholder="e.g. Grand Convention Center Room 101" value="<?php echo htmlspecialchars($editEvent['location'] ?? ''); ?>">
                            <div class="invalid-feedback">Please enter a venue address.</div>
                        </div>
                        <div>
                            <label for="google_map_embed" class="form-label small">Google Map Embed Code (IFrame) or Map URL</label>
                            <textarea class="form-control form-control-sm font-monospace" id="google_map_embed" name="google_map_embed" rows="3" placeholder='<iframe src="..." ...></iframe>'><?php echo htmlspecialchars($editEvent['google_map_embed'] ?? ''); ?></textarea>
                        </div>
                    </div>

                    <!-- Virtual / Hybrid Fields -->
                    <div id="virtual_fields" class="p-3 bg-light rounded border border-light-subtle mb-2">
                        <h6 class="fw-bold mb-2 text-dark"><i class="bi bi-laptop-fill me-1 text-primary"></i> Virtual Conference Fields</h6>
                        <div class="mb-2">
                            <label for="virtual_platform" class="form-label small">Streaming Platform <span class="text-danger">*</span></label>
                            <select class="form-select form-select-sm" id="virtual_platform" name="virtual_platform" onchange="toggleZoomGenerator()">
                                <option value="zoom" <?php echo isset($editEvent) && $editEvent['virtual_platform'] === 'zoom' ? 'selected' : ''; ?>>Zoom Meetings</option>
                                <option value="meet" <?php echo isset($editEvent) && $editEvent['virtual_platform'] === 'meet' ? 'selected' : ''; ?>>Google Meet</option>
                                <option value="teams" <?php echo isset($editEvent) && $editEvent['virtual_platform'] === 'teams' ? 'selected' : ''; ?>>Microsoft Teams</option>
                                <option value="other" <?php echo isset($editEvent) && $editEvent['virtual_platform'] === 'other' ? 'selected' : ''; ?>>Other Platform</option>
                            </select>
                        </div>
                        <div class="form-check form-switch mb-2" id="zoom_generator_switch">
                            <input class="form-check-input" type="checkbox" role="switch" id="auto_zoom" name="auto_zoom" value="1" onchange="toggleZoomInput()">
                            <label class="form-check-label small text-muted fw-bold" for="auto_zoom">Auto-generate Zoom Meeting Link</label>
                        </div>
                        <div id="virtual_link_container">
                            <label for="virtual_link" class="form-label small">Virtual Meeting URL</label>
                            <input type="url" class="form-control form-control-sm" id="virtual_link" name="virtual_link" placeholder="https://zoom.us/j/..." value="<?php echo htmlspecialchars($editEvent['virtual_link'] ?? ''); ?>">
                        </div>
                    </div>
                </div>

                <!-- Step 4: Agenda Builder -->
                <div id="step-4" class="modal-step" style="display: none;">
                    <div class="p-3 bg-light rounded border border-light-subtle mb-3">
                        <h6 class="fw-bold mb-2 text-primary"><i class="bi bi-calendar-plus me-1"></i> Add Session to Agenda</h6>
                        
                        <div class="row g-2 mb-2">
                            <div class="col-12 col-md-4">
                                <label for="agenda_item_date" class="form-label small mb-1">Session Date</label>
                                <select class="form-select form-select-sm" id="agenda_item_date"></select>
                            </div>
                            <div class="col-6 col-md-4">
                                <label for="agenda_item_start_time" class="form-label small mb-1">Start Time</label>
                                <input type="time" class="form-control form-control-sm" id="agenda_item_start_time">
                            </div>
                            <div class="col-6 col-md-4">
                                <label for="agenda_item_end_time" class="form-label small mb-1">End Time</label>
                                <input type="time" class="form-control form-control-sm" id="agenda_item_end_time">
                            </div>
                        </div>

                        <div class="mb-2">
                            <label for="agenda_item_title" class="form-label small mb-1">Session Title <span class="text-danger">*</span></label>
                            <input type="text" class="form-control form-control-sm" id="agenda_item_title" placeholder="e.g. Core Seminar / Lunch Break">
                        </div>

                        <div class="row g-2 mb-2">
                            <div class="col-12 col-md-6">
                                <label for="agenda_item_speaker_profile_id" class="form-label small mb-1">Speaker Assignment</label>
                                <select class="form-select form-select-sm" id="agenda_item_speaker_profile_id" onchange="toggleWizardGuestSpeakerInput()">
                                    <option value="">-- No Speaker Assigned --</option>
                                    <optgroup label="Registered Speaker Profiles">
                                        <?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="Guest Options">
                                        <option value="external">Add Guest Speaker</option>
                                    </optgroup>
                                </select>
                            </div>
                            <div class="col-12 col-md-6" id="wizard_external_speaker_container" style="display: none;">
                                <label for="agenda_item_speaker" class="form-label small mb-1">Guest Speaker Name</label>
                                <input type="text" class="form-control form-control-sm" id="agenda_item_speaker" placeholder="Alex Rivera">
                            </div>
                        </div>

                        <div class="mb-2">
                            <label for="agenda_item_desc" class="form-label small mb-1">Session Description / Summary</label>
                            <textarea class="form-control form-control-sm" id="agenda_item_desc" rows="2" placeholder="Brief outline of the topic..."></textarea>
                        </div>

                        <button type="button" class="btn btn-primary btn-sm px-3 mt-2 fw-bold" onclick="addAgendaSessionToWizard(event)">
                            <i class="bi bi-plus-circle me-1"></i> Add Session
                        </button>
                    </div>

                    <!-- Agenda Items Preview Table List -->
                    <h6 class="fw-bold mb-2"><i class="bi bi-list-ol me-1 text-primary"></i> Added Agenda Sessions:</h6>
                    <div class="table-responsive border rounded" style="max-height: 200px; overflow-y: auto;">
                        <table class="table table-sm table-hover align-middle mb-0">
                            <thead class="table-light text-muted uppercase font-monospace" style="font-size: 0.7rem;">
                                <tr>
                                    <th class="ps-3">Session Title</th>
                                    <th>Date</th>
                                    <th>Time</th>
                                    <th>Speaker</th>
                                    <th class="text-end pe-3">Actions</th>
                                </tr>
                            </thead>
                            <tbody id="agenda-sessions-tbody">
                                <tr>
                                    <td colspan="5" class="text-center py-3 text-muted small">No agenda sessions added yet.</td>
                                </tr>
                            </tbody>
                        </table>
                    </div>
                </div>

            </div>
            
            <div class="modal-footer d-flex justify-content-between">
                <div>
                    <button type="button" class="btn btn-outline-secondary text-danger border-danger border-opacity-25 bg-danger bg-opacity-10" data-bs-dismiss="modal">Cancel</button>
                </div>
                <div class="d-flex gap-2">
                    <button type="button" class="btn btn-secondary" id="btn-prev" onclick="handlePrev()" style="display: none;">&larr; Back</button>
                    <button type="button" class="btn btn-primary px-4" id="btn-next" onclick="handleNext()">Next &rarr;</button>
                    <?php if ($editEvent): ?>
                        <button type="submit" name="submit_edit" class="btn btn-warning px-4 fw-bold" id="btn-submit" style="display: none;"><i class="bi bi-save me-1"></i> Save Changes</button>
                    <?php else: ?>
                        <button type="submit" name="submit_add" class="btn btn-success px-4 fw-bold" id="btn-submit" style="display: none;"><i class="bi bi-calendar-plus me-1"></i> Create Event</button>
                    <?php endif; ?>
                </div>
            </div>
        </form>
    </div>
</div>

<script>
    let currentStep = 1;
    let agendaSessions = [];

    function goToStep(stepNum) {
        // Hide current step
        document.getElementById('step-' + currentStep).style.display = 'none';
        document.getElementById('step-badge-' + currentStep).classList.remove('active', 'fw-bold');
        document.getElementById('step-badge-' + currentStep).classList.add('text-muted');
        document.getElementById('step-badge-' + currentStep).querySelector('.badge').classList.replace('bg-primary', 'bg-secondary');

        // Show new step
        document.getElementById('step-' + stepNum).style.display = 'block';
        document.getElementById('step-badge-' + stepNum).classList.add('active', 'fw-bold');
        document.getElementById('step-badge-' + stepNum).classList.remove('text-muted');
        document.getElementById('step-badge-' + stepNum).querySelector('.badge').classList.replace('bg-secondary', 'bg-primary');

        currentStep = stepNum;

        // Dynamic Calculations when entering step 4
        if (currentStep === 4) {
            populateAgendaDates();
        }

        // Toggle buttons in footer
        document.getElementById('btn-prev').style.display = currentStep === 1 ? 'none' : 'inline-block';
        document.getElementById('btn-next').style.display = currentStep === 4 ? 'none' : 'inline-block';
        document.getElementById('btn-submit').style.display = currentStep === 4 ? 'inline-block' : 'none';
    }

    function validateStep(stepNum) {
        const stepEl = document.getElementById('step-' + stepNum);
        // Validate only visible elements that have the required attribute (offsetParent !== null is true if visible)
        const requiredFields = Array.from(stepEl.querySelectorAll('[required]')).filter(field => field.offsetParent !== null);
        let isValid = true;
        
        requiredFields.forEach(field => {
            if (!field.value.trim()) {
                field.classList.add('is-invalid');
                isValid = false;
            } else {
                field.classList.remove('is-invalid');
            }
        });
        return isValid;
    }

    function handleNext() {
        if (validateStep(currentStep)) {
            goToStep(currentStep + 1);
        }
    }

    function handlePrev() {
        goToStep(currentStep - 1);
    }

    // Step 4 Helper to dynamically populate dates
    function populateAgendaDates() {
        const startVal = document.getElementById('start_date').value;
        const endVal = document.getElementById('end_date').value;
        const select = document.getElementById('agenda_item_date');
        
        if (!startVal || !endVal) return;
        
        const start = new Date(startVal.substring(0, 10));
        const end = new Date(endVal.substring(0, 10));
        
        select.innerHTML = '';
        
        // Generate list of dates inclusive
        for (let d = new Date(start); d <= end; d.setDate(d.getDate() + 1)) {
            const dateString = d.toISOString().substring(0, 10);
            const opt = document.createElement('option');
            opt.value = dateString;
            opt.textContent = d.toLocaleDateString(undefined, { weekday: 'short', month: 'short', day: 'numeric', year: 'numeric' });
            select.appendChild(opt);
        }
    }

    function toggleWizardGuestSpeakerInput() {
        const select = document.getElementById('agenda_item_speaker_profile_id');
        const container = document.getElementById('wizard_external_speaker_container');
        const input = document.getElementById('agenda_item_speaker');
        
        if (select.value === 'external') {
            container.style.display = 'block';
            input.required = true;
        } else {
            container.style.display = 'none';
            input.required = false;
            input.value = '';
        }
    }

    // Agenda add/remove functions
    function addAgendaSessionToWizard(e) {
        if (e) e.preventDefault();
        
        const titleInput = document.getElementById('agenda_item_title');
        const dateSelect = document.getElementById('agenda_item_date');
        const startInput = document.getElementById('agenda_item_start_time');
        const endInput = document.getElementById('agenda_item_end_time');
        const speakerSelect = document.getElementById('agenda_item_speaker_profile_id');
        const guestInput = document.getElementById('agenda_item_speaker');
        const descTextarea = document.getElementById('agenda_item_desc');
        
        const title = titleInput.value.trim();
        if (!title) {
            titleInput.classList.add('is-invalid');
            return;
        }
        titleInput.classList.remove('is-invalid');
        
        const date = dateSelect.value;
        const start = startInput.value;
        const end = endInput.value;
        
        if (!start || !end) {
            alert("Please specify start and end times for this session.");
            return;
        }

        let speakerProfileId = null;
        let speakerName = null;
        
        if (speakerSelect.value === 'external') {
            speakerName = guestInput.value.trim();
            if (!speakerName) {
                guestInput.classList.add('is-invalid');
                return;
            }
            guestInput.classList.remove('is-invalid');
        } else if (speakerSelect.value !== '') {
            speakerProfileId = parseInt(speakerSelect.value);
        }
        
        const session = {
            title: title,
            agenda_date: date,
            start_time: start,
            end_time: end,
            speaker_profile_id: speakerProfileId,
            speaker: speakerName,
            description: descTextarea.value.trim()
        };
        
        agendaSessions.push(session);
        renderAgendaSessions();
        
        // Reset subform fields
        titleInput.value = '';
        startInput.value = '';
        endInput.value = '';
        speakerSelect.value = '';
        guestInput.value = '';
        descTextarea.value = '';
        document.getElementById('wizard_external_speaker_container').style.display = 'none';
    }

    function renderAgendaSessions() {
        const tbody = document.getElementById('agenda-sessions-tbody');
        tbody.innerHTML = '';
        
        // Sort sessions chronologically
        agendaSessions.sort((a, b) => {
            if (a.agenda_date !== b.agenda_date) {
                return a.agenda_date.localeCompare(b.agenda_date);
            }
            return a.start_time.localeCompare(b.start_time);
        });

        if (agendaSessions.length === 0) {
            tbody.innerHTML = `<tr><td colspan="5" class="text-center py-3 text-muted small">No agenda sessions added yet.</td></tr>`;
        } else {
            agendaSessions.forEach((session, idx) => {
                let speakerText = 'None';
                if (session.speaker_profile_id) {
                    const opt = document.querySelector(`#agenda_item_speaker_profile_id option[value="${session.speaker_profile_id}"]`);
                    speakerText = opt ? opt.textContent.split('(')[0].trim() : 'Speaker ID: ' + session.speaker_profile_id;
                } else if (session.speaker) {
                    speakerText = session.speaker + ' (Guest)';
                }
                
                tbody.innerHTML += `
                    <tr>
                        <td><strong class="small text-dark">${escapeHtml(session.title)}</strong></td>
                        <td class="font-monospace small">${session.agenda_date}</td>
                        <td class="font-monospace small text-muted" style="font-size:0.75rem;">${session.start_time} - ${session.end_time}</td>
                        <td class="small">${escapeHtml(speakerText)}</td>
                        <td class="text-end">
                            <button type="button" class="btn btn-sm btn-outline-danger py-0 px-2 small" onclick="removeAgendaSessionFromWizard(${idx})"><i class="bi bi-trash"></i></button>
                        </td>
                    </tr>
                `;
            });
        }
        
        document.getElementById('agenda_json').value = JSON.stringify(agendaSessions);
    }

    function removeAgendaSessionFromWizard(idx) {
        agendaSessions.splice(idx, 1);
        renderAgendaSessions();
    }

    function escapeHtml(text) {
        if (!text) return '';
        return text
            .replace(/&/g, "&amp;")
            .replace(/</g, "&lt;")
            .replace(/>/g, "&gt;")
            .replace(/"/g, "&quot;")
            .replace(/'/g, "&#039;");
    }

    function toggleEventFields() {
        const eventType = document.getElementById('event_type').value;
        const physicalFields = document.getElementById('physical_fields');
        const virtualFields = document.getElementById('virtual_fields');
        const locationInput = document.getElementById('location');
        
        if (eventType === 'physical') {
            physicalFields.style.display = 'block';
            virtualFields.style.display = 'none';
            locationInput.required = true;
            if (locationInput.value === 'Online Webcast') {
                locationInput.value = '';
            }
        } else if (eventType === 'virtual') {
            physicalFields.style.display = 'none';
            virtualFields.style.display = 'block';
            locationInput.required = false;
        } else if (eventType === 'hybrid') {
            physicalFields.style.display = 'block';
            virtualFields.style.display = 'block';
            locationInput.required = true;
            if (locationInput.value === 'Online Webcast') {
                locationInput.value = '';
            }
        }
        toggleZoomGenerator();
    }

    function togglePricingFields() {
        const paymentType = document.getElementById('payment_type').value;
        const priceContainer = document.getElementById('price_container');
        const gstContainer = document.getElementById('gst_container');
        const rzpContainer = document.getElementById('razorpay_gateway_container');
        const priceInput = document.getElementById('price');
        
        if (paymentType === 'paid') {
            priceContainer.style.display = 'block';
            gstContainer.style.display = 'block';
            if (rzpContainer) rzpContainer.style.display = 'flex';
            if (priceInput) priceInput.required = true;
        } else {
            priceContainer.style.display = 'none';
            gstContainer.style.display = 'none';
            if (rzpContainer) rzpContainer.style.display = 'none';
            if (priceInput) priceInput.required = false;
        }
    }

    function toggleRecurrenceFields() {
        const isRec = document.getElementById('is_recurring').checked;
        const fields = document.querySelectorAll('.recurrence-fields');
        fields.forEach(el => {
            el.style.display = isRec ? 'block' : 'none';
        });
    }

    function toggleZoomGenerator() {
        const platform = document.getElementById('virtual_platform').value;
        const zoomGeneratorSwitch = document.getElementById('zoom_generator_switch');
        const autoZoomCheckbox = document.getElementById('auto_zoom');
        
        if (platform === 'zoom') {
            zoomGeneratorSwitch.style.display = 'block';
        } else {
            zoomGeneratorSwitch.style.display = 'none';
            autoZoomCheckbox.checked = false;
        }
        toggleZoomInput();
    }

    function toggleZoomInput() {
        const autoZoomCheckbox = document.getElementById('auto_zoom');
        const virtualLinkContainer = document.getElementById('virtual_link_container');
        const virtualLinkInput = document.getElementById('virtual_link');
        
        if (autoZoomCheckbox.checked) {
            virtualLinkContainer.style.display = 'none';
            virtualLinkInput.required = false;
        } else {
            virtualLinkContainer.style.display = 'block';
        }
    }

    // Drag & Drop Image Logic
    function initDragAndDrop() {
        const dropZone = document.getElementById('drop-zone');
        const fileInput = document.getElementById('banner_file');
        const promptDiv = document.getElementById('drop-zone-prompt');
        const previewDiv = document.getElementById('drop-zone-preview');
        const previewImg = document.getElementById('preview-image');
        const previewFilename = document.getElementById('preview-filename');
        const bannerUrlInput = document.getElementById('banner_url');

        if (!dropZone) return;

        // Drag overlay highlight
        ['dragenter', 'dragover'].forEach(eventName => {
            dropZone.addEventListener(eventName, (e) => {
                e.preventDefault();
                dropZone.style.borderColor = '#0d6efd';
                dropZone.style.backgroundColor = '#f8f9fa';
            }, false);
        });

        ['dragleave', 'drop'].forEach(eventName => {
            dropZone.addEventListener(eventName, (e) => {
                e.preventDefault();
                dropZone.style.borderColor = '#dee2e6';
                dropZone.style.backgroundColor = '#ffffff';
            }, false);
        });

        // Drop file
        dropZone.addEventListener('drop', (e) => {
            const dt = e.dataTransfer;
            const files = dt.files;
            if (files.length) {
                fileInput.files = files;
                handleFileChange();
            }
        });

        // Input change selection
        fileInput.addEventListener('change', handleFileChange);

        function handleFileChange() {
            const file = fileInput.files[0];
            if (file && file.type.startsWith('image/')) {
                const reader = new FileReader();
                reader.onload = function(e) {
                    previewImg.src = e.target.result;
                    previewFilename.textContent = file.name;
                    promptDiv.style.display = 'none';
                    previewDiv.style.display = 'block';
                    
                    // Clear the manual URL fallback if they uploaded a local file
                    bannerUrlInput.value = '';
                }
                reader.readAsDataURL(file);
            }
        }

        // Check if editing and prefilled banner image URL is already set
        const existingUrl = bannerUrlInput.value.trim();
        if (existingUrl) {
            previewImg.src = existingUrl;
            previewFilename.textContent = existingUrl.substring(existingUrl.lastIndexOf('/') + 1);
            promptDiv.style.display = 'none';
            previewDiv.style.display = 'block';
        }
    }

    function removeUploadedFile(e) {
        if (e) {
            e.preventDefault();
            e.stopPropagation();
        }
        const fileInput = document.getElementById('banner_file');
        const promptDiv = document.getElementById('drop-zone-prompt');
        const previewDiv = document.getElementById('drop-zone-preview');
        const previewImg = document.getElementById('preview-image');
        const previewFilename = document.getElementById('preview-filename');
        const bannerUrlInput = document.getElementById('banner_url');
        
        fileInput.value = '';
        previewImg.src = '';
        previewFilename.textContent = '';
        promptDiv.style.display = 'block';
        previewDiv.style.display = 'none';
        
        // Also clear fallback URL in case they are wiping it
        bannerUrlInput.value = '';
    }

    function confirmRecurringDelete(e, isRecurring, eventId, csrfToken) {
        if (!isRecurring) {
            return confirm('Delete this event?');
        }
        
        e.preventDefault();
        
        var choice = confirm("This event is recurring.\n\nClick OK to delete the ENTIRE SERIES of occurrences.\nClick Cancel to delete ONLY THIS SINGLE OCCURRENCE.");
        
        if (choice) {
            window.location.href = "events?action=delete&id=" + eventId + "&delete_series=1&csrf_token=" + csrfToken;
        } else {
            if (confirm("Delete ONLY this single occurrence?")) {
                window.location.href = "events?action=delete&id=" + eventId + "&csrf_token=" + csrfToken;
            }
        }
        return false;
    }

    document.addEventListener('DOMContentLoaded', function() {
        toggleEventFields();
        togglePricingFields();
        toggleRecurrenceFields();
        initDragAndDrop();

        // If modal hides and url was editing, redirect to reset query string
        const modalEl = document.getElementById('eventModal');
        modalEl.addEventListener('hidden.bs.modal', function () {
            if (window.location.search.includes('edit_id=')) {
                window.location.href = 'events';
            }
        });

        // Whenever modal is shown, reset to Step 1
        modalEl.addEventListener('shown.bs.modal', function() {
            goToStep(1);
            togglePricingFields();
        });
    });
</script>

<!-- PHP Auto-Open Modal Trigger (Includes existing agendas prefill) -->
<?php if ($editEvent): ?>
<script>
    const initialAgendaSessions = <?php echo json_encode($existing_agendas ?: []); ?>;
    document.addEventListener('DOMContentLoaded', function() {
        if (initialAgendaSessions && initialAgendaSessions.length) {
            agendaSessions = initialAgendaSessions;
            renderAgendaSessions();
        }
        const myModal = new bootstrap.Modal(document.getElementById('eventModal'));
        myModal.show();
    });
</script>
<?php endif; ?>

<?php endif; ?>

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