<?php
require_once __DIR__ . '/../../functions/security.php';
require_once __DIR__ . '/../log/log_functions.php';

if (function_exists('enrep_require_admin')) {
    enrep_require_admin();
}

$filters = enrep_log_request_filters();

$page = max(1, (int)($_GET['log_page'] ?? 1));
$limit = 100;
$offset = ($page - 1) * $limit;
$total = enrep_log_count($filters);
$rows = enrep_log_fetch($filters, $limit, $offset);
$categories = enrep_log_distinct('category');
$actions = enrep_log_distinct('action');
$people = enrep_log_distinct('actor_name');
$tenantParam = defined('TENANT_URL') ? TENANT_URL : (string)($_REQUEST['tenant'] ?? '');
$exportParams = $filters;
$exportParams['tenant'] = $tenantParam;
$csvUrl = 'includes/log/log_export.php?' . http_build_query(array_merge($exportParams, ['log_export' => 'csv']));
$pdfUrl = 'includes/log/log_export.php?' . http_build_query(array_merge($exportParams, ['log_export' => 'pdf']));
$queryParams = [];
foreach (['t', 'p'] as $keepKey) {
    if (isset($_GET[$keepKey])) {
        $queryParams[$keepKey] = $_GET[$keepKey];
    }
}
foreach ($filters as $key => $value) {
    if ($value !== '' && $value !== null) {
        $queryParams[$key] = $value;
    }
}
$query = '?' . http_build_query($queryParams);
$join = $query === '?' ? '?' : $query . '&';
?>

<script>
document.getElementById('navBox').innerHTML =
    '<li class="breadcrumb-item">Tools <i class="fad fa-angle-double-right mx-2 mt-1" aria-hidden="true"></i></li><li class="breadcrumb-item active">Log Management</li>';
</script>

<div class="container-fluid">
    <div class="d-flex justify-content-between align-items-center mb-3">
        <div>
            <h2 class="mb-0">Log Management</h2>
            <small class="text-muted">Showing <span id="logVisibleCount"><?= count($rows) ?></span> of <span id="logTotalCount"><?= (int)$total ?></span> entries</small>
        </div>
        <div class="btn-group noprint no-print">
            <a class="btn btn-secondary" href="<?= enrep_log_h($csvUrl) ?>" download><i
                    class="fad fa-file-csv me-1"></i>CSV</a>
            <a class="btn btn-secondary" href="<?= enrep_log_h($pdfUrl) ?>"><i class="fad fa-file-pdf me-1"></i>PDF</a>
            <button type="button" class="btn btn-secondary" onclick="printLogView()"><i
                    class="fad fa-print me-1"></i>Print</button>
        </div>
    </div>

    <form method="get" id="logFilterForm" class="row g-2 align-items-end mb-3 noprint no-print">
        <?php foreach (['t', 'p'] as $keepKey) {
            if (isset($_GET[$keepKey])) { ?>
        <input type="hidden" name="<?= enrep_log_h($keepKey) ?>" value="<?= enrep_log_h($_GET[$keepKey]) ?>">
        <?php }
        } ?>
        <div class="col-md-2">
            <label class="form-label">Category</label>
            <select name="category" class="form-control log-quick-filter" data-mdb-select-init data-mdb-filter="true">
                <option value="">All categories</option>
                <?php foreach ($categories as $category) { ?>
                <option value="<?= enrep_log_h($category) ?>"
                    <?= $filters['category'] === $category ? 'selected' : '' ?>><?= enrep_log_h(enrep_log_display_category($category)) ?></option>
                <?php } ?>
            </select>
        </div>
        <div class="col-md-2">
            <label class="form-label">Action</label>
            <select name="action" class="form-control log-quick-filter" data-mdb-select-init data-mdb-filter="true">
                <option value="">All actions</option>
                <?php foreach ($actions as $action) { ?>
                <option value="<?= enrep_log_h($action) ?>" <?= $filters['action'] === $action ? 'selected' : '' ?>>
                    <?= enrep_log_h($action) ?></option>
                <?php } ?>
            </select>
        </div>
        <div class="col-md-2">
            <label class="form-label">User</label>
            <select name="actor" class="form-control log-quick-filter" data-mdb-select-init data-mdb-filter="true">
                <option value="">All users</option>
                <?php foreach ($people as $person) { ?>
                <option value="<?= enrep_log_h($person) ?>" <?= $filters['actor'] === $person ? 'selected' : '' ?>>
                    <?= enrep_log_h($person) ?></option>
                <?php } ?>
            </select>
        </div>
        <div class="col-md-6">
            <div class="bg-light border rounded p-2">
                <div class="row g-2 align-items-end">
                    <div class="col-md-4 date-picker" data-date-type="open" data-mdb-toggle-button="false">
                        <label class="form-label" for="log_date_from">From</label>
                        <input class="form-control" data-mdb-confirm-date-on-select="true" data-mdb-toggle="datepicker" type="text"
                            name="date_from" id="log_date_from"
                            value="<?= enrep_log_h(enrep_log_display_date($filters['date_from'])) ?>" />
                    </div>
                    <div class="col-md-4 date-picker" data-date-type="open" data-mdb-toggle-button="false">
                        <label class="form-label" for="log_date_to">To</label>
                        <input class="form-control" data-mdb-confirm-date-on-select="true" data-mdb-toggle="datepicker" type="text"
                            name="date_to" id="log_date_to"
                            value="<?= enrep_log_h(enrep_log_display_date($filters['date_to'])) ?>" />
                    </div>
                    <div class="col-md-4">
                        <label class="form-label">Search</label>
                        <div class="input-group">
                            <input name="search" value="<?= enrep_log_h($filters['search']) ?>" class="form-control">
                            <button class="btn btn-primary" type="submit"><i class="fad fa-search"></i></button>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </form>

    <?php if ($filters['category'] !== '' && enrep_log_is_super_admin()) { ?>
    <div class="mb-3 noprint no-print">
        <button class="btn btn-danger btn-sm" type="button" onclick='confirmClearLogCategory(<?= json_encode($filters['category']) ?>)'><i class="fad fa-trash-alt me-1"></i>Delete all
            <?= enrep_log_h(enrep_log_display_category($filters['category'])) ?> log entries</button>
    </div>
    <?php } ?>

    <div id="logPrintArea">
        <?= enrep_log_render_table($rows, true) ?>
    </div>

    <?php if ($total > $limit) {
        $pages = (int)ceil($total / $limit); ?>
    <nav class="noprint no-print">
        <ul class="pagination pagination-sm">
            <?php for ($i = 1; $i <= $pages; $i++) { ?>
            <li class="page-item <?= $i === $page ? 'active' : '' ?>">
                <a class="page-link" href="<?= enrep_log_h($join) ?>log_page=<?= $i ?>"><?= $i ?></a>
            </li>
            <?php } ?>
        </ul>
    </nav>
    <?php } ?>
</div>

<script>
function printLogView() {
    printContainer('logPrintArea', {
        orientation: "landscape",
        header: '<p>Log Management</p>',
        footer: '<p>Generated by EnRep Reporting System: <?= date('d-m-Y') ?></p>',
        logoUrl: 'images/company/logo.jpg',
        styles: [ROOT_URL + '/src/css/print.css'],
    });
}

document.querySelectorAll('#logFilterForm .log-quick-filter').forEach(function(select) {
    select.addEventListener('change', function() {
        document.getElementById('logFilterForm').submit();
    });
});

function openLogAttachments(logId) {
    const url = ROOT_URL + '/includes/log/log_attachments.php?id=' + encodeURIComponent(logId) + '&tenant=' + encodeURIComponent(TENANT_URL);
    loadModalContent(url, 'logAttachmentsBox', 'modal-xl', 1060, 'true', 'Log Attachments', 'close');
}

function logAdminRequest(payload) {
    payload.tenant = TENANT_URL;
    return fetch(ROOT_URL + '/includes/log/log_admin.php', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded'
        },
        body: new URLSearchParams(payload)
    }).then(response => response.json());
}

function updateLogCounts(delta) {
    ['logVisibleCount', 'logTotalCount'].forEach(function(id) {
        const el = document.getElementById(id);
        if (!el) return;
        const next = Math.max(0, parseInt(el.textContent || '0', 10) + delta);
        el.textContent = next;
    });
}

function confirmDeleteLogEntry(logId) {
    loadModalContent(
        '<p class="text-center mb-0">Delete this log entry?</p>',
        'deleteLogBox',
        'modal-sm',
        1060,
        'true',
        'Delete Log Entry',
        'cancelConfirm',
        function() {
            deleteLogEntry(logId);
        }
    );
}

function deleteLogEntry(logId) {
    logAdminRequest({
        action: 'delete',
        id: logId
    }).then(function(data) {
        if (!data || data.ok !== true) {
            showResponse('danger', data && data.error ? data.error : 'Unable to delete log entry');
            return;
        }
        killModal('deleteLogBox');
        const row = document.getElementById('logRow' + logId);
        if (row) {
            row.remove();
            updateLogCounts(-1);
        }
        showResponse('success', 'Log entry deleted');
    }).catch(function() {
        showResponse('danger', 'Unable to delete log entry');
    });
}

function confirmClearLogCategory(category) {
    const categoryLabel = category.replace(/_/g, ' ').replace(/^./, function(char) {
        return char.toUpperCase();
    });
    loadModalContent(
        '<p class="text-center mb-0">Permanently delete all log entries in the <strong>' + categoryLabel + '</strong> category?</p><p class="text-center text-danger small mb-0">This removes the records from the log table and cannot be undone.</p>',
        'clearLogCategoryBox',
        'modal-sm',
        1060,
        'true',
        'Delete Log Category Entries',
        'cancelConfirm',
        function() {
            clearLogCategory(category);
        }
    );
}

function clearLogCategory(category) {
    logAdminRequest({
        action: 'clear_category',
        category: category
    }).then(function(data) {
        if (!data || data.ok !== true) {
            showResponse('danger', data && data.error ? data.error : 'Unable to clear log category');
            return;
        }
        killModal('clearLogCategoryBox');
        document.querySelectorAll('#logPrintArea tbody tr').forEach(function(row) {
            row.remove();
        });
        document.getElementById('logVisibleCount').textContent = '0';
        document.getElementById('logTotalCount').textContent = '0';
        showResponse('success', 'Log category entries deleted');
    }).catch(function() {
        showResponse('danger', 'Unable to clear log category');
    });
}
</script>
