<?php
// team_leader/technicians.php
$title = 'Technicians';
ob_start();

require_once '../config/database.php';
$database = new Database();
$db = $database->getConnection();

$cities = $db->query("SELECT * FROM cities WHERE is_active = 1 ORDER BY city_name")->fetchAll(PDO::FETCH_ASSOC);
$skills = $db->query("SELECT * FROM appliance_types ORDER BY name")->fetchAll(PDO::FETCH_ASSOC);
?>

<style>
.tech-page-title{font-family:'Space Grotesk',system-ui,sans-serif;color:var(--cm-text)!important;font-weight:900;letter-spacing:.2px}.tech-page-title i{color:var(--cm-cyan)!important}.tech-page-subtitle{color:var(--cm-muted)!important}.tech-hero{background:linear-gradient(135deg,oklch(0.62 0.22 255/.14),oklch(0.72 0.18 195/.08));border:1px solid var(--cm-border);border-radius:18px;padding:18px 20px;margin-bottom:18px}.stats-card{min-height:112px;padding:18px!important;transition:.2s ease}.stats-card:hover,.technician-card:hover{transform:translateY(-2px);border-color:oklch(0.62 0.22 255/.35)!important}.stats-card h6{color:var(--cm-muted)!important;font-weight:850;text-transform:uppercase;letter-spacing:.06em;font-size:.72rem}.stats-card h3{font-family:'Space Grotesk',system-ui,sans-serif;color:var(--cm-text)!important;font-weight:900}.stats-icon-box{width:54px;height:54px;border-radius:16px;background:oklch(0.62 0.22 255/.14);border:1px solid oklch(0.62 0.22 255/.28);display:flex;align-items:center;justify-content:center}.stats-icon-box i{color:var(--cm-blue);font-size:22px}.stats-icon-box.success{background:oklch(0.72 0.18 155/.13);border-color:oklch(0.72 0.18 155/.30)}.stats-icon-box.success i{color:var(--cm-green)}.stats-icon-box.primary{background:oklch(0.72 0.18 195/.13);border-color:oklch(0.72 0.18 195/.30)}.stats-icon-box.primary i{color:var(--cm-cyan)}.stats-icon-box.danger{background:oklch(0.68 0.22 27/.13);border-color:oklch(0.68 0.22 27/.30)}.stats-icon-box.danger i{color:var(--cm-red)}.filter-section{padding:18px!important}.form-label{color:var(--cm-muted)!important;font-weight:850;font-size:.78rem;text-transform:uppercase;letter-spacing:.05em}.form-label i{color:var(--cm-cyan)!important}.nav-pills{background:var(--cm-card);border:1px solid var(--cm-border);border-radius:16px;padding:8px;gap:6px}.nav-pills .nav-link{color:var(--cm-muted)!important;border-radius:12px!important;font-weight:850;border:1px solid transparent}.nav-pills .nav-link:hover{background:oklch(0.62 0.22 255/.10);color:var(--cm-text)!important}.nav-pills .nav-link.active{background:oklch(0.62 0.22 255/.18)!important;color:var(--cm-text)!important;border-color:oklch(0.62 0.22 255/.30)}.technician-card{background:var(--cm-card);border:1px solid var(--cm-border);border-radius:18px;padding:18px;min-height:100%;color:var(--cm-text);transition:.2s ease}.technician-card h5{font-family:'Space Grotesk',system-ui,sans-serif;font-weight:850;color:var(--cm-text)}.technician-avatar{border-radius:16px;background:linear-gradient(135deg,var(--cm-blue),var(--cm-cyan));color:#fff;font-weight:900;display:flex;align-items:center;justify-content:center;box-shadow:0 10px 24px oklch(0 0 0/.18)}.status-available{background:oklch(0.72 0.18 155/.16)!important;color:oklch(0.88 0.13 155)!important;border:1px solid oklch(0.72 0.18 155/.28)}.status-on-job{background:oklch(0.62 0.22 255/.16)!important;color:oklch(0.86 0.11 255)!important;border:1px solid oklch(0.62 0.22 255/.28)}.status-break{background:oklch(0.82 0.16 85/.16)!important;color:oklch(0.92 0.11 85)!important;border:1px solid oklch(0.82 0.16 85/.28)}.status-leave{background:oklch(0.68 0.22 27/.16)!important;color:oklch(0.88 0.10 27)!important;border:1px solid oklch(0.68 0.22 27/.28)}.status-offline{background:oklch(0.72 0.02 260/.12)!important;color:var(--cm-muted)!important;border:1px solid var(--cm-border)}.alert-info{background:oklch(0.72 0.18 195/.10)!important;border:1px solid oklch(0.72 0.18 195/.25)!important;color:var(--cm-text)!important;border-radius:12px!important}.table-responsive{background:var(--cm-card);border:1px solid var(--cm-border);border-radius:16px;padding:8px}.pagination .page-link{background:var(--cm-card)!important;border-color:var(--cm-border)!important;color:var(--cm-text)!important;font-weight:800}.pagination .page-item.active .page-link{background:var(--cm-blue)!important;border-color:var(--cm-blue)!important}.pagination .page-item.disabled .page-link{color:var(--cm-muted)!important;opacity:.55}.loader{width:38px;height:38px;border:4px solid oklch(0.98 0.005 250/.12);border-top-color:var(--cm-blue);border-radius:50%;animation:spin 1s linear infinite}@keyframes spin{to{transform:rotate(360deg)}}.bg-light{background:oklch(0.98 0.005 250/.06)!important;color:var(--cm-text)!important;border:1px solid var(--cm-border)}.table-sm td,.table-sm th{color:var(--cm-text)!important}.modal .border-bottom{border-color:var(--cm-border)!important}@media(max-width:768px){.nav-pills{display:flex;overflow-x:auto;flex-wrap:nowrap}.nav-pills .nav-item{flex:0 0 auto}.filter-section .btn{width:100%}.technician-card{padding:16px}}
</style>

<!-- Header -->
<div class="tech-hero d-flex justify-content-between align-items-center flex-wrap gap-3">
    <div>
        <h4 class="mb-1 tech-page-title">
            <i class="fas fa-users-cog me-2"></i>Technicians
        </h4>
        <p class="tech-page-subtitle mb-0">Monitor technician status and assignments. Adding/editing technician profiles is admin-only.</p>
    </div>
</div>

<!-- Statistics Cards -->
<div class="row mb-4">
    <div class="col-md-3 mb-3">
        <div class="stats-card">
            <div class="d-flex justify-content-between align-items-center">
                <div>
                    <h6 class="mb-2">Total Technicians</h6>
                    <h3 class="mb-0" id="totalTechs">0</h3>
                </div>
                <div class="stats-icon-box">
                    <i class="fas fa-users"></i>
                </div>
            </div>
        </div>
    </div>
    
    <div class="col-md-3 mb-3">
        <div class="stats-card">
            <div class="d-flex justify-content-between align-items-center">
                <div>
                    <h6 class="mb-2">Available</h6>
                    <h3 class="mb-0" id="availableTechs">0</h3>
                </div>
                <div class="stats-icon-box success">
                    <i class="fas fa-check-circle"></i>
                </div>
            </div>
        </div>
    </div>
    
    <div class="col-md-3 mb-3">
        <div class="stats-card">
            <div class="d-flex justify-content-between align-items-center">
                <div>
                    <h6 class="mb-2">On Job</h6>
                    <h3 class="mb-0" id="onJobTechs">0</h3>
                </div>
                <div class="stats-icon-box primary">
                    <i class="fas fa-tools"></i>
                </div>
            </div>
        </div>
    </div>
    
    <div class="col-md-3 mb-3">
        <div class="stats-card">
            <div class="d-flex justify-content-between align-items-center">
                <div>
                    <h6 class="mb-2">On Leave</h6>
                    <h3 class="mb-0" id="onLeaveTechs">0</h3>
                </div>
                <div class="stats-icon-box danger">
                    <i class="fas fa-calendar-times"></i>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Enhanced Filters -->
<div class="filter-section">
    <div class="row g-3">
        <div class="col-md-3">
            <label class="form-label">
                <i class="fas fa-filter me-2"></i>Filter by Status
            </label>
            <select class="form-select" id="filterStatus">
                <option value="">All Statuses</option>
                <option value="1">🟢 Available</option>
                <option value="2">🔵 On Job</option>
                <option value="3">🟡 Break</option>
                <option value="4">🔴 On Leave</option>
                <option value="5">⚫ Offline</option>
            </select>
        </div>
        
        <div class="col-md-3">
            <label class="form-label">
                <i class="fas fa-city me-2"></i>Filter by City
            </label>
            <select class="form-select" id="filterCity">
                <option value="">All Cities</option>
                <?php foreach($cities as $city): ?>
                    <option value="<?php echo $city['id']; ?>"><?php echo htmlspecialchars($city['city_name']); ?></option>
                <?php endforeach; ?>
            </select>
        </div>
        
        <div class="col-md-2">
            <label class="form-label">
                <i class="fas fa-tools me-2"></i>Specialization
            </label>
            <select class="form-select" id="filterSkill">
                <option value="">All Skills</option>
                <?php foreach($skills as $skill): ?>
                    <option value="<?php echo $skill['id']; ?>"><?php echo htmlspecialchars($skill['name']); ?></option>
                <?php endforeach; ?>
            </select>
        </div>
        
        <div class="col-md-2">
            <label class="form-label">
                <i class="fas fa-search me-2"></i>Search
            </label>
            <input type="text" class="form-control" id="searchTech" placeholder="Name, email, phone...">
        </div>
        
        <div class="col-md-2 d-flex align-items-end gap-2">
            <button class="btn btn-primary flex-grow-1" onclick="applyFilters()">
                <i class="fas fa-filter me-2"></i>Apply
            </button>
            <button class="btn btn-outline-secondary" onclick="resetFilters()" title="Reset Filters">
                <i class="fas fa-redo-alt"></i>
            </button>
            <button class="btn btn-outline-info" onclick="toggleView()" id="viewToggleBtn" title="Toggle View">
                <i class="fas fa-th-large" id="viewToggleIcon"></i>
            </button>
        </div>
    </div>
</div>

<!-- Quick Status Tabs -->
<div class="mb-4">
    <ul class="nav nav-pills nav-fill" id="statusTabs">
        <li class="nav-item">
            <a class="nav-link active" data-status="all" href="#" onclick="filterByStatusTab('all'); return false;">
                <i class="fas fa-users me-2"></i>All
            </a>
        </li>
        <li class="nav-item">
            <a class="nav-link" data-status="1" href="#" onclick="filterByStatusTab(1); return false;">
                🟢 Available
            </a>
        </li>
        <li class="nav-item">
            <a class="nav-link" data-status="2" href="#" onclick="filterByStatusTab(2); return false;">
                🔵 On Job
            </a>
        </li>
        <li class="nav-item">
            <a class="nav-link" data-status="3" href="#" onclick="filterByStatusTab(3); return false;">
                🟡 Break
            </a>
        </li>
        <li class="nav-item">
            <a class="nav-link" data-status="4" href="#" onclick="filterByStatusTab(4); return false;">
                🔴 On Leave
            </a>
        </li>
        <li class="nav-item">
            <a class="nav-link" data-status="5" href="#" onclick="filterByStatusTab(5); return false;">
                ⚫ Offline
            </a>
        </li>
    </ul>
</div>

<!-- Technicians Grid/Cards View -->
<div id="techniciansGridView" style="display: block;">
    <div class="row" id="techniciansGrid">
        <div class="col-12 text-center py-5">
            <div class="loader mx-auto"></div>
            <p class="text-muted mt-3">Loading technicians...</p>
        </div>
    </div>
</div>

<!-- Technicians Table View -->
<div id="techniciansTableView" style="display: none;">
    <div class="table-responsive">
        <table class="table table-hover" id="techniciansTable">
            <thead>
                <tr>
                    <th>Technician</th>
                    <th>Contact</th>
                    <th>Status</th>
                    <th>City</th>
                    <th>Specialization</th>
                    <th>Current Job</th>
                    <th>Actions</th>
                </tr>
            </thead>
            <tbody id="techniciansTableBody">
                <tr>
                    <td colspan="7" class="text-center py-5">
                        <div class="loader mx-auto"></div>
                        <p class="text-muted mt-3">Loading technicians...</p>
                    </td>
                </tr>
            </tbody>
        </table>
    </div>
</div>

<nav aria-label="Page navigation" class="mt-4">
    <ul class="pagination justify-content-center" id="pagination"></ul>
</nav>

<!-- Technician Details Modal -->
<div class="modal fade" id="technicianModal" tabindex="-1">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">Technician Details</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>

            <div class="modal-body" id="technicianDetailsBody">
                <div class="text-center py-5">
                    <div class="loader mx-auto"></div>
                    <p class="text-muted mt-3">Loading details...</p>
                </div>
            </div>

            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
                <button type="button" class="btn btn-success" onclick="assignJob(currentTechId)" id="assignJobBtn">
                    <i class="fas fa-tasks me-2"></i>Assign Job
                </button>
            </div>
        </div>
    </div>
</div>

<!-- Assign Job Modal -->
<div class="modal fade" id="assignJobModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">Assign Job to Technician</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>

            <div class="modal-body">
                <form id="assignJobForm">
                    <input type="hidden" name="technician_id" id="assign_technician_id">
                    
                    <div class="mb-3">
                        <label class="form-label">Select Request</label>
                        <select class="form-select" name="request_id" id="assign_request_id" required>
                            <option value="">Choose request...</option>
                        </select>
                    </div>
                    
                    <div class="mb-3">
                        <label class="form-label">Estimated Arrival</label>
                        <input type="datetime-local" class="form-control" name="estimated_arrival" id="estimated_arrival" required>
                    </div>
                    
                    <div class="mb-3">
                        <label class="form-label">CSR Notes</label>
                        <textarea class="form-control" name="csr_notes" rows="3" placeholder="Special instructions..."></textarea>
                    </div>
                </form>
            </div>

            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                <button type="button" class="btn btn-primary" onclick="submitAssignment()">Assign Job</button>
            </div>
        </div>
    </div>
</div>

<!-- Update Status Modal -->
<div class="modal fade" id="updateStatusModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">Update Technician Status</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>

            <div class="modal-body">
                <form id="updateStatusForm">
                    <input type="hidden" name="technician_id" id="status_technician_id">
                    
                    <div class="mb-3">
                        <label class="form-label">New Status</label>
                        <select class="form-select" name="status_id" id="new_status_id" required>
                            <option value="1">🟢 Available</option>
                            <option value="2">🔵 On Job</option>
                            <option value="3">🟡 Break</option>
                            <option value="4">🔴 On Leave</option>
                            <option value="5">⚫ Offline</option>
                        </select>
                    </div>
                    
                    <div class="mb-3">
                        <label class="form-label">Notes</label>
                        <textarea class="form-control" name="notes" rows="3" placeholder="Reason for status change..."></textarea>
                    </div>
                </form>
            </div>

            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                <button type="button" class="btn btn-primary" onclick="submitStatusUpdate()">Update Status</button>
            </div>
        </div>
    </div>
</div>

<script>
let techniciansData = [];
let currentPage = 1;
let totalPages = 1;
let currentView = 'grid';
let currentTechId = null;

$(document).ready(function() {
    loadTechnicians();
    
    let searchTimer;
    $('#searchTech').on('input', function() {
        clearTimeout(searchTimer);
        searchTimer = setTimeout(function() {
            applyFilters();
        }, 500);
    });
    
    setInterval(loadTechnicians, 30000);
});

function loadTechnicians(page = 1) {
    currentPage = page;
    
    let filters = {
        page: page,
        status: $('#filterStatus').val(),
        city: $('#filterCity').val(),
        skill: $('#filterSkill').val(),
        search: $('#searchTech').val()
    };
    
    if (currentView === 'grid') {
        $('#techniciansGrid').html(`
            <div class="col-12 text-center py-5">
                <div class="loader mx-auto"></div>
                <p class="text-muted mt-3">Loading technicians...</p>
            </div>
        `);
    } else {
        $('#techniciansTableBody').html(`
            <tr>
                <td colspan="7" class="text-center py-5">
                    <div class="loader mx-auto"></div>
                    <p class="text-muted mt-3">Loading technicians...</p>
                </td>
            </tr>
        `);
    }
    
    $.ajax({
        url: '../csr/ajax/get_technicians.php',
        method: 'GET',
        data: filters,
        dataType: 'json',
        success: function(response) {
            if(response.success) {
                techniciansData = response.technicians;
                
                if (response.stats) {
                    updateStatistics(response.stats);
                } else {
                    calculateAndUpdateStats(response.technicians);
                }
                
                if (currentView === 'grid') {
                    displayTechniciansGrid(response.technicians);
                } else {
                    displayTechniciansTable(response.technicians);
                }
                
                if (response.pagination) {
                    updatePagination(response.pagination);
                }
            } else {
                showError(response.message || 'Failed to load technicians');
            }
        },
        error: function() {
            showError('Error loading technicians');
        }
    });
}

function calculateAndUpdateStats(technicians) {
    if (!technicians || technicians.length === 0) {
        updateStatistics({
            total: 0,
            available: 0,
            on_job: 0,
            on_leave: 0
        });
        return;
    }
    
    let stats = {
        total: technicians.length,
        available: 0,
        on_job: 0,
        on_leave: 0
    };
    
    technicians.forEach(function(tech) {
        switch(parseInt(tech.status_id)) {
            case 1:
                stats.available++;
                break;
            case 2:
                stats.on_job++;
                break;
            case 4:
                stats.on_leave++;
                break;
        }
    });
    
    updateStatistics(stats);
}

function updateStatistics(stats) {
    stats = stats || {};
    $('#totalTechs').text(stats.total || 0);
    $('#availableTechs').text(stats.available || 0);
    $('#onJobTechs').text(stats.on_job || 0);
    $('#onLeaveTechs').text(stats.on_leave || 0);
}

function displayTechniciansGrid(technicians) {
    if(!technicians || technicians.length === 0) {
        $('#techniciansGrid').html(`
            <div class="col-12 text-center py-5">
                <i class="fas fa-user-slash fa-4x text-muted mb-3"></i>
                <h5 class="text-muted">No technicians found</h5>
                <p class="text-muted">Try adjusting your filters</p>
            </div>
        `);
        return;
    }
    
    let html = '';
    technicians.forEach(function(tech) {
        let statusClass = getStatusClass(tech.status_name);
        let statusIcon = getStatusIcon(tech.status_name);
        
        html += `
            <div class="col-md-6 col-lg-4 mb-3">
                <div class="technician-card" onclick="viewTechnicianDetails(${tech.id})" style="cursor: pointer;">
                    <div class="d-flex align-items-start mb-3">
                        <div class="technician-avatar me-3" style="width: 50px; height: 50px; font-size: 18px;">
                            ${escapeHtml(tech.initials || 'NA')}
                        </div>

                        <div class="flex-grow-1">
                            <h5 class="mb-1">${escapeHtml(tech.full_name)}</h5>
                            <p class="text-muted mb-1">
                                <i class="fas fa-id-card me-1"></i>${escapeHtml(tech.employee_id || 'No ID')}
                            </p>
                            <p class="text-muted mb-0">
                                <i class="fas fa-phone me-1"></i>${escapeHtml(tech.phone_number || 'No phone')}
                            </p>
                        </div>
                    </div>
                    
                    <div class="mb-2">
                        <span class="badge ${statusClass}">
                            ${statusIcon} ${escapeHtml(tech.status_name || 'Offline')}
                        </span>

                        ${tech.city_name ? `
                            <span class="badge status-on-job ms-1">
                                <i class="fas fa-map-marker-alt me-1"></i>${escapeHtml(tech.city_name)}
                            </span>
                        ` : ''}
                    </div>
                    
                    <div class="mb-3">
                        <i class="fas fa-tools text-muted me-1"></i>
                        <small>${escapeHtml(formatSpecialization(tech.specialization))}</small>
                    </div>
                    
                    ${tech.current_job ? `
                        <div class="alert alert-info py-2 mb-3">
                            <small>
                                <i class="fas fa-clock me-1"></i>
                                Current Job: #${escapeHtml(tech.current_job)}
                            </small>
                        </div>
                    ` : ''}
                    
                    <div class="d-flex gap-2">
                        <button class="btn btn-sm btn-outline-primary flex-grow-1" onclick="event.stopPropagation(); viewTechnicianDetails(${tech.id})">
                            <i class="fas fa-eye me-1"></i>View
                        </button>

                        <button class="btn btn-sm btn-outline-success flex-grow-1" onclick="event.stopPropagation(); assignJob(${tech.id})" ${tech.status_id != 1 ? 'disabled' : ''}>
                            <i class="fas fa-tasks me-1"></i>Assign
                        </button>

                        <button class="btn btn-sm btn-outline-warning" onclick="event.stopPropagation(); updateTechnicianStatus(${tech.id})">
                            <i class="fas fa-edit"></i>
                        </button>

                    </div>
                </div>
            </div>
        `;
    });
    
    $('#techniciansGrid').html(html);
}

function displayTechniciansTable(technicians) {
    if(!technicians || technicians.length === 0) {
        $('#techniciansTableBody').html(`
            <tr>
                <td colspan="7" class="text-center py-5">
                    <i class="fas fa-user-slash fa-3x text-muted mb-3"></i>
                    <p class="text-muted">No technicians found</p>
                </td>
            </tr>
        `);
        return;
    }
    
    let html = '';
    technicians.forEach(function(tech) {
        let statusClass = getStatusClass(tech.status_name);
        let statusIcon = getStatusIcon(tech.status_name);
        
        html += `
            <tr onclick="viewTechnicianDetails(${tech.id})" style="cursor: pointer;">
                <td>
                    <div class="d-flex align-items-center">
                        <div class="technician-avatar me-2" style="width: 35px; height: 35px; font-size: 14px;">
                            ${escapeHtml(tech.initials || 'NA')}
                        </div>
                        <div>
                            <strong>${escapeHtml(tech.full_name)}</strong><br>
                            <small class="text-muted">${escapeHtml(tech.employee_id || '')}</small>
                        </div>
                    </div>
                </td>

                <td>
                    <small>${escapeHtml(tech.email || 'No email')}</small><br>
                    <small class="text-muted">${escapeHtml(tech.phone_number || 'No phone')}</small>
                </td>

                <td>
                    <span class="badge ${statusClass}">
                        ${statusIcon} ${escapeHtml(tech.status_name || 'Offline')}
                    </span>
                </td>

                <td>${escapeHtml(tech.city_name || 'N/A')}</td>
                <td><small>${escapeHtml(formatSpecialization(tech.specialization, true))}</small></td>

                <td>
                    ${tech.current_job ? 
                        `<span class="badge status-on-job">#${escapeHtml(tech.current_job)}</span>` : 
                        '<span class="text-muted">No active job</span>'}
                </td>

                <td onclick="event.stopPropagation();">
                    <div class="btn-group btn-group-sm">
                        <button class="btn btn-outline-primary" onclick="viewTechnicianDetails(${tech.id})" title="View">
                            <i class="fas fa-eye"></i>
                        </button>
                        <button class="btn btn-outline-success" onclick="assignJob(${tech.id})" title="Assign Job" ${tech.status_id != 1 ? 'disabled' : ''}>
                            <i class="fas fa-tasks"></i>
                        </button>
                        <button class="btn btn-outline-warning" onclick="updateTechnicianStatus(${tech.id})" title="Update Status">
                            <i class="fas fa-edit"></i>
                        </button>
                    </div>
                </td>
            </tr>
        `;
    });
    
    $('#techniciansTableBody').html(html);
}

function getStatusClass(statusName) {
    if(!statusName) return 'status-offline';
    statusName = statusName.toLowerCase();
    
    switch(statusName) {
        case 'available': return 'status-available';
        case 'on job': return 'status-on-job';
        case 'break': return 'status-break';
        case 'on leave': return 'status-leave';
        default: return 'status-offline';
    }
}

function getStatusIcon(statusName) {
    if(!statusName) return '⚫';
    statusName = statusName.toLowerCase();
    
    switch(statusName) {
        case 'available': return '🟢';
        case 'on job': return '🔵';
        case 'break': return '🟡';
        case 'on leave': return '🔴';
        default: return '⚫';
    }
}

function formatSpecialization(spec, short = false) {
    if(!spec) return 'No specialization';
    
    let lines = String(spec).split('\n');
    if (short && lines.length > 2) {
        return lines.slice(0, 2).join(', ') + '...';
    }
    return lines.join(', ');
}

function updatePagination(pagination) {
    if (!pagination || pagination.total_pages <= 1) {
        $('#pagination').empty();
        return;
    }
    
    totalPages = pagination.total_pages;
    let html = '';
    
    html += `
        <li class="page-item ${currentPage == 1 ? 'disabled' : ''}">
            <a class="page-link" href="#" onclick="loadTechnicians(${currentPage - 1}); return false;">Previous</a>
        </li>
    `;
    
    for(let i = 1; i <= pagination.total_pages; i++) {
        if(i == 1 || i == pagination.total_pages || (i >= currentPage - 2 && i <= currentPage + 2)) {
            html += `
                <li class="page-item ${i == currentPage ? 'active' : ''}">
                    <a class="page-link" href="#" onclick="loadTechnicians(${i}); return false;">${i}</a>
                </li>
            `;
        } else if(i == currentPage - 3 || i == currentPage + 3) {
            html += `<li class="page-item disabled"><span class="page-link">...</span></li>`;
        }
    }
    
    html += `
        <li class="page-item ${currentPage == pagination.total_pages ? 'disabled' : ''}">
            <a class="page-link" href="#" onclick="loadTechnicians(${currentPage + 1}); return false;">Next</a>
        </li>
    `;
    
    $('#pagination').html(html);
}

function applyFilters() {
    loadTechnicians(1);
}

function resetFilters() {
    $('#filterStatus').val('');
    $('#filterCity').val('');
    $('#filterSkill').val('');
    $('#searchTech').val('');
    filterByStatusTab('all');
}

function filterByStatusTab(status) {
    $('#statusTabs .nav-link').removeClass('active');
    $(`#statusTabs .nav-link[data-status="${status}"]`).addClass('active');
    
    if(status === 'all') {
        $('#filterStatus').val('');
    } else {
        $('#filterStatus').val(status);
    }
    
    applyFilters();
}

function toggleView() {
    if (currentView === 'grid') {
        currentView = 'table';
        $('#techniciansGridView').hide();
        $('#techniciansTableView').show();
        $('#viewToggleIcon').removeClass('fa-th-large').addClass('fa-table');
        $('#viewToggleBtn').attr('title', 'Switch to Grid View');
        displayTechniciansTable(techniciansData);
    } else {
        currentView = 'grid';
        $('#techniciansGridView').show();
        $('#techniciansTableView').hide();
        $('#viewToggleIcon').removeClass('fa-table').addClass('fa-th-large');
        $('#viewToggleBtn').attr('title', 'Switch to Table View');
        displayTechniciansGrid(techniciansData);
    }
}

function viewTechnicianDetails(id) {
    currentTechId = id;
    let tech = techniciansData.find(t => t.id == id);
    if (!tech) return;
    
    let statusIcon = getStatusIcon(tech.status_name);
    let statusClass = getStatusClass(tech.status_name);
    
    let html = `
        <div class="text-center mb-4">
            <div class="technician-avatar mx-auto mb-3" style="width: 80px; height: 80px; font-size: 32px;">
                ${escapeHtml(tech.initials || 'NA')}
            </div>
            <h4>${escapeHtml(tech.full_name)}</h4>
            <p class="text-muted">${tech.employee_id ? 'ID: ' + escapeHtml(tech.employee_id) : ''}</p>
            <span class="badge ${statusClass} p-2">${statusIcon} ${escapeHtml(tech.status_name || 'Offline')}</span>
        </div>
        
        <div class="row">
            <div class="col-md-6">
                <h6 class="border-bottom pb-2">Contact Information</h6>
                <table class="table table-sm">
                    <tr>
                        <th width="40%"><i class="fas fa-envelope me-2"></i>Email:</th>
                        <td>${escapeHtml(tech.email || 'No email')}</td>
                    </tr>
                    <tr>
                        <th><i class="fas fa-phone me-2"></i>Phone:</th>
                        <td>${escapeHtml(tech.phone_number || 'No phone')}</td>
                    </tr>
                </table>
            </div>
            
            <div class="col-md-6">
                <h6 class="border-bottom pb-2">Location</h6>
                <table class="table table-sm">
                    <tr>
                        <th width="40%"><i class="fas fa-city me-2"></i>City:</th>
                        <td>${escapeHtml(tech.city_name || 'Not assigned')}</td>
                    </tr>
                    <tr>
                        <th><i class="fas fa-map-marker-alt me-2"></i>Address:</th>
                        <td>${escapeHtml(tech.address || 'No address provided')}</td>
                    </tr>
                </table>
            </div>
        </div>
        
        <div class="row mt-3">
            <div class="col-12">
                <h6 class="border-bottom pb-2">Specialization</h6>
                <div class="p-3 bg-light rounded">
                    ${escapeHtml(formatSpecialization(tech.specialization))}
                </div>
            </div>
        </div>
        
        <div class="row mt-3">
            <div class="col-12">
                <h6 class="border-bottom pb-2">Current Assignment</h6>
                ${tech.current_job ? `
                    <div class="alert alert-info">
                        <strong>Job #${escapeHtml(tech.current_job)}</strong> - In Progress
                    </div>
                ` : `
                    <p class="text-muted">No active job assigned</p>
                `}
            </div>
        </div>
    `;
    
    $('#technicianDetailsBody').html(html);
    $('#technicianModal').modal('show');
    
    if (tech.status_id != 1) {
        $('#assignJobBtn').prop('disabled', true).attr('title', 'Technician not available');
    } else {
        $('#assignJobBtn').prop('disabled', false).attr('title', 'Assign Job');
    }
}

function assignJob(technicianId) {
    currentTechId = technicianId;
    $('#assign_technician_id').val(technicianId);
    
    $.ajax({
        url: '../csr/ajax/get_available_requests.php',
        method: 'GET',
        data: { technician_id: technicianId },
        dataType: 'json',
        success: function(response) {
            if(response.success) {
                let options = '<option value="">Choose request...</option>';
                response.requests.forEach(function(req) {
                    options += `<option value="${req.id}">${escapeHtml(req.request_number)} - ${escapeHtml(req.full_name)} (${escapeHtml(req.appliance_type)})</option>`;
                });
                $('#assign_request_id').html(options);
                
                let date = new Date();
                date.setHours(date.getHours() + 2);
                $('#estimated_arrival').val(date.toISOString().slice(0,16));
                
                $('#assignJobModal').modal('show');
            } else {
                showToast(response.message, 'error');
            }
        },
        error: function() {
            showToast('Error loading available requests', 'error');
        }
    });
}

function submitAssignment() {
    let formData = $('#assignJobForm').serialize();
    
    $.ajax({
        url: '../csr/ajax/assign_job.php',
        method: 'POST',
        data: formData,
        dataType: 'json',
        success: function(response) {
            if(response.success) {
                showToast(response.message, 'success');
                $('#assignJobModal').modal('hide');
                loadTechnicians(currentPage);
            } else {
                showToast(response.message, 'error');
            }
        },
        error: function() {
            showToast('Error assigning job', 'error');
        }
    });
}

function updateTechnicianStatus(id) {
    currentTechId = id;
    let tech = techniciansData.find(t => t.id == id);
    if (!tech) return;
    
    $('#status_technician_id').val(id);
    $('#new_status_id').val(tech.status_id);
    $('#updateStatusModal').modal('show');
}

function submitStatusUpdate() {
    let formData = $('#updateStatusForm').serialize();
    
    $.ajax({
        url: '../csr/ajax/update_technician_status.php',
        method: 'POST',
        data: formData,
        dataType: 'json',
        success: function(response) {
            if(response.success) {
                showToast(response.message, 'success');
                $('#updateStatusModal').modal('hide');
                loadTechnicians(currentPage);
            } else {
                showToast(response.message, 'error');
            }
        },
        error: function() {
            showToast('Error updating status', 'error');
        }
    });
}

function showToast(message, type = 'info') {
    if (typeof window.showToast === 'function') {
        window.showToast(message, type);
    } else {
        alert(message);
    }
}

function showError(message) {
    console.error(message);
    showToast(message, 'error');
}

function escapeHtml(value) {
    return $('<div>').text(value || '').html();
}
</script>

<?php
$content = ob_get_clean();
include __DIR__ . '/layout.php';
?>