<?php

require_once '../../classes/Database.php';
require_once '../../classes/Logger.php';
require_once '../../classes/User.php';
require_once '../../includes/auth.php';

session_start();


$database = new Database();
$conn = $database->getConnection();


if (!$conn) {
    die("Database connection failed. Please check your database configuration.");
}


$auth = new Auth($conn);


$auth->requireLogin();


if (!$auth->isSuperAdmin($_SESSION['user_id']) && $_SESSION['role'] !== 'branch' && $_SESSION['role'] !== 'warehouse') {
    header('Location: ../../unauthorized.php');
    exit();
}


$logger = new Logger($conn, $_SESSION['user_id'], $_SESSION['username'], $_SESSION['role']);


$userBranchId = null;
if ($_SESSION['role'] === 'branch' || $_SESSION['role'] === 'warehouse') {
    $user = new User($conn);
    $userBranchId = $user->getUserBranch($_SESSION['user_id']);
    if ($_SESSION['role'] === 'warehouse') {
        $userBranchId = 7;
    }
}


try {
    $tableCheck = $conn->query("SHOW TABLES LIKE 'system_logs'");
    if ($tableCheck->rowCount() == 0) {
        die("System logs table does not exist. Please run the setup script first: php setup_logs.php");
    }
} catch (Exception $e) {
    die("Error checking system_logs table: " . $e->getMessage());
}


$filter_user = $_POST['filter_user'] ?? '';
$filter_action = $_POST['filter_action'] ?? '';
$filter_module = $_POST['filter_module'] ?? '';
$filter_date_from = $_POST['filter_date_from'] ?? '';
$filter_date_to = $_POST['filter_date_to'] ?? '';
$limit = $_POST['limit'] ?? 100;


$query = "SELECT * FROM system_logs WHERE 1=1";
$params = [];

if (!empty($filter_user)) {
    $query .= " AND username LIKE :username";
    $params[':username'] = '%' . $filter_user . '%';
}

if (!empty($filter_action)) {
    $query .= " AND action LIKE :action";
    $params[':action'] = '%' . $filter_action . '%';
}

if (!empty($filter_module)) {
    $query .= " AND module = :module";
    $params[':module'] = $filter_module;
}

if (!empty($filter_date_from)) {
    $query .= " AND DATE(timestamp) >= :date_from";
    $params[':date_from'] = $filter_date_from;
}

if (!empty($filter_date_to)) {
    $query .= " AND DATE(timestamp) <= :date_to";
    $params[':date_to'] = $filter_date_to;
}

$query .= " ORDER BY timestamp DESC LIMIT " . (int)$limit;


if (($_SESSION['role'] === 'branch' || $_SESSION['role'] === 'warehouse') && $userBranchId) {

    $query = "SELECT * FROM ($query) AS filtered_logs WHERE user_id = :current_user_id
              OR (affected_table = 'items'
                  AND affected_record_id IN (
                      SELECT item_id FROM items WHERE current_location_id = :user_branch_id
                  )
                  AND (action LIKE '%UPDATE%' OR action LIKE '%DELETE%')
                  AND user_id != :current_user_id)";
    $params[':current_user_id'] = $_SESSION['user_id'];
    $params[':user_branch_id'] = $userBranchId;
}


try {
    $stmt = $conn->prepare($query);
    $stmt->execute($params);
    $logs = $stmt->fetchAll(PDO::FETCH_ASSOC);
} catch (Exception $e) {
    die("Error retrieving logs: " . $e->getMessage());
}


try {

    if ($_SESSION['role'] === 'branch') {
        $users_stmt = $conn->query("SELECT DISTINCT sl.user_id, sl.username FROM system_logs sl
                                   INNER JOIN users u ON sl.user_id = u.user_id
                                   WHERE u.role IN ('admin', 'warehouse')
                                   ORDER BY sl.username");
    }

    elseif ($_SESSION['role'] === 'warehouse') {
        $users_stmt = $conn->query("SELECT DISTINCT sl.user_id, sl.username FROM system_logs sl
                                   INNER JOIN users u ON sl.user_id = u.user_id
                                   WHERE u.role = 'admin'
                                   ORDER BY sl.username");
    }

    else {
        $users_stmt = $conn->query("SELECT DISTINCT user_id, username FROM system_logs ORDER BY username");
    }
    $users = $users_stmt->fetchAll(PDO::FETCH_ASSOC);
    $actions_stmt = $conn->query("SELECT DISTINCT action FROM system_logs ORDER BY action");
    $actions = $actions_stmt->fetchAll(PDO::FETCH_ASSOC);
    $modules_stmt = $conn->query("SELECT DISTINCT module FROM system_logs ORDER BY module");
    $modules = $modules_stmt->fetchAll(PDO::FETCH_ASSOC);
} catch (Exception $e) {
    $users = $actions = $modules = [];
    error_log("Error fetching filter data: " . $e->getMessage());
}


$logger->logAdmin('VIEW_LOGS', 'Accessed system logs page');


$totalLogsCount = count($logs);
error_log("System logs page accessed by {$_SESSION['username']} - Retrieved $totalLogsCount logs");


function getLogContext($action) {
    $action = strtoupper($action);
    if (strpos($action, 'CREATE') !== false) return ['icon' => 'fas fa-plus-circle', 'class' => 'success'];
    if (strpos($action, 'UPDATE') !== false) return ['icon' => 'fas fa-edit', 'class' => 'warning'];
    if (strpos($action, 'DELETE') !== false) return ['icon' => 'fas fa-trash-alt', 'class' => 'danger'];
    if (strpos($action, 'LOGIN_SUCCESS') !== false) return ['icon' => 'fas fa-sign-in-alt', 'class' => 'success'];
    if (strpos($action, 'LOGIN_FAIL') !== false) return ['icon' => 'fas fa-exclamation-triangle', 'class' => 'danger'];
    if (strpos($action, 'LOGOUT') !== false) return ['icon' => 'fas fa-sign-out-alt', 'class' => 'info'];
    if (strpos($action, 'VIEW') !== false) return ['icon' => 'fas fa-eye', 'class' => 'primary'];
    if (strpos($action, 'ADMIN') !== false) return ['icon' => 'fas fa-user-shield', 'class' => 'purple'];
    return ['icon' => 'fas fa-info-circle', 'class' => 'secondary'];
}
?>

<?php include '../../includes/header.php'; ?>
    <style>

        body {
            background-color: #f4f7f9;
        }
        .log-container {
            margin-top: 1.5rem;
        }
        .log-item {
            background-color: #fff;
            border: 1px solid #e9ecef;
            border-radius: 0.5rem;
            margin-bottom: 1rem;
            box-shadow: 0 2px 10px rgba(0,0,0,0.05);
            transition: box-shadow 0.2s ease-in-out;
            display: flex;
            padding: 1.25rem;
        }
        .log-item:hover {
            box-shadow: 0 4px 15px rgba(0,0,0,0.1);
        }
        .log-icon {
            font-size: 1.75rem;
            margin-right: 1.25rem;
            padding-top: 0.25rem;
        }
        .log-content {
            flex-grow: 1;
        }
        .log-header {
            display: flex;
            justify-content: space-between;
            align-items: flex-start;
            flex-wrap: wrap;
            gap: 0.5rem;
            margin-bottom: 0.5rem;
        }
        .log-action {
            font-size: 1.1rem;
            font-weight: 600;
            color: #343a40;
        }
        .log-timestamp {
            font-size: 0.8rem;
            color: #6c757d;
            white-space: nowrap;
        }
        .log-details {
            font-size: 0.95rem;
            color: #495057;
            margin-bottom: 1rem;
            word-wrap: break-word;
        }
        .log-meta {
            display: flex;
            flex-wrap: wrap;
            gap: 1.5rem;
            font-size: 0.85rem;
            color: #6c757d;
            border-top: 1px solid #e9ecef;
            padding-top: 0.75rem;
        }
        .log-meta span {
            display: inline-flex;
            align-items: center;
        }
        .log-meta span i {
            margin-right: 0.4rem;
        }
        .log-meta strong {
            color: #495057;
            margin-left: 0.3rem;
        }

        .log-item.success .log-icon { color: #28a745; }
        .log-item.warning .log-icon { color: #ffc107; }
        .log-item.danger .log-icon { color: #dc3545; }
        .log-item.info .log-icon { color: #17a2b8; }
        .log-item.primary .log-icon { color: #007bff; }
        .log-item.secondary .log-icon { color: #6c757d; }
        .log-item.purple .log-icon { color: #6f42c1; }

        .controls-card {
            background-color: #fff;
            box-shadow: 0 2px 10px rgba(0,0,0,0.05);
            border: 1px solid #e9ecef;
        }
    </style>

    <div class="container-fluid mt-4">
        <h2><i class="fas fa-clipboard-list"></i> System Activity Logs</h2>
        <p class="text-muted">A detailed record of all system and user activities.</p>

        <div class="card controls-card mb-4">
            <div class="card-header">
                <h5><i class="fas fa-filter"></i> Filter & Export</h5>
            </div>
            <div class="card-body">
                <form method="POST" id="filterForm">
                    <div class="row g-3 align-items-end">
                        <div class="col-md-2">
                            <label for="filter_user" class="form-label">User</label>
                            <select name="filter_user" id="filter_user" class="form-select">
                                <option value="">All Users</option>
                                <?php foreach ($users as $user): ?>
                                    <option value="<?php echo htmlspecialchars($user['username']); ?>" <?php echo ($filter_user == $user['username'] || $filter_user == $user['user_id']) ? 'selected' : ''; ?>>
                                        <?php echo htmlspecialchars($user['username']); ?>
                                    </option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                        <div class="col-md-2">
                            <label for="filter_action" class="form-label">Action Type</label>
                            <select name="filter_action" id="filter_action" class="form-select">
                                <option value="">All Actions</option>
                                <optgroup label="Authentication">
                                    <option value="LOGIN" <?php echo ($filter_action == 'LOGIN') ? 'selected' : ''; ?>>Login</option>
                                    <option value="LOGOUT" <?php echo ($filter_action == 'LOGOUT') ? 'selected' : ''; ?>>Logout</option>
                                </optgroup>
                                <optgroup label="Database Operations">
                                    <option value="CREATE" <?php echo ($filter_action == 'CREATE') ? 'selected' : ''; ?>>Create Records</option>
                                    <option value="UPDATE" <?php echo ($filter_action == 'UPDATE') ? 'selected' : ''; ?>>Update Records</option>
                                    <option value="DELETE" <?php echo ($filter_action == 'DELETE') ? 'selected' : ''; ?>>Delete Records</option>
                                </optgroup>
                                <optgroup label="Business Operations">
                                    <option value="SALE" <?php echo ($filter_action == 'SALE') ? 'selected' : ''; ?>>Sales</option>
                                    <option value="SHIPMENT" <?php echo ($filter_action == 'SHIPMENT') ? 'selected' : ''; ?>>Shipments</option>
                                    <option value="EXPENSE" <?php echo ($filter_action == 'EXPENSE') ? 'selected' : ''; ?>>Expenses</option>
                                    <option value="QUOTATION" <?php echo ($filter_action == 'QUOTATION') ? 'selected' : ''; ?>>Quotations</option>
                                </optgroup>
                                <optgroup label="Administrative">
                                    <option value="APPROVE" <?php echo ($filter_action == 'APPROVE') ? 'selected' : ''; ?>>Approvals</option>
                                    <option value="VERIFY" <?php echo ($filter_action == 'VERIFY') ? 'selected' : ''; ?>>Verifications</option>
                                    <option value="VIEW" <?php echo ($filter_action == 'VIEW') ? 'selected' : ''; ?>>Views</option>
                                    <option value="ADMIN" <?php echo ($filter_action == 'ADMIN') ? 'selected' : ''; ?>>Admin Actions</option>
                                </optgroup>
                            </select>
                        </div>
                        <div class="col-md-2">
                            <label for="filter_module" class="form-label">Module</label>
                            <select name="filter_module" id="filter_module" class="form-select">
                                <option value="">All Modules</option>
                                <?php foreach ($modules as $module): ?>
                                    <option value="<?php echo htmlspecialchars($module['module']); ?>" <?php echo ($filter_module == $module['module']) ? 'selected' : ''; ?>>
                                        <?php echo htmlspecialchars($module['module']); ?>
                                    </option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                        <div class="col-md-2">
                            <label for="filter_date_from" class="form-label">From Date</label>
                            <input type="date" name="filter_date_from" id="filter_date_from" class="form-control" value="<?php echo htmlspecialchars($filter_date_from); ?>">
                        </div>
                        <div class="col-md-2">
                            <label for="filter_date_to" class="form-label">To Date</label>
                            <input type="date" name="filter_date_to" id="filter_date_to" class="form-control" value="<?php echo htmlspecialchars($filter_date_to); ?>">
                        </div>
                        <div class="col-md-2 d-flex">
                            <button type="submit" class="btn btn-primary flex-grow-1">Filter</button>
                        </div>
                    </div>
                </form>

                <form method="POST" action="export_logs_pdf.php" id="exportForm" style="display: none;">
                    <input type="hidden" name="filter_user" value="<?php echo htmlspecialchars($filter_user); ?>">
                    <input type="hidden" name="filter_action" value="<?php echo htmlspecialchars($filter_action); ?>">
                    <input type="hidden" name="filter_module" value="<?php echo htmlspecialchars($filter_module); ?>">
                    <input type="hidden" name="filter_date_from" value="<?php echo htmlspecialchars($filter_date_from); ?>">
                    <input type="hidden" name="filter_date_to" value="<?php echo htmlspecialchars($filter_date_to); ?>">
                    <input type="hidden" name="limit" value="<?php echo htmlspecialchars($limit); ?>">
                    <input type="hidden" name="visible_log_ids" id="visibleLogIds">
                </form>

                <hr>
                <div class="row">
                    <div class="col-md-6">
                        <label for="searchInput" class="form-label">Live Search Current Results</label>
                        <div class="input-group">
                             <span class="input-group-text"><i class="fas fa-search"></i></span>
                            <input type="text" id="searchInput" class="form-control" placeholder="Type to search in the <?php echo $totalLogsCount; ?> logs below...">
                        </div>
                    </div>
                     <div class="col-md-2">
                        <label for="limit" class="form-label">Result Limit</label>
                        <select name="limit" id="limit" class="form-select" form="filterForm">
                            <option value="50" <?php echo ($limit == 50) ? 'selected' : ''; ?>>50</option>
                            <option value="100" <?php echo ($limit == 100) ? 'selected' : ''; ?>>100</option>
                            <option value="500" <?php echo ($limit == 500) ? 'selected' : ''; ?>>500</option>
                            <option value="1000" <?php echo ($limit == 1000) ? 'selected' : ''; ?>>1000</option>
                        </select>
                    </div>
                    <div class="col-md-4 d-flex align-items-end">
                        <button type="button" class="btn btn-success flex-grow-1" id="exportBtn">
                            <i class="fas fa-file-pdf"></i> Export Displayed Results to PDF
                        </button>
                    </div>
                </div>
            </div>
        </div>

        <div class="log-container">
            <?php if (empty($logs)): ?>
                <div class="alert alert-info text-center">
                    <h5><i class="fas fa-info-circle"></i> No Logs Found</h5>
                    <p class="mb-0">Please adjust your filters or wait for new system activity.</p>
                </div>
            <?php else: ?>
                <?php foreach ($logs as $log): ?>
                    <?php $context = getLogContext($log['action']); ?>
                    <div class="log-item <?php echo $context['class']; ?>" data-log-id="<?php echo $log['log_id']; ?>">
                        <div class="log-icon">
                            <i class="<?php echo $context['icon']; ?>"></i>
                        </div>
                        <div class="log-content">
                            <div class="log-header">
                                <span class="log-action"><?php echo htmlspecialchars($log['action']); ?></span>
                                <span class="log-timestamp"><i class="far fa-clock"></i> <?php
                                    $dt = new DateTime($log['timestamp'], new DateTimeZone('UTC'));
                                    $dt->setTimezone(new DateTimeZone('Africa/Blantyre'));
                                    echo $dt->format('F j, Y, g:i a');
                                ?></span>
                            </div>
                            <p class="log-details">
                                <?php echo nl2br(htmlspecialchars($log['details'])); ?>
                            </p>
                            <div class="log-meta">
                                <span><i class="fas fa-user"></i>User:<strong><?php echo htmlspecialchars($log['username']); ?></strong></span>
                                <span><i class="fas fa-shield-alt"></i>Role:<strong><?php echo htmlspecialchars($log['user_role']); ?></strong></span>
                                <span><i class="fas fa-cube"></i>Module:<strong><?php echo htmlspecialchars($log['module']); ?></strong></span>
                                <span><i class="fas fa-network-wired"></i>IP:<strong><?php echo htmlspecialchars($log['ip_address']); ?></strong></span>
                            </div>
                        </div>
                    </div>
                <?php endforeach; ?>
            <?php endif; ?>
        </div>
    </div>

    <script>

    const logsData = <?php echo json_encode($logs); ?>;

    $(document).ready(function() {

        $('#searchInput').on('keyup', function() {
            const searchTerm = $(this).val().toLowerCase();
            $('.log-item').each(function() {
                const logText = $(this).text().toLowerCase();
                $(this).toggle(logText.includes(searchTerm));
            });
        });


        $('#exportBtn').click(function() {

            const visibleLogIds = [];
            $('.log-item:visible').each(function() {
                const logId = $(this).data('log-id');
                if (logId) {
                    visibleLogIds.push(logId);
                }
            });

            if (visibleLogIds.length === 0) {
                alert('No logs to export.');
                return;
            }


            $('#visibleLogIds').val(JSON.stringify(visibleLogIds));


            $('#exportForm').submit();
        });


        $('#filterForm').on('submit', function() {
            $(this).find('button[type="submit"]').prop('disabled', true).html('<i class="fas fa-spinner fa-spin"></i> Filtering...');
        });


        $('#limit').on('change', function() {
            $('#filterForm').submit();
        });
    });
    </script>
<?php include __DIR__ . '/../../includes/footer.php'; ?>