<?php
require_once '../config/db.php';
require_once '../config/auth.php';
require_once '../config/functions.php';

if (!isLoggedIn() || !isAdmin()) {
    header("Location: " . BASE_URL . "/auth/login.php");
    exit;
}

$page_title = 'Activity Log';

// Pagination
$page     = max(1, (int)($_GET['page'] ?? 1));
$per_page = 20;
$offset   = ($page - 1) * $per_page;

// Filters
$action_filter = $conn->real_escape_string($_GET['action'] ?? '');
$entity_filter = $conn->real_escape_string($_GET['entity'] ?? '');
$admin_filter  = (int)($_GET['admin'] ?? 0);
$date_from     = $conn->real_escape_string($_GET['date_from'] ?? '');
$date_to       = $conn->real_escape_string($_GET['date_to'] ?? '');

$where = "WHERE 1=1";
if ($action_filter) $where .= " AND al.action LIKE '%$action_filter%'";
if ($entity_filter) $where .= " AND al.entity_type = '$entity_filter'";
if ($admin_filter)  $where .= " AND al.admin_id = $admin_filter";
if ($date_from)     $where .= " AND DATE(al.created_at) >= '$date_from'";
if ($date_to)       $where .= " AND DATE(al.created_at) <= '$date_to'";

$total       = $conn->query("SELECT COUNT(*) c FROM activity_logs al $where")->fetch_assoc()['c'];
$total_pages = ceil($total / $per_page);

$logs = $conn->query("
    SELECT al.*, u.name as admin_name, u.avatar
    FROM activity_logs al
    JOIN users u ON al.admin_id = u.id
    $where
    ORDER BY al.created_at DESC
    LIMIT $per_page OFFSET $offset
");

$admins  = $conn->query("SELECT DISTINCT al.admin_id, u.name FROM activity_logs al JOIN users u ON al.admin_id = u.id ORDER BY u.name");
$actions  = $conn->query("SELECT DISTINCT action FROM activity_logs ORDER BY action");
$entities = $conn->query("SELECT DISTINCT entity_type FROM activity_logs WHERE entity_type IS NOT NULL ORDER BY entity_type");

// Action badge colors
function actionColor($action) {
    if (str_contains($action, 'delete'))   return '#dc2626';
    if (str_contains($action, 'approve'))  return '#059669';
    if (str_contains($action, 'reject'))   return '#d97706';
    if (str_contains($action, 'add') || str_contains($action, 'save')) return '#0891b2';
    if (str_contains($action, 'update') || str_contains($action, 'change')) return '#7c3aed';
    if (str_contains($action, 'return'))   return '#4f9d1c';
    return '#64748b';
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title><?= $page_title ?> - RELINK Admin</title>
<link rel="stylesheet" href="<?= BASE_URL ?>/assets/css/style.css">
<style>
.action-badge {
    display: inline-flex;
    align-items: center;
    gap: 4px;
    padding: 3px 10px;
    border-radius: 20px;
    font-size: 11px;
    font-weight: 700;
    text-transform: uppercase;
    letter-spacing: .4px;
    color: #fff;
    white-space: nowrap;
}
.entity-chip {
    display: inline-flex;
    align-items: center;
    gap: 4px;
    padding: 2px 8px;
    border-radius: 6px;
    font-size: 11px;
    font-weight: 600;
    background: var(--bg-secondary);
    color: var(--text-secondary);
    border: 1px solid var(--border);
}
.ip-chip {
    font-family: monospace;
    font-size: 12px;
    background: var(--bg-secondary);
    padding: 2px 8px;
    border-radius: 6px;
    color: var(--text-muted);
    border: 1px solid var(--border);
}
.log-desc {
    font-size: 13px;
    color: var(--text-secondary);
    max-width: 280px;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
}
.filter-card {
    background: var(--white);
    border: 1px solid var(--border);
    border-radius: var(--radius);
    padding: 16px 20px;
    margin-bottom: 20px;
    box-shadow: var(--shadow-sm);
}
.summary-bar {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 10px 16px;
    background: var(--bg-secondary);
    border-radius: var(--radius-sm);
    margin-bottom: 16px;
    font-size: 13px;
    color: var(--text-muted);
    flex-wrap: wrap;
    gap: 8px;
}
</style>
</head>
<body>
<div class="layout">
    <?php include '../includes/admin_sidebar.php'; ?>
    <div class="main-content">
        <?php include '../includes/topbar.php'; ?>
        <div class="page-content">

            <!-- Header -->
            <div style="display:flex;align-items:center;justify-content:space-between;margin-bottom:20px;flex-wrap:wrap;gap:12px">
                <div>
                    <h2 style="font-size:20px;font-weight:800;color:var(--text);margin:0">📋 Activity Log</h2>
                    <p style="color:var(--text-muted);font-size:13px;margin-top:4px">Track all admin actions and system activities</p>
                </div>
                <div style="display:flex;gap:8px">
                    <span style="background:var(--primary-light);color:var(--primary);font-size:12px;font-weight:700;padding:4px 12px;border-radius:20px"><?= $total ?> total logs</span>
                </div>
            </div>

            <!-- Filters -->
            <div class="filter-card">
                <form method="GET">
                    <div style="display:grid;grid-template-columns:repeat(auto-fit,minmax(160px,1fr));gap:12px;align-items:end">
                        <div class="form-group" style="margin-bottom:0">
                            <label style="font-size:12px;font-weight:600;color:var(--text-muted)">Admin User</label>
                            <select name="admin" class="form-control">
                                <option value="">All Admins</option>
                                <?php while($a = $admins->fetch_assoc()): ?>
                                <option value="<?= $a['admin_id'] ?>" <?= $admin_filter == $a['admin_id'] ? 'selected' : '' ?>><?= htmlspecialchars($a['name']) ?></option>
                                <?php endwhile; ?>
                            </select>
                        </div>
                        <div class="form-group" style="margin-bottom:0">
                            <label style="font-size:12px;font-weight:600;color:var(--text-muted)">Action</label>
                            <select name="action" class="form-control">
                                <option value="">All Actions</option>
                                <?php while($act = $actions->fetch_assoc()): ?>
                                <option value="<?= $act['action'] ?>" <?= $action_filter == $act['action'] ? 'selected' : '' ?>><?= htmlspecialchars($act['action']) ?></option>
                                <?php endwhile; ?>
                            </select>
                        </div>
                        <div class="form-group" style="margin-bottom:0">
                            <label style="font-size:12px;font-weight:600;color:var(--text-muted)">Entity Type</label>
                            <select name="entity" class="form-control">
                                <option value="">All Types</option>
                                <?php while($ent = $entities->fetch_assoc()): ?>
                                <option value="<?= $ent['entity_type'] ?>" <?= $entity_filter == $ent['entity_type'] ? 'selected' : '' ?>><?= htmlspecialchars($ent['entity_type']) ?></option>
                                <?php endwhile; ?>
                            </select>
                        </div>
                        <div class="form-group" style="margin-bottom:0">
                            <label style="font-size:12px;font-weight:600;color:var(--text-muted)">Date From</label>
                            <input type="date" name="date_from" class="form-control" value="<?= htmlspecialchars($date_from) ?>">
                        </div>
                        <div class="form-group" style="margin-bottom:0">
                            <label style="font-size:12px;font-weight:600;color:var(--text-muted)">Date To</label>
                            <input type="date" name="date_to" class="form-control" value="<?= htmlspecialchars($date_to) ?>">
                        </div>
                        <div style="display:flex;gap:8px">
                            <button type="submit" class="btn btn-primary" style="flex:1">🔍 Filter</button>
                            <a href="<?= BASE_URL ?>/admin/activity_log.php" class="btn btn-light" style="flex:1">Clear</a>
                        </div>
                    </div>
                </form>
            </div>

            <!-- Summary -->
            <div class="summary-bar">
                <span>Showing <strong><?= $total == 0 ? 0 : ($offset + 1) . '–' . min($offset + $per_page, $total) ?></strong> of <strong><?= $total ?></strong> activities</span>
                <?php if($action_filter || $entity_filter || $admin_filter || $date_from || $date_to): ?>
                <span style="color:var(--primary);font-weight:600">🔍 Filters active</span>
                <?php endif; ?>
            </div>

            <!-- Table -->
            <div class="card">
                <div class="table-wrapper">
                    <table>
                        <thead>
                            <tr>
                                <th style="width:180px">Admin</th>
                                <th style="width:160px">Action</th>
                                <th style="width:130px">Entity</th>
                                <th>Description</th>
                                <th style="width:130px">IP Address</th>
                                <th style="width:150px">Date & Time</th>
                            </tr>
                        </thead>
                        <tbody>
                        <?php if ($total == 0): ?>
                        <tr>
                            <td colspan="6" style="text-align:center;padding:60px 20px;color:var(--text-muted)">
                                <div style="font-size:40px;margin-bottom:10px">📋</div>
                                <p>No activity logs found.</p>
                            </td>
                        </tr>
                        <?php else: ?>
                        <?php while ($log = $logs->fetch_assoc()): ?>
                        <tr>
                            <td>
                                <div style="display:flex;align-items:center;gap:8px">
                                    <?php if (!empty($log['avatar'])): ?>
                                    <img src="<?= BASE_URL ?>/<?= htmlspecialchars($log['avatar']) ?>" style="width:28px;height:28px;border-radius:50%;object-fit:cover;flex-shrink:0;border:2px solid var(--border)">
                                    <?php else: ?>
                                    <div style="width:28px;height:28px;border-radius:50%;background:var(--primary);display:flex;align-items:center;justify-content:center;color:#fff;font-size:12px;font-weight:700;flex-shrink:0">
                                        <?= strtoupper(substr($log['admin_name'], 0, 1)) ?>
                                    </div>
                                    <?php endif; ?>
                                    <span style="font-size:13px;font-weight:500"><?= htmlspecialchars($log['admin_name']) ?></span>
                                </div>
                            </td>
                            <td>
                                <span class="action-badge" style="background:<?= actionColor($log['action']) ?>">
                                    <?= htmlspecialchars($log['action']) ?>
                                </span>
                            </td>
                            <td>
                                <?php if ($log['entity_type']): ?>
                                <span class="entity-chip">
                                    <?= htmlspecialchars($log['entity_type']) ?>
                                    <?php if ($log['entity_id']): ?>
                                    <span style="color:var(--text-muted)">#<?= $log['entity_id'] ?></span>
                                    <?php endif; ?>
                                </span>
                                <?php else: ?>
                                <span style="color:var(--text-muted);font-size:13px">—</span>
                                <?php endif; ?>
                            </td>
                            <td>
                                <span class="log-desc" title="<?= htmlspecialchars($log['description'] ?? '') ?>">
                                    <?= $log['description'] ? htmlspecialchars($log['description']) : '<span style="color:var(--text-muted)">—</span>' ?>
                                </span>
                            </td>
                            <td>
                                <span class="ip-chip"><?= htmlspecialchars($log['ip_address'] ?: '—') ?></span>
                            </td>
                            <td style="white-space:nowrap">
                                <div style="font-size:12px;font-weight:600;color:var(--text)"><?= date('M d, Y', strtotime($log['created_at'])) ?></div>
                                <div style="font-size:11px;color:var(--text-muted)"><?= date('h:i:s A', strtotime($log['created_at'])) ?></div>
                            </td>
                        </tr>
                        <?php endwhile; ?>
                        <?php endif; ?>
                        </tbody>
                    </table>
                </div>
            </div>

            <!-- Pagination -->
            <?php if ($total_pages > 1): ?>
            <div style="display:flex;gap:6px;justify-content:center;margin-top:20px;flex-wrap:wrap">
                <?php if($page > 1): ?>
                <a href="?page=<?= $page-1 ?>&action=<?= urlencode($action_filter) ?>&entity=<?= urlencode($entity_filter) ?>&admin=<?= $admin_filter ?>&date_from=<?= urlencode($date_from) ?>&date_to=<?= urlencode($date_to) ?>" class="btn btn-light">← Prev</a>
                <?php endif; ?>
                <?php
                $start = max(1, $page - 2);
                $end   = min($total_pages, $page + 2);
                for ($i = $start; $i <= $end; $i++):
                ?>
                <a href="?page=<?= $i ?>&action=<?= urlencode($action_filter) ?>&entity=<?= urlencode($entity_filter) ?>&admin=<?= $admin_filter ?>&date_from=<?= urlencode($date_from) ?>&date_to=<?= urlencode($date_to) ?>"
                   class="btn <?= $page == $i ? 'btn-primary' : 'btn-light' ?>" style="min-width:40px"><?= $i ?></a>
                <?php endfor; ?>
                <?php if($page < $total_pages): ?>
                <a href="?page=<?= $page+1 ?>&action=<?= urlencode($action_filter) ?>&entity=<?= urlencode($entity_filter) ?>&admin=<?= $admin_filter ?>&date_from=<?= urlencode($date_from) ?>&date_to=<?= urlencode($date_to) ?>" class="btn btn-light">Next →</a>
                <?php endif; ?>
            </div>
            <?php endif; ?>

        </div>
    </div>
</div>
<script src="<?= BASE_URL ?>/assets/js/main.js"></script>
</body>
</html>
