<?php
require_once __DIR__ . '/../app/bootstrap.php';
use App\Core\PosService;
PosService::requireAccess();
$vendorId = PosService::currentVendorId();
$register = PosService::defaultRegister($vendorId);
$shift = $register ? PosService::currentShift((int)$register['id'], (int)(current_user()['id'] ?? 0)) : null;
$products = PosService::searchProducts('', $vendorId, 12);
$heldCart = null;
if (!empty($_GET['held_id'])) {
    $held = App\Core\Database::fetchOne('SELECT * FROM pos_held_sales WHERE id=? AND vendor_id=? AND status="held" LIMIT 1', [(int)$_GET['held_id'], $vendorId]);
    if ($held) {
        $heldCart = json_decode($held['cart_json'] ?? '[]', true) ?: [];
        App\Core\Database::execute('UPDATE pos_held_sales SET status="loaded", updated_at=NOW() WHERE id=?', [(int)$held['id']]);
    }
}
$pageTitle = 'Sell / Register | Pro POS';
require_once __DIR__ . '/partials/header.php';
?>
<div class="pos-register" data-pos-app>
  <?php if(!$register): ?>
  <div class="alert alert-warning"><strong>No POS register assigned.</strong> Admin/vendor manager should create a register from POS Settings before live selling.</div>
  <?php endif; ?>
  <?php if(!$shift): ?>
  <div class="alert alert-info d-flex justify-content-between align-items-center flex-wrap gap-2">
    <span><strong>Shift closed.</strong> Open a shift before completing sales. You may still build carts for training.</span>
    <a class="btn btn-primary btn-sm" href="<?= url('pos/shifts.php') ?>">Open Shift</a>
  </div>
  <?php endif; ?>

  <section class="pos-scan-panel mb-3">
    <div class="row g-2 align-items-center">
      <div class="col-lg-5">
        <label class="form-label mb-1">Search product / SKU / barcode</label>
        <div class="input-group input-group-lg">
          <input id="posSearch" class="form-control" placeholder="Scan or type product name, SKU, barcode" autocomplete="off">
          <button class="btn btn-primary" type="button" data-pos-search>Search</button>
        </div>
      </div>
      <div class="col-lg-4">
        <label class="form-label mb-1">Hardware scanner input</label>
        <input id="barcodeInput" class="form-control form-control-lg" placeholder="Focus here, scan, press Enter" autocomplete="off" autofocus>
      </div>
      <div class="col-lg-3 d-grid gap-2 d-lg-flex pt-lg-4">
        <button class="btn btn-outline-primary" type="button" data-camera-start>Phone Camera</button>
        <button class="btn btn-outline-secondary" type="button" data-pos-install>Install App</button>
      </div>
    </div>
    <div id="scannerStatus" class="small text-muted mt-2">USB/Bluetooth barcode scanners work as keyboard input. Phone camera scanner uses the browser barcode API when supported.</div>
  </section>

  <div class="row g-3">
    <div class="col-xl-7">
      <div class="card pos-card h-100">
        <div class="card-header bg-white d-flex justify-content-between align-items-center flex-wrap gap-2">
          <strong>Products</strong>
          <div class="d-flex gap-2">
            <select id="posCategory" class="form-select form-select-sm" style="width:auto"><option value="">All categories</option></select>
            <button class="btn btn-sm btn-outline-primary" type="button" data-refresh-products>Refresh</button>
          </div>
        </div>
        <div class="card-body">
          <div class="pos-product-grid" id="posProductGrid">
            <?php foreach($products as $p): ?>
            <button class="pos-product-tile" type="button" data-product='<?= e(json_encode($p, JSON_UNESCAPED_SLASHES|JSON_UNESCAPED_UNICODE)) ?>'>
              <span class="pos-product-name"><?= e($p['name'] ?? '') ?></span>
              <span class="pos-product-sku"><?= e(($p['sku'] ?? '') . ' / ' . ($p['barcode'] ?? '')) ?></span>
              <span class="pos-product-price"><?= money($p['sale_price'] ?? $p['regular_price'] ?? 0) ?></span>
              <span class="pos-stock">Stock: <?= e($p['stock'] ?? 0) ?></span>
            </button>
            <?php endforeach; ?>
          </div>
        </div>
      </div>
    </div>

    <div class="col-xl-5">
      <div class="card pos-card pos-cart-card">
        <div class="card-header bg-white d-flex justify-content-between align-items-center">
          <strong>Current Sale</strong>
          <div class="btn-group btn-group-sm">
            <button class="btn btn-outline-secondary" type="button" data-hold-sale>Hold</button>
            <button class="btn btn-outline-danger" type="button" data-clear-cart>Clear</button>
          </div>
        </div>
        <div class="card-body p-0">
          <div class="table-responsive pos-cart-table-wrap">
            <table class="table table-sm align-middle mb-0 pos-cart-table">
              <thead><tr><th>Item</th><th style="width:92px">Qty</th><th>Price</th><th>Total</th><th></th></tr></thead>
              <tbody id="posCartBody"><tr><td colspan="5" class="text-center text-muted py-4">Scan or tap a product.</td></tr></tbody>
            </table>
          </div>
        </div>
        <div class="card-footer bg-white">
          <div class="row g-2 mb-2">
            <div class="col-6"><label class="form-label small">Customer phone / name</label><input id="posCustomer" class="form-control" placeholder="Walk-in"></div>
            <div class="col-3"><label class="form-label small">Discount</label><input id="posDiscount" class="form-control" type="number" step="0.01" value="0"></div>
            <div class="col-3"><label class="form-label small">VAT %</label><input id="posTaxPercent" class="form-control" type="number" step="0.01" value="0"></div>
          </div>
          <div class="pos-total-box">
            <div><span>Subtotal</span><strong id="posSubtotal">৳ 0.00</strong></div>
            <div><span>Discount</span><strong id="posDiscountView">৳ 0.00</strong></div>
            <div><span>VAT/TAX</span><strong id="posTaxView">৳ 0.00</strong></div>
            <div class="grand"><span>Total</span><strong id="posGrandTotal">৳ 0.00</strong></div>
          </div>
          <div class="pos-payment-grid mt-3">
            <button class="btn btn-outline-success" type="button" data-pay-method="cash">Cash</button>
            <button class="btn btn-outline-primary" type="button" data-pay-method="bkash">bKash</button>
            <button class="btn btn-outline-primary" type="button" data-pay-method="nagad">Nagad</button>
            <button class="btn btn-outline-dark" type="button" data-pay-method="card">Card</button>
            <button class="btn btn-outline-info" type="button" data-pay-method="wallet">Wallet</button>
            <button class="btn btn-outline-secondary" type="button" data-split-pay>Split</button>
          </div>
          <div class="row g-2 mt-2">
            <div class="col-5"><select id="posPaymentMethod" class="form-select"><option value="cash">Cash</option><option value="bkash">bKash</option><option value="nagad">Nagad</option><option value="card">Card</option><option value="wallet">Wallet</option></select></div>
            <div class="col-4"><input id="posPaidAmount" class="form-control" type="number" step="0.01" placeholder="Paid amount"></div>
            <div class="col-3"><input id="posPaymentRef" class="form-control" placeholder="Ref"></div>
          </div>
          <button class="btn btn-primary btn-lg w-100 mt-3" type="button" data-complete-sale <?= !$shift ? 'disabled title="Open shift first"' : '' ?>>Complete Sale & Print</button>
          <div id="posMessage" class="small mt-2"></div>
        </div>
      </div>
    </div>
  </div>
</div>

<div class="pos-camera-modal" id="posCameraModal" hidden>
  <div class="pos-camera-box">
    <div class="d-flex justify-content-between align-items-center mb-2"><strong>Phone Camera Scanner</strong><button class="btn btn-sm btn-light" type="button" data-camera-stop>Close</button></div>
    <video id="posScannerVideo" playsinline></video>
    <div class="small mt-2">Point camera at barcode/QR. Use manual input if the device browser blocks camera scanning.</div>
  </div>
</div>
<?php if($heldCart !== null): ?><script>window.PH_HELD_CART = <?= json_encode($heldCart, JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES) ?>;</script><?php endif; ?>
<?php require_once __DIR__ . '/partials/footer.php'; ?>
