<?php
declare(strict_types=1);
if (!function_exists('mb_substr')) { function mb_substr(string $s, int $start, ?int $length = null): string { return $length === null ? substr($s, $start) : substr($s, $start, $length); } }
require_once __DIR__ . '/app/functions.php';
require_once __DIR__ . '/app/xlsx.php';

$pass = 0; $fail = 0;
function qa24(string $name, bool $condition): void { global $pass, $fail; if ($condition) { echo "PASS $name\n"; $pass++; } else { echo "FAIL $name\n"; $fail++; } }

$f = normalize_equipment_filters(['warehouse' => '1', 'asset_type' => 'Laptop', 'q' => 'HP']);
qa24('Warehouse filter 1 ostaje validan', $f['warehouse'] === '1');
[$where, $params] = equipment_filter_sql($f);
qa24('Warehouse SQL koristi is_in_warehouse = 1', str_contains($where, 'e.is_in_warehouse = 1'));
qa24('Warehouse flag ne dodaje raw query parametar', !in_array('1', $params, true));
qa24('Nevalidan warehouse filter se resetuje', normalize_equipment_filters(['warehouse' => 'abc'])['warehouse'] === '');

$bad = '<?xml version="1.0"?><worksheet><sheetData><row r="4"><c r="A4"><v>1</v></c></row><row r="4"><c r="D4"><v>2</v></c></row></sheetData></worksheet>';
$rejected = false;
try { xlsx_validate_worksheet_xml('bad.xml', $bad); } catch (Throwable $e) { $rejected = str_contains($e->getMessage(), 'row r="4"'); }
qa24('Validator odbija stari duplicate-row root cause', $rejected);

function qa_rows(int $count, int $warehouseEvery = 0): array {
    $rows = [];
    for ($i = 1; $i <= $count; $i++) {
        $warehouse = $warehouseEvery > 0 && $i % $warehouseEvery === 0;
        $rows[] = [
            'user_name' => $warehouse ? null : 'Korisnik ' . $i,
            'user_email' => $warehouse ? null : 'u' . $i . '@example.org',
            'user_department' => $warehouse ? null : 'Sektor',
            'user_location' => $warehouse ? null : ($i % 2 ? 'Beograd' : 'Kraljevo'),
            'asset_type' => $i % 5 === 0 ? 'Docking station' : ['Laptop','Telefon','Monitor','Tablet'][$i % 4],
            'asset_name' => $i === 2 ? '=Formula-like čćšžđ' : 'Uređaj ' . $i,
            'inventory_no' => str_pad((string)$i, 8, '0', STR_PAD_LEFT),
            'serial_no' => $i === 3 ? '@SER003' : 'SER-' . $i,
            'status' => $warehouse ? 'returned' : 'assigned',
            'assigned_at' => $warehouse ? null : '2026-08-20',
            'notes' => $i === 4 ? "Napomena\x01 test" : 'Napomena ' . $i,
            'updated_at' => '2026-08-20 21:10:00',
            'is_in_warehouse' => $warehouse ? 1 : 0,
        ];
    }
    return $rows;
}

foreach ([[0,0],[1,0],[20,4],[105,10]] as [$count,$warehouseEvery]) {
    $path = create_equipment_xlsx(qa_rows($count, $warehouseEvery), new DateTimeImmutable('2026-08-20 21:10:00', new DateTimeZone('Europe/Belgrade')));
    qa24("XLSX $count redova postoji", is_file($path) && filesize($path) > 500);
    try {
        $zip = new PharData($path);
        $sheet2 = $zip['xl/worksheets/sheet2.xml']->getContent();
        xlsx_validate_worksheet_xml('sheet2.xml', $sheet2);
        qa24("Sažetak $count redova prolazi validator", true);
        qa24("Sažetak $count nema nevalidne cached vrednosti", !preg_match('/NaN|Infinity|undefined|#VALUE!/', $sheet2));
        $hasWarehouse = $warehouseEvery > 0 && $count >= $warehouseEvery;
        qa24("Magacin sheet presence $count", $hasWarehouse ? isset($zip['xl/worksheets/sheet3.xml']) : !isset($zip['xl/worksheets/sheet3.xml']));
        if ($hasWarehouse) {
            $sheet3 = $zip['xl/worksheets/sheet3.xml']->getContent();
            qa24("Magacin $count ima naslov", str_contains($sheet3, 'MAGACIN ICT OPREME'));
            qa24("Magacin $count ima prazna user polja", str_contains($sheet3, '<c r="A5"') && str_contains($sheet3, '<t xml:space="preserve"></t>'));
        }
        if ($count >= 3) {
            $sheet1 = $zip['xl/worksheets/sheet1.xml']->getContent();
            qa24("Leading zero identifier $count ostaje tekst", str_contains($sheet1, '>00000001<'));
            qa24("Formula-like string $count nije formula", str_contains($sheet1, '>=Formula-like čćšžđ<') && !str_contains($sheet1, '<f>'));
        }
    } catch (Throwable $e) {
        qa24("ZIP/OpenXML $count može ponovo da se otvori", false);
    }
    @unlink($path);
}

echo 'RESULT ' . $pass . '/' . ($pass + $fail) . " PASS\n";
exit($fail ? 1 : 0);
