<?php
declare(strict_types=1);

require __DIR__ . '/app/bootstrap.php';
if (!billing_schema_is_current()) {
    http_response_code(503);
    exit('This document is temporarily unavailable while Soda ZW completes a system upgrade.');
}

header('X-Robots-Tag: noindex, nofollow', true);
header('Cache-Control: private, no-store, max-age=0');
header('Referrer-Policy: no-referrer');

$token = (string)($_GET['token'] ?? '');
if (!preg_match('/^[a-f0-9]{64}$/', $token)) {
    http_response_code(404);
    exit('Document link not found.');
}

$statement = db()->prepare(
    'SELECT d.*,c.name customer_name,c.company_name customer_company,c.email customer_email,
        c.phone customer_phone,c.whatsapp customer_whatsapp,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.type IN ("invoice","quotation","credit_note")
       AND d.status NOT IN ("draft","cancelled")
       AND d.share_enabled=1
       AND d.share_token=?
    '
);
$statement->execute([$token]);
$document = $statement->fetch();
if (!$document) {
    http_response_code(404);
    exit('This document link is unavailable.');
}

// Keep the existing secure-link tracking, but only count views of documents
// that passed the public type, status, enabled and token checks above.
db()->prepare(
    'UPDATE documents
     SET share_view_count=share_view_count+1,
         share_first_viewed_at=COALESCE(share_first_viewed_at,NOW()),
         share_last_viewed_at=NOW()
     WHERE id=?'
)->execute([$document['id']]);

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

$company = settings();
$isInvoice = $document['type'] === 'invoice';
$isCredit = $document['type'] === 'credit_note';
$documentLabel = $isInvoice ? 'Invoice' : ($isCredit?'Credit note':'Quotation');
$paid = $isInvoice ? (float)$document['paid'] : 0.0;
$credited = $isInvoice ? (float)$document['credited'] : 0.0;
$balance = $isInvoice ? max(0, (float)$document['total'] - $paid - $credited) : 0.0;
$paynowUrl = '';
if ($isInvoice && $balance > 0.009) {
    $paynowStatement = db()->prepare('SELECT browser_url,status,amount FROM online_payment_attempts WHERE provider="paynow" AND invoice_id=? ORDER BY id DESC LIMIT 1');
    $paynowStatement->execute([(int)$document['id']]);
    $paynowAttempt = $paynowStatement->fetch();
    if ($paynowAttempt && abs((float)$paynowAttempt['amount'] - $balance) <= 0.009 && in_array($paynowAttempt['status'], ['created','initiated','sent'], true) && paynow_url_allowed((string)$paynowAttempt['browser_url'])) {
        $paynowUrl = (string)$paynowAttempt['browser_url'];
    }
}
$formatDate = static fn(?string $date): string => $date ? date('d M Y', strtotime($date)) : 'Not set';
$dueDateLabel = $formatDate($document['due_date'] ?? null);

if ($isCredit) {
    $documentState='CREDIT ISSUED';$stateClass='paid';$stateDetail='Applied to the original invoice';
} 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)$document['total'],
        $paid,
        $document['due_date'] ?? null
    );
} else {
    $quotationStatus = (string)$document['status'];
    $quotationExpired = !in_array($quotationStatus, ['accepted', 'rejected'], true)
        && !empty($document['due_date'])
        && $document['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',
            default => !empty($document['due_date']) ? 'Valid until ' . $dueDateLabel : 'Validity date not set',
        };
    }
}

$businessPhone = preg_replace('/\D+/', '', (string)($company['phone'] ?? ''));
if (str_starts_with($businessPhone, '0')) {
    $businessPhone = '263' . substr($businessPhone, 1);
} elseif (strlen($businessPhone) === 9 && str_starts_with($businessPhone, '7')) {
    $businessPhone = '263' . $businessPhone;
}
if (!$businessPhone) {
    $businessPhone = '263771739696';
}

$contactText = $isInvoice
    ? 'Hello Soda ZW, I am confirming payment for invoice ' . $document['number'] . ' for ' . money($balance, $document['currency_code']) . '. My payment reference is: '
    : ($isCredit
        ? 'Hello Soda ZW, I have a question about credit note ' . $document['number'] . ' for ' . money($document['total'], $document['currency_code']) . '. '
        : 'Hello Soda ZW, I am contacting you about quotation ' . $document['number'] . ' for ' . money($document['total'], $document['currency_code']) . '. ');
$contactLabel = $isInvoice ? 'Confirm payment on WhatsApp' : ($isCredit ? 'Ask about this credit' : 'Discuss quotation on WhatsApp');
$showContactAction = $isCredit || !$isInvoice || $balance > 0.009;
$fulfilment = (string)($document['fulfilment_method'] ?: 'Pickup');
$fulfilmentAddress = (string)($document['delivery_address'] ?: ($fulfilment === 'Pickup' ? '100 Livingstone Avenue' : 'To be confirmed'));
$denseOutput = count($items) > 7
    || strlen((string)$document['notes']) + strlen((string)$document['terms']) > 700;
?>
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<meta name="robots" content="noindex,nofollow">
<title><?=e($document['number'])?> - Soda ZW <?=e($documentLabel)?></title>
<link rel="stylesheet" href="assets/app.css">
<link rel="stylesheet" href="assets/modern.css">
<style>
:root{--doc-navy:#062f56;--doc-orange:#ff5b08;--doc-ink:#17324d;--doc-muted:#687f93;--doc-line:#dce5ec;--doc-soft:#f5f8fa;--doc-green:#178657;--doc-red:#b83d35}
*{box-sizing:border-box}.customer-share{min-height:100vh;padding:24px;background:#eef3f6;color:var(--doc-ink)}
.share-toolbar{display:flex;align-items:center;justify-content:space-between;gap:15px;max-width:920px;margin:0 auto 14px}.share-toolbar p{margin:0;color:#657c90;font-size:12px}.share-actions{display:flex;gap:9px;flex-wrap:wrap}.whatsapp-contact{background:#18a566!important;color:#fff!important;border-color:#18a566!important}
.customer-share .document-card{position:relative;max-width:920px;margin:0 auto;padding:30px 34px 24px;border:1px solid var(--doc-line);border-radius:14px;background:#fff;box-shadow:0 16px 44px rgba(6,47,86,.1);overflow:hidden}.customer-share .document-card:before{content:"";position:absolute;inset:0 0 auto;height:7px;background:linear-gradient(90deg,var(--doc-navy) 0 72%,var(--doc-orange) 72%)}.customer-share .document-card.quotation:before{background:linear-gradient(90deg,var(--doc-orange) 0 28%,var(--doc-navy) 28%)}
.document-head{display:flex;justify-content:space-between;gap:30px;padding:8px 0 16px;border-bottom:1px solid var(--doc-line)}.brand-block{display:flex;align-items:flex-start;gap:15px}.brand-block img{width:112px;height:68px;object-fit:contain}.brand-copy{color:var(--doc-muted);font-size:10px;line-height:1.5}.brand-copy strong{display:block;margin-bottom:3px;color:var(--doc-navy);font-size:13px}.document-title{text-align:right}.document-title>span{color:var(--doc-orange);font-size:8px;font-weight:900;letter-spacing:.16em;text-transform:uppercase}.document-title h1{margin:3px 0;color:var(--doc-navy);font-size:28px;line-height:1;text-transform:uppercase}.document-number{display:block;color:var(--doc-muted);font-size:11px;font-weight:800}
.document-status{display:inline-block;margin-top:9px;padding:7px 12px;border:2px solid var(--doc-orange);border-radius:6px;background:#fff4ed;color:#a94110;font-size:13px;font-weight:950;letter-spacing:.1em;text-transform:uppercase}.document-status.paid{background:var(--doc-orange);color:#fff}.document-status.part-paid{background:#fff1dc;color:#9b5700;border-color:#ed9c28}.document-status.quote-accepted{background:var(--doc-green);color:#fff;border-color:var(--doc-green)}.document-status.quote-rejected,.document-status.quote-expired{background:#fff1ef;color:var(--doc-red);border-color:var(--doc-red)}.document-status.quote-sent{background:var(--doc-navy);color:#fff;border-color:var(--doc-navy)}.status-detail{display:block;margin-top:4px;color:var(--doc-muted);font-size:8px;font-weight:700}
.document-meta{display:grid;grid-template-columns:1.2fr .8fr;gap:28px;padding:16px 0 13px}.section-label{display:block;margin-bottom:6px;color:var(--doc-orange);font-size:8px;font-weight:900;letter-spacing:.14em;text-transform:uppercase}.customer-name{margin:0 0 3px;color:var(--doc-navy);font-size:16px}.customer-copy{margin:0;color:var(--doc-muted);font-size:9.5px;line-height:1.5}.document-facts{display:grid;grid-template-columns:auto auto;gap:5px 15px;margin:0}.document-facts dt{color:var(--doc-muted);font-size:9px}.document-facts dd{margin:0;text-align:right;color:var(--doc-navy);font-size:9px;font-weight:800}
.service-strip{display:grid;grid-template-columns:1fr 1fr;gap:1px;margin-bottom:13px;border:1px solid var(--doc-line);border-radius:8px;background:var(--doc-line);overflow:hidden}.service-strip div{padding:8px 10px;background:var(--doc-soft);color:var(--doc-muted);font-size:9px}.service-strip strong{display:block;margin-bottom:2px;color:var(--doc-navy);font-size:9px}
.document-items{width:100%;border-collapse:separate;border-spacing:0}.document-items th{padding:8px 9px;background:var(--doc-navy);color:#fff;font-size:8px;font-weight:900;letter-spacing:.07em;text-align:left;text-transform:uppercase}.document-items th:last-child,.document-items td:last-child{text-align:right}.document-items td{padding:7px 9px;border-bottom:1px solid #e8eef2;color:#3e566b;font-size:8.8px}.document-items td:first-child{color:var(--doc-navy);font-weight:700}.document-items td:last-child{color:var(--doc-navy);font-weight:800}
.settlement{display:grid;grid-template-columns:minmax(0,1fr) 278px;gap:26px;align-items:start;margin-top:13px}.info-card{padding:11px 13px;border:1px solid var(--doc-line);border-radius:8px;background:var(--doc-soft)}.info-card h3{margin:0 0 5px;color:var(--doc-navy);font-size:10px}.info-card p{margin:3px 0;color:var(--doc-muted);font-size:8.3px;line-height:1.4}.info-card .next-step{margin-top:7px;color:var(--doc-orange);font-weight:900}.document-summary{display:grid;margin:0}.document-summary div{display:flex;justify-content:space-between;gap:20px;padding:4px 7px;color:var(--doc-muted);font-size:9px}.document-summary b{color:var(--doc-navy)}.document-summary .total{margin-top:3px;padding:8px 9px;border-radius:6px;background:var(--doc-navy);color:#fff;font-size:12px;font-weight:900}.document-summary .total b{color:#fff}.document-summary .balance{margin-top:3px;color:var(--doc-orange);font-size:10px;font-weight:900}.document-summary .balance b{color:var(--doc-orange)}
.document-notes{display:grid;grid-template-columns:1fr 1fr;gap:20px;margin-top:11px;padding-top:9px;border-top:1px solid var(--doc-line)}.document-notes h4{margin:0 0 3px;color:var(--doc-navy);font-size:9px}.document-notes p{margin:0;color:var(--doc-muted);font-size:7.8px;line-height:1.4}.document-footer{display:flex;justify-content:space-between;gap:15px;margin-top:12px;padding-top:8px;border-top:1px solid var(--doc-line);color:#8598a8;font-size:7.5px}.document-footer strong{color:var(--doc-navy)}
.compact-output .document-items th,.compact-output .document-items td{padding-top:5px;padding-bottom:5px;font-size:7.8px}.compact-output .document-meta{padding:11px 0 9px}.compact-output .document-notes p{font-size:7px}
@media(max-width:650px){.customer-share{padding:10px}.share-toolbar{align-items:flex-start;flex-direction:column}.share-actions{width:100%}.share-actions .button{flex:1;text-align:center}.customer-share .document-card{padding:24px 17px}.document-head,.brand-block{display:grid}.document-title{text-align:left}.document-meta,.settlement,.document-notes{grid-template-columns:1fr}.document-facts dd{text-align:left}.service-strip{grid-template-columns:1fr}.table-wrap{overflow:auto}.document-items{min-width:560px}}
@page{size:A4 portrait;margin:8mm}
@media print{html,body{width:210mm;min-height:0;background:#fff}.share-toolbar{display:none!important}.customer-share{padding:0;background:#fff}.customer-share .document-card{width:100%;max-width:none;margin:0;padding:20px 23px 16px;border:0;box-shadow:none}.customer-share .document-card:before,.document-status,.document-items th,.document-summary .total,.service-strip div,.info-card{print-color-adjust:exact;-webkit-print-color-adjust:exact}.document-head{padding:5px 0 9px}.brand-block img{width:92px;height:53px}.brand-copy{font-size:7.6px}.brand-copy strong{font-size:9.5px}.document-title h1{font-size:21px}.document-status{margin-top:5px;padding:4px 8px;font-size:10px}.document-meta{gap:18px;padding:9px 0 7px}.customer-name{font-size:12px}.customer-copy,.document-facts dt,.document-facts dd{font-size:7.5px}.service-strip{margin-bottom:7px}.service-strip div{padding:5px 7px}.document-items th,.document-items td{padding:4px 6px;font-size:7.2px}.settlement{grid-template-columns:minmax(0,1fr) 238px;gap:18px;margin-top:7px}.info-card{padding:6px 8px}.info-card p{font-size:6.8px}.document-summary div{padding:2.5px 5px;font-size:7.5px}.document-summary .total{padding:5px 7px;font-size:9px}.document-summary .balance{font-size:8px}.document-notes{gap:14px;margin-top:6px;padding-top:5px}.document-notes p{font-size:6.5px}.document-footer{margin-top:6px;padding-top:5px}.service-strip,.settlement,.document-notes,.document-summary{break-inside:avoid}.document-items tr{break-inside:avoid}}
</style>
</head>
<body class="customer-share">
<div class="share-toolbar">
  <p>Secure <?=e(strtolower($documentLabel))?> copy from Soda ZW</p>
  <div class="share-actions">
    <?php if ($paynowUrl):?><a class="button primary" target="_blank" rel="noopener noreferrer" href="<?=e($paynowUrl)?>">Pay securely with Paynow</a><?php endif;?>
    <?php if ($showContactAction):?><a class="button green whatsapp-contact" target="_blank" rel="noopener" href="https://wa.me/<?=e($businessPhone)?>?text=<?=rawurlencode($contactText)?>"><?=e($contactLabel)?></a><?php endif;?>
    <button class="button primary" type="button" onclick="window.print()">Print / Save PDF</button>
  </div>
</div>

<article class="document-card <?=e(strtolower($documentLabel))?><?=$denseOutput ? ' compact-output' : ''?>">
  <header class="document-head">
    <div class="brand-block">
      <img src="assets/sodazw-logo-invoice.png" alt="Soda ZW">
      <div class="brand-copy"><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="document-title">
      <span><?=$isInvoice ? 'Official customer invoice' : ($isCredit?'Official customer credit':'Customer quotation')?></span>
      <h1><?=e($documentLabel)?></h1>
      <b class="document-number"><?=e($document['number'])?></b>
      <strong class="document-status <?=e($stateClass)?>"><?=e($documentState)?></strong>
      <small class="status-detail"><?=e($stateDetail)?></small>
    </div>
  </header>

  <section class="document-meta">
    <div>
      <span class="section-label"><?=$isInvoice ? 'Bill to' : 'Prepared for'?></span>
      <h2 class="customer-name"><?=e($document['customer_name'])?></h2>
      <p class="customer-copy"><?php if ($document['customer_company']):?><?=e($document['customer_company'])?><br><?php endif;?><?=e($document['customer_address'])?><?php if ($document['customer_city']):?><br><?=e($document['customer_city'])?><?php endif;?><?php if ($document['customer_phone']):?><br><?=e($document['customer_phone'])?><?php endif;?><?php if ($document['customer_email']):?><br><?=e($document['customer_email'])?><?php endif;?><?php if ($document['customer_tax']):?><br>Tax/VAT: <?=e($document['customer_tax'])?><?php endif;?></p>
    </div>
    <div>
      <span class="section-label">Document details</span>
      <dl class="document-facts">
        <dt>Issue date</dt><dd><?=e($formatDate($document['issue_date']))?></dd>
        <dt><?=$isInvoice ? 'Due date' : 'Valid until'?></dt><dd><?=e($dueDateLabel)?></dd>
        <dt>Currency</dt><dd><?=e($document['currency_code'])?></dd>
        <?php if ($document['customer_reference']):?><dt><?=$document['order_source'] === 'Historical import' ? 'Source invoice' : 'Reference'?></dt><dd><?=e($document['customer_reference'])?></dd><?php endif;?>
      </dl>
    </div>
  </section>

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

  <div class="table-wrap"><table class="document-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 $item):?><tr><td><?=e($item['description'])?></td><td><?=e($item['quantity'])?></td><td><?=money($item['unit_price'], $document['currency_code'])?></td><td><?=e($item['tax_rate'])?>%</td><td><?=money($item['line_total'], $document['currency_code'])?></td></tr><?php endforeach;?></tbody></table></div>

  <section class="settlement">
    <div class="info-card">
      <?php if ($isInvoice):?>
        <h3><?=$balance <= 0.009 ? 'Payment complete' : 'Payment information'?></h3>
        <?php if ($balance <= 0.009):?><p>This invoice is paid in full. Thank you.</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 class="next-step">Please quote invoice <?=e($document['number'])?> when paying.</p><?php endif;?>
      <?php elseif ($isCredit):?>
        <h3>Credit adjustment</h3>
        <p>This credit note has been applied against the original customer invoice.</p>
        <p class="next-step">Please retain it with the invoice for your records.</p>
      <?php else:?>
        <h3>Quotation validity</h3>
        <p><?=e($stateDetail)?>.</p>
        <p class="next-step">Please confirm acceptance with Soda ZW before fulfilment.</p>
      <?php endif;?>
    </div>
    <div class="document-summary">
      <div><span>Subtotal</span><b><?=money($document['subtotal'], $document['currency_code'])?></b></div>
      <?php if ((float)$document['discount_total'] > 0):?><div><span>Discount</span><b>-<?=money($document['discount_total'], $document['currency_code'])?></b></div><?php endif;?>
      <?php if ((float)$document['tax_total'] > 0):?><div><span>Tax</span><b><?=money($document['tax_total'], $document['currency_code'])?></b></div><?php endif;?>
      <?php if ((float)$document['delivery_fee'] > 0):?><div><span>Delivery</span><b><?=money($document['delivery_fee'], $document['currency_code'])?></b></div><?php endif;?>
      <div class="total"><span><?=$isInvoice ? 'Invoice total' : ($isCredit?'Credit total':'Quotation total')?></span><b><?=money($document['total'], $document['currency_code'])?></b></div>
      <?php if ($isInvoice):?><div><span>Payments received</span><b><?=money($paid, $document['currency_code'])?></b></div><?php if($credited>.009):?><div><span>Credits applied</span><b><?=money($credited,$document['currency_code'])?></b></div><?php endif;?><div class="balance"><span>Balance due</span><b><?=money($balance, $document['currency_code'])?></b></div><?php endif;?>
    </div>
  </section>

  <?php if ($document['notes'] || $document['terms']):?><section class="document-notes"><?php if ($document['notes']):?><div><h4>Notes</h4><p><?=nl2br(e($document['notes']))?></p></div><?php endif;?><?php if ($document['terms']):?><div><h4><?=$isInvoice ? 'Terms' : 'Quotation terms'?></h4><p><?=nl2br(e($document['terms']))?></p></div><?php endif;?></section><?php endif;?>
  <footer class="document-footer"><span><strong>Soda ZW</strong> · Join the sparkle movement</span><span><?=e($document['number'])?> · Secure customer copy</span></footer>
</article>
</body>
</html>
