<?php
session_start();
if (!isset($_SESSION['role_id']) || !in_array($_SESSION['role_id'], [1, 2])) {
    header("Location: ../../index.php");
    exit();
}
include('../../includes/config.php');
include('../../includes/header.php');
include('../../includes/footer.php');

$user_id = $_SESSION['user_id'];
$role_id = $_SESSION['role_id'];
$store_id = $_SESSION['store_id'] ?? 0;

$module = 'audit_logs';
$device_info = $_SERVER['HTTP_USER_AGENT'] ?? 'unknown';

$details = json_encode([
    'page' => $module,
    'timestamp' => date('Y-m-d H:i:s'),
    'device_info' => $device_info
]);

$log_stmt = $conn->prepare("INSERT INTO audit_log (user_id, role_id, action, module, details, device_info, created_at) VALUES (?, ?, 'view_audit_logs', ?, ?, ?, NOW())");
$log_stmt->bind_param("iisss", $user_id, $role_id, $module, $details, $device_info);
$log_stmt->execute();
$log_stmt->close();

// Load users list for filter dropdown
if ($role_id == 1) {
    $users_list = $conn->query("SELECT id, username FROM users ORDER BY username");
} else {
    $users_list = $conn->prepare("SELECT id, username FROM users WHERE store_id = ? ORDER BY username");
    $users_list->bind_param("i", $store_id);
    $users_list->execute();
    $users_list = $users_list->get_result();
}

// Prepare maps
$product_map = [];
$store_map = [];
$products = $conn->query("SELECT id, product_name FROM products");
while ($p = $products->fetch_assoc()) $product_map[$p['id']] = $p['product_name'];

$stores = $conn->query("SELECT id, store_name FROM stores");
while ($s = $stores->fetch_assoc()) $store_map[$s['id']] = $s['store_name'];

// Filters
$filter_user = $_GET['user_id'] ?? '';
$filter_from = $_GET['from_date'] ?? '';
$filter_to = $_GET['to_date'] ?? '';
$conditions = [];
$params = [];
$types = '';

if ($filter_user !== '') {
    $conditions[] = 'a.user_id = ?';
    $params[] = $filter_user;
    $types .= 'i';
} elseif ($role_id == 2) {
    $conditions[] = 'u.store_id = ?';
    $params[] = $store_id;
    $types .= 'i';
}

if ($filter_from !== '') {
    $conditions[] = 'a.created_at >= ?';
    $params[] = $filter_from . ' 00:00:00';
    $types .= 's';
}
if ($filter_to !== '') {
    $conditions[] = 'a.created_at <= ?';
    $params[] = $filter_to . ' 23:59:59';
    $types .= 's';
}

$where = $conditions ? 'WHERE ' . implode(' AND ', $conditions) : '';

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

// Count total
$count_sql = "SELECT COUNT(*) AS total FROM audit_log a LEFT JOIN users u ON a.user_id = u.id $where";
$count_stmt = $conn->prepare($count_sql);
if ($params) $count_stmt->bind_param($types, ...$params);
$count_stmt->execute();
$total = $count_stmt->get_result()->fetch_assoc()['total'];
$count_stmt->close();
$total_pages = ceil($total / $limit);

// Fetch logs
$sql = "SELECT a.*, u.username FROM audit_log a LEFT JOIN users u ON a.user_id = u.id $where ORDER BY a.created_at DESC LIMIT ? OFFSET ?";
$params[] = $limit;
$params[] = $offset;
$types .= "ii";

$stmt = $conn->prepare($sql);
$stmt->bind_param($types, ...$params);
$stmt->execute();
$logs = $stmt->get_result();
$stmt->close();

// Format function
function formatDetails($json, $products, $stores) {
    $d = json_decode($json, true);
    if (!$d) return '<em>Invalid JSON</em>';
    $formatValue = function($val) use (&$formatValue, $products, $stores) {
        if (is_array($val)) {
            $out = '<ul>';
            foreach ($val as $k => $v) {
                $label = ucwords(str_replace('_', ' ', $k));
                if ($k === 'product_id') $v = $products[$v] ?? "Product #$v";
                if (in_array($k, ['store_id','from_store_id','to_store_id']))
                    $v = $stores[$v] ?? "Store #$v";
                $out .= "<li><strong>$label:</strong> " . $formatValue($v) . "</li>";
            }
            $out .= '</ul>';
            return $out;
        }
        return htmlspecialchars((string)$val);
    };
    return $formatValue($d);
}

function buildQuery($extras = []) {
    $q = $_GET;
    foreach ($extras as $k => $v) $q[$k] = $v;
    return http_build_query($q);
}
?>

<!DOCTYPE html>
<html>
<head>
    <title>Audit Logs</title>
    <link rel="stylesheet" href="../../css/dashboard.css">
    <style>
        body {
            background: url('../../images/profile.jpg') no-repeat center center fixed;
            background-size: cover;
            color: white;
            font-family: 'Segoe UI', sans-serif;
        }
        .container {
            max-width: 1050px;
            margin: 110px auto 40px;
            padding: 25px 30px;
            background: rgba(255,255,255,0.08);
            border-radius: 15px;
            backdrop-filter: blur(12px);
        }
        h2 { margin-bottom: 15px; }
        .filter-row {
            display: flex; justify-content: space-between; flex-wrap: wrap; gap: 10px; align-items: center; margin-bottom: 15px;
        }
        .filter-group select, .filter-group input[type="date"] {
            padding: 6px 10px;
            border: none;
            border-radius: 5px;
            background: rgba(255,255,255,0.2);
            color: white;
        }
        .filter-group button {
            padding: 6px 12px;
            border: none;
            border-radius: 5px;
            font-weight: 600;
            cursor: pointer;
        }
        .filter-btn { background: #ff6f00; color: white; }
        .clear-btn { background: gray; color: white; }
        .export-btn { background: #4caf50; color: white; }
        table {
            width: 100%;
            border-collapse: collapse;
            font-size: 14px;
            background: rgba(255,255,255,0.05);
        }
        th, td {
            padding: 10px;
            border-bottom: 1px solid rgba(255,255,255,0.1);
            vertical-align: top;
        }
        th { background: rgba(255,111,0,0.9); }
        ul { margin: 0; padding-left: 20px; }
        .pagination {
            margin-top: 10px;
            text-align: center;
        }
        .pagination a {
            margin: 2px;
            padding: 6px 10px;
            background: rgba(255,255,255,0.1);
            color: white;
            text-decoration: none;
            border-radius: 5px;
        }
        .pagination a.active { background: #ff6f00; font-weight: bold; }
        .back-link {
            display: inline-block;
            margin-bottom: 20px;
            padding: 10px 20px;
            background: rgba(255, 111, 0, 0);
            color: white;
            font-weight: 600;
            border-radius: 8px;
            text-decoration: none;
        }
        .back-link:hover {
            background: #e65c00;
        }
    </style>
</head>
<body>
<div class="container">
    <a href="reports.php" class="back-link">&larr; Back to Reports</a>
    <h2>Audit Logs</h2>

    <form method="GET" class="filter-row">
        <div class="filter-group">
            <select name="user_id">
                <option value="">All Users</option>
                <?php while ($u = $users_list->fetch_assoc()): ?>
                    <option value="<?= $u['id'] ?>" <?= $filter_user == $u['id'] ? 'selected' : '' ?>>
                        <?= htmlspecialchars($u['username']) ?>
                    </option>
                <?php endwhile; ?>
            </select>
            <input type="date" name="from_date" value="<?= htmlspecialchars($filter_from) ?>">
            <input type="date" name="to_date" value="<?= htmlspecialchars($filter_to) ?>">
            <button type="submit" class="filter-btn">Apply</button>
            <button type="button" onclick="window.location='audit_logs.php'" class="clear-btn">Clear</button>
        </div>
        <div class="filter-group">
            <button type="button" class="export-btn" onclick="window.open('audit_logs_export.php?<?= buildQuery(['format'=>'csv']) ?>','_blank')">Export CSV</button>
            <button type="button" class="export-btn" onclick="window.open('audit_logs_export.php?<?= buildQuery(['format'=>'pdf']) ?>','_blank')">Export PDF</button>
        </div>
    </form>

    <table>
        <thead>
            <tr><th>User</th><th>Action</th><th>Details</th><th>Timestamp</th></tr>
        </thead>
        <tbody>
            <?php while ($log = $logs->fetch_assoc()): ?>
            <tr>
                <td><?= htmlspecialchars($log['username'] ?? 'System') ?></td>
                <td><?= htmlspecialchars(ucwords(str_replace('_', ' ', $log['action']))) ?></td>
                <td><?= formatDetails($log['details'], $product_map, $store_map) ?></td>
                <td><?= date("d M Y H:i", strtotime($log['created_at'])) ?></td>
            </tr>
            <?php endwhile; ?>
        </tbody>
    </table>

    <div class="pagination">
        <?php for ($i = 1; $i <= $total_pages; $i++): ?>
            <a href="?<?= buildQuery(['page' => $i]) ?>" class="<?= $i == $page ? 'active' : '' ?>"><?= $i ?></a>
        <?php endfor; ?>
    </div>
</div>
</body>
</html>
