<?php
// dashboard.php — Admin Activity Dashboard
require_once 'auth.php';
// اگر از کتابخانه jdf استفاده می‌کنید، آن را اینجا اضافه کنید:
// require_once 'jdf.php';

check_access();

// فقط ادمین‌ها دسترسی دارن
if (($_SESSION['user_role'] ?? '') !== 'admin') {
    header('Location: index.php');
    exit();
}

require_once 'tracker.php';
$tracker = new ActivityTracker();

global $valid_users;
function getRealName($username) {
    global $valid_users;
    if (isset($valid_users[$username]) && isset($valid_users[$username]['name'])) {
        return $valid_users[$username]['name'];
    }
    return $username;
}

// تابع کمکی برای نمایش تاریخ شمسی (اگر jdate وجود نداشت، همون میلادی رو میده)
function showDate($datetime) {
    if (empty($datetime)) return '-';
    if (function_exists('jdate')) {
        $timestamp = strtotime($datetime);
        return jdate('Y/m/d H:i:s', $timestamp);
    }
    return $datetime;
}

$days = intval($_GET['days'] ?? 0); // اگر 0 باشه یعنی فیلتر امروز
if ($days === 0 && !isset($_GET['days'])) {
    $days = 30; // پیش‌فرض اولیه
}

$selectedUser = $_GET['user'] ?? '';

$onlineUsers = $tracker->getOnlineUsers();
// اضافه کردن وضعیت idle
$currentTime = time();
foreach ($onlineUsers as &$ou) {
    $lastActivityTime = strtotime($ou['last_activity']);
    $idleTime = $currentTime - $lastActivityTime;
    $ou['is_idle'] = ($idleTime > 300); // 5 دقیقه = 300 ثانیه
}
unset($ou);

$dailyStats = $tracker->getDailyStats($days == 0 ? 1 : $days);
$userStats = $tracker->getUserStats($days == 0 ? 1 : $days);
$hourlyActivity = $tracker->getHourlyActivity($days == 0 ? 1 : $days);
$topActions = $tracker->getTopActions($days == 0 ? 1 : $days);

$topUsersToday = array_slice($tracker->getUserStats(1), 0, 5);
$topUsersWeek = array_slice($tracker->getUserStats(7), 0, 5);
$topUsersMonth = array_slice($tracker->getUserStats(30), 0, 5);

$userSessions = [];
$userActions = [];
$userChartLabels = [];
$userChartData = [];

if ($selectedUser) {
    $userSessions = $tracker->getUserSessions($selectedUser, $days == 0 ? 1 : $days);
    $userActions = $tracker->getUserActions($selectedUser, min($days == 0 ? 1 : $days, 7));
    
    $dailyPresence = [];
    foreach ($userSessions as $sess) {
        $date = substr($sess['login_time'], 0, 10);
        if (function_exists('jdate')) {
             $date = jdate('Y/m/d', strtotime($date));
        }
        if (!isset($dailyPresence[$date])) {
            $dailyPresence[$date] = 0;
        }
        $dailyPresence[$date] += $sess['calc_duration'];
    }
    ksort($dailyPresence);
    foreach ($dailyPresence as $date => $duration) {
        $userChartLabels[] = $date;
        $userChartData[] = round($duration / 60);
    }
}

function formatDuration($seconds) {
    if (!$seconds || $seconds < 0) return '0 دقیقه';
    $hours = floor($seconds / 3600);
    $minutes = floor(($seconds % 3600) / 60);
    if ($hours > 0) return "{$hours} ساعت و {$minutes} دقیقه";
    return "{$minutes} دقیقه";
}

function formatDurationShort($seconds) {
    if (!$seconds || $seconds < 0) return '0m';
    $hours = floor($seconds / 3600);
    $minutes = floor(($seconds % 3600) / 60);
    if ($hours > 0) return "{$hours}h {$minutes}m";
    return "{$minutes}m";
}

$totalSessions = array_sum(array_column($dailyStats, 'total_sessions'));
$totalDuration = array_sum(array_column($dailyStats, 'total_duration'));
$uniqueUsersTotal = count($userStats);
$avgSessionDuration = $totalSessions > 0 ? $totalDuration / $totalSessions : 0;
?>
<!DOCTYPE html>
<html lang="fa" dir="rtl">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>داشبورد فعالیت کاربران</title>
<script src="/St/dashboard/js/chart.umd.min.js"></script>
<style>
    @font-face {
        font-family: 'YekanBakh';
        src: url('/fonts/YekanBakh-Regular.ttf') format('truetype');
        font-weight: normal;
        font-style: normal;
    }

    * { margin: 0; padding: 0; box-sizing: border-box; }

    body {
        font-family: 'YekanBakh', 'Segoe UI', Tahoma, sans-serif;
        background: #f1f4f9;
        color: #1e293b;
        direction: rtl;
        min-height: 100vh;
    }

    .top-bar {
        background: #ffffff; padding: 14px 28px; display: flex; justify-content: space-between;
        align-items: center; border-bottom: 2px solid #e2e8f0; flex-wrap: wrap; gap: 12px;
        box-shadow: 0 1px 3px rgba(0,0,0,0.06); position: sticky; top: 0; z-index: 100;
    }
    .top-bar h1 { font-size: 19px; color: #0f172a; font-weight: 700; letter-spacing: -0.3px; }
    .top-bar-actions { display: flex; gap: 10px; align-items: center; }
    .top-bar a, .top-bar select {
        background: #f8fafc; color: #334155; border: 1px solid #cbd5e1; padding: 7px 16px;
        border-radius: 8px; text-decoration: none; font-size: 13px; cursor: pointer; transition: all 0.15s ease;
    }
    .top-bar a:hover, .top-bar select:hover { background: #e2e8f0; border-color: #94a3b8; }

    .dashboard { max-width: 1400px; margin: 0 auto; padding: 28px; }

    .summary-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(210px, 1fr)); gap: 16px; margin-bottom: 28px; }
    .summary-card { background: #ffffff; border: 1px solid #e2e8f0; border-radius: 12px; padding: 22px 20px; text-align: center; box-shadow: 0 1px 4px rgba(0,0,0,0.04); transition: transform 0.2s ease; }
    .summary-card:hover { transform: translateY(-2px); }
    .summary-card .icon { width: 40px; height: 40px; border-radius: 10px; display: inline-flex; align-items: center; justify-content: center; margin-bottom: 10px; }
    .summary-card .icon svg { width: 24px; height: 24px; fill: #fff; }
    .summary-card .value { font-size: 30px; font-weight: 800; line-height: 1.2; color: #0f172a; }
    .summary-card .label { font-size: 13px; color: #64748b; margin-top: 5px; font-weight: 500; }

    .summary-card.online .icon  { background: #16a34a; }
    .summary-card.online .value { color: #16a34a; }
    .summary-card.users .icon  { background: #2563eb; }
    .summary-card.users .value { color: #2563eb; }
    .summary-card.sessions .icon  { background: #7c3aed; }
    .summary-card.sessions .value { color: #7c3aed; }
    .summary-card.duration .icon  { background: #d97706; }
    .summary-card.duration .value { color: #d97706; }

    .top-widgets-grid { display: grid; grid-template-columns: 2fr 1fr; gap: 20px; margin-bottom: 28px; }
    .online-section, .chart-card, .table-card { background: #ffffff; border: 1px solid #e2e8f0; border-radius: 12px; padding: 22px; box-shadow: 0 1px 4px rgba(0,0,0,0.04); margin-bottom: 28px; }
    .section-title { font-size: 16px; font-weight: 700; margin-bottom: 18px; color: #0f172a; display: flex; align-items: center; gap: 10px; }
    .section-title .title-accent { width: 4px; height: 20px; border-radius: 3px; background: #3b82f6; flex-shrink: 0; }

    .online-list { display: flex; flex-wrap: wrap; gap: 12px; }
    .online-user { background: #f8fafc; border: 1px solid #e2e8f0; border-radius: 10px; padding: 14px 18px; min-width: 240px; transition: border-color 0.15s ease; border-right: 4px solid #16a34a; }
    .online-user.idle { border-right-color: #eab308; }
    .online-user:hover { border-color: #93c5fd; }
    .online-user .name { font-weight: 700; color: #16a34a; font-size: 14px; display: flex; align-items: center; gap: 8px; }
    .online-user.idle .name { color: #eab308; }
    .online-user .meta { font-size: 11.5px; color: #64748b; margin-top: 6px; line-height: 1.6; }

    .tabs-container { display: flex; gap: 8px; margin-bottom: 16px; background: #f1f5f9; padding: 4px; border-radius: 8px; }
    .tab-btn { flex: 1; text-align: center; border: none; background: transparent; padding: 8px 12px; font-family: inherit; font-size: 13px; font-weight: 600; color: #64748b; border-radius: 6px; cursor: pointer; transition: all 0.2s; }
    .tab-btn.active { background: #fff; color: #3b82f6; box-shadow: 0 1px 3px rgba(0,0,0,0.1); }
    .tab-content { display: none; }
    .tab-content.active { display: block; }
    
    .active-user-item { display: flex; justify-content: space-between; align-items: center; padding: 12px 10px; border-bottom: 1px solid #f1f5f9; }
    .active-user-item:last-child { border-bottom: none; }
    .active-user-info { display: flex; flex-direction: column; gap: 4px; }
    .active-user-name { font-weight: 700; color: #334155; font-size: 13px; }
    .active-user-role { font-size: 11px; color: #94a3b8; }
    .active-user-stat { text-align: left; font-size: 12px; font-weight: 600; color: #d97706; background: #fef3c7; padding: 4px 8px; border-radius: 6px; }

    .search-box { width: 100%; padding: 10px 15px; margin-bottom: 15px; border: 1px solid #cbd5e1; border-radius: 8px; font-family: inherit; font-size: 14px; outline: none; transition: border-color 0.2s; }
    .search-box:focus { border-color: #3b82f6; }

    .table-responsive { overflow-x: auto; }
    table { width: 100%; border-collapse: separate; border-spacing: 0; }
    table th { background: #f8fafc; padding: 12px 16px; text-align: right; font-size: 13px; color: #64748b; font-weight: 700; border-bottom: 2px solid #e2e8f0; white-space: nowrap; }
    table td { padding: 12px 16px; font-size: 13px; border-bottom: 1px solid #f1f5f9; white-space: nowrap; color: #334155; }
    table tr:hover td { background: #f8fafc; }
    table a { color: #2563eb; text-decoration: none; font-weight: 600; background: #eff6ff; padding: 5px 12px; border-radius: 6px; transition: background 0.2s; }
    table a:hover { background: #dbeafe; }

    .badge { display: inline-block; padding: 4px 10px; border-radius: 20px; font-size: 11px; font-weight: 700; }
    .badge-admin  { background: #ede9fe; color: #7c3aed; }
    .badge-area   { background: #e0f2fe; color: #0369a1; }
    .badge-online { background: #dcfce7; color: #16a34a; }
    .badge-idle   { background: #fef08a; color: #a16207; }
    .badge-offline{ background: #f1f5f9; color: #94a3b8; }

    .user-detail-header { background: #ffffff; border: 1px solid #e2e8f0; border-right: 4px solid #3b82f6; border-radius: 12px; padding: 22px 28px; margin-bottom: 24px; display: flex; justify-content: space-between; align-items: center; flex-wrap: wrap; gap: 16px; }
    .user-detail-header h2 { font-size: 20px; color: #0f172a; font-weight: 700; display: flex; align-items: center; gap: 12px; }
    .user-detail-header h2 span { font-size: 13px; background: #e2e8f0; color: #475569; padding: 4px 10px; border-radius: 6px; font-weight: normal; }
    .btn-close-detail { background: #ef4444; color: #fff; padding: 8px 20px; border-radius: 8px; text-decoration: none; font-size: 13px; font-weight: 600; box-shadow: 0 2px 4px rgba(239,68,68,0.2); transition: all 0.2s ease; }
    .btn-close-detail:hover { background: #dc2626; transform: translateY(-1px); }

    .action-log { max-height: 420px; overflow-y: auto; }
    .action-item { display: flex; gap: 14px; padding: 12px 14px; border-bottom: 1px solid #f1f5f9; font-size: 13px; align-items: center; }
    .action-item:hover { background: #f8fafc; }
    .action-time { color: #94a3b8; min-width: 140px; direction: ltr; text-align: right; font-size: 12px; }
    .action-type { background: #f1f5f9; color: #475569; padding: 4px 10px; border-radius: 6px; font-size: 11px; min-width: 110px; text-align: center; font-weight: 700; }
    .action-detail { color: #334155; flex: 1; }

    .empty-state { text-align: center; padding: 44px 20px; color: #94a3b8; font-size: 14px; font-weight: 500; }

    @media (max-width: 992px) { .top-widgets-grid { grid-template-columns: 1fr; } }
</style>
</head>
<body>

<div class="top-bar">
    <h1>داشبورد فعالیت کاربران</h1>
    <div class="top-bar-actions">
        <?php if (!$selectedUser): ?>
        <select onchange="changeDays(this.value)" id="days-select">
            <option value="0" <?= $days==0?'selected':'' ?>>امروز</option>
            <option value="7" <?= $days==7?'selected':'' ?>>7 روز</option>
            <option value="14" <?= $days==14?'selected':'' ?>>14 روز</option>
            <option value="30" <?= $days==30?'selected':'' ?>>30 روز</option>
            <option value="90" <?= $days==90?'selected':'' ?>>90 روز</option>
        </select>
        <?php endif; ?>
        <a href="index.php">برگشت به نقشه</a>
        <a href="logout.php">خروج</a>
    </div>
</div>

<div class="dashboard">
    <?php if (!$selectedUser): ?>
    
    <div class="summary-grid">
        <div class="summary-card online">
            <div class="icon"><svg viewBox="0 0 24 24"><path d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm0 14c-2.21 0-4-1.79-4-4s1.79-4 4-4 4 1.79 4 4-1.79 4-4 4z"/></svg></div>
            <div class="value"><?= count($onlineUsers) ?></div>
            <div class="label">آنلاین الان</div>
        </div>
        <div class="summary-card users">
            <div class="icon"><svg viewBox="0 0 24 24"><path d="M16 11c1.66 0 2.99-1.34 2.99-3S17.66 5 16 5c-1.66 0-3 1.34-3 3s1.34 3 3 3zm-8 0c1.66 0 2.99-1.34 2.99-3S9.66 5 8 5C6.34 5 5 6.34 5 8s1.34 3 3 3zm0 2c-2.33 0-7 1.17-7 3.5V19h14v-2.5c0-2.33-4.67-3.5-7-3.5zm8 0c-.29 0-.62.02-.97.05 1.16.84 1.97 1.97 1.97 3.45V19h6v-2.5c0-2.33-4.67-3.5-7-3.5z"/></svg></div>
            <div class="value"><?= $uniqueUsersTotal ?></div>
            <div class="label">کاربر فعال (<?= $days==0 ? 'امروز' : $days.' روز' ?>)</div>
        </div>
        <div class="summary-card sessions">
            <div class="icon"><svg viewBox="0 0 24 24"><path d="M12 4V1L8 5l4 4V6c3.31 0 6 2.69 6 6 0 1.01-.25 1.97-.7 2.8l1.46 1.46C19.54 15.03 20 13.57 20 12c0-4.42-3.58-8-8-8zm0 14c-3.31 0-6-2.69-6-6 0-1.01.25-1.97.7-2.8L5.24 7.74C4.46 8.97 4 10.43 4 12c0 4.42 3.58 8 8 8v3l4-4-4-4v3z"/></svg></div>
            <div class="value"><?= $totalSessions ?></div>
            <div class="label">کل سشن‌ها</div>
        </div>
        <div class="summary-card duration">
            <div class="icon"><svg viewBox="0 0 24 24"><path d="M11.99 2C6.47 2 2 6.48 2 12s4.47 10 9.99 10C17.52 22 22 17.52 22 12S17.52 2 11.99 2zM12 20c-4.42 0-8-3.58-8-8s3.58-8 8-8 8 3.58 8 8-3.58 8-8 8zm.5-13H11v6l5.25 3.15.75-1.23-4.5-2.67z"/></svg></div>
            <div class="value"><?= formatDurationShort($totalDuration) ?></div>
            <div class="label">مجموع حضور</div>
        </div>
    </div>

    <?php if (!empty($onlineUsers)): ?>
    <div class="online-section">
        <div class="section-title">
            <span class="title-accent" style="background:#22c55e"></span>
            کاربران آنلاین (<?= count($onlineUsers) ?> نفر)
        </div>
        <div class="online-list">
            <?php foreach ($onlineUsers as $ou): ?>
            <div class="online-user <?= $ou['is_idle'] ? 'idle' : '' ?>">
                <div class="name">
                    <svg width="16" height="16" viewBox="0 0 24 24" fill="<?= $ou['is_idle'] ? '#eab308' : '#16a34a' ?>"><circle cx="12" cy="12" r="8"/></svg>
                    <?= htmlspecialchars(getRealName($ou['username'])) ?>
                    <span class="badge <?= $ou['user_role']==='admin' ? 'badge-admin' : 'badge-area' ?>">
                        <?= $ou['user_role']==='admin' ? 'ادمین' : 'مدیر منطقه' ?>
                    </span>
                    <?php if($ou['is_idle']): ?>
                        <span class="badge badge-idle">بیکار</span>
                    <?php endif; ?>
                </div>
                <div class="meta">
                    <div>مدت حضور: <?= formatDuration($ou['duration']) ?></div>
                    <div>ورود: <span style="direction:ltr;display:inline-block"><?= showDate($ou['login_time']) ?></span></div>
                </div>
            </div>
            <?php endforeach; ?>
        </div>
    </div>
    <?php endif; ?>

    <div class="top-widgets-grid">
        <div class="chart-card" style="margin-bottom:0;">
            <div class="section-title">
                <span class="title-accent"></span>
                روند سشن‌ها و کاربران
            </div>
            <canvas id="dailyChart" height="110"></canvas>
        </div>

        <div class="chart-card" style="margin-bottom:0;">
            <div class="section-title">
                <span class="title-accent" style="background:#f59e0b"></span>
                فعال‌ترین اعضا
            </div>
            
            <div class="tabs-container">
                <button class="tab-btn active" onclick="switchTab('today')">امروز</button>
                <button class="tab-btn" onclick="switchTab('week')">هفته</button>
                <button class="tab-btn" onclick="switchTab('month')">ماه</button>
            </div>

            <?php
            function renderTopUsers($users) {
                if (empty($users)) {
                    echo '<div class="empty-state" style="padding:20px">فعالیتی ثبت نشده</div>';
                    return;
                }
                foreach ($users as $tu) {
                    $roleName = $tu['user_role']==='admin' ? 'ادمین' : 'مدیر منطقه';
                    $name = htmlspecialchars(getRealName($tu['username']));
                    $sessions = $tu['total_sessions'];
                    $duration = formatDurationShort($tu['total_duration']);
                    echo "<div class='active-user-item'>
                            <div class='active-user-info'>
                                <span class='active-user-name'>{$name}</span>
                                <span class='active-user-role'>{$roleName} | {$sessions} ورود</span>
                            </div>
                            <span class='active-user-stat'>{$duration}</span>
                          </div>";
                }
            }
            ?>
            <div id="tab-today" class="tab-content active"><?php renderTopUsers($topUsersToday); ?></div>
            <div id="tab-week" class="tab-content"><?php renderTopUsers($topUsersWeek); ?></div>
            <div id="tab-month" class="tab-content"><?php renderTopUsers($topUsersMonth); ?></div>
        </div>
    </div>

    <div class="table-card">
        <div class="section-title">
            <span class="title-accent"></span>
            جدول عملکرد همه کاربران (<?= $days==0 ? 'امروز' : $days.' روز اخیر' ?>)
        </div>
        <input type="text" id="userSearch" class="search-box" placeholder="جستجوی نام کاربر..." onkeyup="filterTable()">
        <div class="table-responsive">
            <table id="usersTable">
                <thead>
                    <tr>
                        <th>نام کاربر</th>
                        <th>نقش</th>
                        <th>تعداد سشن</th>
                        <th>روزهای فعال</th>
                        <th>مجموع حضور</th>
                        <th>میانگین هر سشن</th>
                        <th>تعداد اکشن</th>
                        <th>آخرین ورود</th>
                        <th>عملیات</th>
                    </tr>
                </thead>
                <tbody>
                    <?php if (empty($userStats)): ?>
                    <tr id="emptyRow"><td colspan="9" class="empty-state">هنوز داده‌ای ثبت نشده</td></tr>
                    <?php else: ?>
                    <?php foreach ($userStats as $us): ?>
                    <tr>
                        <td><strong><?= htmlspecialchars(getRealName($us['username'])) ?></strong></td>
                        <td>
                            <span class="badge <?= $us['user_role']==='admin' ? 'badge-admin' : 'badge-area' ?>">
                                <?= $us['user_role']==='admin' ? 'ادمین' : 'مدیر منطقه' ?>
                            </span>
                        </td>
                        <td><?= $us['total_sessions'] ?></td>
                        <td><?= $us['active_days'] ?> روز</td>
                        <td><?= formatDuration($us['total_duration']) ?></td>
                        <td><?= formatDuration($us['avg_duration']) ?></td>
                        <td><?= $us['total_actions'] ?></td>
                        <td style="direction:ltr;text-align:right"><?= showDate($us['last_login']) ?></td>
                        <td><a href="?user=<?= urlencode($us['username']) ?>&days=<?= $days ?>">مشاهده جزئیات</a></td>
                    </tr>
                    <?php endforeach; ?>
                    <tr id="emptyRow" style="display:none;"><td colspan="9" class="empty-state">کاربری یافت نشد</td></tr>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>
    </div>

    <?php else: ?>

    <div class="user-detail-header">
        <h2>
            <svg width="24" height="24" viewBox="0 0 24 24" fill="#0f172a"><path d="M12 12c2.21 0 4-1.79 4-4s-1.79-4-4-4-4 1.79-4 4 1.79 4 4 4zm0 2c-2.67 0-8 1.34-8 4v2h16v-2c0-2.66-5.33-4-8-4z"/></svg>
            <?= htmlspecialchars(getRealName($selectedUser)) ?>
            <span>نام کاربری: <?= htmlspecialchars($selectedUser) ?></span>
        </h2>
        <a href="?days=<?= $days ?>" class="btn-close-detail">✖ بستن و بازگشت</a>
    </div>

    <div class="top-widgets-grid">
        <div class="chart-card">
            <div class="section-title">
                <span class="title-accent"></span>
                نمودار حضور روزانه (دقیقه)
            </div>
            <?php if (empty($userChartLabels)): ?>
                <div class="empty-state">داده‌ای برای نمایش نمودار وجود ندارد</div>
            <?php else: ?>
                <canvas id="userChart" height="100"></canvas>
            <?php endif; ?>
        </div>

        <div class="chart-card">
            <div class="section-title">
                <span class="title-accent" style="background:#8b5cf6"></span>
                خلاصه وضعیت کاربر
            </div>
            <?php
                $thisUserStat = null;
                foreach($userStats as $us) { if($us['username'] === $selectedUser) { $thisUserStat = $us; break; } }
            ?>
            <?php if($thisUserStat): ?>
                <div style="display:flex; flex-direction:column; gap:15px; margin-top:20px;">
                    <div style="background:#f8fafc; padding:15px; border-radius:8px; border:1px solid #e2e8f0;">
                        <span style="color:#64748b; font-size:13px; display:block; margin-bottom:5px;">مجموع حضور:</span>
                        <strong style="color:#0f172a; font-size:18px;"><?= formatDuration($thisUserStat['total_duration']) ?></strong>
                    </div>
                    <div style="background:#f8fafc; padding:15px; border-radius:8px; border:1px solid #e2e8f0;">
                        <span style="color:#64748b; font-size:13px; display:block; margin-bottom:5px;">تعداد کل ورودها:</span>
                        <strong style="color:#0f172a; font-size:18px;"><?= $thisUserStat['total_sessions'] ?> بار</strong>
                    </div>
                    <div style="background:#f8fafc; padding:15px; border-radius:8px; border:1px solid #e2e8f0;">
                        <span style="color:#64748b; font-size:13px; display:block; margin-bottom:5px;">روزهای فعال:</span>
                        <strong style="color:#0f172a; font-size:18px;"><?= $thisUserStat['active_days'] ?> روز</strong>
                    </div>
                </div>
            <?php else: ?>
                <div class="empty-state">اطلاعاتی یافت نشد</div>
            <?php endif; ?>
        </div>
    </div>

    <div class="table-card">
        <div class="section-title">
            <span class="title-accent"></span>
            لیست ورود و خروج‌ها (سشن‌ها)
        </div>
        <div class="table-responsive">
            <table>
                <thead>
                    <tr>
                        <th>زمان ورود</th>
                        <th>آخرین فعالیت</th>
                        <th>زمان خروج</th>
                        <th>مدت زمان</th>
                        <th>وضعیت</th>
                        <th>آی‌پی (IP)</th>
                    </tr>
                </thead>
                <tbody>
                    <?php if (empty($userSessions)): ?>
                    <tr><td colspan="6" class="empty-state">سشنی ثبت نشده</td></tr>
                    <?php else: ?>
                    <?php foreach ($userSessions as $sess): ?>
                    <?php 
                        $statusClass = 'badge-offline';
                        $statusText = 'آفلاین';
                        if ($sess['is_active']) {
                            $idleTime = time() - strtotime($sess['last_activity']);
                            if ($idleTime > 300) {
                                $statusClass = 'badge-idle';
                                $statusText = 'بیکار';
                            } else {
                                $statusClass = 'badge-online';
                                $statusText = 'آنلاین';
                            }
                        }
                    ?>
                    <tr>
                        <td style="direction:ltr;text-align:right"><?= showDate($sess['login_time']) ?></td>
                        <td style="direction:ltr;text-align:right"><?= showDate($sess['last_activity']) ?></td>
                        <td style="direction:ltr;text-align:right"><?= $sess['logout_time'] ? showDate($sess['logout_time']) : '-' ?></td>
                        <td><strong><?= formatDuration($sess['calc_duration']) ?></strong></td>
                        <td><span class="badge <?= $statusClass ?>"><?= $statusText ?></span></td>
                        <td style="direction:ltr"><?= htmlspecialchars($sess['ip_address']) ?></td>
                    </tr>
                    <?php endforeach; ?>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>
    </div>

    <div class="table-card">
        <div class="section-title">
            <span class="title-accent" style="background:#f43f5e"></span>
            لاگ جزئیات فعالیت
        </div>
        <div class="action-log">
            <?php if (empty($userActions)): ?>
                <div class="empty-state">هیچ اکشنی برای این کاربر ثبت نشده است.</div>
            <?php else: ?>
                <?php foreach ($userActions as $act): ?>
                <div class="action-item">
                    <span class="action-time"><?= showDate($act['timestamp']) ?></span>
                    <span class="action-type"><?= htmlspecialchars($act['action_type']) ?></span>
                    <span class="action-detail"><?= htmlspecialchars($act['action_detail']) ?></span>
                </div>
                <?php endforeach; ?>
            <?php endif; ?>
        </div>
    </div>

    <?php endif; ?>
</div>

<script>
function changeDays(val) {
    const params = new URLSearchParams(window.location.search);
    params.set('days', val);
    window.location.search = params.toString();
}

function switchTab(tabId) {
    document.querySelectorAll('.tab-btn').forEach(b => b.classList.remove('active'));
    document.querySelectorAll('.tab-content').forEach(c => c.classList.remove('active'));
    event.target.classList.add('active');
    document.getElementById('tab-' + tabId).classList.add('active');
}

function filterTable() {
    let input = document.getElementById("userSearch");
    let filter = input.value.toUpperCase();
    let table = document.getElementById("usersTable");
    let tr = table.getElementsByTagName("tr");
    let visibleCount = 0;

    for (let i = 1; i < tr.length; i++) {
        if (tr[i].id === 'emptyRow') continue;
        let td = tr[i].getElementsByTagName("td")[0];
        if (td) {
            let txtValue = td.textContent || td.innerText;
            if (txtValue.toUpperCase().indexOf(filter) > -1) {
                tr[i].style.display = "";
                visibleCount++;
            } else {
                tr[i].style.display = "none";
            }
        }       
    }
    document.getElementById("emptyRow").style.display = visibleCount === 0 ? "" : "none";
}

Chart.defaults.font.family = 'YekanBakh';
Chart.defaults.color = '#64748b';

<?php if (!$selectedUser): ?>
const dailyData = <?= json_encode(array_reverse($dailyStats)) ?>;
if(document.getElementById('dailyChart')) {
    new Chart(document.getElementById('dailyChart'), {
        type: 'line',
        data: {
            labels: dailyData.map(d => d.date), // برای شمسی کردن این لیبل‌ها نیاز به تبدیل سمت سرور در getDailyStats است
            datasets: [
                {
                    label: 'تعداد ورود',
                    data: dailyData.map(d => d.total_sessions),
                    borderColor: '#3b82f6',
                    backgroundColor: 'rgba(59,130,246,0.1)',
                    fill: true, tension: 0.3, borderWidth: 2
                },
                {
                    label: 'کاربران فعال',
                    data: dailyData.map(d => d.unique_users),
                    borderColor: '#16a34a',
                    backgroundColor: 'rgba(22,163,74,0.1)',
                    fill: true, tension: 0.3, borderWidth: 2
                }
            ]
        },
        options: {
            responsive: true,
            interaction: { mode: 'index', intersect: false },
            plugins: { tooltip: { cornerRadius: 8, padding: 12 } },
            scales: { x: { grid: { display: false } }, y: { grid: { color: '#f1f5f9' }, beginAtZero: true } }
        }
    });
}
<?php else: ?>
const userChartLabels = <?= json_encode($userChartLabels) ?>;
const userChartData = <?= json_encode($userChartData) ?>;

if(document.getElementById('userChart')) {
    new Chart(document.getElementById('userChart'), {
        type: 'bar',
        data: {
            labels: userChartLabels,
            datasets: [{
                label: 'میزان حضور (دقیقه)',
                data: userChartData,
                backgroundColor: '#3b82f6',
                borderRadius: 4
            }]
        },
        options: {
            responsive: true,
            plugins: { legend: { display: false }, tooltip: { cornerRadius: 8, padding: 12 } },
            scales: { x: { grid: { display: false } }, y: { grid: { color: '#f1f5f9' }, beginAtZero: true, title: { display: true, text: 'دقیقه' } } }
        }
    });
}
<?php endif; ?>
</script>
</body>
</html>
