<?php
declare(strict_types=1);

if (session_status() !== PHP_SESSION_ACTIVE) {
    session_start();
}

require_once __DIR__ . '/db.php';
require_once __DIR__ . '/inc/layout.php';

if (empty($_SESSION['user_id'])) {
    header("Location: index.html?e=1");
    exit;
}

$pdo = db();

if (!$pdo instanceof PDO) {
    http_response_code(500);
    exit('DB not ready');
}

$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$pdo->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);

date_default_timezone_set('Asia/Dubai');

if (!function_exists('h')) {
    function h($v): string {
        return htmlspecialchars((string)$v, ENT_QUOTES, 'UTF-8');
    }
}

function table_exists_stat(PDO $pdo, string $table): bool {
    try {
        $st = $pdo->prepare("
            SELECT COUNT(*)
            FROM information_schema.tables
            WHERE table_schema = DATABASE()
              AND table_name = ?
        ");
        $st->execute([$table]);
        return (int)$st->fetchColumn() > 0;
    } catch (Throwable $e) {
        return false;
    }
}

function column_exists_stat(PDO $pdo, string $table, string $column): bool {
    try {
        $st = $pdo->prepare("
            SELECT COUNT(*)
            FROM information_schema.columns
            WHERE table_schema = DATABASE()
              AND table_name = ?
              AND column_name = ?
        ");
        $st->execute([$table, $column]);
        return (int)$st->fetchColumn() > 0;
    } catch (Throwable $e) {
        return false;
    }
}

$role = strtoupper((string)($_SESSION['role'] ?? 'STAFF'));
$isAdmin = in_array($role, ['OWNER', 'ADMIN', 'SUPER_ADMIN'], true);

$sessionBranchId = (int)($_SESSION['branch_id'] ?? 1);
if ($sessionBranchId <= 0) {
    $sessionBranchId = 1;
}

$month = (string)($_GET['month'] ?? date('Y-m'));
if (!preg_match('/^\d{4}-\d{2}$/', $month)) {
    $month = date('Y-m');
}

[$year, $mon] = explode('-', $month);
$year = (int)$year;
$mon  = (int)$mon;

$monthNames = [
    1 => 'يناير',
    2 => 'فبراير',
    3 => 'مارس',
    4 => 'أبريل',
    5 => 'مايو',
    6 => 'يونيو',
    7 => 'يوليو',
    8 => 'أغسطس',
    9 => 'سبتمبر',
    10 => 'أكتوبر',
    11 => 'نوفمبر',
    12 => 'ديسمبر',
];

$monthLabel = ($monthNames[$mon] ?? $month) . ' ' . $year;

/* الفروع */
$branchNames = [
    1 => 'أبوظبي',
    2 => 'دبي',
];

if (table_exists_stat($pdo, 'branches')) {
    $nameCol = column_exists_stat($pdo, 'branches', 'name_ar') ? 'name_ar' : (
        column_exists_stat($pdo, 'branches', 'name') ? 'name' : ''
    );

    if ($nameCol !== '') {
        try {
            $stBranches = $pdo->query("SELECT id, `$nameCol` AS branch_name FROM branches ORDER BY id ASC");
            foreach ($stBranches->fetchAll() as $b) {
                $bid = (int)($b['id'] ?? 0);
                $bname = trim((string)($b['branch_name'] ?? ''));

                if ($bid > 0 && $bname !== '') {
                    $branchNames[$bid] = $bname;
                }
            }
        } catch (Throwable $e) {
        }
    }
}

/* تحقق الجداول */
if (!table_exists_stat($pdo, 'cases')) {
    http_response_code(500);
    exit('Table cases not found');
}

$logTable = '';

if (table_exists_stat($pdo, 'system_activity_logs')) {
    $logTable = 'system_activity_logs';
} elseif (table_exists_stat($pdo, 'activity_logs')) {
    $logTable = 'activity_logs';
}

$hasUsersTable   = table_exists_stat($pdo, 'users');
$hasBranchCol    = column_exists_stat($pdo, 'cases', 'branch_id');
$hasCreatedByCol = column_exists_stat($pdo, 'cases', 'created_by');
$hasStatusCol    = column_exists_stat($pdo, 'cases', 'status');
$hasCreatedAtCol = column_exists_stat($pdo, 'cases', 'created_at');

if (!$hasBranchCol || !$hasCreatedByCol || !$hasStatusCol || !$hasCreatedAtCol) {
    http_response_code(500);
    exit('Required columns are missing in cases table');
}

$params = [
    ':m' => $mon,
    ':y' => $year,
];

$whereBranchCases = '';

if (!$isAdmin) {
    $whereBranchCases = " AND c.branch_id = :branch_id ";
    $params[':branch_id'] = $sessionBranchId;
}

/* اسم الموظف */
$joinUser = '';
$employeeNameExpr = "CONCAT('مستخدم رقم ', c.created_by)";
$groupByUser = "c.created_by";

if ($hasUsersTable) {
    $userNameCol = column_exists_stat($pdo, 'users', 'name') ? 'name' : '';
    $userUsernameCol = column_exists_stat($pdo, 'users', 'username') ? 'username' : '';

    $joinUser = " LEFT JOIN users u ON u.id = c.created_by ";

    if ($userNameCol !== '' && $userUsernameCol !== '') {
        $employeeNameExpr = "COALESCE(NULLIF(u.`$userNameCol`, ''), NULLIF(u.`$userUsernameCol`, ''), CONCAT('مستخدم رقم ', c.created_by))";
        $groupByUser = "c.created_by, u.`$userNameCol`, u.`$userUsernameCol`";
    } elseif ($userNameCol !== '') {
        $employeeNameExpr = "COALESCE(NULLIF(u.`$userNameCol`, ''), CONCAT('مستخدم رقم ', c.created_by))";
        $groupByUser = "c.created_by, u.`$userNameCol`";
    } elseif ($userUsernameCol !== '') {
        $employeeNameExpr = "COALESCE(NULLIF(u.`$userUsernameCol`, ''), CONCAT('مستخدم رقم ', c.created_by))";
        $groupByUser = "c.created_by, u.`$userUsernameCol`";
    }
}
/* ========= إحصائيات الموظفين من سجل النشاط فقط ========= */

$grouped = [];
$topEmployees = [];

if ($logTable === '') {
    http_response_code(500);
    exit('جدول سجل النشاط غير موجود');
}

$logHasUserId     = column_exists_stat($pdo, $logTable, 'user_id');
$logHasActionType = column_exists_stat($pdo, $logTable, 'action_type');
$logHasCreatedAt  = column_exists_stat($pdo, $logTable, 'created_at');
$logHasBranchId   = column_exists_stat($pdo, $logTable, 'branch_id');

if (!$logHasUserId || !$logHasActionType || !$logHasCreatedAt) {
    http_response_code(500);
    exit('أعمدة سجل النشاط غير مكتملة');
}

$logJoinUser = '';
$employeeNameExpr = "CONCAT('مستخدم رقم ', l.user_id)";

if ($hasUsersTable) {
    $logJoinUser = " LEFT JOIN users u ON u.id = l.user_id ";

    $userNameCol = column_exists_stat($pdo, 'users', 'name') ? 'name' : '';
    $userUsernameCol = column_exists_stat($pdo, 'users', 'username') ? 'username' : '';

    if ($userNameCol !== '' && $userUsernameCol !== '') {
        $employeeNameExpr = "COALESCE(NULLIF(u.`$userNameCol`, ''), NULLIF(u.`$userUsernameCol`, ''), CONCAT('مستخدم رقم ', l.user_id))";
    } elseif ($userNameCol !== '') {
        $employeeNameExpr = "COALESCE(NULLIF(u.`$userNameCol`, ''), CONCAT('مستخدم رقم ', l.user_id))";
    } elseif ($userUsernameCol !== '') {
        $employeeNameExpr = "COALESCE(NULLIF(u.`$userUsernameCol`, ''), CONCAT('مستخدم رقم ', l.user_id))";
    }
}

if ($logHasBranchId) {
    $branchExpr = "COALESCE(NULLIF(l.branch_id, 0), :default_branch)";
    $joinCasesForBranch = "";
} else {
    $branchExpr = "COALESCE(NULLIF(MAX(c.branch_id), 0), :default_branch)";
    $joinCasesForBranch = " LEFT JOIN cases c ON c.created_by = l.user_id ";
}

$logParams = [
    ':m' => $mon,
    ':y' => $year,
    ':default_branch' => $sessionBranchId,
];

$whereLogBranch = '';

if (!$isAdmin) {
    if ($logHasBranchId) {
        $whereLogBranch = " AND l.branch_id = :branch_id ";
    } else {
        $whereLogBranch = " AND c.branch_id = :branch_id ";
    }

    $logParams[':branch_id'] = $sessionBranchId;
}

$logSql = "
SELECT
    l.user_id,
    {$branchExpr} AS branch_id,
    {$employeeNameExpr} AS employee_name,

    SUM(CASE WHEN l.action_type IN ('create_case', 'case_created') THEN 1 ELSE 0 END) AS total_cases,
    SUM(CASE WHEN l.action_type IN ('create_task', 'task_created', 'complete_task', 'task_completed') THEN 1 ELSE 0 END) AS total_tasks,
    SUM(CASE WHEN l.action_type IN ('create_client', 'client_created', 'add_client') THEN 1 ELSE 0 END) AS total_clients,
    SUM(CASE WHEN l.action_type IN ('create_hearing', 'hearing_created', 'add_case_session', 'session_created') THEN 1 ELSE 0 END) AS total_sessions,
    SUM(CASE WHEN l.action_type IN ('create_contract', 'contract_created') THEN 1 ELSE 0 END) AS total_contracts,

    SUM(
        CASE
            WHEN l.action_type IN ('create_case', 'case_created') THEN 4
            WHEN l.action_type IN ('create_task', 'task_created') THEN 1
            WHEN l.action_type IN ('complete_task', 'task_completed') THEN 2
            WHEN l.action_type IN ('create_client', 'client_created', 'add_client') THEN 3
            WHEN l.action_type IN ('create_hearing', 'hearing_created', 'add_case_session', 'session_created') THEN 2
            WHEN l.action_type IN ('create_contract', 'contract_created') THEN 3
            WHEN l.action_type IN ('update_case', 'case_updated') THEN 1
            WHEN l.action_type IN ('update_client', 'client_updated') THEN 1
            ELSE 0
        END
    ) AS total_points,

    COUNT(*) AS total_actions

FROM `$logTable` l

{$logJoinUser}
{$joinCasesForBranch}

WHERE MONTH(l.created_at) = :m
  AND YEAR(l.created_at) = :y
  {$whereLogBranch}

GROUP BY l.user_id, employee_name" . ($logHasBranchId ? ", l.branch_id" : "") . "

HAVING total_points > 0

ORDER BY branch_id ASC, total_points DESC, total_actions DESC, employee_name ASC
";

$st = $pdo->prepare($logSql);
$st->execute($logParams);
$rows = $st->fetchAll();

foreach ($rows as $row) {
    $bid = (int)($row['branch_id'] ?? 0);

    if ($bid <= 0) {
        continue;
    }

    if (!isset($grouped[$bid])) {
        $grouped[$bid] = [];
    }

    $row['new_cases'] = 0;
    $row['work_cases'] = 0;
    $row['court_cases'] = 0;
    $row['closed_cases'] = 0;
    $row['completion_rate'] = 0;
    $row['case_points'] = 0;
    $row['activity_points'] = (int)($row['total_points'] ?? 0);

    $grouped[$bid][] = $row;

    if (!isset($topEmployees[$bid])) {
        $topEmployees[$bid] = $row;
    }
}
/* دمج نقاط النشاط مع جدول القضايا */
foreach ($grouped as $bid => &$list) {
    foreach ($list as &$row) {
        $uid = (int)($row['user_id'] ?? 0);

        if (isset($activityByBranchUser[$bid][$uid])) {
            $row['activity_points'] = $activityByBranchUser[$bid][$uid]['activity_points'];
            $row['total_actions']   = $activityByBranchUser[$bid][$uid]['total_actions'];
        }

        $row['total_points'] = (int)($row['case_points'] ?? 0) + (int)($row['activity_points'] ?? 0);
    }

    usort($list, function ($a, $b) {
        return
            ((int)$b['total_points'] <=> (int)$a['total_points'])
            ?: ((int)$b['activity_points'] <=> (int)$a['activity_points'])
            ?: ((int)$b['closed_cases'] <=> (int)$a['closed_cases'])
            ?: ((int)$b['total_cases'] <=> (int)$a['total_cases'])
            ?: strcmp((string)$a['employee_name'], (string)$b['employee_name']);
    });
}
unset($list, $row);

/* الإجماليات */
$branchTotals = [];

foreach ($branchNames as $bid => $branchLabel) {
    $branchTotals[$bid] = [
        'cases'        => 0,
        'new_cases'    => 0,
        'work_cases'   => 0,
        'court_cases'  => 0,
        'closed_cases' => 0,
        'employees'    => 0,
        'top'          => null,
    ];
}

foreach ($grouped as $bid => $list) {
    if (!isset($branchTotals[$bid])) {
        $branchTotals[$bid] = [
            'cases'        => 0,
            'new_cases'    => 0,
            'work_cases'   => 0,
            'court_cases'  => 0,
            'closed_cases' => 0,
            'employees'    => 0,
            'top'          => null,
        ];
    }

    $branchTotals[$bid]['top'] = $topEmployees[$bid] ?? ($list[0] ?? null);

    foreach ($list as $r) {
        if ((int)($r['total_cases'] ?? 0) > 0) {
            $branchTotals[$bid]['employees']++;
        }

        $branchTotals[$bid]['cases']        += (int)($r['total_cases'] ?? 0);
        $branchTotals[$bid]['new_cases']    += (int)($r['new_cases'] ?? 0);
        $branchTotals[$bid]['work_cases']   += (int)($r['work_cases'] ?? 0);
        $branchTotals[$bid]['court_cases']  += (int)($r['court_cases'] ?? 0);
        $branchTotals[$bid]['closed_cases'] += (int)($r['closed_cases'] ?? 0);
    }
}

$displayBranches = $isAdmin
    ? $branchNames
    : [$sessionBranchId => ($branchNames[$sessionBranchId] ?? 'الفرع الحالي')];

render_layout_start('إحصائيات الموظفين حسب الفرع');
?>

<style>
.stats-page{
  width:100% !important;
  max-width:none !important;
  margin:0 !important;
  padding:0 24px 24px !important;
  display:grid;
  gap:18px;
  color:#fff;
}

.stats-page > *{
  width:100% !important;
  max-width:none !important;
}

body{
  background:
    radial-gradient(circle at 20% 20%, rgba(10,77,87,.85), transparent 40%),
    radial-gradient(circle at 80% 80%, rgba(13,106,122,.55), transparent 40%),
    #021d23;
}

.hero-stats,
.panel,
.stat-card,
.branch-section{
  background:rgba(255,255,255,.05);
  border:1px solid rgba(255,255,255,.08);
  box-shadow:0 18px 40px rgba(0,0,0,.16);
  backdrop-filter:blur(12px);
}

.hero-stats{
  border-radius:24px;
  padding:28px;
}

.hero-title{
  font-size:30px;
  margin:0 0 8px;
  color:#fff;
  font-weight:900;
}

.hero-sub{
  color:rgba(255,255,255,.68);
  font-size:16px;
  line-height:1.8;
}

.panel{
  border-radius:22px;
  padding:20px;
}

.month-filter-row{
  display:flex;
  align-items:end;
  gap:16px;
  flex-wrap:wrap;
}

.month-field{
  flex:1 1 320px;
  min-width:260px;
}

.field-top{
  color:#eef7f8;
  font-size:15px;
  font-weight:800;
  margin-bottom:10px;
}

.month-input-wrap{
  position:relative;
}

.input{
  width:100%;
  height:58px;
  border:none;
  outline:none;
  border-radius:18px;
  padding:0 54px 0 18px;
  background:rgba(255,255,255,.10);
  color:#fff;
  font-size:16px;
  font-weight:700;
  font-family:"Tajawal", sans-serif;
  box-shadow:inset 0 0 0 1px rgba(255,255,255,.08);
}

.month-input-wrap::before{
  content:"📅";
  position:absolute;
  right:18px;
  top:50%;
  transform:translateY(-50%);
  font-size:18px;
  pointer-events:none;
}

.month-input::-webkit-calendar-picker-indicator{
  position:absolute;
  inset:0;
  width:100%;
  height:100%;
  opacity:0;
  cursor:pointer;
}

.btn{
  height:58px;
  border:none;
  border-radius:18px;
  padding:0 26px;
  background:linear-gradient(135deg, #f1cc57, #d4af37);
  color:#1c2a2d;
  font-family:"Tajawal", sans-serif;
  font-size:16px;
  font-weight:800;
  cursor:pointer;
  box-shadow:0 10px 24px rgba(212,175,55,.20);
}

.cards-grid{
  display:grid !important;
  grid-template-columns:repeat(auto-fit,minmax(260px,1fr)) !important;
  gap:16px;
}

.stat-card{
  border-radius:20px;
  padding:18px;
}

.stat-label{
  color:rgba(255,255,255,.68);
  font-size:14px;
  margin-bottom:8px;
}

.stat-value{
  font-size:28px;
  color:#ffd76a;
  font-weight:900;
}

.branch-section{
  border-radius:24px;
  padding:22px;
}

.branch-header{
  display:flex;
  justify-content:space-between;
  gap:12px;
  flex-wrap:wrap;
  align-items:center;
  margin-bottom:16px;
}

.branch-title{
  margin:0;
  font-size:26px;
  color:#fff;
  font-weight:900;
}

.winner-card{
  background:linear-gradient(135deg, rgba(212,175,55,.20), rgba(255,215,106,.10));
  border:1px solid rgba(212,175,55,.30);
  border-radius:24px;
  padding:20px;
  box-shadow:0 14px 30px rgba(168,127,10,.16);
  margin-bottom:18px;
}

.winner-badge{
  display:inline-block;
  background:linear-gradient(135deg,#ffd76a,#d4af37);
  color:#1d1600;
  padding:8px 14px;
  border-radius:999px;
  font-size:13px;
  font-weight:900;
  margin-bottom:10px;
}

.winner-name{
  font-size:28px;
  color:#fff7d1;
  margin:0 0 8px;
  font-weight:900;
}

.winner-meta{
  color:rgba(255,255,255,.82);
  display:flex;
  flex-wrap:wrap;
  gap:14px;
  font-size:15px;
  line-height:1.8;
}

.table-wrap{
  width:100% !important;
  overflow-x:auto !important;
  border-radius:18px;
}

.table{
  width:100% !important;
  min-width:1100px !important;
  border-collapse:collapse;
}

.table th{
  background:rgba(255,255,255,.04);
  color:rgba(255,255,255,.72);
  padding:14px 12px;
  text-align:center;
  font-size:14px;
  border-bottom:1px solid rgba(255,255,255,.08);
  font-weight:900;
}

.table td{
  padding:14px 12px;
  text-align:center;
  border-bottom:1px solid rgba(255,255,255,.05);
  font-size:14px;
  color:#fff;
}

.rank{
  width:40px;
  height:40px;
  border-radius:50%;
  display:inline-flex;
  align-items:center;
  justify-content:center;
  background:rgba(255,255,255,.08);
  color:#fff;
  font-weight:700;
  border:1px solid rgba(255,255,255,.08);
}

.rank.top1{
  background:rgba(212,175,55,.18);
  color:#ffd76a;
  border-color:rgba(212,175,55,.28);
}

.rank.top2{
  background:rgba(203,213,225,.14);
  color:#e2e8f0;
}

.rank.top3{
  background:rgba(180,120,60,.16);
  color:#f3c89b;
}

.progress{
  width:140px;
  height:10px;
  background:rgba(255,255,255,.10);
  border-radius:999px;
  margin:0 auto 6px;
  overflow:hidden;
}

.progress > span{
  display:block;
  height:100%;
  background:linear-gradient(90deg,#ffd76a,#d4af37);
  border-radius:999px;
}

.small{
  color:rgba(255,255,255,.68);
  font-size:12px;
}

.no-data{
  text-align:center;
  padding:30px 20px;
  color:rgba(255,255,255,.68);
}

@media (max-width:768px){
  .stats-page{
    padding:0 12px 18px !important;
  }

  .hero-title{
    font-size:24px;
  }

  .winner-name{
    font-size:22px;
  }

  .branch-title{
    font-size:22px;
  }

  .month-filter-row{
    flex-direction:column;
    align-items:stretch;
  }

  .month-field,
  .btn{
    width:100%;
  }
}
</style>

<div class="stats-page">

    <section class="hero-stats">
        <h1 class="hero-title">إحصائيات الموظفين الشهرية حسب الفرع</h1>
        <div class="hero-sub">عرض أداء أبوظبي ودبي مع اعتماد المتصدر من سجل النشاط الحقيقي</div>
    </section>

    <section class="panel">
        <form method="get" class="month-filter-row">
            <div class="month-field">
                <div class="field-top">اختر الشهر</div>
                <div class="month-input-wrap">
                    <input class="input" type="month" name="month" value="<?= h($month) ?>">
                </div>
            </div>

            <button class="btn" type="submit">عرض الإحصائيات</button>
        </form>
    </section>

    <section class="cards-grid">
        <div class="stat-card">
            <div class="stat-label">الشهر</div>
            <div class="stat-value"><?= h($monthLabel) ?></div>
        </div>

        <?php foreach ($displayBranches as $bid => $branchLabel):
            $tot = $branchTotals[$bid] ?? [
                'cases' => 0,
                'closed_cases' => 0,
                'employees' => 0,
            ];
        ?>
            <div class="stat-card">
                <div class="stat-label">إجمالي قضايا <?= h($branchLabel) ?></div>
                <div class="stat-value"><?= (int)$tot['cases'] ?></div>
            </div>
        <?php endforeach; ?>
    </section>

    <?php foreach ($displayBranches as $bid => $branchLabel):
        $list = $grouped[$bid] ?? [];
        $tot  = $branchTotals[$bid] ?? null;
        $top  = $branchTotals[$bid]['top'] ?? null;
    ?>
        <section class="branch-section">

            <div class="branch-header">
                <h2 class="branch-title">فرع <?= h($branchLabel) ?></h2>
            </div>

            <div class="cards-grid" style="margin-bottom:18px;">
                <div class="stat-card">
                    <div class="stat-label">إجمالي القضايا</div>
                    <div class="stat-value"><?= (int)($tot['cases'] ?? 0) ?></div>
                </div>

                <div class="stat-card">
                    <div class="stat-label">القضايا الجديدة</div>
                    <div class="stat-value"><?= (int)($tot['new_cases'] ?? 0) ?></div>
                </div>

                <div class="stat-card">
                    <div class="stat-label">القضايا المغلقة</div>
                    <div class="stat-value"><?= (int)($tot['closed_cases'] ?? 0) ?></div>
                </div>

                <div class="stat-card">
                    <div class="stat-label">الموظفون النشطون</div>
                    <div class="stat-value"><?= (int)($tot['employees'] ?? 0) ?></div>
                </div>
            </div>
<?php
$top = $topEmployees[$bid] ?? null;
?>

<?php if (!empty($top)): ?>
    <div class="winner-card">
        <div class="winner-badge">
            🏆 المتصدر من سجل النشاط - <?= h($branchLabel) ?>
        </div>

        <h3 class="winner-name">
            <?= h($top['employee_name'] ?? 'غير محدد') ?>
        </h3>

        <div class="winner-meta">
            <span>النقاط: <?= (int)($top['total_points'] ?? 0) ?></span>
            <span>النشاطات: <?= (int)($top['total_actions'] ?? 0) ?></span>
            <span>المهام: <?= (int)($top['total_tasks'] ?? 0) ?></span>
            <span>العملاء: <?= (int)($top['total_clients'] ?? 0) ?></span>
            <span>الجلسات: <?= (int)($top['total_sessions'] ?? 0) ?></span>
            <span>القضايا: <?= (int)($top['total_cases'] ?? 0) ?></span>
            <span>العقود: <?= (int)($top['total_contracts'] ?? 0) ?></span>
        </div>
    </div>
<?php else: ?>
    <div class="winner-card">
        <div class="winner-badge">
            لا يوجد متصدر
        </div>

        <h3 class="winner-name">
            لا توجد نشاطات لهذا الفرع خلال هذا الشهر
        </h3>
    </div>
<?php endif; ?>
            <?php if (!$list): ?>
                <div class="no-data">لا توجد بيانات لهذا الفرع خلال هذا الشهر.</div>
            <?php else: ?>
                <div class="table-wrap">
                    <table class="table">
                        <thead>
                            <tr>
                                <th>القضايا</th>
<th>المهام</th>
<th>العملاء</th>
<th>الجلسات</th>
<th>العقود</th>
<th>عدد النشاطات</th>
<th>النقاط</th>
                            </tr>
                        </thead>

                        <tbody>
                        <?php foreach ($list as $i => $row):
                            $rankClass = '';
                            if ($i === 0) {
                                $rankClass = 'top1';
                            } elseif ($i === 1) {
                                $rankClass = 'top2';
                            } elseif ($i === 2) {
                                $rankClass = 'top3';
                            }

                            $rate = (float)($row['completion_rate'] ?? 0);
                            if ($rate < 0) $rate = 0;
                            if ($rate > 100) $rate = 100;
                        ?>
                            <tr>
                                <td>
                                    <span class="rank <?= h($rankClass) ?>">
                                        <?= $i + 1 ?>
                                    </span>
                                </td>

                                <td><?= h($row['employee_name'] ?? '') ?></td>
                             <td><?= (int)($row['total_cases'] ?? 0) ?></td>
<td><?= (int)($row['total_tasks'] ?? 0) ?></td>
<td><?= (int)($row['total_clients'] ?? 0) ?></td>
<td><?= (int)($row['total_sessions'] ?? 0) ?></td>
<td><?= (int)($row['total_contracts'] ?? 0) ?></td>
<td><?= (int)($row['total_actions'] ?? 0) ?></td>
<td><?= (int)($row['total_points'] ?? 0) ?></td>
                                <td>
                                    <div class="progress">
                                        <span style="width:<?= h((string)$rate) ?>%"></span>
                                    </div>
                                    <div class="small"><?= h($row['completion_rate'] ?? 0) ?>%</div>
                                </td>

                                <td><?= (int)($row['case_points'] ?? 0) ?></td>
                                <td><?= (int)($row['activity_points'] ?? 0) ?></td>
                                <td><?= (int)($row['total_actions'] ?? 0) ?></td>
                                <td><?= (int)($row['total_points'] ?? 0) ?></td>
                            </tr>
                        <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
            <?php endif; ?>

        </section>
    <?php endforeach; ?>

</div>

<?php render_layout_end(); ?>