<?php
require_once 'config.php';

if (!isset($_SESSION['user_id'])) {
    header("Location: signin.php");
    exit();
}

// Get all registrations for this user
$stmt = $pdo->prepare("SELECT * FROM conference_registrations WHERE user_id = ? ORDER BY id DESC");
$stmt->execute([$_SESSION['user_id']]);
$all_registrations = $stmt->fetchAll(PDO::FETCH_ASSOC);

// Get current registration (if editing)
$edit_id = isset($_GET['edit_id']) ? intval($_GET['edit_id']) : 0;
$existing_reg = null;
$team_members = [];

if ($edit_id > 0) {
    $stmt = $pdo->prepare("SELECT * FROM conference_registrations WHERE id = ? AND user_id = ?");
    $stmt->execute([$edit_id, $_SESSION['user_id']]);
    $existing_reg = $stmt->fetch(PDO::FETCH_ASSOC);
    
    if ($existing_reg) {
        $stmt = $pdo->prepare("SELECT * FROM team_members WHERE registration_id = ?");
        $stmt->execute([$existing_reg['id']]);
        $team_members = $stmt->fetchAll(PDO::FETCH_ASSOC);
    }
}

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

// All Countries List
$all_countries = [
    'Pakistan', 'USA', 'United Kingdom', 'Canada', 'Australia', 'India', 'China', 'Japan', 
    'Germany', 'France', 'Italy', 'Spain', 'Brazil', 'Mexico', 'South Africa', 'Egypt', 
    'Turkey', 'UAE', 'Saudi Arabia', 'Malaysia', 'Singapore', 'Indonesia', 'Bangladesh', 
    'Sri Lanka', 'Nepal', 'Afghanistan', 'Iran', 'Iraq', 'Jordan', 'Lebanon', 'Morocco', 
    'Nigeria', 'Kenya', 'Argentina', 'Chile', 'Colombia', 'Peru', 'Venezuela', 'Russia', 
    'Poland', 'Netherlands', 'Belgium', 'Sweden', 'Norway', 'Denmark', 'Finland', 'Switzerland',
    'Austria', 'Greece', 'Portugal', 'Ireland', 'New Zealand', 'Thailand', 'Vietnam', 'Philippines'
];
sort($all_countries);

// Specialty/Discipline List (Checkboxes) - This REPLACES the old dropdown
$specialty_list = [
    'Physical therapists',
    'Speech & Language Pathologists',
    'Medical Laboratory Technologist',
    'Medical Imaging Technologist',
    'Nutritionist and Dieticians',
    'Optometrist',
    'Dental Technologist',
    'Operation theater technologist',
    'Rehabilitation and Allied Health Professionals',
    'Health Care Professionals',
    'Undergraduate and post graduate students of all fields',
    'Academicians, clinicians, Hospital Administrators, Public Health',
    'Professional, Industry Experts.'
];

// Handle file upload
function handleFileUpload($file, $user_id, $registration_id) {
    $target_dir = "uploads/student_docs/";
    if (!file_exists($target_dir)) {
        mkdir($target_dir, 0777, true);
    }
    
    $file_extension = strtolower(pathinfo($file["name"], PATHINFO_EXTENSION));
    $allowed_extensions = ['jpg', 'jpeg', 'png', 'pdf'];
    
    if (!in_array($file_extension, $allowed_extensions)) {
        return false;
    }
    
    $new_filename = "student_" . $user_id . "_" . $registration_id . "_" . time() . "." . $file_extension;
    $target_file = $target_dir . $new_filename;
    
    if (move_uploaded_file($file["tmp_name"], $target_file)) {
        return $target_file;
    }
    return false;
}

// Handle form submission
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['save_registration'])) {
    $first_name = trim($_POST['first_name'] ?? '');
    $last_name = trim($_POST['last_name'] ?? '');
    $email = trim($_POST['email'] ?? '');
    $country = trim($_POST['country'] ?? '');
    $cell_no = trim($_POST['cell_no'] ?? '');
    $whatsapp_number = trim($_POST['whatsapp_number'] ?? '');
    $address = trim($_POST['address'] ?? '');
    $category = trim($_POST['category'] ?? '');
    $category_two = trim($_POST['category_two'] ?? '');
    $designation = trim($_POST['designation'] ?? '');
    
    // Process specialty (checkboxes) - Store in interest_field column
    $selected_specialty = $_POST['interest_field'] ?? [];
    if (!is_array($selected_specialty)) {
        $selected_specialty = [];
    }
    $interest_field = implode(', ', $selected_specialty);
    
    $ahpc_reg_number = trim($_POST['ahpc_reg_number'] ?? '');
    $institute = trim($_POST['institute'] ?? '');
    $id_card_number = trim($_POST['id_card_number'] ?? '');
    $event_type = trim($_POST['event_type'] ?? '');
    $registration_type = trim($_POST['registration_type'] ?? '');
    
    // Get team members data
    $member_names = $_POST['member_name'] ?? [];
    $member_emails = $_POST['member_email'] ?? [];
    $member_phones = $_POST['member_phone'] ?? [];
    $member_designations = $_POST['member_designation'] ?? [];
    $member_interests = $_POST['member_interest'] ?? [];

    // Server-side validation
    $validation_errors = [];
    
    // First Name validation (allow letters and hyphens)
    if (empty($first_name)) {
        $validation_errors[] = "First name is required.";
    } elseif (strlen($first_name) < 2) {
        $validation_errors[] = "First name must be at least 2 characters.";
    } elseif (strlen($first_name) > 50) {
        $validation_errors[] = "First name cannot exceed 50 characters.";
    } elseif (!preg_match('/^[A-Za-z\-]+$/', $first_name)) {
        $validation_errors[] = "First name can only contain letters and hyphens.";
    }
    
    // Last Name validation
    if (empty($last_name)) {
        $validation_errors[] = "Last name is required.";
    } elseif (strlen($last_name) < 2) {
        $validation_errors[] = "Last name must be at least 2 characters.";
    } elseif (strlen($last_name) > 50) {
        $validation_errors[] = "Last name cannot exceed 50 characters.";
    } elseif (!preg_match('/^[A-Za-z\-]+$/', $last_name)) {
        $validation_errors[] = "Last name can only contain letters and hyphens.";
    }
    
    if (empty($email)) $validation_errors[] = "Email is required.";
    if (!filter_var($email, FILTER_VALIDATE_EMAIL)) $validation_errors[] = "Please enter a valid email address.";
    if (empty($country)) $validation_errors[] = "Country is required.";
    if (empty($cell_no)) $validation_errors[] = "Cell number is required.";
    if (!preg_match('/^[\+\d][\d\s\-\(\)]{9,14}$/', $cell_no)) $validation_errors[] = "Please enter a valid phone number (10-15 digits).";
    if (empty($whatsapp_number)) $validation_errors[] = "WhatsApp number is required.";
    if (!preg_match('/^[\+\d][\d\s\-\(\)]{9,14}$/', $whatsapp_number)) $validation_errors[] = "Please enter a valid WhatsApp number (10-15 digits).";
    if (empty($category)) $validation_errors[] = "Category is required.";
    if (empty($category_two)) $validation_errors[] = "Registration category is required.";
    if (empty($interest_field)) $validation_errors[] = "Specialty/Discipline is required.";
    if (empty($institute)) $validation_errors[] = "Institute is required.";
    if (empty($id_card_number)) $validation_errors[] = "ID Card/CNIC/Passport number is required.";
    if (empty($event_type)) $validation_errors[] = "Event selection is required.";
    
    // Designation validation for Professional
    if ($category == 'Professional' && empty($designation)) {
        $validation_errors[] = "Designation is required for Professional category.";
    }
    
    // Validate CNIC format for Pakistan
    if ($country == 'Pakistan' && !preg_match('/^\d{5}-\d{7}-\d{1}$/', $id_card_number)) {
        $validation_errors[] = "Please enter a valid CNIC number (format: 12345-1234567-1).";
    }
    
    // Professional validation for Package
    if ($category == 'Professional') {
        if ($category_two == 'Package') {
            if (empty($registration_type)) {
                $validation_errors[] = "Please select package type (5 Person or 10 Person).";
            }
            // For Package, only Conference event is allowed
            if ($event_type != 'Conference Registration') {
                $validation_errors[] = "For Package registration, only Conference event is allowed.";
            }
            // Validate team members count
            $expected_members = ($registration_type == 'Group Discount (5 Person)') ? 5 : (($registration_type == 'Group Discount (10 Person)') ? 10 : 0);
            if ($expected_members > 0 && count($member_names) != $expected_members) {
                $validation_errors[] = "Please add details for all $expected_members team members.";
            }
        }
    }
    
    // Student validation
    if ($category == 'Student') {
        if (isset($_FILES['student_document']) && $_FILES['student_document']['error'] == 0 && $_FILES['student_document']['size'] > 0) {
            // File uploaded - valid
        } elseif (empty($existing_reg['student_document'])) {
            $validation_errors[] = "Student ID card/CNIC upload is required for student registration.";
        }
    }
    
    if (!empty($validation_errors)) {
        $error = implode(" ", $validation_errors);
    } else {
        try {
            $pdo->beginTransaction();
            
            // Handle file upload for students
            $student_document = $existing_reg['student_document'] ?? '';
            if ($category == 'Student' && isset($_FILES['student_document']) && $_FILES['student_document']['error'] == 0 && $_FILES['student_document']['size'] > 0) {
                $temp_reg_id = $existing_reg['id'] ?? time();
                $uploaded_file = handleFileUpload($_FILES['student_document'], $_SESSION['user_id'], $temp_reg_id);
                if ($uploaded_file) {
                    $student_document = $uploaded_file;
                }
            }
            
            if ($existing_reg) {
                // UPDATE existing registration - using interest_field column
                $sql = "UPDATE conference_registrations SET 
                        first_name=?, last_name=?, email=?, country=?, 
                        cell_no=?, whatsapp_number=?, address=?, category=?, 
                        category_two=?, designation=?, interest_field=?, 
                        ahpc_reg_number=?, institute=?, id_card_number=?, 
                        event_type=?, registration_type=?, student_document=? WHERE id=? AND user_id=?";
                $stmt = $pdo->prepare($sql);
                $stmt->execute([$first_name, $last_name, $email, $country, 
                                $cell_no, $whatsapp_number, $address, $category, 
                                $category_two, $designation, $interest_field, 
                                $ahpc_reg_number, $institute, $id_card_number, 
                                $event_type, $registration_type, $student_document, 
                                $edit_id, $_SESSION['user_id']]);
                $registration_id = $edit_id;
                
                // Update users table with first_name and last_name
                try {
                    $sql2 = "UPDATE users SET first_name = ?, last_name = ? WHERE id = ?";
                    $stmt2 = $pdo->prepare($sql2);
                    $stmt2->execute([$first_name, $last_name, $_SESSION['user_id']]);
                    
                    // Update session variables
                    $_SESSION['first_name'] = $first_name;
                    $_SESSION['last_name'] = $last_name;
                    
                } catch (PDOException $e) {
                    error_log("Users table update failed: " . $e->getMessage());
                }
                
                // Delete existing team members and re-insert
                $stmt = $pdo->prepare("DELETE FROM team_members WHERE registration_id = ?");
                $stmt->execute([$registration_id]);
                
                $success = "Registration updated successfully!";
                
            } else {
                // INSERT new registration - using interest_field column
                $sql = "INSERT INTO conference_registrations 
                        (user_id, first_name, last_name, email, country, cell_no, 
                         whatsapp_number, address, category, category_two, 
                         designation, interest_field, ahpc_reg_number, 
                         institute, id_card_number, event_type, registration_type, 
                         student_document, registration_date) 
                        VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, NOW())";
                $stmt = $pdo->prepare($sql);
                $stmt->execute([$_SESSION['user_id'], $first_name, $last_name, $email, $country, 
                                $cell_no, $whatsapp_number, $address, $category, 
                                $category_two, $designation, $interest_field, 
                                $ahpc_reg_number, $institute, $id_card_number, 
                                $event_type, $registration_type, $student_document]);
                $registration_id = $pdo->lastInsertId();
                
                // Update users table with first_name and last_name
                try {
                    $sql2 = "UPDATE users SET first_name = ?, last_name = ? WHERE id = ?";
                    $stmt2 = $pdo->prepare($sql2);
                    $stmt2->execute([$first_name, $last_name, $_SESSION['user_id']]);
                    
                    // Update session variables
                    $_SESSION['first_name'] = $first_name;
                    $_SESSION['last_name'] = $last_name;
                    
                } catch (PDOException $e) {
                    error_log("Users table update failed: " . $e->getMessage());
                }
                
                $success = "Registration submitted successfully!";
            }
            
            // Insert team members (only for Professional with Package)
            if ($category == 'Professional' && $category_two == 'Package') {
                for ($i = 0; $i < count($member_names); $i++) {
                    if (!empty($member_names[$i]) && !empty($member_emails[$i]) && !empty($member_phones[$i])) {
                        // Process team member specialties (checkboxes)
                        $member_interest_value = '';
                        if (isset($member_interests[$i]) && is_array($member_interests[$i])) {
                            $member_interest_value = implode(', ', $member_interests[$i]);
                        }
                        
                        $sql = "INSERT INTO team_members (registration_id, name, email, phone, designation, interest_field) VALUES (?, ?, ?, ?, ?, ?)";
                        $stmt = $pdo->prepare($sql);
                        $stmt->execute([$registration_id, $member_names[$i], $member_emails[$i], $member_phones[$i], 
                                        $member_designations[$i] ?? '', $member_interest_value]);
                    }
                }
            }
            
            $pdo->commit();
            
            // Refresh data
            $stmt = $pdo->prepare("SELECT * FROM conference_registrations WHERE user_id = ? ORDER BY id DESC");
            $stmt->execute([$_SESSION['user_id']]);
            $all_registrations = $stmt->fetchAll(PDO::FETCH_ASSOC);
            
            // Clear form after successful submission
            if (!$existing_reg) {
                $first_name = $last_name = $email = $country = $cell_no = $whatsapp_number = $address = '';
                $category = $category_two = $designation = $interest_field = '';
                $ahpc_reg_number = $institute = $id_card_number = '';
                $event_type = $registration_type = '';
                $team_members = [];
                $edit_id = 0;
                $existing_reg = null;
            }
            
        } catch(Exception $e) {
            $pdo->rollBack();
            $error = "Registration failed: " . $e->getMessage();
        }
    }
}

// Set form values for editing
if ($existing_reg && is_array($existing_reg)) {
    $first_name = $existing_reg['first_name'];
    $last_name = $existing_reg['last_name'];
    $email = $existing_reg['email'];
    $country = $existing_reg['country'] ?? '';
    $cell_no = $existing_reg['cell_no'];
    $whatsapp_number = $existing_reg['whatsapp_number'] ?? '';
    $address = $existing_reg['address'];
    $category = $existing_reg['category'] ?? '';
    $category_two = $existing_reg['category_two'] ?? '';
    $designation = $existing_reg['designation'] ?? '';
    $interest_field = $existing_reg['interest_field'] ?? '';
    $ahpc_reg_number = $existing_reg['ahpc_reg_number'] ?? '';
    $institute = $existing_reg['institute'];
    $id_card_number = $existing_reg['id_card_number'] ?? '';
    $event_type = $existing_reg['event_type'] ?? '';
    $registration_type = $existing_reg['registration_type'] ?? '';
    $student_document = $existing_reg['student_document'] ?? '';
} else {
    // Get current user data from session or database
    $user_id = $_SESSION['user_id'];
    $stmt = $pdo->prepare("SELECT first_name, last_name, email FROM users WHERE id = ?");
    $stmt->execute([$user_id]);
    $user_data = $stmt->fetch(PDO::FETCH_ASSOC);
    
    $first_name = $user_data['first_name'] ?? $_SESSION['first_name'] ?? '';
    $last_name = $user_data['last_name'] ?? $_SESSION['last_name'] ?? '';
    $email = $user_data['email'] ?? $_SESSION['email'] ?? '';
    $country = '';
    $cell_no = '';
    $whatsapp_number = '';
    $address = '';
    $category = '';
    $category_two = '';
    $designation = '';
    $interest_field = '';
    $ahpc_reg_number = '';
    $institute = '';
    $id_card_number = '';
    $event_type = '';
    $registration_type = '';
    $student_document = '';
}

// Convert stored interest field to array for checkboxes
$selected_specialty = [];
if (!empty($interest_field)) {
    $selected_specialty = explode(', ', $interest_field);
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, viewport-fit=cover">
    <title>ARC Conference 2026 | Registration</title>
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }
        
        body {
            font-family: 'Inter', sans-serif;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            padding: 30px 20px;
        }
        
        .top-bar {
            max-width: 1200px;
            margin: 0 auto 25px auto;
            background: white;
            border-radius: 16px;
            padding: 12px 25px;
            display: flex;
            justify-content: space-between;
            align-items: center;
            flex-wrap: wrap;
            gap: 12px;
            box-shadow: 0 4px 12px rgba(0,0,0,0.08);
        }
        
        .logo-area {
            display: flex;
            align-items: center;
            gap: 12px;
        }
        
        .logo-wrapper {
            background: #f0f4f8;
            padding: 6px 12px;
            border-radius: 40px;
        }
        
        .logo-area img {
            max-height: 38px;
            width: auto;
            border-radius: 8px;
        }
        
        .logo-text {
            font-size: 18px;
            font-weight: 700;
            background: linear-gradient(135deg, #1e3c72, #2a5298);
            -webkit-background-clip: text;
            -webkit-text-fill-color: transparent;
        }
        
        .year-badge {
            background: linear-gradient(135deg, #1e3c72, #2a5298);
            color: white;
            padding: 3px 10px;
            border-radius: 25px;
            font-size: 11px;
            font-weight: 600;
        }
        
        .user-badge {
            display: flex;
            align-items: center;
            gap: 15px;
        }
        
        .user-name {
            color: #1e3c72;
            font-weight: 500;
            font-size: 13px;
        }
        
        .logout-btn {
            background: #dc2626;
            color: white;
            padding: 6px 16px;
            border-radius: 10px;
            text-decoration: none;
            font-weight: 500;
            font-size: 12px;
            transition: all 0.2s;
            display: inline-flex;
            align-items: center;
            gap: 6px;
        }
        
        .logout-btn:hover {
            background: #b91c1c;
            transform: translateY(-1px);
        }
        
        .container {
            max-width: 1200px;
            margin: 0 auto;
            background: white;
            border-radius: 24px;
            box-shadow: 0 20px 40px -12px rgba(0, 0, 0, 0.2);
            overflow: hidden;
        }
        
        .form-header {
            background: linear-gradient(135deg, #1e3c72 0%, #2a5298 100%);
            padding: 22px 30px;
            color: white;
        }
        
        .form-header h2 {
            font-size: 22px;
            font-weight: 600;
        }
        
        .form-header h2 i {
            margin-right: 10px;
        }
        
        .form-body {
            padding: 30px;
        }
        
        .form-grid {
            display: grid;
            grid-template-columns: repeat(2, 1fr);
            gap: 20px 25px;
        }
        
        .input-group {
            display: flex;
            flex-direction: column;
        }
        
        .input-group.full-width {
            grid-column: span 2;
        }
        
        label {
            display: block;
            margin-bottom: 6px;
            font-weight: 600;
            color: #1e3c72;
            font-size: 12px;
            letter-spacing: 0.3px;
        }
        
        label i {
            margin-right: 6px;
            width: 16px;
            font-size: 12px;
            color: #2a5298;
        }
        
        label .required {
            color: #dc2626;
            margin-left: 3px;
        }
        
        label .optional {
            color: #6b7280;
            font-weight: normal;
            font-size: 10px;
            margin-left: 5px;
        }
        
        input, select, textarea {
            width: 100%;
            padding: 11px 14px;
            border: 1.5px solid #e2e8f0;
            border-radius: 12px;
            font-size: 13px;
            font-family: 'Inter', sans-serif;
            transition: all 0.2s;
            background: #fafbfc;
        }
        
        input:focus, select:focus, textarea:focus {
            outline: none;
            border-color: #2a5298;
            background: white;
            box-shadow: 0 0 0 3px rgba(42, 82, 152, 0.1);
        }
        
        input.invalid, select.invalid, textarea.invalid {
            border-color: #dc2626;
            background: #fef2f2;
        }
        
        input.valid {
            border-color: #10b981;
            background: #f0fdf4;
        }
        
        input[readonly] {
            background: #eef2f7;
            cursor: not-allowed;
            border-color: #d1d5db;
            color: #4b5563;
        }
        
        input[readonly]:focus {
            box-shadow: none;
            border-color: #d1d5db;
        }
        
        textarea {
            resize: vertical;
            min-height: 80px;
        }
        
        .field-hint {
            font-size: 10px;
            color: #64748b;
            margin-top: 5px;
            display: flex;
            align-items: center;
            gap: 5px;
        }
        
        .field-hint.error-hint {
            color: #dc2626;
        }
        
        .field-hint.success-hint {
            color: #10b981;
        }
        
        /* Checkbox List Styles - Specialty/Discipline */
        .checkbox-list {
            display: grid;
            grid-template-columns: repeat(2, 1fr);
            gap: 8px 15px;
            background: #f9fafb;
            padding: 12px 15px;
            border-radius: 12px;
            border: 1.5px solid #e2e8f0;
            max-height: 200px;
            overflow-y: auto;
        }
        
        .checkbox-list label {
            display: flex;
            align-items: center;
            gap: 8px;
            font-weight: 400;
            color: #1e293b;
            font-size: 12px;
            cursor: pointer;
            padding: 4px 0;
        }
        
        .checkbox-list label:hover {
            color: #1e3c72;
        }
        
        .checkbox-list input[type="checkbox"] {
            width: 16px;
            height: 16px;
            accent-color: #2a5298;
            cursor: pointer;
            flex-shrink: 0;
        }
        
        .checkbox-list::-webkit-scrollbar {
            width: 5px;
        }
        
        .checkbox-list::-webkit-scrollbar-track {
            background: #f1f1f1;
            border-radius: 10px;
        }
        
        .checkbox-list::-webkit-scrollbar-thumb {
            background: #c1c7cd;
            border-radius: 10px;
        }
        
        .checkbox-list::-webkit-scrollbar-thumb:hover {
            background: #a0a7ae;
        }
        
        .btn-submit {
            width: 100%;
            padding: 13px;
            background: linear-gradient(135deg, #1e3c72 0%, #2a5298 100%);
            color: white;
            border: none;
            border-radius: 14px;
            font-size: 15px;
            font-weight: 600;
            cursor: pointer;
            transition: all 0.2s;
            margin-top: 25px;
            display: flex;
            align-items: center;
            justify-content: center;
            gap: 8px;
        }
        
        .btn-submit:hover {
            transform: translateY(-1px);
            box-shadow: 0 6px 14px rgba(30, 60, 114, 0.3);
        }
        
        .btn-new {
            background: #059669;
            margin-top: 10px;
            text-decoration: none;
            display: block;
            text-align: center;
        }
        
        .btn-new:hover {
            background: #047857;
        }
        
        .alert {
            padding: 12px 16px;
            border-radius: 12px;
            margin-bottom: 20px;
            font-size: 13px;
            display: flex;
            align-items: center;
            gap: 10px;
        }
        
        .alert-error {
            background: #fee2e2;
            color: #dc2626;
            border-left: 3px solid #dc2626;
        }
        
        .alert-success {
            background: #dcfce7;
            color: #16a34a;
            border-left: 3px solid #16a34a;
        }
        
        .info-card {
            background: #eff6ff;
            padding: 12px 16px;
            border-radius: 12px;
            margin-bottom: 20px;
            display: flex;
            align-items: center;
            gap: 10px;
            font-size: 12px;
            color: #1e3c72;
            border: 1px solid #dbeafe;
        }
        
        .team-section {
            grid-column: span 2;
            margin-top: 5px;
            padding: 18px;
            background: #f8fafc;
            border-radius: 16px;
            border: 1px solid #e2e8f0;
        }
        
        .team-section h3 {
            color: #1e3c72;
            margin-bottom: 15px;
            font-size: 14px;
        }
        
        .team-member-card {
            background: white;
            padding: 15px;
            border-radius: 12px;
            margin-bottom: 15px;
            border: 1px solid #e2e8f0;
        }
        
        .team-member-title {
            font-weight: 600;
            color: #2a5298;
            margin-bottom: 12px;
            font-size: 12px;
        }
        
        .team-grid {
            display: grid;
            grid-template-columns: repeat(5, 1fr);
            gap: 12px;
        }
        
        .team-grid label {
            font-size: 11px;
            margin-bottom: 4px;
        }
        
        .team-member-checkbox-list {
            display: flex;
            flex-direction: column;
            gap: 4px;
            max-height: 100px;
            overflow-y: auto;
            background: #f9fafb;
            padding: 8px 10px;
            border-radius: 8px;
            border: 1px solid #e2e8f0;
        }
        
        .team-member-checkbox-list label {
            font-size: 10px;
            font-weight: 400;
            display: flex;
            align-items: center;
            gap: 6px;
            cursor: pointer;
            color: #1e293b;
        }
        
        .team-member-checkbox-list input[type="checkbox"] {
            width: 14px;
            height: 14px;
            accent-color: #2a5298;
            cursor: pointer;
            flex-shrink: 0;
        }
        
        .registrations-table {
            margin-top: 30px;
            background: #f8fafc;
            border-radius: 16px;
            padding: 18px;
            border: 1px solid #e2e8f0;
        }
        
        .registrations-table h4 {
            color: #1e3c72;
            margin-bottom: 15px;
            font-size: 14px;
        }
        
        .data-table {
            width: 100%;
            border-collapse: collapse;
            font-size: 12px;
        }
        
        .data-table th {
            text-align: left;
            padding: 10px 12px;
            background: #e2e8f0;
            color: #1e3c72;
            font-weight: 600;
        }
        
        .data-table td {
            padding: 10px 12px;
            border-bottom: 1px solid #e2e8f0;
        }
        
        .data-table tr:hover {
            background: #f1f5f9;
        }
        
        .view-reg-btn {
            background: #10b981;
            color: white;
            padding: 4px 12px;
            border-radius: 6px;
            text-decoration: none;
            font-size: 11px;
            display: inline-block;
            margin-right: 5px;
            border: none;
            cursor: pointer;
        }
        
        .view-reg-btn:hover {
            background: #059669;
        }
        
        .edit-reg-btn {
            background: #2a5298;
            color: white;
            padding: 4px 12px;
            border-radius: 6px;
            text-decoration: none;
            font-size: 11px;
            display: inline-block;
        }
        
        .edit-reg-btn:hover {
            background: #1e3c72;
        }
        
        .checkout-btn {
            background: #f59e0b;
            color: #1e3c72;
            padding: 4px 12px;
            border-radius: 6px;
            text-decoration: none;
            font-size: 11px;
            display: inline-block;
            font-weight: 600;
        }
        
        .checkout-btn:hover {
            background: #d97706;
        }
        
        .file-input {
            padding: 8px 12px !important;
        }
        
        .current-file {
            font-size: 11px;
            color: #059669;
            margin-top: 5px;
        }
        
        /* Modal Styles */
        .modal {
            display: none;
            position: fixed;
            z-index: 1000;
            left: 0;
            top: 0;
            width: 100%;
            height: 100%;
            background-color: rgba(0,0,0,0.6);
            overflow-y: auto;
        }
        
        .modal-content {
            background-color: white;
            margin: 50px auto;
            max-width: 800px;
            width: 90%;
            border-radius: 20px;
            animation: slideDown 0.3s ease-out;
        }
        
        @keyframes slideDown {
            from {
                opacity: 0;
                transform: translateY(-50px);
            }
            to {
                opacity: 1;
                transform: translateY(0);
            }
        }
        
        .modal-header {
            background: linear-gradient(135deg, #1e3c72 0%, #2a5298 100%);
            color: white;
            padding: 18px 25px;
            border-radius: 20px 20px 0 0;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }
        
        .modal-header h3 {
            font-size: 18px;
        }
        
        .close-modal {
            font-size: 28px;
            font-weight: bold;
            cursor: pointer;
            transition: 0.3s;
        }
        
        .close-modal:hover {
            color: #ccc;
        }
        
        .modal-body {
            padding: 25px;
        }
        
        .detail-section {
            margin-bottom: 20px;
            padding-bottom: 15px;
            border-bottom: 1px solid #e2e8f0;
        }
        
        .detail-section h4 {
            color: #1e3c72;
            margin-bottom: 12px;
            font-size: 14px;
        }
        
        .detail-row {
            display: flex;
            margin-bottom: 8px;
            font-size: 13px;
        }
        
        .detail-label {
            width: 140px;
            font-weight: 600;
            color: #4a5568;
        }
        
        .detail-value {
            flex: 1;
            color: #2d3748;
        }
        
        .team-member-list {
            margin-top: 10px;
        }
        
        .team-member-item {
            background: #f8fafc;
            padding: 10px;
            border-radius: 8px;
            margin-bottom: 8px;
        }
        
        @media (max-width: 768px) {
            .form-grid {
                grid-template-columns: 1fr;
                gap: 15px;
            }
            .input-group.full-width, .team-section {
                grid-column: span 1;
            }
            .team-grid {
                grid-template-columns: 1fr;
                gap: 10px;
            }
            .checkbox-list {
                grid-template-columns: 1fr;
                max-height: 150px;
            }
            .team-member-checkbox-list {
                max-height: 80px;
            }
            .data-table {
                display: block;
                overflow-x: auto;
            }
            .form-body {
                padding: 20px;
            }
            body {
                padding: 15px;
            }
            .detail-row {
                flex-direction: column;
            }
            .detail-label {
                width: 100%;
                margin-bottom: 4px;
            }
        }
    </style>
</head>
<body>
    
        <div class="top-bar">
        <div class="logo-area">
            <div class="logo-wrapper">
                <img src="Final logo-02.png" alt="FUI Logo" onerror="this.src='https://via.placeholder.com/120x40?text=FUCP'">
            </div>
            <span class="logo-text">Allied Health Sciences and Rehabilitation Conference - ARC</span>
            <span class="year-badge">2026</span>
        </div>
        <div class="user-badge">
            <span class="user-name"><i class="fas fa-user-circle"></i> <?php echo htmlspecialchars(($first_name ?? '') . ' ' . ($last_name ?? '')); ?></span>
            <a href="logout.php" class="logout-btn"><i class="fas fa-sign-out-alt"></i> Logout</a>
        </div>
    </div>


    <div class="container">
        <div class="form-header">
            <h2><i class="fas fa-clipboard-list"></i> 
                <?php echo $existing_reg ? 'Edit Registration' : 'New Registration'; ?>
            </h2>
        </div>
        <div class="form-body">
            <?php if($error): ?>
                <div class="alert alert-error">
                    <i class="fas fa-exclamation-circle"></i>
                    <?php echo htmlspecialchars($error); ?>
                </div>
            <?php endif; ?>
            <?php if($success): ?>
                <div class="alert alert-success">
                    <i class="fas fa-check-circle"></i>
                    <?php echo htmlspecialchars($success); ?>
                </div>
            <?php endif; ?>
            
            <div class="info-card">
                <i class="fas fa-info-circle"></i>
                <span><span style="color:#dc2626;">*</span> Required fields. <span style="color:#6b7280;">(Optional)</span> fields are marked.</span>
            </div>
            
            <form method="POST" action="" id="registrationForm" enctype="multipart/form-data" onsubmit="return validateForm()">
                <div class="form-grid">
                    <!-- First Name - READONLY -->
                    <div class="input-group">
                        <label><i class="fas fa-user"></i> First Name <span class="required">*</span></label>
                        <input type="text" name="first_name" id="first_name" required 
                               value="<?php echo htmlspecialchars($first_name ?? ''); ?>" 
                               readonly>
                        <div class="field-hint">
                            <i class="fas fa-lock"></i> First name is locked and cannot be changed
                        </div>
                    </div>
                    
                    <!-- Last Name - READONLY -->
                    <div class="input-group">
                        <label><i class="fas fa-user"></i> Last Name <span class="required">*</span></label>
                        <input type="text" name="last_name" id="last_name" required 
                               value="<?php echo htmlspecialchars($last_name ?? ''); ?>" 
                               readonly>
                        <div class="field-hint">
                            <i class="fas fa-lock"></i> Last name is locked and cannot be changed
                        </div>
                    </div>
                    
                    <!-- Email (Readonly) -->
                    <div class="input-group full-width">
                        <label><i class="fas fa-envelope"></i> Email Address <span class="required">*</span></label>
                        <input type="email" name="email" id="email" required readonly 
                               value="<?php echo htmlspecialchars($email ?? ''); ?>">
                        <div class="field-hint">
                            <i class="fas fa-lock"></i> Email is locked and cannot be changed
                        </div>
                    </div>
                    
                    <!-- Category 1 -->
                    <div class="input-group">
                        <label><i class="fas fa-briefcase"></i> Category 1 <span class="required">*</span></label>
                        <select name="category" id="category" required onchange="toggleCategoryTwo()">
                            <option value="">Select category</option>
                            <option value="Professional" <?php echo ($category == 'Professional') ? 'selected' : ''; ?>>Professional</option>
                            <option value="Student" <?php echo ($category == 'Student') ? 'selected' : ''; ?>>Student</option>
                        </select>
                        <div class="field-hint" id="hint_category">
                            <i class="fas fa-info-circle"></i> Select your category
                        </div>
                    </div>
                    
                    <!-- Category 2 and Package Type (Side by Side) -->
                    <div class="input-group" id="category_two_group">
                        <label><i class="fas fa-tag"></i> Category 2 <span class="required">*</span></label>
                        <select name="category_two" id="category_two" required onchange="toggleEventsAndPackage()">
                            <option value="">Select option</option>
                        </select>
                        <div class="field-hint" id="hint_category_two">
                            <i class="fas fa-info-circle"></i> Select registration category
                        </div>
                    </div>
                    
                    <!-- Package Type (next to Category 2) -->
                    <div class="input-group" id="package_type_group" style="display: none;">
                        <label><i class="fas fa-users"></i> Package Type <span class="required">*</span></label>
                        <select name="registration_type" id="registration_type" onchange="updateTeamFields()">
                            <option value="">Select package</option>
                            <option value="Group Discount (5 Person)" <?php echo ($registration_type == 'Group Discount (5 Person)') ? 'selected' : ''; ?>>Group Discount (5 Person)</option>
                            <option value="Group Discount (10 Person)" <?php echo ($registration_type == 'Group Discount (10 Person)') ? 'selected' : ''; ?>>Group Discount (10 Person)</option>
                        </select>
                        <div class="field-hint" id="hint_registration_type">
                            <i class="fas fa-info-circle"></i> Select the package size
                        </div>
                    </div>
                    
                    <!-- Designation (Text Input - Only for Professional) -->
                    <div class="input-group" id="designation_group" style="display: none;">
                        <label><i class="fas fa-user-tie"></i> Designation <span class="required">*</span></label>
                        <input type="text" name="designation" id="designation" 
                               value="<?php echo htmlspecialchars($designation ?? ''); ?>" 
                               placeholder="e.g., Professor, Consultant, Medical Officer"
                               onkeyup="validateTextField(this)"
                               onblur="validateTextField(this)">
                        <div class="field-hint" id="hint_designation">
                            <i class="fas fa-info-circle"></i> Enter your professional designation
                        </div>
                    </div>
                    
                    <!-- Specialty/Discipline - CHECKBOX LIST (Stored in interest_field) -->
                    <div class="input-group full-width">
                        <label><i class="fas fa-stethoscope"></i> Specialty / Discipline <span class="required">*</span> <span style="font-size: 10px;">(Select all that apply)</span></label>
                        <div class="checkbox-list">
                            <?php foreach($specialty_list as $specialty_option): ?>
                                <label>
                                    <input type="checkbox" name="interest_field[]" value="<?php echo $specialty_option; ?>" <?php echo in_array($specialty_option, $selected_specialty) ? 'checked' : ''; ?>>
                                    <?php echo $specialty_option; ?>
                                </label>
                            <?php endforeach; ?>
                        </div>
                        <div class="field-hint" id="hint_interest_field">
                            <i class="fas fa-info-circle"></i> Select your specialty or discipline area(s)
                        </div>
                    </div>
                    
                    <!-- Event Selection (Only Conference and Gala Dinner) -->
                    <div class="input-group full-width">
                        <label><i class="fas fa-calendar-alt"></i> Event <span class="required">*</span></label>
                        <select name="event_type" id="event_type" required>
                            <option value="">Select an event</option>
                        </select>
                        <div class="field-hint" id="hint_event_type">
                            <i class="fas fa-info-circle"></i> Select the type of event
                        </div>
                    </div>
                    
                    <!-- Team Members Section (for Package) -->
                    <div class="team-section full-width" id="teamSection" style="display: none;">
                        <h3><i class="fas fa-users"></i> Team Members</h3>
                        <div id="teamMembersContainer"></div>
                        <div class="field-hint">
                            <i class="fas fa-info-circle"></i> Add team member details for conference registration
                        </div>
                    </div>
                    
                    <!-- Country and ID Card (Side by Side) -->
                    <div class="input-group">
                        <label><i class="fas fa-globe"></i> Country <span class="required">*</span></label>
                        <select name="country" id="country" required onchange="updateIdCardFields()">
                            <option value="">Select your country</option>
                            <?php foreach($all_countries as $country_option): ?>
                                <option value="<?php echo $country_option; ?>" <?php echo ($country == $country_option) ? 'selected' : ''; ?>><?php echo $country_option; ?></option>
                            <?php endforeach; ?>
                        </select>
                        <div class="field-hint" id="hint_country">
                            <i class="fas fa-info-circle"></i> Select your country of residence
                        </div>
                    </div>
                    
                    <!-- ID Card Number (Next to Country) -->
                    <div class="input-group" id="id_card_group">
                        <label><i class="fas fa-id-card"></i> <span id="id_card_label">CNIC Number</span> <span class="required">*</span></label>
                        <input type="text" name="id_card_number" id="id_card_number" required 
                               value="<?php echo htmlspecialchars($id_card_number ?? ''); ?>" 
                               placeholder="Enter your CNIC/ID number"
                               onkeyup="validateIdCardField(this)"
                               onblur="validateIdCardField(this)">
                        <div class="field-hint" id="hint_id_card_number">
                            <i class="fas fa-info-circle"></i> <span id="id_card_hint">Enter your 13-digit CNIC number (e.g., 12345-1234567-1)</span>
                        </div>
                    </div>
                    
                    <!-- Cell Number -->
                    <div class="input-group">
                        <label><i class="fas fa-phone"></i> Cell Number <span class="required">*</span></label>
                        <input type="tel" name="cell_no" id="cell_no" required 
                               value="<?php echo htmlspecialchars($cell_no ?? ''); ?>" 
                               placeholder="+92 300 1234567"
                               onkeyup="validatePhoneField(this)"
                               onblur="validatePhoneField(this)">
                        <div class="field-hint" id="hint_cell_no">
                            <i class="fas fa-info-circle"></i> 10-15 digits (e.g., +92 300 1234567)
                        </div>
                    </div>
                    
                    <!-- WhatsApp Number -->
                    <div class="input-group">
                        <label><i class="fab fa-whatsapp"></i> WhatsApp Number <span class="required">*</span></label>
                        <input type="tel" name="whatsapp_number" id="whatsapp_number" required 
                               value="<?php echo htmlspecialchars($whatsapp_number ?? ''); ?>" 
                               placeholder="+92 300 1234567"
                               onkeyup="validatePhoneField(this)"
                               onblur="validatePhoneField(this)">
                        <div class="field-hint" id="hint_whatsapp_number">
                            <i class="fas fa-info-circle"></i> 10-15 digits (e.g., +92 300 1234567)
                        </div>
                    </div>
                    
                    <!-- AHPC Registration Number (Optional) -->
                    <div class="input-group">
                        <label><i class="fas fa-stethoscope"></i> AHPC Registration Number <span class="optional">(Optional)</span></label>
                        <input type="text" name="ahpc_reg_number" id="ahpc_reg_number" 
                               value="<?php echo htmlspecialchars($ahpc_reg_number ?? ''); ?>" 
                               placeholder="Enter your AHPC registration number"
                               onkeyup="validateTextField(this)"
                               onblur="validateTextField(this)">
                        <div class="field-hint" id="hint_ahpc_reg_number">
                            <i class="fas fa-info-circle"></i> Enter your AHPC registration number (Optional)
                        </div>
                    </div>
                    
                    <!-- Institute -->
                    <div class="input-group full-width">
                        <label><i class="fas fa-building"></i> Institute/Organization <span class="required">*</span></label>
                        <input type="text" name="institute" id="institute" required 
                               value="<?php echo htmlspecialchars($institute ?? ''); ?>" 
                               placeholder="Your institution"
                               onkeyup="validateTextField(this)"
                               onblur="validateTextField(this)">
                        <div class="field-hint" id="hint_institute">
                            <i class="fas fa-info-circle"></i> 3-100 characters
                        </div>
                    </div>
                    
                    <!-- Student Document Upload -->
                    <div class="input-group full-width" id="student_doc_group" style="display: none;">
                        <label><i class="fas fa-upload"></i> Student ID Card <?php if(empty($student_document)): ?><span class="required">*</span><?php endif; ?></label>
                        <input type="file" name="student_document" id="student_document" class="file-input" accept=".jpg,.jpeg,.png,.pdf">
                        <?php if(!empty($student_document)): ?>
                            <div class="current-file">
                                <i class="fas fa-check-circle"></i> Current file: <a href="<?php echo $student_document; ?>" target="_blank">View Uploaded Document</a>
                                <br><small>Leave empty to keep current file</small>
                            </div>
                        <?php endif; ?>
                        <div class="field-hint" id="hint_student_document">
                            <i class="fas fa-info-circle"></i> Upload your student ID card (JPG, PNG, PDF)
                        </div>
                    </div>
                    
                    <!-- Address (Optional) -->
                    <div class="input-group full-width">
                        <label><i class="fas fa-location-dot"></i> Address <span class="optional">(Optional)</span></label>
                        <textarea name="address" id="address" 
                                  placeholder="Your complete address (optional)"
                                  onkeyup="validateAddressField(this)"
                                  onblur="validateAddressField(this)"><?php echo htmlspecialchars($address ?? ''); ?></textarea>
                        <div class="field-hint" id="hint_address">
                            <i class="fas fa-info-circle"></i> Enter your address (Optional)
                        </div>
                    </div>
                </div>
                
                <button type="submit" name="save_registration" class="btn-submit">
                    <i class="fas fa-paper-plane"></i>
                    <?php echo $existing_reg ? 'Update Registration' : 'Submit Registration'; ?>
                </button>
                
                <?php if($existing_reg): ?>
                    <a href="registration.php" class="btn-submit btn-new" style="text-align: center; text-decoration: none; display: block;">
                        <i class="fas fa-plus"></i> New Registration
                    </a>
                <?php endif; ?>
            </form>
            
            <!-- Display All Registrations -->
            <?php if(!empty($all_registrations)): ?>
            <div class="registrations-table">
                <h4><i class="fas fa-history"></i> Your Registrations</h4>
                <table class="data-table">
                    <thead>
                        <tr>
                            <th>#</th>
                            <th>Name</th>
                            <th>Category</th>
                            <th>Event</th>
                            <th>Team Members</th>
                            <th>Date</th>
                            <th>Actions</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php $counter = 1; ?>
                        <?php foreach($all_registrations as $reg): ?>
                        <tr>
                            <td><?php echo $counter++; ?></td>
                            <td><?php echo htmlspecialchars($reg['first_name'] . ' ' . $reg['last_name']); ?></td>
                            <td><?php echo htmlspecialchars($reg['category']); ?> - <?php echo htmlspecialchars($reg['category_two']); ?></td>
                            <td><?php echo htmlspecialchars($reg['event_type']); ?></td>
                            <td>
                                <?php
                                $stmt_count = $pdo->prepare("SELECT COUNT(*) as count FROM team_members WHERE registration_id = ?");
                                $stmt_count->execute([$reg['id']]);
                                $count = $stmt_count->fetch(PDO::FETCH_ASSOC);
                                echo $count['count'] . ' members';
                                ?>
                             </td>
                            <td><?php 
                                $reg_date = $reg['registration_date'] ?? date('Y-m-d');
                                echo date('d-m-Y', strtotime($reg_date)); 
                            ?></td>
                            <td>
                                <button type="button" class="view-reg-btn" onclick="showRegistrationDetails(<?php echo $reg['id']; ?>)">
                                    <i class="fas fa-eye"></i> View
                                </button>
                                <a href="?edit_id=<?php echo $reg['id']; ?>" class="edit-reg-btn">
                                    <i class="fas fa-edit"></i> Edit
                                </a>
                                <a href="#" class="checkout-btn">
                                    <i class="fas fa-shopping-cart"></i> Checkout
                                </a>
                             </td>
                        </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
            <?php endif; ?>
        </div>
    </div>

    <!-- Registration Details Modal -->
    <div id="detailsModal" class="modal">
        <div class="modal-content">
            <div class="modal-header">
                <h3><i class="fas fa-info-circle"></i> Registration Details</h3>
                <span class="close-modal" onclick="closeModal()">&times;</span>
            </div>
            <div class="modal-body" id="modalBody">
                <div style="text-align: center; padding: 20px;">
                    <i class="fas fa-spinner fa-spin"></i> Loading...
                </div>
            </div>
        </div>
    </div>

    <script>
        const existingTeamMembers = <?php echo json_encode($team_members); ?>;
        const currentCategory = '<?php echo $category; ?>';
        const currentCategoryTwo = '<?php echo $category_two; ?>';
        const currentEventType = '<?php echo $event_type; ?>';
        const currentRegistrationType = '<?php echo $registration_type; ?>';
        const currentCountry = '<?php echo $country; ?>';
        const specialtyList = <?php echo json_encode($specialty_list); ?>;
        
        // Update ID Card fields based on country
        function updateIdCardFields() {
            const country = document.getElementById('country').value;
            const idCardLabel = document.getElementById('id_card_label');
            const idCardHint = document.getElementById('id_card_hint');
            const idCardInput = document.getElementById('id_card_number');
            
            if (country === 'Pakistan') {
                idCardLabel.innerHTML = 'CNIC Number';
                idCardHint.innerHTML = 'Enter your 13-digit CNIC number (e.g., 12345-1234567-1)';
                idCardInput.placeholder = '12345-1234567-1';
            } else {
                idCardLabel.innerHTML = 'Passport Number';
                idCardHint.innerHTML = 'Enter your passport number';
                idCardInput.placeholder = 'Enter your Passport number';
            }
        }
        
        // Toggle Category 2 options based on Category 1
        function toggleCategoryTwo() {
            const category = document.getElementById('category').value;
            const categoryTwoSelect = document.getElementById('category_two');
            const studentDocGroup = document.getElementById('student_doc_group');
            const packageTypeGroup = document.getElementById('package_type_group');
            const designationGroup = document.getElementById('designation_group');
            const teamSection = document.getElementById('teamSection');
            
            categoryTwoSelect.innerHTML = '<option value="">Select option</option>';
            
            if (category === 'Professional') {
                // Professional: Show Individual and Package
                const opt1 = document.createElement('option');
                opt1.value = 'Individual';
                opt1.textContent = 'Individual';
                const opt2 = document.createElement('option');
                opt2.value = 'Package';
                opt2.textContent = 'Package';
                categoryTwoSelect.appendChild(opt1);
                categoryTwoSelect.appendChild(opt2);
                studentDocGroup.style.display = 'none';
                designationGroup.style.display = 'block';
                document.getElementById('student_document').required = false;
                document.getElementById('designation').required = true;
                
                if (currentCategoryTwo) {
                    categoryTwoSelect.value = currentCategoryTwo;
                }
                if (currentCategory === 'Professional') {
                    document.getElementById('designation').value = '<?php echo addslashes($designation); ?>';
                }
            } else if (category === 'Student') {
                // Student: Only Individual
                const opt = document.createElement('option');
                opt.value = 'Individual';
                opt.textContent = 'Individual';
                categoryTwoSelect.appendChild(opt);
                studentDocGroup.style.display = 'block';
                designationGroup.style.display = 'none';
                document.getElementById('designation').required = false;
                <?php if(empty($student_document)): ?>
                    document.getElementById('student_document').required = true;
                <?php else: ?>
                    document.getElementById('student_document').required = false;
                <?php endif; ?>
                packageTypeGroup.style.display = 'none';
                teamSection.style.display = 'none';
                
                if (currentCategoryTwo) {
                    categoryTwoSelect.value = currentCategoryTwo;
                }
            }
            
            toggleEventsAndPackage();
        }
        
        // Toggle Events and Package based on Category 2
        function toggleEventsAndPackage() {
            const category = document.getElementById('category').value;
            const categoryTwo = document.getElementById('category_two').value;
            const eventSelect = document.getElementById('event_type');
            const packageTypeGroup = document.getElementById('package_type_group');
            const teamSection = document.getElementById('teamSection');
            
            eventSelect.innerHTML = '<option value="">Select an event</option>';
            
            // Only Conference and Gala Dinner events
            const events = ['Conference Registration', 'Gala Dinner'];
            
            if (category === 'Professional') {
                if (categoryTwo === 'Individual') {
                    events.forEach(event => {
                        const opt = document.createElement('option');
                        opt.value = event;
                        opt.textContent = event;
                        eventSelect.appendChild(opt);
                    });
                    packageTypeGroup.style.display = 'none';
                    teamSection.style.display = 'none';
                    document.getElementById('registration_type').required = false;
                    
                    if (currentEventType && currentCategoryTwo !== 'Package') {
                        eventSelect.value = currentEventType;
                    }
                    
                } else if (categoryTwo === 'Package') {
                    const opt = document.createElement('option');
                    opt.value = 'Conference Registration';
                    opt.textContent = 'Conference Registration';
                    eventSelect.appendChild(opt);
                    eventSelect.value = 'Conference Registration';
                    
                    packageTypeGroup.style.display = 'block';
                    document.getElementById('registration_type').required = true;
                    
                    if (currentRegistrationType) {
                        document.getElementById('registration_type').value = currentRegistrationType;
                    }
                    updateTeamFields();
                }
            } else if (category === 'Student') {
                events.forEach(event => {
                    const opt = document.createElement('option');
                    opt.value = event;
                    opt.textContent = event;
                    eventSelect.appendChild(opt);
                });
                packageTypeGroup.style.display = 'none';
                teamSection.style.display = 'none';
                
                if (currentEventType) {
                    eventSelect.value = currentEventType;
                }
            }
        }
        
        // Update Team Fields based on package selection
        function updateTeamFields() {
            const registrationType = document.getElementById('registration_type').value;
            const teamSection = document.getElementById('teamSection');
            const container = document.getElementById('teamMembersContainer');
            
            let count = 0;
            if (registrationType === 'Group Discount (5 Person)') {
                count = 5;
            } else if (registrationType === 'Group Discount (10 Person)') {
                count = 10;
            }
            
            generateTeamMembers(count, existingTeamMembers);
            
            if (count > 0) {
                teamSection.style.display = 'block';
            } else {
                teamSection.style.display = 'none';
            }
        }
        
        function generateTeamMembers(count, existing = []) {
            const container = document.getElementById('teamMembersContainer');
            if (!container) return;
            container.innerHTML = '';
            if (count === 0) return;
            
            for (let i = 0; i < count; i++) {
                const ex = existing[i] || {};
                
                // Build checkbox options for team member specialties
                let checkboxOptions = '';
                specialtyList.forEach(specialty => {
                    const isChecked = ex.interest_field && ex.interest_field.indexOf(specialty) !== -1;
                    checkboxOptions += `
                        <label>
                            <input type="checkbox" name="member_interest[${i}][]" value="${specialty}" ${isChecked ? 'checked' : ''}>
                            ${specialty}
                        </label>
                    `;
                });
                
                const memberDiv = document.createElement('div');
                memberDiv.className = 'team-member-card';
                memberDiv.innerHTML = `
                    <div class="team-member-title"><i class="fas fa-user-friends"></i> Team Member ${i+1}</div>
                    <div class="team-grid">
                        <div>
                            <label>Full Name *</label>
                            <input type="text" name="member_name[]" required value="${escapeHtml(ex.name || '')}" placeholder="Full name">
                        </div>
                        <div>
                            <label>Email *</label>
                            <input type="email" name="member_email[]" required value="${escapeHtml(ex.email || '')}" placeholder="Email">
                        </div>
                        <div>
                            <label>Phone *</label>
                            <input type="tel" name="member_phone[]" required value="${escapeHtml(ex.phone || '')}" placeholder="Phone">
                        </div>
                        <div>
                            <label>Designation *</label>
                            <input type="text" name="member_designation[]" required value="${escapeHtml(ex.designation || '')}" placeholder="Designation">
                        </div>
                        <div>
                            <label>Specialty / Discipline *</label>
                            <div class="team-member-checkbox-list">
                                ${checkboxOptions}
                            </div>
                        </div>
                    </div>
                `;
                container.appendChild(memberDiv);
            }
        }
        
        function escapeHtml(str) { return !str ? '' : str.replace(/[&<>]/g, m => ({'&':'&amp;','<':'&lt;','>':'&gt;'}[m])); }
        
        // Phone validation
        function validatePhoneField(input) {
            const value = input.value.trim();
            const hint = document.getElementById('hint_' + input.id);
            const phoneRegex = /^[\+\d][\d\s\-\(\)]{9,14}$/;
            let isValid = false, msg = '';
            
            if (!value) msg = '❌ Required';
            else if (!phoneRegex.test(value)) msg = '❌ 10-15 digits required';
            else { isValid = true; msg = '✓ Valid'; }
            
            if (hint) {
                hint.innerHTML = `<i class="fas ${isValid ? 'fa-check-circle' : 'fa-exclamation-circle'}"></i> ${msg}`;
                hint.className = `field-hint ${isValid ? 'success-hint' : 'error-hint'}`;
            }
            input.classList.toggle('invalid', !isValid);
            input.classList.toggle('valid', isValid);
            return isValid;
        }
        
        // Text field validation
        function validateTextField(input) {
            const value = input.value.trim();
            const hint = document.getElementById('hint_' + input.id);
            const isOptional = input.id === 'ahpc_reg_number' || input.id === 'address';
            
            if (isOptional && value === '') {
                if (hint) {
                    hint.innerHTML = `<i class="fas fa-info-circle"></i> Optional field`;
                    hint.className = 'field-hint';
                }
                return true;
            }
            
            let isValid = value.length >= 2 && value.length <= 100;
            let msg = isValid ? '✓ Valid' : '❌ Min 2 characters';
            
            if (hint) {
                hint.innerHTML = `<i class="fas ${isValid ? 'fa-check-circle' : 'fa-exclamation-circle'}"></i> ${msg}`;
                hint.className = `field-hint ${isValid ? 'success-hint' : 'error-hint'}`;
            }
            input.classList.toggle('invalid', !isValid);
            input.classList.toggle('valid', isValid);
            return isValid;
        }
        
        // ID Card validation
        function validateIdCardField(input) {
            const value = input.value.trim();
            const hint = document.getElementById('hint_id_card_number');
            const country = document.getElementById('country').value;
            let isValid = false, msg = '';
            
            if (!value) {
                msg = '❌ Required';
            } else if (country === 'Pakistan') {
                const cnicRegex = /^\d{5}-\d{7}-\d{1}$/;
                if (!cnicRegex.test(value)) {
                    msg = '❌ Invalid CNIC format (e.g., 12345-1234567-1)';
                } else {
                    isValid = true;
                    msg = '✓ Valid CNIC';
                }
            } else {
                if (value.length < 5) {
                    msg = '❌ Min 5 characters';
                } else {
                    isValid = true;
                    msg = '✓ Valid';
                }
            }
            
            if (hint) {
                hint.innerHTML = `<i class="fas ${isValid ? 'fa-check-circle' : 'fa-exclamation-circle'}"></i> ${msg}`;
                hint.className = `field-hint ${isValid ? 'success-hint' : 'error-hint'}`;
            }
            input.classList.toggle('invalid', !isValid);
            input.classList.toggle('valid', isValid);
            return isValid;
        }
        
        function validateAddressField(input) {
            const value = input.value.trim();
            const hint = document.getElementById('hint_address');
            
            // Address is optional
            if (value === '') {
                if (hint) {
                    hint.innerHTML = `<i class="fas fa-info-circle"></i> Optional field`;
                    hint.className = 'field-hint';
                }
                return true;
            }
            
            const isValid = value.length >= 10 && value.length <= 500;
            const msg = isValid ? '✓ Valid' : '❌ 10-500 characters';
            
            if (hint) {
                hint.innerHTML = `<i class="fas ${isValid ? 'fa-check-circle' : 'fa-exclamation-circle'}"></i> ${msg}`;
                hint.className = `field-hint ${isValid ? 'success-hint' : 'error-hint'}`;
            }
            input.classList.toggle('invalid', !isValid);
            input.classList.toggle('valid', isValid);
            return isValid;
        }
        
        function validateForm() {
            let all = true;
            
            if (!validatePhoneField(document.getElementById('cell_no'))) all = false;
            if (!validatePhoneField(document.getElementById('whatsapp_number'))) all = false;
            if (!validateTextField(document.getElementById('institute'))) all = false;
            if (!validateIdCardField(document.getElementById('id_card_number'))) all = false;
            
            const country = document.getElementById('country').value;
            const category = document.getElementById('category').value;
            const categoryTwo = document.getElementById('category_two').value;
            const eventType = document.getElementById('event_type').value;
            
            // Validate specialty checkboxes
            const specialtyCheckboxes = document.querySelectorAll('input[name="interest_field[]"]:checked');
            if (specialtyCheckboxes.length === 0) {
                alert('Please select at least one Specialty/Discipline');
                all = false;
            }
            
            if (!country) { alert('Please select country'); all = false; }
            if (!category) { alert('Please select category'); all = false; }
            if (!categoryTwo) { alert('Please select registration category'); all = false; }
            if (!eventType) { alert('Please select event type'); all = false; }
            
            if (category === 'Professional') {
                const designation = document.getElementById('designation').value;
                if (!designation) { alert('Please enter designation'); all = false; }
            }
            
            if (category === 'Professional' && categoryTwo === 'Package') {
                const registrationType = document.getElementById('registration_type').value;
                if (!registrationType) { alert('Please select package type'); all = false; }
                
                const container = document.getElementById('teamMembersContainer');
                const teamCards = container ? container.children : [];
                const expectedCount = registrationType === 'Group Discount (5 Person)' ? 5 : 10;
                
                if (teamCards.length !== expectedCount) {
                    alert(`Please add all ${expectedCount} team members`);
                    all = false;
                }
            }
            
            if (category === 'Student') {
                const studentDoc = document.getElementById('student_document');
                const hasExisting = <?php echo json_encode(!empty($student_document)); ?>;
                if (!studentDoc.files.length && !hasExisting) {
                    alert('Please upload your student ID card or CNIC copy');
                    all = false;
                }
            }
            
            if (!all) alert('Please fix errors before submitting');
            return all;
        }
        
        // Show Registration Details Modal
        function showRegistrationDetails(regId) {
            const modal = document.getElementById('detailsModal');
            const modalBody = document.getElementById('modalBody');
            
            modal.style.display = 'block';
            modalBody.innerHTML = '<div style="text-align: center; padding: 20px;"><i class="fas fa-spinner fa-spin"></i> Loading...</div>';
            
            fetch(`get_registration_details.php?id=${regId}`)
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        const reg = data.data;
                        const teamMembers = data.team_members || [];
                        
                        let teamHtml = '';
                        if (teamMembers.length > 0) {
                            teamHtml = '<div class="detail-section"><h4><i class="fas fa-users"></i> Team Members</h4><div class="team-member-list">';
                            teamMembers.forEach((member, index) => {
                                const specialtyDisplay = (member.interest_field && member.interest_field.trim() !== '') 
                                    ? escapeHtml(member.interest_field) 
                                    : 'Not specified';
                                teamHtml += `
                                    <div class="team-member-item">
                                        <strong>${index + 1}. ${escapeHtml(member.name)}</strong><br>
                                        <span style="font-size: 12px;">📧 ${escapeHtml(member.email)}</span><br>
                                        <span style="font-size: 12px;">📞 ${escapeHtml(member.phone)}</span><br>
                                        <span style="font-size: 12px;">👔 ${escapeHtml(member.designation || 'Not specified')}</span><br>
                                        <span style="font-size: 12px;">🎯 ${specialtyDisplay}</span>
                                    </div>
                                `;
                            });
                            teamHtml += '</div></div>';
                        }
                        
                        modalBody.innerHTML = `
                            <div class="detail-section">
                                <h4><i class="fas fa-user"></i> Personal Information</h4>
                                <div class="detail-row"><div class="detail-label">Name:</div><div class="detail-value">${escapeHtml(reg.first_name)} ${escapeHtml(reg.last_name)}</div></div>
                                <div class="detail-row"><div class="detail-label">Email:</div><div class="detail-value">${escapeHtml(reg.email)}</div></div>
                                <div class="detail-row"><div class="detail-label">Country:</div><div class="detail-value">${escapeHtml(reg.country)}</div></div>
                                <div class="detail-row"><div class="detail-label">ID Card:</div><div class="detail-value">${escapeHtml(reg.id_card_number)}</div></div>
                                <div class="detail-row"><div class="detail-label">Cell Number:</div><div class="detail-value">${escapeHtml(reg.cell_no)}</div></div>
                                <div class="detail-row"><div class="detail-label">WhatsApp:</div><div class="detail-value">${escapeHtml(reg.whatsapp_number)}</div></div>
                                <div class="detail-row"><div class="detail-label">Address:</div><div class="detail-value">${escapeHtml(reg.address) || 'Not provided'}</div></div>
                            </div>
                            <div class="detail-section">
                                <h4><i class="fas fa-briefcase"></i> Professional Information</h4>
                                <div class="detail-row"><div class="detail-label">Category:</div><div class="detail-value">${escapeHtml(reg.category)} - ${escapeHtml(reg.category_two)}</div></div>
                                ${reg.designation ? `<div class="detail-row"><div class="detail-label">Designation:</div><div class="detail-value">${escapeHtml(reg.designation)}</div></div>` : ''}
                                <div class="detail-row"><div class="detail-label">Specialty/Discipline:</div><div class="detail-value">${escapeHtml(reg.interest_field) || 'Not specified'}</div></div>
                                <div class="detail-row"><div class="detail-label">Event:</div><div class="detail-value">${escapeHtml(reg.event_type)}</div></div>
                                ${reg.registration_type ? `<div class="detail-row"><div class="detail-label">Package Type:</div><div class="detail-value">${escapeHtml(reg.registration_type)}</div></div>` : ''}
                                <div class="detail-row"><div class="detail-label">AHPC Number:</div><div class="detail-value">${escapeHtml(reg.ahpc_reg_number) || 'Not provided'}</div></div>
                                <div class="detail-row"><div class="detail-label">Institute:</div><div class="detail-value">${escapeHtml(reg.institute)}</div></div>
                                ${reg.student_document ? `<div class="detail-row"><div class="detail-label">Student Document:</div><div class="detail-value"><a href="${escapeHtml(reg.student_document)}" target="_blank">View Document</a></div></div>` : ''}
                            </div>
                            ${teamHtml}
                            <div class="detail-section">
                                <h4><i class="fas fa-calendar"></i> Registration Info</h4>
                                <div class="detail-row"><div class="detail-label">Registration Date:</div><div class="detail-value">${new Date(reg.registration_date).toLocaleDateString()}</div></div>
                                <div class="detail-row"><div class="detail-label">Registration ID:</div><div class="detail-value">ARC-${reg.id}</div></div>
                            </div>
                        `;
                    } else {
                        modalBody.innerHTML = `<div class="alert alert-error">${data.message}</div>`;
                    }
                })
                .catch(error => {
                    modalBody.innerHTML = `<div class="alert alert-error">Error loading details</div>`;
                });
        }
        
        function closeModal() {
            document.getElementById('detailsModal').style.display = 'none';
        }
        
        // Initialize all dynamic fields
        document.addEventListener('DOMContentLoaded', function() {
            updateIdCardFields();
            toggleCategoryTwo();
            
            // Add event listeners
            document.getElementById('category').addEventListener('change', toggleCategoryTwo);
            document.getElementById('category_two').addEventListener('change', toggleEventsAndPackage);
            document.getElementById('registration_type').addEventListener('change', updateTeamFields);
        });
        
        window.onclick = function(event) {
            const modal = document.getElementById('detailsModal');
            if (event.target === modal) {
                closeModal();
            }
        }
    </script>
</body>
</html>