<?php

declare(strict_types=1);

require_once __DIR__ . '/../../src/db.php';
require_once __DIR__ . '/../../src/SuperAdmin/SuperAdminAuth.php';
require_once __DIR__ . '/navigation.php';

SuperAdminAuth::requirePermission('activity_log_view');

$admin = SuperAdminAuth::getCurrentAdmin();
$pdo = getPDO();

// Get filters
$page = max(1, (int)($_GET['page'] ?? 1));
$perPage = 50;
$offset = ($page - 1) * $perPage;

$where = ['1=1'];
$params = [];

if (!empty($_GET['admin_id'])) {
    $where[] = 'sal.admin_id = ?';
    $params[] = (int)$_GET['admin_id'];
}

if (!empty($_GET['action'])) {
    $where[] = 'sal.action = ?';
    $params[] = $_GET['action'];
}

if (!empty($_GET['date_from'])) {
    $where[] = 'sal.created_at >= ?';
    $params[] = $_GET['date_from'];
}

if (!empty($_GET['date_to'])) {
    $where[] = 'sal.created_at <= ?';
    $params[] = $_GET['date_to'] . ' 23:59:59';
}

$whereClause = implode(' AND ', $where);

// Get total count
$countStmt = $pdo->prepare("SELECT COUNT(*) FROM super_admin_activity_log sal WHERE $whereClause");
$countStmt->execute($params);
$total = (int)$countStmt->fetchColumn();
$totalPages = ceil($total / $perPage);

// Get activities
$sql = "
    SELECT sal.*, sa.name as admin_name, sa.email as admin_email
    FROM super_admin_activity_log sal
    LEFT JOIN super_admins sa ON sal.admin_id = sa.id
    WHERE $whereClause
    ORDER BY sal.created_at DESC
    LIMIT $perPage OFFSET $offset
";
$stmt = $pdo->prepare($sql);
$stmt->execute($params);
$activities = $stmt->fetchAll();

// Get admins for filter
$admins = $pdo->query('SELECT id, name FROM super_admins ORDER BY name')->fetchAll();

// Get unique actions for filter
$actions = $pdo->query('SELECT DISTINCT action FROM super_admin_activity_log ORDER BY action')->fetchAll();
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Activity Log · Keelance Admin</title>
    <link rel="icon" type="image/png" href="/assets/favicon.png">
    <script src="https://cdn.tailwindcss.com"></script>
</head>
<body class="bg-slate-100 min-h-screen text-slate-900">
<div class="min-h-screen flex flex-col">
<?php renderAdminNavigation(); ?>

<main class="flex-1">
    <div class="max-w-6xl mx-auto px-4 py-6 space-y-6">
        <div class="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-3">
            <div>
                <h1 class="text-2xl font-bold text-slate-900 tracking-tight">Admin Activity Log</h1>
                <p class="text-slate-500 mt-1 text-sm">Track super admin logins, changes, and sensitive actions across the platform.</p>
            </div>
        </div>

        <!-- Filters -->
        <div class="bg-white border border-slate-200 shadow-sm rounded-xl p-4">
        <form method="GET" class="flex flex-wrap gap-4">
            <div class="flex-1 min-w-[150px]">
                <label class="block text-xs text-slate-500 mb-1">Admin</label>
                <select name="admin_id" class="w-full px-3 py-2 bg-slate-50 border border-slate-300 rounded-lg text-slate-900 text-sm focus:outline-none focus:ring-2 focus:ring-blue-500">
                    <option value="">All Admins</option>
                    <?php foreach ($admins as $a): ?>
                        <option value="<?= $a['id'] ?>" <?= ($_GET['admin_id'] ?? '') == $a['id'] ? 'selected' : '' ?>>
                            <?= htmlspecialchars($a['name']) ?>
                        </option>
                    <?php endforeach; ?>
                </select>
            </div>
            
            <div class="flex-1 min-w-[150px]">
                <label class="block text-xs text-slate-500 mb-1">Action</label>
                <select name="action" class="w-full px-3 py-2 bg-slate-50 border border-slate-300 rounded-lg text-slate-900 text-sm focus:outline-none focus:ring-2 focus:ring-blue-500">
                    <option value="">All Actions</option>
                    <?php foreach ($actions as $a): ?>
                        <option value="<?= $a['action'] ?>" <?= ($_GET['action'] ?? '') === $a['action'] ? 'selected' : '' ?>>
                            <?= htmlspecialchars($a['action']) ?>
                        </option>
                    <?php endforeach; ?>
                </select>
            </div>
            
            <div>
                <label class="block text-xs text-slate-500 mb-1">From</label>
                <input type="date" name="date_from" value="<?= $_GET['date_from'] ?? '' ?>"
                       class="px-3 py-2 bg-slate-50 border border-slate-300 rounded-lg text-slate-900 text-sm focus:outline-none focus:ring-2 focus:ring-blue-500">
            </div>
            
            <div>
                <label class="block text-xs text-slate-500 mb-1">To</label>
                <input type="date" name="date_to" value="<?= $_GET['date_to'] ?? '' ?>"
                       class="px-3 py-2 bg-slate-50 border border-slate-300 rounded-lg text-slate-900 text-sm focus:outline-none focus:ring-2 focus:ring-blue-500">
            </div>
            
            <div class="flex items-end gap-2">
                <button type="submit" class="px-4 py-2 bg-blue-600 hover:bg-blue-700 text-white rounded-lg text-sm font-medium transition-colors">
                    Filter
                </button>
                <a href="/admin/activity.php" class="px-4 py-2 bg-slate-50 hover:bg-slate-100 border border-slate-200 rounded-lg text-sm font-medium text-slate-700 transition-colors">
                    Clear
                </a>
            </div>
        </form>
    </div>

    <!-- Activity List -->
    <div class="bg-white border border-slate-200 shadow-sm rounded-xl overflow-hidden">
        <div class="px-4 py-3 border-b border-slate-200 flex items-center justify-between">
            <p class="text-sm text-slate-500"><?= number_format($total) ?> activities</p>
        </div>
        
        <?php if (empty($activities)): ?>
            <div class="text-center py-12">
                <p class="text-slate-500">No activity found</p>
            </div>
        <?php else: ?>
            <div class="divide-y divide-slate-100">
                <?php foreach ($activities as $activity): ?>
                    <?php
                    $actionMap = [
                        'login' => 'logged in',
                        'logout' => 'logged out',
                        'login_as_user' => 'logged in as user',
                        'update_settings' => 'updated settings',
                        'create_plan' => 'created plan',
                        'update_plan' => 'updated plan',
                        'delete_plan' => 'deactivated plan',
                        'create_admin' => 'created admin',
                        'update_admin_permissions' => 'updated admin permissions',
                        'activate_admin' => 'activated admin',
                        'deactivate_admin' => 'deactivated admin',
                        'delete_admin' => 'deleted admin',
                    ];
                    $rawAction = $activity['action'] ?? '';
                    $actionLabel = $actionMap[$rawAction] ?? str_replace('_', ' ', $rawAction);

                    $detailsSummary = null;
                    if (!empty($activity['details'])) {
                        $decoded = json_decode((string)$activity['details'], true);
                        if (json_last_error() === JSON_ERROR_NONE && is_array($decoded)) {
                            $parts = [];
                            foreach ($decoded as $key => $value) {
                                if ($key === 'ip') {
                                    // IP is shown separately below
                                    continue;
                                }
                                if (is_scalar($value)) {
                                    $parts[] = $key . ': ' . $value;
                                }
                            }
                            if ($parts) {
                                $detailsSummary = implode(' · ', $parts);
                            }
                        } else {
                            $detailsSummary = substr((string)$activity['details'], 0, 140);
                        }
                    }
                    ?>
                    <div class="px-4 py-3 hover:bg-slate-50">
                        <div class="flex items-start gap-3">
                            <div class="w-8 h-8 rounded-full bg-blue-500/10 border border-blue-100 flex items-center justify-center flex-shrink-0">
                                <span class="text-blue-400 text-xs font-medium">
                                    <?= strtoupper(substr($activity['admin_name'] ?? 'A', 0, 2)) ?>
                                </span>
                            </div>
                            <div class="flex-1 min-w-0">
                                <p class="text-sm">
                                    <span class="font-medium text-slate-900"><?= htmlspecialchars($activity['admin_name'] ?? 'Unknown') ?></span>
                                    <span class="text-slate-500"><?= $actionLabel ?></span>
                                    <?php if ($activity['entity_type']): ?>
                                        <span class="text-slate-700">
                                            <?= htmlspecialchars($activity['entity_type']) ?>
                                            <?php if ($activity['entity_id']): ?>
                                                <span class="text-slate-500">#<?= (int)$activity['entity_id'] ?></span>
                                            <?php endif; ?>
                                        </span>
                                    <?php endif; ?>
                                </p>
                                <?php if ($detailsSummary): ?>
                                    <p class="text-xs text-slate-500 mt-1">
                                        <?= htmlspecialchars($detailsSummary) ?>
                                    </p>
                                <?php endif; ?>
                                <div class="flex flex-wrap items-center gap-3 mt-1 text-xs text-slate-500">
                                    <span><?= date('M j, Y H:i:s', strtotime($activity['created_at'])) ?></span>
                                    <?php if ($activity['ip_address']): ?>
                                        <span class="inline-flex items-center gap-1 rounded-full border border-slate-200 px-2 py-0.5 text-slate-600 bg-slate-50">
                                            <span>IP:</span>
                                            <span><?= htmlspecialchars($activity['ip_address']) ?></span>
                                        </span>
                                    <?php endif; ?>
                                </div>
                            </div>
                        </div>
                    </div>
                <?php endforeach; ?>
            </div>
        <?php endif; ?>
    </div>

    <!-- Pagination -->
    <?php if ($totalPages > 1): ?>
        <div class="flex justify-center gap-2 mt-6">
            <?php 
            $queryParams = $_GET;
            for ($i = max(1, $page - 3); $i <= min($totalPages, $page + 3); $i++): 
                $queryParams['page'] = $i;
            ?>
                <a href="?<?= http_build_query($queryParams) ?>"
                   class="px-4 py-2 rounded-full text-sm <?= $i === $page ? 'bg-blue-600 text-white' : 'bg-white border border-slate-200 shadow-sm text-slate-600 hover:bg-slate-50' ?>">
                    <?= $i ?>
                </a>
            <?php endfor; ?>
        </div>
    <?php endif; ?>
</main>

<?php renderAdminFooter(); ?>
</div>
</body>
</html>
