<?php
session_start();

if (!isset($_SESSION['csr_id'])) {
    header('Location: ../login.php');
    exit;
}

$title = 'CSR Ranking';

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

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

ensureOperationalTables($db);
ensureAnnouncementTables($db);
ensureCsrTeamTables($db);

$managerId = (int)$_SESSION['csr_id'];

$currentRoleForRanking = getCsrRoleForReport($db, $managerId);
if (!in_array($currentRoleForRanking, ['team_leader','csr_manager'], true)) {
    http_response_code(403);

    echo '<!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Access Denied</title>
        <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
        <style>
            body {
                min-height: 100vh;
                display: flex;
                align-items: center;
                justify-content: center;
                background: linear-gradient(135deg,#080240,#093349);
                font-family: Montserrat, Arial, sans-serif;
                color: #fff;
            }

            .box {
                max-width: 520px;
                background: linear-gradient(135deg,#17295e,#102448);
                border: 1px solid rgba(56,189,248,.28);
                border-radius: 18px;
                padding: 26px;
                text-align: center;
            }

            .btn {
                background: linear-gradient(135deg,#1d9bf0,#17bdd4);
                border: 0;
                color: #fff;
                font-weight: 800;
                border-radius: 10px;
                padding: 10px 16px;
                text-decoration: none;
            }
        </style>
        <link rel="stylesheet" href="../assets/ushs-global-theme.css">
</head>
    <body>
        <div class="box">
            <h2>Access Denied</h2>
            <p class="mb-4">CSR Ranking is only available for CSR Managers / Team Leaders.</p>
            <a class="btn" href="dashboard.php">Back to Dashboard</a>
        </div>
    </body>
    </html>';

    exit;
}

$start = $_GET['start_date'] ?? date('Y-m-01');
$end = $_GET['end_date'] ?? date('Y-m-d');

if (!preg_match('/^\d{4}-\d{2}-\d{2}$/', $start)) {
    $start = date('Y-m-01');
}

if (!preg_match('/^\d{4}-\d{2}-\d{2}$/', $end)) {
    $end = date('Y-m-d');
}

if ($currentRoleForRanking === 'csr_manager') {
    $teamStmt = $db->query("SELECT id, team_name FROM csr_teams WHERE is_active = 1 ORDER BY team_name ASC");
    $managerTeams = $teamStmt->fetchAll(PDO::FETCH_ASSOC);
} else {
    $teamStmt = $db->prepare("SELECT id, team_name FROM csr_teams WHERE manager_id = :manager_id AND is_active = 1 ORDER BY team_name ASC");
    $teamStmt->execute([':manager_id' => $managerId]);
    $managerTeams = $teamStmt->fetchAll(PDO::FETCH_ASSOC);
}
$allowedTeamIds = array_map('intval', array_column($managerTeams, 'id'));

$selectedTeamId = isset($_GET['team_id']) ? (int)$_GET['team_id'] : 0;

if ($selectedTeamId > 0 && !in_array($selectedTeamId, $allowedTeamIds, true)) {
    $selectedTeamId = 0;
}

if (count($managerTeams) === 1) {
    $selectedTeamId = (int)$managerTeams[0]['id'];
}

$whereTeam = $currentRoleForRanking === 'csr_manager'
    ? "ct.is_active = 1"
    : "ct.manager_id = :manager_id AND ct.is_active = 1";

$params = [
    ':s1' => $start,
    ':e1' => $end,
    ':s2' => $start,
    ':e2' => $end,
    ':s3' => $start,
    ':e3' => $end,
    ':s4' => $start,
    ':e4' => $end,
    ':s5' => $start,
    ':e5' => $end
];
if ($currentRoleForRanking !== 'csr_manager') {
    $params[':manager_id'] = $managerId;
}

if ($selectedTeamId > 0) {
    $whereTeam .= " AND ct.id = :selected_team_id";
    $params[':selected_team_id'] = $selectedTeamId;
}

$rankings = [];

if (!empty($managerTeams)) {
    $stmt = $db->prepare("
        SELECT 
            cu.id,
            CONCAT(cu.first_name, ' ', cu.last_name) AS csr_name,
            COALESCE(cu.role, 'csr') AS role,
            GROUP_CONCAT(DISTINCT ct.team_name ORDER BY ct.team_name SEPARATOR ', ') AS team_name,

            COUNT(DISTINCT handled.request_id) AS handled_tickets,
            COUNT(DISTINCT completed.request_id) AS completed_tickets,
            COUNT(DISTINCT canceled.request_id) AS canceled_tickets,

            (
                COUNT(DISTINCT completed.request_id) * 3 
                + COUNT(DISTINCT handled.request_id)
            ) AS score

        FROM csr_users cu

        INNER JOIN csr_team_members ctm 
            ON ctm.csr_id = cu.id

        INNER JOIN csr_teams ct 
            ON ct.id = ctm.team_id

        LEFT JOIN (
            SELECT 
                user_id AS csr_id, 
                request_id 
            FROM request_logs 
            WHERE user_role IN ('csr','team_leader','csr_manager') 
              AND DATE(created_at) BETWEEN :s1 AND :e1

            UNION 

            SELECT 
                csr_id, 
                request_id 
            FROM csr_activity 
            WHERE DATE(created_at) BETWEEN :s2 AND :e2

            UNION 

            SELECT 
                csr_id, 
                request_id 
            FROM csr_request_locks 
            WHERE DATE(locked_at) BETWEEN :s3 AND :e3
        ) handled 
            ON handled.csr_id = cu.id

        LEFT JOIN request_logs completed 
            ON completed.user_id = cu.id 
           AND completed.user_role IN ('csr','team_leader','csr_manager') 
           AND completed.action = 'status_change' 
           AND completed.new_value = '4' 
           AND DATE(completed.created_at) BETWEEN :s4 AND :e4

        LEFT JOIN request_logs canceled 
            ON canceled.user_id = cu.id 
           AND canceled.user_role IN ('csr','team_leader','csr_manager') 
           AND canceled.action = 'status_change' 
           AND canceled.new_value = '5' 
           AND DATE(canceled.created_at) BETWEEN :s5 AND :e5

        WHERE 
            cu.is_active = 1
            AND $whereTeam

        GROUP BY 
            cu.id,
            cu.first_name,
            cu.last_name,
            cu.role

        ORDER BY 
            score DESC,
            handled_tickets DESC,
            completed_tickets DESC,
            csr_name ASC
    ");

    $stmt->execute($params);
    $rankings = $stmt->fetchAll(PDO::FETCH_ASSOC);
}

ob_start();
?>

<style>
    .ranking-shell {
        display: grid;
        gap: 16px;
    }

    .ranking-card {
        background: linear-gradient(135deg,#17295e,#102448);
        border: 1px solid rgba(56,189,248,.24);
        border-radius: 16px;
        padding: 16px;
        color: #fff;
        box-shadow:
            0 10px 24px rgba(0, 0, 0, 0.22),
            inset 0 0 0 1px rgba(255, 255, 255, 0.025);
    }

    .ranking-card h2,
    .ranking-card h4 {
        font-weight: 900;
        color: #ffffff !important;
    }

    .text-muted {
        color: #aebbd4 !important;
    }

    .filter-card {
        display: grid;
        grid-template-columns: 1fr 1fr 1fr auto;
        gap: 12px;
        align-items: end;
    }

    .form-label {
        color: #ffffff !important;
        font-weight: 800 !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 !important;
        min-height: 42px;
    }

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

    .btn-main {
        background: linear-gradient(135deg,#1d9bf0,#17bdd4);
        border: none;
        border-radius: 10px;
        color: #fff;
        font-weight: 900;
        padding: 10px 16px;
        min-height: 42px;
    }

    .team-info {
        background: rgba(8,20,48,.45);
        border: 1px solid rgba(96,165,250,.24);
        color: #d7e7ff;
        border-radius: 12px;
        padding: 12px 14px;
        font-weight: 700;
    }

    .team-info i {
        color: #17bdd4;
    }

    .ranking-table {
        width: 100%;
        color: #fff;
    }

    .ranking-table th {
        background: rgba(8,20,48,.58);
        padding: 12px;
        border-bottom: 1px solid rgba(96,165,250,.22);
        color: #ffffff;
        white-space: nowrap;
    }

    .ranking-table td {
        padding: 12px;
        border-bottom: 1px solid rgba(96,165,250,.20);
        color: #d7e7ff;
        vertical-align: middle;
    }

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

    .rank-badge {
        display: inline-flex;
        width: 34px;
        height: 34px;
        align-items: center;
        justify-content: center;
        border-radius: 50%;
        background: linear-gradient(135deg,#1d9bf0,#17bdd4);
        font-weight: 900;
        color: #ffffff;
    }

    .mine-row td {
        background: rgba(23,189,212,.10) !important;
    }

    .badge-pill {
        border-radius: 999px;
        background: rgba(56,189,248,.18);
        border: 1px solid rgba(56,189,248,.34);
        color: #dff7ff;
        padding: 5px 10px;
        font-weight: 900;
        display: inline-flex;
        align-items: center;
        gap: 4px;
    }

    .empty-state {
        text-align: center;
        color: #aebbd4;
        padding: 28px;
        font-weight: 700;
    }

    @media(max-width: 900px) {
        .filter-card {
            grid-template-columns: 1fr;
        }

        .ranking-table {
            min-width: 820px;
        }

        .table-wrap {
            overflow-x: auto;
        }
    }
</style>

<div class="ranking-shell">
    <div class="ranking-card">
        <h2>
            <i class="fas fa-ranking-star me-2"></i>
            Team CSR Ranking
        </h2>

        <p class="text-muted mb-0">
            Rankings are filtered to your own assigned team only.
        </p>
    </div>

    <?php if(empty($managerTeams)): ?>
        <div class="ranking-card">
            <div class="empty-state">
                <i class="fas fa-users-slash fa-2x mb-2"></i><br>
                You do not have an active team yet. Ask the admin to create a team and assign regular CSRs under you.
            </div>
        </div>
    <?php else: ?>
        <div class="ranking-card">
            <form class="filter-card" method="GET">
                <div>
                    <label class="form-label">Start Date</label>
                    <input 
                        class="form-control" 
                        type="date" 
                        name="start_date" 
                        value="<?= h($start) ?>"
                    >
                </div>

                <div>
                    <label class="form-label">End Date</label>
                    <input 
                        class="form-control" 
                        type="date" 
                        name="end_date" 
                        value="<?= h($end) ?>"
                    >
                </div>

                <div>
                    <label class="form-label">Team</label>

                    <?php if(count($managerTeams) === 1): ?>
                        <div class="team-info">
                            <i class="fas fa-users me-1"></i>
                            <?= h($managerTeams[0]['team_name']) ?>
                        </div>

                        <input 
                            type="hidden" 
                            name="team_id" 
                            value="<?= (int)$managerTeams[0]['id'] ?>"
                        >
                    <?php else: ?>
                        <select class="form-select" name="team_id">
                            <option value="0">All My Teams</option>

                            <?php foreach($managerTeams as $team): ?>
                                <option 
                                    value="<?= (int)$team['id'] ?>" 
                                    <?= $selectedTeamId === (int)$team['id'] ? 'selected' : '' ?>
                                >
                                    <?= h($team['team_name']) ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                    <?php endif; ?>
                </div>

                <button class="btn-main">
                    <i class="fas fa-filter me-1"></i>
                    Apply
                </button>
            </form>
        </div>

        <div class="ranking-card table-wrap">
            <table class="ranking-table">
                <thead>
                    <tr>
                        <th>Rank</th>
                        <th>CSR</th>
                        <th>Team</th>
                        <th>Role</th>
                        <th>Handled</th>
                        <th>Completed</th>
                        <th>Cancelled</th>
                        <th>Score</th>
                    </tr>
                </thead>

                <tbody>
                    <?php foreach($rankings as $i => $r): ?>
                        <tr class="<?= ((int)$r['id'] === $managerId) ? 'mine-row' : '' ?>">
                            <td>
                                <span class="rank-badge">
                                    <?= $i + 1 ?>
                                </span>
                            </td>

                            <td>
                                <strong><?= h($r['csr_name']) ?></strong>

                                <?php if((int)$r['id'] === $managerId): ?>
                                    <span class="badge-pill ms-2">
                                        You
                                    </span>
                                <?php endif; ?>
                            </td>

                            <td>
                                <span class="badge-pill">
                                    <i class="fas fa-users"></i>
                                    <?= h($r['team_name'] ?: 'Team') ?>
                                </span>
                            </td>

                            <td>
                                <?= h($r['role'] === 'csr_manager' ? 'CSR Manager' : ($r['role'] === 'team_leader' ? 'Team Leader' : 'CSR')) ?>
                            </td>

                            <td><?= number_format((int)$r['handled_tickets']) ?></td>
                            <td><?= number_format((int)$r['completed_tickets']) ?></td>
                            <td><?= number_format((int)$r['canceled_tickets']) ?></td>

                            <td>
                                <strong><?= number_format((int)$r['score']) ?></strong>
                            </td>
                        </tr>
                    <?php endforeach; ?>

                    <?php if(empty($rankings)): ?>
                        <tr>
                            <td colspan="8" class="empty-state">
                                No CSR ranking records found for your team in this date range.
                            </td>
                        </tr>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>
    <?php endif; ?>
</div>

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