<?php
session_start();
require_once '../config/db.php';

function status_display_label($status)
{
    $s = strtolower(trim((string) ($status ?? '')));
    $labels = ['approved' => 'Active', 'deactivated' => 'Inactive', 'withdrawn' => 'Inactive', 'rejected' => 'Unrecognized', 'pending' => 'Pending'];
    return $labels[$s] ?? $status;
}

if (!isset($_SESSION['admin_id'])) {
    if (isset($_SESSION['user_role']) && in_array($_SESSION['user_role'], ['AC', 'AAC', 'NROI', 'PPSA'])) {
        header("Location: ../officer/dashboard.php");
    } else {
        header("Location: ../index.php");
    }
    exit;
}

$search = isset($_GET['search']) ? trim($_GET['search']) : '';
$view_mode = isset($_GET['view']) ? $_GET['view'] : 'daily';
$filter_date = isset($_GET['date']) ? $_GET['date'] : '';
$selected_week = isset($_GET['week']) ? $_GET['week'] : '';
$selected_month = isset($_GET['month']) ? $_GET['month'] : '';

// Fetch activity logs
try {
    $whereClause = "WHERE al.performed_by_role IN ('ADMIN', 'AC', 'AAC', 'PPSA', 'NROI')";
    $params = [];

    if ($search !== '') {
        $whereClause .= " AND (al.description LIKE ? OR al.reference_type LIKE ? OR u.first_name LIKE ? OR u.last_name LIKE ? OR a.username LIKE ?)";
        $searchTerm = "%$search%";
        $params = array_fill(0, 5, $searchTerm);
    }

    if ($filter_date !== '') {
        $whereClause .= " AND DATE(al.created_at) = ?";
        $params[] = $filter_date;
        $view_mode = 'daily';
    }

    $sql = "SELECT al.*, 
                CASE 
                    WHEN al.performed_by_role = 'ADMIN' THEN COALESCE(a.username, 'Admin')
                    ELSE CONCAT(u.first_name, ' ', u.last_name)
                END as performer_name
            FROM activity_logs al
            LEFT JOIN users u ON al.performed_by_user_id = u.id
            LEFT JOIN admins a ON al.performed_by_admin_id = a.id
            $whereClause
            ORDER BY al.created_at DESC";
    $stmt = $pdo->prepare($sql);
    $stmt->execute($params);
    $activityLogs = $stmt->fetchAll(PDO::FETCH_ASSOC);

    // Grouping logic
    $groupedLogs = [];
    foreach ($activityLogs as $log) {
        $logTime = strtotime($log['created_at']);
        if ($view_mode === 'weekly') {
            $groupKey = date('o-W', $logTime);
        } elseif ($view_mode === 'monthly') {
            $groupKey = date('Y-m', $logTime);
        } else {
            $groupKey = date('Y-m-d', $logTime);
        }
        $groupedLogs[$groupKey][] = $log;
    }
} catch (Exception $e) {
    $groupedLogs = [];
}
?>
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>System Logs | NROI Portal</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=Inter:wght@300;400;500;600;700;800&display=swap"
        rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <link rel="stylesheet" href="../assets/css/loader.css">
    <link rel="stylesheet" href="../assets/css/style.css">
    <link rel="stylesheet" href="../assets/css/dashboard.css">
    <link rel="icon" type="image/png" href="../assets/images/nroi_logo.png">
</head>

<body class="dashboard-body">
    <?php include '../includes/loader.php'; ?>

    <aside class="sidebar">
        <div class="sidebar-brand-area">
            <div class="sidebar-role-badge">ADMIN</div>
        </div>
        <ul class="sidebar-menu">
            <li class="sidebar-item">
                <a href="dashboard.php" class="sidebar-link">
                    <i class="fas fa-th-large"></i> Overview
                </a>
            </li>
            <li class="sidebar-item">
                <a href="../api/users.php" class="sidebar-link">
                    <i class="fas fa-user-friends"></i> Accounts
                </a>
            </li>
            <li class="sidebar-item">
                <a href="management.php" class="sidebar-link">
                    <i class="fas fa-cog"></i> Management
                </a>
            </li>
            <li class="sidebar-item">
                <a href="../api/matches.php" class="sidebar-link">
                    <i class="fas fa-trophy"></i> Matches
                </a>
            </li>
            <li class="sidebar-item">
                <a href="../api/request.php" class="sidebar-link">
                    <i class="fas fa-inbox"></i> For Approval
                </a>
            </li>
            <li class="sidebar-item">
                <a href="../api/points_card.php" class="sidebar-link">
                    <i class="fas fa-id-card"></i> Points Card
                </a>
            </li>
            <li class="sidebar-item">
                <a href="system_logs.php" class="sidebar-link active">
                    <i class="fas fa-list-alt"></i> System Log
                </a>
            </li>
        </ul>

        <div class="sidebar-profile">
            <div class="sidebar-user-card" id="profileToggle">
                <div class="user-avatar" style="width: 35px; height: 35px; min-width: 35px;">AD</div>
                <div class="sidebar-user-info">
                    <div class="sidebar-user-name">Administrator</div>
                    <div class="sidebar-user-role">System Admin</div>
                </div>
                <i class="fas fa-chevron-up" style="font-size: 0.7rem; color: #94a3b8;"></i>

                <div class="profile-dropdown" id="profileDropdown"
                    style="bottom: 100%; top: auto; right: 10px; left: 10px; width: auto; margin-bottom: 10px;">
                    <a href="profile.php" class="dropdown-item">
                        <i class="far fa-user-circle"></i> My Profile
                    </a>
                    <div style="height: 1px; background: rgba(0,0,0,0.05); margin: 5px 0;"></div>
                    <a href="../logout.php" class="dropdown-item logout">
                        <i class="fas fa-sign-out-alt"></i> Logout
                    </a>
                </div>
            </div>
        </div>
    </aside>

    <div class="main-layout">
        <main class="content-wrapper">
            <header class="welcome-header">
                <div class="header-brand-box">
                    <img src="../assets/images/nroi_logo.png" alt="NROI Logo" class="header-logo">
                    <div class="header-text">
                        <h2>NATIONAL RANGE OFFICERS INSTITUTE</h2>
                        <p>SYSTEM LOG MODULE</p>
                    </div>
                </div>
            </header>

            <div class="content-box">
                <div class="table-header"
                    style="justify-content: space-between; align-items: center; gap: 12px; flex-wrap: wrap;">
                    <div>
                        <h3 style="margin:0;">Full Activity Log</h3>
                        <div style="font-size:0.85rem; color:#64748b;">
                            Comprehensive record of all system-level actions
                        </div>
                    </div>
                </div>

                <div class="search-bar-container"
                    style="padding: 0 20px 20px 20px; display: flex; flex-wrap: wrap; gap: 15px; align-items: center;">
                    <form method="GET" id="logFilterForm"
                        style="display: flex; gap: 10px; flex: 1; min-width: 300px; align-items: center;">
                        <input type="hidden" name="view" value="<?php echo htmlspecialchars($view_mode); ?>">

                        <!-- Search Box -->
                        <div style="position: relative; flex: 1;">
                            <i class="fas fa-search"
                                style="position: absolute; left: 15px; top: 50%; transform: translateY(-50%); color: #94a3b8; font-size: 0.9rem;"></i>
                            <input type="search" name="search" placeholder="Search logs..."
                                value="<?php echo htmlspecialchars($search); ?>"
                                style="width: 100%; padding: 10px 15px 10px 40px; border: 1px solid #e2e8f0; border-radius: 12px; font-size: 0.9rem; outline: none; transition: all 0.2s; background: #f8fafc;">
                        </div>

                        <!-- Date Picker (Daily Only) -->
                        <div
                            style="position: relative; display: flex; align-items: center; gap: 5px; background: #f8fafc; border: 1px solid #e2e8f0; border-radius: 12px; padding: 0 10px;">
                            <i class="far fa-calendar-alt" style="color: #64748b; font-size: 0.9rem;"></i>
                            <input type="date" name="date" value="<?php echo htmlspecialchars($filter_date); ?>"
                                onchange="this.form.submit()"
                                style="border: none; background: transparent; padding: 10px 5px; font-size: 0.85rem; outline: none; color: #1e293b; cursor: pointer;">
                        </div>

                        <button type="submit" class="btn-primary"
                            style="margin: 0; width: auto; padding: 0 20px; height: 42px;">Apply</button>
                    </form>

                    <div class="view-mode-group"
                        style="display: flex; gap: 8px; background: #f1f5f9; padding: 4px; border-radius: 10px;">
                        <a href="?view=daily&search=<?php echo urlencode($search); ?>&date=<?php echo urlencode($filter_date); ?>"
                            class="filter-tab <?php echo $view_mode === 'daily' ? 'active' : ''; ?>"
                            style="padding: 6px 12px; border-radius: 8px; font-size: 0.85rem; text-decoration: none; color: <?php echo $view_mode === 'daily' ? '#fff' : '#64748b'; ?>; background: <?php echo $view_mode === 'daily' ? 'var(--primary-color)' : 'transparent'; ?>; font-weight: 500;">Daily</a>

                        <a href="?view=weekly&search=<?php echo urlencode($search); ?>"
                            class="filter-tab <?php echo $view_mode === 'weekly' ? 'active' : ''; ?>"
                            style="padding: 6px 12px; border-radius: 8px; font-size: 0.85rem; text-decoration: none; color: <?php echo $view_mode === 'weekly' ? '#fff' : '#64748b'; ?>; background: <?php echo $view_mode === 'weekly' ? 'var(--primary-color)' : 'transparent'; ?>; font-weight: 500;">Weekly</a>

                        <a href="?view=monthly&search=<?php echo urlencode($search); ?>"
                            class="filter-tab <?php echo $view_mode === 'monthly' ? 'active' : ''; ?>"
                            style="padding: 6px 12px; border-radius: 8px; font-size: 0.85rem; text-decoration: none; color: <?php echo $view_mode === 'monthly' ? '#fff' : '#64748b'; ?>; background: <?php echo $view_mode === 'monthly' ? 'var(--primary-color)' : 'transparent'; ?>; font-weight: 500;">Monthly</a>
                    </div>

                    <?php if ($search !== '' || $filter_date !== '' || $selected_week !== '' || $selected_month !== '' || $view_mode !== 'daily'): ?>
                        <a href="system_logs.php" class="btn-secondary"
                            style="margin: 0; width: auto; padding: 0 15px; height: 42px; display: flex; align-items: center; border: 1px solid #e2e8f0; border-radius: 12px; background: white; text-decoration: none; color: #64748b;">Reset</a>
                    <?php endif; ?>
                </div>

                <div style="padding: 0 20px 20px 20px;">
                    <?php if ($view_mode === 'weekly' && empty($selected_week)): ?>
                        <!-- Selection List for Weekly -->
                        <div
                            style="display: grid; grid-template-columns: repeat(auto-fill, minmax(280px, 1fr)); gap: 15px;">
                            <?php foreach ($groupedLogs as $key => $logs): ?>
                                <?php
                                list($vYear, $vWeek) = explode('-', $key);
                                $dto = new DateTime();
                                $dto->setISODate($vYear, $vWeek);
                                $start = $dto->format('M d');
                                $dto->modify('+6 days');
                                $end = $dto->format('M d, Y');
                                ?>
                                <a href="?view=weekly&week=<?php echo $key; ?>&search=<?php echo urlencode($search); ?>"
                                    style="display: flex; flex-direction: column; padding: 20px; background: #fff; border: 1px solid #e2e8f0; border-radius: 16px; text-decoration: none; transition: all 0.2s; border-left: 4px solid var(--primary-color);">
                                    <span style="font-weight: 700; color: #1e293b; font-size: 1rem; margin-bottom: 5px;">Week
                                        <?php echo $vWeek; ?></span>
                                    <span style="font-size: 0.85rem; color: #64748b;"><?php echo "$start - $end"; ?></span>
                                    <span
                                        style="margin-top: 10px; font-size: 0.8rem; color: var(--primary-color); font-weight: 600;"><?php echo count($logs); ?>
                                        activities <i class="fas fa-arrow-right"
                                            style="margin-left: 5px; font-size: 0.7rem;"></i></span>
                                </a>
                            <?php endforeach; ?>
                        </div>
                    <?php elseif ($view_mode === 'monthly' && empty($selected_month)): ?>
                        <!-- Selection List for Monthly -->
                        <div
                            style="display: grid; grid-template-columns: repeat(auto-fill, minmax(200px, 1fr)); gap: 15px;">
                            <?php foreach ($groupedLogs as $key => $logs): ?>
                                <?php $logDate = strtotime($key . "-01"); ?>
                                <a href="?view=monthly&month=<?php echo $key; ?>&search=<?php echo urlencode($search); ?>"
                                    style="display: flex; flex-direction: column; padding: 20px; background: #fff; border: 1px solid #e2e8f0; border-radius: 16px; text-decoration: none; transition: all 0.2s; border-left: 4px solid #10b981; text-align: center;">
                                    <span
                                        style="font-weight: 700; color: #1e293b; font-size: 1.1rem;"><?php echo strtoupper(date('F', $logDate)); ?></span>
                                    <span
                                        style="font-size: 0.9rem; color: #64748b; margin-bottom: 8px;"><?php echo date('Y', $logDate); ?></span>
                                    <span
                                        style="font-size: 0.8rem; color: #10b981; font-weight: 600;"><?php echo count($logs); ?>
                                        activities</span>
                                </a>
                            <?php endforeach; ?>
                        </div>
                    <?php else: ?>
                        <!-- Detailed Table View -->
                        <?php
                        // If a week or month is selected, only show those logs
                        $displayLogs = $groupedLogs;
                        if ($view_mode === 'weekly' && !empty($selected_week)) {
                            $displayLogs = isset($groupedLogs[$selected_week]) ? [$selected_week => $groupedLogs[$selected_week]] : [];
                        } elseif ($view_mode === 'monthly' && !empty($selected_month)) {
                            $displayLogs = isset($groupedLogs[$selected_month]) ? [$selected_month => $groupedLogs[$selected_month]] : [];
                        }
                        ?>

                        <?php if (!empty($selected_week) || !empty($selected_month)): ?>
                            <div style="margin-bottom: 20px;">
                                <a href="?view=<?php echo $view_mode; ?>&search=<?php echo urlencode($search); ?>"
                                    class="btn-secondary"
                                    style="margin:0; width:auto; display: inline-flex; align-items:center; gap: 8px; padding: 8px 15px; border-radius: 10px;">
                                    <i class="fas fa-chevron-left"></i> Back to <?php echo ucfirst($view_mode); ?> Overview
                                </a>
                            </div>
                        <?php endif; ?>

                        <div style="overflow-x:auto;">
                            <table class="modern-table">
                                <thead>
                                    <tr>
                                        <th>User</th>
                                        <th>Reference</th>
                                        <th>Description</th>
                                        <th>Status</th>
                                        <th>Date</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php if (empty($displayLogs)): ?>
                                        <tr>
                                            <td colspan="5" style="text-align: center; color: #64748b; padding: 60px;">
                                                <i class="fas fa-folder-open"
                                                    style="font-size: 2rem; display: block; margin-bottom: 15px; opacity: 0.5;"></i>
                                                No activity log entries found for this selection.
                                            </td>
                                        </tr>
                                    <?php else: ?>
                                        <?php foreach ($displayLogs as $key => $logs): ?>
                                            <tr class="date-header-row" style="background: #f8fafc;">
                                                <td colspan="5"
                                                    style="padding: 12px 20px; font-weight: 700; color: #475569; font-size: 0.85rem; letter-spacing: 0.025em; border-bottom: 2px solid #e2e8f0;">
                                                    <?php
                                                    if ($view_mode === 'weekly') {
                                                        list($vYear, $vWeek) = explode('-', $key);
                                                        $dto = new DateTime();
                                                        $dto->setISODate($vYear, $vWeek);
                                                        $start = $dto->format('M d, Y');
                                                        $dto->modify('+6 days');
                                                        $end = $dto->format('M d, Y');
                                                        echo "<i class='fas fa-layer-group' style='margin-right: 8px; color: var(--primary-color);'></i> Week $vWeek ($start - $end)";
                                                    } elseif ($view_mode === 'monthly') {
                                                        $logDate = strtotime($key . "-01");
                                                        echo "<i class='fas fa-calendar-alt' style='margin-right: 8px; color: var(--primary-color);'></i> " . strtoupper(date('F Y', $logDate));
                                                    } else {
                                                        echo "<i class='far fa-calendar-alt' style='margin-right: 8px; color: var(--primary-color);'></i> ";
                                                        $logDate = strtotime($key);
                                                        if (date('Y-m-d') === $key)
                                                            echo "TODAY, " . date('M d, Y', $logDate);
                                                        elseif (date('Y-m-d', strtotime('-1 day')) === $key)
                                                            echo "YESTERDAY, " . date('M d, Y', $logDate);
                                                        else
                                                            echo date('l, M d, Y', $logDate);
                                                    }
                                                    ?>
                                                </td>
                                            </tr>
                                            <?php foreach ($logs as $log): ?>
                                                <tr>
                                                    <td style="font-weight: 600; color: #1e293b; font-size: 0.9rem;">
                                                        <?php echo htmlspecialchars($log['performer_name'] ?: 'System'); ?>
                                                    </td>
                                                    <td>
                                                        <span class="role-badge" style="background: #eff6ff; color: #1e40af;">
                                                            <?php echo $log['reference_type'] === 'user' ? 'Account' : htmlspecialchars(ucfirst($log['reference_type'])); ?>
                                                        </span>
                                                    </td>
                                                    <td style="font-size: 0.9rem; color: #1e293b;">
                                                        <?php echo htmlspecialchars($log['description']); ?>
                                                    </td>
                                                    <td>
                                                        <span
                                                            class="status-badge status-<?php echo htmlspecialchars($log['status']); ?>">
                                                            <?php echo status_display_label($log['status']); ?>
                                                        </span>
                                                    </td>
                                                    <td style="font-size: 0.85rem; color: #64748b;">
                                                        <i class="far fa-clock"
                                                            style="font-size: 0.75rem; margin-right: 3px; opacity: 0.7;"></i>
                                                        <?php echo date('M d, H:i', strtotime($log['created_at'])); ?>
                                                    </td>
                                                </tr>
                                            <?php endforeach; ?>
                                        <?php endforeach; ?>
                                    <?php endif; ?>
                                </tbody>
                            </table>
                        </div>
                    <?php endif; ?>
                </div>
            </div>
        </main>
    </div>

    <script src="../assets/js/loader.js"></script>
    <script>
        const profileToggle = document.getElementById('profileToggle');
        const profileDropdown = document.getElementById('profileDropdown');

        if (profileToggle && profileDropdown) {
            profileToggle.addEventListener('click', (e) => {
                e.stopPropagation();
                profileDropdown.classList.toggle('active');
            });

            document.addEventListener('click', (e) => {
                if (!profileToggle.contains(e.target) && !profileDropdown.contains(e.target)) {
                    profileDropdown.classList.remove('active');
                }
            });
        }
    </script>
    <script src="../assets/js/dashboard-transitions.js"></script>
</body>

</html>