<?php
// public/stock_in.php
require_once __DIR__ . '/../helpers/auth.php';
require_role(['admin', 'staff']);

$pdo = db();
$title = "Stock IN - IMS";
$user = current_user();

function post_str(string $key): string {
    return trim((string)($_POST[$key] ?? ''));
}
function post_int(string $key): int {
    return (int)($_POST[$key] ?? 0);
}
function post_float(string $key): float {
    $val = trim((string)($_POST[$key] ?? '0'));
    return (float)$val;
}

/**
 * AJAX: Lookup product by SKU + current stock
 * GET stock_in.php?ajax=sku_lookup&sku=XXXX
 */
if (isset($_GET['ajax']) && $_GET['ajax'] === 'sku_lookup') {
    header('Content-Type: application/json; charset=utf-8');

    $sku = trim((string)($_GET['sku'] ?? ''));
    if ($sku === '') {
        echo json_encode(['ok' => false, 'error' => 'Missing SKU']);
        exit;
    }

    try {
        $stmt = $pdo->prepare("SELECT id, sku, name FROM products WHERE is_active=1 AND sku = :sku LIMIT 1");
        $stmt->execute([':sku' => $sku]);
        $p = $stmt->fetch();

        if (!$p) {
            echo json_encode(['ok' => false, 'error' => 'SKU not found']);
            exit;
        }

        // Correct formula: IN - OUT + ADJUST
        $stmt = $pdo->prepare("
            SELECT
              (
                COALESCE(SUM(CASE WHEN movement_type='IN' THEN quantity ELSE 0 END),0)
                - COALESCE(SUM(CASE WHEN movement_type='OUT' THEN quantity ELSE 0 END),0)
                + COALESCE(SUM(CASE WHEN movement_type='ADJUST' THEN quantity ELSE 0 END),0)
              ) AS stock
            FROM inventory_movements
            WHERE product_id = :pid
        ");
        $stmt->execute([':pid' => (int)$p['id']]);
        $stock = (int)($stmt->fetch()['stock'] ?? 0);

        echo json_encode([
            'ok' => true,
            'product' => [
                'id' => (int)$p['id'],
                'sku' => (string)$p['sku'],
                'name' => (string)$p['name'],
                'stock' => $stock
            ]
        ]);
        exit;
    } catch (Throwable $e) {
        echo json_encode(['ok' => false, 'error' => 'Server error']);
        exit;
    }
}

$error = '';
$success = '';

$products = $pdo->query("SELECT id, sku, name FROM products WHERE is_active=1 ORDER BY name ASC")->fetchAll();

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $product_id = post_int('product_id');
    $qty = post_int('quantity');
    $unit_cost = post_float('unit_cost');
    $notes = post_str('notes');

    if ($product_id <= 0 || $qty <= 0) {
        $error = "Please select a product and enter a quantity greater than 0.";
    } else {
        try {
            $stmt = $pdo->prepare("
                INSERT INTO inventory_movements
                (product_id, movement_type, quantity, unit_cost, reference_type, reference_id, notes, created_by)
                VALUES
                (:product_id, 'IN', :quantity, :unit_cost, 'MANUAL', NULL, :notes, :created_by)
            ");
            $stmt->execute([
                ':product_id' => $product_id,
                ':quantity' => $qty,
                ':unit_cost' => $unit_cost > 0 ? $unit_cost : null,
                ':notes' => $notes !== '' ? $notes : null,
                ':created_by' => $user['id'],
            ]);

            $success = "Stock added successfully.";
        } catch (PDOException $e) {
            $error = "Error: " . $e->getMessage();
        }
    }
}

// Recent IN movements
$recent = $pdo->query("
    SELECT m.*, p.sku, p.name
    FROM inventory_movements m
    JOIN products p ON p.id = m.product_id
    WHERE m.movement_type='IN'
    ORDER BY m.created_at DESC
    LIMIT 20
")->fetchAll();

require_once __DIR__ . '/../templates/header.php';
require_once __DIR__ . '/../templates/sidebar.php';
?>

<main class="col-12 col-md-9 col-lg-10 p-3 p-md-4">
  <h4 class="mb-3">Stock IN</h4>

  <?php if ($error !== ''): ?>
    <div class="alert alert-danger"><?= htmlspecialchars($error) ?></div>
  <?php endif; ?>

  <?php if ($success !== ''): ?>
    <div class="alert alert-success"><?= htmlspecialchars($success) ?></div>
  <?php endif; ?>

  <div class="row g-3">
    <div class="col-12 col-lg-4">
      <div class="card shadow-sm">
        <div class="card-body">
          <h5 class="card-title mb-3">Add Stock</h5>

          <form method="POST" id="stockForm" autocomplete="off">

            <div class="mb-2">
              <label class="form-label">Scan SKU</label>
              <div class="input-group">
                <input
                  class="form-control"
                  id="scan_sku"
                  type="text"
                  placeholder="Scan/enter SKU then press Enter"
                  autocomplete="off"
                  autocapitalize="off"
                  spellcheck="false"
                >
                <button class="btn btn-outline-primary" type="button" id="btnCamera">Scan with Camera</button>
              </div>
              <div class="form-text">
                Tip: QR codes scan best when the code is sharp, well-lit, and fills a good part of the camera view.
              </div>
            </div>

            <div class="mb-2">
              <label class="form-label">Product</label>
              <select class="form-select" id="product_id" name="product_id" required>
                <option value="0">-- Select --</option>
                <?php foreach ($products as $p): ?>
                  <option value="<?= (int)$p['id'] ?>" data-sku="<?= htmlspecialchars((string)$p['sku'], ENT_QUOTES) ?>">
                    <?= htmlspecialchars($p['name']) ?> (<?= htmlspecialchars($p['sku']) ?>)
                  </option>
                <?php endforeach; ?>
              </select>
            </div>

            <div class="mb-2">
              <label class="form-label">Current Stock</label>
              <input class="form-control" id="current_stock" type="text" value="-" readonly>
            </div>

            <div class="mb-2">
              <label class="form-label">Quantity</label>
              <input class="form-control" id="quantity" name="quantity" type="number" min="1" step="1" required>
            </div>

            <div class="form-check mb-2">
              <input class="form-check-input" type="checkbox" id="auto_submit" checked>
              <label class="form-check-label" for="auto_submit">Auto-submit when Product + Quantity are ready</label>
            </div>

            <div class="mb-2">
              <label class="form-label">Unit Cost (optional)</label>
              <input class="form-control" name="unit_cost" type="number" min="0" step="0.01">
            </div>

            <div class="mb-3">
              <label class="form-label">Notes (optional)</label>
              <input class="form-control" name="notes" maxlength="255">
            </div>

            <button class="btn btn-primary w-100" type="submit">Save Stock IN</button>
          </form>
        </div>
      </div>
    </div>

    <div class="col-12 col-lg-8">
      <div class="card shadow-sm">
        <div class="card-body">
          <h6 class="mb-3">Recent Stock IN</h6>
          <div class="table-responsive">
            <table class="table table-sm align-middle">
              <thead>
                <tr>
                  <th>Date</th>
                  <th>SKU</th>
                  <th>Product</th>
                  <th class="text-end">Qty</th>
                  <th class="text-end">Unit Cost</th>
                </tr>
              </thead>
              <tbody>
                <?php if (!$recent): ?>
                  <tr><td colspan="5" class="text-muted">No records yet.</td></tr>
                <?php else: ?>
                  <?php foreach ($recent as $r): ?>
                    <tr>
                      <td><?= htmlspecialchars($r['created_at']) ?></td>
                      <td><?= htmlspecialchars($r['sku']) ?></td>
                      <td><?= htmlspecialchars($r['name']) ?></td>
                      <td class="text-end"><?= (int)$r['quantity'] ?></td>
                      <td class="text-end"><?= $r['unit_cost'] !== null ? number_format((float)$r['unit_cost'], 2) : '-' ?></td>
                    </tr>
                  <?php endforeach; ?>
                <?php endif; ?>
              </tbody>
            </table>
          </div>

        </div>
      </div>
    </div>
  </div>
</main>

<!-- Camera Scanner Modal -->
<div class="modal fade" id="cameraModal" tabindex="-1" aria-hidden="true">
  <div class="modal-dialog modal-dialog-centered">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title">Scan SKU (QR Camera)</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
      </div>
      <div class="modal-body">
        <div class="alert alert-info py-2 mb-2">
          Point the camera at the QR code. The scanned value must be the product SKU.
        </div>

        <video id="barcode_video" style="width:100%; border-radius: 8px;" muted playsinline></video>
        <div id="scan_status" class="small text-muted mt-2">Ready…</div>

        <div class="small text-muted mt-2">
          If it doesn’t decode: try closer, increase light, avoid glare.
        </div>
      </div>
    </div>
  </div>
</div>

<!-- ZXing (supports many 1D/2D formats) -->
<script src="https://cdn.jsdelivr.net/npm/@zxing/library@0.21.3/umd/index.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/@zxing/browser@0.1.5/umd/zxing-browser.min.js"></script>

<script>
(function () {
  const scanInput = document.getElementById('scan_sku');
  const selectEl = document.getElementById('product_id');
  const qtyEl = document.getElementById('quantity');
  const stockEl = document.getElementById('current_stock');
  const formEl = document.getElementById('stockForm');
  const autoSubmitEl = document.getElementById('auto_submit');
  const btnCamera = document.getElementById('btnCamera');

  const modalEl = document.getElementById('cameraModal');
  const videoEl = document.getElementById('barcode_video');
  const statusEl = document.getElementById('scan_status');

  function normalize(v) { return (v || '').toString().trim(); }

  function flash(el, ok) {
    if (!el) return;
    el.classList.remove('is-valid', 'is-invalid');
    el.classList.add(ok ? 'is-valid' : 'is-invalid');
    setTimeout(() => el.classList.remove('is-valid', 'is-invalid'), 900);
  }

  function maybeAutoSubmit() {
    const pid = parseInt(selectEl.value || '0', 10);
    const q = parseInt(qtyEl.value || '0', 10);
    if (autoSubmitEl && autoSubmitEl.checked && pid > 0 && q > 0) {
      formEl.submit();
    }
  }

  async function lookupSkuAndSelect(sku, {selectProduct=true} = {}) {
    const code = normalize(sku);
    if (!code) return false;

    try {
      const url = window.location.pathname + '?ajax=sku_lookup&sku=' + encodeURIComponent(code);
      const res = await fetch(url, { headers: { 'Accept': 'application/json' } });
      const data = await res.json();

      if (!data.ok) {
        stockEl.value = '-';
        flash(scanInput, false);
        return false;
      }

      const p = data.product;

      if (selectProduct) {
        selectEl.value = String(p.id);
      }
      stockEl.value = String(p.stock);

      flash(scanInput, true);

      if (selectProduct && qtyEl) qtyEl.focus();
      if (selectProduct) maybeAutoSubmit();

      return true;
    } catch (e) {
      stockEl.value = '-';
      flash(scanInput, false);
      return false;
    }
  }

  // USB scanner/manual typing: Enter triggers lookup
  scanInput.addEventListener('keydown', function (e) {
    if (e.key === 'Enter') {
      e.preventDefault();
      const sku = scanInput.value;
      scanInput.value = '';
      lookupSkuAndSelect(sku, {selectProduct:true});
    }
  });

  // If user manually selects product, update stock display
  selectEl.addEventListener('change', function () {
    const opt = selectEl.options[selectEl.selectedIndex];
    const sku = opt && opt.dataset ? opt.dataset.sku : '';
    if (sku) lookupSkuAndSelect(sku, {selectProduct:false});
    else stockEl.value = '-';
  });

  qtyEl.addEventListener('input', () => maybeAutoSubmit());

  // --- Camera scanning (ZXing) ---
  let reader = null;
  let controls = null;
  let cameraModal = null;

  function ensureModal() {
    if (window.bootstrap && window.bootstrap.Modal) {
      cameraModal = new bootstrap.Modal(modalEl);
      return true;
    }
    alert('Bootstrap Modal not available. Please ensure Bootstrap JS is loaded in your templates.');
    return false;
  }

  async function stopCamera() {
    try { if (controls) controls.stop(); } catch (e) {}
    controls = null;
    if (statusEl) statusEl.textContent = 'Stopped.';
  }

  async function startCameraScanner() {
    if (!window.ZXing || !window.ZXingBrowser) {
      alert('Scanner library failed to load. If your host blocks CDN, we must self-host the JS files.');
      return;
    }
    if (!ensureModal()) return;

    cameraModal.show();

    // QR only (faster + more reliable than 1D for phone cameras)
    const formats = [
      ZXing.BarcodeFormat.QR_CODE
    ];

    const hints = new Map();
    hints.set(ZXing.DecodeHintType.POSSIBLE_FORMATS, formats);
    hints.set(ZXing.DecodeHintType.TRY_HARDER, true);

    reader = new ZXing.BrowserMultiFormatReader(hints);

    const constraints = {
      audio: false,
      video: {
        facingMode: { ideal: 'environment' },
        width: { ideal: 1280 },
        height: { ideal: 720 }
      }
    };

    try {
      if (statusEl) statusEl.textContent = 'Starting camera…';

      controls = await reader.decodeFromConstraints(constraints, videoEl, async (result, err) => {
        if (result) {
          const text = normalize(result.getText ? result.getText() : String(result));
          if (statusEl) statusEl.textContent = 'Detected: ' + text;

          await stopCamera();
          cameraModal.hide();

          lookupSkuAndSelect(text, {selectProduct:true});
          return;
        }

        if (err && err.name && err.name !== 'NotFoundException') {
          if (statusEl) statusEl.textContent = 'Scan error: ' + err.name;
        } else {
          if (statusEl) statusEl.textContent = 'Scanning…';
        }
      });

    } catch (err) {
      console.error(err);
      if (statusEl) statusEl.textContent = 'Failed to start.';
      alert(
        "Camera opened but could not decode.\n\nTips:\n" +
        "• Move closer so the QR fills the view\n" +
        "• Improve lighting / avoid glare\n"
      );
    }

    modalEl.addEventListener('hidden.bs.modal', () => stopCamera(), { once: true });
  }

  btnCamera.addEventListener('click', startCameraScanner);

  window.addEventListener('load', () => scanInput.focus());
})();
</script>

<?php require_once __DIR__ . '/../templates/footer.php'; ?>
