<?php
// pages/roster.php
requireRole('any');

// Helpers
$service_id = isset($_GET['service_id']) ? (int)$_GET['service_id'] : null;
$view = isset($_GET['view']) ? $_GET['view'] : 'edit'; // 'edit' or 'print'

require_once 'includes/role_config.php';
// Use the flat list from config
$roles = $all_roles_flat;

// Fetch all upcoming services for selection
$all_services_stmt = $pdo->query("SELECT * FROM services WHERE service_date >= CURDATE() ORDER BY service_date ASC LIMIT 20");
$all_services = $all_services_stmt->fetchAll();

// If no service selected, default to the first upcoming service
if (!$service_id && !empty($all_services)) {
    $service_id = $all_services[0]['id'];
}

// Fetch the selected service
$service = null;
if ($service_id) {
    $stmt = $pdo->prepare("SELECT * FROM services WHERE id = ?");
    $stmt->execute([$service_id]);
    $service = $stmt->fetch();
}

// 2. Ensure Roster Exists & Fetch Assignments
$roster_id = null;
$matrix = []; // [role] => [member_names_array]

if ($service) {
    // Find or Create Roster for this service
    $r_stmt = $pdo->prepare("SELECT * FROM rosters WHERE service_id = ?");
    $r_stmt->execute([$service_id]);
    $roster_data = $r_stmt->fetch();
    $roster_id = $roster_data['id'] ?? null;
    $roster_status = $roster_data['status'] ?? 'Draft';
    
    if (!$roster_id) {
        // Auto Create
        $pdo->prepare("INSERT INTO rosters (service_id, status) VALUES (?, 'Draft')")
            ->execute([$service_id]);
        $roster_id = $pdo->lastInsertId();
        $roster_status = 'Draft';
    }
    
    // Fetch All Assignments for this roster
    $as_stmt = $pdo->prepare("SELECT * FROM roster_assignments WHERE roster_id = ?");
    $as_stmt->execute([$roster_id]);
    while ($row = $as_stmt->fetch()) {
        if (!isset($matrix[$row['role_name']])) {
            $matrix[$row['role_name']] = [];
            $matrix_full[$row['role_name']] = []; // keys are role names
        }
        $matrix[$row['role_name']][] = $row['person_name'];
        $matrix_full[$row['role_name']][] = ['id' => $row['member_id'], 'name' => $row['person_name']];
    }

    // AUTO-LOAD: If current matrix is empty, try to fetch from the most recent PREVIOUS roster (ANY TYPE)
    if (empty($matrix)) {
        $prev_stmt = $pdo->prepare("
            SELECT r.id 
            FROM rosters r
            JOIN services s ON r.service_id = s.id 
            WHERE s.service_date < ? 
            ORDER BY s.service_date DESC LIMIT 1
        ");
        $prev_stmt->execute([$service['service_date']]);
        $prev_roster_id = $prev_stmt->fetchColumn();

        if ($prev_roster_id) {
            $pas_stmt = $pdo->prepare("SELECT * FROM roster_assignments WHERE roster_id = ?");
            $pas_stmt->execute([$prev_roster_id]);
            while ($row = $pas_stmt->fetch()) {
                if (!isset($matrix[$row['role_name']])) {
                    $matrix[$row['role_name']] = [];
                }
                $matrix[$row['role_name']][] = $row['person_name'];
            }
        }
    }
}

// 3. Handle Save


// Fetch Members - ONLY Available members, EXCLUDING Visitors. Fetch ID for tagging.
$users_full = $pdo->query("SELECT id, full_name as name FROM members WHERE unit != 'Visitor' ORDER BY full_name")->fetchAll(PDO::FETCH_ASSOC);
// Keep simple list for legacy if needed, or just use users_full
$users = array_column($users_full, 'name');

// 2b. Prepare Matrix Full for Edit View (with IDs)
// Already populated in logic above (lines 50-84)
// $matrix_full = []; // REMOVED CAUSE OF BUG

// Ensure matrix_full is populated even if empty
if (!isset($matrix_full)) {
    $matrix_full = [];
}

// PRINT VIEW
if ($view === 'print' && $service) {
    // Minimal Layout with high fidelity to requested design
    ?>
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Roster - <?php echo date("M d, Y", strtotime($service['service_date'])); ?></title>
        <style>
            body { font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; color: #000; background-color: #fff !important; margin: 40px; }
            .header { text-align: center; margin-bottom: 30px; }
            .header h1 { margin: 0; font-size: 22px; text-transform: uppercase; color: #000 !important; }
            .header h2 { margin: 5px 0 0 0; font-size: 18px; font-weight: bold; color: #000 !important; }
            .status-badge { 
                display: inline-block; 
                padding: 3px 10px; 
                border: 2px solid #000; 
                font-weight: bold; 
                text-transform: uppercase; 
                margin-top: 10px;
                font-size: 14px;
            }
            .status-draft { color: #888; border-color: #888; }
            .status-approved { color: #000; border-color: #000; }
            .date-info { margin-bottom: 30px; border-top: 1px solid #000; padding-top: 20px; font-weight: bold; color: #000 !important; }
            
            .section-header { 
                background-color: #f0f0f0 !important; 
                border: 1px solid #000; 
                padding: 10px; 
                font-weight: bold; 
                margin-top: 25px;
                margin-bottom: 10px;
                font-size: 16px;
                display: flex;
                align-items: center;
                color: #000 !important;
                -webkit-print-color-adjust: exact;
            }
            .sub-section-title { font-weight: bold; text-decoration: underline; margin: 15px 0 10px 0; display: block; color: #000 !important; }
            
            table { width: 100%; border-collapse: collapse; margin-bottom: 10px; background-color: #fff !important; }
            th, td { border: 1px solid #000; padding: 8px; font-size: 14px; text-align: left; color: #000 !important; }
            th { background-color: #f8f8f8 !important; font-weight: bold; -webkit-print-color-adjust: exact; }
            .label-col { width: 40%; background-color: #fff !important; }
            .value-col { width: 60%; background-color: #fff !important; }

            @media print {
                body { margin: 20px; }
                button { display: none; }
                * { -webkit-print-color-adjust: exact; print-color-adjust: exact; }
            }
        </style>
    </head>
    <body onload="window.print()">
        <div class="header">
            <h1>APOSTOLIC FAITH CHURCH, WECA HQ., ANTHONY</h1>
            <h2>WCS Assignment Schedule (Draft 01)</h2>
            <div class="status-badge <?php echo $roster_status === 'Approved' ? 'status-approved' : 'status-draft'; ?>">
                Status: <?php echo $roster_status; ?>
            </div>
        </div>

        <div class="date-info">
            Date: <?php echo date("F j, Y", strtotime($service['service_date'])); ?>
        </div>

        <?php 
        $section_count = 1;
        // Group Audio & Video under Section 1
        ?>
        <div class="section-header">
            1. Tabernacle Operations: Audio & Video
        </div>

        <div class="sub-section-title">Tabernacle Audio Operations</div>
        <table>
            <thead>
                <tr>
                    <th class="label-col">Assignment</th>
                    <th class="value-col">Assigned Personnel</th>
                </tr>
            </thead>
            <tbody>
                <?php foreach ($role_categories['Tabernacle Audio Operations'] as $role): ?>
                <tr>
                    <td><?php echo $role; ?></td>
                    <td><?php 
                        $vals = $matrix[$role] ?? [];
                        echo is_array($vals) ? implode(', ', $vals) : $vals;
                    ?></td>
                </tr>
                <?php endforeach; ?>
            </tbody>
        </table>

        <div class="sub-section-title">Tabernacle Video Operations</div>
        <table>
            <thead>
                <tr>
                    <th class="label-col">Assignment</th>
                    <th class="value-col">Assigned Personnel</th>
                </tr>
            </thead>
            <tbody>
                <?php foreach ($role_categories['Tabernacle Video Operations'] as $role): ?>
                <tr>
                    <td><?php echo $role; ?></td>
                    <td><?php 
                        $vals = $matrix[$role] ?? [];
                        echo is_array($vals) ? implode(', ', $vals) : $vals;
                    ?></td>
                </tr>
                <?php endforeach; ?>
            </tbody>
        </table>

        <div class="section-header">
            2. Additional Operations & Technical Support
        </div>
        <table>
            <thead>
                <tr>
                    <th class="label-col">Assignment</th>
                    <th class="value-col">Assigned Personnel</th>
                </tr>
            </thead>
            <tbody>
                <?php foreach ($role_categories['Additional Operations & Technical Support'] as $role): ?>
                <tr>
                    <td><?php echo $role; ?></td>
                    <td><?php 
                        $vals = $matrix[$role] ?? [];
                        echo is_array($vals) ? implode(', ', $vals) : $vals;
                    ?></td>
                </tr>
                <?php endforeach; ?>
            </tbody>
        </table>

        <div class="section-header">
            3. Basement and Other Centres
        </div>
        <table>
            <thead>
                <tr>
                    <th class="label-col">Assignments & Centres</th>
                    <th class="value-col">Assigned Personnel</th>
                </tr>
            </thead>
            <tbody>
                <?php foreach ($role_categories['Basement and Other Centres'] as $role): ?>
                <tr>
                    <td><?php echo $role; ?></td>
                    <td><?php 
                        $vals = $matrix[$role] ?? [];
                        echo is_array($vals) ? implode(', ', $vals) : $vals;
                    ?></td>
                </tr>
                <?php endforeach; ?>
            </tbody>
        </table>

    </body>
    </html>
    <?php
    exit;
}
?>

<div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 20px;">
    <div>
        <h1>Roster Management</h1>
        <form method="GET" style="display: inline-block; margin-top: 10px;">
            <input type="hidden" name="page" value="roster">
            <label style="margin-right: 10px; color: #888;">Select Service:</label>
            <select name="service_id" onchange="this.form.submit()" style="padding: 8px; border-radius: 4px; border: 1px solid #444; background: #222; color: #fff; min-width: 300px;">
                <?php if (empty($all_services)): ?>
                    <option value="">No upcoming services</option>
                <?php else: ?>
                    <?php foreach ($all_services as $svc): ?>
                    <option value="<?php echo $svc['id']; ?>" <?php if($service_id == $svc['id']) echo 'selected'; ?>>
                        <?php echo date("D, M j, Y", strtotime($svc['service_date'])) . " - " . $svc['type']; ?>
                    </option>
                    <?php endforeach; ?>
                <?php endif; ?>
            </select>
        </form>
    </div>
    


    <?php if ($service): ?>
    <div style="display: flex; gap: 10px;">
        <?php if ($roster_status === 'Draft' && hasRole('coordinator')): ?>
            <form method="POST" style="display: inline;" action="api/roster_action.php">
                <input type="hidden" name="service_id" value="<?php echo $service_id; ?>">
                <input type="hidden" name="roster_id" value="<?php echo $roster_id; ?>">
                <button name="approve_roster" type="submit" class="btn" style="background-color: var(--accent-color);"><i class="fas fa-check-circle"></i> Approve</button>
            </form>
        <?php endif; ?>
        
        <?php if ($roster_status !== 'Closed'): ?>
            <?php if (hasRole('admin')): ?>
            <form method="POST" style="display: inline;" action="api/roster_action.php" onsubmit="return confirm('Close this roster? It will become read-only.')">
                <input type="hidden" name="service_id" value="<?php echo $service_id; ?>">
                <input type="hidden" name="roster_id" value="<?php echo $roster_id; ?>">
                <button name="close_roster" type="submit" class="btn" style="background-color: #666; color: #fff;"><i class="fas fa-lock"></i> Close Roster</button>
            </form>
            <?php endif; ?>
        <?php endif; ?>

        <a href="index.php?page=roster&service_id=<?php echo $service_id; ?>&view=print" target="_blank" class="btn" style="background-color: #fff; color: #000;"><i class="fas fa-print"></i> PDF</a>
        
        <?php if ($roster_status !== 'Closed'): ?>
        <button form="rosterForm" name="save_roster" type="submit" class="btn"><i class="fas fa-save"></i> Save</button>
        <?php endif; ?>
    </div>
    <?php endif; ?>
</div>

<script src="https://html2canvas.hertzen.com/dist/html2canvas.min.js"></script>
<script>
// Docx Export Logic
function exportDocx() {
    var preHtml = "<html xmlns:o='urn:schemas-microsoft-com:office:office' xmlns:w='urn:schemas-microsoft-com:office:word' xmlns='http://www.w3.org/TR/REC-html40'><head><meta charset='utf-8'><title>Export HTML to Word Document with JavaScript</title></head><body>";
    var postHtml = "</body></html>";
    
    // Construct HTML content for the Word doc
    var content = "<h1 style='text-align:center'>APOSTOLIC FAITH CHURCH, WECA HQ., ANTHONY</h1>";
    content += "<h2 style='text-align:center'>WCS Assignment Schedule (Draft 01) | <?php echo $service['type'] . ' (' . date('M j, Y', strtotime($service['service_date'])) . ')'; ?></h2>";
    content += "<hr>";

    // We can pull the tables visible in the loop below or reconstruct them. Reconstructing is safer visually.
    <?php 
        // We'll PHP generate the content string efficiently
        $js_content = "";
        
        // Helper to add table
        function jsTable($title, $roles, $matrix) {
            $h = "<h3>$title</h3>";
            $h .= "<table border='1' style='width:100%; border-collapse:collapse;'><thead><tr style='background:#f0f0f0'><th>Assignment</th><th>Assigned Personnel</th></tr></thead><tbody>";
            foreach($roles as $r) {
                $vals = isset($matrix[$r]) ? (is_array($matrix[$r]) ? implode(', ', $matrix[$r]) : $matrix[$r]) : '';
                $h .= "<tr><td>$r</td><td>$vals</td></tr>";
            }
            $h .= "</tbody></table><br>";
            return $h;
        }

        $js_content .= jsTable('Tabernacle Audio Operations', $role_categories['Tabernacle Audio Operations'], $matrix);
        $js_content .= jsTable('Tabernacle Video Operations', $role_categories['Tabernacle Video Operations'], $matrix);
        $js_content .= jsTable('Additional Operations & Technical Support', $role_categories['Additional Operations & Technical Support'], $matrix);
        $js_content .= jsTable('Basement and Other Centres', $role_categories['Basement and Other Centres'], $matrix);
        
    ?>
    content += `<?php echo $js_content; ?>`;
    
    var html = preHtml + content + postHtml;

    var blob = new Blob(['\ufeff', html], {
        type: 'application/msword'
    });
    
    // Specify link url
    var url = 'data:application/vnd.ms-word;charset=utf-8,' + encodeURIComponent(html);
    
    // Create download link element
    var downloadLink = document.createElement("a");

    document.body.appendChild(downloadLink);
    
    if(navigator.msSaveOrOpenBlob ){
        navigator.msSaveOrOpenBlob(blob, 'roster.doc');
    }else{
        // Create a link to the file
        downloadLink.href = url;
        
        // Setting the file name
        downloadLink.download = 'roster.doc';
        
        //triggering the function
        downloadLink.click();
    }
    
    document.body.removeChild(downloadLink);
}

// Member Autocomplete Logic
const membersList = <?php echo json_encode($users); ?>;

document.addEventListener('DOMContentLoaded', function() {
    const textareas = document.querySelectorAll('#rosterForm textarea');
    
    // Create suggestion box
    const suggestionBox = document.createElement('div');
    suggestionBox.id = 'member-suggestions';
    suggestionBox.style.cssText = 'position:absolute; background:#333; border:1px solid #444; color:#fff; display:none; z-index:1000; box-shadow: 0 4px 8px rgba(0,0,0,0.5); border-radius:4px; max-height:200px; overflow-y:auto; min-width:200px;';
    document.body.appendChild(suggestionBox);

    let activeTextarea = null;

    textareas.forEach(ta => {
        ta.addEventListener('input', function(e) {
            const value = this.value;
            const cursorPos = this.selectionStart;
            const textBeforeCursor = value.substring(0, cursorPos);
            const segments = textBeforeCursor.split(',');
            const currentQuery = segments[segments.length - 1].trim().toLowerCase();

            if (currentQuery.length < 3) {
                suggestionBox.style.display = 'none';
                return;
            }

            const matches = membersList.filter(m => m.toLowerCase().includes(currentQuery));
            
            if (matches.length > 0) {
                activeTextarea = this;
                renderSuggestions(matches, currentQuery);
                positionSuggestionBox(this);
            } else {
                suggestionBox.style.display = 'none';
            }
        });

        // Hide on blur (with delay to allow click)
        ta.addEventListener('blur', () => {
            setTimeout(() => { suggestionBox.style.display = 'none'; }, 200);
        });
    });

    function renderSuggestions(matches, query) {
        suggestionBox.innerHTML = '';
        matches.slice(0, 10).forEach(match => {
            const div = document.createElement('div');
            div.style.cssText = 'padding:8px 12px; cursor:pointer; border-bottom:1px solid #444;';
            div.innerHTML = match.replace(new RegExp(query, 'gi'), '<strong>$&</strong>');
            
            div.addEventListener('click', () => {
                selectMember(match);
            });
            
            div.addEventListener('mouseover', () => { div.style.background = '#444'; });
            div.addEventListener('mouseout', () => { div.style.background = 'transparent'; });
            
            suggestionBox.appendChild(div);
        });
        suggestionBox.style.display = 'block';
    }

    function positionSuggestionBox(el) {
        const rect = el.getBoundingClientRect();
        suggestionBox.style.left = window.pageXOffset + rect.left + 'px';
        suggestionBox.style.top = window.pageYOffset + rect.bottom + 'px';
    }

    function selectMember(name) {
        if (!activeTextarea) return;
        
        const value = activeTextarea.value;
        const cursorPos = activeTextarea.selectionStart;
        
        const textBeforeCursor = value.substring(0, cursorPos);
        const textAfterCursor = value.substring(cursorPos);
        
        const segments = textBeforeCursor.split(',');
        segments[segments.length - 1] = ' ' + name;
        
        const newValueBefore = segments.join(',').trim();
        activeTextarea.value = newValueBefore + ', ';
        
        activeTextarea.focus();
        suggestionBox.style.display = 'none';
    }
});
</script>

<?php if (isset($_GET['msg'])): ?>
<div class="alert alert-<?php echo $_GET['msg'] === 'Approved' ? 'success' : 'info'; ?>">
    <?php 
    if ($_GET['msg'] === 'Saved') echo "Changes saved!";
    elseif ($_GET['msg'] === 'Approved') echo "Roster approved successfully!";
    else echo htmlspecialchars($_GET['msg']);
    ?>
</div>
<?php endif; ?>

<?php if (!$service): ?>
<div class="alert alert-info">No service selected. Please select a service from the dropdown above or <a href="index.php?page=services">create services</a> first.</div>
<?php else: ?>

<div class="card" style="margin-bottom: 20px; display: flex; justify-content: space-between; align-items: center;">
    <div>
        <h3 style="margin: 0;"><?php echo $service['type'] . " - " . date("l, F j, Y", strtotime($service['service_date'])); ?></h3>
        <p style="color: #888; margin: 5px 0 0 0;">Assign members to roles for this service. You can enter multiple names separated by commas.</p>
    </div>
    <div style="text-align: right;">
        <span class="badge" style="background: <?php echo $roster_status === 'Approved' ? 'var(--success-color)' : '#666'; ?>; padding: 5px 10px; font-size: 0.9rem;">
            Status: <?php echo strtoupper($roster_status); ?>
        </span>
    </div>
</div>

<form method="POST" id="rosterForm" action="api/roster_action.php">
    <input type="hidden" name="service_id" value="<?php echo $service_id; ?>">
    <input type="hidden" name="roster_id" value="<?php echo $roster_id; ?>">
    
    <?php
    // Roster Checklist Feature
    $checklist_items = $pdo->query("SELECT * FROM settings_options WHERE category='roster_checklist' ORDER BY display_order")->fetchAll();
    $saved_checks = json_decode($roster_data['checklist_json'] ?? '[]', true);
    if (!is_array($saved_checks)) $saved_checks = [];
    ?>
    
    <?php if (!empty($checklist_items)): ?>
    <div class="card roster-checklist-section" style="margin-top: 20px; background: #2c3e50; border: 1px solid #34495e;">
        <h3 style="margin-top: 0; color: #ecf0f1; font-size: 1.1rem; border-bottom: 1px solid #7f8c8d; padding-bottom: 10px; margin-bottom: 15px;">
            <i class="fas fa-tasks"></i> Roster Assignment Checklist
        </h3>
        <div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); gap: 10px;">
            <?php foreach ($checklist_items as $item): ?>
            <label style="display: flex; align-items: center; cursor: pointer; color: #fff; background: rgba(0,0,0,0.2); padding: 8px; border-radius: 4px;">
                <input type="checkbox" name="checklist[]" value="<?php echo htmlspecialchars($item['value']); ?>" 
                    <?php if(in_array($item['value'], $saved_checks)) echo 'checked'; ?>
                    style="margin-right: 10px; transform: scale(1.2);">
                <?php echo htmlspecialchars($item['value']); ?>
            </label>
            <?php endforeach; ?>
        </div>
    </div>
    <style>
        @media print {
            .roster-checklist-section { display: none !important; }
        }
    </style>
    <?php endif; ?>

    <?php 
    // Define all sections
    $all_sections = [
        'Tabernacle Operations' => [
            'Audio' => $role_categories['Tabernacle Audio Operations'] ?? [],
            'Video' => $role_categories['Tabernacle Video Operations'] ?? []
        ],
        'Additional Operations & Technical Support' => [
            'General' => $role_categories['Additional Operations & Technical Support'] ?? []
        ],
        'Basement and Other Centres' => [
            'General' => $role_categories['Basement and Other Centres'] ?? []
        ]
    ];
    
    // Filter based on Service Type
    $sections = $all_sections;
    if (stripos($service['type'], 'Bible Study') !== false) {
        // Hide Tabernacle Ops and Additional Ops
        unset($sections['Tabernacle Operations']);
        unset($sections['Additional Operations & Technical Support']);
    }
    ?>

    <?php foreach ($sections as $section_title => $subgroups): ?>
    <div class="card" style="margin-top: 20px; border-left: 5px solid var(--primary-color);">
        <h3 style="margin-bottom: 0;"><?php echo $section_title; ?></h3>
    </div>

    <?php foreach ($subgroups as $sub_title => $s_roles): ?>
    <?php if ($sub_title !== 'General'): ?>
        <h4 style="margin: 15px 0 10px 0; border-bottom: 1px solid #333; padding-bottom: 5px; color: var(--accent-color);"><?php echo $sub_title; ?></h4>
    <?php endif; ?>

    <div class="table-responsive" style="margin-bottom: 20px;">
        <table>
            <thead>
                <tr>
                    <th style="width: 250px;">Assignment</th>
                    <th>Assigned Members</th>
                </tr>
            </thead>
            <tbody>
                <?php foreach ($s_roles as $idx => $role): ?>
                <tr>
                    <td><?php echo htmlspecialchars($role); ?></td>
                    <td>
                        <div class="tag-input-container <?php echo ($roster_status === 'Closed') ? 'disabled' : ''; ?>" data-role-index="<?php echo $idx; ?>">
                            <?php 
                            // Fetch assignments for this role
                            $current_assignments = $matrix_full[$role] ?? [];
                            // Prepare JSON for hidden input
                            $json_val = [];
                            foreach ($current_assignments as $ca) {
                                $json_val[] = ['id' => $ca['id'], 'name' => $ca['name']];
                            }
                            ?> 
                            <div class="tags-list">
                                <?php foreach ($current_assignments as $assign): ?>
                                    <span class="tag" data-id="<?php echo $assign['id'] ? $assign['id'] : ''; ?>" data-name="<?php echo htmlspecialchars($assign['name']); ?>">
                                        <?php echo htmlspecialchars($assign['name']); ?> 
                                        <?php if ($roster_status !== 'Closed'): ?>
                                        <span class="remove">&times;</span>
                                        <?php endif; ?>
                                    </span>
                                <?php endforeach; ?>
                            </div>
                            <?php if ($roster_status !== 'Closed'): ?>
                            <input type="text" class="tag-input" placeholder="Type to search..." autocomplete="off">
                            <?php endif; ?>
                            <input type="hidden" name="assignments_json[<?php echo base64_encode($role); ?>]" class="assignments-json" value="<?php echo htmlspecialchars(json_encode($json_val)); ?>">
                        </div>
                    </td>
                </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
    </div>
    <?php endforeach; ?>
    <?php endforeach; ?>
    <input type="submit" style="display:none;"> <!-- Prevent implicit submit on enter -->
</form>
<?php endif; ?>

<style>
    .tag-input-container {
        border: 1px solid #444;
        background: #222;
        padding: 5px;
        border-radius: 4px;
        min-height: 40px;
        display: flex;
        flex-wrap: wrap;
        gap: 5px;
        align-items: center;
        position: relative;
    }
    .tag-input-container.disabled {
        background: #333;
        opacity: 0.7;
        pointer-events: none;
    }
    .tag {
        background: var(--primary-color);
        color: #fff;
        padding: 2px 8px;
        border-radius: 12px;
        font-size: 0.85rem;
        display: inline-flex;
        align-items: center;
        gap: 5px;
        margin-right: 3px;
        margin-bottom: 3px;
    }
    .tag .remove {
        cursor: pointer;
        font-weight: bold;
        line-height: 1;
        margin-left: 5px;
        opacity: 0.8;
    }
    .tag .remove:hover {
        opacity: 1;
    }
    .tag-input {
        background: transparent;
        border: none;
        color: #fff;
        font-size: 0.9rem;
        flex: 1;
        min-width: 100px;
        outline: none;
        padding: 5px;
    }
    
    /* Suggester */
    #member-suggestions {
        position: absolute;
        background: #333;
        border: 1px solid #555;
        max-height: 200px;
        overflow-y: auto;
        z-index: 1000;
        width: 250px;
        display: none;
        box-shadow: 0 4px 10px rgba(0,0,0,0.5);
    }
    .suggestion-item {
        padding: 8px 10px;
        cursor: pointer;
        border-bottom: 1px solid #444;
        color: #fff;
    }
    .suggestion-item:hover {
        background: var(--primary-color);
    }
</style>

<script type="application/json" id="roster-data">
<?php 
    $json = json_encode($users_full);
    echo ($json === false) ? '[]' : $json; 
?>
</script>
<script src="assets/js/roster.js"></script>
