<?php
require_once 'auth.php';
ensureAdminAuth();
require_once '../config/database.php';
require_once '../includes/app_helpers.php';

$database = new Database();
$db = $database->getConnection();
ensureCsrTeamTables($db);
$message = '';
$error = '';

try {
    if ($_SERVER['REQUEST_METHOD'] === 'POST') {
        if (isset($_POST['save_team'])) {
            $teamId = (int)($_POST['team_id'] ?? 0);
            $teamName = trim($_POST['team_name'] ?? '');
            $managerId = (int)($_POST['manager_id'] ?? 0);
            $isActive = ((int)($_POST['is_active'] ?? 1) === 1) ? 1 : 0;
            $members = array_values(array_unique(array_filter(array_map('intval', $_POST['members'] ?? []))));

            if ($teamName === '' || $managerId <= 0) {
                throw new Exception('Team name and Team Leader are required.');
            }
            if (count($members) > 5) {
                throw new Exception('A Team Leader can only have up to 5 regular CSRs for now.');
            }

            $check = $db->prepare("SELECT id FROM csr_users WHERE id = :id AND is_active = 1 AND COALESCE(role, 'csr') = 'team_leader' LIMIT 1");
            $check->execute([':id' => $managerId]);
            if (!$check->fetchColumn()) {
                throw new Exception('Selected Team Leader must be an active Team Leader account.');
            }

            $db->beginTransaction();
            if ($teamId > 0) {
                $stmt = $db->prepare("UPDATE csr_teams SET team_name = :team_name, manager_id = :manager_id, is_active = :is_active WHERE id = :id");
                $stmt->execute([':team_name' => $teamName, ':manager_id' => $managerId, ':is_active' => $isActive, ':id' => $teamId]);
                $db->prepare("DELETE FROM csr_team_members WHERE team_id = :team_id")->execute([':team_id' => $teamId]);
                $message = 'Team updated successfully.';
            } else {
                $stmt = $db->prepare("INSERT INTO csr_teams (team_name, manager_id, is_active) VALUES (:team_name, :manager_id, :is_active)");
                $stmt->execute([':team_name' => $teamName, ':manager_id' => $managerId, ':is_active' => $isActive]);
                $teamId = (int)$db->lastInsertId();
                $message = 'Team created successfully.';
            }

            if ($members) {
                $insert = $db->prepare("INSERT IGNORE INTO csr_team_members (team_id, csr_id) VALUES (:team_id, :csr_id)");
                foreach ($members as $csrId) {
                    $insert->execute([':team_id' => $teamId, ':csr_id' => $csrId]);
                }
            }
            $db->commit();
        }

        if (isset($_POST['delete_team'])) {
            $teamId = (int)($_POST['team_id'] ?? 0);
            $db->prepare("DELETE FROM csr_team_members WHERE team_id = :team_id")->execute([':team_id' => $teamId]);
            $db->prepare("DELETE FROM csr_teams WHERE id = :id")->execute([':id' => $teamId]);
            $message = 'Team deleted successfully.';
        }
    }
} catch (Exception $e) {
    if ($db->inTransaction()) $db->rollBack();
    $error = $e->getMessage();
}

$managers = $db->query("SELECT id, CONCAT(first_name, ' ', last_name) AS name, email FROM csr_users WHERE is_active = 1 AND COALESCE(role, 'csr') = 'team_leader' ORDER BY first_name, last_name")->fetchAll(PDO::FETCH_ASSOC);
$regularCsrs = $db->query("SELECT id, CONCAT(first_name, ' ', last_name) AS name, email FROM csr_users WHERE is_active = 1 AND COALESCE(role, 'csr') = 'csr' ORDER BY first_name, last_name")->fetchAll(PDO::FETCH_ASSOC);
$teams = $db->query("SELECT t.*, CONCAT(m.first_name, ' ', m.last_name) AS manager_name, m.email AS manager_email,
                           (SELECT COUNT(*) FROM csr_team_members tm WHERE tm.team_id = t.id) AS member_count
                    FROM csr_teams t
                    LEFT JOIN csr_users m ON m.id = t.manager_id
                    ORDER BY t.is_active DESC, t.team_name ASC")->fetchAll(PDO::FETCH_ASSOC);
$teamMembers = [];
foreach ($db->query("SELECT tm.team_id, cu.id, CONCAT(cu.first_name, ' ', cu.last_name) AS name, cu.email FROM csr_team_members tm JOIN csr_users cu ON cu.id = tm.csr_id ORDER BY cu.first_name, cu.last_name")->fetchAll(PDO::FETCH_ASSOC) as $row) {
    $teamMembers[(int)$row['team_id']][] = $row;
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>CSR Teams - 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">
<link rel="stylesheet" href="../assets/theme.css">
<link rel="stylesheet" href="../assets/portal-dark.css">
<style>
:root{--bg1:#080240;--bg2:#093349;--card1:#17295e;--card2:#102448;--cyan:#17bdd4;--muted:#aebbd4;--soft:#d7e7ff}
body{background:linear-gradient(135deg,var(--bg1),var(--bg2)) fixed!important;color:#fff!important;font-family:Montserrat,sans-serif!important}.sidebar{min-height:100vh;background:rgba(8,2,64,.96);position:fixed;width:250px;border-right:1px solid rgba(96,165,250,.18)}.sidebar-header{padding:24px 18px;text-align:center;border-bottom:1px solid rgba(96,165,250,.18)}.sidebar-header i{color:var(--cyan)}.sidebar-header h4{font-size:1.1rem;font-weight:900}.sidebar-menu{padding:20px 0}.sidebar-menu a{color:#b9dcff!important;padding:13px 20px;display:block;text-decoration:none;border-left:4px solid transparent;font-weight:700;font-size:14px}.sidebar-menu a:hover,.sidebar-menu a.active{background:rgba(56,189,248,.12);color:#fff!important;border-left-color:var(--cyan)}.sidebar-menu i{margin-right:10px;width:20px}.main-content{margin-left:250px;padding:24px}.panel,.team-card{background:linear-gradient(135deg,var(--card1),var(--card2))!important;border:1px solid rgba(56,189,248,.24)!important;border-radius:18px!important;box-shadow:0 10px 24px rgba(0,0,0,.24);padding:20px;margin-bottom:20px}.text-muted{color:var(--muted)!important}.form-control,.form-select{background:rgba(8,20,48,.72)!important;border:1px solid rgba(96,165,250,.34)!important;color:#fff!important;border-radius:10px}.form-select option{background:#102448;color:#fff}.btn-main{background:linear-gradient(135deg,#1d9bf0,#17bdd4);border:0;border-radius:10px;color:#fff;font-weight:900;padding:10px 16px}.table{color:#fff!important}.table th{background:rgba(8,20,48,.58)!important;color:#fff!important;border-color:rgba(96,165,250,.22)!important}.table td{background:rgba(8,20,48,.18)!important;color:var(--soft)!important;border-color:rgba(96,165,250,.20)!important}.badge{border-radius:999px;font-weight:900}.member-pill{display:inline-flex;margin:3px;padding:5px 9px;border:1px solid rgba(56,189,248,.3);border-radius:999px;background:rgba(56,189,248,.12);color:#dff7ff;font-size:12px;font-weight:800}@media(max-width:768px){.sidebar{position:relative;width:100%;min-height:auto}.main-content{margin-left:0;padding:14px}.table{min-width:900px}}

/* Dropdown + dark text fixes */
.panel label,
.panel .form-label,
.panel h1,
.panel h2,
.panel h3,
.panel h4,
.panel h5,
.panel h6,
.panel strong,
.team-card label,
.team-card strong {
    color: #ffffff !important;
}

.panel small,
.panel .text-muted,
.table small,
.table .text-muted {
    color: var(--muted) !important;
}

.form-control,
.form-select,
select.form-select,
select.form-select[multiple],
textarea.form-control {
    background-color: rgba(8, 20, 48, .72) !important;
    color: #ffffff !important;
    border: 1px solid rgba(96, 165, 250, .34) !important;
    border-radius: 10px !important;
}

.form-control:focus,
.form-select:focus,
select.form-select:focus,
select.form-select[multiple]:focus {
    background-color: rgba(8, 20, 48, .88) !important;
    color: #ffffff !important;
    border-color: rgba(23, 189, 212, .75) !important;
    box-shadow: 0 0 0 .18rem rgba(23, 189, 212, .18) !important;
}

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

select.form-select option:checked,
select.form-select option:hover,
select.form-select option:focus,
.form-select option:checked,
.form-select option:hover,
.form-select option:focus,
select.form-select[multiple] option:checked,
select.form-select[multiple] option:hover,
select.form-select[multiple] option:focus {
    background: linear-gradient(135deg, #1d9bf0, #17bdd4) !important;
    background-color: #17bdd4 !important;
    color: #ffffff !important;
}

select.form-select[multiple] option {
    padding: 7px 10px;
}

select.form-select[multiple] option:checked {
    box-shadow: 0 0 0 999px #17bdd4 inset !important;
    -webkit-text-fill-color: #ffffff !important;
}

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

</style>
    <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="panel"><h2><i class="fas fa-people-group me-2" style="color:var(--cyan)"></i>CSR Teams</h2><p class="text-muted mb-0">Create Team Leader groups. Each Team Leader can have up to 5 regular CSRs. Incoming chats are routed to Team Leaders first.</p></div>
<?php if($message): ?><div class="alert alert-success"><?=h($message)?></div><?php endif; ?><?php if($error): ?><div class="alert alert-danger"><?=h($error)?></div><?php endif; ?>
<div class="panel"><h4 class="fw-bold mb-3">Add / Update Team</h4><form method="POST" class="row g-3"><input type="hidden" name="team_id" id="team_id"><div class="col-md-4"><label class="form-label fw-bold text-white">Team Name</label><input class="form-control" name="team_name" id="team_name" placeholder="Team Deemo" required></div><div class="col-md-4"><label class="form-label fw-bold text-white">Team Leader / CSR Manager</label><select class="form-select" name="manager_id" id="manager_id" required><option value="">Select Manager</option><?php foreach($managers as $m): ?><option value="<?=(int)$m['id']?>"><?=h($m['name'])?> - <?=h($m['email'])?></option><?php endforeach; ?></select></div><div class="col-md-4"><label class="form-label fw-bold text-white">Status</label><select class="form-select" name="is_active" id="is_active"><option value="1">Active</option><option value="0">Inactive</option></select></div><div class="col-12"><label class="form-label fw-bold text-white">Regular CSRs under this Team Leader <span class="text-muted">(maximum 5)</span></label><select class="form-select" name="members[]" id="members" multiple size="6"><?php foreach($regularCsrs as $c): ?><option value="<?=(int)$c['id']?>"><?=h($c['name'])?> - <?=h($c['email'])?></option><?php endforeach; ?></select></div><div class="col-12 d-flex gap-2"><button class="btn-main" name="save_team"><i class="fas fa-save me-1"></i>Save Team</button><button type="button" class="btn btn-outline-info" onclick="clearTeamForm()">Clear</button></div></form></div>
<div class="panel"><h4 class="fw-bold mb-3">Team List</h4><div class="table-responsive"><table class="table table-hover align-middle"><thead><tr><th>Team</th><th>Team Leader</th><th>Members</th><th>Status</th><th>Action</th></tr></thead><tbody><?php foreach($teams as $t): $members=$teamMembers[(int)$t['id']]??[]; ?><tr><td><strong><?=h($t['team_name'])?></strong><br><small class="text-muted">Last assigned: <?=h($t['last_assigned_at'] ?: 'Never')?></small></td><td><?=h($t['manager_name'] ?: 'No manager')?><br><small class="text-muted"><?=h($t['manager_email'] ?? '')?></small></td><td><?php if(!$members): ?><span class="text-muted">No members yet</span><?php else: foreach($members as $m): ?><span class="member-pill"><?=h($m['name'])?></span><?php endforeach; endif; ?><br><small class="text-muted"><?=count($members)?> / 5 CSR members</small></td><td><?=$t['is_active']?'<span class="badge bg-success">Active</span>':'<span class="badge bg-secondary">Inactive</span>'?></td><td><button class="btn btn-sm btn-outline-info" onclick='editTeam(<?=json_encode(['id'=>(int)$t['id'],'team_name'=>$t['team_name'],'manager_id'=>(int)$t['manager_id'],'is_active'=>(int)$t['is_active'],'members'=>array_map(fn($x)=>(int)$x['id'],$members)], JSON_HEX_TAG|JSON_HEX_APOS|JSON_HEX_QUOT|JSON_HEX_AMP)?>)'><i class="fas fa-edit me-1"></i>Edit</button><form method="POST" class="d-inline" onsubmit="return confirm('Delete this team?')"><input type="hidden" name="team_id" value="<?=(int)$t['id']?>"><button class="btn btn-sm btn-outline-danger" name="delete_team"><i class="fas fa-trash"></i></button></form></td></tr><?php endforeach; ?><?php if(!$teams): ?><tr><td colspan="5" class="text-center text-muted py-4">No teams created yet.</td></tr><?php endif; ?></tbody></table></div></div>
</main>
<script>
function editTeam(team){document.getElementById('team_id').value=team.id||'';document.getElementById('team_name').value=team.team_name||'';document.getElementById('manager_id').value=team.manager_id||'';document.getElementById('is_active').value=String(team.is_active??1);const members=document.getElementById('members');[...members.options].forEach(o=>{o.selected=(team.members||[]).map(Number).includes(Number(o.value));});window.scrollTo({top:0,behavior:'smooth'});}function clearTeamForm(){document.getElementById('team_id').value='';document.getElementById('team_name').value='';document.getElementById('manager_id').value='';document.getElementById('is_active').value='1';[...document.getElementById('members').options].forEach(o=>o.selected=false);}
</script>
</body>
</html>
