<?php
require_once 'includes/db.php';
requireRole(['owner', 'manager']);

$company_id = $_SESSION['company_id'];
$shifts = fetchAll("
    SELECT s.*, COUNT(e.id) as employee_count 
    FROM shifts s 
    LEFT JOIN employees e ON s.id = e.shift_id 
    WHERE s.company_id = ? 
    GROUP BY s.id 
    ORDER BY s.created_at DESC
", [$company_id]);
?>

<style>
    .shifts-toolbar {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 2rem;
        gap: 1rem;
        flex-wrap: wrap;
    }
    .search-wrapper {
        position: relative;
        flex: 1;
        max-width: 400px;
    }
    .search-wrapper i {
        position: absolute;
        left: 1rem;
        top: 50%;
        transform: translateY(-50%);
        color: var(--text-muted);
        opacity: 0.6;
    }
    .search-wrapper input {
        padding-left: 2.75rem;
        border-radius: 50px;
        background: var(--bg-card);
        border: 1px solid var(--border);
        box-shadow: var(--shadow-sm);
        transition: all 0.2s ease;
    }
    .search-wrapper input:focus {
        border-color: var(--primary);
        box-shadow: 0 0 0 3px rgba(124, 58, 237, 0.15);
    }
    .shift-card {
        transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
        border: 1px solid var(--border);
    }
    .shift-card:hover {
        transform: translateY(-4px);
        box-shadow: var(--shadow-xl);
        border-color: var(--primary)33;
    }
    .shift-icon-box {
        width: 48px;
        height: 48px;
        border-radius: 12px;
        background: rgba(124, 58, 237, 0.08);
        color: var(--primary);
        display: flex;
        align-items: center;
        justify-content: center;
        font-size: 1.25rem;
    }
    .shift-time-badge {
        font-size: 0.75rem;
        font-weight: 700;
        padding: 0.35rem 0.75rem;
        border-radius: 50px;
        background: rgba(16, 185, 129, 0.08);
        color: var(--success);
        display: inline-flex;
        align-items: center;
        gap: 0.35rem;
    }
    .shift-actions {
        display: flex;
        gap: 0.5rem;
        margin-top: 1.25rem;
        padding-top: 1rem;
        border-top: 1px solid var(--border);
    }
    /* Split assignment modal styles */
    .assignment-container {
        display: grid;
        grid-template-columns: 1.1fr 0.9fr;
        gap: 1.5rem;
        min-height: 450px;
    }
    @media (max-width: 768px) {
        .assignment-container {
            grid-template-columns: 1fr;
        }
    }
    .assignment-panel {
        background: var(--bg-dark);
        border: 1px solid var(--border);
        border-radius: 14px;
        padding: 1.25rem;
        display: flex;
        flex-direction: column;
    }
    .assignment-panel-title {
        font-size: 0.9rem;
        font-weight: 800;
        text-transform: uppercase;
        letter-spacing: 0.5px;
        color: var(--text-muted);
        margin-bottom: 1rem;
        display: flex;
        justify-content: space-between;
        align-items: center;
    }
    .employee-scroll-list {
        flex: 1;
        overflow-y: auto;
        max-height: 320px;
        padding-right: 0.25rem;
        display: flex;
        flex-direction: column;
        gap: 0.5rem;
    }
    .employee-row-item {
        display: flex;
        align-items: center;
        justify-content: space-between;
        padding: 0.75rem;
        background: var(--bg-card);
        border: 1px solid var(--border);
        border-radius: 10px;
        transition: border-color 0.2s;
    }
    .employee-row-item:hover {
        border-color: var(--primary)44;
    }
    .employee-row-left {
        display: flex;
        align-items: center;
        gap: 0.75rem;
    }
    .employee-row-avatar {
        width: 32px;
        height: 32px;
        border-radius: 50%;
        background: var(--bg-dark);
        border: 1px solid var(--border);
        display: flex;
        align-items: center;
        justify-content: center;
        font-size: 0.85rem;
        font-weight: 700;
        overflow: hidden;
    }
    .employee-row-details h4 {
        margin: 0 0 0.15rem 0;
        font-size: 0.875rem;
        font-weight: 700;
        color: var(--text-main);
    }
    .employee-row-details span {
        font-size: 0.75rem;
        color: var(--text-muted);
    }
</style>

<div class="shifts-toolbar">
    <div class="search-wrapper">
        <i class="fas fa-search"></i>
        <input type="text" id="shiftSearch" class="form-control" placeholder="Search shifts by name...">
    </div>
    <button class="btn btn-primary" onclick="openCreateShiftModal()">
        <i class="fas fa-plus"></i> Add New Shift
    </button>
</div>

<div class="data-grid" id="shiftsGrid">
    <?php if (empty($shifts)): ?>
        <div style="grid-column: 1 / -1; text-align: center; padding: 5rem 2rem; color: var(--text-muted); background: var(--bg-card); border-radius: 20px; border: 1px solid var(--border);">
            <i class="fas fa-calendar-alt fa-3x" style="margin-bottom: 1.25rem; opacity: 0.4; color: var(--primary);"></i>
            <h3>No Shifts Configured</h3>
            <p style="margin-bottom: 1.5rem;">Define your company's working shifts and begin tracking attendance by scheduling slots.</p>
            <button class="btn btn-primary" onclick="openCreateShiftModal()">Create Your First Shift</button>
        </div>
    <?php else: ?>
        <?php foreach ($shifts as $shift): ?>
            <div class="data-card shift-card" data-name="<?php echo htmlspecialchars(strtolower($shift['name'])); ?>">
                <div class="data-card-header">
                    <div style="display: flex; align-items: center; gap: 1rem;">
                        <div class="shift-icon-box">
                            <i class="fas fa-business-time"></i>
                        </div>
                        <div>
                            <h3 style="font-size: 1.125rem; font-weight: 800; margin: 0;"><?php echo htmlspecialchars($shift['name']); ?></h3>
                            <span style="font-size: 0.8rem; color: var(--text-muted);">
                                Created on <?php echo date('M d, Y', strtotime($shift['created_at'])); ?>
                            </span>
                        </div>
                    </div>
                </div>

                <div class="data-card-body" style="padding-top: 0.5rem;">
                    <div style="display: flex; flex-direction: column; gap: 0.75rem;">
                        <div style="display: flex; align-items: center; gap: 0.75rem;">
                            <i class="fas fa-clock" style="color: var(--text-muted); width: 16px;"></i>
                            <span style="font-size: 0.9rem; font-weight: 700; color: var(--text-main);">
                                <?php echo date("g:i A", strtotime($shift['start_time'])); ?> - <?php echo date("g:i A", strtotime($shift['end_time'])); ?>
                            </span>
                        </div>
                        <div style="display: flex; align-items: center; gap: 0.75rem; flex-wrap: wrap;">
                            <i class="fas fa-hourglass-half" style="color: var(--text-muted); width: 16px;"></i>
                            <span class="shift-time-badge">
                                <i class="fas fa-bolt"></i> <?php echo number_format($shift['working_hours'], 2); ?> hrs / day
                            </span>
                            <span class="shift-time-badge" style="background: rgba(245, 158, 11, 0.08); color: #F59E0B;">
                                <i class="fas fa-user-clock"></i> Min: <?php echo number_format($shift['minimum_working_hours'], 2); ?> hrs
                            </span>
                        </div>
                        <div style="display: flex; align-items: center; gap: 0.75rem; margin-top: 0.25rem; padding-top: 0.75rem; border-top: 1px solid var(--border);">
                            <i class="fas fa-users" style="color: var(--text-muted); width: 16px;"></i>
                            <span style="font-size: 0.875rem; font-weight: 600; color: var(--text-main);">
                                <?php echo $shift['employee_count']; ?> Employees Assigned
                            </span>
                        </div>
                    </div>
                </div>

                <div class="data-card-footer shift-actions">
                    <button class="btn btn-outline" style="background: var(--bg-dark); font-size: 0.8rem; padding: 0.5rem 0.75rem; flex: 1.5; display: inline-flex; align-items: center; justify-content: center; gap: 0.4rem; border: 1px solid var(--border);" 
                            onclick="openTagEmployeesModal(<?php echo $shift['id']; ?>, '<?php echo htmlspecialchars($shift['name'], ENT_QUOTES); ?>')">
                        <i class="fas fa-users-cog"></i> Assign Staff
                    </button>
                    <button class="btn btn-icon" style="background: var(--bg-dark); color: var(--primary); padding: 0.5rem; border: 1px solid var(--border);" 
                            onclick='openEditShiftModal(<?php echo json_encode($shift); ?>)' title="Edit Shift">
                        <i class="fas fa-edit"></i>
                    </button>
                    <button class="btn btn-icon" style="background: rgba(239, 68, 68, 0.08); color: var(--danger); padding: 0.5rem; border: 1px solid rgba(239, 68, 68, 0.15);" 
                            onclick="deleteShift(<?php echo $shift['id']; ?>)" title="Delete Shift">
                        <i class="fas fa-trash"></i>
                    </button>
                </div>
            </div>
        <?php endforeach; ?>
    <?php endif; ?>
</div>

<!-- Add / Edit Shift Modal -->
<div id="shiftModal" class="modal-overlay">
    <div class="modal-content" style="max-width: 480px; width: 90vw;">
        <div class="modal-header">
            <h2 id="shiftModalTitle">Create Shift</h2>
            <button class="btn-icon" onclick="closeModal('shiftModal')"><i class="fas fa-times"></i></button>
        </div>
        <form id="shiftForm" onsubmit="saveShift(event)">
            <input type="hidden" name="id" id="shift_id">
            <div class="modal-body" style="display: flex; flex-direction: column; gap: 1.25rem;">
                <div class="form-group">
                    <label class="form-label" style="font-weight: 700;">Shift Name</label>
                    <input type="text" name="name" id="shift_name" class="form-control" placeholder="e.g. Day Shift, Night Shift" required>
                </div>
                <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 1rem;">
                    <div class="form-group">
                        <label class="form-label" style="font-weight: 700;">Start Time</label>
                        <input type="time" name="start_time" id="shift_start_time" class="form-control" required onchange="calculateDuration()">
                    </div>
                    <div class="form-group">
                        <label class="form-label" style="font-weight: 700;">End Time</label>
                        <input type="time" name="end_time" id="shift_end_time" class="form-control" required onchange="calculateDuration()">
                    </div>
                </div>
                <div class="form-group">
                    <label class="form-label" style="font-weight: 700;">Working Hours (Auto Calculated)</label>
                    <input type="text" id="shift_working_hours" class="form-control" style="background: var(--bg-dark); cursor: not-allowed; font-weight: 700; color: var(--primary);" readonly placeholder="0.00">
                </div>
                <div class="form-group">
                    <label class="form-label" style="font-weight: 700;">Minimum Working Hours</label>
                    <input type="number" step="0.1" min="0" max="24" name="minimum_working_hours" id="shift_minimum_working_hours" class="form-control" placeholder="e.g. 8.0" required value="0.0">
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn" onclick="closeModal('shiftModal')">Cancel</button>
                <button type="submit" class="btn btn-primary" id="saveShiftBtn">Save Shift</button>
            </div>
        </form>
    </div>
</div>

<!-- Bulk Tagging Modal -->
<div id="tagEmployeesModal" class="modal-overlay">
    <div class="modal-content" style="max-width: 900px; width: 95vw;">
        <div class="modal-header">
            <div>
                <h2 style="margin: 0 0 0.25rem 0;">Assign Employees to Shift</h2>
                <p id="tagModalSubtitle" style="margin: 0; font-size: 0.875rem; color: var(--text-muted); font-weight: 500;"></p>
            </div>
            <button class="btn-icon" onclick="closeModal('tagEmployeesModal')"><i class="fas fa-times"></i></button>
        </div>
        <div class="modal-body">
            <div class="assignment-container">
                <!-- Left panel: Search and Add -->
                <div class="assignment-panel">
                    <div class="assignment-panel-title">
                        <span>Search & Add Staff</span>
                        <span id="searchResultsCount" style="font-size: 0.75rem; font-weight: 700; color: var(--primary);">0 found</span>
                    </div>
                    
                    <div style="position: relative; margin-bottom: 1rem;">
                        <i class="fas fa-search" style="position: absolute; left: 0.85rem; top: 50%; transform: translateY(-50%); color: var(--text-muted); font-size: 0.85rem;"></i>
                        <input type="text" id="empAssignSearch" class="form-control" placeholder="Search by name or code..." style="padding-left: 2.25rem; font-size: 0.85rem; height: 38px; border-radius: 8px;" oninput="debounceSearch()">
                    </div>

                    <div style="display: flex; justify-content: space-between; align-items: center; padding: 0.5rem 0.75rem; background: var(--bg-card); border: 1px solid var(--border); border-radius: 8px; margin-bottom: 0.75rem; font-size: 0.8rem; font-weight: 700;">
                        <label style="display: flex; align-items: center; gap: 0.5rem; cursor: pointer; margin: 0;">
                            <input type="checkbox" id="checkAllEmployees" onchange="toggleCheckAll(this)" style="cursor: pointer; width: 16px; height: 16px;">
                            <span>Select All Matches</span>
                        </label>
                        <button class="btn btn-sm btn-primary" id="bulkAssignBtn" onclick="assignCheckedEmployees()" disabled style="padding: 0.35rem 0.75rem; font-size: 0.75rem; border-radius: 6px;">
                            Assign Selected
                        </button>
                    </div>

                    <div class="employee-scroll-list" id="searchEmployeesList">
                        <!-- Search results injected here -->
                    </div>
                </div>

                <!-- Right panel: Currently Tagged -->
                <div class="assignment-panel">
                    <div class="assignment-panel-title">
                        <span>Assigned Employees</span>
                        <span id="taggedEmployeesCount" style="font-size: 0.75rem; font-weight: 700; color: var(--success); padding: 0.15rem 0.5rem; background: rgba(16, 185, 129, 0.1); border-radius: 50px;">0 Assigned</span>
                    </div>

                    <div class="employee-scroll-list" id="taggedEmployeesList" style="max-height: 375px;">
                        <!-- Tagged employees injected here -->
                    </div>
                </div>
            </div>
        </div>
        <div class="modal-footer" style="margin-top: 1rem; border-top: 1px solid var(--border); padding-top: 1rem; display: flex; justify-content: flex-end; gap: 1rem;">
            <button type="button" class="btn" onclick="closeModal('tagEmployeesModal')">Cancel</button>
            <button type="button" class="btn btn-primary" id="saveAssignmentsBtn" onclick="saveAssignments()">Save Changes</button>
        </div>
    </div>
</div>

<script>
let currentShiftId = null;
let searchDebounceTimeout = null;

// Search shifts card filtering
document.getElementById('shiftSearch').addEventListener('input', function(e) {
    const term = e.target.value.toLowerCase();
    const cards = document.querySelectorAll('.shift-card');
    
    cards.forEach(card => {
        const name = card.getAttribute('data-name');
        if (name.includes(term)) {
            card.style.display = 'flex';
        } else {
            card.style.display = 'none';
        }
    });
});

function openModal(id) {
    const el = document.getElementById(id);
    if (el) el.classList.add('active');
}

function closeModal(id) {
    const el = document.getElementById(id);
    if (el) el.classList.remove('active');
}

// Working Hours auto-calculator (midnight crossing safe)
function calculateDuration() {
    const startVal = document.getElementById('shift_start_time').value;
    const endVal = document.getElementById('shift_end_time').value;
    if (!startVal || !endVal) return;
    
    const [startH, startM] = startVal.split(':').map(Number);
    const [endH, endM] = endVal.split(':').map(Number);
    
    let diffMinutes = (endH * 60 + endM) - (startH * 60 + startM);
    if (diffMinutes < 0) {
        diffMinutes += 24 * 60; // crosses midnight boundary
    }
    
    const hours = (diffMinutes / 60).toFixed(2);
    document.getElementById('shift_working_hours').value = hours;
}

function openCreateShiftModal() {
    document.getElementById('shiftModalTitle').innerText = 'Create New Shift';
    document.getElementById('shiftForm').reset();
    document.getElementById('shift_id').value = '';
    document.getElementById('shift_working_hours').value = '0.00';
    document.getElementById('shift_minimum_working_hours').value = '0.00';
    openModal('shiftModal');
}

function openEditShiftModal(shift) {
    document.getElementById('shiftModalTitle').innerText = 'Edit Shift';
    document.getElementById('shift_id').value = shift.id;
    document.getElementById('shift_name').value = shift.name;
    document.getElementById('shift_start_time').value = shift.start_time.substring(0, 5);
    document.getElementById('shift_end_time').value = shift.end_time.substring(0, 5);
    document.getElementById('shift_working_hours').value = parseFloat(shift.working_hours).toFixed(2);
    document.getElementById('shift_minimum_working_hours').value = parseFloat(shift.minimum_working_hours || 0).toFixed(2);
    openModal('shiftModal');
}

async function saveShift(e) {
    e.preventDefault();
    const btn = document.getElementById('saveShiftBtn');
    btn.disabled = true;
    
    const shiftData = {
        id: document.getElementById('shift_id').value,
        name: document.getElementById('shift_name').value,
        start_time: document.getElementById('shift_start_time').value,
        end_time: document.getElementById('shift_end_time').value,
        minimum_working_hours: document.getElementById('shift_minimum_working_hours').value
    };
    
    try {
        const basePath = window.APP_CONFIG ? window.APP_CONFIG.BASE_PATH : '/';
        const response = await fetch(`${basePath}api/shifts.php?action=save`, {
            method: 'POST',
            headers: {'Content-Type': 'application/json'},
            body: JSON.stringify({ shift: shiftData })
        });
        const res = await response.json();
        if (res.success) {
            notify(res.message, 'success');
            closeModal('shiftModal');
            setTimeout(() => location.reload(), 1000);
        } else {
            notify(res.message || 'Failed to save shift', 'error');
        }
    } catch(err) {
        notify('Failed to save shift', 'error');
    } finally {
        btn.disabled = false;
    }
}

async function deleteShift(id) {
    const confirmed = await confirmAction({
        title: 'Delete Shift',
        message: 'Are you sure you want to delete this shift? Tagged employees will be unassigned.',
        confirmText: 'Yes, Delete',
        confirmClass: 'var(--danger)'
    });
    
    if (!confirmed) return;
    
    try {
        const basePath = window.APP_CONFIG ? window.APP_CONFIG.BASE_PATH : '/';
        const response = await fetch(`${basePath}api/shifts.php?action=delete`, {
            method: 'POST',
            headers: {'Content-Type': 'application/json'},
            body: JSON.stringify({ id: id })
        });
        const res = await response.json();
        if (res.success) {
            notify(res.message, 'success');
            setTimeout(() => location.reload(), 1000);
        } else {
            notify(res.message || 'Failed to delete shift', 'error');
        }
    } catch(err) {
        notify('Failed to delete shift', 'error');
    }
}

// Bulk assignments functions
let localTaggedEmployees = [];
let availableEmployees = [];

async function openTagEmployeesModal(shiftId, shiftName) {
    currentShiftId = shiftId;
    document.getElementById('tagModalSubtitle').innerText = `Managing assignments for: ${shiftName}`;
    document.getElementById('empAssignSearch').value = '';
    document.getElementById('checkAllEmployees').checked = false;
    
    // Fetch currently assigned employees to initialize the local state
    const basePath = window.APP_CONFIG ? window.APP_CONFIG.BASE_PATH : '/';
    const container = document.getElementById('taggedEmployeesList');
    container.innerHTML = '<div style="text-align: center; padding: 2rem; color: var(--text-muted);"><i class="fas fa-spinner fa-spin fa-2x"></i></div>';
    
    try {
        const response = await fetch(`${basePath}api/shifts.php?action=list_tagged_employees&shift_id=${currentShiftId}`);
        const res = await response.json();
        if (res.success) {
            localTaggedEmployees = res.data;
        } else {
            localTaggedEmployees = [];
            notify(res.message || 'Failed to load assigned employees', 'error');
        }
    } catch(err) {
        localTaggedEmployees = [];
        notify('Failed to load assigned employees', 'error');
    }
    
    renderTaggedEmployees();
    await loadSearchEmployees();
    openModal('tagEmployeesModal');
}

function renderTaggedEmployees() {
    const container = document.getElementById('taggedEmployeesList');
    document.getElementById('taggedEmployeesCount').innerText = `${localTaggedEmployees.length} Assigned`;
    
    if (localTaggedEmployees.length === 0) {
        container.innerHTML = `
            <div style="text-align: center; padding: 3rem 1rem; color: var(--text-muted);">
                <i class="fas fa-user-slash fa-2x" style="margin-bottom: 0.75rem; opacity: 0.5;"></i>
                <p style="margin: 0; font-size: 0.875rem;">No employees assigned to this shift yet.</p>
            </div>
        `;
        return;
    }
    
    const basePath = window.APP_CONFIG ? window.APP_CONFIG.BASE_PATH : '/';
    let html = '';
    localTaggedEmployees.forEach(emp => {
        const avatar = emp.profile_picture 
            ? `<img src="${basePath}${emp.profile_picture}" style="width: 100%; height: 100%; object-fit: cover;">`
            : emp.name.charAt(0).toUpperCase();
            
        html += `
            <div class="employee-row-item">
                <div class="employee-row-left">
                    <div class="employee-row-avatar">${avatar}</div>
                    <div class="employee-row-details">
                        <h4>${escapeHtml(emp.name)}</h4>
                        <span>Code: ${escapeHtml(emp.employee_code || '-')} | ${escapeHtml(emp.role_name || 'Operator')}</span>
                    </div>
                </div>
                <button class="btn btn-icon btn-sm" style="background: rgba(239, 68, 68, 0.08); color: var(--danger); border: none; padding: 0.35rem;" 
                        onclick="removeLocalEmployee(${emp.id})" title="Remove employee from shift">
                    <i class="fas fa-user-minus"></i>
                </button>
            </div>
        `;
    });
    container.innerHTML = html;
}

function debounceSearch() {
    clearTimeout(searchDebounceTimeout);
    searchDebounceTimeout = setTimeout(loadSearchEmployees, 300);
}

async function loadSearchEmployees() {
    const container = document.getElementById('searchEmployeesList');
    const queryStr = document.getElementById('empAssignSearch').value;
    container.innerHTML = '<div style="text-align: center; padding: 2rem; color: var(--text-muted);"><i class="fas fa-spinner fa-spin fa-2x"></i></div>';
    
    document.getElementById('checkAllEmployees').checked = false;
    document.getElementById('bulkAssignBtn').disabled = true;
    document.getElementById('bulkAssignBtn').innerText = 'Assign Selected';
    
    try {
        const basePath = window.APP_CONFIG ? window.APP_CONFIG.BASE_PATH : '/';
        // We pass shift_id as 0 so we query all active employees, and then manually filter out
        // those who are already assigned inside our local memory state!
        const response = await fetch(`${basePath}api/shifts.php?action=search_employees&shift_id=0&query=${encodeURIComponent(queryStr)}`);
        const res = await response.json();
        
        if (res.success) {
            const assignedIds = localTaggedEmployees.map(e => e.id);
            availableEmployees = res.data.filter(emp => !assignedIds.includes(emp.id));
            
            document.getElementById('searchResultsCount').innerText = `${availableEmployees.length} found`;
            if (availableEmployees.length === 0) {
                container.innerHTML = `
                    <div style="text-align: center; padding: 3rem 1rem; color: var(--text-muted);">
                        <i class="fas fa-search-minus fa-2x" style="margin-bottom: 0.75rem; opacity: 0.5;"></i>
                        <p style="margin: 0; font-size: 0.875rem;">No unassigned employees match search.</p>
                    </div>
                `;
                return;
            }
            
            let html = '';
            availableEmployees.forEach(emp => {
                const avatar = emp.profile_picture 
                    ? `<img src="${basePath}${emp.profile_picture}" style="width: 100%; height: 100%; object-fit: cover;">`
                    : emp.name.charAt(0).toUpperCase();
                    
                html += `
                    <div class="employee-row-item">
                        <div class="employee-row-left">
                            <input type="checkbox" class="emp-assign-cb" value="${emp.id}" onchange="updateBulkAssignButton()" style="cursor: pointer; width: 18px; height: 18px; margin-right: 0.75rem;">
                            <div class="employee-row-avatar">${avatar}</div>
                            <div class="employee-row-details">
                                <h4>${escapeHtml(emp.name)}</h4>
                                <span>Code: ${escapeHtml(emp.employee_code || '-')} | ${escapeHtml(emp.role_name || 'Operator')}</span>
                            </div>
                        </div>
                    </div>
                `;
            });
            container.innerHTML = html;
        } else {
            container.innerHTML = `<div style="padding: 1rem; color: var(--danger); text-align: center;">Error: ${res.message}</div>`;
        }
    } catch(err) {
        container.innerHTML = '<div style="padding: 1rem; color: var(--danger); text-align: center;">Failed to search employees</div>';
    }
}

function toggleCheckAll(source) {
    const checkboxes = document.querySelectorAll('.emp-assign-cb');
    checkboxes.forEach(cb => cb.checked = source.checked);
    updateBulkAssignButton();
}

function updateBulkAssignButton() {
    const checkedBoxes = document.querySelectorAll('.emp-assign-cb:checked');
    const btn = document.getElementById('bulkAssignBtn');
    
    if (checkedBoxes.length > 0) {
        btn.disabled = false;
        btn.innerText = `Assign Selected (${checkedBoxes.length})`;
    } else {
        btn.disabled = true;
        btn.innerText = 'Assign Selected';
    }
}

function assignCheckedEmployees() {
    const checkedBoxes = document.querySelectorAll('.emp-assign-cb:checked');
    if (checkedBoxes.length === 0) return;
    
    checkedBoxes.forEach(cb => {
        const id = parseInt(cb.value);
        const emp = availableEmployees.find(e => e.id === id);
        if (emp && !localTaggedEmployees.some(e => e.id === id)) {
            localTaggedEmployees.push(emp);
        }
    });
    
    renderTaggedEmployees();
    loadSearchEmployees();
}

function removeLocalEmployee(id) {
    localTaggedEmployees = localTaggedEmployees.filter(emp => emp.id !== id);
    renderTaggedEmployees();
    loadSearchEmployees();
}

async function saveAssignments() {
    const btn = document.getElementById('saveAssignmentsBtn');
    btn.disabled = true;
    btn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Saving...';
    
    const employeeIds = localTaggedEmployees.map(emp => emp.id);
    
    try {
        const basePath = window.APP_CONFIG ? window.APP_CONFIG.BASE_PATH : '/';
        const response = await fetch(`${basePath}api/shifts.php?action=save_assignments`, {
            method: 'POST',
            headers: {'Content-Type': 'application/json'},
            body: JSON.stringify({
                shift_id: currentShiftId,
                employee_ids: employeeIds
            })
        });
        const res = await response.json();
        if (res.success) {
            notify(res.message, 'success');
            closeModal('tagEmployeesModal');
            // Refresh screen to reflect details on the shift cards!
            setTimeout(() => location.reload(), 1000);
        } else {
            notify(res.message || 'Failed to save assignments', 'error');
            btn.disabled = false;
            btn.innerText = 'Save Changes';
        }
    } catch(err) {
        notify('Failed to save assignments', 'error');
        btn.disabled = false;
        btn.innerText = 'Save Changes';
    }
}

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