<?php

declare(strict_types=1);

date_default_timezone_set('Asia/Colombo');

require_once __DIR__ . '/../includes/auth.php';
require_once __DIR__ . '/../config/app.php';
require_once __DIR__ . '/../config/db.php';

mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);

if (($_SESSION['role'] ?? '') !== 'admin') {
    http_response_code(403);
    exit('Access denied.');
}

function bindLogParams(
    mysqli_stmt $stmt,
    string $types,
    array &$params
): void {
    if ($types === '' || $params === []) {
        return;
    }

    $refs = [];

    foreach ($params as $key => &$value) {
        $refs[$key] = &$value;
    }

    mysqli_stmt_bind_param($stmt, $types, ...$refs);
}

function logPageUrl(int $page): string
{
    $params = $_GET;
    $params['page'] = $page;

    return '?' . http_build_query($params);
}

$keyword = trim((string)($_GET['keyword'] ?? ''));
$roleFilter = trim((string)($_GET['role'] ?? ''));
$moduleFilter = trim((string)($_GET['module'] ?? ''));
$actionFilter = trim((string)($_GET['action'] ?? ''));
$dateFrom = trim((string)($_GET['date_from'] ?? ''));
$dateTo = trim((string)($_GET['date_to'] ?? ''));

$perPageOptions = [25, 50, 100];

$perPage = filter_input(
    INPUT_GET,
    'per_page',
    FILTER_VALIDATE_INT
);

if (!in_array($perPage, $perPageOptions, true)) {
    $perPage = 25;
}

$page = filter_input(
    INPUT_GET,
    'page',
    FILTER_VALIDATE_INT,
    ['options' => ['default' => 1, 'min_range' => 1]]
);

if (!$page) {
    $page = 1;
}

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

if ($keyword !== '') {
    $where .= '
        AND (
            user_name LIKE ?
            OR module LIKE ?
            OR action LIKE ?
            OR description LIKE ?
            OR ip_address LIKE ?
        )
    ';

    $search = '%' . $keyword . '%';
    $types .= 'sssss';

    for ($i = 0; $i < 5; $i++) {
        $params[] = $search;
    }
}

if ($roleFilter !== '') {
    $where .= ' AND role = ? ';
    $types .= 's';
    $params[] = $roleFilter;
}

if ($moduleFilter !== '') {
    $where .= ' AND module = ? ';
    $types .= 's';
    $params[] = $moduleFilter;
}

if ($actionFilter !== '') {
    $where .= ' AND action = ? ';
    $types .= 's';
    $params[] = $actionFilter;
}

if ($dateFrom !== '') {
    $date = DateTime::createFromFormat('Y-m-d', $dateFrom);

    if ($date && $date->format('Y-m-d') === $dateFrom) {
        $where .= ' AND DATE(log_time) >= ? ';
        $types .= 's';
        $params[] = $dateFrom;
    } else {
        $dateFrom = '';
    }
}

if ($dateTo !== '') {
    $date = DateTime::createFromFormat('Y-m-d', $dateTo);

    if ($date && $date->format('Y-m-d') === $dateTo) {
        $where .= ' AND DATE(log_time) <= ? ';
        $types .= 's';
        $params[] = $dateTo;
    } else {
        $dateTo = '';
    }
}

$countStmt = mysqli_prepare(
    $conn,
    'SELECT COUNT(*) FROM activity_logs ' . $where
);

$countParams = $params;
bindLogParams($countStmt, $types, $countParams);
mysqli_stmt_execute($countStmt);

$countResult = mysqli_stmt_get_result($countStmt);
$totalRecords = (int)(mysqli_fetch_row($countResult)[0] ?? 0);

mysqli_stmt_close($countStmt);

$totalPages = max(1, (int)ceil($totalRecords / $perPage));

if ($page > $totalPages) {
    $page = $totalPages;
}

$offset = ($page - 1) * $perPage;

$listStmt = mysqli_prepare(
    $conn,
    'SELECT
        id,
        log_time,
        user_name,
        role,
        module,
        action,
        description,
        ip_address
     FROM activity_logs
     ' . $where . '
     ORDER BY log_time DESC, id DESC
     LIMIT ? OFFSET ?'
);

$listTypes = $types . 'ii';
$listParams = $params;
$listParams[] = $perPage;
$listParams[] = $offset;

bindLogParams($listStmt, $listTypes, $listParams);
mysqli_stmt_execute($listStmt);

$listResult = mysqli_stmt_get_result($listStmt);
$logs = [];

while ($row = mysqli_fetch_assoc($listResult)) {
    $logs[] = $row;
}

mysqli_stmt_close($listStmt);

function distinctLogValues(
    mysqli $conn,
    string $column
): array {
    $allowed = ['role', 'module', 'action'];

    if (!in_array($column, $allowed, true)) {
        return [];
    }

    $stmt = mysqli_prepare(
        $conn,
        "SELECT DISTINCT {$column}
         FROM activity_logs
         WHERE {$column} IS NOT NULL
           AND {$column} <> ''
         ORDER BY {$column} ASC"
    );

    mysqli_stmt_execute($stmt);
    $result = mysqli_stmt_get_result($stmt);

    $values = [];

    while ($row = mysqli_fetch_row($result)) {
        $values[] = (string)$row[0];
    }

    mysqli_stmt_close($stmt);

    return $values;
}

$roles = distinctLogValues($conn, 'role');
$modules = distinctLogValues($conn, 'module');
$actions = distinctLogValues($conn, 'action');

$firstRecord = $totalRecords > 0 ? $offset + 1 : 0;
$lastRecord = min($offset + $perPage, $totalRecords);

include __DIR__ . '/../includes/header.php';
include __DIR__ . '/../includes/navbar.php';
?>

<main class="container-fluid px-3 px-lg-4 mt-4 mb-5">

    <div class="mb-4">
        <h4 class="mb-1">
            <i class="fa-solid fa-clock-rotate-left me-1"></i>
            Activity Log
        </h4>

        <p class="text-muted mb-0">
            Review important actions recorded during school data collection.
        </p>
    </div>

    <div class="card shadow-sm mb-4">

        <div class="card-header bg-light">
            <strong>
                <i class="fa-solid fa-filter me-1"></i>
                Search and Filters
            </strong>
        </div>

        <div class="card-body">

            <form method="get" class="row g-3">

                <div class="col-12 col-lg-4">
                    <label for="keyword" class="form-label">Search</label>

                    <input
                        type="search"
                        name="keyword"
                        id="keyword"
                        class="form-control"
                        value="<?= htmlspecialchars(
                            $keyword,
                            ENT_QUOTES,
                            'UTF-8'
                        ) ?>"
                        placeholder="User, action, details or IP"
                    >
                </div>

                <div class="col-12 col-md-6 col-lg-2">
                    <label for="role" class="form-label">Role</label>

                    <select name="role" id="role" class="form-select">
                        <option value="">All Roles</option>

                        <?php foreach ($roles as $value): ?>
                            <option
                                value="<?= htmlspecialchars(
                                    $value,
                                    ENT_QUOTES,
                                    'UTF-8'
                                ) ?>"
                                <?= $roleFilter === $value
                                    ? 'selected'
                                    : '' ?>
                            >
                                <?= htmlspecialchars(
                                    ucwords(str_replace('_', ' ', $value)),
                                    ENT_QUOTES,
                                    'UTF-8'
                                ) ?>
                            </option>
                        <?php endforeach; ?>
                    </select>
                </div>

                <div class="col-12 col-md-6 col-lg-2">
                    <label for="module" class="form-label">Module</label>

                    <select name="module" id="module" class="form-select">
                        <option value="">All Modules</option>

                        <?php foreach ($modules as $value): ?>
                            <option
                                value="<?= htmlspecialchars(
                                    $value,
                                    ENT_QUOTES,
                                    'UTF-8'
                                ) ?>"
                                <?= $moduleFilter === $value
                                    ? 'selected'
                                    : '' ?>
                            >
                                <?= htmlspecialchars(
                                    $value,
                                    ENT_QUOTES,
                                    'UTF-8'
                                ) ?>
                            </option>
                        <?php endforeach; ?>
                    </select>
                </div>

                <div class="col-12 col-md-6 col-lg-2">
                    <label for="action" class="form-label">Action</label>

                    <select name="action" id="action" class="form-select">
                        <option value="">All Actions</option>

                        <?php foreach ($actions as $value): ?>
                            <option
                                value="<?= htmlspecialchars(
                                    $value,
                                    ENT_QUOTES,
                                    'UTF-8'
                                ) ?>"
                                <?= $actionFilter === $value
                                    ? 'selected'
                                    : '' ?>
                            >
                                <?= htmlspecialchars(
                                    $value,
                                    ENT_QUOTES,
                                    'UTF-8'
                                ) ?>
                            </option>
                        <?php endforeach; ?>
                    </select>
                </div>

                <div class="col-12 col-md-6 col-lg-2">
                    <label for="per_page" class="form-label">Rows</label>

                    <select
                        name="per_page"
                        id="per_page"
                        class="form-select"
                    >
                        <?php foreach ($perPageOptions as $value): ?>
                            <option
                                value="<?= $value ?>"
                                <?= $perPage === $value
                                    ? 'selected'
                                    : '' ?>
                            >
                                <?= $value ?>
                            </option>
                        <?php endforeach; ?>
                    </select>
                </div>

                <div class="col-12 col-md-6 col-lg-2">
                    <label for="date_from" class="form-label">
                        Date From
                    </label>

                    <input
                        type="date"
                        name="date_from"
                        id="date_from"
                        class="form-control"
                        value="<?= htmlspecialchars(
                            $dateFrom,
                            ENT_QUOTES,
                            'UTF-8'
                        ) ?>"
                    >
                </div>

                <div class="col-12 col-md-6 col-lg-2">
                    <label for="date_to" class="form-label">
                        Date To
                    </label>

                    <input
                        type="date"
                        name="date_to"
                        id="date_to"
                        class="form-control"
                        value="<?= htmlspecialchars(
                            $dateTo,
                            ENT_QUOTES,
                            'UTF-8'
                        ) ?>"
                    >
                </div>

                <div class="col-12 d-flex flex-wrap gap-2">

                    <button type="submit" class="btn btn-primary">
                        <i class="fa-solid fa-magnifying-glass me-1"></i>
                        Search
                    </button>

                    <a
                        href="<?= htmlspecialchars(
                            BASE_URL . 'admin/activity_logs.php',
                            ENT_QUOTES,
                            'UTF-8'
                        ) ?>"
                        class="btn btn-outline-secondary"
                    >
                        <i class="fa-solid fa-rotate-left me-1"></i>
                        Reset
                    </a>

                </div>

            </form>

        </div>

    </div>

    <div class="card shadow-sm">

        <div
            class="card-header bg-primary text-white
                   d-flex justify-content-between align-items-center"
        >
            <strong>
                <i class="fa-solid fa-list me-1"></i>
                Recorded Activity
            </strong>

            <span>
                <?= number_format($totalRecords) ?>
                record<?= $totalRecords === 1 ? '' : 's' ?>
            </span>
        </div>

        <div class="card-body p-0">

            <?php if ($logs === []): ?>

                <div class="text-center text-muted py-5">
                    No activity records found.
                </div>

            <?php else: ?>

                <div class="table-responsive">

                    <table
                        class="table table-hover table-bordered
                               align-middle mb-0"
                    >

                        <thead class="table-light">
                            <tr>
                                <th>Date & Time</th>
                                <th>User</th>
                                <th>Role</th>
                                <th>Module</th>
                                <th>Action</th>
                                <th>Details</th>
                                <th>IP Address</th>
                            </tr>
                        </thead>

                        <tbody>

                            <?php foreach ($logs as $log): ?>

                                <tr>
                                    <td>
                                        <?= htmlspecialchars(
                                            date(
                                                'Y-m-d H:i:s',
                                                strtotime($log['log_time'])
                                            ),
                                            ENT_QUOTES,
                                            'UTF-8'
                                        ) ?>
                                    </td>

                                    <td>
                                        <?= htmlspecialchars(
                                            $log['user_name'],
                                            ENT_QUOTES,
                                            'UTF-8'
                                        ) ?>
                                    </td>

                                    <td>
                                        <span class="badge bg-secondary">
                                            <?= htmlspecialchars(
                                                ucwords(
                                                    str_replace(
                                                        '_',
                                                        ' ',
                                                        $log['role']
                                                    )
                                                ),
                                                ENT_QUOTES,
                                                'UTF-8'
                                            ) ?>
                                        </span>
                                    </td>

                                    <td>
                                        <?= htmlspecialchars(
                                            $log['module'],
                                            ENT_QUOTES,
                                            'UTF-8'
                                        ) ?>
                                    </td>

                                    <td>
                                        <strong>
                                            <?= htmlspecialchars(
                                                $log['action'],
                                                ENT_QUOTES,
                                                'UTF-8'
                                            ) ?>
                                        </strong>
                                    </td>

                                    <td>
                                        <?= nl2br(
                                            htmlspecialchars(
                                                $log['description'] ?: '-',
                                                ENT_QUOTES,
                                                'UTF-8'
                                            )
                                        ) ?>
                                    </td>

                                    <td>
                                        <?= htmlspecialchars(
                                            $log['ip_address'] ?: '-',
                                            ENT_QUOTES,
                                            'UTF-8'
                                        ) ?>
                                    </td>
                                </tr>

                            <?php endforeach; ?>

                        </tbody>

                    </table>

                </div>

            <?php endif; ?>

        </div>

        <?php if ($totalRecords > 0): ?>

            <div
                class="card-footer d-flex flex-column flex-md-row
                       justify-content-between align-items-md-center gap-3"
            >

                <div class="text-muted">
                    Showing
                    <?= number_format($firstRecord) ?>
                    to
                    <?= number_format($lastRecord) ?>
                    of
                    <?= number_format($totalRecords) ?>
                    records
                </div>

                <?php if ($totalPages > 1): ?>

                    <nav aria-label="Activity log pagination">
                        <ul class="pagination mb-0">

                            <li
                                class="page-item
                                <?= $page <= 1 ? 'disabled' : '' ?>"
                            >
                                <a
                                    class="page-link"
                                    href="<?= $page > 1
                                        ? htmlspecialchars(
                                            logPageUrl($page - 1),
                                            ENT_QUOTES,
                                            'UTF-8'
                                        )
                                        : '#' ?>"
                                >
                                    Previous
                                </a>
                            </li>

                            <?php
                            $startPage = max(1, $page - 2);
                            $endPage = min($totalPages, $page + 2);
                            ?>

                            <?php for (
                                $pageNumber = $startPage;
                                $pageNumber <= $endPage;
                                $pageNumber++
                            ): ?>

                                <li
                                    class="page-item
                                    <?= $pageNumber === $page
                                        ? 'active'
                                        : '' ?>"
                                >
                                    <a
                                        class="page-link"
                                        href="<?= htmlspecialchars(
                                            logPageUrl($pageNumber),
                                            ENT_QUOTES,
                                            'UTF-8'
                                        ) ?>"
                                    >
                                        <?= $pageNumber ?>
                                    </a>
                                </li>

                            <?php endfor; ?>

                            <li
                                class="page-item
                                <?= $page >= $totalPages
                                    ? 'disabled'
                                    : '' ?>"
                            >
                                <a
                                    class="page-link"
                                    href="<?= $page < $totalPages
                                        ? htmlspecialchars(
                                            logPageUrl($page + 1),
                                            ENT_QUOTES,
                                            'UTF-8'
                                        )
                                        : '#' ?>"
                                >
                                    Next
                                </a>
                            </li>

                        </ul>
                    </nav>

                <?php endif; ?>

            </div>

        <?php endif; ?>

    </div>

</main>

<?php include __DIR__ . '/../includes/footer.php'; ?>