<?php
require_once __DIR__ . '/config.php';
require_once __DIR__ . '/includes/auth.php';
require_once __DIR__ . '/includes/db.php';
require_login();

$mysqli = db();
$id = (int)($_GET['id'] ?? 0);
if (!$id) { die('Missing id'); }
// Print tuning: page margin (mm) and inner padding (mm)
$pageMargin = isset($_GET['m']) ? max(0, min(25, (int)$_GET['m'])) : 5; // mm (default 1cm)
$innerPad   = isset($_GET['pad']) ? max(0, min(25, (int)$_GET['pad'])) : 5; // mm

function fmt_currency($code, $n){
  $v = number_format((float)$n, 2, '.', ',');
  $c = strtoupper((string)$code);
  switch ($c) {
    case 'USD': return '$' . $v;
    case 'LKR': return 'LKR ' . $v;
    case 'INR': return '₹' . $v;
    case 'AED': return 'د.إ' . $v;
    case 'CNY': return '¥' . $v;
    default: return ($c ? $c.' ' : '') . $v;
  }
}

// Fetch PO header
$stmt = $mysqli->prepare('SELECT po.*, s.name AS supplier_name, s.address AS supplier_address, s.country AS supplier_country, s.phone AS supplier_phone, s.email AS supplier_email_db, s.currency AS supplier_currency FROM purchase_orders po LEFT JOIN suppliers s ON s.id = po.supplier_id WHERE po.id = ?');
$stmt->bind_param('i', $id);
$stmt->execute();
$po = $stmt->get_result()->fetch_assoc();
if (!$po) { die('PO not found'); }

// Items
$it = $mysqli->prepare('SELECT line_no, description, hs_code, quantity, unit, unit_price, line_total FROM purchase_order_items WHERE po_id = ? ORDER BY line_no ASC');
$it->bind_param('i', $id);
$it->execute();
$items = $it->get_result();

$total = 0.0;
$rows = [];
while ($row = $items->fetch_assoc()) { $rows[] = $row; $total += (float)$row['line_total']; }

// Load shop settings (single row)
$settings = [
  'company_name' => 'Granite Warehouse',
  'address_line' => 'Warehouse Address Line',
  'city_country' => 'City, Country',
  'phone' => '-',
];
$resSet = $mysqli->query('SELECT company_name, address_line, city_country, phone FROM shop_settings ORDER BY id ASC LIMIT 1');
if ($resSet && $rowS = $resSet->fetch_assoc()) {
  $settings = array_merge($settings, $rowS);
}
?>
<!doctype html>
<html>
<head>
  <meta charset="utf-8">
  <title>Purchase Order - <?php echo htmlspecialchars($po['order_no']); ?></title>
  <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
  <style>
    /* Print to A4 portrait with configurable margins; we control inner padding */
    @page { size: A4 portrait; margin: <?php echo $pageMargin; ?>mm; }
    html, body { background: #fff; }
    body { font-size: 13px; margin: 0; }
    /* Minimal fallback utilities (do not rely on external Bootstrap when printing) */
    .container { width: 100%; margin: 0 auto; }
    .mb-3 { margin-bottom: .6rem !important; }
    .my-4 { margin-top: .8rem !important; margin-bottom: .8rem !important; }
    .text-center { text-align: center; }
    .text-end { text-align: right; }
    .no-print { display: inline-block; }
    .align-middle { vertical-align: middle !important; }
    .table { width: 100%; border-collapse: collapse; }
    .table-bordered th, .table-bordered td { border: 1px solid #000; }
    /* Fixed A4 canvas with inner padding so print is exactly as designed */
    html, body { width: 210mm; }
    .a4 { width: 210mm; height: 297mm; padding: <?php echo $innerPad; ?>mm; margin: 0 auto; box-sizing: border-box; }
    /* Neutralize Bootstrap container constraints on print */
    @media print {
      /* Ensure buttons and non-print elements hidden */
      .no-print { display: none !important; }
      html, body { width: 210mm !important; height: 297mm !important; }
      .container { width: 210mm !important; max-width: none !important; padding-left: 0 !important; padding-right: 0 !important; }
      .row { --bs-gutter-x: .4rem; --bs-gutter-y: .4rem; }
    }
    /* Dark green-blue theme for headers */
    .section-title { background: #0b5f4a; color: #fff; padding: 3px 6px; font-weight: 600; font-size: 13px; }
    .box { border: 1px solid #dcdcdc; padding: 8px; min-height: 90px; page-break-inside: avoid; }
    .po-table { font-size: 12px; table-layout: fixed; border-collapse: collapse; width: 100%; }
    .po-table thead th { background: #0b5f4a; color: #fff; }
    .po-table th, .po-table td { padding: 4px 6px !important; vertical-align: top; word-break: normal; overflow-wrap: anywhere; border: 1px solid #000 !important; }
    .mb-3 { margin-bottom: .6rem !important; }
    .my-4 { margin-top: .8rem !important; margin-bottom: .8rem !important; }
    .g-3 { --bs-gutter-y: .6rem; --bs-gutter-x: .6rem; }
    /* Print-safe fixed grid to avoid stacking at print time */
    .pp-row { display: flex; gap: 12px; }
    .pp-row .pp-col { flex: 0 0 auto; }
    .pp-row.pp-3 .pp-col { width: calc((100% - 24px) / 3); }
    .pp-row.pp-2 .pp-col { width: calc((100% - 12px) / 2); }
    /* Spacer to push content down for pre-printed letterhead */
    .letterhead-spacer { height: 50mm; }
    @media print {
      .pp-row { display: flex !important; gap: 12px !important; }
      .pp-row.pp-3 .pp-col { width: calc((100% - 24px) / 3) !important; }
      .pp-row.pp-2 .pp-col { width: calc((100% - 12px) / 2) !important; }
    }
    /* Repeat table headers on each printed page */
    thead { display: table-header-group; }
    tfoot { display: table-footer-group; }
    /* Avoid breaking key elements */
    .row, .table-responsive, .po-header { page-break-inside: avoid; }
    tr, td, th { page-break-inside: avoid; page-break-after: auto; }
    @media print {
      .no-print { display: none !important; }
      body { -webkit-print-color-adjust: exact; print-color-adjust: exact; }
    }
  </style>
</head>
<body class="bg-white">
  <div class="container my-4 a4">
    <div class="letterhead-spacer"></div>
    <div class="d-flex justify-content-between align-items-center mb-3">
      <h4 class="mb-0">PURCHASE ORDER</h4>
      <button class="btn btn-primary no-print" onclick="window.print()">Print</button>
    </div>

    <div class="pp-row pp-3 mb-3">
      <div class="pp-col">
        <div class="section-title">IMPORTER</div>
        <div class="box small">
          <div><strong>STEP WORLD TRADE SOLUTION (PVT) LTD</strong></div>
          <div>390/7H, EKAMUTHU MAWATHA, THALANGAMA NORTH, BATTARAMULLA,100604</div>
          <div>SRILANKA</div>
          <div>Phone: <?php echo htmlspecialchars($settings['phone']); ?></div>
        </div>
      </div>
      <div class="pp-col">
        <div class="section-title">EXPORTER</div>
        <div class="box small">
          <div><strong><?php echo htmlspecialchars($po['supplier_name']); ?></strong></div>
          <?php if(!empty($po['supplier_address'])): ?><div><?php echo nl2br(htmlspecialchars($po['supplier_address'])); ?></div><?php endif; ?>
          <?php if(!empty($po['supplier_country'])): ?><div><?php echo htmlspecialchars($po['supplier_country']); ?></div><?php endif; ?>
          <?php if(!empty($po['supplier_email'])): ?><div>Email: <?php echo htmlspecialchars($po['supplier_email']); ?></div><?php endif; ?>
          <?php if(!empty($po['supplier_phone'])): ?><div>Phone: <?php echo htmlspecialchars($po['supplier_phone']); ?></div><?php endif; ?>
          <?php if(!empty($po['tax_id'])): ?><div>GSTIN: <?php echo htmlspecialchars($po['tax_id']); ?></div><?php endif; ?>
        </div>
      </div>
      <div class="pp-col">
        <div class="section-title">PURCHASE ORDER INFO</div>
        <div class="box small">
          <div><strong>Date:</strong> <?php echo htmlspecialchars($po['order_date']); ?></div>
          <div><strong>PO Number:</strong> <?php echo htmlspecialchars($po['order_no']); ?></div>
          <div><strong>Ship Mode:</strong> <?php echo htmlspecialchars($po['ship_mode'] ?? ''); ?></div>
          <div><strong>Delivery Term:</strong> <?php echo htmlspecialchars($po['delivery_term'] ?? ''); ?></div>
          <div><strong>Payment Term:</strong> <?php echo htmlspecialchars($po['payment_term'] ?? ''); ?></div>
        </div>
      </div>
    </div>

    <div class="pp-row pp-2 mb-3">
      <div class="pp-col">
        <div class="section-title">SHIP TO</div>
        <div class="box small">
          <div><strong>STEP WORLD TRADE SOLUTION (PVT) LTD</strong></div>
          <div>390/7H, EKAMUTHU MAWATHA, THALANGAMA NORTH, BATTARAMULLA,100604</div>
          <div>SRILANKA</div>
          <div>Phone: <?php echo htmlspecialchars($settings['phone']); ?></div>
        </div>
      </div>
      <div class="pp-col">
        <div class="section-title">SUPPLIER CONTACT</div>
        <div class="box small">
          <div><strong>Contact:</strong> <?php echo htmlspecialchars($po['supplier_contact'] ?? ''); ?></div>
          <div><strong>Email:</strong> <?php echo htmlspecialchars($po['supplier_email'] ?? $po['supplier_email_db'] ?? ''); ?></div>
          <div><strong>Expected Delivery:</strong> <?php echo htmlspecialchars($po['expected_date'] ?? ''); ?></div>
          <div><strong>Status:</strong> <?php echo htmlspecialchars(ucfirst($po['status'])); ?></div>
        </div>
      </div>
    </div>

    <div class="table-responsive">
      <table class="table table-bordered po-table align-middle">
        <thead>
          <tr>
            <th style="width:60px;">NO</th>
            <th style="width:40%;">ITEMS DESCRIPTION</th>
            <th style="width:110px;">HS CODE</th>
            <th style="width:120px;">QUANTITY(SQM)</th>
            <th style="width:130px;">UNIT PRICE(USD)</th>
            <th style="width:140px;">TOTAL VALUE</th>
          </tr>
        </thead>
        <tbody>
          <?php if (empty($rows)): ?>
            <tr><td colspan="7" class="text-center text-muted">NO ITEMS</td></tr>
          <?php else: ?>
            <?php foreach ($rows as $i => $r): ?>
              <tr>
                <td class="text-center"><?php echo str_pad((string)($i+1), 2, '0', STR_PAD_LEFT); ?></td>
                <td><?php echo nl2br(htmlspecialchars($r['description'])); if ($i===0 && !empty($po['notes'])) { echo '<div class="mt-1">'.nl2br(htmlspecialchars($po['notes'])).'</div>'; } ?></td>
                <td><?php echo htmlspecialchars($r['hs_code']); ?></td>
                <td><?php echo number_format((float)$r['quantity'], 3); ?></td>
                <td><?php echo fmt_currency($po['supplier_currency'] ?? 'USD', $r['unit_price']); ?></td>
                <td><?php echo fmt_currency($po['supplier_currency'] ?? 'USD', $r['line_total']); ?></td>
              </tr>
            <?php endforeach; ?>
          <?php endif; ?>
        </tbody>
        <tfoot>
          <tr>
            <td colspan="5" class="text-end"><strong>TOTAL</strong></td>
            <td><strong><?php echo fmt_currency($po['supplier_currency'] ?? 'USD', $total); ?></strong></td>
          </tr>
        </tfoot>
      </table>
    </div>


  </div>
  <script>
    // No scaling: prints as-is with A4 margins controlled by @page
  </script>
</body>
</html>
