<?php
// Copy of test script for dev folder
require_once __DIR__ . '/../../config/config.php';
require_once __DIR__ . '/../../app/core/Database.php';
require_once __DIR__ . '/../../app/core/Model.php';
require_once __DIR__ . '/../../app/models/Customer.php';
require_once __DIR__ . '/../../app/models/Invoice.php';
require_once __DIR__ . '/../../app/models/Document.php';
require_once __DIR__ . '/../../app/core/PdfGenerator.php';

function out($m) { echo $m . PHP_EOL; }

try {
    $customerModel = new Customer();
    $customers = $customerModel->all();
    if (empty($customers)) {
        $custId = $customerModel->create([
            'name' => 'Dev CLI Test Customer',
            'email' => 'dev-cli-test@example.com',
            'phone' => '+233000000001',
            'company' => 'Dev CLI Test Co',
            'address' => 'Accra',
            'notes' => 'Created by dev test script',
        ]);
        out("Created customer id: $custId");
    } else {
        $custId = $customers[0]['id'];
        out("Using existing customer id: $custId");
    }

    $invoiceModel = new Invoice();
    $items = [
        ['description' => 'Dev Item A', 'quantity' => 1, 'unit_price' => 100.00, 'total_price' => 100.00],
    ];
    $total = 0.0; foreach ($items as $it) { $total += $it['total_price']; }

    $invoiceId = $invoiceModel->create([
        'invoice_number' => 'DEV-' . time(),
        'customer_id' => $custId,
        'total_amount' => $total,
        'paid_amount' => 0.00,
        'due_date' => date('Y-m-d', strtotime('+7 days')),
        'status' => 'Outstanding',
    ]);

    out('Created invoice id: ' . $invoiceId);
    $invoiceModel->saveItems((int)$invoiceId, $items);

    $pdfGen = new PdfGenerator();
    $siteSettings = [
        'topbar_email' => 'info@balorpfinishes.com',
        'topbar_phone' => '+233 24 000 0000',
        'topbar_location' => 'Accra, Ghana',
    ];
    $invoice = $invoiceModel->findWithCustomer((int)$invoiceId);
    $itemsFromDb = $invoiceModel->getItems((int)$invoiceId);
    $pdfContent = $pdfGen->generateInvoicePdf($invoice, $itemsFromDb, $siteSettings);
    $outDir = __DIR__ . '/../../storage/documents';
    if (!is_dir($outDir)) mkdir($outDir, 0755, true);
    $filename = $outDir . '/dev-test-invoice-' . $invoiceId . '.pdf';
    file_put_contents($filename, $pdfContent);
    out("Wrote PDF to: $filename (" . filesize($filename) . " bytes)");

    // cleanup left to developer intentionally
    out('Dev test script finished.');

} catch (Throwable $e) {
    out('ERROR: ' . $e->getMessage());
    exit(1);
}

?>