<?php
require_once __DIR__ . '/app/bootstrap.php';
$user = require_equipment_manager();
require_once __DIR__ . '/app/xlsx.php';

$filters = normalize_equipment_filters($_GET);
if (!is_system_admin($user)) {
    // Scope iz sesije ima prednost nad manipulacijom query parametra.
    $filters['organization_unit'] = (string)equipment_manager_organization_unit($user);
}
[$whereSql, $params] = equipment_filter_sql($filters, $user);

$sql = 'SELECT e.*, u.name AS user_name, u.email AS user_email, u.department AS user_department, u.location AS user_location
        FROM equipment e
        LEFT JOIN users u ON u.id = e.user_id
        WHERE ' . $whereSql . '
        ORDER BY CASE WHEN u.name IS NULL THEN 1 ELSE 0 END, u.name ASC,
                 FIELD(e.status, "assigned", "repair", "returned", "retired"),
                 FIELD(e.asset_type, "Laptop", "Telefon", "Tablet", "Monitor", "Docking station", "Ostalo"),
                 e.asset_name ASC';
$stmt = db()->prepare($sql);
$stmt->execute($params);
$rows = $stmt->fetchAll();

$generatedAt = new DateTimeImmutable('now', app_timezone());
$filename = 'SOS-pregled-opreme-' . $generatedAt->format('Ymd-Hi') . '.xlsx';

try {
    $xlsxPath = create_equipment_xlsx($rows, $generatedAt);
} catch (Throwable $e) {
    error_log('Equipment XLSX export failed: ' . $e->getMessage());
    http_response_code(500);
    header('Content-Type: text/plain; charset=UTF-8');
    echo 'Excel export trenutno nije moguće generisati. Proverite PHP ZIP/Phar podršku i pokušajte ponovo.';
    exit;
}

header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
header('Content-Disposition: attachment; filename="' . $filename . '"');
header('Content-Length: ' . filesize($xlsxPath));
header('Cache-Control: private, no-store, no-cache, must-revalidate');
header('Pragma: no-cache');
header('Expires: 0');

$handle = fopen($xlsxPath, 'rb');
if ($handle !== false) {
    fpassthru($handle);
    fclose($handle);
}
@unlink($xlsxPath);
exit;
