<?php
require_once 'auth_rbac.php';
require_once '../db_config.php';


// Require admin login
requirePermission('delegates', 'view');

$currentPage = 'delegates';

// Handle delegate update
if (isset($_POST['action']) && $_POST['action'] === 'update_delegate' && isset($_POST['delegate_id'])) {
    try {
        $pdo = getDBConnection();
        
        // Handle dietary requirements - use "other" text if "other" option selected
        $dietary_requirements = $_POST['dietary_requirements'];
        if ($dietary_requirements === '__other__' && !empty($_POST['dietary_other'])) {
            $dietary_requirements = json_encode([$_POST['dietary_other']]);
        } elseif ($dietary_requirements === '__other__') {
            $dietary_requirements = '[]';
        } elseif (!empty($dietary_requirements)) {
            // Store as JSON array to match database format
            $dietary_requirements = json_encode([$dietary_requirements]);
        } else {
            $dietary_requirements = '[]';
        }
        
        $stmt = $pdo->prepare("
            UPDATE delegates 
            SET full_name = ?, badge_name = ?, designation = ?, department = ?, email = ?,
                dietary_requirements = ?, special_assistance = ?, updated_at = NOW()
            WHERE id = ?
        ");
        
        $stmt->execute([
            $_POST['full_name'],
            $_POST['badge_name'],
            $_POST['designation'],
            $_POST['department'],
            $_POST['email'] ?? null,
            $dietary_requirements,
            $_POST['special_assistance'],
            $_POST['delegate_id']
        ]);
        
        if ($stmt->rowCount() > 0) {
            // Redirect to prevent form resubmission
            header("Location: delegates.php?success=delegate_updated&id=" . $_POST['delegate_id']);
            exit();
        } else {
            $error = "No changes were made to the delegate information.";
        }
    } catch (Exception $e) {
        $error = "Error updating delegate: " . $e->getMessage();
    }
}

// Handle success message from redirect
if (isset($_GET['success']) && $_GET['success'] === 'delegate_updated') {
    $success = "Delegate information updated successfully!";
}

// Pagination
$page = isset($_GET['page']) ? max(1, intval($_GET['page'])) : 1;
$per_page = 25;
$offset = ($page - 1) * $per_page;

// Search and filter
$search = $_GET['search'] ?? '';
$dietary_filter = $_GET['dietary'] ?? '';
$assistance_filter = $_GET['assistance'] ?? '';
$status_filter = $_GET['status'] ?? '';
$product_code_filter = $_GET['product_code'] ?? '';

try {
    $pdo = getDBConnection();
    
    // Build WHERE clause
    $where_conditions = [];
    $params = [];
    
    if (!empty($search)) {
        $where_conditions[] = "(d.full_name LIKE ? OR d.badge_name LIKE ? OR d.designation LIKE ? OR r.registration_number LIKE ?)";
        $search_param = "%{$search}%";
        $params = array_merge($params, [$search_param, $search_param, $search_param, $search_param]);
    }
    
    if (!empty($dietary_filter)) {
        $where_conditions[] = "d.dietary_requirements LIKE ?";
        $params[] = "%{$dietary_filter}%";
    }
    
    if (!empty($status_filter)) {
        $where_conditions[] = "r.payment_status = ?";
        $params[] = $status_filter;
    }
    
    if ($assistance_filter === 'yes') {
        $where_conditions[] = "d.special_assistance IS NOT NULL AND d.special_assistance != ''";
    } elseif ($assistance_filter === 'no') {
        $where_conditions[] = "(d.special_assistance IS NULL OR d.special_assistance = '')";
    }
    
    if (!empty($product_code_filter)) {
        $where_conditions[] = "(EXISTS (
            SELECT 1 FROM registration_products rp2 
            JOIN products p2 ON rp2.product_id = p2.id 
            JOIN product_categories pc2 ON p2.category_id = pc2.id 
            WHERE rp2.registration_id = r.id 
            AND pc2.name = 'Delegate Pass' 
            AND p2.product_code = ?
        ) OR (NOT EXISTS (
            SELECT 1 FROM registration_products rp3 
            JOIN products p3 ON rp3.product_id = p3.id 
            JOIN product_categories pc3 ON p3.category_id = pc3.id 
            WHERE rp3.registration_id = r.id 
            AND pc3.name = 'Delegate Pass'
        ) AND r.delegate_type = ?))";
        $params[] = $product_code_filter;
        // Handle legacy mapping
        $legacy_type = $product_code_filter === 'DELEGATE_EARLY_BIRD' ? 'earlyBird' : 'standard';
        $params[] = $legacy_type;
    }
    
    $where_clause = !empty($where_conditions) ? "WHERE " . implode(" AND ", $where_conditions) : "";
    
    // Get total count for pagination
    $count_query = "
        SELECT COUNT(DISTINCT d.id) 
        FROM delegates d 
        JOIN registrations r ON d.registration_id = r.id 
        LEFT JOIN registration_products rp ON r.id = rp.registration_id
        LEFT JOIN products p ON rp.product_id = p.id
        LEFT JOIN product_categories pc ON p.category_id = pc.id
        {$where_clause}
    ";
    $stmt = $pdo->prepare($count_query);
    $stmt->execute($params);
    $total_records = $stmt->fetchColumn();
    $total_pages = ceil($total_records / $per_page);
    
    // Get delegates with registration info and delegate product code
    $query = "
        SELECT 
            d.*,
            r.registration_number,
            r.contact_full_name as contact_name,
            r.university_name,
            r.delegate_type,
            r.payment_status,
            r.created_at as registration_date,
            MAX(CASE WHEN pc.name = 'Delegate Pass' THEN rp.pricing_tier END) as pricing_tier,
            MAX(CASE WHEN pc.name = 'Delegate Pass' THEN p.product_code END) as product_code
        FROM delegates d 
        JOIN registrations r ON d.registration_id = r.id 
        LEFT JOIN registration_products rp ON r.id = rp.registration_id
        LEFT JOIN products p ON rp.product_id = p.id
        LEFT JOIN product_categories pc ON p.category_id = pc.id
        {$where_clause}
        GROUP BY d.id, r.registration_number, r.contact_full_name, r.university_name, r.delegate_type, r.payment_status, r.created_at
        ORDER BY r.created_at DESC, d.id ASC
        LIMIT {$per_page} OFFSET {$offset}
    ";
    
    $stmt = $pdo->prepare($query);
    $stmt->execute($params);
    $delegates = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    // Get delegate statistics
    $stats_query = "
        SELECT 
            COUNT(*) as total_delegates,
            COUNT(CASE WHEN r.payment_status = 'paid' THEN 1 END) as paid_delegates,
            COUNT(CASE WHEN r.payment_status = 'pending' THEN 1 END) as pending_delegates,
            COUNT(CASE WHEN d.dietary_requirements IS NOT NULL AND d.dietary_requirements != '' AND d.dietary_requirements != '[]' THEN 1 END) as delegates_with_dietary,
            COUNT(CASE WHEN d.special_assistance IS NOT NULL AND d.special_assistance != '' THEN 1 END) as delegates_with_assistance
        FROM delegates d
        LEFT JOIN registrations r ON d.registration_id = r.id
    ";
    $stats = $pdo->query($stats_query)->fetch(PDO::FETCH_ASSOC);
    
    // Get dietary options from admin_settings table
    $dietary_options_query = "SELECT setting_value FROM admin_settings WHERE setting_key = 'dietaryOptions'";
    $dietary_json = $pdo->query($dietary_options_query)->fetchColumn();
    
    $dietary_options = [];
    if ($dietary_json) {
        $decoded = json_decode($dietary_json, true);
        if (is_array($decoded)) {
            $dietary_options = $decoded;
        }
    }
    
    // Fallback if no options found in settings
    if (empty($dietary_options)) {
        $dietary_options = ["None", "Non Veg (Chicken)", "Non Veg (Fish)", "Veg"];
    }
    
    // Get available product codes for delegate products
    $product_codes_query = "
        SELECT p.product_code, p.name, p.display_order
        FROM products p
        JOIN product_categories pc ON p.category_id = pc.id
        WHERE pc.name = 'Delegate Pass' AND p.is_active = 1
        GROUP BY p.product_code, p.name, p.display_order
        ORDER BY p.display_order, p.name
    ";
    $product_codes_result = $pdo->query($product_codes_query)->fetchAll(PDO::FETCH_ASSOC);
    
    // Add legacy options for registrations without products
    $product_codes = [
        ['product_code' => 'DELEGATE_EARLY_BIRD', 'name' => 'Early Bird Delegate'],
        ['product_code' => 'DELEGATE_STANDARD', 'name' => 'Standard Delegate']
    ];
    
    // Merge with actual product codes from database
    foreach ($product_codes_result as $pc) {
        $exists = false;
        foreach ($product_codes as $existing) {
            if ($existing['product_code'] === $pc['product_code']) {
                $exists = true;
                break;
            }
        }
        if (!$exists) {
            $product_codes[] = $pc;
        }
    }
    
} catch (Exception $e) {
    $error = "Database error: " . $e->getMessage();
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Delegates - XChange Admin</title>
    <?php include '../includes/favicon.php'; ?>
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
    <link href="https://fonts.googleapis.com/css2?family=Poppins:wght@400;600;700;800;900&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="../styles.css">
    <link rel="stylesheet" href="admin.css">
    <style>
        /* Full width layout for delegates page - 95% to prevent horizontal scroll */
        body .admin-content {
            max-width: 95vw !important;
            width: 95vw !important;
            margin: 0 auto !important;
            padding: 2rem 15px 60px 15px !important;
        }
        
        /* Override any parent container constraints */
        body {
            overflow-x: auto;
        }
        
        /* Ensure table doesn't overflow */
        .table-container {
            overflow-x: auto;
            width: 100%;
            max-width: 100%;
        }
        
        /* Make table responsive and ensure it uses full width */
        .table {
            min-width: 100%;
            width: 100%;
            table-layout: auto;
        }
        
        /* Force full width for all content areas */
        .admin-content .stats-grid,
        .admin-content .search-filters,
        .admin-content .table-container,
        .admin-content > * {
            max-width: 100% !important;
            width: 100% !important;
        }
        
        /* Allow text wrapping for better content visibility */
        .table td, .table th {
            white-space: normal;
            word-wrap: break-word;
            word-break: break-word;
            padding: 6px 8px;
            font-size: 13px;
            line-height: 1.4;
            color: #000000 !important;
            vertical-align: top;
        }
        
        /* Make table headers slightly larger but still compact */
        .table th {
            font-size: 14px;
            font-weight: 600;
        }
        
        /* Make specific text elements smaller */
        .table .status-badge {
            font-size: 11px;
            padding: 2px 6px;
        }
        
        .table .btn {
            font-size: 12px;
            padding: 4px 8px;
        }
        
        /* Flexible column widths with text wrapping support */
        .table th:nth-child(1), .table td:nth-child(1) { 
            min-width: 100px; 
            max-width: 120px; 
        } /* Registration # */
        .table th:nth-child(2), .table td:nth-child(2) { 
            min-width: 120px; 
            max-width: 200px; 
        } /* Full Name */
        .table th:nth-child(3), .table td:nth-child(3) { 
            min-width: 100px; 
            max-width: 150px; 
        } /* Badge Name */
        .table th:nth-child(4), .table td:nth-child(4) { 
            min-width: 150px; 
            max-width: 250px; 
        } /* Email */
        .table th:nth-child(5), .table td:nth-child(5) { 
            min-width: 100px; 
            max-width: 150px; 
        } /* Designation */
        .table th:nth-child(6), .table td:nth-child(6) { 
            min-width: 120px; 
            max-width: 180px; 
        } /* Department */
        .table th:nth-child(7), .table td:nth-child(7) { 
            min-width: 120px; 
            max-width: 200px; 
        } /* University */
        .table th:nth-child(8), .table td:nth-child(8) { 
            min-width: 80px; 
            max-width: 120px; 
        } /* Dietary */
        .table th:nth-child(9), .table td:nth-child(9) { 
            min-width: 100px; 
            max-width: 150px; 
        } /* Assistance */
        .table th:nth-child(10), .table td:nth-child(10) { 
            min-width: 100px; 
            max-width: 120px; 
        } /* Product Code */
        .table th:nth-child(11), .table td:nth-child(11) { 
            min-width: 80px; 
            max-width: 100px; 
        } /* Status */
        .table th:nth-child(12), .table td:nth-child(12) { 
            min-width: 80px; 
            max-width: 100px; 
        } /* Actions */
    </style>
</head>
<body>
    <?php include 'includes/admin_nav.php'; ?>

    <div class="admin-content">
        <?php if (isset($error)): ?>
            <div class="alert alert-error mb-4"><?php echo htmlspecialchars($error); ?></div>
        <?php endif; ?>
        <?php if (isset($success)): ?>
            <div class="alert alert-success mb-4"><?php echo htmlspecialchars($success); ?></div>
        <?php endif; ?>
        
        <?php if (!isset($error)): ?>
        
        <!-- Delegate Statistics -->
        <div class="stats-grid">
            <div class="stat-card">
                <h3>Total Delegates</h3>
                <p class="stat-value"><?php echo number_format($stats['total_delegates']); ?></p>
                <p class="stat-change">All registered delegates</p>
            </div>
            
            <div class="stat-card">
                <h3>Confirmed</h3>
                <p class="stat-value"><?php echo number_format($stats['paid_delegates']); ?></p>
                <p class="stat-change"><?php echo $stats['total_delegates'] > 0 ? round(($stats['paid_delegates'] / $stats['total_delegates']) * 100, 1) : 0; ?>% of total</p>
            </div>
            
            <div class="stat-card">
                <h3>Pending Payment</h3>
                <p class="stat-value"><?php echo number_format($stats['pending_delegates']); ?></p>
                <p class="stat-change"><?php echo $stats['total_delegates'] > 0 ? round(($stats['pending_delegates'] / $stats['total_delegates']) * 100, 1) : 0; ?>% of total</p>
            </div>
            
            <div class="stat-card">
                <h3>Dietary Requirements</h3>
                <p class="stat-value"><?php echo number_format($stats['delegates_with_dietary']); ?></p>
                <p class="stat-change"><?php echo $stats['total_delegates'] > 0 ? round(($stats['delegates_with_dietary'] / $stats['total_delegates']) * 100, 1) : 0; ?>% have dietary needs</p>
            </div>
            
            <div class="stat-card">
                <h3>Special Assistance</h3>
                <p class="stat-value"><?php echo number_format($stats['delegates_with_assistance']); ?></p>
                <p class="stat-change"><?php echo $stats['total_delegates'] > 0 ? round(($stats['delegates_with_assistance'] / $stats['total_delegates']) * 100, 1) : 0; ?>% need assistance</p>
            </div>
        </div>
        
        <!-- Filters -->
        <div class="filters">
            <form method="GET" class="filter-form">
                <div class="filter-row">
                    <div class="filter-field">
                        <label for="search" class="filter-label">Search</label>
                        <input type="text" id="search" name="search" class="filter-input" 
                               placeholder="Name, designation, registration #..." 
                               value="<?php echo htmlspecialchars($search); ?>">
                    </div>
                    
                    <div class="filter-field">
                        <label for="dietary" class="filter-label">Dietary Requirements</label>
                        <select id="dietary" name="dietary" class="filter-input">
                            <option value="">All</option>
                            <?php foreach ($dietary_options as $option): ?>
                                <option value="<?php echo htmlspecialchars($option); ?>" <?php echo $dietary_filter === $option ? 'selected' : ''; ?>>
                                    <?php echo htmlspecialchars($option); ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    
                    <div class="filter-field">
                        <label for="assistance" class="filter-label">Special Assistance</label>
                        <select id="assistance" name="assistance" class="filter-input">
                            <option value="">All</option>
                            <option value="yes" <?php echo $assistance_filter === 'yes' ? 'selected' : ''; ?>>Needs Assistance</option>
                            <option value="no" <?php echo $assistance_filter === 'no' ? 'selected' : ''; ?>>No Assistance</option>
                        </select>
                    </div>
                    
                    <div class="filter-field">
                        <label for="status" class="filter-label">Status</label>
                        <select id="status" name="status" class="filter-input">
                            <option value="">All</option>
                            <option value="paid" <?php echo $status_filter === 'paid' ? 'selected' : ''; ?>>Paid</option>
                            <option value="pending" <?php echo $status_filter === 'pending' ? 'selected' : ''; ?>>Pending</option>
                            <option value="failed" <?php echo $status_filter === 'failed' ? 'selected' : ''; ?>>Failed</option>
                        </select>
                    </div>
                    
                    <div class="filter-field">
                        <label for="product_code" class="filter-label">Product Code</label>
                        <select id="product_code" name="product_code" class="filter-input">
                            <option value="">All</option>
                            <?php foreach ($product_codes as $pc): ?>
                                <option value="<?php echo htmlspecialchars($pc['product_code']); ?>" 
                                        <?php echo $product_code_filter === $pc['product_code'] ? 'selected' : ''; ?>>
                                    <?php echo htmlspecialchars($pc['product_code'] . ' - ' . $pc['name']); ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    
                    <div class="filter-actions">
                        <button type="submit" class="btn btn-primary">
                            <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                                <path d="M22 3H2l8 9.46V19l4 2v-8.54L22 3z"/>
                            </svg>
                            Filter
                        </button>
                        <a href="delegates.php" class="btn btn-secondary">
                            <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                                <path d="M3 6h18l-2 13H5L3 6z"/>
                                <path d="M8 6V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"/>
                            </svg>
                            Reset
                        </a>
                    </div>
                </div>
            </form>
        </div>

        <!-- Delegates Table -->
        <div class="data-table">
            <h2>All Delegates (<?php echo number_format($total_records); ?> total)</h2>
            <div class="table-container">
                <table class="table">
                    <thead>
                        <tr>
                            <th>Registration #</th>
                            <th>Full Name</th>
                            <th>Badge Name</th>
                            <th>Email</th>
                            <th>Designation</th>
                            <th>Department</th>
                            <th>University</th>
                            <th>Dietary</th>
                            <th>Assistance</th>
                            <th>Product Code</th>
                            <th>Status</th>
                            <th>Actions</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php if (empty($delegates)): ?>
                        <tr>
                            <td colspan="11" class="empty-state muted">
                                No delegates found
                            </td>
                        </tr>
                        <?php else: ?>
                        <?php foreach ($delegates as $delegate): ?>
                        <tr>
                            <td>
                                <a href="registration-details.php?id=<?php echo urlencode($delegate['registration_number']); ?>" 
                                   class="link link-strong">
                                    <?php echo htmlspecialchars($delegate['registration_number']); ?>
                                </a>
                            </td>
                            <td><?php echo htmlspecialchars($delegate['full_name']); ?></td>
                            <td><?php echo htmlspecialchars($delegate['badge_name']); ?></td>
                            <td><?php echo htmlspecialchars($delegate['email'] ?: '—'); ?></td>
                            <td><?php echo htmlspecialchars($delegate['designation']); ?></td>
                            <td><?php echo htmlspecialchars($delegate['department'] ?: '—'); ?></td>
                            <td><?php echo htmlspecialchars($delegate['university_name']); ?></td>
                            <td>
                                <?php 
                                $dietary = $delegate['dietary_requirements'];
                                if (!empty($dietary)) {
                                    // Handle JSON array format
                                    if (strpos($dietary, '[') === 0) {
                                        $decoded = json_decode($dietary, true);
                                        if (is_array($decoded) && !empty($decoded)) {
                                            echo htmlspecialchars(implode(', ', $decoded));
                                        } else {
                                            echo '—';
                                        }
                                    } else {
                                        echo htmlspecialchars($dietary);
                                    }
                                } else {
                                    echo '—';
                                }
                                ?>
                            </td>
                            <td><?php echo htmlspecialchars($delegate['special_assistance'] ?: '—'); ?></td>
                            <td>
                                <span class="status-badge badge-type">
                                    <?php 
                                    if (!empty($delegate['product_code'])) {
                                        echo htmlspecialchars($delegate['product_code']);
                                    } else {
                                        // Fallback to legacy delegate type if no product code
                                        echo $delegate['delegate_type'] === 'earlyBird' ? 'DELEGATE_EARLY_BIRD' : 'DELEGATE_STANDARD';
                                    }
                                    ?>
                                </span>
                            </td>
                            <td>
                                <span class="status-badge status-<?php echo $delegate['payment_status']; ?>">
                                    <?php echo ucfirst($delegate['payment_status']); ?>
                                </span>
                            </td>
                            <td>
                                <button type="button" class="btn btn-sm btn-outline-primary" 
                                        onclick="openDelegateEditModal(<?php echo $delegate['id']; ?>, '<?php echo htmlspecialchars($delegate['full_name'], ENT_QUOTES); ?>', '<?php echo htmlspecialchars($delegate['badge_name'], ENT_QUOTES); ?>', '<?php echo htmlspecialchars($delegate['designation'], ENT_QUOTES); ?>', '<?php echo htmlspecialchars($delegate['department'] ?? '', ENT_QUOTES); ?>', '<?php echo htmlspecialchars($delegate['email'] ?? '', ENT_QUOTES); ?>', '<?php echo htmlspecialchars($delegate['dietary_requirements'] ?? '', ENT_QUOTES); ?>', '<?php echo htmlspecialchars($delegate['special_assistance'] ?? '', ENT_QUOTES); ?>')">
                                    ✏️ Edit
                                </button>
                            </td>
                        </tr>
                        <?php endforeach; ?>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>
        </div>

        <!-- Pagination -->
        <?php if ($total_pages > 1): ?>
        <div class="pagination">
            <?php if ($page > 1): ?>
                <a href="?page=<?php echo $page - 1; ?>&search=<?php echo urlencode($search); ?>&dietary=<?php echo urlencode($dietary_filter); ?>&assistance=<?php echo urlencode($assistance_filter); ?>&status=<?php echo urlencode($status_filter); ?>&product_code=<?php echo urlencode($product_code_filter); ?>">
                    Previous
                </a>
            <?php endif; ?>
            
            <?php for ($i = max(1, $page - 2); $i <= min($total_pages, $page + 2); $i++): ?>
                <?php if ($i === $page): ?>
                    <span class="current"><?php echo $i; ?></span>
                <?php else: ?>
                    <a href="?page=<?php echo $i; ?>&search=<?php echo urlencode($search); ?>&dietary=<?php echo urlencode($dietary_filter); ?>&assistance=<?php echo urlencode($assistance_filter); ?>&status=<?php echo urlencode($status_filter); ?>&product_code=<?php echo urlencode($product_code_filter); ?>">
                        <?php echo $i; ?>
                    </a>
                <?php endif; ?>
            <?php endfor; ?>
            
            <?php if ($page < $total_pages): ?>
                <a href="?page=<?php echo $page + 1; ?>&search=<?php echo urlencode($search); ?>&dietary=<?php echo urlencode($dietary_filter); ?>&assistance=<?php echo urlencode($assistance_filter); ?>&status=<?php echo urlencode($status_filter); ?>&product_code=<?php echo urlencode($product_code_filter); ?>">
                    Next
                </a>
            <?php endif; ?>
        </div>
        <?php endif; ?>
        
        <?php endif; ?>
    </div>

<!-- Delegate Edit Modal -->
<div id="delegateEditModal" class="modal" style="display: none;">
    <div class="modal-content">
        <div class="modal-header">
            <h4>Edit Delegate Information</h4>
            <span class="close" onclick="closeDelegateEditModal()">&times;</span>
        </div>
        <form id="delegateEditForm" method="POST">
            <input type="hidden" name="action" value="update_delegate">
            <input type="hidden" name="delegate_id" id="edit_delegate_id">
            
            <div class="form-group">
                <label for="edit_full_name">Full Name *</label>
                <input type="text" id="edit_full_name" name="full_name" required>
            </div>
            
            <div class="form-group">
                <label for="edit_badge_name">Badge Name *</label>
                <input type="text" id="edit_badge_name" name="badge_name" required>
            </div>
            
            <div class="form-group">
                <label for="edit_designation">Designation *</label>
                <input type="text" id="edit_designation" name="designation" required>
            </div>
            
            <div class="form-group">
                <label for="edit_department">Department *</label>
                <input type="text" id="edit_department" name="department" required>
            </div>
            
            <div class="form-group">
                <label for="edit_email">Email Address</label>
                <input type="email" id="edit_email" name="email">
            </div>
            
            <div class="form-group">
                <label for="edit_dietary_requirements">Dietary Requirements</label>
                <select id="edit_dietary_requirements" name="dietary_requirements">
                    <option value="">-- No dietary requirements --</option>
                    <?php foreach ($dietary_options as $option): ?>
                        <option value="<?php echo htmlspecialchars($option); ?>">
                            <?php echo htmlspecialchars($option); ?>
                        </option>
                    <?php endforeach; ?>
                    <option value="__other__">Other (specify below)</option>
                </select>
                <input type="text" id="edit_dietary_other" name="dietary_other" 
                       placeholder="Please specify other dietary requirement" 
                       style="display: none; margin-top: 8px;">
            </div>
            
            <div class="form-group">
                <label for="edit_special_assistance">Special Assistance</label>
                <input type="text" id="edit_special_assistance" name="special_assistance" 
                       placeholder="Describe any special requirements...">
            </div>
            
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" onclick="closeDelegateEditModal()">Cancel</button>
                <button type="submit" class="btn btn-primary">💾 Save Changes</button>
            </div>
        </form>
    </div>
</div>

<style>
/* Modal Styling */
.modal {
    position: fixed;
    z-index: 1000;
    left: 0;
    top: 0;
    width: 100%;
    height: 100%;
    background-color: rgba(0,0,0,0.5);
    overflow: auto;
}

.modal-content {
    background-color: #fefefe;
    margin: 5% auto;
    padding: 0;
    border: none;
    border-radius: 12px;
    width: 90%;
    max-width: 600px;
    box-shadow: 0 10px 30px rgba(0,0,0,0.3);
    animation: modalSlideIn 0.3s ease-out;
}

@keyframes modalSlideIn {
    from {
        opacity: 0;
        transform: translateY(-50px);
    }
    to {
        opacity: 1;
        transform: translateY(0);
    }
}

.modal-header {
    padding: 20px 24px;
    border-bottom: 1px solid #e2e8f0;
    display: flex;
    justify-content: space-between;
    align-items: center;
    background: #f8fafc;
    border-radius: 12px 12px 0 0;
}

.modal-header h4 {
    margin: 0;
    color: #1e293b;
    font-weight: 600;
}

.close {
    color: #64748b;
    font-size: 28px;
    font-weight: bold;
    cursor: pointer;
    line-height: 1;
}

.close:hover,
.close:focus {
    color: #ef4444;
}

.form-group {
    margin-bottom: 20px;
    padding: 0 24px;
}

.form-group:first-of-type {
    margin-top: 24px;
}

.form-group label {
    display: block;
    margin-bottom: 6px;
    font-weight: 600;
    color: #374151;
    font-size: 14px;
}

.form-group input,
.form-group textarea,
.form-group select {
    width: 100%;
    padding: 12px 16px;
    border: 1px solid #d1d5db;
    border-radius: 8px;
    font-size: 14px;
    transition: border-color 0.2s, box-shadow 0.2s;
    box-sizing: border-box;
    background-color: #ffffff;
}

.form-group select {
    cursor: pointer;
    background-image: url("data:image/svg+xml,%3csvg xmlns='http://www.w3.org/2000/svg' fill='none' viewBox='0 0 20 20'%3e%3cpath stroke='%236b7280' stroke-linecap='round' stroke-linejoin='round' stroke-width='1.5' d='m6 8 4 4 4-4'/%3e%3c/svg%3e");
    background-position: right 12px center;
    background-repeat: no-repeat;
    background-size: 16px;
    padding-right: 40px;
    -webkit-appearance: none;
    -moz-appearance: none;
    appearance: none;
}

.form-group input:focus,
.form-group textarea:focus,
.form-group select:focus {
    outline: none;
    border-color: #3b82f6;
    box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.1);
}

.form-group textarea {
    resize: vertical;
    min-height: 80px;
}

.modal-footer {
    padding: 20px 24px;
    border-top: 1px solid #e2e8f0;
    display: flex;
    justify-content: flex-end;
    gap: 12px;
    background: #f8fafc;
    border-radius: 0 0 12px 12px;
}

.btn-sm {
    padding: 6px 12px;
    font-size: 13px;
}

.btn-outline-primary {
    background: transparent;
    border: 1px solid #3b82f6;
    color: #3b82f6;
}

.btn-outline-primary:hover {
    background: #3b82f6;
    color: white;
}

</style>

<script>
function openDelegateEditModal(id, fullName, badgeName, designation, department, email, dietary, assistance) {
    document.getElementById('edit_delegate_id').value = id;
    document.getElementById('edit_full_name').value = fullName;
    document.getElementById('edit_badge_name').value = badgeName;
    document.getElementById('edit_designation').value = designation;
    document.getElementById('edit_department').value = department || '';
    document.getElementById('edit_email').value = email || '';
    
    // Handle dietary requirements dropdown
    const dietarySelect = document.getElementById('edit_dietary_requirements');
    const dietaryOther = document.getElementById('edit_dietary_other');
    
    // Parse JSON array if dietary is in JSON format
    let dietaryValue = '';
    if (dietary && dietary.trim() !== '') {
        try {
            const parsed = JSON.parse(dietary);
            if (Array.isArray(parsed) && parsed.length > 0) {
                dietaryValue = parsed[0]; // Take first value from array
            }
        } catch (e) {
            dietaryValue = dietary; // Fallback to original value if not JSON
        }
    }
    
    // Check if current dietary requirement exists in dropdown options
    let foundOption = false;
    for (let option of dietarySelect.options) {
        if (option.value === dietaryValue) {
            option.selected = true;
            foundOption = true;
            break;
        }
    }
    
    // If not found in dropdown and has value, select "Other" and show text input
    if (!foundOption && dietaryValue && dietaryValue.trim() !== '') {
        dietarySelect.value = '__other__';
        dietaryOther.value = dietaryValue;
        dietaryOther.style.display = 'block';
    } else if (!dietaryValue || dietaryValue.trim() === '') {
        dietarySelect.value = '';
        dietaryOther.style.display = 'none';
    } else {
        dietaryOther.style.display = 'none';
    }
    
    document.getElementById('edit_special_assistance').value = assistance;
    
    document.getElementById('delegateEditModal').style.display = 'block';
    document.body.style.overflow = 'hidden';
}

function closeDelegateEditModal() {
    document.getElementById('delegateEditModal').style.display = 'none';
    document.body.style.overflow = 'auto';
    
    // Reset form and hide other input
    document.getElementById('edit_dietary_other').style.display = 'none';
    document.getElementById('edit_dietary_other').value = '';
}

// Handle dietary requirements dropdown change
document.addEventListener('DOMContentLoaded', function() {
    const dietarySelect = document.getElementById('edit_dietary_requirements');
    const dietaryOther = document.getElementById('edit_dietary_other');
    
    dietarySelect.addEventListener('change', function() {
        if (this.value === '__other__') {
            dietaryOther.style.display = 'block';
            dietaryOther.focus();
        } else {
            dietaryOther.style.display = 'none';
            dietaryOther.value = '';
        }
    });
});
</script>

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