<?php

// inc/layout.php
// لا تضع declare(strict_types=1) هنا لتجنب BOM/whitespace

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

/* =========================================================
   Helpers
========================================================= */

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

if (!function_exists('current_user_id')) {
    function current_user_id(): int
    {
        return (int)($_SESSION['user_id'] ?? 0);
    }
}

if (!function_exists('current_user_name')) {
    function current_user_name(): string
    {
        $name = trim((string)($_SESSION['name'] ?? ''));
        if ($name !== '') {
            return $name;
        }

        $fullName = trim((string)($_SESSION['full_name'] ?? ''));
        if ($fullName !== '') {
            return $fullName;
        }

        $username = trim((string)($_SESSION['username'] ?? ''));
        if ($username !== '') {
            return $username;
        }

        return 'المستخدم';
    }
}

/* =========================================================
   صورة الموظف
========================================================= */
if (!function_exists('default_employee_photo')) {
    function default_employee_photo(): string
    {
        return 'https://hamdanlegalgroup.ae/wp-content/uploads/2026/02/mamad.webp';
    }
}

if (!function_exists('current_user_photo')) {
    function current_user_photo(): string
    {
        $username = trim(mb_strtolower((string)($_SESSION['username'] ?? '')));
        $name     = trim((string)($_SESSION['name'] ?? ''));
        $fullName = trim((string)($_SESSION['full_name'] ?? ''));

        $photosByUsername = [
            's0040'         => 'https://hamdanlegalgroup.ae/wp-content/uploads/2025/10/py-1.png',
            'z0019'       => 'https://hamdanlegalgroup.ae/wp-content/uploads/2025/10/مستشار-اشرف-ربيع-1.webp',
            'adel'         => 'https://hamdanlegalgroup.ae/wp-content/uploads/2025/08/aad-1.png',
            'r0002'         => 'https://hamdanlegalgroup.ae/wp-content/uploads/2025/07/1-1.webp',
            'm0004'        => 'https://hamdanlegalgroup.ae/wp-content/uploads/2025/10/mazy-1.png',
            'w0014'       => 'https://hamdanlegalgroup.ae/wp-content/uploads/2026/02/WALEED.webp',
            'e0015'         => 'https://hamdanlegalgroup.ae/wp-content/uploads/2026/02/EMAN.webp',
            'e0010'        => 'https://hamdanlegalgroup.ae/wp-content/uploads/2025/07/4-1.webp',
            'i0003'        => 'https://hamdanlegalgroup.ae/wp-content/uploads/2025/07/8.22webp.webp',
            'a0012'        => 'https://hamdanlegalgroup.ae/wp-content/uploads/2025/07/mh-1.webp',
            'hk'        => 'https://hamdanlegalgroup.ae/wp-content/uploads/2026/03/hk.png',

        ];

        $photosByName = [
            'سيف ا'    => 'https://hamdanlegalgroup.ae/wp-content/uploads/2025/10/py-1.png',
            'المستشار اشرف'     => 'https://hamdanlegalgroup.ae/wp-content/uploads/2025/10/مستشار-اشرف-ربيع-1.webp',
            'عادل الكعبي'   => 'https://hamdanlegalgroup.ae/wp-content/uploads/2025/08/aad-1.png',
            'رولا منير'     => 'https://hamdanlegalgroup.ae/wp-content/uploads/2025/07/1-1.webp',
            'مازن عامر'     => 'https://hamdanlegalgroup.ae/wp-content/uploads/2025/10/mazy-1.png',
            'وليد حامد'     => 'https://hamdanlegalgroup.ae/wp-content/uploads/2026/02/WALEED.webp',
            'إيمان صبيان'   => 'https://hamdanlegalgroup.ae/wp-content/uploads/2026/02/EMAN.webp',
            'محمد الكعبي'   => 'https://hamdanlegalgroup.ae/wp-content/uploads/2026/02/mamad.webp',
        ];

        if ($username !== '' && isset($photosByUsername[$username])) {
            return $photosByUsername[$username];
        }

        if ($name !== '' && isset($photosByName[$name])) {
            return $photosByName[$name];
        }

        if ($fullName !== '' && isset($photosByName[$fullName])) {
            return $photosByName[$fullName];
        }

        return default_employee_photo();
    }
}

if (!function_exists('current_branch_id')) {
    function current_branch_id(): int
    {
        return (int)($_SESSION['branch_id'] ?? 1);
    }
}

if (!function_exists('current_role')) {
    function current_role(): string
    {
        return strtoupper(trim((string)($_SESSION['role'] ?? 'STAFF')));
    }
}

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

if (!function_exists('is_owner')) {
    function is_owner(): bool
    {
        return current_role() === 'OWNER';
    }
}

if (!function_exists('branch_name_ar')) {
    function branch_name_ar(int $branchId): string
    {
        switch ($branchId) {
            case 2:
                return 'دبي';
            case 3:
                return 'الشارقة';
            case 4:
                return 'العين';
            default:
                return 'أبوظبي';
        }
    }
}

if (!function_exists('branch_name_en')) {
    function branch_name_en(int $branchId): string
    {
        switch ($branchId) {
            case 2:
                return 'Dubai';
            case 3:
                return 'Sharjah';
            case 4:
                return 'Al Ain';
            default:
                return 'Abu Dhabi';
        }
    }
}

if (!function_exists('current_branch_name_ar')) {
    function current_branch_name_ar(): string
    {
        return branch_name_ar(current_branch_id());
    }
}

if (!function_exists('current_branch_name_en')) {
    function current_branch_name_en(): string
    {
        return branch_name_en(current_branch_id());
    }
}

/* =========================================================
   base_path / u
========================================================= */

if (!function_exists('layout_base_path')) {
    function layout_base_path(): string
    {
        $script = str_replace('\\', '/', (string)($_SERVER['SCRIPT_NAME'] ?? ''));
        $pos = strpos($script, '/HLG-Justice-Hub/');
        if ($pos !== false) {
            return '/HLG-Justice-Hub/';
        }
        return '/';
    }
}

if (!function_exists('u')) {
    function u(string $path = ''): string
    {
        return rtrim(layout_base_path(), '/') . '/' . ltrim($path, '/');
    }
}

/* =========================================================
   current path helpers
========================================================= */

if (!function_exists('current_script_rel')) {
    function current_script_rel(): string
    {
        $script = str_replace('\\', '/', (string)($_SERVER['SCRIPT_NAME'] ?? ''));
        $base   = rtrim(layout_base_path(), '/');

        if ($base !== '' && $base !== '/' && str_starts_with($script, $base . '/')) {
            $script = substr($script, strlen($base) + 1);
        } else {
            $script = ltrim($script, '/');
        }

        return trim($script, '/');
    }
}

if (!function_exists('nav_active')) {
    function nav_active(string $target): bool
    {
        $current = current_script_rel();
        $target  = trim(str_replace('\\', '/', $target), '/');

        if ($current === $target) {
            return true;
        }

        if ($target === 'hearings/hearings.php' && str_starts_with($current, 'hearings/')) {
            return true;
        }

        if ($target === 'financial/dashboard.php' && str_starts_with($current, 'financial/')) {
            return true;
        }

        if ($target === 'cases.php' && in_array($current, [
            'cases.php',
            'case_add.php',
            'case_edit.php',
            'case_view.php',
            'case_files.php',
            'case_details.php',
            'case_session_save.php',
        ], true)) {
            return true;
        }

        if (
            $target === 'HLG-AI-Legal-Core/legal_ai.php'
            && in_array($current, [
                'HLG-AI-Legal-Core/legal_ai.php',
                'HLG-AI-Legal-Core/legal_ai_library.php',
                'HLG-AI-Legal-Core/legal_ai_case.php',
                'HLG-AI-Legal-Core/legal_ai_contract.php',
                'HLG-AI-Legal-Core/legal_ai_memos.php',
                'HLG-AI-Legal-Core/legal_ai_history.php',
                'HLG-AI-Legal-Core/legal_ai_add_content.php',
            ], true)
        ) {
            return true;
        }

        if (
            $target === 'hr_employees.php'
            && in_array($current, [
                'hr_employees.php',
                'hr_employee_form.php',
                'hr_attendance.php',
                'hr_leaves.php',
            ], true)
        ) {
            return true;
        }

        return false;
    }
}

/* =========================================================
   Notifications helpers
========================================================= */

if (!function_exists('layout_get_pdo')) {
    function layout_get_pdo(): ?PDO
    {
        try {
            if (isset($GLOBALS['pdo']) && $GLOBALS['pdo'] instanceof PDO) {
                $GLOBALS['pdo']->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
                $GLOBALS['pdo']->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
                return $GLOBALS['pdo'];
            }

            if (function_exists('db')) {
                $pdo = db();
                if ($pdo instanceof PDO) {
                    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
                    $pdo->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
                    return $pdo;
                }
            }
        } catch (Throwable $e) {
        }

        return null;
    }
}

if (!function_exists('layout_table_exists')) {
    function layout_table_exists(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;
        }
    }
}
/* =========================================================
   Update employee activity
========================================================= */
if (!empty($_SESSION['user_id'])) {
    try {
        $pdoActivity = layout_get_pdo();
        if ($pdoActivity instanceof PDO && layout_table_exists($pdoActivity, 'employees')) {
            $st = $pdoActivity->prepare("
                UPDATE employees
                SET last_activity = NOW()
                WHERE id = ?
            ");
            $st->execute([(int)$_SESSION['user_id']]);
        }
    } catch (Throwable $e) {
        // تجاهل الخطأ حتى لا تتعطل الصفحة
    }
}


if (!function_exists('layout_header')) {
function layout_header($title = '')
{
?>
<!doctype html>
<html lang="ar" dir="rtl">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<title><?= htmlspecialchars($title) ?></title>

<link rel="stylesheet" href="assets/css/style.css">

</head>

<body>

<div class="dashboard-page">
<?php
}
}

if (!function_exists('layout_footer')) {
function layout_footer()
{
?>
</div>

</body>
</html>
<?php
}
}
if (!empty($_SESSION['user_id'])) {
    try {
        $pdo = db();
        if ($pdo instanceof PDO) {
            $st = $pdo->prepare("
                UPDATE employees 
                SET last_activity = NOW() 
                WHERE id = ?
            ");
            $st->execute([$_SESSION['user_id']]);
        }
    } catch (Throwable $e) {}
}
/* =========================================================
   Owner popup on login
========================================================= */
if (!function_exists('layout_login_popup')) {
    function layout_login_popup(): ?array
    {
        $pdo = layout_get_pdo();
        if (!$pdo instanceof PDO) {
            return null;
        }

        if (
            !layout_table_exists($pdo, 'owner_popup_messages') ||
            !layout_table_exists($pdo, 'owner_popup_message_reads')
        ) {
            return null;
        }

        $employeeId = (int)($_SESSION['user_id'] ?? 0);
        $branchId   = (int)($_SESSION['branch_id'] ?? 0);
        $role       = current_role();

        if ($employeeId <= 0) {
            return null;
        }

        if ($role === 'OWNER') {
            return null;
        }

        try {
            $st = $pdo->prepare("
                SELECT m.*
                FROM owner_popup_messages m
                LEFT JOIN owner_popup_message_reads r
                    ON r.message_id = m.id
                   AND r.employee_id = ?
                WHERE m.is_active = 1
                  AND r.id IS NULL
                  AND (
                        m.target_type = 'all_branches'
                        OR (m.target_type = 'single_branch' AND m.target_branch_id = ?)
                        OR (m.target_type = 'employee' AND m.target_employee_id = ?)
                  )
                ORDER BY m.created_at DESC
                LIMIT 1
            ");

            $st->execute([$employeeId, $branchId, $employeeId]);
            $row = $st->fetch(PDO::FETCH_ASSOC);

            return is_array($row) ? $row : null;
        } catch (Throwable $e) {
            return null;
        }
    }
}

$popup = layout_login_popup();

if (!function_exists('layout_general_notifications')) {
    function layout_general_notifications(): array
    {
        $pdo = layout_get_pdo();
        if (!$pdo instanceof PDO) {
            return [];
        }

        if (!layout_table_exists($pdo, 'notifications')) {
            return [];
        }

        $userId = (int)($_SESSION['user_id'] ?? 0);
        if ($userId <= 0) {
            return [];
        }

        try {
            $st = $pdo->prepare("
                SELECT
                    id,
                    title,
                    message,
                    type,
                    related_id,
                    is_read,
                    created_at
                FROM notifications
                WHERE user_id = ?
                ORDER BY is_read ASC, id DESC
                LIMIT 20
            ");
            $st->execute([$userId]);
            $rows = $st->fetchAll();

            $items = [];
            foreach ($rows as $r) {
                $relatedId = (int)($r['related_id'] ?? 0);
                $type = trim((string)($r['type'] ?? 'general'));

                $icon = match ($type) {
                    'case_update' => '✏️',
                    'case_add'    => '📁',
                    'session_add' => '📅',
                    'warning'     => '⚠️',
                    default       => '🔔',
                };

                $items[] = [
                    'type'    => $type,
                    'icon'    => $icon,
                    'text'    => trim((string)($r['title'] ?? 'إشعار')),
                    'sub'     => trim((string)($r['message'] ?? '')),
                    'url'     => $relatedId > 0 ? u('case_edit.php?id=' . $relatedId) : '#',
                    'is_read' => (int)($r['is_read'] ?? 0),
                    'created' => trim((string)($r['created_at'] ?? '')),
                ];
            }

            return $items;
        } catch (Throwable $e) {
            return [];
        }
    }
}

if (!function_exists('layout_hearing_notifications')) {
    function layout_hearing_notifications(): array
    {
        $pdo = layout_get_pdo();
        if (!$pdo instanceof PDO) {
            return [];
        }

        if (!layout_table_exists($pdo, 'case_sessions') || !layout_table_exists($pdo, 'cases')) {
            return [];
        }

        try {
            date_default_timezone_set('Asia/Dubai');

            $today    = date('Y-m-d');
            $tomorrow = date('Y-m-d', strtotime('+1 day'));
            $after3   = date('Y-m-d', strtotime('+3 day'));

            $role     = current_role();
            $branchId = current_branch_id();

            $sql = "
                SELECT
                    cs.id,
                    cs.case_id,
                    cs.session_date,
                    cs.session_time,
                    cs.status,
                    cs.court_name,
                    c.case_no,
                    c.title,
                    c.branch_id
                FROM case_sessions cs
                INNER JOIN cases c ON c.id = cs.case_id
                WHERE 1=1
            ";

            $params = [];

          if ($role !== 'OWNER') {
    $sql .= " AND c.branch_id = ? ";
    $params[] = $branchId;
}
            $sql .= " ORDER BY cs.session_date ASC, cs.session_time ASC, cs.id DESC ";

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

            $notifications = [];

            foreach ($rows as $r) {
                $caseId = (int)($r['case_id'] ?? 0);
                $caseNo = trim((string)($r['case_no'] ?? ''));
                $title  = trim((string)($r['title'] ?? ''));
                $date   = (string)($r['session_date'] ?? '');
                $time   = trim((string)($r['session_time'] ?? ''));
                $status = strtoupper((string)($r['status'] ?? 'SCHEDULED'));

                $caseLabel = $caseNo !== '' ? $caseNo : ('القضية #' . $caseId);
                if ($title !== '') {
                    $caseLabel .= ' - ' . $title;
                }

                if ($date === $today) {
                    $notifications[] = [
                        'type'    => 'today',
                        'icon'    => '📅',
                        'text'    => "جلسة اليوم: {$caseLabel}",
                        'sub'     => $time !== '' ? "الساعة {$time}" : '',
                        'url'     => u('case_edit.php?id=' . $caseId . '#sessionsBox'),
                        'is_read' => 0,
                        'created' => '',
                    ];
                }

                if ($date === $tomorrow) {
                    $notifications[] = [
                        'type'    => 'tomorrow',
                        'icon'    => '⏰',
                        'text'    => "جلسة غداً: {$caseLabel}",
                        'sub'     => $time !== '' ? "الساعة {$time}" : '',
                        'url'     => u('case_edit.php?id=' . $caseId . '#sessionsBox'),
                        'is_read' => 0,
                        'created' => '',
                    ];
                }

                if ($date > $today && $date <= $after3) {
                    $notifications[] = [
                        'type'    => 'soon',
                        'icon'    => '🗓️',
                        'text'    => "جلسة قريبة: {$caseLabel}",
                        'sub'     => "بتاريخ {$date}" . ($time !== '' ? " • {$time}" : ''),
                        'url'     => u('case_edit.php?id=' . $caseId . '#sessionsBox'),
                        'is_read' => 0,
                        'created' => '',
                    ];
                }

                if ($date < $today && $status === 'SCHEDULED') {
                    $notifications[] = [
                        'type'    => 'late',
                        'icon'    => '⚠️',
                        'text'    => 'جلسة سابقة بدون تحديث نتيجة',
                        'sub'     => $caseLabel,
                        'url'     => u('case_edit.php?id=' . $caseId . '#sessionsBox'),
                        'is_read' => 0,
                        'created' => '',
                    ];
                }

                if ($status === 'POSTPONED') {
                    $notifications[] = [
                        'type'    => 'postponed',
                        'icon'    => '🔁',
                        'text'    => 'جلسة مؤجلة',
                        'sub'     => $caseLabel,
                        'url'     => u('case_edit.php?id=' . $caseId . '#sessionsBox'),
                        'is_read' => 0,
                        'created' => '',
                    ];
                }
            }

            return array_slice($notifications, 0, 12);
        } catch (Throwable $e) {
            return [];
        }
    }
}


if (!function_exists('layout_all_notifications')) {
    function layout_all_notifications(): array
    {
        $general  = layout_general_notifications();
        $hearings = layout_hearing_notifications();

        return array_slice(array_merge($general, $hearings), 0, 20);
    }
}

if (!function_exists('layout_unread_general_count')) {
    function layout_unread_general_count(): int
    {
        $pdo = layout_get_pdo();
        if (!$pdo instanceof PDO) {
            return 0;
        }

        if (!layout_table_exists($pdo, 'notifications')) {
            return 0;
        }

        $userId = (int)($_SESSION['user_id'] ?? 0);
        if ($userId <= 0) {
            return 0;
        }

        try {
            $st = $pdo->prepare("
                SELECT COUNT(*)
                FROM notifications
                WHERE user_id = ?
                  AND is_read = 0
            ");
            $st->execute([$userId]);
            return (int)$st->fetchColumn();
        } catch (Throwable $e) {
            return 0;
        }
    }
}
if (!function_exists('layout_branch_name_for_alerts')) {
    function layout_branch_name_for_alerts(int $branchId): string
    {
        return match ($branchId) {
            1 => 'أبوظبي',
            2 => 'دبي',
            3 => 'الشارقة',
            4 => 'العين',
            default => 'الفرع العام',
        };
    }
}

if (!function_exists('layout_document_ticker_alerts')) {
 
   function layout_document_ticker_alerts(): array
{
    $pdo = layout_get_pdo();
    if (!$pdo instanceof PDO) {
        return [];
    }

    $role     = current_role();
    $branchId = current_branch_id();
    $canAll   = in_array($role, ['OWNER', 'ADMIN', 'SUPER_ADMIN', 'SUPERADMIN'], true);

    $items = [];

    try {
        $hasEmployeeAlerts = layout_table_exists($pdo, 'hr_document_alerts');
        $hasEmployeesTable = layout_table_exists($pdo, 'employees');
        $hasCompanyAlerts  = layout_table_exists($pdo, 'company_document_alerts');

        if (!$hasEmployeeAlerts && !$hasCompanyAlerts) {
            return [];
        }

        if ($hasEmployeeAlerts && $hasEmployeesTable) {
            $hasHrIsRead   = false;
            $hasHrResolved = false;

            $st = $pdo->query("SHOW COLUMNS FROM hr_document_alerts LIKE 'is_read'");
            $hasHrIsRead = (bool) $st->fetch(PDO::FETCH_ASSOC);

            $st = $pdo->query("SHOW COLUMNS FROM hr_document_alerts LIKE 'is_resolved'");
            $hasHrResolved = (bool) $st->fetch(PDO::FETCH_ASSOC);

            $sql = "
                SELECT
                    a.id,
                    a.employee_id,
                    a.docs_id,
                    a.branch_id,
                    a.document_key,
                    a.document_label,
                    a.expiry_date,
                    a.days_left,
                    a.status,
                    " . ($hasHrIsRead ? "a.is_read" : "0 AS is_read") . ",
                    " . ($hasHrResolved ? "a.is_resolved" : "0 AS is_resolved") . ",
                    e.name AS employee_name
                FROM hr_document_alerts a
                LEFT JOIN employees e ON e.id = a.employee_id
                WHERE 1=1
            ";

            $params = [];

            if ($hasHrIsRead) {
                $sql .= " AND a.is_read = 0 ";
            }

            if ($hasHrResolved) {
                $sql .= " AND a.is_resolved = 0 ";
            }

            if (!$canAll) {
                $sql .= " AND a.branch_id = ? ";
                $params[] = $branchId;
            }

            $sql .= "
                ORDER BY
                    CASE WHEN a.status = 'expired' THEN 0 ELSE 1 END,
                    a.days_left ASC,
                    a.id DESC
                LIMIT 12
            ";

            $st = $pdo->prepare($sql);
            $st->execute($params);
            $rows = $st->fetchAll(PDO::FETCH_ASSOC);

            foreach ($rows as $r) {
                $daysLeft  = (int) ($r['days_left'] ?? 0);
                $status    = (string) ($r['status'] ?? '');
                $isExpired = ($status === 'expired' || $daysLeft < 0);

                $items[] = [
                    'kind'        => 'employee',
                    'source_type' => 'employee',
                    'priority'    => $isExpired ? 1 : 2,
                    'is_expired'  => $isExpired,
                    'url'         => u('hr/hr_docs_edit.php?id=' . (int) ($r['employee_id'] ?? 0)),
                    'label'       => trim((string) ($r['employee_name'] ?? ('الموظف #' . (int) ($r['employee_id'] ?? 0)))),
                    'document'    => trim((string) ($r['document_label'] ?? 'مستند')),
                    'branch'      => layout_branch_name_for_alerts((int) ($r['branch_id'] ?? 0)),
                    'days_text'   => $daysLeft < 0
                        ? 'منتهي منذ ' . abs($daysLeft) . ' يوم'
                        : 'متبقي ' . $daysLeft . ' يوم',
                ];
            }
        }

        if ($hasCompanyAlerts) {
            $companySql = "
                SELECT
                    id,
                    company_docs_id,
                    branch_id,
                    branch_name,
                    document_key,
                    document_label,
                    expiry_date,
                    days_left,
                    status,
                    is_read
                FROM company_document_alerts
                WHERE (is_read = 0 OR is_read IS NULL)
            ";

            $companyParams = [];

            if (!$canAll) {
                $companySql .= " AND branch_id = ? ";
                $companyParams[] = $branchId;
            }

            $companySql .= "
                ORDER BY
                    CASE WHEN status = 'expired' THEN 0 ELSE 1 END,
                    days_left ASC,
                    id DESC
                LIMIT 12
            ";

            $stCompany = $pdo->prepare($companySql);
            $stCompany->execute($companyParams);
            $companyRows = $stCompany->fetchAll(PDO::FETCH_ASSOC);

            foreach ($companyRows as $r) {
                $daysLeft  = (int) ($r['days_left'] ?? 0);
                $status    = (string) ($r['status'] ?? '');
                $isExpired = ($status === 'expired' || $daysLeft < 0);

                $branchName = trim((string) ($r['branch_name'] ?? ''));
                if ($branchName === '') {
                    $branchName = layout_branch_name_for_alerts((int) ($r['branch_id'] ?? 0));
                }

                $items[] = [
                    'kind'        => 'company',
                    'source_type' => 'company',
                    'priority'    => $isExpired ? 1 : 2,
                    'is_expired'  => $isExpired,
                    'url'         => u('hr/company_docs_edit.php?id=' . (int) ($r['company_docs_id'] ?? 0)),
                    'label'       => 'مستندات الشركة',
                    'document'    => trim((string) ($r['document_label'] ?? 'مستند شركة')),
                    'branch'      => $branchName,
                    'days_text'   => $daysLeft < 0
                        ? 'منتهي منذ ' . abs($daysLeft) . ' يوم'
                        : 'متبقي ' . $daysLeft . ' يوم',
                ];
            }
        }

        usort($items, static function (array $a, array $b): int {
            $pa = (int) ($a['priority'] ?? 9);
            $pb = (int) ($b['priority'] ?? 9);

            if ($pa !== $pb) {
                return ($pa < $pb) ? -1 : 1;
            }

            return 0;
        });

        error_log('ticker items count = ' . count($items));

        return array_slice($items, 0, 16);
    } catch (Throwable $e) {
        error_log('layout_document_ticker_alerts: ' . $e->getMessage());
        return $items;
    }
}
}
/* =========================================================
   Layout Start
========================================================= */


if (!function_exists('render_layout_start')) {
    function render_layout_start(string $title = ''): void
    {
        $branchId      = current_branch_id();
        $branchName    = branch_name_ar($branchId);
        $name          = trim((string)($_SESSION['name'] ?? $_SESSION['username'] ?? 'مستخدم'));
        $role          = current_role();
        $logo          = (string)($_SESSION['logo'] ?? 'https://hamdanlegalgroup.ae/wp-content/uploads/2026/02/logomail.png');
        $returnUrl     = (string)($_SERVER['REQUEST_URI'] ?? u('dashboard.php'));

       $notifications   = layout_all_notifications();
$generalUnread   = layout_unread_general_count();
$notifyCount     = count(layout_hearing_notifications()) + $generalUnread;
$tickerAlerts    = layout_document_ticker_alerts();

$systemAlerts = [];

try {
    $pdoLayoutAlerts = layout_get_pdo();

   if ($pdoLayoutAlerts instanceof PDO && layout_table_exists($pdoLayoutAlerts, 'hr_document_alerts')) {
    $stCheck = $pdoLayoutAlerts->query("SHOW COLUMNS FROM hr_document_alerts LIKE 'is_resolved'");
    $hasIsResolved = (bool)$stCheck->fetch(PDO::FETCH_ASSOC);

    if ($hasIsResolved) {
        $hasCompanyAlerts = layout_table_exists($pdoLayoutAlerts, 'company_document_alerts');

        if ($hasCompanyAlerts) {
            $alertsSql = "
                SELECT *
                FROM (
                    SELECT
                        'employee' AS source_type,
                        id,
                        employee_id,
                        employee_name,
                        docs_id,
                        branch_id,
                        document_key,
                        document_label,
                        expiry_date,
                        days_left,
                        status,
                        alert_date,
                        is_read,
                        created_at
                    FROM hr_document_alerts
                    WHERE is_resolved = 0

                    UNION ALL

                    SELECT
                        'company' AS source_type,
                        id,
                        0 AS employee_id,
                        branch_name AS employee_name,
                        company_docs_id AS docs_id,
                        branch_id,
                        document_key,
                        document_label,
                        expiry_date,
                        days_left,
                        status,
                        alert_date,
                        is_read,
                        created_at
                    FROM company_document_alerts
                ) AS combined_alerts
                ORDER BY
                    CASE
                        WHEN status = 'expired' THEN 1
                        WHEN status = 'warning' THEN 2
                        ELSE 3
                    END,
                    days_left ASC,
                    id DESC
                LIMIT 20
            ";
        } else {
            $alertsSql = "
                SELECT
                    'employee' AS source_type,
                    id,
                    employee_id,
                    employee_name,
                    docs_id,
                    branch_id,
                    document_key,
                    document_label,
                    expiry_date,
                    days_left,
                    status,
                    alert_date,
                    is_read,
                    created_at
                FROM hr_document_alerts
                WHERE is_resolved = 0
                ORDER BY
                    CASE
                        WHEN status = 'expired' THEN 1
                        WHEN status = 'warning' THEN 2
                        ELSE 3
                    END,
                    days_left ASC,
                    id DESC
                LIMIT 20
            ";
        }

        $alertsStmt = $pdoLayoutAlerts->prepare($alertsSql);
        $alertsStmt->execute();
        $systemAlerts = $alertsStmt->fetchAll(PDO::FETCH_ASSOC);
    }
}
} catch (Throwable $e) {
    $systemAlerts = [];
}
?>
<?php header("Content-Type: text/html; charset=utf-8");         ?>
<!doctype html>
<html lang="ar" dir="rtl">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width,initial-scale=1">
  <title><?= h($title !== '' ? $title : 'HLG-ONE') ?></title>

  <link rel="preconnect" href="https://fonts.googleapis.com">
  <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
  <link href="https://fonts.googleapis.com/css2?family=Tajawal:wght@400;500;700;800;900&display=swap" rel="stylesheet">

  <style>
    :root{
      --layout-bg1:#071a23;
      --layout-bg2:#0b2633;
      --layout-line:rgba(255,255,255,.08);
      --layout-text:rgba(255,255,255,.92);
      --layout-muted:rgba(255,255,255,.68);
      --layout-shadow:0 10px 30px rgba(0,0,0,.18);
      --layout-sidebar-w:280px;
    }

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

    html,
    body{
      margin:0;
      padding:0;
      width:100%;
      max-width:100%;
      overflow-x:hidden;
      font-family:Tajawal,system-ui,-apple-system,Segoe UI,Arial,sans-serif;
      background:radial-gradient(1200px 700px at 85% 10%, #0f394d 0%, var(--layout-bg1) 55%, #031018 100%);
      color:var(--layout-text);
    }

    body{
      min-height:100vh;
    }

    a{
      color:inherit;
      text-decoration:none;
    }

    .layout-app{
      display:flex;
      align-items:flex-start;
      min-height:100vh;
      width:100%;
      max-width:100%;
      overflow-x:hidden;
    }

   .layout-sidebar{
  width:var(--layout-sidebar-w);
  flex:0 0 var(--layout-sidebar-w);
  min-width:var(--layout-sidebar-w);
  padding:18px 14px;
  border-left:1px solid var(--layout-line);
  background:linear-gradient(180deg, rgba(255,255,255,.04), rgba(255,255,255,.02));
  position:sticky;
  top:0;
  min-height:100vh;
  overflow-x:hidden;
  overflow-y:visible;
  z-index:1100;
}

    .layout-brand{
      display:flex;
      align-items:center;
      justify-content:space-between;
      padding:12px;
      border:1px solid var(--layout-line);
      border-radius:16px;
      background:rgba(0,0,0,.12);
      margin-bottom:14px;
      max-width:100%;
    }

    .layout-brand-left{
      display:flex;
      gap:10px;
      align-items:center;
      min-width:0;
      max-width:100%;
    }

    .layout-brand-logo{
      width:44px;
      height:44px;
      border-radius:12px;
      background:rgba(255,255,255,.06);
      display:flex;
      align-items:center;
      justify-content:center;
      overflow:hidden;
      flex:0 0 44px;
    }

    .layout-brand-logo img{
      width:100%;
      height:100%;
      object-fit:contain;
    }

    .layout-brand-title{
      min-width:0;
      max-width:100%;
    }

    .layout-brand-title .layout-name{
      font-weight:900;
      letter-spacing:.2px;
      white-space:nowrap;
      overflow:hidden;
      text-overflow:ellipsis;
    }

    .layout-brand-title .layout-sub{
      font-size:12px;
      color:var(--layout-muted);
      white-space:nowrap;
      overflow:hidden;
      text-overflow:ellipsis;
    }

    .layout-nav{
      display:flex;
      flex-direction:column;
      gap:10px;
      margin-top:10px;
      max-width:100%;
    }

    .layout-nav a{
      display:flex;
      align-items:center;
      justify-content:space-between;
      gap:10px;
      padding:12px;
      border-radius:16px;
      border:1px solid var(--layout-line);
      background:rgba(255,255,255,.03);
      transition:.15s ease;
      max-width:100%;
      min-width:0;
    }

    .layout-nav a:hover{
      transform:translateY(-1px);
      background:rgba(255,255,255,.06);
    }

    .layout-nav a.active{
      background:linear-gradient(180deg, rgba(0,106,122,.32), rgba(0,66,79,.18));
      border-color:rgba(0,106,122,.48);
      box-shadow:var(--layout-shadow);
    }

    .layout-nav .layout-label{
      font-weight:700;
      min-width:0;
      overflow:hidden;
      text-overflow:ellipsis;
      white-space:nowrap;
    }

    .layout-pill{
      font-size:10px;
      color:var(--layout-muted);
      padding:6px 10px;
      border-radius:999px;
      border:1px solid var(--layout-line);
      background:rgba(0,0,0,.10);
      white-space:nowrap;
      flex:0 0 auto;
    }

    .layout-footerBox{
      margin-top:14px;
      padding:12px;
      border-radius:16px;
      border:1px solid var(--layout-line);
      background:rgba(0,0,0,.12);
      max-width:100%;
    }

    .layout-who{
      display:flex;
      justify-content:space-between;
      gap:10px;
      align-items:center;
      color:var(--layout-muted);
      font-size:13px;
      flex-wrap:wrap;
      max-width:100%;
    }

    .layout-logout{
      margin-top:10px;
      display:block;
      text-align:center;
      padding:11px 12px;
      border-radius:16px;
      border:1px solid rgba(255,255,255,.10);
      background:rgba(255,255,255,.04);
      font-weight:800;
    }

    .layout-logout:hover{
      background:rgba(255,255,255,.07);
    }

    .layout-content{
      flex:1 1 auto;
      min-width:0;
      width:100%;
      max-width:100%;
      padding:18px 18px 26px;
      overflow-x:hidden;
      overflow-y:visible;
    }

    .layout-content > *{
      max-width:100%;
      min-width:0;
    }

    .layout-topbar{
      display:flex;
      align-items:center;
      justify-content:space-between;
      gap:12px;
      padding:14px 16px;
      border:1px solid var(--layout-line);
      border-radius:18px;
      background:rgba(0,0,0,.12);
      margin-bottom:14px;
      flex-wrap:wrap;
      width:100%;
      max-width:100%;
      min-width:0;
    }

    .layout-topbarMain{
      min-width:0;
      flex:1 1 auto;
    }

    .layout-topbarActions{
      display:flex;
      align-items:center;
      gap:10px;
      flex-wrap:wrap;
      justify-content:flex-start;
      min-width:0;
      max-width:100%;
    }

    .layout-t1{
      font-weight:900;
      font-size:30px;
      line-height:1.2;
    }

    .layout-t2{
      color:var(--layout-muted);
      font-size:13px;
      margin-top:4px;
      line-height:1.7;
    }

    .layout-mobileMenuBtn{
      display:none;
      align-items:center;
      justify-content:center;
      width:52px;
      height:52px;
      border-radius:16px;
      border:1px solid var(--layout-line);
      background:rgba(255,255,255,.06);
      color:var(--layout-text);
      cursor:pointer;
      font-size:24px;
      font-weight:900;
      line-height:1;
      flex:0 0 auto;
    }

    .layout-mobileMenuBtn:hover{
      background:rgba(255,255,255,.10);
    }

    .layout-mobileBackdrop{
      display:none;
      position:fixed;
      inset:0;
      background:rgba(0,0,0,.42);
      z-index:1090;
      opacity:0;
      pointer-events:none;
      transition:opacity .2s ease;
    }

    .layout-btn{
      display:inline-flex;
      align-items:center;
      justify-content:center;
      gap:8px;
      min-height:46px;
      padding:10px 14px;
      border-radius:14px;
      border:1px solid rgba(0,106,122,.45);
      background:linear-gradient(180deg, rgba(0,106,122,.35), rgba(0,66,79,.18));
      color:var(--layout-text);
      cursor:pointer;
      font-weight:800;
      white-space:nowrap;
      text-decoration:none;
    }

    .layout-btn:hover{
      filter:brightness(1.05);
    }

    .layout-btn-ghost{
      background:rgba(255,255,255,.04);
      border:1px solid var(--layout-line);
      font-weight:700;
    }

    .layout-notifyWrap{
      position:relative;
      flex:0 0 auto;
    }

    .layout-notifyBtn{
      position:relative;
      display:inline-flex;
      align-items:center;
      justify-content:center;
      width:56px;
      height:52px;
      border:none;
      outline:none;
      cursor:pointer;
      border-radius:16px;
      background:linear-gradient(180deg,#0b2230,#102f40);
      color:#f8fafc;
      font-size:24px;
      line-height:1;
      box-shadow:inset 0 1px 0 rgba(255,255,255,.06), 0 8px 22px rgba(0,0,0,.18);
      transition:transform .18s ease, box-shadow .18s ease, background .18s ease;
    }

    .layout-notifyBtn:hover{
      transform:translateY(-1px);
      box-shadow:inset 0 1px 0 rgba(255,255,255,.06), 0 12px 28px rgba(0,0,0,.24);
    }

    .layout-notifyBtn .layout-bellIcon{
      display:inline-flex;
      align-items:center;
      justify-content:center;
      transform-origin:top center;
    }

    .layout-notifyBtn.hasAlert .layout-bellIcon{
      animation:layoutBellShake 1.8s ease-in-out infinite;
    }

    .layout-notifyBtn.ringNow .layout-bellIcon{
      animation:layoutBellShakeStrong .7s ease-in-out 3;
    }

    .layout-notifyCount{
      position:absolute;
      top:-6px;
      right:-6px;
      min-width:24px;
      height:24px;
      padding:0 7px;
      border-radius:999px;
      display:inline-flex;
      align-items:center;
      justify-content:center;
      background:#ef4444;
      color:#fff;
      border:2px solid #08202d;
      font-size:12px;
      font-weight:800;
      line-height:1;
      box-shadow:0 8px 16px rgba(239,68,68,.35);
      animation:layoutBadgePulse 1.5s ease-in-out infinite;
    }

    .layout-notifyMenu{
      position:absolute;
      top:calc(100% + 10px);
      right:0;
      width:360px;
      max-width:calc(100vw - 24px);
      background:#fff;
      border:1px solid #e5e7eb;
      border-radius:18px;
      box-shadow:0 20px 40px rgba(15,23,42,.16);
      overflow:hidden;
      opacity:0;
      visibility:hidden;
      transform:translateY(8px);
      transition:opacity .18s ease, transform .18s ease, visibility .18s ease;
      z-index:9999;
    }

    .layout-notifyWrap.open .layout-notifyMenu{
      opacity:1;
      visibility:visible;
      transform:translateY(0);
    }

    .layout-notifyHead{
      padding:14px 16px;
      font-size:15px;
      font-weight:800;
      color:#0f172a;
      background:#f8fafc;
      border-bottom:1px solid #eef2f7;
    }

    .layout-notifyEmpty{
      padding:18px 16px;
      color:#64748b;
      font-size:14px;
      text-align:center;
    }

    .layout-notifyList{
      max-height:340px;
      overflow:auto;
    }

    .layout-notifyItem{
      display:flex;
      align-items:flex-start;
      gap:12px;
      padding:14px 16px;
      text-decoration:none;
      color:#0f172a;
      border-bottom:1px solid #f1f5f9;
      transition:background .16s ease;
    }

    .layout-notifyItem:last-child{
      border-bottom:none;
    }

    .layout-notifyItem:hover{
      background:#f8fafc;
    }

    .layout-notifyIcon{
      width:38px;
      height:38px;
      flex:0 0 38px;
      border-radius:12px;
      display:flex;
      align-items:center;
      justify-content:center;
      background:linear-gradient(180deg,#ecfeff,#dff7f5);
      border:1px solid #bfe7e2;
      font-size:18px;
    }

    .layout-notifyText{
      min-width:0;
      font-size:14px;
      font-weight:700;
      line-height:1.7;
      color:#0f172a;
    }

    .layout-notifyText small{
      display:block;
      margin-top:4px;
      color:#64748b;
      font-size:12px;
      font-weight:600;
      line-height:1.6;
    }

    .layout-branch-form{
      display:flex;
      gap:8px;
      align-items:center;
      margin:0;
    }

    .layout-branch-select{
      width:160px;
      min-width:160px;
      background:rgba(0,0,0,.40);
      color:#fff;
      border:1px solid rgba(255,255,255,.20);
      padding:11px 12px;
      border-radius:14px;
      font:inherit;
      outline:none;
    }

    .layout-branch-select option{
      background:#0b2633;
      color:#fff;
    }

    @keyframes layoutBellShake{
      0%,100%{transform:rotate(0deg)}
      10%{transform:rotate(12deg)}
      20%{transform:rotate(-10deg)}
      30%{transform:rotate(8deg)}
      40%{transform:rotate(-6deg)}
      50%{transform:rotate(4deg)}
      60%{transform:rotate(-2deg)}
      70%{transform:rotate(1deg)}
    }

    @keyframes layoutBellShakeStrong{
      0%,100%{transform:rotate(0deg) scale(1)}
      10%{transform:rotate(18deg) scale(1.08)}
      20%{transform:rotate(-16deg) scale(1.08)}
      30%{transform:rotate(14deg) scale(1.08)}
      40%{transform:rotate(-12deg) scale(1.06)}
      50%{transform:rotate(10deg) scale(1.05)}
      60%{transform:rotate(-8deg) scale(1.04)}
      70%{transform:rotate(6deg) scale(1.03)}
      80%{transform:rotate(-3deg) scale(1.02)}
    }

    @keyframes layoutBadgePulse{
      0%,100%{
        transform:scale(1);
        box-shadow:0 8px 16px rgba(239,68,68,.35);
      }
      50%{
        transform:scale(1.12);
        box-shadow:0 10px 20px rgba(239,68,68,.50);
      }
    }
    .layout-docTicker{
  position:relative;
  overflow:hidden;
  width:100%;
  max-width:100%;
  margin:-2px 0 14px;
  border-radius:18px;
  border:1px solid rgba(255,255,255,.08);
  background:linear-gradient(135deg,#08242f,#0b3240);
  box-shadow:0 10px 24px rgba(0,0,0,.12);
  padding:10px 0;
}

.layout-docTicker-track{
  display:flex;
  align-items:center;
  gap:12px;
  width:max-content;
  animation:layoutDocTickerMove 42s linear infinite;
}

.layout-docTicker:hover .layout-docTicker-track{
  animation-play-state:paused;
}

.layout-docTicker-chip{
  display:inline-flex;
  align-items:center;
  gap:10px;
  padding:10px 16px;
  border-radius:999px;
  text-decoration:none;
  color:#fff;
  white-space:nowrap;
  border:1px solid rgba(255,255,255,.10);
  background:rgba(255,255,255,.08);
  backdrop-filter:blur(3px);
}

.layout-docTicker-badge{
  display:inline-flex;
  align-items:center;
  justify-content:center;
  min-width:58px;
  padding:5px 10px;
  border-radius:999px;
  font-size:12px;
  font-weight:800;
}

.layout-docTicker-chip.expired .layout-docTicker-badge{
  background:#ffe3e3;
  color:#b42323;
}

.layout-docTicker-chip.warning .layout-docTicker-badge{
  background:#fff4d6;
  color:#9b6500;
}

.layout-docTicker-text{
  font-size:13px;
  font-weight:700;
  color:rgba(255,255,255,.95);
}

@keyframes layoutDocTickerMove{
  from { transform:translateX(0); }
  to   { transform:translateX(-50%); }
}

    @media (max-width: 980px){
      .layout-mobileMenuBtn{
        display:inline-flex;
      }

      .layout-app{
        display:block;
      }

      .layout-sidebar{
        position:fixed;
        top:0;
        right:0;
        height:100vh;
        width:min(86vw, 320px);
        min-width:min(86vw, 320px);
        transform:translateX(100%);
        transition:transform .25s ease;
        box-shadow:-10px 0 30px rgba(0,0,0,.35);
        border-left:1px solid var(--layout-line);
        background:linear-gradient(180deg, #08202d, #0b2633);
      }

      body.menu-open .layout-sidebar{
        transform:translateX(0);
      }

      .layout-mobileBackdrop{
        display:block;
      }

      body.menu-open .layout-mobileBackdrop{
        opacity:1;
        pointer-events:auto;
      }

      .layout-content{
        padding:14px;
      }
    }

    @media (max-width: 640px){
      .layout-topbar{
        align-items:flex-start;
      }

      .layout-t1{
        font-size:24px;
      }

      .layout-topbarActions{
        width:100%;
      }

      .layout-notifyMenu{
        width:320px;
        right:auto;
        left:0;
      }
    }
    /* =========================================================
   Legacy compatibility layer for old pages
========================================================= */
.grid{
  display:grid;
  grid-template-columns:1fr;
  gap:12px;
  width:100%;
  max-width:100%;
}

.card{
  border:1px solid var(--layout-line);
  background:rgba(255,255,255,.04);
  border-radius:18px;
  padding:14px;
  overflow:hidden;
  width:100%;
  max-width:100%;
}

.cardHead{
  display:flex;
  align-items:center;
  justify-content:space-between;
  gap:10px;
  margin-bottom:10px;
  flex-wrap:wrap;
  max-width:100%;
}

.row{
  display:flex;
  gap:10px;
  flex-wrap:wrap;
  align-items:center;
  min-width:0;
  max-width:100%;
}

.row > *{
  min-width:0;
  max-width:100%;
}

.btn{
  display:inline-flex;
  align-items:center;
  justify-content:center;
  gap:8px;
  min-height:46px;
  padding:10px 14px;
  border-radius:14px;
  border:1px solid rgba(0,106,122,.45);
  background:linear-gradient(180deg, rgba(0,106,122,.35), rgba(0,66,79,.18));
  color:var(--layout-text);
  cursor:pointer;
  font-weight:800;
  white-space:nowrap;
  text-decoration:none;
  font:inherit;
}

.btn:hover{
  filter:brightness(1.05);
}

.btn.ghost{
  background:rgba(255,255,255,.04);
  border:1px solid var(--layout-line);
  font-weight:700;
}

.btn.danger{
  border:1px solid rgba(255,107,107,.45);
  background:rgba(255,107,107,.12);
  color:#fff;
}

.msg{
  padding:10px 12px;
  border-radius:14px;
  border:1px solid var(--layout-line);
  background:rgba(0,0,0,.12);
  margin-bottom:10px;
  max-width:100%;
}

.msg.ok{
  border-color:rgba(76,217,100,.35);
  background:rgba(76,217,100,.10);
}

.msg.err{
  border-color:rgba(255,107,107,.35);
  background:rgba(255,107,107,.10);
}

.input,
textarea,
select{
  font:inherit;
}

.input{
  width:100%;
  max-width:100%;
  min-width:0;
  padding:11px 12px;
  border-radius:14px;
  border:1px solid var(--layout-line);
  background:rgba(0,0,0,.18);
  color:var(--layout-text);
  outline:none;
}

textarea{
  width:100%;
  max-width:100%;
  min-width:0;
  padding:11px 12px;
  border-radius:14px;
  border:1px solid var(--layout-line);
  background:rgba(0,0,0,.18);
  color:var(--layout-text);
  outline:none;
  resize:vertical;
}

.muted{
  color:var(--layout-muted);
}
.sidebar-link-stats{
  display:flex;
  align-items:center;
  justify-content:space-between;
  gap:12px;
}

.sidebar-link-stats .sidebar-title{
  flex:1 1 auto;
  text-align:right;
}

.sidebar-pill{
  display:inline-flex;
  align-items:center;
  justify-content:center;
  height:34px;
  min-width:34px;
  padding:0 12px;
  border-radius:999px;
  border:1px solid rgba(255,255,255,.08);
  background:rgba(8, 28, 38, .55);
  box-shadow:inset 0 1px 0 rgba(255,255,255,.04);
  white-space:nowrap;
}

.sidebar-pill-icon{
  order:2;              /* يخليه على اليسار في flex مع RTL */
  min-width:40px;
  padding:0 10px;
  font-size:18px;
  color:#ffd86b;
  box-shadow:
    0 0 14px rgba(255,216,107,.18),
    inset 0 1px 0 rgba(255,255,255,.05);
}

.sidebar-link-stats:hover .sidebar-pill-icon{
  box-shadow:
    0 0 20px rgba(255,216,107,.32),
    inset 0 1px 0 rgba(255,255,255,.06);
  transform:translateX(-1px);
}
.online-user{
display:flex;
align-items:center;
gap:8px;
padding:6px 10px;
border-radius:8px;
background:#f3fafb;
margin-bottom:6px;
}

.dot{
width:10px;
height:10px;
border-radius:50%;
background:#2ecc71;
box-shadow:0 0 6px #2ecc71;
}

.permissions-modal{
  display:none;
  position:fixed;
  inset:0;
  background:rgba(0,0,0,.45);
  backdrop-filter:blur(4px);
  z-index:99999;
  align-items:center;
  justify-content:center;
  padding:20px;
}

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

.permissions-modal__box{
  width:100%;
  max-width:420px;
  background:#fff;
  border-radius:22px;
  padding:32px 24px 24px;
  text-align:center;
  box-shadow:0 20px 60px rgba(0,0,0,.20);
  position:relative;
}

.permissions-modal__close{
  position:absolute;
  top:12px;
  left:12px;
  border:0;
  background:transparent;
  font-size:28px;
  line-height:1;
  cursor:pointer;
  color:#666;
}

.permissions-modal__icon{
  font-size:52px;
  margin-bottom:12px;
}

.permissions-modal__title{
  margin:0 0 10px;
  font-size:24px;
  color:#0f2a33;
  font-weight:700;
}

.permissions-modal__text{
  margin:0;
  font-size:15px;
  color:#6b7280;
  line-height:1.8;
}

.permissions-modal__actions{
  margin-top:22px;
}

.permissions-modal__btn{
  border:0;
  background:#0b6b43;
  color:#fff;
  padding:12px 22px;
  border-radius:12px;
  font-size:15px;
  cursor:pointer;
}
.layout-branch-select--disabled,
.layout-branch-select:disabled{
  opacity:.70;
  cursor:not-allowed;
  background:rgba(255,255,255,.06);
  color:rgba(255,255,255,.88);
  border:1px solid rgba(255,255,255,.14);
}
.btn-small{
  display:inline-flex;
  align-items:center;
  justify-content:center;
  gap:6px;
  padding:7px 12px;
  border-radius:10px;
  text-decoration:none;
  background:#006a7a;
  color:#fff;
  font-size:13px;
  margin-left:6px;
  border:none;
  cursor:pointer;
}
.btn-small:hover{
  opacity:.92;
}
/* زر الجرس */
.bell-btn{
  width:46px;
  height:46px;
  display:flex;
  align-items:center;
  justify-content:center;
  border-radius:14px;
  background:rgba(255,255,255,.06);
  border:1px solid rgba(255,255,255,.08);
  position:relative;
}

/* أيقونة الجرس */
.bell-btn svg,
.bell-btn i{
  font-size:22px;
  width:22px;
  height:22px;
}

/* رقم الإشعارات */
.bell-btn .badge{
  position:absolute;
  top:-6px;
  left:-6px;
  background:#ef4444;
  color:#fff;
  font-size:12px;
  font-weight:700;
  width:20px;
  height:20px;
  border-radius:50%;
  display:flex;
  align-items:center;
  justify-content:center;
}
.welcome-user-box{
  display:flex;
  align-items:center;
  gap:12px;
}

.welcome-avatar{
  width:58px;
  height:58px;
  border-radius:50%;
  object-fit:cover;
  display:block;
  border:3px solid #d4af37;
  box-shadow:0 8px 20px rgba(0,0,0,.18);
  background:#fff;
  flex:0 0 58px;
}

.welcome-text{
  display:flex;
  flex-direction:column;
  min-width:0;
}

.welcome-name{
  font-size:22px;
  font-weight:800;
  line-height:1.2;
  color:#fff;
}

.welcome-branch{
  margin-top:4px;
  font-size:14px;
  color:rgba(255,255,255,.82);
}

@media (max-width:768px){
  .welcome-avatar{
    width:48px;
    height:48px;
    flex-basis:48px;
  }

  .welcome-name{
    font-size:17px;
  }

  .welcome-branch{
    font-size:12px;
  }
}
.layout-docTicker {
  width: 100%;
  overflow: hidden;
  background: linear-gradient(90deg, #00424f, #006a7a);
  border-radius: 12px;
  margin: 10px 0;
  padding: 8px 0;
}

.layout-docTicker-track {
  display: flex;
  gap: 10px;
  animation: tickerMove 25s linear infinite;
}

.layout-docTicker-chip {
  display: inline-flex;
  align-items: center;
  gap: 8px;
  padding: 6px 14px;
  background: rgba(255,255,255,0.1);
  border-radius: 999px;
  color: #fff;
  text-decoration: none;
  white-space: nowrap;
  font-size: 13px;
}

.layout-docTicker-chip.expired {
  background: rgba(255, 0, 0, 0.2);
}

.layout-docTicker-chip.warning {
  background: rgba(255, 165, 0, 0.2);
}

.layout-docTicker-badge {
  font-weight: bold;
}

@keyframes tickerMove {
  0% { transform: translateX(0); }
  100% { transform: translateX(-50%); }
}
</style>

</head>
<body>
<div class="layout-mobileBackdrop" id="layoutMobileBackdrop"></div>

<div class="layout-app">

  <aside class="layout-sidebar" id="layoutSidebar">
    <div class="layout-brand">
      <div class="layout-brand-left">
        <div class="layout-brand-logo">
          <img src="<?= h($logo) ?>" alt="HLG">
        </div>
        <div class="layout-brand-title">
          <div class="layout-name">HLG-ONE</div>
          <div class="layout-sub">مجموعة حمدان القانونية</div>
        </div>
      </div>
    </div>

    <nav class="layout-nav">
      <a class="<?= nav_active('dashboard.php') ? 'active' : '' ?>" href="<?= h(u('dashboard.php')) ?>">
        <span class="layout-label">الرئيسية</span>
        <span class="layout-pill">لوحة التحكم</span>
      </a>

      <a class="<?= nav_active('cases.php') ? 'active' : '' ?>" href="<?= h(u('cases.php')) ?>">
        <span class="layout-label">القضايا</span>
        <span class="layout-pill">إدارة</span>
      </a>

      <a class="<?= nav_active('hearings/hearings.php') ? 'active' : '' ?>" href="<?= h(u('hearings/hearings.php')) ?>">
        <span class="layout-label">الجلسات</span>
        <span class="layout-pill">مراجعة</span>
      </a>

      <a class="<?= nav_active('tasks.php') ? 'active' : '' ?>" href="<?= h(u('tasks.php')) ?>">
        <span class="layout-label">المهام</span>
        <span class="layout-pill">متابعة</span>
      </a>
    <?php
$role = strtoupper(trim((string)($_SESSION['role'] ?? '')));
?>

<?php if (in_array($role, ['OWNER','ADMIN'], true)): ?>
<a class="<?= nav_active('contracts/index.php') ? 'active' : '' ?>" href="<?= h(u('contracts/index.php')) ?>">
  <span class="layout-label">إدارة العقود</span>
  <span class="layout-pill">💾</span>
</a>
<?php endif; ?>

<a class="<?= nav_active('clients/index.php') ? 'active' : '' ?>" href="<?= h(u('clients/index.php')) ?>">
  <span class="layout-label">العملاء</span>
  <span class="layout-pill">شركاؤنا</span>
</a>
      <a class="<?= nav_active('HLG-AI-Legal-Core/legal_ai.php') ? 'active' : '' ?>" href="<?= h(u('HLG-AI-Legal-Core/legal_ai.php')) ?>">
        <span class="layout-label">الذكاء القانوني</span>
        <span class="layout-pill">AI</span>
      </a>
<a href="https://hamdanlegalgroup.ae/HLG-Justice-Hub/employee_statistics.php" class="sidebar-link sidebar-link-stats">
  <span class="sidebar-pill sidebar-pill-icon">🏆</span>
  <span class="sidebar-title">إحصائيات الموظفين</span>
</a>
      <?php if (is_owner()): ?>
        <a class="<?= nav_active('hr_comms_email.php') ? 'active' : '' ?>" href="<?= h(u('hr_comms_email.php')) ?>">
          <span class="layout-label">التواصل مع الموظفين</span>
          <span class="layout-pill">تواصل</span>
        </a>
      <?php endif; ?>
 <?php if (is_owner()): ?>
        <a class="<?= nav_active('owner_popup_stats.php') ? 'active' : '' ?>" href="<?= h(u('owner_popup_stats.php')) ?>">
          <span class="layout-label">رسائل النظام</span>
          <span class="layout-pill">التفاصيل</span>
        </a>
      <?php endif; ?>
 <a class="<?= nav_active('hr/hr_docs_dashboard.php') ? 'active' : '' ?>" href="<?= h(u('hr/hr_docs_dashboard.php')) ?>">
        <span class="layout-label">المستندات</span>
        <span class="layout-pill">مراقبة</span>
      </a>

      <a class="<?= nav_active('hr_employee_form.php') ? 'active' : '' ?>" href="<?= h(u('hr_employee_form.php')) ?>">
        <span class="layout-label">شؤون الموظفين</span>
        <span class="layout-pill">HR</span>
      </a>

      <a class="<?= nav_active('finance/salaries.php') ? 'active' : '' ?>" href="<?= h(u('finance/salaries.php')) ?>">
        <span class="layout-label">إدارة الرواتب</span>
        <span class="layout-pill">$</span>
      </a>
<?php
$role = strtoupper(trim((string)($_SESSION['role'] ?? '')));
?>

<?php
$role = strtoupper(trim((string)($_SESSION['role'] ?? '')));
$branchId = (int)($_SESSION['branch_id'] ?? 0);

$canSeeFinance = ($role === 'OWNER') || ($role === 'ADMIN' && $branchId === 1);
?>

<?php if ($canSeeFinance): ?>
<a class="<?= nav_active('financial/dashboard.php') ? 'active' : '' ?>" href="<?= h(u('financial/dashboard.php')) ?>">
  <span class="layout-label">الإدارة المالية</span>
  <span class="layout-pill">اللوحة المالية</span>
</a>
<?php endif; ?>
<?php if (strtoupper((string)($_SESSION['role'] ?? '')) === 'OWNER'): ?>
<a class="<?= nav_active('permissions_manage.php') ? 'active' : '' ?>"
   href="<?= h(u('permissions_manage.php')) ?>">
  <span class="layout-label">الصلاحيات</span>
  <span class="layout-pill">تحكم</span>
</a>
<?php endif; ?>
<?php if (in_array(strtoupper((string)($_SESSION['role'] ?? '')), ['OWNER'], true)): ?>
  <a class="<?= nav_active('password_reset_requests.php') ? 'active' : '' ?>" href="<?= h(u('password_reset_requests.php')) ?>">
    <span class="layout-label">طلبات كلمات المرور</span>
    <span class="layout-pill">إدارة</span>
  </a>
<?php endif; ?>
    </nav>
    

   <div class="layout-footerBox">
  <div class="layout-who">
    <div><?= h($name) ?></div>
    <div><?= h($role) ?> · <?= h($branchName) ?></div>
  </div>

  <a class="layout-logout" href="<?= h(u('logout.php')) ?>">خروج</a>
</div>
</aside>
<main class="layout-content">

<div class="layout-topbar">
  <button
    type="button"
    class="layout-mobileMenuBtn"
    id="layoutMobileMenuBtn"
    aria-label="فتح القائمة"
    aria-expanded="false"
  >☰</button>

  <div class="hero-head">
    <div class="welcome-user-box">
      <img
        src="<?= h(current_user_photo()) ?>"
        alt="<?= h(current_user_name()) ?>"
        class="welcome-avatar"
      >

      <div class="welcome-text">
        <div class="welcome-name"><?= h(current_user_name()) ?></div>
        <div class="welcome-branch">فرع <?= h(current_branch_name_ar()) ?> · HLG-ONE</div>
      </div>
    </div>
  </div>

    <div class="layout-topbarActions">
        
      <div class="layout-notifyWrap" id="layoutNotifyWrap">
        <button
          type="button"
          class="layout-notifyBtn <?= $notifyCount > 0 ? 'hasAlert' : '' ?>"
          id="layoutNotifyBtn"
          aria-label="الإشعارات"
          aria-expanded="false"
          aria-controls="layoutNotifyMenu"
        >
          <span class="layout-bellIcon">🔔</span>
          <?php if ($notifyCount > 0): ?>
            <span class="layout-notifyCount" id="layoutNotifyCount"><?= (int)$notifyCount ?></span>
          <?php endif; ?>
        </button>

        <div class="layout-notifyMenu" id="layoutNotifyMenu" role="menu" aria-hidden="true">
          <div class="layout-notifyHead">الإشعارات</div>

          <?php if (empty($notifications)): ?>
            <div class="layout-notifyEmpty">لا توجد إشعارات حالياً</div>
          <?php else: ?>
            <div class="layout-notifyList">
              <?php foreach ($notifications as $n): ?>
                <a class="layout-notifyItem" href="<?= h((string)($n['url'] ?? '#')) ?>">
                  <div class="layout-notifyIcon"><?= h((string)($n['icon'] ?? '🔔')) ?></div>
                  <div class="layout-notifyText">
                    <?= h((string)($n['text'] ?? 'إشعار جديد')) ?>
                    <?php if (!empty($n['sub'])): ?>
                      <small><?= h((string)$n['sub']) ?></small>
                    <?php elseif (!empty($n['created'])): ?>
                      <small><?= h((string)$n['created']) ?></small>
                    <?php endif; ?>
                  </div>
                </a>
              <?php endforeach; ?>
            </div>
          <?php endif; ?>
        </div>
      </div>

      <a class="layout-btn layout-btn-ghost" href="<?= h(u('hr_employees.php')) ?>">الموظفين</a>
      <a class="layout-btn layout-btn-ghost" href="<?= h(u('hr_attendance.php')) ?>">الحضور</a>
      <a class="layout-btn layout-btn-ghost" href="<?= h(u('hr_leaves.php')) ?>">الإجازات</a>

      <form method="post" action="<?= h(u('set_branch.php')) ?>" class="layout-branch-form">
  <input type="hidden" name="return" value="<?= h($returnUrl) ?>">

  <select
    name="branch_id"
    class="layout-branch-select <?= is_owner() ? '' : 'layout-branch-select--disabled' ?>"
    <?= is_owner() ? 'onchange="this.form.submit()"' : 'disabled' ?>
    title="<?= is_owner() ? 'تبديل الفرع' : 'عرض فقط - التبديل متاح للأونر فقط' ?>"
  >
    <option value="1" <?= $branchId === 1 ? 'selected' : '' ?>>أبوظبي</option>
    <option value="2" <?= $branchId === 2 ? 'selected' : '' ?>>دبي</option>
    <option value="3" <?= $branchId === 3 ? 'selected' : '' ?>>الشارقة</option>
    <option value="4" <?= $branchId === 4 ? 'selected' : '' ?>>العين</option>
  </select>
</form>
    </div>
  </div>
    <script>
      (function(){
        const wrap = document.getElementById('layoutNotifyWrap');
        const btn  = document.getElementById('layoutNotifyBtn');
        const menu = document.getElementById('layoutNotifyMenu');
        const countEl = document.getElementById('layoutNotifyCount');

        if (wrap && btn && menu) {
          let lastCount = countEl ? parseInt(countEl.textContent || '0', 10) || 0 : 0;

          function openMenu(){
            wrap.classList.add('open');
            btn.setAttribute('aria-expanded', 'true');
            menu.setAttribute('aria-hidden', 'false');
            btn.classList.remove('ringNow');
          }

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

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

          function triggerStrongRing(){
            btn.classList.remove('ringNow');
            void btn.offsetWidth;
            btn.classList.add('ringNow');

            setTimeout(() => {
              btn.classList.remove('ringNow');
            }, 2200);
          }

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

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

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

          document.addEventListener('keydown', function(e){
            if (e.key === 'Escape') {
              closeMenu();
            }
          });

          if (lastCount > 0) {
            triggerStrongRing();
          }

          window.updateNotificationBell = function(newCount){
            newCount = parseInt(newCount || '0', 10) || 0;

            let badge = document.getElementById('layoutNotifyCount');

            if (newCount > 0) {
              btn.classList.add('hasAlert');

              if (!badge) {
                badge = document.createElement('span');
                badge.className = 'layout-notifyCount';
                badge.id = 'layoutNotifyCount';
                btn.appendChild(badge);
              }

              badge.textContent = String(newCount);

              if (newCount > lastCount) {
                triggerStrongRing();
              }
            } else {
              btn.classList.remove('hasAlert', 'ringNow');
              if (badge) badge.remove();
            }

            lastCount = newCount;
          };
        }

        const body = document.body;
        const sidebar = document.getElementById('layoutSidebar');
        const mobileBtn = document.getElementById('layoutMobileMenuBtn');
        const backdrop = document.getElementById('layoutMobileBackdrop');

        if (sidebar && mobileBtn && backdrop) {
          function openSidebar(){
            body.classList.add('menu-open');
            mobileBtn.setAttribute('aria-expanded', 'true');
          }

          function closeSidebar(){
            body.classList.remove('menu-open');
            mobileBtn.setAttribute('aria-expanded', 'false');
          }

          function toggleSidebar(){
            if (body.classList.contains('menu-open')) {
              closeSidebar();
            } else {
              openSidebar();
            }
          }

          mobileBtn.addEventListener('click', function(e){
            e.preventDefault();
            e.stopPropagation();
            toggleSidebar();
          });

          backdrop.addEventListener('click', function(){
            closeSidebar();
          });

          document.addEventListener('keydown', function(e){
            if (e.key === 'Escape') {
              closeSidebar();
            }
          });

          sidebar.querySelectorAll('a').forEach(function(link){
            link.addEventListener('click', function(){
              closeSidebar();
            });
          });

          window.addEventListener('resize', function(){
            if (window.innerWidth > 980) {
              closeSidebar();
            }
          });
        }
      })();
    </script>
<?php
    }
}

/* =========================================================
   Layout End
========================================================= */
if (!function_exists('render_layout_end')) {
    function render_layout_end(): void
    {
        ?>
  </main>
</div>

</div>
<?php global $popup; ?>
<?php if (!empty($popup) && is_array($popup)): ?>
<style>
  .sys-popup-overlay{
    position:fixed;
    inset:0;
    background:rgba(2,12,16,.55);
    backdrop-filter:blur(6px);
    -webkit-backdrop-filter:blur(6px);
    display:flex;
    align-items:center;
    justify-content:center;
    z-index:999999;
    padding:24px;
    animation:sysPopupFade .22s ease;
  }

  .sys-popup{
    width:min(620px, 100%);
    border-radius:26px;
    overflow:hidden;
    border:1px solid rgba(255,255,255,.08);
    background:
      linear-gradient(180deg, rgba(255,255,255,.06), rgba(255,255,255,.03));
    box-shadow:
      0 30px 80px rgba(0,0,0,.40),
      inset 0 1px 0 rgba(255,255,255,.05);
    color:#fff;
    direction:rtl;
    text-align:right;
    font-family:Tajawal, Arial, sans-serif;
    animation:sysPopupUp .24s ease;
    backdrop-filter:blur(16px);
    -webkit-backdrop-filter:blur(16px);
  }

  .sys-popup-head{
    padding:20px 24px;
    background:
      linear-gradient(135deg, rgba(0,66,79,.95), rgba(0,106,122,.92));
    border-bottom:1px solid rgba(255,255,255,.08);
    display:flex;
    align-items:center;
    justify-content:space-between;
    gap:14px;
  }

  .sys-popup-title{
    margin:0;
    font-size:28px;
    font-weight:900;
    color:#fff;
    line-height:1.2;
  }

  .sys-popup-badge{
    display:inline-flex;
    align-items:center;
    gap:8px;
    padding:8px 12px;
    border-radius:999px;
    background:rgba(255,255,255,.08);
    border:1px solid rgba(255,255,255,.10);
    color:#ffd76a;
    font-size:13px;
    font-weight:800;
    white-space:nowrap;
  }

  .sys-popup-dot{
    width:8px;
    height:8px;
    border-radius:50%;
    background:#ffd76a;
    box-shadow:0 0 0 4px rgba(255,215,106,.12);
  }

  .sys-popup-body{
    padding:24px;
    background:rgba(5,21,27,.88);
  }

  .sys-popup-message{
    margin:0;
    color:rgba(255,255,255,.90);
    font-size:20px;
    line-height:2;
    white-space:pre-wrap;
  }

  .sys-popup-foot{
    margin-top:22px;
    display:flex;
    justify-content:flex-end;
    gap:10px;
    flex-wrap:wrap;
  }

  .sys-popup-btn{
    border:1px solid rgba(212,175,55,.24);
    background:linear-gradient(135deg,#ffd76a,#d4af37);
    color:#1d1600;
    height:46px;
    min-width:120px;
    padding:0 18px;
    border-radius:14px;
    cursor:pointer;
    font-family:inherit;
    font-size:16px;
    font-weight:900;
    box-shadow:0 14px 26px rgba(212,175,55,.18);
    transition:.18s ease;
  }

  .sys-popup-btn:hover{
    transform:translateY(-2px);
    box-shadow:0 18px 32px rgba(212,175,55,.24);
  }

  .sys-popup-btn:active{
    transform:translateY(0);
  }

  @keyframes sysPopupFade{
    from{opacity:0}
    to{opacity:1}
  }

  @keyframes sysPopupUp{
    from{
      opacity:0;
      transform:translateY(14px) scale(.985);
    }
    to{
      opacity:1;
      transform:translateY(0) scale(1);
    }
  }

  @media (max-width:700px){
    .sys-popup{
      border-radius:22px;
    }

    .sys-popup-head,
    .sys-popup-body{
      padding:18px;
    }

    .sys-popup-title{
      font-size:23px;
    }

    .sys-popup-message{
      font-size:17px;
      line-height:1.9;
    }

    .sys-popup-btn{
      width:100%;
    }

    .sys-popup-foot{
      justify-content:stretch;
    }
  }
  
</style>

<?php
if (!empty($_SESSION['user_id'])) {
    try {
        $st = $pdo->prepare("
            UPDATE employees
            SET last_activity = NOW()
            WHERE id = ?
        ");
        $st->execute([$_SESSION['user_id']]);
    } catch (Throwable $e) {}
}

$onlineEmployees = [];
try {
    $st = $pdo->query("
        SELECT id, full_name, branch_id
        FROM employees
        WHERE last_activity >= (NOW() - INTERVAL 2 MINUTE)
        ORDER BY full_name
    ");
    $onlineEmployees = $st->fetchAll(PDO::FETCH_ASSOC);
} catch (Throwable $e) {}
?>

<div id="ownerPopupOverlay" class="sys-popup-overlay">
  <div class="sys-popup" role="dialog" aria-modal="true" aria-labelledby="sysPopupTitle">
    <div class="sys-popup-head">
      <h3 class="sys-popup-title" id="sysPopupTitle">
        <?= h($popup['title'] ?? 'تنبيه إداري') ?>
      </h3>

      <div class="sys-popup-badge">
        <span class="sys-popup-dot"></span>
        <span>رسالة النظام</span>
      </div>
    </div>

    <div class="sys-popup-body">
      <p class="sys-popup-message"><?= h($popup['message'] ?? '') ?></p>

      <div class="sys-popup-foot">
        <button type="button"
                class="sys-popup-btn"
                onclick="closeOwnerPopup(<?= (int)($popup['id'] ?? 0) ?>)">
          تم
        </button>
      </div>
    </div>
  </div>
</div>

<script>
function closeOwnerPopup(messageId) {
  const popupEl = document.getElementById('ownerPopupOverlay');

  fetch("<?= h(u('mark_popup_seen.php')) ?>", {
    method: "POST",
    headers: {
      "Content-Type": "application/x-www-form-urlencoded; charset=UTF-8"
    },
    body: "message_id=" + encodeURIComponent(messageId)
  })
  .then(function(response) {
    if (!response.ok) {
      throw new Error("Request failed");
    }
    return response.text();
  })
  .then(function() {
    if (popupEl) popupEl.remove();
  })
  .catch(function(error) {
    console.error("Popup close error:", error);
    if (popupEl) popupEl.remove();
  });
}
</script>
<?php endif; ?>
<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 () {
  async function pingActivity() {
    try {
      await fetch('<?= h(u("ajax/update_activity.php")) ?>', {
        method: 'GET',
        credentials: 'same-origin',
        cache: 'no-store'
      });
    } catch (e) {}
  }

  pingActivity();
  setInterval(pingActivity, 30000);
})();
</script>
</body>
</html>
<?php
    }
}