<?php
require 'header.php';
require 'db.php';

// logo URL (remote or change to local path like 'uploads/logo.jpg')
$logo_url = 'https://i.postimg.cc/qMxJQtNj/300500402-431417199006021-188592855639854309-n.jpg';

$invoice_no = $_GET['invoice_no'] ?? '';
if (!$invoice_no) { echo "Invoice number required."; exit; }

$stmt = $conn->prepare('SELECT * FROM invoices WHERE invoice_no = ? LIMIT 1');
if ($stmt === false) { echo "DB error"; exit; }
$stmt->bind_param('s', $invoice_no);
$stmt->execute();
$res = $stmt->get_result();
$inv = $res->fetch_assoc();
$stmt->close();
if (!$inv) { echo "Invoice not found: " . htmlspecialchars($invoice_no); exit; }

$items = json_decode($inv['items'], true);
if (!is_array($items)) $items = [];
function h($s){ return htmlspecialchars((string)$s); }

$theme = ($inv['theme'] ?? 'A') === 'B' ? 'B' : 'A';
?>
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Print Invoice <?php echo h($invoice_no) ?></title>
<style>
/* page */
@page { size: A4; margin: 6mm 6mm 6mm 6mm; }

/* base */
html,body{margin:0;padding:0;font-family: 'SolaimanLipi','Inter',Arial,sans-serif;color:#0f172a;-webkit-print-color-adjust:exact;print-color-adjust:exact;background:#f6f7fb}
.container{width:210mm;margin:10mm auto;padding:0;box-sizing:border-box}

/* card */
.card{width:100%;border-radius:8px;overflow:hidden;border:1px solid #e6e9ef;background:#fff;box-shadow:0 6px 18px rgba(15,23,42,0.04)}

/* header */
.header{padding:18px 20px;display:flex;gap:16px;align-items:center}
.logo{
  width:90px;
  height:90px;
  border-radius:8px;
  overflow:hidden;
  display:flex;
  align-items:center;
  justify-content:center;
  border:1px solid rgba(0,0,0,0.04);
  background:transparent;
}
.logo img{width:100%;height:100%;object-fit:cover;display:block;}
.title {line-height:1}
.title h1{margin:0;font-size:28px}
.title .sub{font-size:14px;margin-top:6px;color:inherit;font-weight:700}
.owner{margin-top:6px;font-size:14px;font-weight:800;color:inherit}
.memo-badge{margin-left:auto;padding:8px 12px;border-radius:8px;color:#fff;font-weight:800;font-size:13px}

/* theme gradients */
.theme-A .header{background:linear-gradient(90deg,#7c2d91,#f97316);color:#fff}
.theme-A .logo{background:rgba(255,255,255,0.85);color:#7c2d91}
.theme-A .memo-badge{background:rgba(255,255,255,0.12)}
.theme-B .header{background:linear-gradient(90deg,#2563eb,#06b6d4);color:#fff}
.theme-B .logo{background:rgba(255,255,255,0.85);color:#2563eb}
.theme-B .memo-badge{background:rgba(255,255,255,0.12)}

/* customer info (red highlight) */
.cust-list {
  background: #fff;
  border: 3px solid #dc2626;
  border-radius: 10px;
  padding: 14px 18px;
  margin: 14px 0;
  box-shadow: 0 4px 10px rgba(220,38,38,0.08);
}
.cust-list .row {
  display:flex;
  justify-content:space-between;
  gap:12px;
  padding:8px 0;
  align-items:flex-start;
  border-bottom: 1px dashed #f1f5f9;
}
.cust-list .row:last-child{ border-bottom: none; }
.cust-list .label { width: 90px; font-weight:700; color:#374151; display:inline-block; }
.cust-list .value { color:#0f172a; white-space:pre-wrap; }

/* items area inside margin (table wrap ensures table is inside margin with border/padding) */
.items { padding: 6px 18px 0 18px; }
.table-wrap {
  background:#fff;
  border:1px solid #eef2f7;
  border-radius:6px;
  padding:6px;
  box-shadow: 0 2px 6px rgba(2,6,23,0.02);
}

/* table styles — header bold & larger; DB rows bold */
.table{width:100%;border-collapse:collapse;font-size:14px}
.table thead th {
  background: linear-gradient(90deg, #7c2d91, #f97316);
  color: #fff;
  text-align: left;
  padding: 14px;
  border-bottom: 2px solid rgba(255,255,255,0.12);
  font-weight: 900;
  font-size:16px;
  letter-spacing: 0.4px;
}
.table td{
  padding:12px;
  border-bottom:1px solid #f3f4f6;
  vertical-align:middle;
  font-weight:700;
  font-size:14px;
}
.table td.right{text-align:right}
.table tbody tr:last-child td{border-bottom:0}

/* thumbnail */
.thumb {
  display:inline-block;
  max-width:64px;
  max-height:64px;
  border-radius:6px;
  overflow:hidden;
  border:1px solid #e6e9ef;
  box-shadow:0 2px 6px rgba(2,6,23,0.04);
}
.thumb img{display:block;width:100%;height:100%;object-fit:cover;}

/* totals (deep red) */
.totals-wrap { display: flex; justify-content: flex-end; padding: 12px 20px; }
.totals {
  width: 320px;
  padding: 12px;
  border-radius: 8px;
  background: #dc2626;
  color: #fff;
  border: 2px solid #b91c1c;
  font-size: 14px;
  box-shadow: 0 3px 8px rgba(220, 38, 38, 0.25);
}
.totals .row { display:flex; justify-content:space-between; padding:10px 6px; font-weight:900; border-top:1px dashed rgba(255,255,255,0.25); }
.totals .row:first-child{ border-top:0; font-size:15px; }

/* footer */
.footer{padding:14px 18px;background:linear-gradient(90deg,#fffaf0,#fffefb);font-size:13px;color:#44302e;margin:16px;border-radius:6px;border:1px solid #f3e8e3}
.footer .terms{line-height:1.5}
.footer .sig{display:flex;justify-content:space-between;align-items:center;margin-top:12px}
.footer .sig .left{font-size:13px}
.footer .sig .right{font-weight:800;text-align:right}
.sigline{display:block;border-top:1px solid #ddd;padding-top:8px;width:220px;margin-top:8px}

/* weekly close */
.weekly-close{ margin-top:14px;border:3px solid #dc2626;color:#b91c1c;font-size:18px;font-weight:900;text-align:center;padding:10px 0;border-radius:8px;background:#fff5f5; }

/* buttons (screen only) */
.controls { text-align:right; margin-top:10px; }
.btn {
  display:inline-block;
  padding:8px 12px;
  border-radius:6px;
  font-weight:700;
  cursor:pointer;
  border:none;
  margin-left:8px;
}
.btn-save { background:#0f172a;color:#fff; }
.btn-print { background:#dc2626;color:#fff; }

/* print-only behaviour: show only card and preserve colors */
@media print{
  body * { visibility: hidden; }
  .card, .card * { visibility: visible; }
  .card { position: absolute; left: 0; top: 0; width: 100%; box-shadow:none; border:none; background:#fff; }
  .noprint { display:none !important; }
  * { -webkit-print-color-adjust: exact; print-color-adjust: exact; }
}
*{-webkit-print-color-adjust:exact;print-color-adjust:exact}
</style>
</head>
<body>
<div class="container">
  <div class="card <?php echo $theme === 'B' ? 'theme-B' : 'theme-A' ?>">
    <div class="header">
      <div class="logo">
        <img src="<?php echo h($logo_url) ?>" alt="Shanto Jewellers logo">
      </div>
      <div class="title">
        <h1>Shanto Jewellers</h1>
        <div class="sub">Jamgora Chowrasta, Haji Liaqat Mir Sorak, Ashulia, Savar, Dhaka</div>
        <div class="owner">প্রোঃ সজল বণিক (সেতু)</div>
        <div class="sub" style="margin-top:6px">Mobile: 01826-555535, 01775-054150</div>
      </div>
      <div class="memo-badge">ক্যাশ মেমো</div>
    </div>

    <div class="section">
      <!-- Customer info red margin -->
      <div class="cust-list">
        <div class="row">
          <div><span class="label">নাম:</span> <span class="value"><?php echo h($inv['customer_name']) ?></span></div>
          <div><span class="label">Date:</span> <span class="value"><?php echo h($inv['date']) ?></span></div>
        </div>
        <div class="row">
          <div style="flex:1"><span class="label">ঠিকানা:</span> <span class="value"><?php echo nl2br(h($inv['address'])) ?></span></div>
          <div><span class="label">Order:</span> <span class="value"><?php echo h($inv['order_no']) ?></span></div>
        </div>
        <div class="row">
          <div><span class="label">ফোন:</span> <span class="value"><?php echo h($inv['phone']) ?></span></div>
          <div><span class="label">Invoice:</span> <span class="value"><?php echo h($inv['invoice_no']) ?></span></div>
        </div>
      </div>

      <!-- items inside table-wrap so it's clearly inside margin -->
      <div class="items">
        <div class="table-wrap">
          <table class="table">
            <thead>
              <tr>
                <th style="width:40%">বিবরণ</th>
                <th style="width:12%">ছবি</th>
                <th style="width:10%">Qty</th>
                <th style="width:18%">Wt</th>
                <th style="width:20%" class="right">টাকা</th>
              </tr>
            </thead>
            <tbody>
              <?php $total=0; if (count($items)===0): ?>
                <tr><td colspan="5" style="padding:12px;font-weight:700">— কোনো আইটেম নেই —</td></tr>
              <?php else: foreach($items as $it):
                // calculate line total robustly
                $line = 0.0;
                if (isset($it['line_total'])) {
                  $line = floatval($it['line_total']);
                } else {
                  $p = floatval($it['price'] ?? 0);
                  $q = floatval($it['qty'] ?? 1);
                  $line = $p * $q;
                }
                $total += $line;
                // image path handling
                $imgPath = $it['image'] ?? null;
                $imgAvailable = false;
                if ($imgPath) {
                  // normalize - if relative path, check file exists
                  $serverPath = __DIR__ . '/' . ltrim($imgPath, '/');
                  if (file_exists($serverPath) && is_file($serverPath)) {
                    $imgAvailable = true;
                    $imgUrl = h($imgPath);
                  } else {
                    // if it's an absolute/remote URL, allow it (no server check)
                    if (preg_match('#^https?://#i', $imgPath)) {
                      $imgAvailable = true;
                      $imgUrl = h($imgPath);
                    }
                  }
                }
                // weight is now free text (stored as 'weight')
                $weight_text = isset($it['weight']) ? (string)$it['weight'] : '';
              ?>
                <tr>
                  <td><?php echo h($it['desc']) ?></td>
                  <td>
                    <?php if ($imgAvailable): ?>
                      <a href="<?php echo $imgUrl ?>" target="_blank" class="thumb" title="Open full image">
                        <img src="<?php echo $imgUrl ?>" alt="item image">
                      </a>
                    <?php else: ?>
                      <div style="color:#9ca3af;font-weight:700">— নেই —</div>
                    <?php endif; ?>
                  </td>
                  <td><?php echo h($it['qty']) ?></td>
                  <td><?php echo h($weight_text) ?></td>
                  <td class="right"><?php echo number_format($line,2) ?></td>
                </tr>
              <?php endforeach; endif; ?>
            </tbody>
          </table>
        </div>
      </div>

      <!-- totals -->
      <div class="totals-wrap">
        <div class="totals">
          <div class="row"><div>মোট</div><div><?php echo number_format($total,2) ?> টাকা</div></div>
          <div class="row"><div>অগ্রিম</div><div><?php echo number_format(floatval($inv['advance'] ?? 0),2) ?> টাকা</div></div>
          <div class="row"><div>বাকি</div><div><?php echo number_format(($total - floatval($inv['advance'] ?? 0)),2) ?> টাকা</div></div>
        </div>
      </div>

      <div class="footer">
        <div class="terms">
          <strong>শর্তাবলী:</strong>
          <p style="margin-top:8px">অলংকার সীল (এক) শুধুমাত্র নিশ্চয়তা বহন করে। ব্যবহার না করলে বা অপছন্দ হলে তিন দিনের মধ্যে বদলে নেওয়া যাবে — বাংলাদেশ জুয়েলারী সমিতির সিদ্ধান্ত অনুযায়ী দোকানের গহনা থেকে ২০% কর্তন করে ক্রয় ফেরত এবং ১৫% কর্তন করে বদল করা হয়। বিক্রিত জিনিস ফেরত নেওয়া হয় না সব অবস্থায়। ক্যাশ মেমো সঙ্গে আনুন। অর্ডারকৃত মাল ৩ মাসের মধ্যে না নিলে বাতিল বলে গণ্য হবে। নাকফুল ও ব্রঞ্জের চুড়ি ফেরত বা বদল হয় না।</p>
        </div>
        <div class="sig">
          <div class="left">
            <div>গ্রহীতার স্বাক্ষর</div>
            <span class="sigline"></span>
          </div>
          <div class="right">
            <div class="weekly-close">সাপ্তাহিক বন্ধ: শনিবার</div>
            <div style="margin-top:12px">পক্ষে — শান্ত জুয়েলার্স</div>
          </div>
        </div>
      </div>

    </div>

  </div>

  <!-- controls (screen only) -->
  <div class="controls noprint">
    <button class="btn btn-save" id="saveBtn">Save (PDF)</button>
    <button class="btn btn-print" id="printBtn">Print</button>
  </div>

</div>

<script>
  document.getElementById('saveBtn').addEventListener('click', function(){ window.print(); });
  document.getElementById('printBtn').addEventListener('click', function(){ window.print(); });
  (function(){ document.body.style.webkitPrintColorAdjust = 'exact'; })();
</script>
</body>
</html>
