<?php
/**
 * sale_print.php  (root page — print/invoice view)
 * Upload: /home/jewellersbd/public_html/erp.jewellersbd.com/sale_print.php
 * Usage: sale_print.php?id=10  OR  sale_print.php?invoice=INV-2026-001
 *
 * Also fills api/sales/print_sale.php (JSON API for AJAX use)
 */
require_once __DIR__ . '/config/session.php';
require_once __DIR__ . '/config/db.php';
if (session_status() === PHP_SESSION_NONE) session_start();
if (empty($_SESSION['user_id'])) { header('Location: ui/login.html'); exit; }

// Load sale
$sale_id  = (int)($_GET['id'] ?? 0);
$inv_no   = trim($_GET['invoice'] ?? '');

if ($sale_id > 0) {
    $s = $pdo->prepare("SELECT * FROM sales WHERE id=? LIMIT 1");
    $s->execute([$sale_id]);
} elseif ($inv_no) {
    $s = $pdo->prepare("SELECT * FROM sales WHERE invoice_no=? LIMIT 1");
    $s->execute([$inv_no]);
} else {
    die('<p style="padding:20px;color:red">sale id বা invoice নম্বর দিন।</p>');
}
$sale = $s->fetch(PDO::FETCH_ASSOC);
if (!$sale) die('<p style="padding:20px;color:red">বিক্রয় পাওয়া যায়নি।</p>');

// Items
$items = $pdo->prepare("SELECT * FROM sale_items WHERE sale_id=? ORDER BY id");
$items->execute([$sale['id']]);
$sale_items = $items->fetchAll(PDO::FETCH_ASSOC);

// Payments
$pays = $pdo->prepare("SELECT sp.*, ca.account_name FROM sale_payments sp LEFT JOIN cash_accounts ca ON ca.id=sp.cash_account_id WHERE sp.sale_id=? ORDER BY sp.id");
$pays->execute([$sale['id']]);
$payments = $pays->fetchAll(PDO::FETCH_ASSOC);

// Exchanges
$exch = $pdo->prepare("SELECT * FROM sale_exchanges WHERE sale_id=? ORDER BY id");
$exch->execute([$sale['id']]);
$exchanges = $exch->fetchAll(PDO::FETCH_ASSOC);

// Shop info (settings table or hardcoded fallback)
$shop_name  = 'বধুবরণ জুয়েলার্স';
$shop_addr  = '';
$shop_phone = '';
try {
    $set = $pdo->query("SELECT setting_key, setting_value FROM settings WHERE setting_key IN ('shop_name','shop_address','shop_phone')")->fetchAll(PDO::FETCH_KEY_PAIR);
    $shop_name  = $set['shop_name']  ?? $shop_name;
    $shop_addr  = $set['shop_address'] ?? $shop_addr;
    $shop_phone = $set['shop_phone'] ?? $shop_phone;
} catch (Exception $e) {}

// Helper: weight to vori
function toVori(float $g): string {
    if ($g <= 0) return '০';
    $V=11.664; $v=floor($g/$V); $r=$g-($v*$V);
    $a=floor($r/($V/16)); $r2=$r-($a*($V/16)); $ro=floor($r2/($V/96));
    $p=[]; if($v>0)$p[]=$v.' ভরি'; if($a>0)$p[]=$a.' আনা'; if($ro>0)$p[]=$ro.' রতি';
    return $p ? implode(' ',$p) : round($g,3).'g';
}
function fmt(float $n): string {
    return '৳'.number_format($n, 2);
}

$status_label = ['paid'=>'পরিশোধিত','partial'=>'আংশিক','due'=>'বাকি'];
$status_color = ['paid'=>'#15803d','partial'=>'#d97706','due'=>'#dc2626'];
$sl = $status_label[$sale['payment_status']] ?? $sale['payment_status'];
$sc = $status_color[$sale['payment_status']] ?? '#1e293b';
?>
<!DOCTYPE html>
<html lang="bn">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<title>Invoice — <?= htmlspecialchars($sale['invoice_no']) ?></title>
<style>
:root{--navy:#1e2a3b;--gold:#d4a843;--border:#e2e8f0;--text:#1e293b;--muted:#64748b;--surface:#f8fafc;}
*{box-sizing:border-box;margin:0;padding:0;}
body{font-family:'Segoe UI',system-ui,sans-serif;background:var(--surface);color:var(--text);font-size:14px;}

/* Screen toolbar */
.toolbar{background:var(--navy);padding:0 16px;height:52px;display:flex;align-items:center;gap:10px;border-bottom:2px solid var(--gold);}
.toolbar h1{font-size:15px;font-weight:700;color:#fff;flex:1;}
.btn-print{padding:8px 18px;background:var(--gold);color:var(--navy);border:none;border-radius:7px;font-size:13px;font-weight:800;cursor:pointer;}
.btn-back{color:var(--gold);text-decoration:none;font-size:12px;font-weight:600;padding:6px 10px;border:1px solid rgba(212,168,67,.4);border-radius:6px;}

.page-wrap{max-width:680px;margin:16px auto;padding:0 12px 40px;}

/* Invoice card */
.invoice{background:#fff;border-radius:12px;border:1px solid var(--border);box-shadow:0 2px 8px rgba(0,0,0,.07);overflow:hidden;}

/* Header */
.inv-header{background:var(--navy);padding:18px 20px;border-bottom:3px solid var(--gold);}
.shop-name{font-size:20px;font-weight:800;color:#fff;letter-spacing:.5px;}
.shop-sub{font-size:12px;color:rgba(255,255,255,.6);margin-top:2px;}
.inv-meta{display:flex;justify-content:space-between;align-items:flex-start;margin-top:14px;}
.inv-no{font-size:14px;font-weight:700;color:var(--gold);}
.inv-date{font-size:12px;color:rgba(255,255,255,.7);text-align:right;}

/* Customer */
.inv-customer{padding:14px 20px;border-bottom:1px solid var(--border);display:flex;justify-content:space-between;align-items:center;gap:10px;}
.cust-label{font-size:10px;color:var(--muted);text-transform:uppercase;letter-spacing:.5px;}
.cust-name{font-size:15px;font-weight:700;color:var(--text);}
.cust-phone{font-size:12px;color:var(--muted);}
.status-badge{padding:4px 12px;border-radius:20px;font-size:12px;font-weight:800;white-space:nowrap;}

/* Items table */
.inv-section{padding:14px 20px;}
.section-title{font-size:11px;font-weight:700;color:var(--muted);text-transform:uppercase;letter-spacing:.6px;margin-bottom:10px;padding-bottom:6px;border-bottom:1px solid var(--border);}
.items-table{width:100%;border-collapse:collapse;font-size:13px;}
.items-table th{background:var(--navy);color:rgba(255,255,255,.85);padding:7px 8px;text-align:left;font-size:10px;text-transform:uppercase;letter-spacing:.4px;font-weight:600;}
.items-table th:first-child{border-radius:6px 0 0 0;}
.items-table th:last-child{border-radius:0 6px 0 0;text-align:right;}
.items-table td{padding:8px 8px;border-bottom:1px solid var(--border);vertical-align:top;}
.items-table td:last-child{text-align:right;font-weight:700;}
.items-table tr:last-child td{border-bottom:none;}
.item-name{font-weight:700;color:var(--text);}
.item-sub{font-size:11px;color:var(--muted);margin-top:2px;}

/* Totals */
.totals-block{padding:0 20px 14px;}
.total-row{display:flex;justify-content:space-between;padding:5px 0;font-size:13px;border-bottom:1px solid var(--border);}
.total-row:last-child{border-bottom:none;}
.total-row.grand{font-size:16px;font-weight:800;color:var(--navy);padding:10px 0;}
.total-row.due-row{font-size:15px;font-weight:800;color:#dc2626;}
.total-row .tl{color:var(--muted);}
.total-row.grand .tl{color:var(--navy);}
.total-divider{border:none;border-top:2px solid var(--border);margin:4px 0;}

/* Payments */
.pay-row{display:flex;justify-content:space-between;padding:5px 0;font-size:13px;}
.pay-row .pl{color:var(--muted);}

/* Exchange */
.exch-row{font-size:12px;color:var(--muted);padding:3px 0;}

/* Footer */
.inv-footer{background:var(--surface);border-top:1px solid var(--border);padding:12px 20px;text-align:center;font-size:11px;color:var(--muted);}

/* ══ PRINT ══ */
@media print {
    .toolbar{display:none!important;}
    body{background:#fff;}
    .page-wrap{margin:0;padding:0;max-width:100%;}
    .invoice{box-shadow:none;border:none;border-radius:0;}
}
</style>
</head>
<body>

<div class="toolbar">
  <h1>🧾 Invoice</h1>
  <a href="ui/sales_list.html" class="btn-back">← তালিকা</a>
  <button class="btn-print" onclick="window.print()">🖨️ প্রিন্ট করুন</button>
</div>

<div class="page-wrap">
<div class="invoice">

  <!-- Header -->
  <div class="inv-header">
    <div class="shop-name"><?= htmlspecialchars($shop_name) ?></div>
    <?php if ($shop_addr || $shop_phone): ?>
    <div class="shop-sub"><?= htmlspecialchars($shop_addr) ?><?= $shop_phone ? ' | ☎ '.$shop_phone : '' ?></div>
    <?php endif; ?>
    <div class="inv-meta">
      <div>
        <div class="inv-no">Invoice: <?= htmlspecialchars($sale['invoice_no']) ?></div>
      </div>
      <div class="inv-date">
        <?= date('d M Y', strtotime($sale['sale_date'])) ?><br>
        <?= date('h:i A', strtotime($sale['sale_date'])) ?>
      </div>
    </div>
  </div>

  <!-- Customer -->
  <div class="inv-customer">
    <div>
      <div class="cust-label">গ্রাহক</div>
      <div class="cust-name"><?= htmlspecialchars($sale['customer_name_snapshot'] ?: 'অজানা গ্রাহক') ?></div>
      <?php if ($sale['customer_phone_snapshot']): ?>
      <div class="cust-phone">📱 <?= htmlspecialchars($sale['customer_phone_snapshot']) ?></div>
      <?php endif; ?>
    </div>
    <span class="status-badge" style="background:<?= $sc ?>22;color:<?= $sc ?>;border:1.5px solid <?= $sc ?>">
      <?= $sl ?>
    </span>
  </div>

  <!-- Items -->
  <?php if (!empty($sale_items)): ?>
  <div class="inv-section">
    <div class="section-title">🛍️ পণ্য তালিকা</div>
    <table class="items-table">
      <thead>
        <tr>
          <th>#</th>
          <th>পণ্য</th>
          <th>ওজন</th>
          <th>দাম</th>
        </tr>
      </thead>
      <tbody>
        <?php foreach ($sale_items as $i => $item): ?>
        <tr>
          <td style="color:var(--muted);font-size:12px"><?= $i+1 ?></td>
          <td>
            <div class="item-name"><?= htmlspecialchars($item['product_name']) ?></div>
            <div class="item-sub">
              <?= htmlspecialchars($item['karat'] ?? '') ?>
              <?php if ($item['barcode']): ?> · <?= htmlspecialchars($item['barcode']) ?><?php endif; ?>
              <?php if ($item['making_charge'] > 0): ?> · মজুরি: <?= fmt($item['making_charge']) ?><?php endif; ?>
            </div>
          </td>
          <td style="font-size:12px;white-space:nowrap">
            <?= number_format((float)$item['gross_weight_gram'],3) ?>g<br>
            <span style="color:var(--muted);font-size:11px"><?= toVori((float)$item['gross_weight_gram']) ?></span>
          </td>
          <td><?= fmt((float)$item['item_total']) ?></td>
        </tr>
        <?php endforeach; ?>
      </tbody>
    </table>
  </div>
  <?php endif; ?>

  <!-- Exchanges (পুরনো সোনা) -->
  <?php if (!empty($exchanges)): ?>
  <div class="inv-section" style="padding-top:0">
    <div class="section-title">♻️ বিনিময় (পুরনো সোনা)</div>
    <?php foreach ($exchanges as $ex): ?>
    <div class="exch-row">
      <?= htmlspecialchars($ex['item_description'] ?? 'পুরনো সোনা') ?>
      · <?= number_format((float)($ex['gross_weight_gram'] ?? 0), 3) ?>g
      · <?= toVori((float)($ex['gross_weight_gram'] ?? 0)) ?>
      · <strong><?= fmt((float)($ex['exchange_value'] ?? 0)) ?></strong>
    </div>
    <?php endforeach; ?>
  </div>
  <?php endif; ?>

  <!-- Totals -->
  <div class="totals-block">
    <div class="section-title">💰 হিসাব</div>
    <?php if ((float)$sale['items_subtotal'] > 0): ?>
    <div class="total-row"><span class="tl">পণ্যের মোট</span><span><?= fmt((float)$sale['items_subtotal']) ?></span></div>
    <?php endif; ?>
    <?php if ((float)$sale['making_charge_total'] > 0): ?>
    <div class="total-row"><span class="tl">মজুরি</span><span><?= fmt((float)$sale['making_charge_total']) ?></span></div>
    <?php endif; ?>
    <?php if ((float)$sale['vat_amount'] > 0): ?>
    <div class="total-row"><span class="tl">VAT (<?= $sale['vat_percent'] ?>%)</span><span><?= fmt((float)$sale['vat_amount']) ?></span></div>
    <?php endif; ?>
    <?php if ((float)$sale['discount_amount'] > 0): ?>
    <div class="total-row" style="color:#15803d"><span class="tl">ছাড়</span><span>− <?= fmt((float)$sale['discount_amount']) ?></span></div>
    <?php endif; ?>
    <?php if ((float)$sale['exchange_value'] > 0): ?>
    <div class="total-row" style="color:#15803d"><span class="tl">বিনিময় মূল্য বাদ</span><span>− <?= fmt((float)$sale['exchange_value']) ?></span></div>
    <?php endif; ?>
    <hr class="total-divider">
    <div class="total-row grand"><span class="tl">সর্বমোট</span><span><?= fmt((float)$sale['grand_total']) ?></span></div>
    <div class="total-row" style="color:#15803d"><span class="tl">পরিশোধিত</span><span><?= fmt((float)$sale['paid_total']) ?></span></div>
    <?php if ((float)$sale['due_amount'] > 0): ?>
    <div class="total-row due-row"><span>বাকি</span><span><?= fmt((float)$sale['due_amount']) ?></span></div>
    <?php endif; ?>
  </div>

  <!-- Payments -->
  <?php if (!empty($payments)): ?>
  <div class="inv-section" style="padding-top:0">
    <div class="section-title">🏦 পেমেন্ট বিবরণ</div>
    <?php foreach ($payments as $pay): ?>
    <div class="pay-row">
      <span class="pl"><?= htmlspecialchars($pay['account_name'] ?? 'Cash') ?></span>
      <span><?= fmt((float)$pay['amount']) ?></span>
    </div>
    <?php endforeach; ?>
  </div>
  <?php endif; ?>

  <!-- Footer -->
  <div class="inv-footer">
    ধন্যবাদ আমাদের দোকানে কেনাকাটা করার জন্য 🙏<br>
    <?= htmlspecialchars($shop_name) ?><?= $shop_phone ? ' | ☎ '.$shop_phone : '' ?>
  </div>

</div><!-- /invoice -->
</div><!-- /page-wrap -->

</body>
</html>