<?php

declare(strict_types=1);

require_once __DIR__ . '/includes/vendor_loader.php';
require_once __DIR__ . '/includes/bootstrap.php';
require_once __DIR__ . '/includes/helpers.php';
require_once __DIR__ . '/includes/invoice_contract.php';
require_once __DIR__ . '/includes/invoice_pdf_generator.php';

header('Content-Type: text/html; charset=utf-8');

$scriptDir = rtrim(str_replace('\\', '/', dirname((string)($_SERVER['SCRIPT_NAME'] ?? '/test-pdf.php'))), '/');
if ($scriptDir === '/') {
    $scriptDir = '';
}

$download = isset($_GET['download']) && $_GET['download'] === '1';
$testFile = __DIR__ . '/uploads/contracts/karvi_pdf_test.pdf';
$result = ['ok' => false, 'message' => '', 'size' => 0, 'path' => $testFile];

try {
    karvi_load_vendor(true);

    $contract = [
        'token' => 'testpdf000000000000000000000001',
        'id' => 1,
        'invoice_mode' => 'pos',
        'contract_line' => 'Karvi POS',
        'contract_date' => date('Y-m-d'),
        'delivery_date' => date('Y-m-d', time() + (25 * 86400)),
        'customer_details' => "Test GmbH\nMusterstr. 1\n60311 Frankfurt",
        'installment_months' => 12,
        'line_items' => [[
            'description' => 'Karvi POS System inkl. iPad',
            'quantity' => 1,
            'unit_price_net' => 1950,
            'total_net' => 1950,
        ]],
        'optional_printer' => 0,
        'discount' => 0,
        'totals' => invoice_calculate_totals(
            [['total_net' => 1950]],
            0,
            false,
            ['unit_price_net' => 0]
        ),
    ];

    $config = app_config();
    if (!is_dir($config['contracts_dir']) && !@mkdir($config['contracts_dir'], 0755, true) && !is_dir($config['contracts_dir'])) {
        throw new RuntimeException('Cannot create uploads/contracts folder.');
    }

    if (!is_writable($config['contracts_dir'])) {
        throw new RuntimeException('uploads/contracts is not writable.');
    }

    generate_invoice_contract_pdf($contract, $testFile);

    if (!is_file($testFile) || filesize($testFile) < 512) {
        throw new RuntimeException('PDF file was not created.');
    }

    $result['ok'] = true;
    $result['size'] = (int)filesize($testFile);
    $result['message'] = 'PDF generated successfully.';
} catch (Throwable $e) {
    $result['message'] = $e->getMessage();
}

if ($download && $result['ok']) {
    header('Content-Type: application/pdf');
    header('Content-Disposition: attachment; filename="karvi_pdf_test.pdf"');
    header('Content-Length: ' . (string)$result['size']);
    readfile($testFile);
    exit;
}

$vendorDir = karvi_resolve_vendor_dir();
$healthUrl = ($scriptDir !== '' ? $scriptDir : '') . '/health.php';
$downloadUrl = ($scriptDir !== '' ? $scriptDir : '') . '/test-pdf.php?download=1';
?>
<!DOCTYPE html>
<html lang="de">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Karvi PDF Test</title>
    <style>
        body { font-family: Arial, sans-serif; max-width: 760px; margin: 2rem auto; padding: 0 1rem; }
        .ok { color: #0a7; font-weight: bold; }
        .bad { color: #c00; font-weight: bold; }
        .btn { display: inline-block; padding: 12px 24px; background: #b8860b; color: #fff; text-decoration: none; border-radius: 8px; margin: 0.5rem 0.5rem 0 0; }
        code { background: #eee; padding: 2px 5px; word-break: break-all; }
        .box { background: #f8f8f8; border: 1px solid #ddd; padding: 1rem; border-radius: 8px; margin-top: 1rem; }
    </style>
</head>
<body>
    <h1>Karvi PDF Test</h1>
    <p>Vendor folder: <code><?= htmlspecialchars($vendorDir, ENT_QUOTES, 'UTF-8') ?></code></p>
    <p>FPDF: <code><?= is_file($vendorDir . '/setasign/fpdf/fpdf.php') ? 'found' : 'missing' ?></code></p>
    <p>FPDI: <code><?= is_file($vendorDir . '/setasign/fpdi/src/Fpdi.php') ? 'found' : 'missing' ?></code></p>

    <?php if ($result['ok']): ?>
        <p class="ok"><?= htmlspecialchars($result['message'], ENT_QUOTES, 'UTF-8') ?> (<?= (int)$result['size'] ?> bytes)</p>
        <a class="btn" href="<?= htmlspecialchars($downloadUrl, ENT_QUOTES, 'UTF-8') ?>">Download test PDF</a>
    <?php else: ?>
        <p class="bad">FAIL — <?= htmlspecialchars($result['message'], ENT_QUOTES, 'UTF-8') ?></p>
        <div class="box">
            <strong>Fix:</strong>
            <ol>
                <li>Upload full <code>vendor/</code> folder to <code><?= htmlspecialchars($vendorDir, ENT_QUOTES, 'UTF-8') ?></code></li>
                <li>Must include <code>setasign/fpdf/fpdf.php</code> and <code>setasign/fpdi/</code></li>
                <li>Make <code>uploads/contracts/</code> writable (755 or 775)</li>
            </ol>
        </div>
    <?php endif; ?>

    <p><a class="btn" href="<?= htmlspecialchars($healthUrl, ENT_QUOTES, 'UTF-8') ?>">Health Check</a></p>
</body>
</html>
