<?php require_once __DIR__ . '/../includes/auth.php'; require_login(); require_once __DIR__ . '/../includes/db.php'; require_once __DIR__ . '/../config.php';
$mysqli = db();
$id = (int)($_GET['id'] ?? 0);
if (!$id) { echo 'Missing id'; exit; }
$inv = $mysqli->query('SELECT i.*, c.name AS customer_name, c.address, c.phone, c.email, c.gst_no FROM invoices i JOIN customers c ON c.id=i.customer_id WHERE i.id='.(int)$id)->fetch_assoc();

// Get branch address from logged-in user's branch
$branch_id = $_SESSION['branch_id'] ?? null;
$branch = null;
if ($branch_id) {
  $stmt = $mysqli->prepare('SELECT name, address, phone FROM branches WHERE id = ?');
  $stmt->bind_param('i', $branch_id);
  $stmt->execute();
  $branch = $stmt->get_result()->fetch_assoc();
}
// Fallback to shop_settings if no branch
if (!$branch) {
  $settings = $mysqli->query('SELECT company_name, address_line, city_country, company_email, phone FROM shop_settings LIMIT 1')->fetch_assoc();
  $branch = [
    'name' => $settings['company_name'] ?? 'Your Company Name',
    'address' => ($settings['address_line'] ?? '') . ' ' . ($settings['city_country'] ?? ''),
    'phone' => $settings['phone'] ?? ''
  ];
}

if (!$inv) { echo 'Invoice not found'; exit; }
$items = [];
$sqlItems = "SELECT ii.description, ii.qty, ii.unit_price, ii.line_total,
    COALESCE(fp_po.order_no, cp_po.po_no) AS po_no
  FROM invoice_items ii
  LEFT JOIN final_products fp ON fp.id = ii.final_product_id
  LEFT JOIN purchase_orders fp_po ON fp_po.id = fp.po_id
  LEFT JOIN cut_pieces cp ON cp.id = ii.cut_piece_id
  LEFT JOIN cutting_jobs cj ON cj.id = cp.job_id
  LEFT JOIN final_products fp2 ON (cj.source_type='finished' AND fp2.id=cj.source_id)
  LEFT JOIN raw_material_products rmp_fp ON rmp_fp.id = fp2.rmp_id
  LEFT JOIN raw_material_products rmp_raw ON (cj.source_type='raw' AND rmp_raw.id=cj.source_id)
  LEFT JOIN cut_pieces cp2 ON (cj.source_type='cut_piece' AND cp2.id=cj.source_id)
  LEFT JOIN cutting_jobs pj ON pj.id = cp2.job_id
  LEFT JOIN final_products fp3 ON (pj.source_type='finished' AND fp3.id=pj.source_id)
  LEFT JOIN raw_material_products rmp_fp2 ON rmp_fp2.id = fp3.rmp_id
  LEFT JOIN raw_material_products rmp_raw2 ON (pj.source_type='raw' AND rmp_raw2.id=pj.source_id)
  LEFT JOIN purchase_orders po_fp ON po_fp.id = rmp_fp.po_id
  LEFT JOIN purchase_orders po_raw ON po_raw.id = rmp_raw.po_id
  LEFT JOIN purchase_orders po_fp2 ON po_fp2.id = rmp_fp2.po_id
  LEFT JOIN purchase_orders po_raw2 ON po_raw2.id = rmp_raw2.po_id
  LEFT JOIN (
    SELECT cp_inner.id,
           COALESCE(po_fp_inner.order_no, po_raw_inner.order_no, po_fp2_inner.order_no, po_raw2_inner.order_no) AS po_no
    FROM cut_pieces cp_inner
    LEFT JOIN cutting_jobs cj_inner ON cj_inner.id = cp_inner.job_id
    LEFT JOIN final_products fp_inner ON (cj_inner.source_type='finished' AND fp_inner.id=cj_inner.source_id)
    LEFT JOIN raw_material_products rmp_fp_inner ON rmp_fp_inner.id = fp_inner.rmp_id
    LEFT JOIN raw_material_products rmp_raw_inner ON (cj_inner.source_type='raw' AND rmp_raw_inner.id=cj_inner.source_id)
    LEFT JOIN cut_pieces cp2_inner ON (cj_inner.source_type='cut_piece' AND cp2_inner.id=cj_inner.source_id)
    LEFT JOIN cutting_jobs pj_inner ON pj_inner.id = cp2_inner.job_id
    LEFT JOIN final_products fp2_inner ON (pj_inner.source_type='finished' AND fp2_inner.id=pj_inner.source_id)
    LEFT JOIN raw_material_products rmp_fp2_inner ON rmp_fp2_inner.id = fp2_inner.rmp_id
    LEFT JOIN raw_material_products rmp_raw2_inner ON (pj_inner.source_type='raw' AND rmp_raw2_inner.id=pj_inner.source_id)
    LEFT JOIN purchase_orders po_fp_inner ON po_fp_inner.id = rmp_fp_inner.po_id
    LEFT JOIN purchase_orders po_raw_inner ON po_raw_inner.id = rmp_raw_inner.po_id
    LEFT JOIN purchase_orders po_fp2_inner ON po_fp2_inner.id = rmp_fp2_inner.po_id
    LEFT JOIN purchase_orders po_raw2_inner ON po_raw2_inner.id = rmp_raw2_inner.po_id
  ) AS cp_po ON cp_po.id = cp.id
  WHERE ii.invoice_id = ".(int)$id;
$res=$mysqli->query($sqlItems);
while($r=$res->fetch_assoc()){ $items[]=$r; }
$payments = [];$sumPaid = 0.0; $res2=$mysqli->query('SELECT pay_date, method, reference_no, amount FROM payments WHERE invoice_id='.(int)$id.' ORDER BY id');
while($r2=$res2->fetch_assoc()){ $payments[]=$r2; $sumPaid += (float)$r2['amount']; }
$balance = max(0, (float)$inv['grand_total'] - $sumPaid);
?><!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Invoice <?php echo htmlspecialchars($inv['invoice_no']); ?></title>
<style>
  @page { size: A4; margin: 18mm; }
  body { font-family: Arial, sans-serif; color:#222; margin:0; }
  /* Repeat this header on each printed page */
  .print-header { display: table-header-group; }
  .header { width:210mm;display:flex; justify-content:space-between; align-items:flex-start; margin-bottom: 10px; }
  .header .right { margin-left:auto; text-align:right; }
  .logo { display:block; max-height:60px; max-width:180px; object-fit:contain; margin-left:auto; margin-bottom:6px; }
  .company { font-size: 18px; font-weight: 700; }
  .muted { color:#6c757d; }
  table { width:100%; border-collapse: collapse; }
  th, td { padding: 8px; border-bottom: 1px solid #e5e5e5; }
  th { background:#f8f9fa; text-align:left; }
  .totals { width: 360px; margin-left:auto; }
  .text-end { text-align:right; }
  .text-center { text-align:center; }
  .small { font-size: 12px; }
  .mb-2 { margin-bottom: 8px; }
  .mb-3 { margin-bottom: 12px; }
  .mt-2 { margin-top: 8px; }
  .badge { display:inline-block; padding:2px 6px; background:#e9ecef; border-radius:4px; font-size:12px; }
  .footer { margin-top: 28px; font-size: 12px; color:#6c757d; }
  .title { font-size: 24px; font-weight:700; }
  .sig { margin-top: 80px; display:flex; justify-content:flex-end; }
  .sig .line { width: 320px; border-top: 1px solid #000; text-align:center; padding-top:8px; font-size: 12px; }
</style>
</head>
<body>
  <div class="print-header">
    <div class="text-center title">INVOICE</div>
    <div class="header">
      <div>
        <div class="small">Invoice No: <strong><?php echo htmlspecialchars($inv['invoice_no']); ?></strong></div>
        <div class="small">Date: <?php echo htmlspecialchars($inv['invoice_date']); ?></div>
        <div class="small">Status: <span class="badge"><?php echo htmlspecialchars($inv['status']); ?></span></div>
      </div>
      <div class="right">
        <img class="logo" src="../assets/uploads/logo/logo_20251025_110009_f7c7ff84.png" alt="SW Logo" onerror="this.style.display='none'">
        <div class="company"><?php echo htmlspecialchars($branch['name'] ?? 'SW Granite'); ?></div>
        <div class="small"><?php echo nl2br(htmlspecialchars(trim($branch['address'] ?? ''))); ?></div>
        <div class="small"><?php echo htmlspecialchars($branch['phone'] ?? ''); ?> </div>
      </div>
    </div>
    <div class="mb-2" style="display:flex; gap:40px;">
      <div style="flex:1;">
        <div><strong><?php echo htmlspecialchars($inv['customer_name']); ?></strong></div>
        <div class="small"><?php echo nl2br(htmlspecialchars($inv['address'] ?? '')); ?></div>
        <div class="small"><?php echo htmlspecialchars($inv['phone'] ?? ''); ?> <?php echo htmlspecialchars($inv['email'] ?? ''); ?></div>
      </div>
    </div>
  </div>

  <table>
    <thead><tr><th>#</th><th>Description</th><th class="text-end">Qty</th><th class="text-end">Unit (LKR)</th><th class="text-end">Line (LKR)</th></tr></thead>
    <tbody>
      <?php $i=1; 
      foreach ($items as $it): ?>
      <tr>
        <td><?php echo htmlspecialchars($i); ?></td>
        <td>
          <?php echo htmlspecialchars($it['description']); ?>
          <!-- <?php if (!empty($it['po_no'])): ?>
            <div class="small muted">PO: <?php echo htmlspecialchars($it['po_no']); ?></div>
          <?php endif; ?> -->
        </td>
        <td class="text-end"><?php echo htmlspecialchars($it['qty']); ?></td>
        <td class="text-end"><?php echo number_format((float)$it['unit_price'], 2); ?></td>
        <td class="text-end"><?php echo number_format((float)$it['line_total'], 2); ?></td>
      </tr>
      <?php 
    $i++;
    endforeach; ?>
    </tbody>
  </table>

  <table class="totals mt-2">
    <tr><td>Subtotal</td><td class="text-end">LKR <?php echo number_format((float)$inv['subtotal'], 2); ?></td></tr>
    <tr><td>Tax (<?php echo number_format((float)$inv['tax_percent'],2); ?>%)</td><td class="text-end">LKR <?php echo number_format((float)$inv['tax_amount'], 2); ?></td></tr>
    <tr><td>Transport</td><td class="text-end">LKR <?php echo number_format((float)$inv['transport_charges'], 2); ?></td></tr>
    <tr><td>Discount</td><td class="text-end">LKR <?php echo number_format((float)$inv['discount'], 2); ?></td></tr>
    <tr><th>Total</th><th class="text-end">LKR <?php echo number_format((float)$inv['grand_total'], 2); ?></th></tr>
    <tr><td>Paid</td><td class="text-end">LKR <?php echo number_format((float)$sumPaid, 2); ?></td></tr>
    <tr><th>Balance</th><th class="text-end">LKR <?php echo number_format((float)$balance, 2); ?></th></tr>
  </table>

  
  <div class="sig">
    <div class="line">Authorized Signature</div>
  </div>

  <div class="footer">
    Thank you for your business.
  </div>

  <script>window.print();</script>
</body>
</html>
