<?php
require __DIR__ . '/_boot.php';

use App\Services\ExcelWriter;
use App\Services\ExcelReader;
use App\Services\PdfWriter;
use App\Services\CsvWriter;

$out = SIPIUTANG_ROOT . '/storage/tmp';
@mkdir($out, 0775, true);

head('ExcelWriter -> XLSX valid & dapat dibaca kembali');
$cols = [
    ['label' => 'No Invoice',   'key' => 'inv',   'type' => 'text',  'width' => 18],
    ['label' => 'No Faktur Pajak', 'key' => 'fp', 'type' => 'text',  'width' => 22],
    ['label' => 'Tgl Invoice',  'key' => 'tgl',   'type' => 'date'],
    ['label' => 'Customer',     'key' => 'cust',  'type' => 'text',  'width' => 30],
    ['label' => 'Nominal',      'key' => 'nom',   'type' => 'money'],
    ['label' => 'Saldo',        'key' => 'saldo', 'type' => 'money'],
    ['label' => 'Umur (hari)',  'key' => 'umur',  'type' => 'int'],
    ['label' => '% Tertagih',   'key' => 'pc',    'type' => 'pct'],
];
$rows = [
    ['inv' => 'FA/26/0215', 'fp' => '04002600029966887', 'tgl' => '2026-01-31', 'cust' => 'FAST FOOD INDONESIA PT', 'nom' => 832500, 'saldo' => 0, 'umur' => 12, 'pc' => 100],
    ['inv' => 'FB/26/0035', 'fp' => '04002600033274431', 'tgl' => '2026-01-31', 'cust' => 'BERKAH ARUNA KULINER PT', 'nom' => 203130, 'saldo' => -5000, 'umur' => -3, 'pc' => 102.5],
    ['inv' => 'FA/26/1879', 'fp' => '04002600250891937', 'tgl' => '2026-07-03', 'cust' => 'PT PARDIC JAYA CHEMICALS', 'nom' => 122100000, 'saldo' => 122100000, 'umur' => 0, 'pc' => 0],
];
$w = new ExcelWriter();
$w->setTitle('Uji Laporan');
$w->addSheet('Piutang', $cols, $rows, [
    'judul' => 'LAPORAN AGING PIUTANG',
    'subjudul' => ['PT Roto-Rooter Indonesia', 'Tanggal Pelaporan: 27-07-2026'],
    'total' => ['inv' => 'TOTAL', 'nom' => 123135630, 'saldo' => 122095000, 'umur' => 3],
]);
$file = $out . '/uji_export.xlsx';
$w->save($file);
assertTrue(is_file($file) && filesize($file) > 2000, 'Berkas XLSX terbentuk (' . ukuranBerkas(filesize($file)) . ')');

$rd = new ExcelReader($file);
$sheets = $rd->sheetNames();
assertEq($sheets[0]['name'] ?? '', 'Piutang', 'Nama sheet terbaca kembali');
$back = $rd->rows('Piutang', 0, 1);
$flat = [];
foreach ($back as $n => $cells) {
    foreach ($cells as $col => $c) $flat[$col . $n] = $c['v'];
}
$hdrRow = null;
foreach ($back as $n => $cells) if (($cells['A']['v'] ?? '') === 'No Invoice') { $hdrRow = $n; break; }
assertTrue($hdrRow !== null, 'Baris header ditemukan pada baris ' . $hdrRow);
assertEq($flat['A' . ($hdrRow + 1)] ?? '', 'FA/26/0215', 'Data baris 1 kolom A');
assertEq($flat['B' . ($hdrRow + 1)] ?? '', '04002600029966887', 'Faktur pajak: nol di depan utuh, bukan notasi ilmiah');
assertEq($flat['C' . ($hdrRow + 1)] ?? '', '2026-01-31', 'Tanggal terbaca sebagai tanggal');
assertEq($flat['E' . ($hdrRow + 1)] ?? 0, 832500, 'Nominal numerik');
assertEq($flat['F' . ($hdrRow + 2)] ?? 0, -5000, 'Saldo negatif tersimpan sebagai angka negatif');

head('CsvWriter');
$csv = CsvWriter::build($cols, $rows, ['total' => ['inv' => 'TOTAL', 'nom' => 123135630]]);
assertTrue(str_contains($csv, 'No Faktur Pajak'), 'Header CSV ada');
assertTrue(str_contains($csv, '="04002600029966887"'), 'Faktur pajak dibungkus formula teks agar Excel tidak mengubahnya');
assertTrue(str_starts_with($csv, "\xEF\xBB\xBF"), 'CSV memakai BOM UTF-8 agar karakter Indonesia benar di Excel');
assertTrue(str_contains($csv, 'TOTAL'), 'Baris total ada');

head('PdfWriter -> PDF valid');
$p = new PdfWriter('landscape');
$p->setHeader([
    'perusahaan' => 'PT Roto-Rooter Indonesia',
    'judul' => 'LAPORAN AGING PIUTANG',
    'subjudul' => 'Konfigurasi: Standar Excel (0-45 / 46-90 / 91-120 / >120)',
    'periode' => '01-01-2026 s/d 27-07-2026',
    'tanggal_lapor' => '27-07-2026',
    'filter' => ['Area' => 'Jakarta', 'Unit Bisnis' => 'Komersial'],
    'dibuat_oleh' => 'Administrator Sistem',
]);
$p->setColumns([
    ['label' => 'No Invoice', 'key' => 'inv', 'type' => 'text', 'width' => 1.3],
    ['label' => 'Tgl Invoice', 'key' => 'tgl', 'type' => 'date', 'width' => 1],
    ['label' => 'Customer', 'key' => 'cust', 'type' => 'text', 'width' => 2.6],
    ['label' => 'Nominal', 'key' => 'nom', 'type' => 'money', 'width' => 1.4],
    ['label' => 'Saldo', 'key' => 'saldo', 'type' => 'money', 'width' => 1.4],
    ['label' => 'Umur', 'key' => 'umur', 'type' => 'int', 'width' => 0.7],
]);
$p->setSignature([
    ['peran' => 'Diperiksa oleh,', 'nama' => '(...................................)', 'jabatan' => 'Staff Finance AR'],
    ['peran' => 'Disetujui oleh,', 'nama' => '(...................................)', 'jabatan' => 'Manager Finance'],
]);
$p->start();
$p->kpiBoxes([
    ['label' => 'Total Piutang', 'value' => rp(2666117599)],
    ['label' => 'Jatuh Tempo', 'value' => rp(497000000)],
    ['label' => 'ACP', 'value' => '42 hari'],
    ['label' => 'Collection Rate', 'value' => '67,2%'],
]);
$p->groupHeading('AREA: JAKARTA');
for ($i = 0; $i < 90; $i++) {
    $p->row(['inv' => 'FA/26/' . str_pad((string)$i, 4, '0', STR_PAD_LEFT), 'tgl' => '2026-03-15',
             'cust' => 'CUSTOMER CONTOH DENGAN NAMA SANGAT PANJANG SEKALI ' . $i,
             'nom' => 1250000 + $i * 1000, 'saldo' => $i % 4 === 0 ? -50000 : 1250000, 'umur' => $i - 20]);
}
$p->grandTotal(['inv' => 'GRAND TOTAL', 'nom' => 118500000, 'saldo' => 95000000, 'umur' => 35]);
$pdf = $p->render();
$file2 = $out . '/uji_export.pdf';
file_put_contents($file2, $pdf);
assertTrue(str_starts_with($pdf, '%PDF-1.4'), 'Header PDF benar');
assertTrue(str_contains($pdf, '%%EOF'), 'Trailer PDF ada');
assertTrue(preg_match('/\/Type \/Pages \/Count (\d+)/', $pdf, $m) === 1 && (int)$m[1] >= 2, 'PDF multi-halaman (' . ($m[1] ?? '?') . ' halaman)');
assertTrue(filesize($file2) > 3000, 'Ukuran PDF wajar (' . ukuranBerkas(filesize($file2)) . ')');

summary();
