<?php
// ============================================================
//  MediCore — Purchase Return Print Voucher
//  File: purchase/return-print.php
// ============================================================
require_once '../includes/db.php';
require_once '../includes/auth.php';
require_once '../includes/form_icons.php';
require_login();

$id      = (int)($_GET['id']      ?? 0);
$thermal = (int)($_GET['thermal'] ?? 0);
if (!$id) die('Invalid return ID');

$ret = db_row("SELECT pr.*, u.name AS created_by_name
                  FROM purchase_returns pr
             LEFT JOIN users u ON u.id = pr.created_by
                 WHERE pr.id = ?", [$id]);
if (!$ret) die('Return record not found');

$items = db_rows(
    "SELECT pri.*, p.form, p.strength
       FROM purchase_return_items pri
  LEFT JOIN products p ON p.id = pri.product_id
      WHERE pri.return_id = ?
      ORDER BY pri.id", [$id]
);

$cfg   = get_settings();
$cur   = $cfg['currency'];
$total = (float)$ret['total_amount'];
$creditLabels = [
    'supplier_credit' => 'Supplier Credit',
    'cash_recovery'   => 'Cash Recovery',
    'adjustment'      => 'Adjustment',
];
?>
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>PRN: <?= htmlspecialchars($ret['prn']) ?></title>
  <style>
    *{margin:0;padding:0;box-sizing:border-box}
    body{font-family:'Segoe UI',Arial,sans-serif;font-size:12px;
         color:#111;background:#fff;padding:20px}
    .print-bar{display:flex;gap:8px;margin-bottom:16px;padding:10px 14px;
               background:#f0f4ff;border-radius:6px;align-items:center;flex-wrap:wrap}
    .print-bar button{padding:7px 16px;border:none;border-radius:5px;
                      cursor:pointer;font-size:12px;font-weight:600}
    .btn-orange{background:#ea580c;color:#fff}
    .btn-grey{background:#fff;color:#2d3a8c;border:1px solid #2d3a8c}
    @media print{.print-bar{display:none}}
    .invoice{max-width:720px;margin:0 auto;border:1px solid #ddd;
             border-radius:8px;overflow:hidden}
    .inv-head{background:#ea580c;color:#fff;padding:16px 22px;
              display:flex;justify-content:space-between;align-items:center}
    .inv-head .shop-name{font-size:17px;font-weight:700}
    .inv-head .shop-sub{font-size:11px;opacity:.8;margin-top:2px}
    .prn-badge{background:rgba(255,255,255,.2);padding:4px 12px;
               border-radius:4px;font-size:11px;font-weight:700;
               letter-spacing:1px;margin-top:6px;display:inline-block}
    .inv-meta{display:grid;grid-template-columns:1fr 1fr 1fr;border-bottom:1px solid #e5e7eb}
    .mc{padding:10px 16px;border-right:1px solid #e5e7eb}
    .mc:last-child{border-right:none}
    .ml{font-size:10px;color:#888;margin-bottom:2px}
    .mv{font-weight:600}
    .inv-items{width:100%;border-collapse:collapse}
    .inv-items thead tr{background:#fff7ed;border-bottom:2px solid #fdba74}
    .inv-items th{padding:8px 10px;text-align:left;font-size:11px;
                  font-weight:700;color:#9a3412;text-transform:uppercase;letter-spacing:.5px}
    .inv-items td{padding:8px 10px;border-bottom:1px solid #f0f0f0;font-size:12px}
    .inv-items tbody tr:nth-child(even){background:#fffaf5}
    .r{text-align:right}.c{text-align:center}
    .mono{font-family:'Courier New',monospace}
    .totals-box{padding:12px 16px;background:#fff7ed;border-top:2px solid #fdba74}
    .t-row{display:flex;justify-content:space-between;padding:5px 0;font-size:12px}
    .t-row.final{border-top:2px solid #ea580c;margin-top:6px;padding-top:8px;
                 font-weight:700;font-size:15px;color:#ea580c}
    .reason-box{padding:12px 16px;background:#f9fafb;border-top:1px solid #e5e7eb;
                font-size:11.5px;color:#555}
    .inv-foot{background:#f9fafb;padding:10px 16px;border-top:1px solid #e5e7eb;
              display:flex;justify-content:space-between;font-size:10px;color:#999}
    body.thermal{font-family:'Courier New',monospace;font-size:11px;width:80mm;padding:4mm;background:#fff}
    body.thermal .invoice{max-width:100%;border:none;border-radius:0}
    body.thermal .inv-head{background:#fff;color:#000;padding:0 0 6px;
                            border-bottom:1px dashed #000;display:block;text-align:center}
    body.thermal .inv-head .shop-name{font-size:13px}
    body.thermal .prn-badge{background:#ffedd5;color:#ea580c;padding:2px 6px}
    body.thermal .inv-meta{display:block;border:none;border-bottom:1px dashed #000;padding:4px 0}
    body.thermal .mc{padding:2px 0;border:none}
    body.thermal .ml{display:inline;font-weight:700}
    body.thermal .mv{display:inline}
    body.thermal .inv-items th{font-size:10px;padding:3px 2px}
    body.thermal .inv-items td{font-size:10px;padding:3px 2px}
    body.thermal .inv-items thead tr{background:#fff}
    body.thermal .totals-box{padding:4px 0;background:#fff;border-top:1px dashed #000}
    body.thermal .t-row{font-size:11px;padding:2px 0}
    body.thermal .inv-foot{background:#fff;padding:4px 0;border-top:1px dashed #000}
    @media print{body.thermal{width:80mm}}
  </style>
</head>
<body class="<?= $thermal ? 'thermal' : '' ?>">

<div class="print-bar">
  <button class="btn-orange" onclick="window.print()">🖨 Print</button>
  <a href="?id=<?= $id ?>&thermal=<?= $thermal?0:1 ?>"
     style="padding:7px 16px;border-radius:5px;font-size:12px;font-weight:600;
            text-decoration:none;background:#fff;color:#2d3a8c;border:1px solid #2d3a8c">
    <?= $thermal ? '📄 A4 View' : '🖨 80mm Thermal' ?>
  </a>
  <button class="btn-grey" onclick="window.close()">✕ Close</button>
  <span style="font-size:11px;color:#555;margin-left:8px">
    PRN: <strong><?= htmlspecialchars($ret['prn']) ?></strong>
  </span>
</div>

<div class="invoice">
  <div class="inv-head">
    <div>
      <div class="shop-name"><?= htmlspecialchars($cfg['shop_name']) ?></div>
      <div class="shop-sub"><?= htmlspecialchars($cfg['address']) ?></div>
      <?php if ($cfg['phone']): ?>
      <div class="shop-sub">📞 <?= htmlspecialchars($cfg['phone']) ?></div>
      <?php endif; ?>
    </div>
    <div style="text-align:right">
      <div style="font-size:10px;opacity:.7;letter-spacing:2px">PURCHASE RETURN VOUCHER</div>
      <div style="font-size:17px;font-weight:700;font-family:'Courier New',monospace">
        <?= htmlspecialchars($ret['prn']) ?>
      </div>
      <div class="prn-badge">↩ RETURN TO SUPPLIER</div>
    </div>
  </div>

  <div class="inv-meta">
    <div class="mc">
      <div class="ml">Supplier</div>
      <div class="mv"><?= htmlspecialchars($ret['supplier_name']) ?></div>
    </div>
    <div class="mc">
      <div class="ml">Return Date</div>
      <div class="mv"><?= htmlspecialchars($ret['date']) ?></div>
    </div>
    <div class="mc">
      <div class="ml">Original PO</div>
      <div class="mv mono"><?= htmlspecialchars($ret['purchase_invoice']) ?></div>
    </div>
  </div>

  <table class="inv-items">
    <thead>
      <tr>
        <th style="width:28px">#</th>
        <th>Product</th>
        <th class="c">Qty Returned (pcs)</th>
        <th class="r">Purchase Rate</th>
        <th class="r">Amount</th>
      </tr>
    </thead>
    <tbody>
      <?php foreach ($items as $i => $it): ?>
      <tr>
        <td style="color:#999"><?= $i+1 ?></td>
        <td>
          <div style="font-weight:600"><?= form_icon_name($it['form'] ?? '', $it['product_name']) ?></div>
          <?php if (!$thermal && ($it['strength']||$it['form'])): ?>
          <div style="font-size:10px;color:#888">
            <?= htmlspecialchars(trim($it['strength'].' '.$it['form'])) ?>
          </div>
          <?php endif; ?>
        </td>
        <td class="c mono" style="font-weight:700;color:#ea580c"><?= $it['qty'] ?></td>
        <td class="r mono"><?= $cur.number_format($it['rate'],2) ?></td>
        <td class="r mono" style="font-weight:700;color:#ea580c">
          <?= $cur.number_format($it['amount'],2) ?>
        </td>
      </tr>
      <?php endforeach; ?>
    </tbody>
  </table>

  <div class="totals-box">
    <div class="t-row">
      <span>Credit Method</span>
      <span><?= htmlspecialchars($creditLabels[$ret['credit_type']] ?? $ret['credit_type']) ?></span>
    </div>
    <?php if ($ret['credit_type']==='cash_recovery' && $ret['credit_account']): ?>
    <div class="t-row">
      <span>Recovery Account</span>
      <span><?= htmlspecialchars($ret['credit_account']) ?></span>
    </div>
    <?php endif; ?>
    <div class="t-row final">
      <span>Total Return Value</span>
      <span class="mono"><?= $cur.number_format($total,2) ?></span>
    </div>
  </div>

  <?php if ($ret['reason']): ?>
  <div class="reason-box">
    <strong>Reason:</strong> <?= htmlspecialchars($ret['reason']) ?>
  </div>
  <?php endif; ?>

  <div class="inv-foot">
    <span>Processed by: <?= htmlspecialchars($ret['created_by_name']??'') ?></span>
    <span>Printed: <?= date('d M Y, h:i A') ?></span>
    <span>MediCore PMS</span>
  </div>
</div>
</body>
</html>
