<?php
//declare(strict_types=1);

require_once __DIR__ . '/../system/bootstrap.php';
require_once __DIR__ . '/../system/auth.php';

$user = require_auth($pdo);

if (!in_array($user['role'], ['admin', 'super_admin'], true)) {
    http_response_code(403);
    exit('Forbidden');
}

if (!class_exists('ZipArchive')) {
    http_response_code(500);
    exit('ZipArchive not available on this server');
}

/* ==========================================================
   FILTERS (MATCH list.php EXACTLY)
   ========================================================== */

$where  = [];
$params = [];

if ($user['role'] !== 'super_admin') {
    $where[] = 'a.company_id = :company_id';
    $params['company_id'] = $user['company_id'];
}

$search   = trim($_GET['search'] ?? '');
$action   = trim($_GET['action'] ?? '');
$browser  = trim($_GET['browser'] ?? '');
$os       = trim($_GET['operating_system'] ?? '');
$dateFrom = trim($_GET['date_from'] ?? '');
$dateTo   = trim($_GET['date_to'] ?? '');

if ($action !== '') {
    $where[] = 'a.action = :action';
    $params['action'] = $action;
}

if ($browser !== '') {
    $where[] = 'a.browser = :browser';
    $params['browser'] = $browser;
}

if ($os !== '') {
    $where[] = 'a.operating_system = :os';
    $params['os'] = $os;
}

if ($search !== '') {
    $where[] = '(u1.email LIKE :q OR u2.email LIKE :q OR a.action LIKE :q)';
    $params['q'] = '%' . $search . '%';
}

if ($dateFrom !== '') {
    $where[] = 'DATE(a.created_at) >= :date_from';
    $params['date_from'] = $dateFrom;
}

if ($dateTo !== '') {
    $where[] = 'DATE(a.created_at) <= :date_to';
    $params['date_to'] = $dateTo;
}

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

/* ==========================================================
   QUERY
   ========================================================== */

$stmt = $pdo->prepare("
    SELECT
        a.created_at,
        a.action,
        u1.email AS actor_email,
        u2.email AS target_email,
        a.ip_address,
        a.browser,
        a.operating_system
    FROM audit_logs a
    LEFT JOIN users u1 ON u1.id = a.actor_user_id
    LEFT JOIN users u2 ON u2.id = a.target_user_id
    $whereSql
    ORDER BY a.created_at DESC
");

foreach ($params as $k => $v) {
    $stmt->bindValue(':' . $k, $v);
}

$stmt->execute();
$rows = $stmt->fetchAll();

/* ==========================================================
   XLSX GENERATION (NO LIBRARIES)
   ========================================================== */

$filename = 'audit_logs_' . date('Y-m-d_H-i-s') . '.xlsx';
$tmpDir = sys_get_temp_dir() . '/xlsx_' . uniqid();
mkdir($tmpDir, 0777, true);
mkdir("$tmpDir/xl/worksheets", 0777, true);
mkdir("$tmpDir/xl/_rels", 0777, true);
mkdir("$tmpDir/_rels", 0777, true);

/* ---- sheet data ---- */
$sheetData = '';
$headers = ['Date','Action','Actor','Target','IP Address','Browser','Operating System'];

$rowNum = 1;
$sheetData .= '<row r="1">';
foreach ($headers as $i => $h) {
    $col = chr(65 + $i);
    $sheetData .= "<c r=\"$col$rowNum\" t=\"inlineStr\"><is><t>$h</t></is></c>";
}
$sheetData .= '</row>';

foreach ($rows as $row) {
    $rowNum++;
    $sheetData .= "<row r=\"$rowNum\">";
    $values = array_values($row);
    foreach ($values as $i => $v) {
        $col = chr(65 + $i);
        $v = htmlspecialchars((string)$v);
        $sheetData .= "<c r=\"$col$rowNum\" t=\"inlineStr\"><is><t>$v</t></is></c>";
    }
    $sheetData .= '</row>';
}

file_put_contents("$tmpDir/xl/worksheets/sheet1.xml", <<<XML
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<worksheet xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main">
  <sheetData>$sheetData</sheetData>
</worksheet>
XML);

/* ---- static files ---- */
file_put_contents("$tmpDir/[Content_Types].xml", <<<XML
<Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types">
  <Override PartName="/xl/worksheets/sheet1.xml" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.worksheet+xml"/>
  <Override PartName="/xl/workbook.xml" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml"/>
</Types>
XML);

file_put_contents("$tmpDir/_rels/.rels", <<<XML
<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">
  <Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument" Target="xl/workbook.xml"/>
</Relationships>
XML);

file_put_contents("$tmpDir/xl/workbook.xml", <<<XML
<workbook xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main">
  <sheets>
    <sheet name="Audit Logs" sheetId="1" r:id="rId1"/>
  </sheets>
</workbook>
XML);

file_put_contents("$tmpDir/xl/_rels/workbook.xml.rels", <<<XML
<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">
  <Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/worksheet" Target="worksheets/sheet1.xml"/>
</Relationships>
XML);

/* ---- zip ---- */
if (!class_exists('ZipArchive')) {
    http_response_code(500);
    exit('ZipArchive not available on this server');
}

$zip = new ZipArchive();
$zipPath = "$tmpDir/export.xlsx";

$result = $zip->open($zipPath, ZipArchive::CREATE | ZipArchive::OVERWRITE);
if ($result !== true) {
    http_response_code(500);
    exit('Failed to create Excel file (ZIP error)');
}

$files = new RecursiveIteratorIterator(
    new RecursiveDirectoryIterator($tmpDir, FilesystemIterator::SKIP_DOTS)
);

foreach ($files as $file) {
    if ($file->isFile() && basename($file) !== 'export.xlsx') {
        $zip->addFile(
            $file->getRealPath(),
            substr($file->getRealPath(), strlen($tmpDir) + 1)
        );
    }
}

$zip->close();


/* ---- output ---- */
header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
header('Content-Disposition: attachment; filename="' . $filename . '"');
readfile($zipPath);

/* ---- cleanup ---- */
array_map('unlink', glob("$tmpDir/xl/worksheets/*"));
@unlink("$tmpDir/xl/workbook.xml");
@unlink("$tmpDir/xl/_rels/workbook.xml.rels");
@unlink("$tmpDir/_rels/.rels");
@unlink("$tmpDir/[Content_Types].xml");
@unlink($zipPath);
@rmdir("$tmpDir/xl/worksheets");
@rmdir("$tmpDir/xl/_rels");
@rmdir("$tmpDir/xl");
@rmdir("$tmpDir/_rels");
@rmdir($tmpDir);
exit;
