<?php
// dashboard.php — Admin Activity Dashboard
require_once 'auth.php';
check_access();

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

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

$days = intval($_GET['days'] ?? 30);
$selectedUser = $_GET['user'] ?? '';

$onlineUsers = $tracker->getOnlineUsers();
$dailyStats = $tracker->getDailyStats($days);
$userStats = $tracker->getUserStats($days);
$hourlyActivity = $tracker->getHourlyActivity($days);
$topActions = $tracker->getTopActions($days);

$userSessions = [];
$userActions = [];
if ($selectedUser) {
    $userSessions = $tracker->getUserSessions($selectedUser, $days);
    $userActions = $tracker->getUserActions($selectedUser, min($days, 7));
}

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="https://cdn.jsdelivr.net/npm/chart.js@4.4.0/dist/chart.umd.min.js"></script>
<style>
    * { margin: 0; padding: 0; box-sizing: border-box; }

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

    /* ===== Top Bar ===== */
    .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);
    }

    .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;
        font-family: inherit;
    }

    .top-bar a:hover, .top-bar select:hover {
        background: #e2e8f0;
        border-color: #94a3b8;
    }

    .top-bar select:focus {
        outline: 2px solid #3b82f6;
        outline-offset: 1px;
    }

    /* ===== Dashboard Container ===== */
    .dashboard {
        max-width: 1400px;
        margin: 0 auto;
        padding: 28px;
    }

    /* ===== Summary Cards ===== */
    .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: box-shadow 0.2s ease, transform 0.2s ease;
    }

    .summary-card:hover {
        box-shadow: 0 4px 12px rgba(0,0,0,0.07);
        transform: translateY(-1px);
    }

    .summary-card .icon {
        width: 40px;
        height: 40px;
        border-radius: 10px;
        display: inline-flex;
        align-items: center;
        justify-content: center;
        margin-bottom: 10px;
        font-size: 18px;
        font-weight: 700;
        color: #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; }

    .summary-card.avg .icon  { background: #db2777; }
    .summary-card.avg .value { color: #db2777; }

    /* ===== Online Users Section ===== */
    .online-section {
        background: #ffffff;
        border: 1px solid #e2e8f0;
        border-radius: 12px;
        padding: 22px;
        margin-bottom: 28px;
        box-shadow: 0 1px 4px rgba(0,0,0,0.04);
    }

    .section-title {
        font-size: 15px;
        font-weight: 700;
        margin-bottom: 16px;
        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-dot {
        width: 9px;
        height: 9px;
        background: #22c55e;
        border-radius: 50%;
        animation: pulse 2s infinite;
        flex-shrink: 0;
    }

    @keyframes pulse {
        0%, 100% { opacity: 1; }
        50% { opacity: 0.35; }
    }

    .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;
    }

    .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 .meta {
        font-size: 11.5px;
        color: #64748b;
        margin-top: 6px;
        line-height: 1.6;
    }

    .online-user .meta span {
        margin-left: 14px;
    }

    /* ===== Charts Row ===== */
    .charts-row {
        display: grid;
        grid-template-columns: 2fr 1fr;
        gap: 16px;
        margin-bottom: 28px;
    }

    .chart-card {
        background: #ffffff;
        border: 1px solid #e2e8f0;
        border-radius: 12px;
        padding: 22px;
        box-shadow: 0 1px 4px rgba(0,0,0,0.04);
    }

    /* ===== Tables ===== */
    .table-card {
        background: #ffffff;
        border: 1px solid #e2e8f0;
        border-radius: 12px;
        padding: 22px;
        margin-bottom: 28px;
        overflow-x: auto;
        box-shadow: 0 1px 4px rgba(0,0,0,0.04);
    }

    table {
        width: 100%;
        border-collapse: separate;
        border-spacing: 0;
    }

    table th {
        background: #f8fafc;
        padding: 11px 14px;
        text-align: right;
        font-size: 12px;
        color: #64748b;
        font-weight: 700;
        white-space: nowrap;
        border-bottom: 2px solid #e2e8f0;
        text-transform: uppercase;
        letter-spacing: 0.3px;
    }

    table td {
        padding: 11px 14px;
        font-size: 13px;
        border-bottom: 1px solid #f1f5f9;
        white-space: nowrap;
        color: #334155;
    }

    table tr:hover td {
        background: #f8fafc;
    }

    table tr:last-child td {
        border-bottom: none;
    }

    table a {
        color: #2563eb;
        text-decoration: none;
        font-weight: 600;
    }

    table a:hover {
        text-decoration: underline;
    }

    .badge {
        display: inline-block;
        padding: 3px 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-offline{ background: #f1f5f9; color: #94a3b8; }

    /* ===== User Detail Header ===== */
    .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;
        box-shadow: 0 1px 4px rgba(0,0,0,0.04);
    }

    .user-detail-header h2 {
        font-size: 20px;
        color: #0f172a;
        font-weight: 700;
    }

    .btn-close-detail {
        background: #f1f5f9;
        color: #475569;
        padding: 8px 18px;
        border-radius: 8px;
        text-decoration: none;
        font-size: 13px;
        font-weight: 600;
        border: 1px solid #e2e8f0;
        transition: all 0.15s ease;
    }

    .btn-close-detail:hover {
        background: #e2e8f0;
        color: #1e293b;
    }

    /* ===== Action Log ===== */
    .action-log {
        max-height: 420px;
        overflow-y: auto;
    }

    .action-log::-webkit-scrollbar {
        width: 6px;
    }

    .action-log::-webkit-scrollbar-track {
        background: #f8fafc;
        border-radius: 3px;
    }

    .action-log::-webkit-scrollbar-thumb {
        background: #cbd5e1;
        border-radius: 3px;
    }

    .action-item {
        display: flex;
        gap: 14px;
        padding: 10px 14px;
        border-bottom: 1px solid #f1f5f9;
        font-size: 12.5px;
        align-items: flex-start;
        transition: background 0.1s ease;
    }

    .action-item:hover {
        background: #f8fafc;
    }

    .action-item:last-child {
        border-bottom: none;
    }

    .action-time {
        color: #94a3b8;
        min-width: 135px;
        direction: ltr;
        text-align: right;
        font-variant-numeric: tabular-nums;
        font-size: 11.5px;
    }

    .action-type {
        background: #f1f5f9;
        color: #475569;
        padding: 2px 10px;
        border-radius: 6px;
        font-size: 11px;
        min-width: 105px;
        text-align: center;
        font-weight: 600;
    }

    .action-detail {
        color: #334155;
        flex: 1;
    }

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

    /* ===== Responsive ===== */
    @media (max-width: 768px) {
        .charts-row { grid-template-columns: 1fr; }
        .summary-grid { grid-template-columns: repeat(2, 1fr); }
        .dashboard { padding: 14px; }
        .top-bar { padding: 12px 16px; }
        .top-bar h1 { font-size: 16px; }
    }
</style>
</head>
<body>

<div class="top-bar">
    <h1>داشبورد فعالیت کاربران</h1>
    <div class="top-bar-actions">
        <select onchange="changeDays(this.value)" id="days-select">
            <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>
        <a href="index.php">برگشت به نقشه</a>
        <a href="logout.php">خروج</a>
    </div>
</div>

<div class="dashboard">

    <!-- ===== Summary Cards ===== -->
    <div class="summary-grid">
        <div class="summary-card online">
            <div class="icon">O</div>
            <div class="value"><?= count($onlineUsers) ?></div>
            <div class="label">آنلاین الان</div>
        </div>
        <div class="summary-card users">
            <div class="icon">U</div>
            <div class="value"><?= $uniqueUsersTotal ?></div>
            <div class="label">کاربر فعال (<?= $days ?> روز)</div>
        </div>
        <div class="summary-card sessions">
            <div class="icon">S</div>
            <div class="value"><?= $totalSessions ?></div>
            <div class="label">کل سشن‌ها</div>
        </div>
        <div class="summary-card duration">
            <div class="icon">T</div>
            <div class="value"><?= formatDurationShort($totalDuration) ?></div>
            <div class="label">مجموع حضور</div>
        </div>
        <div class="summary-card avg">
            <div class="icon">A</div>
            <div class="value"><?= formatDurationShort($avgSessionDuration) ?></div>
            <div class="label">میانگین هر سشن</div>
        </div>
    </div>

    <!-- ===== Online Users ===== -->
    <?php if (!empty($onlineUsers)): ?>
    <div class="online-section">
        <div class="section-title">
            <span class="online-dot"></span>
            کاربران آنلاین (<?= count($onlineUsers) ?> نفر)
        </div>
        <div class="online-list">
            <?php foreach ($onlineUsers as $ou): ?>
            <div class="online-user">
                <div class="name">
                    <?= htmlspecialchars($ou['username']) ?>
                    <span class="badge <?= $ou['user_role']==='admin' ? 'badge-admin' : 'badge-area' ?>">
                        <?= $ou['user_role']==='admin' ? 'ادمین' : 'مدیر منطقه' ?>
                    </span>
                </div>
                <div class="meta">
                    <span>مدت: <?= formatDuration($ou['duration']) ?></span>
                    <span>ورود: <?= $ou['login_time'] ?></span>
                    <span>IP: <?= htmlspecialchars($ou['ip_address']) ?></span>
                </div>
            </div>
            <?php endforeach; ?>
        </div>
    </div>
    <?php endif; ?>

    <!-- ===== Charts ===== -->
    <div class="charts-row">
        <div class="chart-card">
            <div class="section-title">
                <span class="title-accent"></span>
                روند سشن‌ها و کاربران
            </div>
            <canvas id="dailyChart" height="100"></canvas>
        </div>
        <div class="chart-card">
            <div class="section-title">
                <span class="title-accent"></span>
                ساعات فعالیت
            </div>
            <canvas id="hourlyChart" height="200"></canvas>
        </div>
    </div>

    <!-- ===== User Table ===== -->
    <div class="table-card">
        <div class="section-title">
            <span class="title-accent"></span>
            آمار کاربران (<?= $days ?> روز اخیر)
        </div>
        <table>
            <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><td colspan="9" class="empty-state">هنوز داده‌ای ثبت نشده</td></tr>
                <?php else: ?>
                <?php foreach ($userStats as $us): ?>
                <tr>
                    <td><strong><?= htmlspecialchars($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"><?= $us['last_login'] ?></td>
                    <td><a href="?user=<?= urlencode($us['username']) ?>&days=<?= $days ?>">مشاهده</a></td>
                </tr>
                <?php endforeach; ?>
                <?php endif; ?>
            </tbody>
        </table>
    </div>

    <!-- ===== Top Actions ===== -->
    <div class="table-card">
        <div class="section-title">
            <span class="title-accent"></span>
            پرتکرارترین اکشن‌ها
        </div>
        <table>
            <thead>
                <tr>
                    <th>نوع اکشن</th>
                    <th>جزئیات</th>
                    <th>تعداد</th>
                </tr>
            </thead>
            <tbody>
                <?php if (empty($topActions)): ?>
                <tr><td colspan="3" class="empty-state">اکشنی ثبت نشده</td></tr>
                <?php else: ?>
                <?php foreach ($topActions as $ta): ?>
                <tr>
                    <td><span class="action-type"><?= htmlspecialchars($ta['action_type']) ?></span></td>
                    <td><?= htmlspecialchars($ta['action_detail']) ?></td>
                    <td><strong><?= $ta['count'] ?></strong></td>
                </tr>
                <?php endforeach; ?>
                <?php endif; ?>
            </tbody>
        </table>
    </div>

    <!-- ===== User Detail ===== -->
    <?php if ($selectedUser): ?>
    <div class="user-detail-header">
        <h2>جزئیات کاربر: <?= htmlspecialchars($selectedUser) ?></h2>
        <a href="?days=<?= $days ?>" class="btn-close-detail">بستن</a>
    </div>

    <!-- Sessions -->
    <div class="table-card">
        <div class="section-title">
            <span class="title-accent"></span>
            سشن‌ها
        </div>
        <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): ?>
                <tr>
                    <td style="direction:ltr;text-align:right"><?= $sess['login_time'] ?></td>
                    <td style="direction:ltr;text-align:right"><?= $sess['last_activity'] ?></td>
                    <td style="direction:ltr;text-align:right"><?= $sess['logout_time'] ?: '-' ?></td>
                    <td><?= formatDuration($sess['calc_duration']) ?></td>
                    <td>
                        <span class="badge <?= $sess['is_active'] ? 'badge-online' : 'badge-offline' ?>">
                            <?= $sess['is_active'] ? 'آنلاین' : 'آفلاین' ?>
                        </span>
                    </td>
                    <td style="direction:ltr"><?= htmlspecialchars($sess['ip_address']) ?></td>
                </tr>
                <?php endforeach; ?>
                <?php endif; ?>
            </tbody>
        </table>
    </div>

    <!-- Actions Log -->
    <div class="table-card">
        <div class="section-title">
            <span class="title-accent"></span>
            لاگ اکشن‌ها (7 روز اخیر)
        </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"><?= $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();
}

// ===== Daily Chart =====
const dailyData = <?= json_encode(array_reverse($dailyStats)) ?>;
const dailyLabels = dailyData.map(d => d.date);
const dailySessions = dailyData.map(d => d.total_sessions);
const dailyUsers = dailyData.map(d => d.unique_users);

new Chart(document.getElementById('dailyChart'), {
    type: 'line',
    data: {
        labels: dailyLabels,
        datasets: [
            {
                label: 'سشن‌ها',
                data: dailySessions,
                borderColor: '#3b82f6',
                backgroundColor: 'rgba(59,130,246,0.08)',
                fill: true,
                tension: 0.4,
                borderWidth: 2.5,
                pointRadius: 3,
                pointBackgroundColor: '#3b82f6'
            },
            {
                label: 'کاربران یکتا',
                data: dailyUsers,
                borderColor: '#16a34a',
                backgroundColor: 'rgba(22,163,74,0.08)',
                fill: true,
                tension: 0.4,
                borderWidth: 2.5,
                pointRadius: 3,
                pointBackgroundColor: '#16a34a'
            }
        ]
    },
    options: {
        responsive: true,
        interaction: {
            intersect: false,
            mode: 'index'
        },
        plugins: {
            legend: {
                labels: {
                    color: '#475569',
                    font: { size: 12, weight: '600' },
                    usePointStyle: true,
                    pointStyle: 'circle'
                }
            },
            tooltip: {
                backgroundColor: '#1e293b',
                titleColor: '#f1f5f9',
                bodyColor: '#e2e8f0',
                borderColor: '#334155',
                borderWidth: 1,
                cornerRadius: 8,
                padding: 10
            }
        },
        scales: {
            x: {
                ticks: { color: '#94a3b8', maxRotation: 45, font: { size: 11 } },
                grid: { color: '#f1f5f9' }
            },
            y: {
                ticks: { color: '#94a3b8', font: { size: 11 } },
                grid: { color: '#f1f5f9' },
                beginAtZero: true
            }
        }
    }
});

// ===== Hourly Chart =====
const hourlyData = <?= json_encode(array_values($hourlyActivity)) ?>;
const hourlyLabels = Array.from({length: 24}, (_, i) => `${i}:00`);

new Chart(document.getElementById('hourlyChart'), {
    type: 'bar',
    data: {
        labels: hourlyLabels,
        datasets: [{
            label: 'فعالیت',
            data: hourlyData,
            backgroundColor: hourlyData.map((v) => {
                const max = Math.max(...hourlyData);
                const ratio = max > 0 ? v / max : 0;
                return `rgba(59, 130, 246, ${0.15 + ratio * 0.75})`;
            }),
            borderColor: '#3b82f6',
            borderWidth: 1,
            borderRadius: 5,
            borderSkipped: false
        }]
    },
    options: {
        responsive: true,
        plugins: {
            legend: { display: false },
            tooltip: {
                backgroundColor: '#1e293b',
                titleColor: '#f1f5f9',
                bodyColor: '#e2e8f0',
                cornerRadius: 8,
                padding: 10
            }
        },
        scales: {
            x: {
                ticks: { color: '#94a3b8', font: { size: 10 } },
                grid: { display: false }
            },
            y: {
                ticks: { color: '#94a3b8', font: { size: 10 } },
                grid: { color: '#f1f5f9' },
                beginAtZero: true
            }
        }
    }
});
</script>
</body>
</html>
