<?php
declare(strict_types=1);

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

/* ===== Debug ===== */
$debug = (isset($_GET['debug']) && $_GET['debug'] === '1');
ini_set('display_errors', $debug ? '1' : '0');
ini_set('display_startup_errors', $debug ? '1' : '0');
error_reporting(E_ALL);

require_once __DIR__ . '/db.php';
require_once __DIR__ . '/inc/app_url.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');
}
$employeeId = (int)($_SESSION['employee_id'] ?? 0);

if ($employeeId === 0) {
    $st = $pdo->prepare("
        SELECT id 
        FROM employees 
        WHERE name = ? OR full_name = ?
        LIMIT 1
    ");
    $st->execute([
        $_SESSION['name'] ?? '',
        $_SESSION['name'] ?? ''
    ]);

    $employeeId = (int)($st->fetchColumn() ?: 0);
    $_SESSION['employee_id'] = $employeeId;
}
/* ===== Session ===== */
$userId   = (int)($_SESSION['user_id'] ?? 0);
$branchId = (int)($_SESSION['branch_id'] ?? 1);
$role     = strtoupper((string)($_SESSION['role'] ?? 'STAFF'));
$isOwner  = ($role === 'OWNER');
$_SESSION['performance'] = $performance;
$_SESSION['today_points'] = $todayPoints;
$_SESSION['daily_target'] = $dailyTarget;
if ($userId <= 0) {
    header("Location: index.html?e=1");
    exit;
}

/* ===== Helpers ===== */
if (!function_exists('n')) {
    function n($v): int
    {
        return (int)($v ?? 0);
    }
}

if (!function_exists('money_short')) {
    function money_short($v): string
    {
        $v = (float)($v ?? 0);
        if ($v >= 1000000) {
            return rtrim(rtrim(number_format($v / 1000000, 1, '.', ''), '0'), '.') . 'M';
        }
        if ($v >= 1000) {
            return rtrim(rtrim(number_format($v / 1000, 1, '.', ''), '0'), '.') . 'K';
        }
        return (string)(int)$v;
    }
}

if (!function_exists('case_status_label')) {
    function case_status_label($s): array
    {
        $s = strtoupper(trim((string)$s));
        return match ($s) {
            'NEW'    => ['جديدة', 'new'],
            'WORK'   => ['قيد العمل', 'work'],
            'COURT'  => ['في المحكمة', 'court'],
            'CLOSED' => ['مغلقة', 'closed'],
            default  => ['قيد العمل', 'work'],
        };
    }
}

if (!function_exists('can_see_financial_section')) {
    function can_see_financial_section(): bool
    {
        return in_array(current_role(), ['OWNER', 'ADMIN'], true);
    }
}

if (!function_exists('table_exists')) {
    function table_exists(PDO $pdo, string $table): bool
    {
        try {
            $db = (string)$pdo->query("SELECT DATABASE()")->fetchColumn();
            if ($db === '') {
                return false;
            }

            $st = $pdo->prepare("
                SELECT 1
                FROM information_schema.tables
                WHERE table_schema = ?
                  AND table_name = ?
                LIMIT 1
            ");
            $st->execute([$db, $table]);
            return (bool)$st->fetchColumn();
        } catch (Throwable $e) {
            return false;
        }
    }
}

if (!function_exists('column_exists')) {
    function column_exists(PDO $pdo, string $table, string $column): bool
    {
        try {
            $db = (string)$pdo->query("SELECT DATABASE()")->fetchColumn();
            if ($db === '') {
                return false;
            }

            $st = $pdo->prepare("
                SELECT 1
                FROM information_schema.columns
                WHERE table_schema = ?
                  AND table_name = ?
                  AND column_name = ?
                LIMIT 1
            ");
            $st->execute([$db, $table, $column]);
            return (bool)$st->fetchColumn();
        } catch (Throwable $e) {
            return false;
        }
    }
}

if (!function_exists('getBranchName')) {
    function getBranchName(PDO $pdo, int $branchId): string
    {
        $fallback = match ($branchId) {
            2 => 'دبي',
            3 => 'الشارقة',
            4 => 'العين',
            default => 'أبوظبي',
        };

        if (!table_exists($pdo, 'branches')) {
            return $fallback;
        }

        try {
            $st = $pdo->prepare("SELECT name_ar FROM branches WHERE id = ? LIMIT 1");
            $st->execute([$branchId]);
            $name = trim((string)($st->fetchColumn() ?: ''));
            return $name !== '' ? $name : $fallback;
        } catch (Throwable $e) {
            return $fallback;
        }
    }
}

/* ===== بيانات الفرع الحالي ===== */
$displayBranchName = getBranchName($pdo, $branchId);

/* ===== تحديث نشاط المستخدم الحالي ===== */
try {
    if (table_exists($pdo, 'employees') && column_exists($pdo, 'employees', 'last_activity')) {
        $st = $pdo->prepare("
            UPDATE employees
            SET last_activity = NOW()
            WHERE id = ?
            LIMIT 1
        ");
        $st->execute([$_SESSION['employee_id']]);
    }
} catch (Throwable $e) {
    // لا توقف الصفحة
}

/* ===== الموظفون المتصلون الآن ===== */
$onlineEmployees = [];

try {
    if (table_exists($pdo, 'employees') && column_exists($pdo, 'employees', 'last_activity')) {
      $hasFullName = column_exists($pdo, 'employees', 'full_name');
$hasName     = column_exists($pdo, 'employees', 'name');
$hasBranchId = column_exists($pdo, 'employees', 'branch_id');

$nameParts = [];

if ($hasFullName) {
    $nameParts[] = "NULLIF(TRIM(full_name), '')";
}
if ($hasName) {
    $nameParts[] = "NULLIF(TRIM(name), '')";
}

$nameParts[] = "CONCAT('موظف #', id)";
$displayNameSql = 'COALESCE(' . implode(', ', $nameParts) . ')';

   $sql = "
SELECT
    id,
    COALESCE(NULLIF(full_name,''),NULLIF(name,''),CONCAT('موظف #',id)) AS employee_name
FROM employees
WHERE last_activity >= (NOW() - INTERVAL 3 MINUTE)
AND branch_id = ?
ORDER BY last_activity DESC
LIMIT 10
";
$employeeId = (int)($_SESSION['employee_id'] ?? 0);

if ($employeeId <= 0) {
    $sessionName = trim((string)($_SESSION['name'] ?? ''));
    
    
    
    $sessionUsername = trim((string)($_SESSION['username'] ?? ''));

    if ($sessionName !== '' || $sessionUsername !== '') {
        $st = $pdo->prepare("
            SELECT id
            FROM employees
            WHERE
                TRIM(COALESCE(full_name, '')) = ?
                OR TRIM(COALESCE(name, '')) = ?
                OR TRIM(COALESCE(full_name, '')) = ?
                OR TRIM(COALESCE(name, '')) = ?
            LIMIT 1
        ");
        $st->execute([
            $sessionName,
            $sessionName,
            $sessionUsername,
            $sessionUsername
        ]);

        $employeeId = (int)($st->fetchColumn() ?: 0);

        if ($employeeId > 0) {
            $_SESSION['employee_id'] = $employeeId;
        }
    }
}
$st = $pdo->prepare($sql);
$st->execute([$branchId]);

$onlineEmployees = $st->fetchAll();
        $params = [];

        if (!$isOwner && $hasBranchId) {
            $sql .= " AND branch_id = ?";
            $params[] = $branchId;
        }

        $sql .= " ORDER BY last_activity DESC, id DESC LIMIT 12";

        $st = $pdo->prepare($sql);
        $st->execute($params);
        $onlineEmployees = $st->fetchAll(PDO::FETCH_ASSOC);
    }
} catch (Throwable $e) {
    $onlineEmployees = [];
}

/* ===== عدد المتصلين ===== */
$onlineCount = count($onlineEmployees);

/* ===== اسم الفرع الحالي ===== */
$currentBranchName = getBranchName($pdo, $branchId);
/* ===== Session/User ===== */
$name = (string)($_SESSION['name'] ?? $_SESSION['username'] ?? 'مستخدم');
$role = current_role();
$isOwner = ($role === 'OWNER');
$logo = "https://hamdanlegalgroup.ae/wp-content/uploads/2026/02/logomail.png";

/* ===== Branch ===== */
$branchId = (int)($_SESSION['branch_id'] ?? 1);
if ($branchId <= 0) $branchId = 1;
$currentBranchName = getBranchName($pdo, $branchId);

/* ===== Validate required tables ===== */
if (!table_exists($pdo, 'cases')) {
    http_response_code(500);
    exit('Table "cases" not found');
}

/* ===== Detect cases columns ===== */
$CASES_TABLE      = 'cases';
$casesBranchCol   = column_exists($pdo, $CASES_TABLE, 'branch_id') ? 'branch_id' : (column_exists($pdo, $CASES_TABLE, 'branch') ? 'branch' : '');
$casesCreatedAt   = column_exists($pdo, $CASES_TABLE, 'created_at') ? 'created_at' : '';
$casesTitleCol    = column_exists($pdo, $CASES_TABLE, 'title') ? 'title' : (column_exists($pdo, $CASES_TABLE, 'case_title') ? 'case_title' : 'title');
$casesNoCol       = column_exists($pdo, $CASES_TABLE, 'case_no') ? 'case_no' : (column_exists($pdo, $CASES_TABLE, 'case_number') ? 'case_number' : 'case_no');
$casesClientCol   = column_exists($pdo, $CASES_TABLE, 'client_name') ? 'client_name' : (column_exists($pdo, $CASES_TABLE, 'client') ? 'client' : 'client_name');
$casesStatusCol   = column_exists($pdo, $CASES_TABLE, 'status') ? 'status' : 'status';
$casesNextDateCol = column_exists($pdo, $CASES_TABLE, 'next_hearing_date') ? 'next_hearing_date' : '';
$casesSecretCol   = column_exists($pdo, $CASES_TABLE, 'is_secret') ? 'is_secret' : '';

if ($debug) {
    echo "<pre style='direction:ltr;background:#111;color:#0f0;padding:12px;border-radius:10px;max-width:1100px;margin:12px auto;overflow:auto'>";
    echo "APP_BASE_URL: " . h(app_base_url()) . "\n";
    echo "DB: " . ($pdo->query("SELECT DATABASE()")->fetchColumn() ?: '') . "\n";
    echo "branchId(session): " . (int)$branchId . "\n";
    echo "casesBranchCol: " . ($casesBranchCol ?: '(none)') . "\n";
    echo "created_at: " . ($casesCreatedAt ?: '(none)') . "\n";
    echo "next_hearing_date: " . ($casesNextDateCol ?: '(none)') . "\n";
    echo "is_secret: " . ($casesSecretCol ?: '(none)') . "\n\n";

    $cntAll = (int)$pdo->query("SELECT COUNT(*) FROM `$CASES_TABLE`")->fetchColumn();
    echo "cases total: $cntAll\n";

    if ($casesBranchCol) {
        $st = $pdo->query("SELECT `$casesBranchCol` v, COUNT(*) c FROM `$CASES_TABLE` GROUP BY `$casesBranchCol` ORDER BY c DESC");
        echo "cases grouped by $casesBranchCol:\n";
        foreach ($st->fetchAll() as $r) {
            echo "- " . ($r['v'] ?? 'NULL') . " => " . ($r['c'] ?? 0) . "\n";
        }
        $st2 = $pdo->prepare("SELECT COUNT(*) FROM `$CASES_TABLE` WHERE `$casesBranchCol` = ?");
        $st2->execute([$branchId]);
        echo "\ncount for current branchId=$branchId : " . (int)$st2->fetchColumn() . "\n";
    } else {
        echo "WARNING: no branch column found in cases table. Showing all branches.\n";
    }
    echo "</pre>";
}

/* ===== Branch filter ===== */
$whereBranch  = "1=1";
$paramsBranch = [];

if ($casesBranchCol !== '') {
    $whereBranch  = "`$casesBranchCol` = ?";
    $paramsBranch = [$branchId];
}

/* ===== Counters ===== */
$activeCasesCount = 0;
try {
    $sql = "SELECT COUNT(*) FROM `$CASES_TABLE` WHERE $whereBranch AND UPPER(`$casesStatusCol`) IN ('NEW','WORK','COURT')";
    $st = $pdo->prepare($sql);
    $st->execute($paramsBranch);
    $activeCasesCount = n($st->fetchColumn());
} catch (Throwable $e) {
    $activeCasesCount = 0;
}

$upcomingHearingsCount = 0;

try {
    $st = $pdo->prepare("
        SELECT COUNT(*)
        FROM case_sessions cs
        LEFT JOIN cases c ON c.id = cs.case_id
        WHERE DATE(cs.session_date) >= CURDATE()
          AND COALESCE(cs.branch_id, c.branch_id) = ?
    ");

    $st->execute([$branchId]);

    $upcomingHearingsCount = (int)$st->fetchColumn();

} catch (Throwable $e) {
    $upcomingHearingsCount = 0;
}
$pendingTasksCount = 0;
if (table_exists($pdo, 'tasks')) {
    try {
        $tasksBranchCol = column_exists($pdo, 'tasks', 'branch_id') ? 'branch_id' : (column_exists($pdo, 'tasks', 'branch') ? 'branch' : '');
        $whereT = "1=1";
        $parT = [];

        if ($tasksBranchCol !== '') {
            $whereT = "`$tasksBranchCol` = ?";
            $parT = [$branchId];
        }

        $sql = "SELECT COUNT(*) FROM tasks WHERE $whereT AND UPPER(status) IN ('PENDING','OPEN')";
        $st = $pdo->prepare($sql);
        $st->execute($parT);
        $pendingTasksCount = n($st->fetchColumn());
    } catch (Throwable $e) {
        $pendingTasksCount = 0;
    }
}

$amountDue = 0.0;
if (table_exists($pdo, 'invoices')) {
    try {
        $invBranchCol = column_exists($pdo, 'invoices', 'branch_id') ? 'branch_id' : (column_exists($pdo, 'invoices', 'branch') ? 'branch' : '');
        $totalCol = column_exists($pdo, 'invoices', 'total_amount') ? 'total_amount' : (column_exists($pdo, 'invoices', 'total') ? 'total' : '');
        $paidCol  = column_exists($pdo, 'invoices', 'paid_amount') ? 'paid_amount' : (column_exists($pdo, 'invoices', 'paid') ? 'paid' : '');

        if ($totalCol !== '' && $paidCol !== '') {
            $whereI = "1=1";
            $parI = [];

            if ($invBranchCol !== '') {
                $whereI = "`$invBranchCol` = ?";
                $parI = [$branchId];
            }

            $sql = "SELECT COALESCE(SUM(GREATEST(($totalCol - $paidCol), 0)), 0)
                    FROM invoices
                    WHERE $whereI AND UPPER(status) IN ('UNPAID','PARTIAL')";
            $st = $pdo->prepare($sql);
            $st->execute($parI);
            $amountDue = (float)($st->fetchColumn() ?: 0);
        }
    } catch (Throwable $e) {
        $amountDue = 0.0;
    }
}
$amountDueLabel = money_short($amountDue);

/* ===== Latest cases ===== */
$latestCases = [];
try {
    $orderBy = $casesCreatedAt !== '' ? "`$casesCreatedAt` DESC, id DESC" : "id DESC";
    $secretSelectLatest = $casesSecretCol !== '' ? ", `$casesSecretCol` AS is_secret" : ", 0 AS is_secret";

    $sql = "SELECT
              id,
              `$casesNoCol` AS case_no,
              `$casesTitleCol` AS title,
              `$casesClientCol` AS client_name,
              `$casesStatusCol` AS status
              $secretSelectLatest
            FROM `$CASES_TABLE`
            WHERE $whereBranch
            ORDER BY $orderBy
            LIMIT 8";

    $st = $pdo->prepare($sql);
    $st->execute($paramsBranch);
    $latestCases = $st->fetchAll();
} catch (Throwable $e) {
    $latestCases = [];
}
/* ===== Upcoming sessions (FROM hearings.php logic) ===== */
$upcomingSessions = [];

try {

    $sql = "
        SELECT
            cs.id,
            cs.case_id,
            cs.session_date,
            cs.session_time,
            cs.session_type,
            cs.status,

            CASE
                WHEN cs.client_name IS NOT NULL
                     AND cs.client_name != ''
                THEN cs.client_name
                ELSE c.client_name
            END AS client_name,

            c.title AS case_title,
            c.case_no AS case_number,

            COALESCE(b2.name_ar, b.name_ar, '—') AS branch_name,

            COALESCE(c.is_secret, 0) AS is_secret

        FROM case_sessions cs

        LEFT JOIN cases c
            ON c.id = cs.case_id

        LEFT JOIN branches b
            ON b.id = c.branch_id

        LEFT JOIN branches b2
            ON b2.id = cs.branch_id

        WHERE DATE(cs.session_date) >= CURDATE()
          AND COALESCE(cs.branch_id, c.branch_id) = ?
    ";

    $params = [$branchId];

    $sql .= "
        ORDER BY
            cs.session_date ASC,
            cs.session_time ASC,
            cs.id ASC
        LIMIT 22
    ";

    $st = $pdo->prepare($sql);
    $st->execute($params);

    $upcomingSessions = $st->fetchAll(PDO::FETCH_ASSOC);

} catch (Throwable $e) {

    $upcomingSessions = [];

    if ($debug) {
        echo '<pre style="background:#200;color:#fff;padding:12px">';
        echo h($e->getMessage());
        echo '</pre>';
    }
}
/* ===== بطاقة التحفيز - نفس منطق صفحة الإحصائيات ===== */
$todayBranchId = (int)($_SESSION['branch_id'] ?? 1);
if ($todayBranchId <= 0) {
    $todayBranchId = 1;
}

$currentMonth = date('Y-m');
[$cardYear, $cardMon] = array_map('intval', explode('-', $currentMonth));

$motivationData = [
    'top_employee' => null,
    'best_branch'  => null,
    'my_rank'      => null,
    'my_cases'     => 0,
    'my_progress'  => 0,
    'branch_total' => 0,
];

$branchNames = [
    1 => 'أبوظبي',
    2 => 'دبي',
    3 => 'الشارقة',
    4 => 'العين',
];

$employeePhotoColumn = '';
if (function_exists('column_exists') && table_exists($pdo, 'users')) {
    foreach (['photo', 'avatar', 'image', 'profile_photo', 'photo_path'] as $col) {
        if (column_exists($pdo, 'users', $col)) {
            $employeePhotoColumn = $col;
            break;
        }
    }
}

try {
    $photoSelect = $employeePhotoColumn !== '' ? ", u.`$employeePhotoColumn` AS employee_photo" : ", '' AS employee_photo";
    $photoGroup  = $employeePhotoColumn !== '' ? ", u.`$employeePhotoColumn`" : "";

    /* أفضل موظف في الفرع الحالي خلال الشهر الحالي */
    $sqlTopEmployee = "
        SELECT
            c.branch_id,
            c.created_by AS user_id,
            COALESCE(u.name, u.username, CONCAT('مستخدم رقم ', c.created_by)) AS employee_name,
            COUNT(c.id) AS total_cases
            $photoSelect
        FROM cases c
        LEFT JOIN users u ON u.id = c.created_by
        WHERE c.branch_id = :branch_id
          AND MONTH(c.created_at) = :m
          AND YEAR(c.created_at) = :y
        GROUP BY c.branch_id, c.created_by, u.name, u.username $photoGroup
        ORDER BY total_cases DESC, employee_name ASC
        LIMIT 1
    ";
    $st = $pdo->prepare($sqlTopEmployee);
    $st->execute([
        ':branch_id' => $todayBranchId,
        ':m'         => $cardMon,
        ':y'         => $cardYear,
    ]);
    $motivationData['top_employee'] = $st->fetch(PDO::FETCH_ASSOC) ?: null;

    /* أفضل فرع خلال الشهر الحالي */
    $sqlBestBranch = "
        SELECT
            c.branch_id,
            COUNT(c.id) AS total_cases
        FROM cases c
        WHERE MONTH(c.created_at) = :m
          AND YEAR(c.created_at) = :y
          AND c.branch_id IN (1,2,3,4)
        GROUP BY c.branch_id
        ORDER BY total_cases DESC, c.branch_id ASC
        LIMIT 1
    ";
    $st = $pdo->prepare($sqlBestBranch);
    $st->execute([
        ':m' => $cardMon,
        ':y' => $cardYear,
    ]);
    $bestBranch = $st->fetch(PDO::FETCH_ASSOC) ?: null;
    if ($bestBranch) {
        $bestBranch['branch_name'] = $branchNames[(int)$bestBranch['branch_id']] ?? 'الفرع';
    }
    $motivationData['best_branch'] = $bestBranch;

    /* إجمالي قضايا الفرع الحالي خلال الشهر الحالي */
    $sqlBranchTotal = "
        SELECT COUNT(c.id)
        FROM cases c
        WHERE c.branch_id = :branch_id
          AND MONTH(c.created_at) = :m
          AND YEAR(c.created_at) = :y
    ";
    $st = $pdo->prepare($sqlBranchTotal);
    $st->execute([
        ':branch_id' => $todayBranchId,
        ':m'         => $cardMon,
        ':y'         => $cardYear,
    ]);
    $motivationData['branch_total'] = (int)($st->fetchColumn() ?: 0);

    /* ترتيب المستخدم الحالي في نفس الفرع خلال الشهر الحالي */
    $sqlRanking = "
        SELECT ranked.user_id, ranked.employee_name, ranked.total_cases, ranked.employee_rank
        FROM (
            SELECT
                t.user_id,
                t.employee_name,
                t.total_cases,
                (
                    SELECT COUNT(*) + 1
                    FROM (
                        SELECT
                            c2.created_by AS user_id,
                            COUNT(c2.id) AS total_cases
                        FROM cases c2
                        WHERE c2.branch_id = :branch_id2
                          AND MONTH(c2.created_at) = :m2
                          AND YEAR(c2.created_at) = :y2
                        GROUP BY c2.created_by
                    ) z
                    WHERE z.total_cases > t.total_cases
                ) AS employee_rank
            FROM (
                SELECT
                    c.created_by AS user_id,
                    COALESCE(u.name, u.username, CONCAT('مستخدم رقم ', c.created_by)) AS employee_name,
                    COUNT(c.id) AS total_cases
                FROM cases c
                LEFT JOIN users u ON u.id = c.created_by
                WHERE c.branch_id = :branch_id1
                  AND MONTH(c.created_at) = :m1
                  AND YEAR(c.created_at) = :y1
                GROUP BY c.created_by, u.name, u.username
            ) t
        ) ranked
        WHERE ranked.user_id = :user_id
        LIMIT 1
    ";
    $st = $pdo->prepare($sqlRanking);
    $st->execute([
        ':branch_id1' => $todayBranchId,
        ':m1'         => $cardMon,
        ':y1'         => $cardYear,
        ':branch_id2' => $todayBranchId,
        ':m2'         => $cardMon,
        ':y2'         => $cardYear,
        ':user_id'    => (int)($_SESSION['user_id'] ?? 0),
    ]);
    $myRank = $st->fetch(PDO::FETCH_ASSOC) ?: null;

    if ($myRank) {
        $motivationData['my_rank']  = (int)$myRank['employee_rank'];
        $motivationData['my_cases'] = (int)$myRank['total_cases'];

        $topCases = (int)($motivationData['top_employee']['total_cases'] ?? 0);
        if ($topCases > 0) {
            $motivationData['my_progress'] = min(100, (int)round(($motivationData['my_cases'] / $topCases) * 100));
        }
    }

} catch (Throwable $e) {
    $motivationData = [
        'top_employee' => null,
        'best_branch'  => null,
        'my_rank'      => null,
        'my_cases'     => 0,
        'my_progress'  => 0,
        'branch_total' => 0,
    ];

    if (!empty($debug)) {
        echo "<pre style='direction:ltr;background:#200;color:#fff;padding:12px;border-radius:10px;max-width:1100px;margin:12px auto;overflow:auto'>";
        echo "Dashboard motivation error:\n";
        echo h($e->getMessage());
        echo "</pre>";
    }
}
$closedCases = 0;
$newCasesThisMonth = 0;
$lateTasks = 0;

try {
    $st = $pdo->prepare("
        SELECT COUNT(*) 
        FROM cases
        WHERE $whereBranch
          AND UPPER(status) = 'CLOSED'
    ");
    $st->execute($paramsBranch);
    $closedCases = (int)$st->fetchColumn();

    if ($casesCreatedAt !== '') {
        $st = $pdo->prepare("
            SELECT COUNT(*)
            FROM cases
            WHERE $whereBranch
              AND `$casesCreatedAt` >= DATE_FORMAT(CURDATE(), '%Y-%m-01')
              AND `$casesCreatedAt` < DATE_ADD(LAST_DAY(CURDATE()), INTERVAL 1 DAY)
        ");
        $st->execute($paramsBranch);
        $newCasesThisMonth = (int)$st->fetchColumn();
    }

    if (table_exists($pdo, 'tasks')) {
        $tasksBranchCol = column_exists($pdo, 'tasks', 'branch_id') ? 'branch_id' : '';
        $tasksDueCol    = column_exists($pdo, 'tasks', 'due_date') ? 'due_date' : '';
        $tasksStatusCol = column_exists($pdo, 'tasks', 'status') ? 'status' : '';

        if ($tasksDueCol !== '' && $tasksStatusCol !== '') {
            $whereLateTasks = "1=1";
            $lateParams = [];

            if ($tasksBranchCol !== '') {
                $whereLateTasks = "`$tasksBranchCol` = ?";
                $lateParams[] = $branchId;
            }

            $st = $pdo->prepare("
                SELECT COUNT(*)
                FROM tasks
                WHERE $whereLateTasks
                  AND `$tasksDueCol` < CURDATE()
                  AND UPPER(`$tasksStatusCol`) NOT IN ('DONE','COMPLETED','CLOSED')
            ");
            $st->execute($lateParams);
            $lateTasks = (int)$st->fetchColumn();
        }
    }
} catch (Throwable $e) {
    $closedCases = 0;
    $newCasesThisMonth = 0;
    $lateTasks = 0;
}
$role = strtoupper((string)($_SESSION['role'] ?? ''));

if ($role === 'OWNER') {
    $performance = 100;
    $todayPoints = 0;
    $dailyTarget = 0;
    $isOwner = true;
} else {
    $isOwner = false;

    // 👇 كود الحساب الحالي (نفس اللي عندك)
    $todayPoints = 0;
    $dailyTarget = 40;

    try {
        $currentUserId = (int)($_SESSION['user_id'] ?? 0);

        if ($currentUserId > 0 && $pdo instanceof PDO) {
            $st = $pdo->prepare("
                SELECT COALESCE(SUM(
                    CASE
                        WHEN action_type = 'create_case' THEN 4
                        WHEN action_type = 'create_contract' THEN 3
                        WHEN action_type = 'create_client' THEN 2
                        WHEN action_type = 'complete_task' THEN 2
                        WHEN action_type = 'create_task' THEN 1
                        WHEN action_type LIKE 'update_%' THEN 1
                        ELSE 1
                    END
                ), 0)
                FROM system_activity_logs
                WHERE user_id = ?
                  AND DATE(created_at) = CURDATE()
            ");
            $st->execute([$currentUserId]);
            $todayPoints = (int)$st->fetchColumn();
        }
    } catch (Throwable $e) {
        $todayPoints = 0;
    }

    $performance = $dailyTarget > 0
        ? min(100, (int)round(($todayPoints / $dailyTarget) * 100))
        : 0;
}
render_layout_start('لوحة التحكم');
?>
<script>
document.body.classList.add('dashboard-body');
</script>
<style>
/* =====================================================
   HLG-ONE Executive Dashboard UI
   Clean Glass + Gold + Responsive
===================================================== */

body{
  background:
    radial-gradient(circle at 15% 12%, rgba(0,106,122,.55), transparent 34%),
    radial-gradient(circle at 85% 82%, rgba(212,175,55,.18), transparent 36%),
    linear-gradient(145deg,#011b21 0%,#003743 48%,#021d23 100%) !important;
}

.dashboard-page{
  --hlg-dark:#00424f;
  --hlg-teal:#006a7a;
  --hlg-gold:#d4af37;
  --hlg-gold-soft:#ffd76a;
  --hlg-white:rgba(255,255,255,.94);
  --hlg-muted:rgba(255,255,255,.70);
  --hlg-border:rgba(212,175,55,.45);

  width:100%;
  max-width:100%;
  color:#fff;
}

.dashboard-page *,
.dashboard-page *::before,
.dashboard-page *::after{
  box-sizing:border-box;
}

/* ================= TOPBAR ================= */

.dashboard-page .topbar-local{
  min-height:68px;
  display:flex;
  align-items:center;
  justify-content:space-between;
  gap:20px;
  padding:12px 16px;
  margin-bottom:18px;
  position:sticky;
  top:12px;
  z-index:50;
  border-radius:22px;
  border:1px solid var(--hlg-border);
  background:
    linear-gradient(145deg,rgba(255,255,255,.09),rgba(255,255,255,.035)),
    linear-gradient(135deg,rgba(0,66,79,.86),rgba(0,106,122,.45));
  box-shadow:0 18px 45px rgba(0,0,0,.24);
  backdrop-filter:blur(16px);
  -webkit-backdrop-filter:blur(16px);
}

.dashboard-page .top-left{
  display:flex;
  align-items:center;
  gap:10px;
  flex-wrap:wrap;
}

.dashboard-page .branch-dot{
  width:10px;
  height:10px;
  border-radius:50%;
  background:#cfff52;
  box-shadow:0 0 0 4px rgba(207,255,82,.14);
}

.dashboard-page .branch-name{
  font-weight:900;
  color:#fff;
  white-space:nowrap;
}

.dashboard-page .branch-switch{
  position:relative;
  display:inline-flex;
  align-items:center;
}

.dashboard-page .branch-btn{
  display:flex;
  align-items:center;
  gap:10px;
  padding:10px 14px;
  border-radius:999px;
  border:1px solid rgba(255,255,255,.12);
  background:rgba(255,255,255,.07);
  color:#fff;
  cursor:pointer;
  font-family:inherit;
  font-weight:900;
  box-shadow:0 10px 22px rgba(0,0,0,.14);
}

.dashboard-page .branch-menu{
  position:absolute;
  top:calc(100% + 10px);
  right:0;
  min-width:190px;
  padding:8px;
  display:none;
  z-index:99999;
  border-radius:16px;
  background:#082b34;
  border:1px solid rgba(212,175,55,.35);
  box-shadow:0 20px 45px rgba(0,0,0,.35);
}

.dashboard-page .branch-switch.is-open .branch-menu{
  display:block;
}

.dashboard-page .branch-choice{
  width:100%;
  padding:12px;
  border:0;
  border-radius:12px;
  background:transparent;
  color:#fff;
  cursor:pointer;
  text-align:right;
  font-family:inherit;
  font-weight:900;
}

.dashboard-page .branch-choice:hover{
  background:rgba(255,255,255,.08);
}

/* ================= PAGE HEAD ================= */

.dashboard-page .page-head{
  margin:18px 6px 14px;
  display:flex;
  justify-content:space-between;
  align-items:flex-end;
  gap:12px;
  flex-wrap:wrap;
}

.dashboard-page .welcome{
  display:flex;
  flex-direction:column;
  gap:4px;
}

.dashboard-page .welcome .hi{
  font-size:28px;
  font-weight:900;
  color:#fff;
}

.dashboard-page .welcome .sub{
  color:var(--hlg-muted);
  font-size:14px;
}

/* ================= STATS ================= */

.dashboard-page .stats{
  display:grid;
  grid-template-columns:repeat(3,minmax(0,1fr));
  gap:18px;
  margin-top:14px;
}

@media (min-width:1400px){
  .dashboard-page .stats{
    grid-template-columns:repeat(6,minmax(0,1fr));
  }
}

.dashboard-page .stat,
.dashboard-page .cardBox,
.leader-main,
.leader-stat-box,
.leader-empty{
  position:relative;
  overflow:hidden;
  border-radius:26px;
  border:1px solid var(--hlg-border);
  background:
    linear-gradient(145deg,rgba(255,255,255,.105),rgba(255,255,255,.035)),
    radial-gradient(circle at 18% 8%,rgba(255,215,106,.13),transparent 34%),
    linear-gradient(135deg,rgba(0,66,79,.80),rgba(0,106,122,.38));
  box-shadow:
    0 24px 65px rgba(0,0,0,.26),
    0 0 0 1px rgba(255,215,106,.10),
    inset 0 1px 0 rgba(255,255,255,.14),
    inset 0 0 28px rgba(212,175,55,.08);
  backdrop-filter:blur(18px) saturate(140%);
  -webkit-backdrop-filter:blur(18px) saturate(140%);
  transition:
    transform .35s cubic-bezier(.22,.61,.36,1),
    box-shadow .35s cubic-bezier(.22,.61,.36,1),
    border-color .35s ease;
}

.dashboard-page .stat:hover,
.dashboard-page .cardBox:hover,
.leader-main:hover,
.leader-stat-box:hover{
  transform:translateY(-7px) scale(1.012);
  border-color:rgba(255,215,106,.85);
  box-shadow:
    0 34px 85px rgba(0,0,0,.34),
    0 0 0 1px rgba(255,215,106,.26),
    0 0 38px rgba(212,175,55,.18),
    inset 0 1px 0 rgba(255,255,255,.18),
    inset 0 0 32px rgba(212,175,55,.10);
}

/* shine */
.dashboard-page .stat::before,
.dashboard-page .cardBox::before,
.leader-main::before,
.leader-stat-box::before,
.leader-empty::before{
  content:"";
  position:absolute;
  top:-55%;
  right:-75%;
  width:62%;
  height:210%;
  background:linear-gradient(
    115deg,
    transparent 0%,
    rgba(255,255,255,.02) 30%,
    rgba(255,255,255,.12) 43%,
    rgba(255,255,255,.30) 50%,
    rgba(255,255,255,.10) 58%,
    rgba(255,255,255,.02) 72%,
    transparent 100%
  );
  filter:blur(.6px);
  opacity:0;
  transform:translateX(150%) rotate(13deg);
  pointer-events:none;
  z-index:1;
  animation:hlgAppleShine 22s cubic-bezier(.22,.61,.36,1) infinite;
}

.dashboard-page .stat::after,
.dashboard-page .cardBox::after,
.leader-main::after,
.leader-stat-box::after,
.leader-empty::after{
  content:"";
  position:absolute;
  inset:1px;
  border-radius:inherit;
  background:
    radial-gradient(circle at 18% 10%,rgba(255,255,255,.14),transparent 28%),
    radial-gradient(circle at 88% 88%,rgba(255,215,106,.12),transparent 34%),
    linear-gradient(180deg,rgba(255,255,255,.075),transparent 45%);
  pointer-events:none;
  opacity:.72;
  z-index:0;
}

.dashboard-page .stat > *,
.dashboard-page .cardBox > *,
.leader-main > *,
.leader-stat-box > *,
.leader-empty > *{
  position:relative;
  z-index:2;
}

@keyframes hlgAppleShine{
  0%{transform:translateX(155%) rotate(13deg);opacity:0;}
  18%{opacity:0;}
  34%{opacity:.22;}
  48%{opacity:.38;}
  61%{opacity:.16;}
  74%{transform:translateX(-190%) rotate(13deg);opacity:0;}
  100%{transform:translateX(-190%) rotate(13deg);opacity:0;}
}

.dashboard-page .stat:nth-child(1)::before{animation-delay:0s;}
.dashboard-page .stat:nth-child(2)::before{animation-delay:2.7s;}
.dashboard-page .stat:nth-child(3)::before{animation-delay:5.1s;}
.dashboard-page .stat:nth-child(4)::before{animation-delay:1.4s;}
.dashboard-page .stat:nth-child(5)::before{animation-delay:4.2s;}
.dashboard-page .stat:nth-child(6)::before{animation-delay:7.3s;}

.dashboard-page .stat{
  min-height:126px;
  padding:20px;
  display:flex;
  align-items:center;
  justify-content:space-between;
  gap:12px;
}

.dashboard-page .stat .value{
  font-size:38px;
  line-height:1;
  color:var(--hlg-gold-soft);
  font-weight:900;
  text-shadow:
    0 0 14px rgba(255,215,106,.22),
    0 2px 12px rgba(0,0,0,.25);
}

.dashboard-page .stat .label{
  margin-top:8px;
  color:var(--hlg-white);
  font-size:14px;
  font-weight:800;
}

.dashboard-page .badgeIcon{
  width:58px;
  height:58px;
  border-radius:20px;
  background:linear-gradient(145deg,rgba(255,255,255,.18),rgba(255,255,255,.05));
  border:1px solid rgba(255,215,106,.35);
  box-shadow:
    0 14px 28px rgba(0,0,0,.20),
    inset 0 1px 0 rgba(255,255,255,.18);
  display:flex;
  align-items:center;
  justify-content:center;
  flex:0 0 auto;
  font-size:25px;
}

/* ================= GRID / CARDS ================= */

.dashboard-page .grid{
  margin-top:18px;
  display:grid;
  grid-template-columns:1fr 1fr;
  gap:18px;
}

.dashboard-page .cardBox{
  min-width:0;
}

.dashboard-page .cardBox .head{
  padding:18px 20px;
  display:flex;
  align-items:center;
  justify-content:space-between;
  gap:10px;
  background:rgba(0,0,0,.12);
  border-bottom:1px solid rgba(212,175,55,.22);
}

.dashboard-page .cardBox .head .title{
  font-size:21px;
  font-weight:900;
  color:#fff;
}

.dashboard-page .cardBox .head .count{
  color:var(--hlg-gold-soft);
  font-size:13px;
  font-weight:900;
  white-space:nowrap;
}

.dashboard-page .list{
  padding:8px 12px 12px;
}

.dashboard-page .rowItem{
  display:flex;
  align-items:center;
  justify-content:space-between;
  gap:10px;
  padding:14px 12px;
  border-radius:18px;
  border:1px solid transparent;
  transition:.18s ease;
}

.dashboard-page .rowItem:hover{
  background:rgba(255,255,255,.075);
  border-color:rgba(255,215,106,.28);
}

.dashboard-page .rowLeft{
  display:flex;
  align-items:center;
  gap:12px;
  min-width:0;
}

.dashboard-page .dateBox{
  min-width:110px;
  padding:10px;
  text-align:center;
  flex:0 0 auto;
  border-radius:14px;
  border:1px solid rgba(255,255,255,.10);
  background:rgba(255,255,255,.05);
}

.dashboard-page .dateBox .d{
  font-weight:900;
  color:var(--hlg-gold-soft);
}

.dashboard-page .info{
  min-width:0;
  display:flex;
  flex-direction:column;
  gap:4px;
}

.dashboard-page .info .line1{
  font-weight:900;
  color:#fff;
  white-space:nowrap;
  overflow:hidden;
  text-overflow:ellipsis;
}

.dashboard-page .info .line2{
  color:rgba(255,255,255,.68);
  font-size:13px;
  white-space:nowrap;
  overflow:hidden;
  text-overflow:ellipsis;
}

.dashboard-page .tag{
  font-size:12px;
  padding:6px 10px;
  border-radius:999px;
  border:1px solid rgba(255,255,255,.10);
  background:rgba(255,255,255,.06);
  font-weight:900;
  flex:0 0 auto;
}

.dashboard-page .tag.work{
  background:rgba(245,158,11,.14);
  border-color:rgba(245,158,11,.25);
  color:#fbbf24;
}

.dashboard-page .tag.court{
  background:rgba(59,130,246,.14);
  border-color:rgba(59,130,246,.25);
  color:#60a5fa;
}

.dashboard-page .tag.new{
  background:rgba(16,185,129,.14);
  border-color:rgba(16,185,129,.25);
  color:#34d399;
}

.dashboard-page .tag.closed{
  background:rgba(148,163,184,.14);
  border-color:rgba(148,163,184,.24);
  color:#cbd5e1;
}

.dashboard-page .actionBtn{
  width:42px;
  height:42px;
  border-radius:14px;
  border:1px solid rgba(255,215,106,.32);
  background:rgba(255,255,255,.07);
  display:flex;
  align-items:center;
  justify-content:center;
  cursor:pointer;
  transition:.18s ease;
  flex:0 0 auto;
  text-decoration:none;
  color:#fff;
  box-shadow:inset 0 1px 0 rgba(255,255,255,.10);
}

.dashboard-page .actionBtn:hover{
  background:linear-gradient(135deg,#ffd76a,#d4af37);
  color:#10262d;
  transform:translateY(-2px) scale(1.04);
}

.dashboard-page .actionBtn.blocked-secret{
  opacity:.65;
}

/* ================= LEADER CARD ================= */

.leader-card{
  display:grid;
  grid-template-columns:minmax(0,1.55fr) 320px;
  gap:16px;
  margin:0 0 16px;
}

.leader-main,
.leader-side{
  min-width:0;
}

.leader-main{
  padding:22px;
}

.leader-badge{
  display:inline-flex;
  align-items:center;
  gap:8px;
  min-height:36px;
  padding:0 14px;
  border-radius:999px;
  background:rgba(255,255,255,.07);
  border:1px solid rgba(255,215,106,.24);
  color:#fff;
  font-size:12px;
  font-weight:900;
  margin-bottom:16px;
}

.leader-head{
  display:flex;
  align-items:center;
  gap:16px;
  margin-bottom:16px;
  flex-wrap:wrap;
}

.leader-avatar{
  width:84px;
  height:84px;
  border-radius:22px;
  overflow:hidden;
  background:linear-gradient(135deg,#FFD76A,#D4AF37);
  color:#17313a;
  border:1px solid rgba(255,255,255,.14);
  box-shadow:0 12px 24px rgba(0,0,0,.18);
  display:flex;
  align-items:center;
  justify-content:center;
  flex:0 0 auto;
}

.leader-avatar img{
  width:100%;
  height:100%;
  object-fit:cover;
  display:block;
}

.leader-avatar span{
  font-size:34px;
}

.leader-copy{
  min-width:0;
  flex:1 1 auto;
}

.leader-title{
  margin:0 0 8px;
  color:var(--hlg-gold-soft);
  font-size:30px;
  line-height:1.1;
  font-weight:900;
  text-shadow:0 0 18px rgba(255,215,106,.20);
}

.leader-subtitle{
  margin:0;
  color:rgba(255,255,255,.78);
  font-size:14px;
  line-height:1.9;
  max-width:720px;
}

.leader-metrics{
  display:flex;
  flex-wrap:wrap;
  gap:10px;
  margin-bottom:16px;
}

.leader-pill{
  min-height:38px;
  padding:0 14px;
  border-radius:999px;
  display:inline-flex;
  align-items:center;
  justify-content:center;
  background:rgba(255,255,255,.07);
  border:1px solid rgba(255,215,106,.24);
  color:#fff;
  font-size:13px;
  font-weight:900;
}

.leader-progress-wrap{
  padding:16px;
  border-radius:18px;
  background:rgba(255,255,255,.05);
  border:1px solid rgba(255,255,255,.10);
}

.leader-progress-top{
  display:flex;
  align-items:center;
  justify-content:space-between;
  gap:12px;
  margin-bottom:10px;
  color:#fff;
  font-size:14px;
}

.leader-progress-top strong{
  color:var(--hlg-gold-soft);
}

.leader-progress{
  height:14px;
  border-radius:999px;
  background:rgba(255,255,255,.10);
  overflow:hidden;
}

.leader-progress > span{
  display:block;
  height:100%;
  border-radius:999px;
  background:linear-gradient(90deg,#d7ff58 0%,#bff56f 45%,#ffffff 100%);
  box-shadow:0 0 18px rgba(215,255,88,.22);
}

.leader-note{
  margin-top:10px;
  color:rgba(255,255,255,.76);
  font-size:13px;
  line-height:1.8;
}

.leader-side{
  display:grid;
  gap:14px;
  align-content:start;
}

.leader-stat-box{
  padding:18px;
}

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

.leader-stat-value{
  color:var(--hlg-gold-soft);
  font-size:28px;
  font-weight:900;
  line-height:1.1;
  text-shadow:0 0 18px rgba(255,215,106,.20);
}

.leader-stat-sub{
  margin-top:8px;
  color:rgba(255,255,255,.74);
  font-size:13px;
  line-height:1.7;
}

.leader-btn{
  position:relative;
  overflow:hidden;
  min-height:48px;
  border-radius:16px;
  display:flex;
  align-items:center;
  justify-content:center;
  text-decoration:none;
  border:1px solid rgba(255,255,255,.25);
  background:linear-gradient(90deg,#ffd76a 0%,#d4af37 48%,#ffe08a 100%);
  color:#10262d;
  font-size:14px;
  font-weight:900;
  box-shadow:
    0 18px 36px rgba(0,0,0,.20),
    0 0 25px rgba(212,175,55,.25);
  transition:.2s ease;
}

.leader-btn:hover{
  transform:translateY(-2px);
}

.leader-btn::after{
  content:"";
  position:absolute;
  top:0;
  right:-70%;
  width:45%;
  height:100%;
  background:linear-gradient(120deg,transparent,rgba(255,255,255,.58),transparent);
  transform:skewX(-18deg);
  animation:hlgBtnShine 5.8s ease-in-out infinite;
}

@keyframes hlgBtnShine{
  0%,35%{right:-70%;opacity:0;}
  50%{opacity:.75;}
  75%,100%{right:130%;opacity:0;}
}

.leader-empty{
  padding:22px;
}

.leader-empty h3{
  margin:0 0 8px;
  font-size:24px;
  font-weight:900;
}

.leader-empty p{
  margin:0;
  color:rgba(255,255,255,.76);
  line-height:1.8;
}

/* ================= ONLINE BOX ================= */

.online-box{
  margin-top:14px;
  padding:14px 16px;
  border-radius:20px;
  border:1px solid rgba(212,175,55,.35);
  background:linear-gradient(135deg,rgba(255,255,255,.06),rgba(255,255,255,.025));
}

.online-head{
  color:#fff;
  font-size:22px;
  font-weight:900;
  margin-bottom:12px;
}

.online-list{
  display:flex;
  flex-direction:column;
  gap:10px;
}

.online-item{
  display:flex;
  align-items:center;
  justify-content:flex-start;
  gap:10px;
  background:rgba(255,255,255,.06);
  border:1px solid rgba(255,255,255,.10);
  border-radius:14px;
  padding:10px 14px;
}

.online-dot{
  width:10px;
  height:10px;
  border-radius:50%;
  background:#63d471;
  box-shadow:0 0 10px rgba(99,212,113,.7);
  flex:0 0 10px;
}

.online-name{
  color:#fff;
  font-size:15px;
  font-weight:800;
}

.online-empty{
  background:rgba(255,255,255,.06);
  border:1px dashed rgba(255,255,255,.16);
  border-radius:12px;
  padding:12px 14px;
  color:#d9e4e7;
  font-size:14px;
}

/* ================= FOOTER ================= */

.footerNote{
  margin-top:18px;
  padding:14px 18px;
  border-radius:18px;
  border:1px solid rgba(212,175,55,.30);
  background:linear-gradient(145deg,rgba(255,255,255,.075),rgba(255,255,255,.03));
  box-shadow:
    0 18px 40px rgba(0,0,0,.20),
    inset 0 1px 0 rgba(255,255,255,.10);
  color:rgba(255,255,255,.75);
  font-size:13px;
}

.footer-inner{
  display:flex;
  justify-content:space-between;
  align-items:center;
  flex-wrap:wrap;
  gap:10px;
}

.footerNote .footer-copy,
.footer-system{
  color:var(--hlg-gold-soft);
  font-weight:800;
}

/* ================= SECRET MODAL ================= */

.secret-modal{
  position:fixed;
  inset:0;
  background:rgba(15,23,42,.45);
  display:none;
  align-items:center;
  justify-content:center;
  z-index:99999;
  padding:20px;
}

.secret-modal.show{
  display:flex;
}

.secret-box{
  width:min(420px,100%);
  background:#fff;
  border-radius:24px;
  padding:28px 24px;
  text-align:center;
  box-shadow:0 30px 80px rgba(0,0,0,.25);
  border:1px solid #fecaca;
  animation:secretPop .18s ease;
}

.secret-icon{
  width:76px;
  height:76px;
  margin:0 auto 14px;
  border-radius:20px;
  display:flex;
  align-items:center;
  justify-content:center;
  font-size:36px;
  background:#fff1f2;
  border:1px solid #fecaca;
}

.secret-title{
  margin:0 0 10px;
  font-size:24px;
  font-weight:900;
  color:#991b1b;
}

.secret-text{
  margin:0;
  color:#475569;
  line-height:1.9;
  font-size:14px;
}

.secret-actions{
  display:flex;
  justify-content:center;
  gap:10px;
  flex-wrap:wrap;
  margin-top:18px;
}

.secret-btn{
  min-width:110px;
  height:44px;
  border:none;
  border-radius:14px;
  cursor:pointer;
  font-family:inherit;
  font-weight:900;
  font-size:14px;
}

.secret-btn.primary{
  background:#b91c1c;
  color:#fff;
}

.secret-btn.light{
  background:#f8fafc;
  color:#0f172a;
  border:1px solid #e2e8f0;
}

@keyframes secretPop{
  from{opacity:0;transform:translateY(8px) scale(.97);}
  to{opacity:1;transform:translateY(0) scale(1);}
}

/* ================= RESPONSIVE ================= */

@media (max-width:1200px){
  .dashboard-page .stats{
    grid-template-columns:repeat(2,minmax(0,1fr));
  }

  .dashboard-page .grid{
    grid-template-columns:1fr;
  }
}

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

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

  .leader-avatar{
    width:72px;
    height:72px;
  }
}

@media (max-width:820px){
  .dashboard-page .topbar-local{
    align-items:flex-start;
    flex-direction:column;
    gap:12px;
  }

  .dashboard-page .stats{
    grid-template-columns:1fr;
  }

  .dashboard-page .page-head{
    align-items:flex-start;
  }

  .dashboard-page .welcome .hi{
    font-size:24px;
  }

  .dashboard-page .stat{
    min-height:112px;
  }

  .dashboard-page .stat .value{
    font-size:32px;
  }

  .dashboard-page .badgeIcon{
    width:50px;
    height:50px;
  }

  .dashboard-page .rowItem{
    align-items:flex-start;
  }

  .dashboard-page .dateBox{
    min-width:86px;
  }
}

@media (max-width:700px){
  .footer-inner{
    flex-direction:column;
    text-align:center;
  }

  .dashboard-page .cardBox .head{
    align-items:flex-start;
    flex-direction:column;
  }

  .dashboard-page .rowLeft{
    align-items:flex-start;
  }
}
.performance-box{
  padding:16px;
  border-radius:18px;
  background:linear-gradient(135deg,rgba(255,255,255,.08),rgba(255,255,255,.03));
  border:1px solid rgba(212,175,55,.35);
  color:#fff;
}

.performance-box .progress{
  height:12px;
  background:rgba(255,255,255,.12);
  border-radius:999px;
  overflow:hidden;
  margin-bottom:10px;
}

.performance-box .progress span{
  display:block;
  height:100%;
  border-radius:999px;
  transition:width .4s ease;
}

.performance-box p{
  margin:0;
  font-weight:800;
}

.performance-box small{
  color:rgba(255,255,255,.7);
}
/* =========================
   LEGEND STATUS (ULTRA UI)
========================= */

.dashboard-page .tag{
  position:relative;
  display:inline-flex;
  align-items:center;
  justify-content:center;
  min-width:110px;
  height:36px;
  padding:0 16px;

  border-radius:999px;
  font-size:13px;
  font-weight:900;
  letter-spacing:.3px;

  border:1px solid transparent;
  overflow:hidden;

  backdrop-filter:blur(10px);
  -webkit-backdrop-filter:blur(10px);

  box-shadow:
    0 10px 25px rgba(0,0,0,.25),
    inset 0 1px 0 rgba(255,255,255,.2);

  transition:all .25s ease;
}

/* لمعة متحركة */
.dashboard-page .tag::after{
  content:"";
  position:absolute;
  top:0;
  left:-70%;
  width:50%;
  height:100%;
  background:linear-gradient(
    120deg,
    transparent,
    rgba(255,255,255,.55),
    transparent
  );
  transform:skewX(-20deg);
  animation:tagShine 4s infinite;
}

@keyframes tagShine{
  0%{ left:-70%; opacity:0 }
  40%{ opacity:.8 }
  100%{ left:130%; opacity:0 }
}

/* ================= الحالات ================= */

/* جديدة */
.dashboard-page .tag.new{
  background:linear-gradient(135deg,#16a34a,#22c55e);
  color:#ecfdf5;
  border-color:rgba(34,197,94,.45);

  box-shadow:
    0 12px 28px rgba(34,197,94,.35),
    0 0 18px rgba(34,197,94,.25);
}

/* قيد العمل */
.dashboard-page .tag.work{
  background:linear-gradient(135deg,#f59e0b,#fbbf24);
  color:#1a1400;
  border-color:rgba(251,191,36,.45);

  box-shadow:
    0 12px 28px rgba(251,191,36,.35),
    0 0 18px rgba(251,191,36,.25);
}

/* في المحكمة */
.dashboard-page .tag.court{
  background:linear-gradient(135deg,#3b82f6,#60a5fa);
  color:#ecf3ff;
  border-color:rgba(96,165,250,.45);

  box-shadow:
    0 12px 28px rgba(96,165,250,.35),
    0 0 18px rgba(96,165,250,.25);
}

/* مغلقة */
.dashboard-page .tag.closed{
  background:linear-gradient(135deg,#64748b,#94a3b8);
  color:#f1f5f9;
  border-color:rgba(148,163,184,.45);

  box-shadow:
    0 10px 22px rgba(148,163,184,.25);
}

/* hover */
.dashboard-page .tag:hover{
  transform:translateY(-2px) scale(1.05);
}
/* تمديد الهيدر بالكامل */
.dashboard-page .topbar-local{
  width:100% !important;
  max-width:100% !important;

  display:flex !important;
  align-items:center !important;
  justify-content:space-between !important;

  flex-wrap:nowrap !important; /* صف واحد */
  gap:14px !important;

  padding:16px 20px !important;
}
@media (max-width: 768px) {
  .layout-branch-form {
    transform: translateX(-20px);
  }
}
/* بعد يومين - أصفر */
.dashboard-page .rowItem.session-alert{
  border:1px solid rgba(255,215,106,.9);
  background:rgba(255,215,106,.10);
  animation:yellowPulse 2s infinite;
}

.dashboard-page .rowItem.session-alert .dateBox{
  background:rgba(255,215,106,.18);
  border-color:rgba(255,215,106,.9);
}

/* غداً - برتقالي */
.dashboard-page .rowItem.session-warning{
  border:1px solid rgba(255,149,0,.95);
  background:rgba(255,149,0,.12);
  animation:orangePulse 1.6s infinite;
}

.dashboard-page .rowItem.session-warning .dateBox{
  background:rgba(255,149,0,.18);
  border-color:rgba(255,149,0,.95);
}

/* اليوم - أحمر */
.dashboard-page .rowItem.session-danger{
  border:1px solid rgba(255,59,48,.95);
  background:rgba(255,59,48,.14);
  animation:redPulse 1.1s infinite;
}

.dashboard-page .rowItem.session-danger .dateBox{
  background:rgba(255,59,48,.18);
  border-color:rgba(255,59,48,.95);
}

/* البادجات */
.today-label{
  margin-top:6px;
  font-size:10px;
  font-weight:900;
}

.today-label.alert{
  color:#ffd76a;
}

.today-label.warning{
  color:#ff9500;
}

.today-label.danger{
  color:#ff3b30;
}

/* أنيميشن */
@keyframes yellowPulse{
  0%,100%{
    box-shadow:0 0 12px rgba(255,215,106,.25);
  }
  50%{
    box-shadow:0 0 28px rgba(255,215,106,.7);
  }
}

@keyframes orangePulse{
  0%,100%{
    box-shadow:0 0 12px rgba(255,149,0,.25);
  }
  50%{
    box-shadow:0 0 30px rgba(255,149,0,.85);
  }
}

@keyframes redPulse{
  0%,100%{
    box-shadow:0 0 12px rgba(255,59,48,.25);
  }
  50%{
    box-shadow:0 0 36px rgba(255,59,48,.95);
  }
}
</style>
 
<?php
$topEmployee = $motivationData['top_employee'] ?? null;
$bestBranch  = $motivationData['best_branch'] ?? null;
$myRank      = $motivationData['my_rank'] ?? null;
$myCases     = (int)($motivationData['my_cases'] ?? 0);
$myProgress  = (int)($motivationData['my_progress'] ?? 0);
$branchTotal = (int)($motivationData['branch_total'] ?? 0);

$employeeName  = (string)($topEmployee['employee_name'] ?? 'لا يوجد متصدر حالياً');
$employeeCases = (int)($topEmployee['total_cases'] ?? 0);
$employeePhoto = trim((string)($topEmployee['employee_photo'] ?? ''));

if ($employeePhoto !== '' && !preg_match('~^https?://~i', $employeePhoto)) {
    $employeePhoto = app_url(ltrim($employeePhoto, '/'));
}

$displayBranchName = $currentBranchName ?: 'الفرع الحالي';
$bestBranchName    = (string)($bestBranch['branch_name'] ?? '—');
$bestBranchCases   = (int)($bestBranch['total_cases'] ?? 0);
?>


<div class="online-box" id="onlineBox">

<div class="dashboard-page">
  <div class="topbar-local">
    <div class="top-left">
      <?php if ($role === 'OWNER'): ?>
        <div class="branch-switch" id="branchWrap">
          <button class="branch-btn" type="button" id="branchBtn" aria-haspopup="true" aria-expanded="false">
            <span class="branch-dot"></span>
            <span class="branch-name"><?= h($displayBranchName) ?></span>
            <span style="opacity:.8">▾</span>
          </button>

          <div class="branch-menu" id="branchMenu" role="menu" aria-label="Branch menu">
            <form action="<?= h(u('branch_switch.php')) ?>" method="post" style="margin:0;">
              <input type="hidden" name="branch_id" value="1">
              <button type="submit" class="branch-choice">أبوظبي</button>
            </form>

            <form action="<?= h(u('branch_switch.php')) ?>" method="post" style="margin:0;">
              <input type="hidden" name="branch_id" value="2">
              <button type="submit" class="branch-choice">دبي</button>
            </form>

            <form action="<?= h(u('branch_switch.php')) ?>" method="post" style="margin:0;">
              <input type="hidden" name="branch_id" value="3">
              <button type="submit" class="branch-choice">الشارقة</button>
            </form>

            <form action="<?= h(u('branch_switch.php')) ?>" method="post" style="margin:0;">
              <input type="hidden" name="branch_id" value="4">
              <button type="submit" class="branch-choice">العين</button>
            </form>
          </div>
        </div>
      <?php else: ?>
        <div style="display:flex;align-items:center;gap:10px;">
          <span class="branch-dot"></span>
          <span class="branch-name"><?= h($displayBranchName) ?></span>
        </div>
      <?php endif; ?>
    </div>
  </div>

  <?php if ($topEmployee): ?>
  <section class="leader-card">
    <div class="leader-main">
      <div class="leader-badge">
        <span>🏆</span>
        <span>المتصدر الحالي</span>
      </div>

      <div class="leader-head">
        <div class="leader-avatar">
          <?php if ($employeePhoto !== ''): ?>
            <img src="<?= h($employeePhoto) ?>" alt="<?= h($employeeName) ?>">
          <?php else: ?>
            <span>⚖️</span>
          <?php endif; ?>
        </div>

        <div class="leader-copy">
          <h2 class="leader-title"><?= h($employeeName) ?></h2>
          <p class="leader-subtitle">
            المتصدر الحالي في فرع <?= h($displayBranchName) ?> خلال هذا الشهر بناءً على إجمالي القضايا المسجلة في النظام.
          </p>
        </div>
      </div>

      <div class="leader-metrics">
        <span class="leader-pill">إجمالي قضاياه: <?= (int)$employeeCases ?></span>
        <span class="leader-pill">أفضل فرع: <?= h($bestBranchName) ?></span>
        <span class="leader-pill">إجمالي قضايا الفرع: <?= (int)$branchTotal ?></span>
        <?php if ($myRank !== null): ?>
          <span class="leader-pill">ترتيبك الحالي: #<?= (int)$myRank ?></span>
        <?php endif; ?>
      </div>

      <div class="leader-progress-wrap">
        <div class="leader-progress-top">
          <span>مستوى تقدمك نحو الصدارة</span>
          <strong><?= $myRank !== null ? (int)$myProgress . '%' : '0%' ?></strong>
        </div>

        <div class="leader-progress">
          <span style="width:<?= $myRank !== null ? (int)$myProgress : 0 ?>%"></span>
        </div>

        <div class="leader-note">
          <?php if ($myRank !== null): ?>
            لديك <?= (int)$myCases ?> قضية خلال هذا الشهر في هذا الفرع. استمر للوصول إلى المركز الأول.
          <?php else: ?>
            لا يوجد لك ترتيب محسوب حالياً. ابدأ بإضافة القضايا لتظهر في لوحة المنافسة.
          <?php endif; ?>
        </div>
      </div>
    </div>

    <aside class="leader-side">
      <div class="leader-stat-box">
        <div class="leader-stat-label">أفضل فرع هذا الشهر</div>
        <div class="leader-stat-value"><?= h($bestBranchName) ?></div>
        <div class="leader-stat-sub">بعدد <?= (int)$bestBranchCases ?> قضية</div>
      </div>

      <div class="leader-stat-box">
        <div class="leader-stat-label">ترتيبك الحالي</div>
        <div class="leader-stat-value"><?= $myRank !== null ? '#' . (int)$myRank : '—' ?></div>
        <div class="leader-stat-sub">
          <?= $myRank !== null ? 'إجمالي قضاياك: ' . (int)$myCases : 'لم يتم احتساب ترتيبك بعد' ?>
        </div>
      </div>

      <a href="<?= h(u('employee_statistics.php')) ?>" class="leader-btn">عرض الإحصائيات الكاملة</a>
    </aside>
  </section>
<?php else: ?>
  <section class="leader-empty">
    <h3>المتصدر الحالي</h3>
    <p>لا توجد بيانات كافية لعرض المتصدر الحالي لهذا الشهر.</p>
  </section>
<?php endif; ?>

 <section class="stats">

  <div class="stat">
    <div>
      <div class="value"><?= (int)$upcomingHearingsCount ?></div>
      <div class="label">جلسات قادمة</div>
    </div>
    <div class="badgeIcon">📅</div>
  </div>

  <div class="stat">
    <div>
      <div class="value"><?= (int)$pendingTasksCount ?></div>
      <div class="label">مهام معلقة</div>
    </div>
    <div class="badgeIcon">🧾</div>
  </div>

  <div class="stat">
    <div>
      <div class="value"><?= (int)$activeCasesCount ?></div>
      <div class="label">قضايا نشطة</div>
    </div>
    <div class="badgeIcon">⚖️</div>
  </div>

  <div class="stat">
    <div>
      <div class="value"><?= (int)$closedCases ?></div>
      <div class="label">قضايا مغلقة</div>
    </div>
    <div class="badgeIcon">✅</div>
  </div>

  <div class="stat">
    <div>
      <div class="value"><?= (int)$newCasesThisMonth ?></div>
      <div class="label">قضايا جديدة هذا الشهر</div>
    </div>
    <div class="badgeIcon">🆕</div>
  </div>

  <div class="stat">
    <div>
      <div class="value"><?= (int)$lateTasks ?></div>
      <div class="label">مهام متأخرة</div>
    </div>
    <div class="badgeIcon">⚠️</div>
  </div>

</section>
  <div id="secretModal" class="secret-modal" aria-hidden="true">
    <div class="secret-box" role="dialog" aria-modal="true" aria-labelledby="secretModalTitle">
      <div class="secret-icon">🔒</div>
      <h3 class="secret-title" id="secretModalTitle">وصول غير متاح</h3>
      <p class="secret-text">
        هذه القضية مصنفة كقضية سرية، ولا يمكن فتحها من هذا الحساب.
      </p>

      <div class="secret-actions">
        <button type="button" class="secret-btn primary" onclick="closeSecretModal()">حسناً</button>
        <button type="button" class="secret-btn light" onclick="closeSecretModal()">إغلاق</button>
      </div>
    </div>
  </div>

  <section class="grid">

  <div class="cardBox">
    <div class="head">
      <div class="title">الجلسات القادمة</div>
      <div class="count"><?= count($upcomingSessions) ?> جلسات</div>
    </div>

    <div class="list">
      <?php if (empty($upcomingSessions)): ?>

        <div style="padding:14px 10px;color:rgba(255,255,255,.68);">
          لا توجد جلسات قادمة لهذا الفرع حالياً.
        </div>

      <?php else: ?>

        <?php foreach ($upcomingSessions as $s): ?>
          <?php
            $date = trim((string)($s['session_date'] ?? ''));
            $caseTitle = (string)($s['case_title'] ?? 'جلسة');
            $caseId2 = (int)($s['case_id'] ?? 0);

            $isSecretSessionCase = !empty($s['is_secret']);
            $isBlockedSessionCase = ($isSecretSessionCase && !$isOwner);

            $sessionDateOnly = $date !== '' ? substr($date, 0, 10) : '';
            $daysLeft = 999;

            if ($sessionDateOnly !== '') {
                $todayTs = strtotime(date('Y-m-d'));
                $sessionTs = strtotime($sessionDateOnly);

                if ($todayTs !== false && $sessionTs !== false) {
                    $daysLeft = (int)floor(($sessionTs - $todayTs) / 86400);
                }
            }

            $sessionClass = '';
            $sessionLabel = '';

            if ($daysLeft === 0) {
                $sessionClass = 'session-danger';
                $sessionLabel = 'جلسة اليوم';
            } elseif ($daysLeft === 1) {
                $sessionClass = 'session-warning';
                $sessionLabel = 'غداً';
            } elseif ($daysLeft === 2) {
                $sessionClass = 'session-alert';
                $sessionLabel = 'بعد يومين';
            }
          ?>

          <div class="rowItem <?= h($sessionClass) ?>">
            <div class="rowLeft">

              <div class="dateBox">
                <div class="d"><?= h($date) ?></div>

                <?php if ($sessionLabel !== ''): ?>
                  <div class="session-label <?= h($sessionClass) ?>">
                    <?= h($sessionLabel) ?>
                  </div>
                <?php endif; ?>
              </div>

              <div class="info">
                <div class="line1"><?= h($caseTitle) ?></div>
              </div>

            </div>

            <?php if ($isBlockedSessionCase): ?>
              <a class="actionBtn blocked-secret" href="#" onclick="openSecretModal(event)" title="قضية سرية">↗</a>
            <?php else: ?>
              <a class="actionBtn" href="<?= $caseId2 ? h(u('case_view.php?id=' . $caseId2)) : '#' ?>" title="فتح">↗</a>
            <?php endif; ?>
          </div>

        <?php endforeach; ?>

      <?php endif; ?>
    </div>
  </div>
    <div class="cardBox">
      <div class="head">
        <div class="title">أحدث القضايا</div>
        <div class="count"><?= count($latestCases) ?> قضايا</div>
      </div>

      <div class="list">
        <?php if (empty($latestCases)): ?>
          <div style="padding:14px 10px;color:rgba(255,255,255,.68);">لا توجد قضايا لهذا الفرع حتى الآن.</div>
        <?php else: ?>
          <?php foreach ($latestCases as $c): ?>
            <?php
              $id = (int)($c['id'] ?? 0);
              $title = (string)($c['title'] ?? 'قضية');
              $code = (string)($c['case_no'] ?? ('HLG-' . $id));
              $client = (string)($c['client_name'] ?? '');
              [$tagText, $tagClass] = case_status_label((string)($c['status'] ?? ''));
              $isSecretLatestCase = !empty($c['is_secret']);
              $isBlockedLatestCase = ($isSecretLatestCase && !$isOwner);
            ?>
            <div class="rowItem">
              <div class="rowLeft">
                <span class="tag <?= h($tagClass) ?>"><?= h($tagText) ?></span>
                <div class="info">
                  <div class="line1"><?= h($title) ?></div>
                  <div class="line2"><?= h($code) ?><?php if ($client !== ''): ?> • <?= h($client) ?><?php endif; ?></div>
                </div>
              </div>

              <?php if ($isBlockedLatestCase): ?>
                <a class="actionBtn blocked-secret" href="#" onclick="openSecretModal(event)" title="قضية سرية">📁</a>
              <?php else: ?>
                <a class="actionBtn" href="<?= h(u('case_files.php?id=' . $id)) ?>" title="فتح">📁</a>
              <?php endif; ?>
            </div>
          <?php endforeach; ?>
        <?php endif; ?>
      </div>
    </div>
  </section>

  <div class="footerNote">
  <div class="footer-inner">
    <span class="footer-copy">
      © <?= date('Y') ?> مجموعة حمدان القانونية – جميع الحقوق محفوظة
    </span>

    <span class="footer-system">
      HLG-ONE Legal System
    </span>
  </div>
</div>
</div>
<script>
(function(){
  const wrap = document.getElementById('branchWrap');
  const btn  = document.getElementById('branchBtn');
  const menu = document.getElementById('branchMenu');

  function openSecretModal(e){
    if (e) e.preventDefault();
    const modal = document.getElementById('secretModal');
    if (!modal) return;
    modal.classList.add('show');
    modal.setAttribute('aria-hidden', 'false');
  }

  function closeSecretModal(){
    const modal = document.getElementById('secretModal');
    if (!modal) return;
    modal.classList.remove('show');
    modal.setAttribute('aria-hidden', 'true');
  }

  window.openSecretModal = openSecretModal;
  window.closeSecretModal = closeSecretModal;

  if (wrap && btn && menu) {
    function openMenu() {
      wrap.classList.add('is-open');
      btn.setAttribute('aria-expanded', 'true');
    }

    function closeMenu() {
      wrap.classList.remove('is-open');
      btn.setAttribute('aria-expanded', 'false');
    }

    function toggleMenu() {
      if (wrap.classList.contains('is-open')) {
        closeMenu();
      } else {
        openMenu();
      }
    }

    btn.addEventListener('click', function(e){
      e.stopPropagation();
      toggleMenu();
    });

    document.addEventListener('click', function(e){
      if (!wrap.contains(e.target)) {
        closeMenu();
      }

      const modal = document.getElementById('secretModal');
      if (modal && modal.classList.contains('show') && e.target === modal) {
        closeSecretModal();
      }
    });

    menu.addEventListener('click', function(e){
      e.stopPropagation();
    });

    document.addEventListener('keydown', function(e){
      if (e.key === 'Escape') {
        closeMenu();
        closeSecretModal();
      }
    });
  } else {
    document.addEventListener('click', function(e){
      const modal = document.getElementById('secretModal');
      if (!modal || !modal.classList.contains('show')) return;
      if (e.target === modal) {
        closeSecretModal();
      }
    });

    document.addEventListener('keydown', function(e){
      if (e.key === 'Escape') {
        closeSecretModal();
      }
    });
  }
})();
</script>
<script>
function refreshOnlineEmployees() {
  fetch('online_employees_widget.php', {
    method: 'GET',
    credentials: 'same-origin'
  })
  .then(response => response.text())
  .then(html => {
    const box = document.getElementById('onlineList');
    if (box) {
      box.innerHTML = html;
    }
  })
  .catch(() => {});
}

setInterval(refreshOnlineEmployees, 20000);
</script>
<script>
function updateActivity(){
    fetch('update_activity.php', {
        method:'GET',
        credentials:'same-origin'
    }).catch(()=>{});
}

setInterval(updateActivity,20000);
updateActivity();

</script>
<?php render_layout_end(); ?>