<?php
declare(strict_types=1);
require __DIR__ . '/app/bootstrap.php';
require_auth();
require_current_schema();

$id = (int)($_GET['id'] ?? 0);
$stmt = db()->prepare('SELECT d.*,c.name customer_name,c.company_name customer_company,c.email customer_email,c.phone customer_phone,c.address customer_address,c.city customer_city,c.tax_number customer_tax,(SELECT COALESCE(SUM(p.amount),0) FROM payments p WHERE p.invoice_id=d.id)-(SELECT COALESCE(SUM(r.amount),0) FROM payment_reversals r JOIN payments rp ON rp.id=r.payment_id WHERE rp.invoice_id=d.id) paid,(SELECT COALESCE(SUM(ca.amount),0) FROM credit_note_applications ca WHERE ca.invoice_id=d.id) credited FROM documents d JOIN customers c ON c.id=d.customer_id WHERE d.id=?');
$stmt->execute([$id]);
$d = $stmt->fetch();
if (!$d) { http_response_code(404); exit('Document not found.'); }

$itemStmt = db()->prepare('SELECT * FROM document_items WHERE document_id=? ORDER BY sort_order');
$itemStmt->execute([$id]);
$items = $itemStmt->fetchAll();

$company = settings();
$isInvoice = $d['type'] === 'invoice';
$isCredit = $d['type'] === 'credit_note';
if (!$isInvoice && !$isCredit && $d['type'] !== 'quotation') {
    http_response_code(404);
    exit('Document not found.');
}

$receiptRequested = ($_GET['mode'] ?? '') === 'receipt';
$paid = $isInvoice ? (float)$d['paid'] : 0.0;
$credited = $isInvoice ? (float)$d['credited'] : 0.0;
$balance = $isInvoice ? max(0, (float)$d['total'] - $paid - $credited) : 0.0;
$isReceipt = $receiptRequested && $isInvoice && $paid > 0.009;
if ($receiptRequested && !$isReceipt) {
    http_response_code(409);
    exit('A receipt is available after a payment has been recorded against this invoice.');
}
$documentLabel = $isReceipt ? 'Payment receipt' : ($isInvoice ? 'Invoice' : ($isCredit ? 'Credit note' : 'Quotation'));
$payments = [];
$latestPayment = null;
if ($isInvoice) {
    $paymentStmt = db()->prepare('SELECT p.*,COALESCE(a.name,p.method) account_name FROM payments p LEFT JOIN payment_accounts a ON a.id=p.account_id WHERE p.invoice_id=? ORDER BY p.payment_date DESC,p.id DESC');
    $paymentStmt->execute([$id]);
    $payments = $paymentStmt->fetchAll();
    $latestPayment = $payments[0] ?? null;
}
$formatDate = static fn(?string $date): string => $date ? date('d M Y', strtotime($date)) : 'Not set';
$dueDateLabel = $formatDate($d['due_date'] ?? null);

if ($isCredit) {
    $documentState='CREDIT ISSUED';$stateClass='paid';$stateDetail='Applied to the original invoice';
} elseif ($isReceipt) {
    $documentState = $balance <= 0.009 ? 'PAID' : 'PART PAYMENT';
    $stateClass = $balance <= 0.009 ? 'paid' : 'part-paid';
    $stateDetail = $balance <= 0.009 ? 'Payment received in full' : 'Payment received · balance remains due';
} elseif ($isInvoice) {
    if ($balance <= 0.009) {
        $documentState = 'PAID';
        $stateClass = 'paid';
    } elseif ($paid > 0.009) {
        $documentState = 'PART PAID';
        $stateClass = 'part-paid';
    } else {
        $documentState = 'UNPAID';
        $stateClass = 'unpaid';
    }
    $stateDetail = invoice_payment_detail((float)$d['total'], $paid, $d['due_date'] ?? null);
} else {
    $quotationStatus = (string)$d['status'];
    $quotationExpired = !in_array($quotationStatus, ['accepted', 'rejected', 'cancelled'], true)
        && !empty($d['due_date'])
        && $d['due_date'] < date('Y-m-d');
    if ($quotationExpired) {
        $documentState = 'EXPIRED';
        $stateClass = 'quote-expired';
        $stateDetail = 'Validity ended ' . $dueDateLabel;
    } else {
        $documentState = strtoupper(str_replace('_', ' ', $quotationStatus));
        $stateClass = 'quote-' . preg_replace('/[^a-z0-9_-]/i', '', $quotationStatus);
        $stateDetail = match ($quotationStatus) {
            'accepted' => 'Accepted by the customer',
            'rejected' => 'Quotation not accepted',
            'draft' => 'Internal draft - not yet issued',
            'cancelled' => 'Cancelled quotation',
            default => !empty($d['due_date']) ? 'Valid until ' . $dueDateLabel : 'Validity date not set',
        };
    }
}

$lifecycleFlag = $isInvoice && in_array((string)$d['status'], ['draft', 'cancelled'], true)
    ? strtoupper((string)$d['status'])
    : '';
$fulfilment = $d['fulfilment_method'] ?: 'Pickup';
$fulfilmentAddress = $d['delivery_address'] ?: ($fulfilment === 'Pickup' ? '100 Livingstone Avenue' : 'To be confirmed');
$denseOutput = count($items) > 7 || strlen((string)$d['notes']) + strlen((string)$d['terms']) > 700 || ($isReceipt && count($payments) > 3);
$documentClass = $isReceipt ? 'payment-receipt' : strtolower(str_replace(' ', '-', $documentLabel));
?>
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<title><?=e($d['number'])?> · Soda ZW <?=e($documentLabel)?></title>
<link rel="stylesheet" href="assets/app.css">
<style>
:root{--invoice-navy:#062f56;--invoice-orange:#ff5b08;--invoice-ink:#17324d;--invoice-muted:#687f93;--invoice-line:#dce5ec;--invoice-soft:#f5f8fa}
@page{size:A4 portrait;margin:8mm}
body{background:#eaf0f4;color:var(--invoice-ink)}
.print-toolbar{display:flex;gap:9px;max-width:900px;margin:16px auto}
.premium-invoice{position:relative;max-width:900px;margin:0 auto 30px;padding:34px 38px 28px;background:#fff;border:1px solid var(--invoice-line);box-shadow:0 18px 50px rgba(6,47,86,.12);overflow:hidden}
.premium-invoice:before{content:"";position:absolute;inset:0 0 auto;height:7px;background:linear-gradient(90deg,var(--invoice-navy) 0 72%,var(--invoice-orange) 72%)}.premium-invoice.quotation:before{background:linear-gradient(90deg,var(--invoice-orange) 0 28%,var(--invoice-navy) 28%)}
.premium-invoice.payment-receipt:before{height:10px;background:linear-gradient(90deg,var(--invoice-navy) 0 58%,var(--invoice-orange) 58%)}
.invoice-header{display:flex;justify-content:space-between;gap:35px;padding:12px 0 20px;border-bottom:1px solid var(--invoice-line)}
.brand-block{display:flex;gap:16px;align-items:flex-start}.brand-block img{width:118px;height:72px;object-fit:contain}.brand-details{font-size:10px;line-height:1.55;color:var(--invoice-muted)}.brand-details strong{display:block;margin-bottom:3px;color:var(--invoice-navy);font-size:13px}
.invoice-identity{text-align:right}.invoice-kicker{display:block;color:var(--invoice-orange);font-size:9px;font-weight:900;letter-spacing:.18em;text-transform:uppercase}.invoice-identity h1{margin:4px 0 2px;color:var(--invoice-navy);font-size:30px;line-height:1;text-transform:uppercase}.invoice-number{display:block;color:var(--invoice-muted);font-size:12px;font-weight:800;letter-spacing:.05em}
.payment-stamp{display:inline-block;margin-top:10px;padding:7px 13px;border:2px solid var(--invoice-orange);border-radius:6px;background:#fff3ec;color:#b43d00;font-size:12px;font-weight:950;letter-spacing:.1em;text-transform:uppercase}.payment-stamp.paid{background:var(--invoice-orange);color:#fff;font-size:16px;box-shadow:0 5px 15px rgba(255,91,8,.2)}.payment-stamp.part-paid{border-color:#ed9c28;background:#fff1dc;color:#9b5700}.payment-stamp.quote-accepted{border-color:#178657;background:#178657;color:#fff}.payment-stamp.quote-rejected,.payment-stamp.quote-expired,.payment-stamp.quote-cancelled{border-color:#b83d35;background:#fff1ef;color:#b83d35}.payment-stamp.quote-sent{border-color:var(--invoice-navy);background:var(--invoice-navy);color:#fff}.payment-stamp.quote-draft{border-color:#7b8994;background:#f1f4f6;color:#5f6f7b}.payment-detail{display:block;margin-top:4px;color:var(--invoice-muted);font-size:8px;font-weight:700}.lifecycle-flag{display:inline-block;margin-top:5px;padding:3px 7px;border-radius:4px;background:#b83d35;color:#fff;font-size:7px;font-weight:900;letter-spacing:.1em}
.invoice-information{display:grid;grid-template-columns:1.25fr .75fr;gap:30px;padding:20px 0 16px}.section-label{display:block;margin-bottom:7px;color:var(--invoice-orange);font-size:8px;font-weight:900;letter-spacing:.16em;text-transform:uppercase}.customer-name{margin:0 0 3px;color:var(--invoice-navy);font-size:17px}.customer-copy{margin:0;color:var(--invoice-muted);font-size:10px;line-height:1.55}.invoice-facts{display:grid;grid-template-columns:auto auto;gap:6px 18px;margin:0}.invoice-facts dt{color:var(--invoice-muted);font-size:9px}.invoice-facts dd{margin:0;text-align:right;color:var(--invoice-navy);font-size:9px;font-weight:800}
.service-strip{display:grid;grid-template-columns:1fr 1fr;gap:1px;margin-bottom:16px;border:1px solid var(--invoice-line);border-radius:8px;background:var(--invoice-line);overflow:hidden}.service-strip div{padding:9px 11px;background:var(--invoice-soft);font-size:9px;color:var(--invoice-muted)}.service-strip strong{display:block;margin-bottom:2px;color:var(--invoice-navy);font-size:9px}
.items{width:100%;border-collapse:separate;border-spacing:0}.items th{padding:9px 10px;background:var(--invoice-navy);color:#fff;font-size:8px;font-weight:900;letter-spacing:.08em;text-align:left;text-transform:uppercase}.items th:first-child{border-radius:6px 0 0 0}.items th:last-child{border-radius:0 6px 0 0;text-align:right}.items td{padding:9px 10px;border-bottom:1px solid #e8eef2;color:#3e566b;font-size:9px}.items td:first-child{color:var(--invoice-navy);font-weight:700}.items td:last-child{text-align:right;color:var(--invoice-navy);font-weight:800}
.settlement{display:grid;grid-template-columns:minmax(0,1fr) 285px;gap:30px;align-items:start;margin-top:16px}.payment-card{padding:13px 15px;border:1px solid var(--invoice-line);border-radius:8px;background:var(--invoice-soft)}.payment-card h3{margin:0 0 6px;color:var(--invoice-navy);font-size:10px}.payment-card p{margin:3px 0;color:var(--invoice-muted);font-size:8.5px;line-height:1.4}.payment-card .thank-you{margin-top:8px;color:var(--invoice-orange);font-weight:900}
.receipt-payment-list{display:grid;gap:5px;margin-top:8px}.receipt-payment-row{display:grid;grid-template-columns:70px 1fr auto;gap:8px;padding-top:5px;border-top:1px solid var(--invoice-line);font-size:8px}.receipt-payment-row b{color:var(--invoice-navy)}
.totals{display:grid;gap:0}.totals div{display:flex;justify-content:space-between;gap:20px;padding:5px 7px;color:var(--invoice-muted);font-size:9px}.totals b{color:var(--invoice-navy)}.totals .grand{margin-top:3px;padding:9px 10px;border-radius:6px;background:var(--invoice-navy);color:#fff;font-size:13px;font-weight:900}.totals .grand b{color:#fff}.totals .balance{margin-top:3px;color:var(--invoice-orange);font-size:11px;font-weight:900}.totals .balance b{color:var(--invoice-orange)}
.invoice-notes{display:grid;grid-template-columns:1fr 1fr;gap:24px;margin-top:15px;padding-top:12px;border-top:1px solid var(--invoice-line)}.invoice-notes h4{margin:0 0 4px;color:var(--invoice-navy);font-size:9px}.invoice-notes p{margin:0;color:var(--invoice-muted);font-size:8px;line-height:1.4}.invoice-footer{display:flex;justify-content:space-between;gap:15px;margin-top:16px;padding-top:10px;border-top:1px solid var(--invoice-line);color:#8598a8;font-size:7.5px}.invoice-footer strong{color:var(--invoice-navy)}.compact-output .invoice-information{padding:13px 0 10px}.compact-output .items th,.compact-output .items td{padding-top:5px;padding-bottom:5px;font-size:7.8px}.compact-output .invoice-notes p{font-size:7px}
@media(max-width:650px){.premium-invoice{padding:26px 19px}.invoice-header,.brand-block{display:grid}.invoice-identity{text-align:left}.invoice-information,.settlement,.invoice-notes{grid-template-columns:1fr}.invoice-facts dd{text-align:left}.service-strip{grid-template-columns:1fr}.items{min-width:600px}.items-wrap{overflow:auto}}
@media print{
  html,body{width:210mm;min-height:0;background:#fff;font-size:9px}.print-toolbar{display:none!important}.premium-invoice{width:100%;max-width:none;min-height:0;margin:0;padding:23px 25px 18px;border:0;box-shadow:none}.premium-invoice:before,.payment-stamp,.items th,.totals .grand,.service-strip div,.payment-card,.lifecycle-flag{print-color-adjust:exact;-webkit-print-color-adjust:exact}.invoice-header{padding:7px 0 10px}.brand-block img{width:96px;height:57px}.brand-details{font-size:8px}.brand-details strong{font-size:10px}.invoice-identity h1{font-size:23px}.payment-stamp{margin-top:6px;padding:5px 10px}.payment-stamp.paid{font-size:14px}.invoice-information{gap:20px;padding:11px 0 9px}.customer-name{font-size:13px}.customer-copy{font-size:8px}.service-strip{margin-bottom:9px}.service-strip div{padding:6px 8px}.items th,.items td{padding:5px 7px;font-size:7.8px}.settlement{grid-template-columns:minmax(0,1fr) 250px;gap:22px;margin-top:9px}.payment-card{padding:8px 10px}.payment-card p{font-size:7.5px}.totals div{padding:3px 6px;font-size:8px}.totals .grand{padding:6px 8px;font-size:10px}.totals .balance{font-size:9px}.invoice-notes{gap:18px;margin-top:8px;padding-top:7px}.invoice-notes p{font-size:7px}.invoice-footer{margin-top:8px;padding-top:6px}.items-wrap,.service-strip,.settlement,.invoice-notes{break-inside:avoid}.items tr{break-inside:avoid}
}
</style>
</head>
<body>
<div class="print-toolbar"><button class="button primary" onclick="window.print()">Print / Save as PDF</button><button class="button secondary" onclick="window.close()">Close</button></div>

<article class="premium-invoice <?=e($documentClass)?><?=$denseOutput ? ' compact-output' : ''?>">
  <header class="invoice-header">
    <div class="brand-block">
      <img src="assets/sodazw-logo-invoice.png" alt="Soda ZW">
      <div class="brand-details"><strong><?=e($company['trading_name'] ?: 'Soda ZW')?></strong><?=e($company['address'])?><br><?=e($company['city'])?>, <?=e($company['country'])?><br><?=e($company['phone'])?><?php if($company['email']):?><br><?=e($company['email'])?><?php endif;?><?php if($company['tax_number']):?><br>Tax/VAT: <?=e($company['tax_number'])?><?php endif;?></div>
    </div>
    <div class="invoice-identity"><span class="invoice-kicker"><?=$isReceipt ? 'Official proof of payment' : ($isInvoice ? 'Official customer invoice' : ($isCredit?'Official customer credit':'Customer quotation'))?></span><h1><?=e($documentLabel)?></h1><span class="invoice-number"><?=$isReceipt ? 'For invoice ' : ''?><?=e($d['number'])?></span><span class="payment-stamp <?=e($stateClass)?>"><?=e($documentState)?></span><span class="payment-detail"><?=e($stateDetail)?></span><?php if($lifecycleFlag&&!$isReceipt):?><span class="lifecycle-flag"><?=e($lifecycleFlag)?></span><?php endif;?></div>
  </header>

  <section class="invoice-information">
    <div><span class="section-label"><?=$isReceipt?'Received from':($isInvoice?'Bill to':'Prepared for')?></span><h2 class="customer-name"><?=e($d['customer_name'])?></h2><p class="customer-copy"><?php if($d['customer_company']):?><?=e($d['customer_company'])?><br><?php endif;?><?=e($d['customer_address'])?><?php if($d['customer_city']):?><br><?=e($d['customer_city'])?><?php endif;?><?php if($d['customer_phone']):?><br><?=e($d['customer_phone'])?><?php endif;?><?php if($d['customer_email']):?><br><?=e($d['customer_email'])?><?php endif;?><?php if($d['customer_tax']):?><br>Tax/VAT: <?=e($d['customer_tax'])?><?php endif;?></p></div>
    <div><span class="section-label"><?=$isReceipt?'Receipt details':'Document details'?></span><dl class="invoice-facts"><?php if($isReceipt):?><dt>Payment date</dt><dd><?=e($formatDate($latestPayment['payment_date'] ?? null))?></dd><dt>Invoice</dt><dd><?=e($d['number'])?></dd><dt>Payment channel</dt><dd><?=e((string)($latestPayment['account_name'] ?? 'Recorded payment'))?></dd><?php if(!empty($latestPayment['reference'])):?><dt>Reference</dt><dd><?=e((string)$latestPayment['reference'])?></dd><?php endif;?><?php else:?><dt>Issue date</dt><dd><?=e($formatDate($d['issue_date']))?></dd><dt><?=$isInvoice?'Due date':'Valid until'?></dt><dd><?=e($dueDateLabel)?></dd><?php endif;?><dt>Currency</dt><dd><?=e($d['currency_code'])?></dd><?php if(!$isReceipt&&$d['customer_reference']):?><dt>Reference</dt><dd><?=e($d['customer_reference'])?></dd><?php endif;?></dl></div>
  </section>

  <section class="service-strip"><div><strong>Order source</strong><?=e($d['order_source'] ?: 'Direct Soda ZW order')?></div><div><strong><?=$isInvoice ? 'Fulfilment' : 'Proposed fulfilment'?> · <?=e($fulfilment)?></strong><?=e($fulfilmentAddress)?><?php if((float)$d['delivery_fee']>0):?> · Delivery <?=money($d['delivery_fee'],$d['currency_code'])?><?php endif;?></div></section>

  <div class="items-wrap"><table class="items"><thead><tr><th>Description</th><th>Qty</th><th>Unit price</th><th>Tax</th><th>Total</th></tr></thead><tbody><?php foreach($items as $it):?><tr><td><?=e($it['description'])?></td><td><?=e($it['quantity'])?></td><td><?=money($it['unit_price'],$d['currency_code'])?></td><td><?=e($it['tax_rate'])?>%</td><td><?=money($it['line_total'],$d['currency_code'])?></td></tr><?php endforeach;?></tbody></table></div>

  <section class="settlement">
    <div class="payment-card"><?php if($isReceipt):?><h3>Payment history</h3><p>This receipt confirms the payments recorded against invoice <?=e($d['number'])?>.</p><div class="receipt-payment-list"><?php foreach($payments as $payment):?><div class="receipt-payment-row"><span><?=e($formatDate($payment['payment_date']))?></span><span><?=e((string)$payment['account_name'])?><?=!empty($payment['reference'])?' · '.e((string)$payment['reference']):''?></span><b><?=money($payment['amount'],$d['currency_code'])?></b></div><?php endforeach;?></div><p class="thank-you">Thank you. Your payment has been received.</p><?php elseif($isInvoice):?><h3><?=$balance <= .009 ? 'Payment complete' : 'Payment information'?></h3><?php if($balance <= .009):?><p>This invoice is paid in full.</p><?php else:?><?php if($company['bank_details']):?><p><?=nl2br(e($company['bank_details']))?></p><?php endif;?><?php if($company['payment_instructions']):?><p><?=nl2br(e($company['payment_instructions']))?></p><?php endif;?><p>Please quote invoice <?=e($d['number'])?> when paying.</p><?php endif;?><p class="thank-you">Thank you for choosing Soda ZW.</p><?php elseif($isCredit):?><h3>Credit adjustment</h3><p>This credit note has been applied against the original customer invoice.</p><p>Please retain it with the invoice for your records.</p><p class="thank-you">Thank you for choosing Soda ZW.</p><?php else:?><h3>Quotation validity</h3><p><?=e($stateDetail)?>.</p><p>Please confirm acceptance with Soda ZW before fulfilment.</p><p class="thank-you">We look forward to serving you.</p><?php endif;?></div>
    <div class="totals"><div><span>Subtotal</span><b><?=money($d['subtotal'],$d['currency_code'])?></b></div><?php if((float)$d['discount_total']):?><div><span>Discount</span><b>-<?=money($d['discount_total'],$d['currency_code'])?></b></div><?php endif;?><?php if((float)$d['tax_total']):?><div><span>Tax</span><b><?=money($d['tax_total'],$d['currency_code'])?></b></div><?php endif;?><?php if((float)$d['delivery_fee']):?><div><span>Delivery</span><b><?=money($d['delivery_fee'],$d['currency_code'])?></b></div><?php endif;?><div class="grand"><span><?=$isReceipt ? 'Amount received' : ($isInvoice ? 'Invoice total' : ($isCredit?'Credit total':'Quotation total'))?></span><b><?=money($isReceipt?$paid:$d['total'],$d['currency_code'])?></b></div><?php if($isInvoice):?><?php if(!$isReceipt):?><div><span>Payments received</span><b><?=money($paid,$d['currency_code'])?></b></div><?php endif;?><?php if($credited>.009):?><div><span>Credits applied</span><b><?=money($credited,$d['currency_code'])?></b></div><?php endif;?><div class="balance"><span>Balance due</span><b><?=money($balance,$d['currency_code'])?></b></div><?php endif;?></div>
  </section>

  <?php if(!$isReceipt && ($d['notes'] || $d['terms'])):?><section class="invoice-notes"><?php if($d['notes']):?><div><h4>Notes</h4><p><?=nl2br(e($d['notes']))?></p></div><?php endif;?><?php if($d['terms']):?><div><h4><?=$isInvoice ? 'Terms' : 'Quotation terms'?></h4><p><?=nl2br(e($d['terms']))?></p></div><?php endif;?></section><?php endif;?>
  <footer class="invoice-footer"><span><strong>Soda ZW</strong> · Join the sparkle movement</span><span><?=$isReceipt?'Receipt for ':''?><?=e($d['number'])?> · Generated <?=e(date('d M Y'))?></span></footer>
</article>
</body>
</html>
