<?php
declare(strict_types=1);

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

require_once __DIR__ . '/db.php';

header('Content-Type: text/html; charset=utf-8');

$pdo = db();
if (!$pdo instanceof PDO) {
    exit('<div class="online-empty">تعذر تحميل البيانات</div>');
}

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

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

$currentUserId = (int)($_SESSION['user_id'] ?? 0);
$branchId      = (int)($_SESSION['branch_id'] ?? 1);
$role          = strtoupper((string)($_SESSION['role'] ?? 'STAFF'));
$isOwner       = ($role === 'OWNER');

/* تحديث نشاط المستخدم الحالي */
if ($currentUserId > 0) {
    try {
        $st = $pdo->prepare("
            UPDATE employees
            SET last_activity = NOW()
            WHERE id = ?
        ");
        $st->execute([$currentUserId]);
    } catch (Throwable $e) {}
}

try {
    $sql = "
        SELECT
            id,
            COALESCE(NULLIF(full_name, ''), NULLIF(name, ''), CONCAT('موظف #', id)) AS full_name,
            branch_id,
            role,
            last_activity
        FROM employees
        WHERE last_activity IS NOT NULL
          AND last_activity >= (NOW() - INTERVAL 10 MINUTE)
    ";

    $params = [];

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

    $sql .= " ORDER BY last_activity DESC, full_name ASC";

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

if (!$rows) {
    echo '<div class="online-empty">لا يوجد موظفون متصلون</div>';
    exit;
}

foreach ($rows as $emp) {
    echo '<div class="online-item">';
    echo '<span class="online-dot"></span>';
    echo '<span class="online-name">' . h($emp['full_name']) . '</span>';
    echo '</div>';
}