<?php
include $_SERVER['DOCUMENT_ROOT'] . "/WebBuilder/WebApp.class.php";

if (!isset($_GET['record_id'])) { die("No invoice specified."); }

$db = new DBMain();

// Fetch invoice
$invoice_res = $db->exec_query('invoices', ['*'], '', '', '', '', "record_id = " . intval($_GET['record_id']));
$invoice     = $invoice_res->fetch_assoc();
if (!$invoice) { die("Invoice not found."); }

$invoice_number = $invoice['invoice_no'];
$date_created   = $invoice['date_created'];
$date_due       = $invoice['date_due'];
$description    = $invoice['description'];
$total          = number_format($invoice['total'], 2, '.', ',');

// Line items
$content_array = explode(';', $invoice['invoice_content']);
$content_rows  = '';
foreach ($content_array as $line) {
    if (strlen($line) > 2) {
        $info = explode(',', $line);
        $content_rows .= "
        <tr>
            <td>{$info[0]}</td>
            <td class='num'>{$info[1]}</td>
            <td class='num'>R " . number_format($info[2], 2, '.', ',') . "</td>
            <td class='num'>{$info[3]}</td>
            <td class='num'><strong>R " . number_format($info[4], 2, '.', ',') . "</strong></td>
        </tr>";
    }
}

// Company
$company_res  = $db->exec_query('company', ['*']);
$company      = $company_res->fetch_assoc();

// Client
$client_res = $db->exec_query('clients', ['*'], '', '', '', '', "record_id = {$invoice['clients_id']}");
$client     = $client_res->fetch_assoc();
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Invoice #<?= $invoice_number ?></title>
<style>
  * { box-sizing: border-box; margin: 0; padding: 0; }

  body {
    font-family: Arial, sans-serif;
    background: #e8e8e8;
    display: flex;
    flex-direction: column;
    height: 100vh;
    overflow: hidden;
  }

  /* ── Toolbar ── */
   .toolbar {
    margin-bottom: 1vw;
    border: 1px solid #04AA6D;
    position: relative;
    background-color: #f5f5f5;
    height: fit-content;
    text-align: center;
    border-radius: 2vw;
    margin-left: auto;
    margin-right: auto;
  }
  /* .toolbar {
    display: flex;
    align-items: center;
    gap: 10px;
    padding: 10px 16px;
    background: #1a1a2e;
    color: #fff;
    flex-shrink: 0;
    box-shadow: 0 2px 8px rgba(0,0,0,0.3);
  } */
  .toolbar .inv-title {
    font-size: 2em;
    font-weight: 700;
    flex: 1;
    letter-spacing: 0.05em;
  }
  .toolbar button {
    padding: 7px 16px;
    border: none;
    border-radius: 5px;
    cursor: pointer;
    font-size: 15px;
    font-weight: 600;
    transition: opacity 0.15s;
    border: 2px solid #2c6e49;
  }
  .toolbar button:hover { opacity: 0.85; }
  /* .btn-home     { background: #4a4a6a; color: #fff; } */
  /* .btn-download { background: #2c6e49; color: #fff; } */
  /* .btn-print    { background: #1971c2; color: #fff; } */

  /* ── Scrollable invoice area ── */
  .scroll-area {
    flex: 1;
    overflow-y: auto;
    padding: 24px 16px;
    display: flex;
    justify-content: center;
  }

  /* ── Invoice paper ── */
  .invoice-paper {
    background: #fff;
    width: 100%;
    max-width: 820px;
    height: fit-content;
    padding: 20px;
    box-shadow: 0 4px 24px rgba(0,0,0,0.15);
    border-radius: 6px;
  }

  /* Header */
  .inv-header {
    display: flex;
    justify-content: space-between;
    align-items: flex-start;
    margin-bottom: 28px;
    border-bottom: 3px solid #111;
    padding-bottom: 20px;
  }
  .inv-header img { width: 180px; height: 80px; object-fit: contain; display: block; }
  .inv-header-right { text-align: right; }
  .inv-header-right h1 { font-size: 36px; font-weight: 900; letter-spacing: 2px; color: #111; }
  .inv-header-right .inv-no { font-size: 18px; font-weight: 700; color: #444; margin-top: 4px; }
  .inv-header-right .inv-dates { font-size: 12px; color: #666; margin-top: 8px; line-height: 2; }

  /* From / To */
  .parties {
    display: flex;
    gap: 20px;
    margin-bottom: 24px;
    background: #f8f8f8;
    border-radius: 6px;
    padding: 16px 20px;
  }
  .party { flex: 1; }
  .party label {
    font-size: 10px;
    text-transform: uppercase;
    letter-spacing: 0.12em;
    color: #999;
    display: block;
    margin-bottom: 6px;
  }
  .party .pname { font-size: 15px; font-weight: 700; color: #111; }
  .party .pdet  { font-size: 12px; color: #555; margin-top: 3px; line-height: 1.7; }

  /* Description */
  .inv-desc {
    font-size: 13px;
    color: #555;
    background: #f8f8f8;
    border-radius: 6px;
    padding: 12px 16px;
    margin-bottom: 20px;
    white-space: pre-wrap;
  }

  /* Line items table */
  .lt { width: 100%; border-collapse: collapse; margin-bottom: 20px; }
  .lt th {
    font-size: 10px;
    text-transform: uppercase;
    letter-spacing: 0.1em;
    color: #888;
    padding: 8px 10px;
    border-bottom: 2px solid #ddd;
    background: #f4f4f4;
    text-align: left;
  }
  .lt th.num, .lt td.num { text-align: right; }
  .lt td {
    padding: 10px 10px;
    font-size: 13px;
    border-bottom: 1px solid #eee;
    vertical-align: top;
  }
  .lt tr:last-child td { border-bottom: none; }

  /* Total */
  .inv-total {
    text-align: right;
    border-top: 2px solid #111;
    padding-top: 14px;
    margin-bottom: 28px;
  }
  .inv-total .tl { font-size: 11px; text-transform: uppercase; letter-spacing: 0.1em; color: #999; }
  .inv-total .tv { font-size: 30px; font-weight: 800; color: #111; margin-top: 4px; }

  /* Banking + deposit row */
  .inv-banking {
    display: flex;
    justify-content: space-between;
    align-items: flex-start;
    background: #f8f8f8;
    border-radius: 6px;
    padding: 16px 20px;
    font-size: 12px;
    color: #444;
    line-height: 2;
    margin-bottom: 28px;
  }
  .inv-banking b { color: #111; }

  /* T&Cs */
  .tc-block {
    border-top: 2px solid #ddd;
    padding-top: 20px;
    margin-top: 10px;
  }
  .tc-block h4 {
    font-size: 11px;
    text-transform: uppercase;
    letter-spacing: 0.1em;
    color: #999;
    margin-bottom: 10px;
  }
  .tc-section {
    background: #f8f8f8;
    border-radius: 6px;
    padding: 14px 18px;
    margin-bottom: 12px;
    font-size: 12px;
    color: #555;
    line-height: 1.8;
  }
  .tc-section span { color: #c00; font-weight: 700; display: block; margin-bottom: 6px; }

  /* Print styles */
  @media print {
    body { background: white; height: auto; overflow: visible; }
    .toolbar { display: none !important; }
    .scroll-area { overflow: visible; padding: 0; }
    .invoice-paper { box-shadow: none; border-radius: 0; max-width: 100%; padding: 20px; }
    .tc-block { page-break-before: always; }
  }
</style>
</head>
<body>

<!-- ── Toolbar ─────────────────────────────────────────────── -->
<div class="toolbar" style="display:flex; align-items: center; width:90%; padding: 2vw;">
  <span class="inv-title">Invoice #<?= $invoice_number ?></span>
  <div style="display:flex; justify-content: space-between; width: 25%;">
    <button class="btn-home"     onclick="goHome()">Home</button>
  </div>
</div>

<!-- ── Invoice paper ───────────────────────────────────────── -->
<div class="scroll-area">
<div class="invoice-paper" id="invoice-paper">

  <div class="inv-header">
    <img src="Logo.svg" alt="Logo" />
    <div class="inv-header-right">
      <h1>INVOICE</h1>
      <div class="inv-no">#<?= $invoice_number ?></div>
      <div class="inv-dates">
        <b>DATE:</b> <?= htmlspecialchars($date_created) ?><br>
        <b>DUE:</b> &nbsp;<?= htmlspecialchars($date_due) ?>
      </div>
    </div>
  </div>

  <div class="parties">
    <div class="party">
      <label>From</label>
      <div class="pname"><?= htmlspecialchars($company['company_name']) ?></div>
      <div class="pdet">
        <?= htmlspecialchars($company['email']) ?><br>
        <?= htmlspecialchars($company['phone']) ?><br>
        <?= htmlspecialchars($company['address']) ?>
      </div>
    </div>
    <div class="party" style="text-align:right;">
      <label>To</label>
      <div class="pname"><?= htmlspecialchars($client['clients_name']) ?></div>
      <div class="pdet">
        <?= htmlspecialchars($client['email']) ?><br>
        <?= htmlspecialchars($client['cell']) ?><br>
        <?= htmlspecialchars($client['address']) ?>
      </div>
    </div>
  </div>

  <?php if ($description): ?>
  <div class="inv-desc"><?= htmlspecialchars($description) ?></div>
  <?php endif; ?>

  <table class="lt">
    <thead>
      <tr>
        <th>Description</th>
        <th class="num">Quantity</th>
        <th class="num">Amount</th>
        <th class="num">Discount</th>
        <th class="num">Sub Total</th>
      </tr>
    </thead>
    <tbody>
      <?= $content_rows ?>
    </tbody>
  </table>

  <div class="inv-total">
    <div class="tl">Invoice Total</div>
    <div class="tv">R <?= $total ?></div>
  </div>

  <div class="inv-banking">
    <div>
      <b>BANK:</b> <?= htmlspecialchars($company['bank']) ?><br>
      <b>ACC:</b> <?= htmlspecialchars($company['acc']) ?><br>
      <b>BRANCH:</b> <?= htmlspecialchars($company['branch']) ?><br>
      <b>REFERENCE:</b> <?= $invoice_number ?><br>
      <b>EMAIL:</b> <?= htmlspecialchars($company['email']) ?>
    </div>
    <div style="text-align:right;max-width:300px;font-size:12px;color:#666;">
      70% deposit with ordering · 30% on collection<br>
      <span style="font-size:11px;">Delivery 4–6 weeks per sculpture after order approval.</span>
    </div>
  </div>

  <div class="tc-block">
    <h4>Terms &amp; Conditions</h4>
    <div class="tc-section">
      <span>NOTICE</span>
      All Orders are subject to acceptance by Pro Art Moldings. Acceptance of orders is based on the express condition
      that buyer agrees to all of the terms and conditions contained herein. Acceptance of delivery by buyer will
      constitute buyer's assent to these terms and conditions. These terms and conditions represent the complete
      agreement of the parties, and no terms or conditions in any way adding to, modifying, or otherwise changing the
      provisions stated herein shall be binding upon manufacturer unless made in writing, and signed and approved by
      an officer of manufacturer.
    </div>
    <div class="tc-section">
      <span>PRICES AND TERMS</span>
      All Pro Art Moldings products are made to order. Prices are subject to change without notice. All product prices
      are exclusive of other charges and are FOB shipping point at our workshop in Kiepersol, Mpumalanga, South Africa.
      A minimum deposit of 50% of the total purchase price is required to initiate order fulfillment. A service charge of
      2% per month will be added to all accounts not paid within 60 days from the date of invoice.
    </div>
    <div class="tc-section">
      <span>CANCELLATION POLICY</span>
      Orders may not be cancelled after ten (10) business days after deposit is received or purchase order accepted.
      After ten (10) business days, any deposit made is nonrefundable and may be applied to a future new order within
      ninety (90) days. Cancellations require prior written approval and confirmation from Pro Art Moldings.
    </div>
  </div>

</div><!-- /invoice-paper -->
</div><!-- /scroll-area -->

<script>
// ── Home: load index in this iframe ──────────────────────────
function goHome() {
  window.location.href = '/WebApp/index.php';
}

// ── PDF libs (lazy load) ──────────────────────────────────────
const PDF_LIBS = [
  'https://cdnjs.cloudflare.com/ajax/libs/html2canvas/1.4.1/html2canvas.min.js',
  'https://cdnjs.cloudflare.com/ajax/libs/jspdf/2.5.1/jspdf.umd.min.js',
];
let _libsLoading = null;
function loadPdfLibs() {
  if (typeof html2canvas !== 'undefined' && typeof window.jspdf !== 'undefined') return Promise.resolve();
  if (_libsLoading) return _libsLoading;
  _libsLoading = Promise.all(PDF_LIBS.map(src => new Promise((res, rej) => {
    const s = document.createElement('script');
    s.src = src; s.onload = res; s.onerror = () => rej(new Error('Failed: ' + src));
    document.head.appendChild(s);
  })));
  return _libsLoading;
}

// ── Save as PDF ───────────────────────────────────────────────
async function savePdf() {
  const btn  = document.getElementById('pdf-btn');
  const orig = btn.innerHTML;
  btn.disabled = true;
  btn.innerHTML = '⏳ Generating…';

  const paper = document.getElementById('invoice-paper');

  // Temporarily strip card chrome for a clean capture
  const restore = [];
  const setStyle = (el, prop, val) => {
    restore.push({ el, prop, was: el.style[prop] });
    el.style[prop] = val;
  };

  try {
    await loadPdfLibs();

    setStyle(paper, 'boxShadow',    'none');
    setStyle(paper, 'borderRadius', '0');
    setStyle(paper, 'padding',      '28px');

    const { jsPDF } = window.jspdf;
    const pdf   = new jsPDF({ orientation: 'portrait', unit: 'mm', format: 'a4' });
    const pageW = pdf.internal.pageSize.getWidth();
    const pageH = pdf.internal.pageSize.getHeight();

    // ── Page 1: invoice body (hide T&Cs) ──
    const tcBlock = document.querySelector('.tc-block');
    const tcWas   = tcBlock ? tcBlock.style.display : '';
    if (tcBlock) tcBlock.style.display = 'none';

    let canvas = await html2canvas(paper, { scale: 2, useCORS: true, backgroundColor: '#ffffff' });
    let imgH   = (canvas.height * pageW) / canvas.width;
    pdf.addImage(canvas.toDataURL('image/jpeg', 0.95), 'JPEG', 0, 0, pageW, Math.min(imgH, pageH));

    // ── Page 2: T&Cs only ──
    if (tcBlock) {
      tcBlock.style.display = tcWas;

      // Hide everything in paper except tcBlock
      const hidden = [];
      for (const child of paper.children) {
        if (child !== tcBlock) {
          hidden.push({ el: child, was: child.style.display });
          child.style.display = 'none';
        }
      }

      canvas = await html2canvas(paper, { scale: 2, useCORS: true, backgroundColor: '#ffffff' });
      imgH   = (canvas.height * pageW) / canvas.width;
      pdf.addPage('a4', 'portrait');
      pdf.addImage(canvas.toDataURL('image/jpeg', 0.95), 'JPEG', 0, 0, pageW, Math.min(imgH, pageH));

      hidden.forEach(({ el, was }) => el.style.display = was);
    }

    const filename = 'Invoice_<?= $invoice_number ?>_<?= preg_replace('/[^A-Za-z0-9]/', '_', $client['clients_name']) ?>.pdf';
    const blob = pdf.output('blob');

    // Call showSaveFilePicker on window.top to bypass iframe restriction
    const topWin  = (window.top && window.top !== window) ? window.top : window;
    const pickerFn = topWin.showSaveFilePicker?.bind(topWin);

    if (typeof pickerFn === 'function') {
      try {
        const handle   = await pickerFn({
          suggestedName: filename,
          types: [{ description: 'PDF Document', accept: { 'application/pdf': ['.pdf'] } }],
        });
        const writable = await handle.createWritable();
        await writable.write(blob);
        await writable.close();
        alert('✅ Saved: ' + handle.name);
        return;
      } catch(e) {
        if (e?.name === 'AbortError') return;
        console.warn('showSaveFilePicker failed, falling back', e);
      }
    }

    // Fallback: anchor download
    const url = URL.createObjectURL(blob);
    const a   = document.createElement('a');
    a.href = url; a.download = filename;
    document.body.appendChild(a); a.click();
    setTimeout(() => { a.remove(); URL.revokeObjectURL(url); }, 200);

  } catch(e) {
    alert('PDF error: ' + e.message);
  } finally {
    restore.forEach(({ el, prop, was }) => el.style[prop] = was);
    btn.innerHTML = orig;
    btn.disabled  = false;
  }
}
</script>
</body>
</html>