<?php
require_once 'auth.php';
ensureAdminAuth();

require_once '../config/database.php';
require_once '../includes/app_helpers.php';

$database = new Database();
$db = $database->getConnection();
ensureAnnouncementTables($db);

$message = '';
$error = '';

function staffRoleLabel($role) {
    if ($role === 'csr_manager') return 'MANAGER';
    if ($role === 'team_leader') return 'TEAM LEADER';
    return 'AGENT';
}

function ensureTeamLeaderTeam(PDO $db, int $leaderId, string $leaderName): int {
    if ($leaderId <= 0) return 0;

    $stmt = $db->prepare("SELECT id FROM csr_teams WHERE manager_id = :leader_id ORDER BY is_active DESC, id ASC LIMIT 1");
    $stmt->execute([':leader_id' => $leaderId]);
    $existingId = (int)$stmt->fetchColumn();

    $teamName = 'Team ' . trim($leaderName ?: ('Leader #' . $leaderId));

    if ($existingId > 0) {
        $update = $db->prepare("UPDATE csr_teams SET team_name = :team_name, is_active = 1 WHERE id = :id");
        $update->execute([':team_name' => $teamName, ':id' => $existingId]);
        return $existingId;
    }

    $insert = $db->prepare("INSERT INTO csr_teams (team_name, manager_id, is_active) VALUES (:team_name, :manager_id, 1)");
    $insert->execute([':team_name' => $teamName, ':manager_id' => $leaderId]);
    return (int)$db->lastInsertId();
}

if ($_SERVER['REQUEST_METHOD'] === 'POST' && ($_POST['action'] ?? '') === 'assign_agent_team') {
    header('Content-Type: application/json');

    try {
        $agentId = (int)($_POST['agent_id'] ?? 0);
        $teamId = (int)($_POST['team_id'] ?? 0);

        if ($agentId <= 0) {
            throw new Exception('Missing CSR agent.');
        }

        $agentCheck = $db->prepare("SELECT id FROM csr_users WHERE id = :id AND role = 'csr' LIMIT 1");
        $agentCheck->execute([':id' => $agentId]);
        if (!$agentCheck->fetchColumn()) {
            throw new Exception('Only AGENT accounts can be assigned to Team Leaders.');
        }

        if ($teamId > 0) {
            $teamCheck = $db->prepare("SELECT id FROM csr_teams WHERE id = :id AND is_active = 1 LIMIT 1");
            $teamCheck->execute([':id' => $teamId]);
            if (!$teamCheck->fetchColumn()) {
                throw new Exception('Team Leader container was not found.');
            }
        }

        $db->beginTransaction();
        $remove = $db->prepare("DELETE FROM csr_team_members WHERE csr_id = :csr_id");
        $remove->execute([':csr_id' => $agentId]);

        if ($teamId > 0) {
            $add = $db->prepare("INSERT INTO csr_team_members (team_id, csr_id) VALUES (:team_id, :csr_id)");
            $add->execute([':team_id' => $teamId, ':csr_id' => $agentId]);
        }

        $db->commit();

        echo json_encode([
            'success' => true,
            'message' => $teamId > 0 ? 'CSR agent assigned to Team Leader.' : 'CSR agent moved to unassigned list.'
        ]);
    } catch (Exception $e) {
        if ($db->inTransaction()) {
            $db->rollBack();
        }
        http_response_code(400);
        echo json_encode(['success' => false, 'message' => $e->getMessage()]);
    }

    exit;
}

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['save_csr'])) {
    try {
        $id = (int)($_POST['csr_id'] ?? 0);
        $first = trim($_POST['first_name'] ?? '');
        $last = trim($_POST['last_name'] ?? '');
        $email = trim($_POST['email'] ?? '');
        $password = $_POST['password'] ?? '';
        $active = isset($_POST['is_active']) ? 1 : 0;
        $role = in_array(($_POST['role'] ?? 'csr'), ['csr','team_leader','csr_manager'], true) ? $_POST['role'] : 'csr';
        if ($role === 'csr_manager') {
            $excludeId = (int)($_POST['csr_id'] ?? 0);
            $checkManager = $db->prepare("SELECT COUNT(*) FROM csr_users WHERE role = 'csr_manager' AND id <> :exclude_id");
            $checkManager->execute([':exclude_id' => $excludeId]);
            if ((int)$checkManager->fetchColumn() >= 1) {
                throw new Exception('Only one CSR Manager account is allowed.');
            }
        }

        if ($first === '' || $last === '' || $email === '') {
            throw new Exception('First name, last name, and email are required.');
        }

        if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
            throw new Exception('Please enter a valid CSR email address.');
        }

        $check = $db->prepare('SELECT id FROM csr_users WHERE email = :email' . ($id > 0 ? ' AND id != :id' : ''));
        $check->bindValue(':email', $email);

        if ($id > 0) {
            $check->bindValue(':id', $id, PDO::PARAM_INT);
        }

        $check->execute();

        if ($check->fetch(PDO::FETCH_ASSOC)) {
            throw new Exception('A CSR account with this email already exists.');
        }

        if ($id > 0) {
            $stmt = $db->prepare("
                UPDATE csr_users 
                SET first_name = :first, last_name = :last, email = :email, is_active = :active, role = :role 
                WHERE id = :id
            ");

            $stmt->execute([
                ':first' => $first,
                ':last' => $last,
                ':email' => $email,
                ':active' => $active,
                ':role' => $role,
                ':id' => $id
            ]);

            if ($password !== '') {
                $pwd = password_hash($password, PASSWORD_DEFAULT);

                $db->prepare("
                    UPDATE csr_users 
                    SET password = :password 
                    WHERE id = :id
                ")->execute([
                    ':password' => $pwd,
                    ':id' => $id
                ]);
            }

            if ($role === 'team_leader') {
                ensureTeamLeaderTeam($db, $id, trim($first . ' ' . $last));
            } else {
                $db->prepare("UPDATE csr_teams SET is_active = 0 WHERE manager_id = :manager_id")->execute([':manager_id' => $id]);
            }

            $message = 'CSR account updated.';
        } else {
            if ($password === '') {
                throw new Exception('Password is required for new CSR users.');
            }

            $pwd = password_hash($password, PASSWORD_DEFAULT);

            $stmt = $db->prepare("
                INSERT INTO csr_users 
                    (first_name, last_name, email, password, is_active, role) 
                VALUES 
                    (:first, :last, :email, :password, :active, :role)
            ");

            $stmt->execute([
                ':first' => $first,
                ':last' => $last,
                ':email' => $email,
                ':password' => $pwd,
                ':active' => $active,
                ':role' => $role
            ]);

            if ($role === 'team_leader') {
                ensureTeamLeaderTeam($db, (int)$db->lastInsertId(), trim($first . ' ' . $last));
            }

            $message = 'CSR account created.';
        }
    } catch (Exception $e) {
        $error = 'Save failed: ' . $e->getMessage();
    }
}

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['save_technician'])) {
    try {
        $id = (int)($_POST['technician_id'] ?? 0);
        $first = trim($_POST['tech_first_name'] ?? '');
        $last = trim($_POST['tech_last_name'] ?? '');
        $email = trim($_POST['tech_email'] ?? '');
        $phone = trim($_POST['tech_phone'] ?? '');
        $password = $_POST['tech_password'] ?? '';
        $employeeId = trim($_POST['tech_employee_id'] ?? '');
        $cityId = ($_POST['tech_city_id'] ?? '') !== '' ? (int)$_POST['tech_city_id'] : null;
        $statusId = ($_POST['tech_status_id'] ?? '') !== '' ? (int)$_POST['tech_status_id'] : 1;
        $address = trim($_POST['tech_address'] ?? '');
        $specialization = trim($_POST['tech_specialization'] ?? '');
        $active = isset($_POST['tech_is_active']) ? 1 : 0;

        if ($first === '' || $last === '' || $email === '' || $phone === '') {
            throw new Exception('First name, last name, email, and phone are required for technicians.');
        }

        if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
            throw new Exception('Please enter a valid technician email address.');
        }

        $check = $db->prepare('SELECT id FROM technicians WHERE email = :email' . ($id > 0 ? ' AND id != :id' : ''));
        $check->bindValue(':email', $email);

        if ($id > 0) {
            $check->bindValue(':id', $id, PDO::PARAM_INT);
        }

        $check->execute();

        if ($check->fetch(PDO::FETCH_ASSOC)) {
            throw new Exception('A technician with this email already exists.');
        }

        if ($id > 0) {
            $stmt = $db->prepare("
                UPDATE technicians
                SET first_name = :first,
                    last_name = :last,
                    email = :email,
                    phone_number = :phone,
                    employee_id = :employee_id,
                    specialization = :specialization,
                    city_id = :city_id,
                    address = :address,
                    status_id = :status_id,
                    is_active = :active
                WHERE id = :id
            ");

            $stmt->execute([
                ':first' => $first,
                ':last' => $last,
                ':email' => $email,
                ':phone' => $phone,
                ':employee_id' => $employeeId,
                ':specialization' => $specialization,
                ':city_id' => $cityId,
                ':address' => $address,
                ':status_id' => $statusId,
                ':active' => $active,
                ':id' => $id
            ]);

            if ($password !== '') {
                $db->prepare('UPDATE technicians SET password = :password WHERE id = :id')->execute([
                    ':password' => password_hash($password, PASSWORD_DEFAULT),
                    ':id' => $id
                ]);
            }

            $message = 'Technician updated successfully.';
        } else {
            if ($password === '') {
                throw new Exception('Password is required for new technicians.');
            }

            $stmt = $db->prepare("
                INSERT INTO technicians
                    (first_name, last_name, email, phone_number, password, employee_id, specialization, city_id, address, status_id, is_active)
                VALUES
                    (:first, :last, :email, :phone, :password, :employee_id, :specialization, :city_id, :address, :status_id, :active)
            ");

            $stmt->execute([
                ':first' => $first,
                ':last' => $last,
                ':email' => $email,
                ':phone' => $phone,
                ':password' => password_hash($password, PASSWORD_DEFAULT),
                ':employee_id' => $employeeId,
                ':specialization' => $specialization,
                ':city_id' => $cityId,
                ':address' => $address,
                ':status_id' => $statusId,
                ':active' => $active
            ]);

            $message = 'Technician added successfully.';
        }
    } catch (Exception $e) {
        $error = 'Technician save failed: ' . $e->getMessage();
    }
}

try {
    $csrUsers = $db->query("
        SELECT 
            id, 
            first_name, 
            last_name, 
            email, 
            COALESCE(role, 'csr') AS role,
            is_active, 
            last_login 
        FROM csr_users 
        ORDER BY id DESC
    ")->fetchAll(PDO::FETCH_ASSOC);
} catch (Exception $e) {
    $csrUsers = [];
    $error = 'Could not load CSR users: ' . $e->getMessage();
}

try {
    $existingLeaders = $db->query("SELECT id, first_name, last_name FROM csr_users WHERE role = 'team_leader' ORDER BY first_name, last_name")->fetchAll(PDO::FETCH_ASSOC);
    foreach ($existingLeaders as $leaderRow) {
        ensureTeamLeaderTeam($db, (int)$leaderRow['id'], trim(($leaderRow['first_name'] ?? '') . ' ' . ($leaderRow['last_name'] ?? '')));
    }
} catch (Exception $e) {
    // Keep the staff page usable even if team auto-create fails.
}

try {
    $teamLeaders = $db->query("
        SELECT
            cu.id,
            cu.first_name,
            cu.last_name,
            cu.email,
            cu.phone_number,
            cu.is_active,
            cu.last_login,
            ct.id AS team_id,
            ct.team_name
        FROM csr_users cu
        LEFT JOIN csr_teams ct ON ct.manager_id = cu.id AND ct.is_active = 1
        WHERE cu.role = 'team_leader'
        ORDER BY cu.first_name, cu.last_name
    ")->fetchAll(PDO::FETCH_ASSOC);
} catch (Exception $e) {
    $teamLeaders = [];
}

try {
    $agentAssignments = $db->query("
        SELECT
            cu.id,
            cu.first_name,
            cu.last_name,
            cu.email,
            cu.phone_number,
            cu.is_active,
            cu.last_login,
            MIN(ctm.team_id) AS team_id
        FROM csr_users cu
        LEFT JOIN csr_team_members ctm ON ctm.csr_id = cu.id
        WHERE cu.role = 'csr'
        GROUP BY cu.id, cu.first_name, cu.last_name, cu.email, cu.phone_number, cu.is_active, cu.last_login
        ORDER BY cu.first_name, cu.last_name
    ")->fetchAll(PDO::FETCH_ASSOC);
} catch (Exception $e) {
    $agentAssignments = [];
}

$agentsByTeam = ['unassigned' => []];
foreach ($teamLeaders as $leaderRow) {
    $agentsByTeam[(int)($leaderRow['team_id'] ?? 0)] = [];
}
foreach ($agentAssignments as $agentRow) {
    $assignedTeamId = (int)($agentRow['team_id'] ?? 0);
    if ($assignedTeamId > 0 && array_key_exists($assignedTeamId, $agentsByTeam)) {
        $agentsByTeam[$assignedTeamId][] = $agentRow;
    } else {
        $agentsByTeam['unassigned'][] = $agentRow;
    }
}

try {
    $cities = $db->query("
        SELECT id, city_name 
        FROM cities 
        WHERE is_active = 1 
        ORDER BY city_name
    ")->fetchAll(PDO::FETCH_ASSOC);
} catch (Exception $e) {
    $cities = [];
}

try {
    $technicianStatuses = $db->query("
        SELECT id, status_name 
        FROM technician_statuses 
        ORDER BY id
    ")->fetchAll(PDO::FETCH_ASSOC);
} catch (Exception $e) {
    $technicianStatuses = [
        ['id' => 1, 'status_name' => 'Available'],
        ['id' => 2, 'status_name' => 'On Job'],
        ['id' => 3, 'status_name' => 'Break'],
        ['id' => 4, 'status_name' => 'On Leave'],
        ['id' => 5, 'status_name' => 'Offline'],
    ];
}

try {
    $techs = $db->query("
        SELECT 
            t.id, 
            t.first_name, 
            t.last_name, 
            t.email, 
            t.phone_number,
            t.employee_id,
            t.specialization,
            t.city_id,
            t.address,
            t.status_id,
            t.is_active,
            c.city_name,
            ts.status_name
        FROM technicians t
        LEFT JOIN cities c ON t.city_id = c.id
        LEFT JOIN technician_statuses ts ON t.status_id = ts.id
        ORDER BY t.id DESC 
        LIMIT 100
    ")->fetchAll(PDO::FETCH_ASSOC);
} catch (Exception $e) {
    $techs = [];
}

$total_csr = count($csrUsers);
$active_csr = count(array_filter($csrUsers, function($u) {
    return (int)$u['is_active'] === 1;
}));

$total_techs = count($techs);
$active_techs = count(array_filter($techs, function($t) {
    return !isset($t['is_active']) || (int)$t['is_active'] === 1;
}));
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Staff - Admin</title>

    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <link href="https://fonts.googleapis.com/css2?family=Montserrat:wght@400;500;600;700;800;900&display=swap" rel="stylesheet">

    <style>
        :root {
            --admin-bg-1: #080240;
            --admin-bg-2: #093349;
            --admin-card-1: #17295e;
            --admin-card-2: #102448;
            --admin-border: rgba(96, 165, 250, 0.24);
            --admin-border-strong: rgba(56, 189, 248, 0.42);
            --admin-cyan: #17bdd4;
            --admin-blue: #1d9bf0;
            --admin-text: #f8fafc;
            --admin-muted: #aebbd4;
            --admin-soft: #d7e7ff;
            --admin-green: #22c55e;
            --admin-red: #f43f5e;
            --admin-input: rgba(8, 20, 48, 0.72);
        }

        * {
            box-sizing: border-box;
        }

        body {
            background: linear-gradient(135deg, var(--admin-bg-1) 0%, var(--admin-bg-2) 100%) fixed !important;
            color: var(--admin-text) !important;
            font-family: 'Montserrat', sans-serif !important;
            min-height: 100vh;
            overflow-x: hidden;
        }

        .sidebar {
            min-height: 100vh;
            background: rgba(8, 2, 64, 0.96);
            backdrop-filter: blur(14px);
            color: white;
            position: fixed;
            width: 250px;
            transition: all 0.3s;
            overflow-y: auto;
            z-index: 1000;
            border-right: 1px solid rgba(96, 165, 250, 0.18);
        }

        .sidebar-header {
            padding: 24px 18px;
            text-align: center;
            border-bottom: 1px solid rgba(96, 165, 250, 0.18);
        }

        .sidebar-header i {
            color: #ffffff;
        }

        .sidebar-header h4 {
            font-size: 1.1rem;
            margin-top: 10px;
            font-weight: 900;
            color: #ffffff;
        }

        .sidebar-header p {
            font-size: 0.8rem;
            color: var(--admin-muted);
        }

        .sidebar-menu {
            padding: 20px 0;
        }

        .sidebar-menu a {
            color: #b9dcff !important;
            padding: 13px 20px;
            display: block;
            text-decoration: none;
            transition: all 0.25s;
            border-left: 4px solid transparent;
            font-weight: 700;
            font-size: 14px;
        }

        .sidebar-menu a:hover,
        .sidebar-menu a.active {
            background: rgba(56, 189, 248, 0.12);
            color: #ffffff !important;
            border-left-color: var(--admin-cyan);
        }

        .sidebar-menu i {
            margin-right: 10px;
            width: 20px;
        }

        .main-content {
            margin-left: 250px;
            padding: 24px;
            min-height: 100vh;
            background: transparent !important;
        }

        .content-header {
            background: linear-gradient(135deg, var(--admin-card-1), var(--admin-card-2)) !important;
            padding: 20px;
            border-radius: 18px;
            border: 1px solid rgba(56, 189, 248, 0.28);
            box-shadow: 0 10px 24px rgba(0, 0, 0, 0.24);
            margin-bottom: 20px;
            color: #ffffff !important;
        }

        .content-header h2 {
            color: #ffffff !important;
            font-weight: 900;
        }

        .content-header h2 i {
            color: var(--admin-cyan) !important;
        }

        .content-header p,
        .text-muted {
            color: var(--admin-muted) !important;
        }

        .card {
            background: linear-gradient(135deg, var(--admin-card-1), var(--admin-card-2)) !important;
            border: 1px solid rgba(56, 189, 248, 0.24) !important;
            border-radius: 16px !important;
            box-shadow:
                0 10px 24px rgba(0, 0, 0, 0.24),
                inset 0 0 0 1px rgba(255, 255, 255, 0.025) !important;
            color: #ffffff !important;
            overflow: hidden;
            transition: all 0.25s ease;
        }

        .card:hover {
            border-color: rgba(56, 189, 248, 0.38) !important;
        }

        .card-header,
        .card-header.bg-white {
            background: linear-gradient(135deg, rgba(29, 155, 240, 0.16), rgba(23, 189, 212, 0.08)) !important;
            border-bottom: 1px solid rgba(56, 189, 248, 0.22) !important;
            padding: 15px 20px;
            font-weight: 900;
            color: #ffffff !important;
        }

        .card-body {
            padding: 20px;
            color: #ffffff !important;
        }

        h1, h2, h3, h4, h5, h6, strong, label {
            color: #ffffff !important;
        }

        .stat-card {
            height: 100%;
        }

        .stat-card:hover {
            transform: translateY(-3px);
        }

        .stat-icon-box {
            background: rgba(56, 189, 248, 0.14) !important;
            border: 1px solid rgba(56, 189, 248, 0.22);
            border-radius: 12px;
            width: 48px;
            height: 48px;
            display: flex;
            align-items: center;
            justify-content: center;
        }

        .stat-icon-box i {
            color: #dff7ff !important;
            font-size: 20px;
        }

        .form-control,
        .form-select,
        textarea,
        input {
            background-color: var(--admin-input) !important;
            border: 1px solid rgba(96, 165, 250, 0.34) !important;
            color: #ffffff !important;
            border-radius: 10px !important;
            min-height: 42px;
        }

        .form-control::placeholder,
        input::placeholder,
        textarea::placeholder {
            color: #aebbd4 !important;
            opacity: 1;
        }

        .form-control:focus,
        .form-select:focus {
            border-color: rgba(56, 189, 248, 0.62) !important;
            box-shadow: 0 0 0 0.18rem rgba(56, 189, 248, 0.18) !important;
        }

        .form-select option {
            background: #102448;
            color: #ffffff;
        }

        select.form-select option,
        .form-select option {
            background-color: #102448 !important;
            color: #ffffff !important;
        }

        select.form-select option:hover,
        select.form-select option:checked,
        select.form-select option:focus,
        .form-select option:hover,
        .form-select option:checked,
        .form-select option:focus {
            background-color: #17bdd4 !important;
            color: #ffffff !important;
        }

        .active-toggle-box {
            width: 100%;
            max-width: 460px;
            background: rgba(8, 20, 48, 0.45);
            border: 1px solid rgba(96, 165, 250, 0.24);
            border-radius: 14px;
            padding: 12px 14px;
            display: flex;
            align-items: center;
            justify-content: space-between;
            gap: 15px;
        }

        .active-toggle-box strong {
            color: #ffffff !important;
            font-size: 14px;
            font-weight: 900;
            display: block;
        }

        .active-toggle-box small {
            color: #aebbd4 !important;
            font-size: 12px;
            font-weight: 600;
        }

        .status-switch {
            position: relative;
            display: inline-block;
            width: 54px;
            height: 28px;
            margin: 0;
            flex-shrink: 0;
        }

        .status-switch input {
            opacity: 0;
            width: 0;
            height: 0;
        }

        .status-slider {
            position: absolute;
            cursor: pointer;
            inset: 0;
            background: rgba(148, 163, 184, 0.35);
            border: 1px solid rgba(148, 163, 184, 0.45);
            transition: 0.25s;
            border-radius: 999px;
        }

        .status-slider:before {
            position: absolute;
            content: "";
            height: 20px;
            width: 20px;
            left: 4px;
            top: 3px;
            background: #ffffff;
            transition: 0.25s;
            border-radius: 50%;
        }

        .status-switch input:checked + .status-slider {
            background: linear-gradient(135deg, #1d9bf0 0%, #17bdd4 100%);
            border-color: rgba(56, 189, 248, 0.70);
        }

        .status-switch input:checked + .status-slider:before {
            transform: translateX(25px);
        }

        .btn {
            font-weight: 800 !important;
            border-radius: 10px !important;
        }

        .btn-primary,
        .btn-info {
            background: linear-gradient(135deg, #1d9bf0 0%, #17bdd4 100%) !important;
            border: none !important;
            color: #ffffff !important;
        }

        .btn-outline-secondary {
            border-color: rgba(148, 163, 184, 0.42) !important;
            color: #e2e8f0 !important;
            background: rgba(148, 163, 184, 0.10) !important;
        }

        .btn-outline-secondary:hover {
            background: rgba(148, 163, 184, 0.24) !important;
            color: #ffffff !important;
        }

        .btn-outline-primary {
            border-color: rgba(56, 189, 248, 0.42) !important;
            color: #dff7ff !important;
            background: rgba(56, 189, 248, 0.10) !important;
        }

        .btn-outline-primary:hover {
            background: rgba(56, 189, 248, 0.24) !important;
            color: #ffffff !important;
        }

        .badge {
            padding: 6px 10px;
            border-radius: 999px;
            font-weight: 900;
        }

        .badge.bg-primary {
            background: linear-gradient(135deg, #1d9bf0 0%, #17bdd4 100%) !important;
            color: #ffffff !important;
        }

        .badge.bg-info {
            background: rgba(56, 189, 248, 0.18) !important;
            color: #dff7ff !important;
            border: 1px solid rgba(56, 189, 248, 0.34);
        }

        .badge.bg-success {
            background: rgba(34, 197, 94, 0.18) !important;
            color: #bbf7d0 !important;
            border: 1px solid rgba(34, 197, 94, 0.34);
        }

        .badge.bg-secondary {
            background: rgba(148, 163, 184, 0.20) !important;
            border: 1px solid rgba(148, 163, 184, 0.34);
            color: #e2e8f0 !important;
        }

        .alert {
            border-radius: 14px;
            border: 1px solid rgba(56, 189, 248, 0.28) !important;
        }

        .alert-success {
            background: rgba(34, 197, 94, 0.14) !important;
            color: #bbf7d0 !important;
        }

        .alert-danger {
            background: rgba(244, 63, 94, 0.14) !important;
            color: #fecaca !important;
        }

        .table-responsive {
            border-radius: 12px;
            overflow-x: auto;
            background: transparent !important;
        }

        .table {
            color: var(--admin-text) !important;
            margin-bottom: 0 !important;
        }

        .table th {
            font-weight: 900;
            color: #ffffff !important;
            white-space: nowrap;
            background: rgba(8, 20, 48, 0.58) !important;
            border-color: rgba(96, 165, 250, 0.22) !important;
            font-size: 13px;
        }

        .table td {
            vertical-align: middle;
            color: var(--admin-soft) !important;
            border-color: rgba(96, 165, 250, 0.20) !important;
            background: rgba(8, 20, 48, 0.18) !important;
        }

        .table tbody tr:hover td {
            background: rgba(56, 189, 248, 0.10) !important;
            color: #ffffff !important;
        }

        .table small {
            color: var(--admin-muted) !important;
        }

        .table strong {
            color: #ffffff !important;
        }

        .staff-avatar {
            width: 42px;
            height: 42px;
            border-radius: 50%;
            background: linear-gradient(135deg, #1d9bf0 0%, #17bdd4 100%);
            color: #ffffff;
            display: inline-flex;
            align-items: center;
            justify-content: center;
            font-weight: 900;
            flex-shrink: 0;
            border: 1px solid rgba(255,255,255,0.18);
            margin-right: 10px;
        }

        .staff-name-wrap {
            display: flex;
            align-items: center;
            gap: 4px;
        }


        .team-board-grid {
            display: grid;
            grid-template-columns: minmax(280px, 360px) 1fr;
            gap: 18px;
            align-items: start;
        }

        .team-leader-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(280px, 1fr));
            gap: 16px;
        }

        .agent-pool,
        .team-dropzone {
            min-height: 180px;
            background: rgba(8, 20, 48, 0.38);
            border: 1px dashed rgba(96, 165, 250, 0.38);
            border-radius: 16px;
            padding: 12px;
            transition: all 0.2s ease;
        }

        .agent-pool.drag-over,
        .team-dropzone.drag-over {
            border-color: rgba(23, 189, 212, 0.92);
            background: rgba(23, 189, 212, 0.12);
            box-shadow: 0 0 0 3px rgba(23, 189, 212, 0.12);
        }

        .agent-card {
            display: flex;
            align-items: center;
            justify-content: space-between;
            gap: 10px;
            background: rgba(15, 31, 68, 0.92);
            border: 1px solid rgba(96, 165, 250, 0.28);
            border-radius: 14px;
            padding: 10px 12px;
            margin-bottom: 10px;
            cursor: grab;
            color: #ffffff;
            user-select: none;
        }

        .agent-card:active {
            cursor: grabbing;
        }

        .agent-card.dragging {
            opacity: 0.48;
        }

        .agent-card__name {
            font-weight: 900;
            color: #ffffff;
            line-height: 1.2;
        }

        .agent-card__meta {
            color: var(--admin-muted);
            font-size: 12px;
            font-weight: 600;
            word-break: break-word;
        }

        .team-leader-card {
            background: linear-gradient(135deg, rgba(23, 41, 94, 0.98), rgba(16, 36, 72, 0.98));
            border: 1px solid rgba(56, 189, 248, 0.24);
            border-radius: 18px;
            padding: 14px;
            min-height: 260px;
        }

        .team-leader-card__header {
            display: flex;
            align-items: flex-start;
            justify-content: space-between;
            gap: 10px;
            margin-bottom: 12px;
        }

        .team-empty {
            color: var(--admin-muted);
            text-align: center;
            padding: 26px 10px;
            font-weight: 700;
        }

        .assignment-toast {
            position: fixed;
            right: 18px;
            bottom: 18px;
            z-index: 3000;
            min-width: 260px;
            max-width: 360px;
            border-radius: 14px;
            padding: 13px 15px;
            background: rgba(15, 23, 42, 0.96);
            color: #ffffff;
            border: 1px solid rgba(56, 189, 248, 0.42);
            box-shadow: 0 18px 40px rgba(0, 0, 0, 0.32);
            display: none;
            font-weight: 800;
        }

        .assignment-toast.show {
            display: block;
        }

        @media (max-width: 992px) {
            .team-board-grid {
                grid-template-columns: 1fr;
            }
        }

        @media (max-width: 768px) {
            .sidebar {
                width: 100%;
                position: relative;
                min-height: auto;
            }

            .main-content {
                margin-left: 0;
                padding: 14px;
            }

            .content-header {
                padding: 15px;
                display: block !important;
            }

            .content-header > div:last-child {
                margin-top: 12px;
            }

            .content-header h2 {
                font-size: 1.3rem;
            }

            .card-body {
                padding: 15px;
            }

            .table {
                min-width: 820px;
            }

            .active-toggle-box {
                max-width: 100%;
            }
        }
    </style>

    <link rel="stylesheet" href="../assets/theme.css">
    <link rel="stylesheet" href="../assets/portal-dark.css">
    <link rel="stylesheet" href="../assets/ushs-global-theme.css">
    <link rel="stylesheet" href="../assets/admin-sidebar.css">
</head>

<body>
    <?php require_once __DIR__ . '/admin_sidebar.php'; render_admin_sidebar(); ?>

    <main class="main-content">
        <div class="content-header d-flex justify-content-between align-items-center">
            <div>
                <h2 class="mb-1">
                    <i class="fas fa-user-tie me-2"></i>
                    Staff Management
                </h2>

                <p class="text-muted mb-0">
                    Manage CSR accounts and add/update technician records from the admin side only.
                </p>
            </div>

            <div>
                <span class="badge bg-primary p-2">
                    <i class="fas fa-calendar me-1"></i>
                    <?php echo date('F d, Y'); ?>
                </span>
            </div>
        </div>

        <?php if($message): ?>
            <div class="alert alert-success">
                <i class="fas fa-check-circle me-2"></i>
                <?= htmlspecialchars($message) ?>
            </div>
        <?php endif; ?>

        <?php if($error): ?>
            <div class="alert alert-danger">
                <i class="fas fa-exclamation-circle me-2"></i>
                <?= htmlspecialchars($error) ?>
            </div>
        <?php endif; ?>

        <div class="row mb-4">
            <div class="col-md-3 col-6 mb-3">
                <div class="card stat-card">
                    <div class="card-body d-flex justify-content-between align-items-center">
                        <div>
                            <h6 class="text-muted mb-1">CSR Users</h6>
                            <h3 class="mb-0"><?= number_format($total_csr) ?></h3>
                        </div>
                        <div class="stat-icon-box"><i class="fas fa-headset"></i></div>
                    </div>
                </div>
            </div>

            <div class="col-md-3 col-6 mb-3">
                <div class="card stat-card">
                    <div class="card-body d-flex justify-content-between align-items-center">
                        <div>
                            <h6 class="text-muted mb-1">Active CSR</h6>
                            <h3 class="mb-0"><?= number_format($active_csr) ?></h3>
                        </div>
                        <div class="stat-icon-box"><i class="fas fa-user-check"></i></div>
                    </div>
                </div>
            </div>

            <div class="col-md-3 col-6 mb-3">
                <div class="card stat-card">
                    <div class="card-body d-flex justify-content-between align-items-center">
                        <div>
                            <h6 class="text-muted mb-1">Technicians</h6>
                            <h3 class="mb-0"><?= number_format($total_techs) ?></h3>
                        </div>
                        <div class="stat-icon-box"><i class="fas fa-tools"></i></div>
                    </div>
                </div>
            </div>

            <div class="col-md-3 col-6 mb-3">
                <div class="card stat-card">
                    <div class="card-body d-flex justify-content-between align-items-center">
                        <div>
                            <h6 class="text-muted mb-1">Active Techs</h6>
                            <h3 class="mb-0"><?= number_format($active_techs) ?></h3>
                        </div>
                        <div class="stat-icon-box"><i class="fas fa-wrench"></i></div>
                    </div>
                </div>
            </div>
        </div>

        <div class="card mb-4">
            <div class="card-header">
                <i class="fas fa-user-plus me-2" style="color: var(--admin-cyan);"></i>
                Add / Update CSR Account
            </div>

            <div class="card-body">
                <form method="POST" class="row g-3">
                    <input type="hidden" name="csr_id" id="csr_id">

                    <div class="col-md-3">
                        <label class="form-label">First Name</label>
                        <input class="form-control" name="first_name" id="first_name" required>
                    </div>

                    <div class="col-md-3">
                        <label class="form-label">Last Name</label>
                        <input class="form-control" name="last_name" id="last_name" required>
                    </div>

                    <div class="col-md-3">
                        <label class="form-label">Email</label>
                        <input class="form-control" type="email" name="email" id="email" required>
                    </div>

                    <div class="col-md-3">
                        <label class="form-label">Role</label>
                        <select class="form-select" name="role" id="role">
                            <option value="csr">AGENT</option>
                            <option value="team_leader">TEAM LEADER</option>
                            <option value="csr_manager">MANAGER</option>
                        </select>
                    </div>

                    <div class="col-md-3">
                        <label class="form-label">Password</label>
                        <input class="form-control" type="password" name="password" id="password" placeholder="Required for new / optional update">
                    </div>

                    <div class="col-md-12">
                        <div class="active-toggle-box">
                            <div>
                                <strong>CSR Account Status</strong>
                                <small>Turn off to disable this CSR account.</small>
                            </div>

                            <label class="status-switch">
                                <input type="checkbox" name="is_active" id="is_active" checked>
                                <span class="status-slider"></span>
                            </label>
                        </div>
                    </div>

                    <div class="col-md-12 d-flex gap-2 flex-wrap">
                        <button name="save_csr" class="btn btn-primary">
                            <i class="fas fa-save me-1"></i>
                            Save CSR User
                        </button>

                        <button type="button" onclick="clearForm()" class="btn btn-outline-secondary">
                            <i class="fas fa-eraser me-1"></i>
                            Clear
                        </button>
                    </div>
                </form>
            </div>
        </div>

        <div class="card mb-4">
            <div class="card-header d-flex justify-content-between align-items-center">
                <span>
                    <i class="fas fa-headset me-2" style="color: var(--admin-cyan);"></i>
                    CSR Users
                </span>

                <span class="badge bg-info">
                    <?= number_format($total_csr) ?> records
                </span>
            </div>

            <div class="card-body table-responsive">
                <table class="table table-hover align-middle">
                    <thead>
                        <tr>
                            <th>Name</th>
                            <th>Email</th>
                            <th>Role</th>
                            <th>Status</th>
                            <th>Last Login</th>
                            <th>Action</th>
                        </tr>
                    </thead>

                    <tbody>
                        <?php foreach($csrUsers as $u): ?>
                            <?php
                                $csrFullName = trim(($u['first_name'] ?? '') . ' ' . ($u['last_name'] ?? ''));
                                $csrInitials = strtoupper(substr($u['first_name'] ?? 'C', 0, 1) . substr($u['last_name'] ?? '', 0, 1));
                                if ($csrInitials === '') {
                                    $csrInitials = 'C';
                                }
                            ?>

                            <tr>
                                <td>
                                    <div class="staff-name-wrap">
                                        <span class="staff-avatar"><?= htmlspecialchars($csrInitials) ?></span>

                                        <div>
                                            <strong><?= htmlspecialchars($csrFullName ?: 'CSR Account') ?></strong><br>
                                            <small>ID #<?= (int)$u['id'] ?></small>
                                        </div>
                                    </div>
                                </td>

                                <td>
                                    <i class="fas fa-envelope me-1" style="color: var(--admin-cyan);"></i>
                                    <?= htmlspecialchars($u['email']) ?>
                                </td>

                                <td>
                                    <span class="badge bg-info"><?= htmlspecialchars(staffRoleLabel($u['role'] ?? 'csr')) ?></span>
                                </td>

                                <td>
                                    <?= $u['is_active'] 
                                        ? '<span class="badge bg-success">Active</span>' 
                                        : '<span class="badge bg-secondary">Inactive</span>' 
                                    ?>
                                </td>

                                <td><?= htmlspecialchars($u['last_login'] ?? 'Never') ?></td>

                                <td>
                                    <button 
                                        class="btn btn-sm btn-outline-primary" 
                                        onclick='editCSR(<?= json_encode($u, JSON_HEX_TAG|JSON_HEX_APOS|JSON_HEX_QUOT|JSON_HEX_AMP) ?>)'
                                    >
                                        <i class="fas fa-edit me-1"></i>
                                        Edit
                                    </button>
                                </td>
                            </tr>
                        <?php endforeach; ?>

                        <?php if(empty($csrUsers)): ?>
                            <tr>
                                <td colspan="6" class="text-center text-muted py-4">
                                    <i class="fas fa-user-slash fa-2x mb-2"></i><br>
                                    No CSR users found.
                                </td>
                            </tr>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>
        </div>

        <div class="card mb-4">
            <div class="card-header d-flex justify-content-between align-items-center flex-wrap gap-2">
                <span>
                    <i class="fas fa-people-arrows me-2" style="color: var(--admin-cyan);"></i>
                    Team Leader Assignment Board
                </span>

                <span class="badge bg-info">
                    Drag AGENT accounts into a Team Leader container
                </span>
            </div>

            <div class="card-body">
                <p class="text-muted mb-3">
                    Drag CSR agents from the unassigned list into the Team Leader container. Changes save instantly and will appear on the Team Leader dashboard.
                </p>

                <div class="team-board-grid">
                    <div>
                        <div class="d-flex justify-content-between align-items-center mb-2">
                            <h5 class="mb-0">
                                <i class="fas fa-user-clock me-2" style="color: var(--admin-cyan);"></i>
                                Unassigned AGENTS
                            </h5>
                            <span class="badge bg-secondary" id="count-unassigned"><?= count($agentsByTeam['unassigned'] ?? []) ?></span>
                        </div>

                        <div class="agent-pool assignment-dropzone" data-team-id="0" data-zone-label="unassigned">
                            <?php foreach(($agentsByTeam['unassigned'] ?? []) as $agent): ?>
                                <?php
                                    $agentName = trim(($agent['first_name'] ?? '') . ' ' . ($agent['last_name'] ?? '')) ?: 'CSR Agent';
                                    $agentInitials = strtoupper(substr($agent['first_name'] ?? 'C', 0, 1) . substr($agent['last_name'] ?? '', 0, 1));
                                    if ($agentInitials === '') $agentInitials = 'C';
                                ?>
                                <div class="agent-card" draggable="true" data-agent-id="<?= (int)$agent['id'] ?>">
                                    <div class="d-flex align-items-center gap-2">
                                        <span class="staff-avatar m-0"><?= htmlspecialchars($agentInitials) ?></span>
                                        <div>
                                            <div class="agent-card__name"><?= htmlspecialchars($agentName) ?></div>
                                            <div class="agent-card__meta"><?= htmlspecialchars($agent['email'] ?? '') ?></div>
                                            <div class="agent-card__meta">Recent login: <?= htmlspecialchars($agent['last_login'] ?? 'Never') ?></div>
                                        </div>
                                    </div>
                                    <i class="fas fa-grip-vertical text-muted"></i>
                                </div>
                            <?php endforeach; ?>
                            <?php if (empty($agentsByTeam['unassigned'])): ?>
                                <div class="team-empty">No unassigned AGENT accounts.</div>
                            <?php endif; ?>
                        </div>
                    </div>

                    <div>
                        <div class="d-flex justify-content-between align-items-center mb-2">
                            <h5 class="mb-0">
                                <i class="fas fa-users-gear me-2" style="color: var(--admin-cyan);"></i>
                                Team Leader Containers
                            </h5>
                            <span class="badge bg-primary"><?= count($teamLeaders) ?> Team Leader<?= count($teamLeaders) === 1 ? '' : 's' ?></span>
                        </div>

                        <?php if (empty($teamLeaders)): ?>
                            <div class="team-empty border rounded-4">No TEAM LEADER accounts yet. Create a CSR user with role TEAM LEADER first.</div>
                        <?php endif; ?>

                        <div class="team-leader-grid">
                            <?php foreach($teamLeaders as $leaderRow): ?>
                                <?php
                                    $teamId = (int)($leaderRow['team_id'] ?? 0);
                                    $leaderName = trim(($leaderRow['first_name'] ?? '') . ' ' . ($leaderRow['last_name'] ?? '')) ?: 'Team Leader';
                                    $leaderInitials = strtoupper(substr($leaderRow['first_name'] ?? 'T', 0, 1) . substr($leaderRow['last_name'] ?? 'L', 0, 1));
                                    $teamAgents = $agentsByTeam[$teamId] ?? [];
                                ?>
                                <div class="team-leader-card">
                                    <div class="team-leader-card__header">
                                        <div class="d-flex align-items-center gap-2">
                                            <span class="staff-avatar m-0"><?= htmlspecialchars($leaderInitials) ?></span>
                                            <div>
                                                <h5 class="mb-0">Team <?= htmlspecialchars($leaderName) ?></h5>
                                                <div class="agent-card__meta"><?= htmlspecialchars($leaderRow['email'] ?? '') ?></div>
                                                <div class="agent-card__meta">Leader login: <?= htmlspecialchars($leaderRow['last_login'] ?? 'Never') ?></div>
                                            </div>
                                        </div>
                                        <span class="badge bg-info assignment-count"><?= count($teamAgents) ?> Agent<?= count($teamAgents) === 1 ? '' : 's' ?></span>
                                    </div>

                                    <div class="team-dropzone assignment-dropzone" data-team-id="<?= $teamId ?>" data-zone-label="team">
                                        <?php foreach($teamAgents as $agent): ?>
                                            <?php
                                                $agentName = trim(($agent['first_name'] ?? '') . ' ' . ($agent['last_name'] ?? '')) ?: 'CSR Agent';
                                                $agentInitials = strtoupper(substr($agent['first_name'] ?? 'C', 0, 1) . substr($agent['last_name'] ?? '', 0, 1));
                                                if ($agentInitials === '') $agentInitials = 'C';
                                            ?>
                                            <div class="agent-card" draggable="true" data-agent-id="<?= (int)$agent['id'] ?>">
                                                <div class="d-flex align-items-center gap-2">
                                                    <span class="staff-avatar m-0"><?= htmlspecialchars($agentInitials) ?></span>
                                                    <div>
                                                        <div class="agent-card__name"><?= htmlspecialchars($agentName) ?></div>
                                                        <div class="agent-card__meta"><?= htmlspecialchars($agent['email'] ?? '') ?></div>
                                                        <div class="agent-card__meta">Recent login: <?= htmlspecialchars($agent['last_login'] ?? 'Never') ?></div>
                                                    </div>
                                                </div>
                                                <i class="fas fa-grip-vertical text-muted"></i>
                                            </div>
                                        <?php endforeach; ?>

                                        <?php if (empty($teamAgents)): ?>
                                            <div class="team-empty">Drop AGENT accounts here.</div>
                                        <?php endif; ?>
                                    </div>
                                </div>
                            <?php endforeach; ?>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <div class="assignment-toast" id="assignmentToast"></div>

        <div class="card mb-4" id="technicianFormCard">
            <div class="card-header">
                <i class="fas fa-user-plus me-2" style="color: var(--admin-cyan);"></i>
                Add / Update Technician
            </div>

            <div class="card-body">
                <form method="POST" class="row g-3">
                    <input type="hidden" name="technician_id" id="technician_id">

                    <div class="col-md-3">
                        <label class="form-label">First Name</label>
                        <input class="form-control" name="tech_first_name" id="tech_first_name" required>
                    </div>

                    <div class="col-md-3">
                        <label class="form-label">Last Name</label>
                        <input class="form-control" name="tech_last_name" id="tech_last_name" required>
                    </div>

                    <div class="col-md-3">
                        <label class="form-label">Email</label>
                        <input class="form-control" type="email" name="tech_email" id="tech_email" required>
                    </div>

                    <div class="col-md-3">
                        <label class="form-label">Phone</label>
                        <input class="form-control" name="tech_phone" id="tech_phone" required>
                    </div>

                    <div class="col-md-3">
                        <label class="form-label">Password</label>
                        <input class="form-control" type="password" name="tech_password" id="tech_password" placeholder="Required for new / optional update">
                    </div>

                    <div class="col-md-3">
                        <label class="form-label">Employee ID</label>
                        <input class="form-control" name="tech_employee_id" id="tech_employee_id">
                    </div>

                    <div class="col-md-3">
                        <label class="form-label">City</label>
                        <select class="form-select" name="tech_city_id" id="tech_city_id">
                            <option value="">Select City</option>
                            <?php foreach($cities as $city): ?>
                                <option value="<?= (int)$city['id'] ?>"><?= htmlspecialchars($city['city_name']) ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>

                    <div class="col-md-3">
                        <label class="form-label">Status</label>
                        <select class="form-select" name="tech_status_id" id="tech_status_id">
                            <?php foreach($technicianStatuses as $status): ?>
                                <option value="<?= (int)$status['id'] ?>"><?= htmlspecialchars($status['status_name']) ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>

                    <div class="col-md-6">
                        <label class="form-label">Address</label>
                        <textarea class="form-control" name="tech_address" id="tech_address" rows="2"></textarea>
                    </div>

                    <div class="col-md-6">
                        <label class="form-label">Specialization</label>
                        <textarea class="form-control" name="tech_specialization" id="tech_specialization" rows="2" placeholder="Refrigerator&#10;Washer&#10;Air Conditioner"></textarea>
                    </div>

                    <div class="col-md-12">
                        <div class="active-toggle-box">
                            <div>
                                <strong>Technician Account Status</strong>
                                <small>Turn on to make this technician active for assignment.</small>
                            </div>

                            <label class="status-switch">
                                <input type="checkbox" name="tech_is_active" id="tech_is_active" checked>
                                <span class="status-slider"></span>
                            </label>
                        </div>
                    </div>

                    <div class="col-md-12 d-flex gap-2 flex-wrap">
                        <button name="save_technician" class="btn btn-primary">
                            <i class="fas fa-save me-1"></i>
                            Save Technician
                        </button>

                        <button type="button" onclick="clearTechForm()" class="btn btn-outline-secondary">
                            <i class="fas fa-eraser me-1"></i>
                            Clear
                        </button>
                    </div>
                </form>
            </div>
        </div>

        <div class="card">
            <div class="card-header d-flex justify-content-between align-items-center">
                <span>
                    <i class="fas fa-tools me-2" style="color: var(--admin-cyan);"></i>
                    Technicians
                </span>

                <span class="badge bg-info">
                    <?= number_format($total_techs) ?> records
                </span>
            </div>

            <div class="card-body">
                <p class="text-muted mb-3">
                    Technician creation and profile updates are now handled here in Admin Staff Management. CSR can still monitor and assign technicians, but cannot add or edit technician profiles.
                </p>

                <div class="table-responsive">
                    <table class="table table-hover align-middle">
                        <thead>
                            <tr>
                                <th>Name</th>
                                <th>Email</th>
                                <th>Phone</th>
                                <th>City</th>
                                <th>Status</th>
                                <th>Action</th>
                            </tr>
                        </thead>

                        <tbody>
                            <?php foreach($techs as $t): ?>
                                <?php
                                    $techFullName = trim(($t['first_name'] ?? '') . ' ' . ($t['last_name'] ?? ''));
                                    $techInitials = strtoupper(substr($t['first_name'] ?? 'T', 0, 1) . substr($t['last_name'] ?? '', 0, 1));
                                    if ($techInitials === '') {
                                        $techInitials = 'T';
                                    }
                                ?>

                                <tr>
                                    <td>
                                        <div class="staff-name-wrap">
                                            <span class="staff-avatar"><?= htmlspecialchars($techInitials) ?></span>

                                            <div>
                                                <strong><?= htmlspecialchars($techFullName ?: 'Technician') ?></strong><br>
                                                <small>ID #<?= (int)$t['id'] ?></small>
                                            </div>
                                        </div>
                                    </td>

                                    <td>
                                        <i class="fas fa-envelope me-1" style="color: var(--admin-cyan);"></i>
                                        <?= htmlspecialchars($t['email'] ?? '') ?>
                                    </td>

                                    <td>
                                        <i class="fas fa-phone me-1" style="color: var(--admin-cyan);"></i>
                                        <?= htmlspecialchars($t['phone_number'] ?? '') ?>
                                    </td>

                                    <td>
                                        <i class="fas fa-city me-1" style="color: var(--admin-cyan);"></i>
                                        <?= htmlspecialchars($t['city_name'] ?? 'N/A') ?>
                                    </td>

                                    <td>
                                        <span class="badge bg-info"><?= htmlspecialchars($t['status_name'] ?? 'Available') ?></span>

                                        <?= !isset($t['is_active']) || $t['is_active'] 
                                            ? '<span class="badge bg-success ms-1">Active</span>' 
                                            : '<span class="badge bg-secondary ms-1">Inactive</span>' 
                                        ?>
                                    </td>

                                    <td>
                                        <button 
                                            class="btn btn-sm btn-outline-primary" 
                                            onclick='editTechnician(<?= json_encode($t, JSON_HEX_TAG|JSON_HEX_APOS|JSON_HEX_QUOT|JSON_HEX_AMP) ?>)'
                                        >
                                            <i class="fas fa-edit me-1"></i>
                                            Edit
                                        </button>
                                    </td>
                                </tr>
                            <?php endforeach; ?>

                            <?php if(empty($techs)): ?>
                                <tr>
                                    <td colspan="6" class="text-center text-muted py-4">
                                        <i class="fas fa-tools fa-2x mb-2"></i><br>
                                        No technicians found.
                                    </td>
                                </tr>
                            <?php endif; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </main>

    <script>

        let draggedAgentCard = null;

        function showAssignmentToast(message, isError = false) {
            const toast = document.getElementById('assignmentToast');
            if (!toast) return;
            toast.textContent = message;
            toast.style.borderColor = isError ? 'rgba(244, 63, 94, 0.65)' : 'rgba(56, 189, 248, 0.42)';
            toast.classList.add('show');
            setTimeout(() => toast.classList.remove('show'), 2600);
        }

        function updateDropzoneEmptyState(zone) {
            if (!zone) return;
            const cards = zone.querySelectorAll('.agent-card');
            const empty = zone.querySelector('.team-empty');
            if (zone.dataset.teamId === '0') {
                const unassignedCount = document.getElementById('count-unassigned');
                if (unassignedCount) unassignedCount.textContent = cards.length;
            }
            if (cards.length > 0 && empty) {
                empty.remove();
            }
            if (cards.length === 0 && !empty) {
                const div = document.createElement('div');
                div.className = 'team-empty';
                div.textContent = zone.dataset.teamId === '0' ? 'No unassigned AGENT accounts.' : 'Drop AGENT accounts here.';
                zone.appendChild(div);
            }
        }

        function updateTeamCount(zone) {
            const teamCard = zone.closest('.team-leader-card');
            if (!teamCard) return;
            const countBadge = teamCard.querySelector('.assignment-count');
            if (!countBadge) return;
            const count = zone.querySelectorAll('.agent-card').length;
            countBadge.textContent = count + ' Agent' + (count === 1 ? '' : 's');
        }

        function bindAgentCards() {
            document.querySelectorAll('.agent-card').forEach(card => {
                card.addEventListener('dragstart', function(e) {
                    draggedAgentCard = this;
                    this.classList.add('dragging');
                    e.dataTransfer.effectAllowed = 'move';
                    e.dataTransfer.setData('text/plain', this.dataset.agentId || '');
                });

                card.addEventListener('dragend', function() {
                    this.classList.remove('dragging');
                    draggedAgentCard = null;
                });
            });
        }

        function bindAssignmentZones() {
            document.querySelectorAll('.assignment-dropzone').forEach(zone => {
                zone.addEventListener('dragover', function(e) {
                    e.preventDefault();
                    this.classList.add('drag-over');
                });

                zone.addEventListener('dragleave', function() {
                    this.classList.remove('drag-over');
                });

                zone.addEventListener('drop', async function(e) {
                    e.preventDefault();
                    this.classList.remove('drag-over');

                    const agentCard = draggedAgentCard;
                    if (!agentCard) return;

                    const oldZone = agentCard.closest('.assignment-dropzone');
                    const agentId = agentCard.dataset.agentId;
                    const teamId = this.dataset.teamId || '0';

                    this.appendChild(agentCard);
                    updateDropzoneEmptyState(oldZone);
                    updateDropzoneEmptyState(this);
                    updateTeamCount(oldZone);
                    updateTeamCount(this);

                    const formData = new FormData();
                    formData.append('action', 'assign_agent_team');
                    formData.append('agent_id', agentId);
                    formData.append('team_id', teamId);

                    try {
                        const response = await fetch('staff.php', {
                            method: 'POST',
                            body: formData,
                            credentials: 'same-origin'
                        });
                        const result = await response.json();

                        if (!response.ok || !result.success) {
                            throw new Error(result.message || 'Assignment failed.');
                        }

                        showAssignmentToast(result.message || 'Team assignment saved.');
                    } catch (err) {
                        if (oldZone) {
                            oldZone.appendChild(agentCard);
                            updateDropzoneEmptyState(oldZone);
                            updateDropzoneEmptyState(this);
                            updateTeamCount(oldZone);
                            updateTeamCount(this);
                        }
                        showAssignmentToast(err.message || 'Could not save assignment.', true);
                    }
                });
            });
        }

        bindAgentCards();
        bindAssignmentZones();

        function editCSR(u) {
            document.getElementById('csr_id').value = u.id || '';
            document.getElementById('first_name').value = u.first_name || '';
            document.getElementById('last_name').value = u.last_name || '';
            document.getElementById('email').value = u.email || '';
            document.getElementById('role').value = u.role || 'csr';
            document.getElementById('password').value = '';
            document.getElementById('is_active').checked = Number(u.is_active) === 1;

            window.scrollTo({
                top: 0,
                behavior: 'smooth'
            });
        }

        function clearForm() {
            document.getElementById('csr_id').value = '';
            document.getElementById('first_name').value = '';
            document.getElementById('last_name').value = '';
            document.getElementById('email').value = '';
            document.getElementById('role').value = 'csr';
            document.getElementById('password').value = '';
            document.getElementById('is_active').checked = true;
        }

        function editTechnician(t) {
            document.getElementById('technician_id').value = t.id || '';
            document.getElementById('tech_first_name').value = t.first_name || '';
            document.getElementById('tech_last_name').value = t.last_name || '';
            document.getElementById('tech_email').value = t.email || '';
            document.getElementById('tech_phone').value = t.phone_number || '';
            document.getElementById('tech_password').value = '';
            document.getElementById('tech_employee_id').value = t.employee_id || '';
            document.getElementById('tech_city_id').value = t.city_id || '';
            document.getElementById('tech_status_id').value = t.status_id || '1';
            document.getElementById('tech_address').value = t.address || '';
            document.getElementById('tech_specialization').value = t.specialization || '';

            const techActiveToggle = document.getElementById('tech_is_active');
            techActiveToggle.checked = Number(t.is_active) === 1;

            document.getElementById('technicianFormCard').scrollIntoView({
                behavior: 'smooth',
                block: 'start'
            });
        }

        function clearTechForm() {
            document.getElementById('technician_id').value = '';
            document.getElementById('tech_first_name').value = '';
            document.getElementById('tech_last_name').value = '';
            document.getElementById('tech_email').value = '';
            document.getElementById('tech_phone').value = '';
            document.getElementById('tech_password').value = '';
            document.getElementById('tech_employee_id').value = '';
            document.getElementById('tech_city_id').value = '';
            document.getElementById('tech_status_id').value = '1';
            document.getElementById('tech_address').value = '';
            document.getElementById('tech_specialization').value = '';
            document.getElementById('tech_is_active').checked = true;
        }
    </script>
</body>
</html>