<?php
/**
 * Pure Chemical Admin
 * File: admin/activity_logs.php
 *
 * Database table:
 * activity_logs
 *
 * No new table is created.
 */

if (session_status() !== PHP_SESSION_ACTIVE) {
    session_start();
}

require_once __DIR__ . '/includes/db.php';

if (file_exists(__DIR__ . '/includes/auth.php')) {
    require_once __DIR__ . '/includes/auth.php';
}

if (file_exists(__DIR__ . '/includes/functions.php')) {
    require_once __DIR__ . '/includes/functions.php';
}

if (file_exists(__DIR__ . '/includes/csrf.php')) {
    require_once __DIR__ . '/includes/csrf.php';
}

if (function_exists('requireAdmin')) {
    requireAdmin();
}


/* =========================================================
   HELPERS
========================================================= */

function al_e($value): string
{
    return htmlspecialchars((string)$value, ENT_QUOTES, 'UTF-8');
}

function al_post_string(string $key, string $default = ''): string
{
    return isset($_POST[$key]) ? trim((string)$_POST[$key]) : $default;
}

function al_post_int(string $key, int $default = 0): int
{
    return isset($_POST[$key]) ? (int)$_POST[$key] : $default;
}

function al_get_string(string $key, string $default = ''): string
{
    return isset($_GET[$key]) ? trim((string)$_GET[$key]) : $default;
}

function al_get_int(string $key, int $default = 0): int
{
    return isset($_GET[$key]) ? (int)$_GET[$key] : $default;
}

function al_csrf_field(): string
{
    if (function_exists('csrf_field')) {
        return csrf_field();
    }

    if (function_exists('csrf_token')) {
        return '<input type="hidden" name="csrf_token" value="' .
            al_e(csrf_token()) . '">';
    }

    if (empty($_SESSION['csrf_token'])) {
        $_SESSION['csrf_token'] = bin2hex(random_bytes(32));
    }

    return '<input type="hidden" name="csrf_token" value="' .
        al_e($_SESSION['csrf_token']) . '">';
}

function al_verify_csrf(): bool
{
    if (function_exists('csrf_verify')) {
        return (bool) csrf_verify();
    }

    $token = $_POST['csrf_token'] ?? '';

    if (
        empty($_SESSION['csrf_token']) ||
        empty($token)
    ) {
        return false;
    }

    return hash_equals(
        (string) $_SESSION['csrf_token'],
        (string) $token
    );
}

function al_redirect(string $url): never
{
    header('Location: ' . $url);
    exit;
}

function al_flash(string $type, string $message): void
{
    $_SESSION['al_flash'] = [
        'type' => $type,
        'message' => $message
    ];
}

function al_get_flash(): ?array
{
    if (empty($_SESSION['al_flash'])) {
        return null;
    }

    $flash = $_SESSION['al_flash'];

    unset($_SESSION['al_flash']);

    return $flash;
}

function al_json_pretty(?string $value): string
{
    if ($value === null || trim($value) === '') {
        return '';
    }

    $decoded = json_decode($value, true);

    if (json_last_error() === JSON_ERROR_NONE) {
        $pretty = json_encode(
            $decoded,
            JSON_PRETTY_PRINT |
            JSON_UNESCAPED_UNICODE |
            JSON_UNESCAPED_SLASHES
        );

        if ($pretty !== false) {
            return $pretty;
        }
    }

    return $value;
}

function al_action_class(string $action): string
{
    $action = strtolower(trim($action));

    if (
        strpos($action, 'delete') !== false ||
        strpos($action, 'remove') !== false ||
        strpos($action, 'destroy') !== false
    ) {
        return 'danger';
    }

    if (
        strpos($action, 'create') !== false ||
        strpos($action, 'add') !== false ||
        strpos($action, 'insert') !== false
    ) {
        return 'success';
    }

    if (
        strpos($action, 'update') !== false ||
        strpos($action, 'edit') !== false
    ) {
        return 'warning';
    }

    if (
        strpos($action, 'login') !== false ||
        strpos($action, 'logout') !== false
    ) {
        return 'info';
    }

    return 'neutral';
}


/* =========================================================
   POST ACTIONS
========================================================= */

if ($_SERVER['REQUEST_METHOD'] === 'POST') {

    if (!al_verify_csrf()) {
        al_flash(
            'error',
            'Security token expired. Please try again.'
        );

        al_redirect('activity_logs.php');
    }

    $action = al_post_string('action');


    /* -----------------------------------------------------
       DELETE SINGLE LOG
    ----------------------------------------------------- */

    if ($action === 'delete') {

        $id = al_post_int('id');

        if ($id <= 0) {
            al_flash(
                'error',
                'Invalid activity log selected.'
            );

            al_redirect('activity_logs.php');
        }

        try {

            $stmt = $pdo->prepare(
                "DELETE FROM activity_logs WHERE id = ?"
            );

            $stmt->execute([$id]);

            al_flash(
                'success',
                'Activity log deleted successfully.'
            );

        } catch (Throwable $e) {

            error_log(
                'Activity Log Delete Error: ' .
                $e->getMessage()
            );

            al_flash(
                'error',
                'Unable to delete activity log.'
            );
        }

        al_redirect('activity_logs.php');
    }


    /* -----------------------------------------------------
       BULK DELETE
    ----------------------------------------------------- */

    if ($action === 'bulk_delete') {

        $ids = $_POST['ids'] ?? [];

        if (!is_array($ids)) {
            $ids = [];
        }

        $ids = array_values(
            array_filter(
                array_map('intval', $ids),
                static function ($id) {
                    return $id > 0;
                }
            )
        );

        if (empty($ids)) {
            al_flash(
                'error',
                'Please select at least one activity log.'
            );

            al_redirect('activity_logs.php');
        }

        try {

            $placeholders = implode(
                ',',
                array_fill(0, count($ids), '?')
            );

            $stmt = $pdo->prepare(
                "DELETE FROM activity_logs
                 WHERE id IN ($placeholders)"
            );

            $stmt->execute($ids);

            al_flash(
                'success',
                count($ids) .
                ' activity log(s) deleted successfully.'
            );

        } catch (Throwable $e) {

            error_log(
                'Activity Log Bulk Delete Error: ' .
                $e->getMessage()
            );

            al_flash(
                'error',
                'Unable to delete selected activity logs.'
            );
        }

        al_redirect('activity_logs.php');
    }
}


/* =========================================================
   FILTERS
========================================================= */

$search = al_get_string('search');
$filterUser = al_get_int('user_id');
$filterModule = al_get_string('module');
$filterAction = al_get_string('action_filter');
$filterEntityType = al_get_string('entity_type');
$dateFrom = al_get_string('date_from');
$dateTo = al_get_string('date_to');


/* =========================================================
   USERS
========================================================= */

$users = [];

try {

    $stmt = $pdo->query(
        "SELECT id, name, email
         FROM users
         ORDER BY name ASC, id ASC"
    );

    $users = $stmt->fetchAll();

} catch (Throwable $e) {

    /*
     * Some installations may have a different users
     * structure. Logs still remain accessible.
     */
    try {

        $stmt = $pdo->query(
            "SELECT id
             FROM users
             ORDER BY id ASC"
        );

        $users = $stmt->fetchAll();

    } catch (Throwable $ignore) {
        $users = [];
    }
}


/* =========================================================
   FILTER OPTIONS
========================================================= */

$modules = [];
$actions = [];
$entityTypes = [];

try {

    $modules = $pdo
        ->query(
            "SELECT DISTINCT module
             FROM activity_logs
             WHERE module IS NOT NULL
               AND module <> ''
             ORDER BY module ASC"
        )
        ->fetchAll(PDO::FETCH_COLUMN);

} catch (Throwable $e) {
    $modules = [];
}

try {

    $actions = $pdo
        ->query(
            "SELECT DISTINCT action
             FROM activity_logs
             WHERE action IS NOT NULL
               AND action <> ''
             ORDER BY action ASC"
        )
        ->fetchAll(PDO::FETCH_COLUMN);

} catch (Throwable $e) {
    $actions = [];
}

try {

    $entityTypes = $pdo
        ->query(
            "SELECT DISTINCT entity_type
             FROM activity_logs
             WHERE entity_type IS NOT NULL
               AND entity_type <> ''
             ORDER BY entity_type ASC"
        )
        ->fetchAll(PDO::FETCH_COLUMN);

} catch (Throwable $e) {
    $entityTypes = [];
}


/* =========================================================
   STATS
========================================================= */

$totalLogs = 0;
$todayLogs = 0;
$activeUsers = 0;
$totalModules = 0;

try {

    $totalLogs = (int) $pdo
        ->query(
            "SELECT COUNT(*)
             FROM activity_logs"
        )
        ->fetchColumn();

    $todayLogs = (int) $pdo
        ->query(
            "SELECT COUNT(*)
             FROM activity_logs
             WHERE DATE(created_at) = CURDATE()"
        )
        ->fetchColumn();

    $activeUsers = (int) $pdo
        ->query(
            "SELECT COUNT(DISTINCT user_id)
             FROM activity_logs
             WHERE user_id IS NOT NULL"
        )
        ->fetchColumn();

    $totalModules = (int) $pdo
        ->query(
            "SELECT COUNT(DISTINCT module)
             FROM activity_logs
             WHERE module IS NOT NULL
               AND module <> ''"
        )
        ->fetchColumn();

} catch (Throwable $e) {
    // Keep defaults.
}


/* =========================================================
   LOG DETAIL
========================================================= */

$viewId = al_get_int('view');
$viewLog = null;

if ($viewId > 0) {

    try {

        $stmt = $pdo->prepare(
            "SELECT
                al.*,
                u.name AS user_name,
                u.email AS user_email
             FROM activity_logs al
             LEFT JOIN users u
                ON u.id = al.user_id
             WHERE al.id = ?
             LIMIT 1"
        );

        $stmt->execute([$viewId]);

        $viewLog = $stmt->fetch() ?: null;

    } catch (Throwable $e) {

        /*
         * Fallback without users columns.
         */
        $stmt = $pdo->prepare(
            "SELECT *
             FROM activity_logs
             WHERE id = ?
             LIMIT 1"
        );

        $stmt->execute([$viewId]);

        $viewLog = $stmt->fetch() ?: null;
    }
}


/* =========================================================
   LIST QUERY
========================================================= */

$where = [];
$params = [];

if ($search !== '') {

    $where[] = "(
        al.module LIKE ?
        OR al.action LIKE ?
        OR al.entity_type LIKE ?
        OR al.description LIKE ?
        OR al.ip_address LIKE ?
        OR CAST(al.entity_id AS CHAR) LIKE ?
        OR CAST(al.id AS CHAR) LIKE ?
    )";

    $searchLike = '%' . $search . '%';

    for ($i = 0; $i < 7; $i++) {
        $params[] = $searchLike;
    }
}

if ($filterUser > 0) {

    $where[] = "al.user_id = ?";
    $params[] = $filterUser;
}

if ($filterModule !== '') {

    $where[] = "al.module = ?";
    $params[] = $filterModule;
}

if ($filterAction !== '') {

    $where[] = "al.action = ?";
    $params[] = $filterAction;
}

if ($filterEntityType !== '') {

    $where[] = "al.entity_type = ?";
    $params[] = $filterEntityType;
}

if ($dateFrom !== '') {

    $where[] = "DATE(al.created_at) >= ?";
    $params[] = $dateFrom;
}

if ($dateTo !== '') {

    $where[] = "DATE(al.created_at) <= ?";
    $params[] = $dateTo;
}


$sql = "
    SELECT
        al.*,
        u.name AS user_name,
        u.email AS user_email
    FROM activity_logs al
    LEFT JOIN users u
        ON u.id = al.user_id
";

if (!empty($where)) {
    $sql .= ' WHERE ' . implode(' AND ', $where);
}

$sql .= "
    ORDER BY al.id DESC
    LIMIT 500
";

try {

    $stmt = $pdo->prepare($sql);
    $stmt->execute($params);
    $logs = $stmt->fetchAll();

} catch (Throwable $e) {

    /*
     * Fallback query in case users.name/email is unavailable.
     */
    $fallbackSql = "
        SELECT *
        FROM activity_logs al
    ";

    if (!empty($where)) {

        /*
         * User filter cannot safely work without the JOIN,
         * but all normal filters remain available.
         */
        $fallbackWhere = [];

        $fallbackParams = [];

        if ($search !== '') {

            $fallbackWhere[] = "(
                al.module LIKE ?
                OR al.action LIKE ?
                OR al.entity_type LIKE ?
                OR al.description LIKE ?
                OR al.ip_address LIKE ?
                OR CAST(al.entity_id AS CHAR) LIKE ?
                OR CAST(al.id AS CHAR) LIKE ?
            )";

            for ($i = 0; $i < 7; $i++) {
                $fallbackParams[] = $searchLike;
            }
        }

        if ($filterUser > 0) {
            $fallbackWhere[] = "al.user_id = ?";
            $fallbackParams[] = $filterUser;
        }

        if ($filterModule !== '') {
            $fallbackWhere[] = "al.module = ?";
            $fallbackParams[] = $filterModule;
        }

        if ($filterAction !== '') {
            $fallbackWhere[] = "al.action = ?";
            $fallbackParams[] = $filterAction;
        }

        if ($filterEntityType !== '') {
            $fallbackWhere[] = "al.entity_type = ?";
            $fallbackParams[] = $filterEntityType;
        }

        if ($dateFrom !== '') {
            $fallbackWhere[] = "DATE(al.created_at) >= ?";
            $fallbackParams[] = $dateFrom;
        }

        if ($dateTo !== '') {
            $fallbackWhere[] = "DATE(al.created_at) <= ?";
            $fallbackParams[] = $dateTo;
        }

        if (!empty($fallbackWhere)) {
            $fallbackSql .=
                ' WHERE ' .
                implode(' AND ', $fallbackWhere);
        }

        $fallbackSql .= "
            ORDER BY al.id DESC
            LIMIT 500
        ";

        $stmt = $pdo->prepare($fallbackSql);
        $stmt->execute($fallbackParams);

        $logs = $stmt->fetchAll();

    } else {

        $logs = [];
    }
}

$flash = al_get_flash();

?>
<!DOCTYPE html>
<html lang="en">

<head>

    <meta charset="UTF-8">

    <meta
        name="viewport"
        content="width=device-width, initial-scale=1.0"
    >

    <title>
        Activity Logs | Pure Chemical Admin
    </title>

    <meta
        name="theme-color"
        content="#0f172a"
    >

    <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@400;500;600;700;800&display=swap"
        rel="stylesheet"
    >

    <link
        rel="stylesheet"
        href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.2/css/all.min.css"
    >


    <style>

        :root {

            --primary: #2563eb;
            --primary-dark: #1d4ed8;
            --primary-soft: #eff6ff;

            --success: #16a34a;
            --success-soft: #f0fdf4;

            --danger: #dc2626;
            --danger-soft: #fef2f2;

            --warning: #d97706;
            --warning-soft: #fffbeb;

            --info: #0891b2;
            --info-soft: #ecfeff;

            --purple: #7c3aed;
            --purple-soft: #f5f3ff;

            --dark: #0f172a;
            --text: #1e293b;
            --muted: #64748b;

            --border: #e2e8f0;
            --bg: #f8fafc;
            --white: #ffffff;

            --radius: 18px;

            --shadow:
                0 10px 30px rgba(15, 23, 42, .06);

            --sidebar-width: 285px;
        }


        * {
            box-sizing: border-box;
        }


        html {
            scroll-behavior: smooth;
        }


        body {

            margin: 0;

            background:
                radial-gradient(
                    circle at top right,
                    rgba(37, 99, 235, .06),
                    transparent 28%
                ),
                var(--bg);

            color: var(--text);

            font-family:
                "Inter",
                sans-serif;

            font-size: 14px;
        }


        a {
            color: inherit;
            text-decoration: none;
        }


        button,
        input,
        select {
            font: inherit;
        }


        button {
            cursor: pointer;
        }


        /* =====================================================
           PAGE
        ===================================================== */

        .al-page {

            margin-left:
                var(--sidebar-width);

            min-height: 100vh;
        }


        /* =====================================================
           TOPBAR
        ===================================================== */

        .al-topbar {

            height: 76px;

            position: sticky;
            top: 0;

            z-index: 50;

            display: flex;

            align-items: center;

            justify-content: space-between;

            padding: 0 30px;

            background:
                rgba(255, 255, 255, .93);

            border-bottom:
                1px solid rgba(226, 232, 240, .85);

            backdrop-filter:
                blur(16px);

            -webkit-backdrop-filter:
                blur(16px);
        }


        .al-topbar-left {

            display: flex;

            align-items: center;

            gap: 14px;
        }


        .al-mobile-menu {

            display: none;

            width: 42px;
            height: 42px;

            align-items: center;
            justify-content: center;

            border:
                1px solid var(--border);

            border-radius: 12px;

            background: #fff;

            color: var(--dark);
        }


        .al-title {

            margin: 0;

            color: var(--dark);

            font-size: 19px;

            font-weight: 800;

            letter-spacing: -.025em;
        }


        .al-subtitle {

            margin: 4px 0 0;

            color: var(--muted);

            font-size: 12px;
        }


        .al-admin-badge {

            display: inline-flex;

            align-items: center;

            gap: 8px;

            padding:
                9px 13px;

            border:
                1px solid var(--border);

            border-radius: 12px;

            background: #fff;

            color: var(--muted);

            font-size: 12px;

            font-weight: 700;
        }


        .al-admin-badge i {
            color: var(--primary);
        }


        /* =====================================================
           CONTENT
        ===================================================== */

        .al-content {

            max-width: 1750px;

            margin: 0 auto;

            padding: 30px;
        }


        .al-heading {

            display: flex;

            align-items: flex-end;

            justify-content: space-between;

            gap: 20px;

            margin-bottom: 24px;
        }


        .al-heading h1 {

            margin: 0;

            color: var(--dark);

            font-size: 30px;

            line-height: 1.2;

            letter-spacing: -.045em;
        }


        .al-heading p {

            margin: 8px 0 0;

            color: var(--muted);

            font-size: 13px;
        }


        .al-heading-actions {

            display: flex;

            gap: 9px;
        }


        /* =====================================================
           BUTTONS
        ===================================================== */

        .al-btn {

            min-height: 42px;

            display: inline-flex;

            align-items: center;

            justify-content: center;

            gap: 8px;

            padding:
                0 15px;

            border-radius: 12px;

            border:
                1px solid transparent;

            font-size: 13px;

            font-weight: 700;

            transition:
                transform .18s ease,
                box-shadow .18s ease,
                background .18s ease;
        }


        .al-btn:hover {
            transform: translateY(-1px);
        }


        .al-btn-primary {

            color: #fff;

            background:
                linear-gradient(
                    135deg,
                    var(--primary),
                    var(--primary-dark)
                );

            box-shadow:
                0 8px 20px
                rgba(37, 99, 235, .20);
        }


        .al-btn-secondary {

            color: var(--text);

            background: #fff;

            border-color:
                var(--border);
        }


        .al-btn-danger {

            color: var(--danger);

            background:
                var(--danger-soft);

            border-color:
                #fecaca;
        }


        /* =====================================================
           ALERT
        ===================================================== */

        .al-alert {

            display: flex;

            align-items: center;

            gap: 11px;

            margin-bottom: 22px;

            padding:
                14px 17px;

            border-radius: 14px;

            font-weight: 600;
        }


        .al-alert.success {

            color: #166534;

            background:
                var(--success-soft);

            border:
                1px solid #bbf7d0;
        }


        .al-alert.error {

            color: #991b1b;

            background:
                var(--danger-soft);

            border:
                1px solid #fecaca;
        }


        .al-alert-close {

            margin-left: auto;

            border: 0;

            background: transparent;

            color: inherit;
        }


        /* =====================================================
           STATS
        ===================================================== */

        .al-stats {

            display: grid;

            grid-template-columns:
                repeat(4, minmax(0, 1fr));

            gap: 16px;

            margin-bottom: 22px;
        }


        .al-stat {

            position: relative;

            overflow: hidden;

            padding: 20px;

            border:
                1px solid var(--border);

            border-radius:
                var(--radius);

            background: #fff;

            box-shadow:
                var(--shadow);
        }


        .al-stat::after {

            content: "";

            position: absolute;

            width: 90px;
            height: 90px;

            right: -30px;
            top: -30px;

            border-radius: 50%;

            background:
                rgba(37, 99, 235, .055);
        }


        .al-stat-icon {

            width: 42px;
            height: 42px;

            display: flex;

            align-items: center;
            justify-content: center;

            border-radius: 12px;

            color: var(--primary);

            background:
                var(--primary-soft);
        }


        .al-stat:nth-child(2)
        .al-stat-icon {

            color: var(--success);

            background:
                var(--success-soft);
        }


        .al-stat:nth-child(3)
        .al-stat-icon {

            color: var(--purple);

            background:
                var(--purple-soft);
        }


        .al-stat:nth-child(4)
        .al-stat-icon {

            color: var(--info);

            background:
                var(--info-soft);
        }


        .al-stat-label {

            margin-top: 16px;

            color: var(--muted);

            font-size: 12px;

            font-weight: 600;
        }


        .al-stat-value {

            margin-top: 4px;

            color: var(--dark);

            font-size: 25px;

            font-weight: 800;

            letter-spacing: -.04em;
        }


        /* =====================================================
           CARD
        ===================================================== */

        .al-card {

            border:
                1px solid var(--border);

            border-radius:
                var(--radius);

            background: #fff;

            box-shadow:
                var(--shadow);
        }


        /* =====================================================
           FILTERS
        ===================================================== */

        .al-filter-card {

            margin-bottom: 22px;

            padding: 18px;
        }


        .al-filter-grid {

            display: grid;

            grid-template-columns:
                1.5fr
                1fr
                1fr
                1fr
                1fr;

            gap: 12px;

            align-items: end;
        }


        .al-filter-grid-bottom {

            display: grid;

            grid-template-columns:
                1fr
                1fr
                auto;

            gap: 12px;

            margin-top: 13px;

            align-items: end;
        }


        .al-field label {

            display: block;

            margin-bottom: 7px;

            color: #475569;

            font-size: 10px;

            font-weight: 800;

            text-transform: uppercase;

            letter-spacing: .07em;
        }


        .al-input,
        .al-select {

            width: 100%;

            height: 43px;

            padding:
                0 12px;

            border:
                1px solid var(--border);

            border-radius: 11px;

            outline: none;

            background: #fff;

            color: var(--text);

            transition:
                border-color .18s ease,
                box-shadow .18s ease;
        }


        .al-input:focus,
        .al-select:focus {

            border-color:
                #93c5fd;

            box-shadow:
                0 0 0 4px
                rgba(37, 99, 235, .08);
        }


        .al-filter-actions {

            display: flex;

            gap: 8px;
        }


        /* =====================================================
           TABLE
        ===================================================== */

        .al-table-card {
            overflow: hidden;
        }


        .al-table-header {

            display: flex;

            align-items: center;

            justify-content: space-between;

            gap: 15px;

            padding:
                18px 20px;

            border-bottom:
                1px solid var(--border);
        }


        .al-table-title {

            color: var(--dark);

            font-size: 15px;

            font-weight: 800;
        }


        .al-table-meta {

            display: flex;

            align-items: center;

            gap: 8px;
        }


        .al-count {

            display: inline-flex;

            align-items: center;

            padding:
                6px 10px;

            border-radius: 999px;

            color: var(--primary);

            background:
                var(--primary-soft);

            font-size: 11px;

            font-weight: 800;
        }


        .al-table-wrap {
            overflow-x: auto;
        }


        .al-table {

            width: 100%;

            min-width: 1180px;

            border-collapse: collapse;
        }


        .al-table th {

            padding:
                13px 15px;

            background:
                #f8fafc;

            color: #64748b;

            font-size: 10px;

            font-weight: 800;

            text-transform: uppercase;

            letter-spacing: .07em;

            text-align: left;

            white-space: nowrap;
        }


        .al-table td {

            padding:
                15px;

            border-top:
                1px solid #eef2f7;

            vertical-align: middle;
        }


        .al-table tbody tr {

            transition:
                background .16s ease;
        }


        .al-table tbody tr:hover {

            background:
                #fafcff;
        }


        /* =====================================================
           CHECKBOX
        ===================================================== */

        .al-check {

            width: 17px;
            height: 17px;

            accent-color:
                var(--primary);

            cursor: pointer;
        }


        /* =====================================================
           ID
        ===================================================== */

        .al-id {

            display: inline-flex;

            min-width: 38px;

            height: 30px;

            align-items: center;
            justify-content: center;

            padding:
                0 9px;

            border-radius: 9px;

            background:
                #f1f5f9;

            color:
                #475569;

            font-size: 11px;

            font-weight: 800;
        }


        /* =====================================================
           USER
        ===================================================== */

        .al-user {

            display: flex;

            align-items: center;

            gap: 9px;
        }


        .al-user-avatar {

            width: 34px;
            height: 34px;

            display: flex;

            align-items: center;
            justify-content: center;

            flex: 0 0 34px;

            border-radius: 10px;

            color: var(--primary);

            background:
                var(--primary-soft);

            font-size: 12px;
        }


        .al-user strong {

            display: block;

            color: var(--dark);

            font-size: 12px;
        }


        .al-user span {

            display: block;

            margin-top: 2px;

            color: var(--muted);

            font-size: 10px;
        }


        .al-system-user {

            color: #64748b;

            font-size: 11px;

            font-weight: 700;
        }


        /* =====================================================
           MODULE
        ===================================================== */

        .al-module {

            display: inline-flex;

            padding:
                6px 9px;

            border-radius: 8px;

            background:
                #f8fafc;

            border:
                1px solid var(--border);

            color:
                #475569;

            font-size: 10px;

            font-weight: 800;

            text-transform: uppercase;

            letter-spacing: .04em;
        }


        /* =====================================================
           ACTION BADGE
        ===================================================== */

        .al-action {

            display: inline-flex;

            align-items: center;

            gap: 6px;

            padding:
                6px 9px;

            border-radius: 8px;

            font-size: 10px;

            font-weight: 800;

            text-transform: uppercase;

            letter-spacing: .04em;
        }


        .al-action.success {

            color: #166534;

            background:
                var(--success-soft);
        }


        .al-action.danger {

            color: #991b1b;

            background:
                var(--danger-soft);
        }


        .al-action.warning {

            color: #92400e;

            background:
                var(--warning-soft);
        }


        .al-action.info {

            color: #155e75;

            background:
                var(--info-soft);
        }


        .al-action.neutral {

            color: #475569;

            background:
                #f1f5f9;
        }


        /* =====================================================
           ENTITY
        ===================================================== */

        .al-entity {

            display: flex;

            flex-direction: column;

            gap: 3px;
        }


        .al-entity-type {

            color:
                var(--dark);

            font-size: 11px;

            font-weight: 700;
        }


        .al-entity-id {

            color:
                var(--muted);

            font-size: 10px;
        }


        /* =====================================================
           DESCRIPTION
        ===================================================== */

        .al-description {

            max-width: 280px;

            color:
                #64748b;

            font-size: 11px;

            line-height: 1.55;

            display:
                -webkit-box;

            -webkit-line-clamp: 2;

            -webkit-box-orient: vertical;

            overflow: hidden;
        }


        /* =====================================================
           IP
        ===================================================== */

        .al-ip {

            display: inline-flex;

            padding:
                5px 8px;

            border-radius: 7px;

            background:
                #f8fafc;

            border:
                1px solid var(--border);

            color:
                #475569;

            font-family:
                monospace;

            font-size: 10px;
        }


        /* =====================================================
           DATE
        ===================================================== */

        .al-date {

            color:
                #64748b;

            font-size: 10px;

            white-space: nowrap;
        }


        /* =====================================================
           ACTIONS
        ===================================================== */

        .al-row-actions {

            display: flex;

            gap: 6px;
        }


        .al-action-btn {

            width: 34px;
            height: 34px;

            display: inline-flex;

            align-items: center;
            justify-content: center;

            border:
                1px solid var(--border);

            border-radius: 9px;

            background: #fff;

            color:
                #64748b;

            transition:
                all .18s ease;
        }


        .al-action-btn:hover {

            transform:
                translateY(-1px);

            color:
                var(--primary);

            border-color:
                #bfdbfe;

            background:
                var(--primary-soft);
        }


        .al-action-btn.delete:hover {

            color:
                var(--danger);

            border-color:
                #fecaca;

            background:
                var(--danger-soft);
        }


        /* =====================================================
           EMPTY
        ===================================================== */

        .al-empty {

            padding:
                70px 25px;

            text-align: center;
        }


        .al-empty-icon {

            width: 66px;
            height: 66px;

            display: flex;

            align-items: center;
            justify-content: center;

            margin:
                0 auto 16px;

            border-radius: 20px;

            color:
                var(--primary);

            background:
                var(--primary-soft);

            font-size: 25px;
        }


        .al-empty h3 {

            margin: 0;

            color:
                var(--dark);

            font-size: 16px;
        }


        .al-empty p {

            max-width: 450px;

            margin:
                8px auto 0;

            color:
                var(--muted);

            font-size: 12px;

            line-height: 1.7;
        }


        /* =====================================================
           DETAIL OVERLAY
        ===================================================== */

        .al-modal {

            position: fixed;

            inset: 0;

            z-index: 200;

            display: flex;

            align-items: center;

            justify-content: center;

            padding: 25px;

            background:
                rgba(15, 23, 42, .52);

            backdrop-filter:
                blur(5px);
        }


        .al-modal-box {

            width: min(900px, 100%);

            max-height:
                calc(100vh - 50px);

            overflow-y: auto;

            border:
                1px solid rgba(255,255,255,.5);

            border-radius: 22px;

            background: #fff;

            box-shadow:
                0 30px 80px
                rgba(15, 23, 42, .25);
        }


        .al-modal-header {

            display: flex;

            align-items: flex-start;

            justify-content: space-between;

            gap: 15px;

            padding:
                22px;

            border-bottom:
                1px solid var(--border);
        }


        .al-modal-header h2 {

            margin: 0;

            color:
                var(--dark);

            font-size: 18px;
        }


        .al-modal-header p {

            margin:
                5px 0 0;

            color:
                var(--muted);

            font-size: 11px;
        }


        .al-modal-close {

            width: 36px;
            height: 36px;

            display: flex;

            align-items: center;
            justify-content: center;

            border:
                1px solid var(--border);

            border-radius: 10px;

            background: #fff;

            color:
                #64748b;
        }


        .al-modal-body {

            padding:
                22px;
        }


        .al-detail-grid {

            display: grid;

            grid-template-columns:
                repeat(2, minmax(0, 1fr));

            gap: 14px;

            margin-bottom: 18px;
        }


        .al-detail {

            padding:
                14px;

            border:
                1px solid var(--border);

            border-radius: 13px;

            background:
                #f8fafc;
        }


        .al-detail-label {

            margin-bottom: 5px;

            color:
                #64748b;

            font-size: 9px;

            font-weight: 800;

            text-transform: uppercase;

            letter-spacing: .07em;
        }


        .al-detail-value {

            color:
                var(--dark);

            font-size: 12px;

            font-weight: 700;

            word-break: break-word;
        }


        .al-code-section {

            margin-top: 17px;
        }


        .al-code-title {

            display: flex;

            align-items: center;

            justify-content: space-between;

            margin-bottom: 8px;

            color:
                var(--dark);

            font-size: 12px;

            font-weight: 800;
        }


        .al-code {

            max-height: 260px;

            overflow: auto;

            padding:
                15px;

            border:
                1px solid #1e293b;

            border-radius: 13px;

            background:
                #0f172a;

            color:
                #e2e8f0;

            font-family:
                Consolas,
                Monaco,
                monospace;

            font-size: 11px;

            line-height: 1.65;

            white-space: pre-wrap;

            word-break: break-word;
        }


        /* =====================================================
           RESPONSIVE
        ===================================================== */

        @media (max-width: 1250px) {

            .al-filter-grid {

                grid-template-columns:
                    repeat(3, minmax(0, 1fr));
            }

            .al-stats {

                grid-template-columns:
                    repeat(2, minmax(0, 1fr));
            }
        }


        @media (max-width: 991px) {

            .al-page {
                margin-left: 0;
            }

            .al-mobile-menu {
                display: inline-flex;
            }

            .al-topbar {

                height: 68px;

                padding:
                    0 18px;
            }

            .al-admin-badge {
                display: none;
            }

            .al-content {

                padding:
                    22px 18px;
            }

            .al-heading {

                align-items:
                    flex-start;

                flex-direction:
                    column;
            }

            .al-heading-actions {
                width: 100%;
            }

            .al-heading-actions .al-btn {
                flex: 1;
            }
        }


        @media (max-width: 700px) {

            .al-stats {

                grid-template-columns:
                    1fr;
            }

            .al-filter-grid {

                grid-template-columns:
                    1fr;
            }

            .al-filter-grid-bottom {

                grid-template-columns:
                    1fr;
            }

            .al-filter-actions .al-btn {
                flex: 1;
            }

            .al-detail-grid {

                grid-template-columns:
                    1fr;
            }

            .al-heading h1 {
                font-size: 25px;
            }
        }


        @media (max-width: 480px) {

            .al-content {

                padding:
                    18px 12px;
            }

            .al-heading-actions {

                flex-direction:
                    column;
            }

            .al-heading-actions .al-btn {

                width: 100%;
            }

            .al-table-header {

                align-items:
                    flex-start;

                flex-direction:
                    column;
            }

            .al-modal {

                padding:
                    10px;
            }

            .al-modal-box {

                max-height:
                    calc(100vh - 20px);

                border-radius:
                    17px;
            }
        }

    </style>

</head>


<body>

<?php
/*
 * Existing Pure Chemical admin sidebar.
 * No duplicate sidebar is created.
 */
require_once __DIR__ . '/sidebar.php';
?>


<div class="al-page">


    <!-- =====================================================
         TOPBAR
    ====================================================== -->

    <header class="al-topbar">

        <div class="al-topbar-left">

            <button
                type="button"
                class="al-mobile-menu"
                onclick="toggleSidebar()"
                aria-label="Open menu"
            >
                <i class="fa-solid fa-bars"></i>
            </button>

            <div>

                <h1 class="al-title">
                    Activity Logs
                </h1>

                <p class="al-subtitle">
                    Monitor administrative and system activity
                </p>

            </div>

        </div>


        <div>

            <div class="al-admin-badge">

                <i class="fa-solid fa-shield-halved"></i>

                Audit Center

            </div>

        </div>

    </header>


    <main class="al-content">


        <!-- =================================================
             FLASH
        ================================================== -->

        <?php if ($flash): ?>

            <div
                class="al-alert <?= al_e($flash['type']) ?>"
                id="alFlash"
            >

                <?php if ($flash['type'] === 'success'): ?>

                    <i class="fa-solid fa-circle-check"></i>

                <?php else: ?>

                    <i class="fa-solid fa-circle-exclamation"></i>

                <?php endif; ?>

                <span>
                    <?= al_e($flash['message']) ?>
                </span>

                <button
                    type="button"
                    class="al-alert-close"
                    onclick="document.getElementById('alFlash').remove()"
                >
                    <i class="fa-solid fa-xmark"></i>
                </button>

            </div>

        <?php endif; ?>


        <!-- =================================================
             HEADING
        ================================================== -->

        <section class="al-heading">

            <div>

                <h1>
                    Activity Logs
                </h1>

                <p>
                    Complete audit trail of actions performed inside
                    the Pure Chemical administration panel.
                </p>

            </div>


            <div class="al-heading-actions">

                <a
                    href="activity_logs.php"
                    class="al-btn al-btn-secondary"
                >
                    <i class="fa-solid fa-rotate-right"></i>
                    Refresh
                </a>

            </div>

        </section>


        <!-- =================================================
             STATS
        ================================================== -->

        <section class="al-stats">


            <div class="al-stat">

                <div class="al-stat-icon">
                    <i class="fa-solid fa-list-check"></i>
                </div>

                <div class="al-stat-label">
                    Total Logs
                </div>

                <div class="al-stat-value">
                    <?= number_format($totalLogs) ?>
                </div>

            </div>


            <div class="al-stat">

                <div class="al-stat-icon">
                    <i class="fa-solid fa-calendar-day"></i>
                </div>

                <div class="al-stat-label">
                    Today's Activity
                </div>

                <div class="al-stat-value">
                    <?= number_format($todayLogs) ?>
                </div>

            </div>


            <div class="al-stat">

                <div class="al-stat-icon">
                    <i class="fa-solid fa-users"></i>
                </div>

                <div class="al-stat-label">
                    Active Users
                </div>

                <div class="al-stat-value">
                    <?= number_format($activeUsers) ?>
                </div>

            </div>


            <div class="al-stat">

                <div class="al-stat-icon">
                    <i class="fa-solid fa-cubes"></i>
                </div>

                <div class="al-stat-label">
                    Modules
                </div>

                <div class="al-stat-value">
                    <?= number_format($totalModules) ?>
                </div>

            </div>


        </section>


        <!-- =================================================
             FILTERS
        ================================================== -->

        <section class="al-card al-filter-card">

            <form
                method="get"
                action="activity_logs.php"
            >


                <div class="al-filter-grid">


                    <!-- SEARCH -->

                    <div class="al-field">

                        <label>
                            Search
                        </label>

                        <input
                            type="text"
                            name="search"
                            class="al-input"
                            value="<?= al_e($search) ?>"
                            placeholder="Module, action, entity, description, IP..."
                        >

                    </div>


                    <!-- USER -->

                    <div class="al-field">

                        <label>
                            User
                        </label>

                        <select
                            name="user_id"
                            class="al-select"
                        >

                            <option value="">
                                All users
                            </option>

                            <?php foreach ($users as $user): ?>

                                <option
                                    value="<?= (int)$user['id'] ?>"
                                    <?= $filterUser === (int)$user['id'] ? 'selected' : '' ?>
                                >

                                    <?php
                                    $userLabel = 'User #' .
                                        (int)$user['id'];

                                    if (
                                        isset($user['name']) &&
                                        trim((string)$user['name']) !== ''
                                    ) {
                                        $userLabel =
                                            (string)$user['name'];
                                    } elseif (
                                        isset($user['email']) &&
                                        trim((string)$user['email']) !== ''
                                    ) {
                                        $userLabel =
                                            (string)$user['email'];
                                    }
                                    ?>

                                    <?= al_e($userLabel) ?>

                                </option>

                            <?php endforeach; ?>

                        </select>

                    </div>


                    <!-- MODULE -->

                    <div class="al-field">

                        <label>
                            Module
                        </label>

                        <select
                            name="module"
                            class="al-select"
                        >

                            <option value="">
                                All modules
                            </option>

                            <?php foreach ($modules as $module): ?>

                                <option
                                    value="<?= al_e($module) ?>"
                                    <?= $filterModule === $module ? 'selected' : '' ?>
                                >
                                    <?= al_e($module) ?>
                                </option>

                            <?php endforeach; ?>

                        </select>

                    </div>


                    <!-- ACTION -->

                    <div class="al-field">

                        <label>
                            Action
                        </label>

                        <select
                            name="action_filter"
                            class="al-select"
                        >

                            <option value="">
                                All actions
                            </option>

                            <?php foreach ($actions as $action): ?>

                                <option
                                    value="<?= al_e($action) ?>"
                                    <?= $filterAction === $action ? 'selected' : '' ?>
                                >
                                    <?= al_e($action) ?>
                                </option>

                            <?php endforeach; ?>

                        </select>

                    </div>


                    <!-- ENTITY TYPE -->

                    <div class="al-field">

                        <label>
                            Entity Type
                        </label>

                        <select
                            name="entity_type"
                            class="al-select"
                        >

                            <option value="">
                                All entity types
                            </option>

                            <?php foreach ($entityTypes as $entityType): ?>

                                <option
                                    value="<?= al_e($entityType) ?>"
                                    <?= $filterEntityType === $entityType ? 'selected' : '' ?>
                                >
                                    <?= al_e($entityType) ?>
                                </option>

                            <?php endforeach; ?>

                        </select>

                    </div>

                </div>


                <div class="al-filter-grid-bottom">


                    <div class="al-field">

                        <label>
                            From Date
                        </label>

                        <input
                            type="date"
                            name="date_from"
                            class="al-input"
                            value="<?= al_e($dateFrom) ?>"
                        >

                    </div>


                    <div class="al-field">

                        <label>
                            To Date
                        </label>

                        <input
                            type="date"
                            name="date_to"
                            class="al-input"
                            value="<?= al_e($dateTo) ?>"
                        >

                    </div>


                    <div class="al-filter-actions">

                        <button
                            type="submit"
                            class="al-btn al-btn-primary"
                        >
                            <i class="fa-solid fa-filter"></i>
                            Apply Filters
                        </button>

                        <a
                            href="activity_logs.php"
                            class="al-btn al-btn-secondary"
                        >
                            Reset
                        </a>

                    </div>


                </div>

            </form>

        </section>


        <!-- =================================================
             TABLE
        ================================================== -->

        <section class="al-card al-table-card">


            <div class="al-table-header">

                <div class="al-table-title">
                    Audit Trail
                </div>


                <div class="al-table-meta">

                    <span class="al-count">
                        <?= number_format(count($logs)) ?>
                        Records
                    </span>

                </div>

            </div>


            <?php if (!empty($logs)): ?>


                <form
                    method="post"
                    action="activity_logs.php"
                    id="bulkDeleteForm"
                    onsubmit="return confirmBulkDelete();"
                >

                    <?= al_csrf_field() ?>

                    <input
                        type="hidden"
                        name="action"
                        value="bulk_delete"
                    >


                    <div class="al-table-wrap">

                        <table class="al-table">

                            <thead>

                                <tr>

                                    <th style="width:40px;">

                                        <input
                                            type="checkbox"
                                            class="al-check"
                                            id="selectAll"
                                            onclick="toggleAllLogs(this)"
                                        >

                                    </th>

                                    <th>
                                        ID
                                    </th>

                                    <th>
                                        User
                                    </th>

                                    <th>
                                        Module
                                    </th>

                                    <th>
                                        Action
                                    </th>

                                    <th>
                                        Entity
                                    </th>

                                    <th>
                                        Description
                                    </th>

                                    <th>
                                        IP Address
                                    </th>

                                    <th>
                                        Created
                                    </th>

                                    <th>
                                        Actions
                                    </th>

                                </tr>

                            </thead>


                            <tbody>

                            <?php foreach ($logs as $log): ?>

                                <?php
                                $actionClass =
                                    al_action_class(
                                        (string)($log['action'] ?? '')
                                    );

                                $actionText =
                                    trim(
                                        (string)($log['action'] ?? '')
                                    );

                                $userName =
                                    trim(
                                        (string)($log['user_name'] ?? '')
                                    );

                                $userEmail =
                                    trim(
                                        (string)($log['user_email'] ?? '')
                                    );
                                ?>


                                <tr>


                                    <!-- CHECK -->

                                    <td>

                                        <input
                                            type="checkbox"
                                            name="ids[]"
                                            value="<?= (int)$log['id'] ?>"
                                            class="al-check log-check"
                                        >

                                    </td>


                                    <!-- ID -->

                                    <td>

                                        <span class="al-id">
                                            #<?= (int)$log['id'] ?>
                                        </span>

                                    </td>


                                    <!-- USER -->

                                    <td>

                                        <?php if ($log['user_id']): ?>

                                            <div class="al-user">

                                                <div class="al-user-avatar">

                                                    <i class="fa-solid fa-user"></i>

                                                </div>

                                                <div>

                                                    <strong>

                                                        <?php
                                                        if ($userName !== '') {
                                                            echo al_e($userName);
                                                        } else {
                                                            echo 'User #' .
                                                                (int)$log['user_id'];
                                                        }
                                                        ?>

                                                    </strong>

                                                    <?php if ($userEmail !== ''): ?>

                                                        <span>
                                                            <?= al_e($userEmail) ?>
                                                        </span>

                                                    <?php else: ?>

                                                        <span>
                                                            User ID:
                                                            #<?= (int)$log['user_id'] ?>
                                                        </span>

                                                    <?php endif; ?>

                                                </div>

                                            </div>

                                        <?php else: ?>

                                            <span class="al-system-user">
                                                <i class="fa-solid fa-gear"></i>
                                                System
                                            </span>

                                        <?php endif; ?>

                                    </td>


                                    <!-- MODULE -->

                                    <td>

                                        <?php if (!empty($log['module'])): ?>

                                            <span class="al-module">
                                                <?= al_e($log['module']) ?>
                                            </span>

                                        <?php else: ?>

                                            <span style="color:#94a3b8;">
                                                —
                                            </span>

                                        <?php endif; ?>

                                    </td>


                                    <!-- ACTION -->

                                    <td>

                                        <span
                                            class="al-action <?= al_e($actionClass) ?>"
                                        >

                                            <?php if ($actionClass === 'danger'): ?>

                                                <i class="fa-solid fa-trash-can"></i>

                                            <?php elseif ($actionClass === 'success'): ?>

                                                <i class="fa-solid fa-plus"></i>

                                            <?php elseif ($actionClass === 'warning'): ?>

                                                <i class="fa-solid fa-pen"></i>

                                            <?php elseif ($actionClass === 'info'): ?>

                                                <i class="fa-solid fa-right-to-bracket"></i>

                                            <?php else: ?>

                                                <i class="fa-solid fa-bolt"></i>

                                            <?php endif; ?>

                                            <?= al_e($actionText ?: 'Activity') ?>

                                        </span>

                                    </td>


                                    <!-- ENTITY -->

                                    <td>

                                        <div class="al-entity">

                                            <span class="al-entity-type">

                                                <?= !empty($log['entity_type'])
                                                    ? al_e($log['entity_type'])
                                                    : '—'
                                                ?>

                                            </span>

                                            <?php if (!empty($log['entity_id'])): ?>

                                                <span class="al-entity-id">

                                                    ID:
                                                    #<?= (int)$log['entity_id'] ?>

                                                </span>

                                            <?php endif; ?>

                                        </div>

                                    </td>


                                    <!-- DESCRIPTION -->

                                    <td>

                                        <?php if (!empty($log['description'])): ?>

                                            <div
                                                class="al-description"
                                                title="<?= al_e($log['description']) ?>"
                                            >
                                                <?= al_e($log['description']) ?>
                                            </div>

                                        <?php else: ?>

                                            <span style="color:#94a3b8;">
                                                —
                                            </span>

                                        <?php endif; ?>

                                    </td>


                                    <!-- IP -->

                                    <td>

                                        <?php if (!empty($log['ip_address'])): ?>

                                            <span class="al-ip">
                                                <?= al_e($log['ip_address']) ?>
                                            </span>

                                        <?php else: ?>

                                            <span style="color:#94a3b8;">
                                                —
                                            </span>

                                        <?php endif; ?>

                                    </td>


                                    <!-- DATE -->

                                    <td>

                                        <div class="al-date">

                                            <?php
                                            if (!empty($log['created_at'])) {

                                                echo al_e(
                                                    date(
                                                        'd M Y',
                                                        strtotime(
                                                            $log['created_at']
                                                        )
                                                    )
                                                );

                                                echo '<br>';

                                                echo al_e(
                                                    date(
                                                        'h:i A',
                                                        strtotime(
                                                            $log['created_at']
                                                        )
                                                    )
                                                );

                                            } else {
                                                echo '—';
                                            }
                                            ?>

                                        </div>

                                    </td>


                                    <!-- ACTIONS -->

                                    <td>

                                        <div class="al-row-actions">


                                            <a
                                                href="activity_logs.php?view=<?= (int)$log['id'] ?>"
                                                class="al-action-btn"
                                                title="View Details"
                                            >

                                                <i class="fa-solid fa-eye"></i>

                                            </a>


                                            <form
                                                method="post"
                                                action="activity_logs.php"
                                                style="display:inline;"
                                                onsubmit="return confirm('Delete this activity log permanently?');"
                                            >

                                                <?= al_csrf_field() ?>

                                                <input
                                                    type="hidden"
                                                    name="action"
                                                    value="delete"
                                                >

                                                <input
                                                    type="hidden"
                                                    name="id"
                                                    value="<?= (int)$log['id'] ?>"
                                                >

                                                <button
                                                    type="submit"
                                                    class="al-action-btn delete"
                                                    title="Delete"
                                                >

                                                    <i class="fa-solid fa-trash"></i>

                                                </button>

                                            </form>


                                        </div>

                                    </td>


                                </tr>

                            <?php endforeach; ?>

                            </tbody>

                        </table>

                    </div>


                    <!-- BULK ACTION BAR -->

                    <div
                        style="
                            display:flex;
                            align-items:center;
                            justify-content:space-between;
                            gap:12px;
                            padding:14px 18px;
                            border-top:1px solid var(--border);
                            background:#fafcff;
                        "
                    >

                        <div
                            id="selectedCount"
                            style="
                                color:#64748b;
                                font-size:11px;
                                font-weight:700;
                            "
                        >
                            0 selected
                        </div>


                        <button
                            type="submit"
                            class="al-btn al-btn-danger"
                            id="bulkDeleteBtn"
                            disabled
                        >

                            <i class="fa-solid fa-trash-can"></i>

                            Delete Selected

                        </button>

                    </div>


                </form>


            <?php else: ?>


                <div class="al-empty">

                    <div class="al-empty-icon">

                        <i class="fa-solid fa-clock-rotate-left"></i>

                    </div>


                    <h3>
                        No activity logs found
                    </h3>


                    <p>
                        No audit records match your current filters.
                        Try changing the search or filter conditions.
                    </p>


                    <div style="margin-top:18px;">

                        <a
                            href="activity_logs.php"
                            class="al-btn al-btn-secondary"
                        >

                            <i class="fa-solid fa-rotate-right"></i>

                            Clear Filters

                        </a>

                    </div>

                </div>


            <?php endif; ?>


        </section>


    </main>

</div>


<!-- =========================================================
     DETAIL MODAL
========================================================= -->

<?php if ($viewLog): ?>


    <div
        class="al-modal"
        id="logModal"
        onclick="closeModalOutside(event)"
    >

        <div class="al-modal-box">


            <div class="al-modal-header">

                <div>

                    <h2>
                        Activity Log #<?= (int)$viewLog['id'] ?>
                    </h2>

                    <p>
                        Complete audit information for this activity.
                    </p>

                </div>


                <button
                    type="button"
                    class="al-modal-close"
                    onclick="closeLogModal()"
                >

                    <i class="fa-solid fa-xmark"></i>

                </button>

            </div>


            <div class="al-modal-body">


                <div class="al-detail-grid">


                    <div class="al-detail">

                        <div class="al-detail-label">
                            User
                        </div>

                        <div class="al-detail-value">

                            <?php if (!empty($viewLog['user_id'])): ?>

                                <?php
                                $modalUser =
                                    trim(
                                        (string)(
                                            $viewLog['user_name']
                                            ?? ''
                                        )
                                    );

                                if ($modalUser === '') {
                                    $modalUser =
                                        'User #' .
                                        (int)$viewLog['user_id'];
                                }
                                ?>

                                <?= al_e($modalUser) ?>

                                <?php if (!empty($viewLog['user_email'])): ?>

                                    <div
                                        style="
                                            margin-top:4px;
                                            color:#64748b;
                                            font-size:10px;
                                            font-weight:500;
                                        "
                                    >
                                        <?= al_e($viewLog['user_email']) ?>
                                    </div>

                                <?php endif; ?>

                            <?php else: ?>

                                System

                            <?php endif; ?>

                        </div>

                    </div>


                    <div class="al-detail">

                        <div class="al-detail-label">
                            Module
                        </div>

                        <div class="al-detail-value">
                            <?= !empty($viewLog['module'])
                                ? al_e($viewLog['module'])
                                : '—'
                            ?>
                        </div>

                    </div>


                    <div class="al-detail">

                        <div class="al-detail-label">
                            Action
                        </div>

                        <div class="al-detail-value">
                            <?= !empty($viewLog['action'])
                                ? al_e($viewLog['action'])
                                : '—'
                            ?>
                        </div>

                    </div>


                    <div class="al-detail">

                        <div class="al-detail-label">
                            Entity
                        </div>

                        <div class="al-detail-value">

                            <?= !empty($viewLog['entity_type'])
                                ? al_e($viewLog['entity_type'])
                                : '—'
                            ?>

                            <?php if (!empty($viewLog['entity_id'])): ?>

                                <span
                                    style="
                                        color:#64748b;
                                        font-weight:600;
                                    "
                                >
                                    #<?= (int)$viewLog['entity_id'] ?>
                                </span>

                            <?php endif; ?>

                        </div>

                    </div>


                    <div class="al-detail">

                        <div class="al-detail-label">
                            IP Address
                        </div>

                        <div class="al-detail-value">
                            <?= !empty($viewLog['ip_address'])
                                ? al_e($viewLog['ip_address'])
                                : '—'
                            ?>
                        </div>

                    </div>


                    <div class="al-detail">

                        <div class="al-detail-label">
                            Created At
                        </div>

                        <div class="al-detail-value">

                            <?php
                            if (!empty($viewLog['created_at'])) {

                                echo al_e(
                                    date(
                                        'd M Y, h:i:s A',
                                        strtotime(
                                            $viewLog['created_at']
                                        )
                                    )
                                );

                            } else {
                                echo '—';
                            }
                            ?>

                        </div>

                    </div>


                    <div
                        class="al-detail"
                        style="grid-column:1 / -1;"
                    >

                        <div class="al-detail-label">
                            Description
                        </div>

                        <div class="al-detail-value">

                            <?= !empty($viewLog['description'])
                                ? nl2br(
                                    al_e(
                                        $viewLog['description']
                                    )
                                )
                                : 'No description available.'
                            ?>

                        </div>

                    </div>


                </div>


                <!-- OLD VALUES -->

                <?php if (
                    isset($viewLog['old_values']) &&
                    trim((string)$viewLog['old_values']) !== ''
                ): ?>

                    <div class="al-code-section">

                        <div class="al-code-title">

                            <span>
                                <i class="fa-solid fa-clock-rotate-left"></i>
                                Old Values
                            </span>

                        </div>

                        <pre class="al-code"><?= al_e(
                            al_json_pretty(
                                (string)$viewLog['old_values']
                            )
                        ) ?></pre>

                    </div>

                <?php endif; ?>


                <!-- NEW VALUES -->

                <?php if (
                    isset($viewLog['new_values']) &&
                    trim((string)$viewLog['new_values']) !== ''
                ): ?>

                    <div class="al-code-section">

                        <div class="al-code-title">

                            <span>
                                <i class="fa-solid fa-code-branch"></i>
                                New Values
                            </span>

                        </div>

                        <pre class="al-code"><?= al_e(
                            al_json_pretty(
                                (string)$viewLog['new_values']
                            )
                        ) ?></pre>

                    </div>

                <?php endif; ?>


                <!-- USER AGENT -->

                <?php if (
                    isset($viewLog['user_agent']) &&
                    trim((string)$viewLog['user_agent']) !== ''
                ): ?>

                    <div class="al-code-section">

                        <div class="al-code-title">

                            <span>
                                <i class="fa-solid fa-desktop"></i>
                                User Agent
                            </span>

                        </div>

                        <pre class="al-code"><?= al_e(
                            (string)$viewLog['user_agent']
                        ) ?></pre>

                    </div>

                <?php endif; ?>


            </div>


        </div>

    </div>


<?php endif; ?>


<script>


    /* =====================================================
       SIDEBAR
    ===================================================== */

    function toggleSidebar() {

        const sidebar =
            document.getElementById('pcSidebar');

        if (!sidebar) {
            return;
        }

        sidebar.classList.toggle('open');
    }


    document.addEventListener(
        'click',
        function (event) {

            const sidebar =
                document.getElementById('pcSidebar');

            const button =
                document.querySelector('.al-mobile-menu');

            if (
                !sidebar ||
                !button ||
                window.innerWidth > 991
            ) {
                return;
            }

            if (
                sidebar.classList.contains('open') &&
                !sidebar.contains(event.target) &&
                !button.contains(event.target)
            ) {

                sidebar.classList.remove('open');
            }

        }
    );


    /* =====================================================
       SELECT ALL
    ===================================================== */

    function toggleAllLogs(source) {

        const checks =
            document.querySelectorAll('.log-check');

        checks.forEach(function (checkbox) {

            checkbox.checked =
                source.checked;

        });

        updateSelectedCount();
    }


    /* =====================================================
       SELECTED COUNT
    ===================================================== */

    function updateSelectedCount() {

        const checked =
            document.querySelectorAll(
                '.log-check:checked'
            );

        const countElement =
            document.getElementById(
                'selectedCount'
            );

        const deleteButton =
            document.getElementById(
                'bulkDeleteBtn'
            );

        const count =
            checked.length;

        if (countElement) {

            countElement.textContent =
                count +
                (
                    count === 1
                    ? ' selected'
                    : ' selected'
                );
        }

        if (deleteButton) {
            deleteButton.disabled =
                count === 0;
        }

        const selectAll =
            document.getElementById(
                'selectAll'
            );

        const all =
            document.querySelectorAll(
                '.log-check'
            );

        if (selectAll) {

            selectAll.checked =
                all.length > 0 &&
                checked.length === all.length;
        }
    }


    document.querySelectorAll('.log-check')
        .forEach(function (checkbox) {

            checkbox.addEventListener(
                'change',
                updateSelectedCount
            );

        });


    /* =====================================================
       BULK DELETE CONFIRM
    ===================================================== */

    function confirmBulkDelete() {

        const count =
            document.querySelectorAll(
                '.log-check:checked'
            ).length;

        if (count === 0) {
            return false;
        }

        return confirm(
            'Delete ' +
            count +
            ' selected activity log(s) permanently?'
        );
    }


    /* =====================================================
       MODAL
    ===================================================== */

    function closeLogModal() {

        const modal =
            document.getElementById(
                'logModal'
            );

        if (modal) {

            modal.remove();

            /*
             * Remove ?view=... from URL
             * without reloading.
             */
            if (
                window.history &&
                window.history.replaceState
            ) {

                const url =
                    new URL(
                        window.location.href
                    );

                url.searchParams.delete(
                    'view'
                );

                window.history.replaceState(
                    {},
                    document.title,
                    url.toString()
                );
            }
        }
    }


    function closeModalOutside(event) {

        if (
            event.target &&
            event.target.id === 'logModal'
        ) {

            closeLogModal();
        }
    }


    document.addEventListener(
        'keydown',
        function (event) {

            if (event.key === 'Escape') {

                const modal =
                    document.getElementById(
                        'logModal'
                    );

                if (modal) {
                    closeLogModal();
                }
            }

        }
    );


    /* =====================================================
       FLASH
    ===================================================== */

    setTimeout(function () {

        const flash =
            document.getElementById(
                'alFlash'
            );

        if (!flash) {
            return;
        }

        flash.style.opacity = '0';

        flash.style.transition =
            'opacity .3s ease';

        setTimeout(function () {

            if (flash) {
                flash.remove();
            }

        }, 300);

    }, 4500);


    /*
     * Initial selected count.
     */
    updateSelectedCount();

</script>


</body>
</html>