<?php
session_start();
if (!isset($_SESSION['role_id']) || $_SESSION['role_id'] != 1) {
    header("Location: ../../index.php");
    exit();
}

include('../../includes/config.php');

// Determine export format
$format = $_GET['format'] ?? 'csv';
$format = strtolower($format);
if (!in_array($format, ['csv', 'pdf'])) {
    die("Invalid format.");
}

// 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'; }
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) : '';

// Load mappings
$product_map = [];
$store_map = [];
$users_map = [];

$p = $conn->query("SELECT id, product_name FROM products");
while ($r = $p->fetch_assoc()) $product_map[$r['id']] = $r['product_name'];
$s = $conn->query("SELECT id, store_name FROM stores");
while ($r = $s->fetch_assoc()) $store_map[$r['id']] = $r['store_name'];
$u = $conn->query("SELECT id, username FROM users");
while ($r = $u->fetch_assoc()) $users_map[$r['id']] = $r['username'];

// 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";
$stmt = $conn->prepare($sql);
if ($params) $stmt->bind_param($types, ...$params);
$stmt->execute();
$logs = $stmt->get_result();

function parseDetails($json, $products, $stores) {
    $d = json_decode($json, true);
    if (!$d) return "Invalid JSON";
    $pairs = [];
    foreach ($d as $k => $v) {
        if ($k === 'product_id') $v = $products[$v] ?? "Product #$v";
        elseif (in_array($k, ['store_id', 'from_store_id', 'to_store_id'])) {
            $v = $stores[$v] ?? "Store #$v";
            $k = str_replace(['_id'], '', str_replace('_store_id', 'store', $k));
        }
        $pairs[] = ucfirst(str_replace('_', ' ', $k)) . ": " . $v;
    }
    return implode("; ", $pairs);
}

if ($format === 'csv') {
    header('Content-Type: text/csv');
    header('Content-Disposition: attachment; filename="audit_logs.csv"');

    $out = fopen('php://output', 'w');
    fputcsv($out, ['User', 'Action', 'Details', 'Timestamp']);
    while ($log = $logs->fetch_assoc()) {
        fputcsv($out, [
            $log['username'] ?? 'System',
            ucwords(str_replace('_', ' ', $log['action'])),
            parseDetails($log['details'], $product_map, $store_map),
            date("d M Y H:i", strtotime($log['created_at']))
        ]);
    }
    fclose($out);
    exit();
}

// Simplified HTML Export
if ($format === 'pdf') {
    ?>
    <!DOCTYPE html>
    <html>
    <head>
        <title>Audit Logs - PDF View</title>
        <style>
            body { font-family: Arial, sans-serif; font-size: 12px; padding: 20px; }
            table { border-collapse: collapse; width: 100%; margin-top: 20px; }
            th, td { border: 1px solid #999; padding: 8px; }
            th { background: #ff6f00; color: white; }
            h2 { text-align: center; }
            @media print {
                button { display: none; }
            }
        </style>
    </head>
    <body>
        <h2>Audit Logs</h2>
        <button onclick="window.print()">Print or Save as PDF</button>
        <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><?= htmlspecialchars(parseDetails($log['details'], $product_map, $store_map)) ?></td>
                    <td><?= date("d M Y H:i", strtotime($log['created_at'])) ?></td>
                </tr>
            <?php endwhile; ?>
            </tbody>
        </table>
    </body>
    </html>
    <?php
    exit();
}
?>
