<?php
requirePermission($conn, 'quotations', 'open');
$id = isset($_GET['id']) ? (int)$_GET['id'] : 0;
if (!$id) { echo '<div class="card" style="padding:20px">Quotation not found.</div>'; return; }
$sql = "SELECT q.*, c.customer_name, c.business_name AS customer_business, c.phone AS customer_phone, c.email AS customer_email, c.address AS customer_address,
               i.name AS item_name,
               a.client_name AS account_client_name, a.business_name AS account_business_name, a.phone AS account_phone, a.email AS account_email, a.currency AS account_currency, a.logo AS account_logo
        FROM quotations q
        LEFT JOIN customers c ON c.id=q.customer_id
        LEFT JOIN items i ON i.id=q.item_id
        LEFT JOIN accounts a ON a.id=q.account_id
        WHERE q.id=$id AND q.account_id=$account_id LIMIT 1";
$res = $conn->query($sql);
if (!$res || !$res->num_rows) { echo '<div class="card" style="padding:20px">Quotation not found.</div>'; return; }
$d = $res->fetch_assoc();
$currency = $d['account_currency'] ?: 'USD';
$printNow = isset($_GET['print']);
$qItems = [];
if (tableExists($conn, 'quotation_items')) {
    $iq = $conn->query("SELECT qi.*, i.name item_name, i.currency item_currency FROM quotation_items qi LEFT JOIN items i ON i.id=qi.item_id WHERE qi.quotation_id=$id ORDER BY qi.id");
    while ($iq && $ir = $iq->fetch_assoc()) $qItems[] = $ir;
}
if (!$qItems) {
    $qItems[] = ['item_name'=>$d['item_name'], 'quantity'=>$d['quantity'], 'unit_price'=>$d['unit_price'], 'line_total'=>((float)$d['quantity']*(float)$d['unit_price']), 'item_currency'=>$currency];
}
$subTotal = 0;
foreach ($qItems as $ir) $subTotal += (float)($ir['line_total'] ?? ((float)$ir['quantity']*(float)$ir['unit_price']));
?>
<style>
.invoice-actions{max-width:980px;margin:0 auto 14px;display:flex;gap:8px;justify-content:flex-end}.invoice-wrap{max-width:980px;margin:0 auto;background:#fff;border:1px solid var(--border);border-radius:18px;overflow:hidden;box-shadow:var(--shadow-sm)}.invoice-head{display:flex;justify-content:space-between;gap:20px;padding:30px;border-bottom:1px solid var(--border);background:linear-gradient(135deg,#f8fafc,#fff)}.invoice-logo{max-width:170px;max-height:90px;object-fit:contain;margin-bottom:10px}.invoice-title{font-size:32px;font-weight:900;color:var(--primary);margin:0;text-align:right}.invoice-no{text-align:right;color:var(--text-muted);font-size:13px;margin-top:5px}.invoice-body{padding:28px}.invoice-grid{display:grid;grid-template-columns:1fr 1fr;gap:18px;margin-bottom:24px}.invoice-box{background:var(--bg-base);border:1px solid var(--border);border-radius:14px;padding:20px}.invoice-box h4{margin:0 0 10px;color:var(--text-muted);font-size:12px;text-transform:uppercase;letter-spacing:.04em}.invoice-table{width:100%;border-collapse:collapse;margin-top:16px;border:1px solid var(--border);border-radius:14px;overflow:hidden}.invoice-table th{background:#4f8794;color:#fff;text-align:left;padding:14px;font-size:13px;text-transform:uppercase}.invoice-table td{border-bottom:1px solid var(--border);padding:14px;vertical-align:top}.invoice-table tr:last-child td{border-bottom:0}.invoice-table th:first-child,.invoice-table td:first-child{width:55px;text-align:center;font-weight:800}.invoice-table .desc-cell{color:var(--text-muted);font-size:12px;margin-top:3px}.invoice-total{max-width:390px;margin-left:auto;margin-top:18px}.invoice-total-row{display:flex;justify-content:space-between;padding:10px 0;border-bottom:1px solid var(--border)}.invoice-total-row.grand{font-size:20px;font-weight:900;color:var(--primary);border-bottom:0}.invoice-notes{margin-top:24px;background:#f8fafc;border:1px solid var(--border);border-radius:14px;padding:18px}
@media print{#sidebar,#top-header,.invoice-actions{display:none!important}#main-content{margin:0!important}.invoice-wrap{box-shadow:none;border:0;border-radius:0}.invoice-head,.invoice-body{padding:22px}body{background:#fff}.page-breadcrumb,.page-title-area{display:none!important}}
@media(max-width:700px){.invoice-head,.invoice-grid{grid-template-columns:1fr;display:grid}.invoice-title,.invoice-no{text-align:left}.invoice-body{padding:16px}.invoice-table{font-size:13px}}
</style>
<div class="invoice-actions"><a href="index.php?page=quotations" class="btn btn-secondary">← Back</a><button class="btn btn-primary" onclick="window.print()">Print</button></div>
<div class="invoice-wrap">
  <div class="invoice-head">
    <div><?php if(!empty($d['account_logo'])): ?><img class="invoice-logo" src="<?= htmlspecialchars($d['account_logo']) ?>" alt="Logo"><?php endif; ?><h3 style="margin:0"><?= htmlspecialchars($d['account_business_name'] ?: $d['account_client_name'] ?: 'Company') ?></h3><div class="text-muted text-xs"><?= htmlspecialchars($d['account_phone'] ?: '') ?> <?= htmlspecialchars($d['account_email'] ?: '') ?></div></div>
    <div><h1 class="invoice-title">QUOTATION</h1><div class="invoice-no">QT-<?= str_pad($d['id'],5,'0',STR_PAD_LEFT) ?><br><?= formatDate($d['date_created']) ?></div></div>
  </div>
  <div class="invoice-body">
    <div class="invoice-grid">
      <div class="invoice-box"><h4>Customer</h4><strong><?= htmlspecialchars($d['customer_name'] ?: '—') ?></strong><br><?= htmlspecialchars($d['customer_business'] ?: '') ?><br><?= htmlspecialchars($d['customer_phone'] ?: '') ?><br><?= htmlspecialchars($d['customer_email'] ?: '') ?><br><?= nl2br(htmlspecialchars($d['customer_address'] ?: '')) ?></div>
      <div class="invoice-box"><h4>Details</h4>Valid until: <?= htmlspecialchars($d['valid_until'] ?: '—') ?><br>Currency: <?= htmlspecialchars($currency) ?><br>Status: <?= htmlspecialchars(ucfirst($d['status'])) ?><?php if(!empty($d['customer_details'])): ?><br><br><?= nl2br(htmlspecialchars($d['customer_details'])) ?><?php endif; ?></div>
    </div>
    <table class="invoice-table"><thead><tr><th>#</th><th>Name / Desc</th><th style="width:150px">Unit Price</th><th style="width:90px">Qty</th><th style="width:150px">Total</th></tr></thead><tbody><?php $n=1; foreach($qItems as $ir): $cur=$ir['item_currency'] ?: $currency; $qty=(float)($ir['quantity'] ?? 1); $unit=(float)($ir['unit_price'] ?? 0); $line=(float)($ir['line_total'] ?? ($qty*$unit)); ?><tr><td><?= $n++ ?></td><td><strong><?= htmlspecialchars($ir['item_name'] ?: '—') ?></strong><?php if(!empty($ir['description'])): ?><div class="desc-cell"><?= htmlspecialchars($ir['description']) ?></div><?php endif; ?></td><td><?= crmMoney($unit, $cur ?: $currency) ?></td><td><?= rtrim(rtrim(number_format($qty,2), '0'), '.') ?></td><td><?= crmMoney($line, $cur ?: $currency) ?></td></tr><?php endforeach; ?></tbody></table>
    <div class="invoice-total"><div class="invoice-total-row"><span>Subtotal</span><strong><?= crmMoney($subTotal, $currency) ?></strong></div><div class="invoice-total-row"><span>Discount</span><strong><?= crmMoney($d['discount'], $currency) ?></strong></div><div class="invoice-total-row"><span>TVA <?= number_format((float)$d['tva_percent'],2) ?>%</span><strong><?= crmMoney($d['tva_value'], $currency) ?></strong></div><div class="invoice-total-row grand"><span>Total</span><span><?= crmMoney($d['total'], $currency) ?></span></div></div>
    <?php if(!empty($d['notes'])): ?><div class="invoice-notes"><strong>Notes</strong><br><?= nl2br(htmlspecialchars($d['notes'])) ?></div><?php endif; ?>
  </div>
</div>
<?php if($printNow): ?><script>setTimeout(()=>window.print(),350);</script><?php endif; ?>
