<?php
// FILE: public/stock_in.php
require_once __DIR__ . '/../helpers/auth.php';
require_once __DIR__ . '/../helpers/audit.php';
require_once __DIR__ . '/../helpers/inventory.php';

require_role(['admin', 'staff']);

$pdo = db();
$title = 'Stock In - Caerus Tech IMS';
$user = current_user();

function h(?string $value): string
{
    return htmlspecialchars((string)($value ?? ''), ENT_QUOTES, 'UTF-8');
}
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_nullable(string $key): ?float
{
    $raw = trim((string)($_POST[$key] ?? ''));
    if ($raw === '') {
        return null;
    }
    return (float)str_replace(',', '.', $raw);
}
function normalize_optional_datetime(string $input): ?string
{
    $value = trim($input);
    if ($value === '') {
        return null;
    }

    $value = str_replace('T', ' ', $value);
    if (preg_match('/^\d{4}-\d{2}-\d{2} \d{2}:\d{2}$/', $value)) {
        return $value . ':00';
    }
    if (preg_match('/^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}$/', $value)) {
        return $value;
    }
    return null;
}

if (isset($_GET['ajax']) && $_GET['ajax'] === 'lookup') {
    header('Content-Type: application/json; charset=utf-8');
    $code = trim((string)($_GET['code'] ?? ''));
    if ($code === '') {
        echo json_encode(['ok' => false, 'error' => 'Missing scan code']);
        exit;
    }

    try {
        $product = inventory_find_product_by_code($pdo, $code, true);
        if (!$product) {
            echo json_encode(['ok' => false, 'error' => 'Barcode or SKU not found']);
            exit;
        }

        echo json_encode([
            'ok' => true,
            'product' => [
                'id' => (int)$product['id'],
                'sku' => (string)$product['sku'],
                'name' => (string)$product['name'],
                'unit' => (string)($product['unit'] ?? 'pcs'),
                'barcode_value' => (string)($product['barcode_value'] ?? ''),
                'current_stock' => (int)$product['current_stock'],
                'reorder_level' => (int)($product['reorder_level'] ?? 0),
                'supplier_id' => $product['supplier_id'] ?? null,
                'supplier_name' => $product['supplier_name'] ?? '',
            ],
        ]);
    } catch (Throwable $e) {
        http_response_code(500);
        echo json_encode(['ok' => false, 'error' => $e->getMessage()]);
    }
    exit;
}

$error = '';
$success = '';
$lastStock = null;
$supplierOrdersReady = supplier_orders_feature_ready($pdo);

$products = $pdo->query("
    SELECT
        p.id,
        p.sku,
        p.name,
        p.barcode_value,
        p.unit,
        p.supplier_id,
        s.name AS supplier_name
    FROM products p
    LEFT JOIN suppliers s ON s.id = p.supplier_id
    WHERE p.is_active = 1
    ORDER BY p.name ASC
")->fetchAll(PDO::FETCH_ASSOC);

$suppliers = $pdo->query("
    SELECT id, name, contact_person, phone, email, address, city, country
    FROM suppliers
    WHERE is_active = 1
    ORDER BY name ASC
")->fetchAll(PDO::FETCH_ASSOC);

if ($_SERVER['REQUEST_METHOD'] === 'POST' && ($_POST['action'] ?? '') === 'stock_in_manual') {
    $productId = post_int('product_id');
    $qty = post_int('quantity');
    $unitCost = post_float_nullable('unit_cost');
    $notes = post_str('notes');

    if ($productId <= 0 || $qty <= 0) {
        $error = 'Scan a valid product and enter a quantity greater than zero.';
    } else {
        try {
            $result = inventory_create_movement(
                $pdo,
                $productId,
                'IN',
                $qty,
                $unitCost,
                'MANUAL',
                null,
                $notes !== '' ? $notes : null,
                (int)($user['id'] ?? 0),
                false
            );

            $lastStock = $result['current_stock'];
            $product = inventory_get_product($pdo, $productId);

            audit_log('STOCK_IN', 'inventory_movements', (string)$result['movement_id'], json_encode([
                'product_id' => $productId,
                'sku' => $product['sku'] ?? null,
                'barcode_value' => $product['barcode_value'] ?? null,
                'quantity' => $qty,
                'unit_cost' => $unitCost,
            ], JSON_UNESCAPED_SLASHES));

            $success = 'Stock received successfully. New stock level: ' . (int)$lastStock;
        } catch (Throwable $e) {
            $error = 'Unable to save stock entry: ' . $e->getMessage();
        }
    }
}

if ($_SERVER['REQUEST_METHOD'] === 'POST' && ($_POST['action'] ?? '') === 'create_supplier_order') {
    if (!$supplierOrdersReady) {
        $error = 'Supplier scheduled orders are not installed yet. Run schema_update.sql first.';
    } else {
        $supplierId = post_int('supplier_id');
        $expectedArrivalAt = normalize_optional_datetime(post_str('expected_arrival_at'));
        $referenceNo = post_str('reference_no');
        $notes = post_str('order_notes');

        $itemProductIds = $_POST['order_product_id'] ?? [];
        $itemQuantities = $_POST['order_quantity'] ?? [];
        $itemUnitCosts = $_POST['order_unit_cost'] ?? [];

        $items = [];
        if (is_array($itemProductIds) && is_array($itemQuantities) && is_array($itemUnitCosts)) {
            $count = min(count($itemProductIds), count($itemQuantities), count($itemUnitCosts));
            for ($i = 0; $i < $count; $i++) {
                $productId = (int)$itemProductIds[$i];
                $qty = (int)$itemQuantities[$i];
                $rawCost = trim((string)$itemUnitCosts[$i]);
                $unitCost = $rawCost !== '' ? (float)str_replace(',', '.', $rawCost) : null;

                if ($productId > 0 && $qty > 0) {
                    $items[] = [
                        'product_id' => $productId,
                        'quantity_ordered' => $qty,
                        'unit_cost' => $unitCost,
                    ];
                }
            }
        }

        if ($supplierId <= 0) {
            $error = 'Select a supplier for the scheduled order.';
        } elseif (!$expectedArrivalAt) {
            $error = 'Expected arrival date and time is required.';
        } elseif (!$items) {
            $error = 'Add at least one supplier order item.';
        } else {
            try {
                $result = supplier_order_create(
                    $pdo,
                    $supplierId,
                    $expectedArrivalAt,
                    $referenceNo !== '' ? $referenceNo : null,
                    $notes !== '' ? $notes : null,
                    $items,
                    (int)($user['id'] ?? 0)
                );

                audit_log('CREATE_SUPPLIER_ORDER', 'supplier_orders', (string)$result['order_id'], json_encode([
                    'order_code' => $result['order_code'],
                    'supplier_id' => $supplierId,
                    'expected_arrival_at' => $expectedArrivalAt,
                    'item_count' => count($items),
                ], JSON_UNESCAPED_SLASHES));

                $success = 'Supplier order scheduled successfully as ' . $result['order_code'] . '.';
                $supplierOrdersReady = supplier_orders_feature_ready($pdo);
            } catch (Throwable $e) {
                $error = 'Unable to create supplier order: ' . $e->getMessage();
            }
        }
    }
}

if ($_SERVER['REQUEST_METHOD'] === 'POST' && ($_POST['action'] ?? '') === 'receive_supplier_order') {
    if (!$supplierOrdersReady) {
        $error = 'Supplier scheduled orders are not installed yet. Run schema_update.sql first.';
    } else {
        $orderId = post_int('receive_order_id');
        $receiveNote = post_str('receive_note');
        $lineIds = $_POST['receive_line_id'] ?? [];
        $quantities = $_POST['receive_quantity'] ?? [];

        $receiveLines = [];
        if (is_array($lineIds) && is_array($quantities)) {
            $count = min(count($lineIds), count($quantities));
            for ($i = 0; $i < $count; $i++) {
                $lineId = (int)$lineIds[$i];
                $qty = (int)$quantities[$i];
                if ($lineId > 0 && $qty > 0) {
                    $receiveLines[$lineId] = $qty;
                }
            }
        }

        if ($orderId <= 0) {
            $error = 'Select a supplier order to receive.';
        } else {
            try {
                $result = supplier_order_receive(
                    $pdo,
                    $orderId,
                    $receiveLines,
                    (int)($user['id'] ?? 0),
                    $receiveNote !== '' ? $receiveNote : null
                );

                audit_log('RECEIVE_SUPPLIER_ORDER', 'supplier_orders', (string)$orderId, json_encode([
                    'received_total' => $result['received_total'],
                    'status' => $result['status'],
                ], JSON_UNESCAPED_SLASHES));

                $success = 'Supplier order ' . (string)($result['order']['order_code'] ?? ('#' . $orderId)) . ' received successfully. Added qty: ' . (int)$result['received_total'] . '.';
            } catch (Throwable $e) {
                $error = 'Unable to receive supplier order: ' . $e->getMessage();
            }
        }
    }
}

$recent = $pdo->query("
    SELECT
        m.id,
        m.created_at,
        m.quantity,
        m.unit_cost,
        m.notes,
        p.sku,
        p.name,
        p.barcode_value
    FROM inventory_movements m
    INNER JOIN products p ON p.id = m.product_id
    WHERE m.movement_type = 'IN'
    ORDER BY m.created_at DESC, m.id DESC
    LIMIT 20
")->fetchAll(PDO::FETCH_ASSOC);

$scheduledOrders = [];
$orderItemsMap = [];
if ($supplierOrdersReady) {
    $scheduledOrders = $pdo->query("
        SELECT
            so.id,
            so.order_code,
            so.status,
            so.reference_no,
            so.expected_arrival_at,
            so.notes,
            so.created_at,
            s.id AS supplier_id,
            s.name AS supplier_name,
            s.contact_person,
            s.phone,
            s.email,
            s.address,
            s.city,
            s.country,
            COALESCE(SUM(soi.quantity_ordered), 0) AS ordered_total,
            COALESCE(SUM(soi.quantity_received), 0) AS received_total,
            COUNT(soi.id) AS line_count
        FROM supplier_orders so
        INNER JOIN suppliers s ON s.id = so.supplier_id
        LEFT JOIN supplier_order_items soi ON soi.order_id = so.id
        GROUP BY so.id
        ORDER BY
          CASE so.status
            WHEN 'SCHEDULED' THEN 1
            WHEN 'PARTIAL' THEN 2
            WHEN 'RECEIVED' THEN 3
            WHEN 'CANCELLED' THEN 4
            ELSE 5
          END,
          so.expected_arrival_at ASC,
          so.id DESC
        LIMIT 100
    ")->fetchAll(PDO::FETCH_ASSOC);

    foreach ($scheduledOrders as $order) {
        $orderItemsMap[(int)$order['id']] = supplier_order_items($pdo, (int)$order['id']);
    }
}

require_once __DIR__ . '/../templates/header.php';
require_once __DIR__ . '/../templates/sidebar.php';
?>
<main class="col-12 col-lg-10 app-content">
  <div class="page-head">
    <div>
      <div class="page-kicker">Inventory intake</div>
      <h1 class="page-title">Stock in and supplier receiving</h1>
      <p class="page-subtitle">Receive stock manually, schedule incoming supplier orders with ETA, and receive them later with supplier details and item-by-item tracking.</p>
    </div>
  </div>

  <div class="row g-3 mb-3">
    <div class="col-12 col-md-4">
      <div class="stat-card">
        <div class="stat-label">Active products</div>
        <div class="stat-value"><?= count($products) ?></div>
        <div class="stat-sub">Available for receiving</div>
      </div>
    </div>
    <div class="col-12 col-md-4">
      <div class="stat-card">
        <div class="stat-label">Open supplier orders</div>
        <div class="stat-value"><?= $supplierOrdersReady ? count(array_filter($scheduledOrders, fn(array $o): bool => in_array((string)$o['status'], ['SCHEDULED', 'PARTIAL'], true))) : 0 ?></div>
        <div class="stat-sub"><?= $supplierOrdersReady ? 'Scheduled or partially received' : 'Run schema_update.sql first' ?></div>
      </div>
    </div>
    <div class="col-12 col-md-4">
      <div class="stat-card">
        <div class="stat-label">Last new stock</div>
        <div class="stat-value"><?= $lastStock !== null ? (int)$lastStock : '—' ?></div>
        <div class="stat-sub">From your latest successful entry</div>
      </div>
    </div>
  </div>

  <?php if ($error !== ''): ?>
    <div class="alert alert-danger mb-3"><?= h($error) ?></div>
  <?php endif; ?>
  <?php if ($success !== ''): ?>
    <div class="alert alert-success mb-3"><?= h($success) ?></div>
  <?php endif; ?>
  <?php if (!$supplierOrdersReady): ?>
    <div class="alert alert-warning mb-3">Supplier scheduled orders are not ready yet. Run <strong>public/schema_update.sql</strong> once in phpMyAdmin, then reload this page.</div>
  <?php endif; ?>

  <ul class="nav nav-tabs mb-3" id="stockTabs" role="tablist">
    <li class="nav-item" role="presentation">
      <button class="nav-link active" id="tab-receive-now" data-bs-toggle="tab" data-bs-target="#pane-receive-now" type="button" role="tab">Receive now</button>
    </li>
    <li class="nav-item" role="presentation">
      <button class="nav-link" id="tab-supplier-orders" data-bs-toggle="tab" data-bs-target="#pane-supplier-orders" type="button" role="tab">Supplier orders / ETA</button>
    </li>
  </ul>

  <div class="tab-content">
    <div class="tab-pane fade show active" id="pane-receive-now" role="tabpanel">
      <div class="row g-3 align-items-start">
        <div class="col-12 col-xl-5">
          <div class="card scanner-panel">
            <div class="card-body p-4">
              <div class="d-flex justify-content-between align-items-start mb-3">
                <div>
                  <h5 class="mb-1">Receive stock</h5>
                  <div class="text-muted small">Scanner flow: scan barcode → quantity → save.</div>
                </div>
                <button class="btn btn-sm btn-outline-secondary" type="button" id="btnCamera">Camera scan</button>
              </div>

              <form method="post" id="stockForm" autocomplete="off" class="d-grid gap-3">
                <input type="hidden" name="action" value="stock_in_manual">

                <div>
                  <label class="form-label" for="scan_code">Scan barcode or SKU</label>
                  <input class="form-control" id="scan_code" type="text" placeholder="Scan with USB scanner or type manually" autocomplete="off" autocapitalize="off" spellcheck="false">
                  <div class="form-text">Most USB scanners type the code and send Enter automatically.</div>
                </div>

                <div class="soft-panel">
                  <div class="small text-muted mb-1">Selected product</div>
                  <div class="fw-semibold" id="selected_name">No product selected</div>
                  <div class="small text-muted" id="selected_meta">Scan a barcode or choose a product below.</div>
                </div>

                <div>
                  <label class="form-label">Fallback product selector</label>
                  <select class="form-select" id="product_id" name="product_id" required>
                    <option value="0">Select a product</option>
                    <?php foreach ($products as $product): ?>
                      <option
                        value="<?= (int)$product['id'] ?>"
                        data-sku="<?= h($product['sku']) ?>"
                        data-name="<?= h($product['name']) ?>"
                        data-barcode="<?= h($product['barcode_value'] ?? '') ?>"
                        data-unit="<?= h($product['unit'] ?? 'pcs') ?>"
                        data-supplier="<?= h($product['supplier_name'] ?? '') ?>"
                      >
                        <?= h($product['name']) ?> (<?= h($product['sku']) ?><?= !empty($product['barcode_value']) ? ' · ' . h($product['barcode_value']) : '' ?>)
                      </option>
                    <?php endforeach; ?>
                  </select>
                </div>

                <div class="row g-3">
                  <div class="col-md-6">
                    <label class="form-label">Current stock</label>
                    <input class="form-control" id="current_stock" type="text" value="-" readonly>
                  </div>
                  <div class="col-md-6">
                    <label class="form-label">Quantity</label>
                    <input class="form-control" id="quantity" name="quantity" type="number" min="1" step="1" required>
                  </div>
                </div>

                <div class="row g-3">
                  <div class="col-md-6">
                    <label class="form-label">Unit cost</label>
                    <input class="form-control" name="unit_cost" type="number" min="0" step="0.01" placeholder="Optional">
                  </div>
                  <div class="col-md-6 d-flex align-items-end">
                    <div class="form-check">
                      <input class="form-check-input" type="checkbox" id="auto_submit">
                      <label class="form-check-label" for="auto_submit">Auto-save when qty is ready</label>
                    </div>
                  </div>
                </div>

                <div>
                  <label class="form-label">Notes</label>
                  <input class="form-control" name="notes" maxlength="255" placeholder="Supplier batch, receiving note, or reference">
                </div>

                <button class="btn btn-dark w-100" type="submit">Save stock in</button>
              </form>
            </div>
          </div>
        </div>

        <div class="col-12 col-xl-7">
          <div class="card">
            <div class="card-body p-4">
              <h5 class="mb-1">Recent stock-in history</h5>
              <div class="text-muted small mb-3">Fast verification of your latest receiving entries.</div>

              <div class="table-responsive">
                <table class="table align-middle">
                  <thead>
                    <tr>
                      <th>Date</th>
                      <th>Product</th>
                      <th class="text-end">Qty</th>
                      <th class="text-end">Unit cost</th>
                      <th>Notes</th>
                    </tr>
                  </thead>
                  <tbody>
                    <?php if (!$recent): ?>
                      <tr><td colspan="5" class="text-muted">No stock-in records yet.</td></tr>
                    <?php else: ?>
                      <?php foreach ($recent as $row): ?>
                        <tr>
                          <td><?= h($row['created_at']) ?></td>
                          <td>
                            <div class="fw-semibold"><?= h($row['name']) ?></div>
                            <div class="small text-muted"><span class="code-chip"><?= h($row['sku']) ?></span><?= !empty($row['barcode_value']) ? ' · ' . h($row['barcode_value']) : '' ?></div>
                          </td>
                          <td class="text-end fw-semibold"><?= (int)$row['quantity'] ?></td>
                          <td class="text-end"><?= $row['unit_cost'] !== null ? number_format((float)$row['unit_cost'], 2) : '—' ?></td>
                          <td><?= h($row['notes'] ?? '—') ?></td>
                        </tr>
                      <?php endforeach; ?>
                    <?php endif; ?>
                  </tbody>
                </table>
              </div>
            </div>
          </div>
        </div>
      </div>

      <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">Camera barcode scanner</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-3">Supported: UPC-A, UPC-E, EAN, Code 128, Code 39, and QR.</div>
              <video id="barcode_video" style="width:100%; border-radius:14px;" muted playsinline></video>
              <div id="scan_status" class="scanner-status mt-2">Ready to scan.</div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <div class="tab-pane fade" id="pane-supplier-orders" role="tabpanel">
      <div class="row g-3">
        <div class="col-12 col-xl-5">
          <div class="card mb-3">
            <div class="card-body p-4">
              <h5 class="mb-1">Schedule supplier order</h5>
              <div class="text-muted small mb-3">Plan incoming items, set ETA, and track supplier info before stock arrives.</div>

              <form method="post" id="supplierOrderForm" class="d-grid gap-3">
                <input type="hidden" name="action" value="create_supplier_order">

                <div>
                  <label class="form-label">Supplier</label>
                  <select class="form-select" name="supplier_id" id="supplier_id" <?= $supplierOrdersReady ? 'required' : 'disabled' ?>>
                    <option value="0">Select supplier</option>
                    <?php foreach ($suppliers as $supplier): ?>
                      <option
                        value="<?= (int)$supplier['id'] ?>"
                        data-contact="<?= h($supplier['contact_person'] ?? '') ?>"
                        data-phone="<?= h($supplier['phone'] ?? '') ?>"
                        data-email="<?= h($supplier['email'] ?? '') ?>"
                        data-address="<?= h(trim((string)($supplier['address'] ?? ''))) ?>"
                        data-city="<?= h($supplier['city'] ?? '') ?>"
                        data-country="<?= h($supplier['country'] ?? '') ?>"
                      >
                        <?= h($supplier['name']) ?>
                      </option>
                    <?php endforeach; ?>
                  </select>
                </div>

                <div class="soft-panel">
                  <div class="small text-muted mb-1">Supplier info</div>
                  <div class="fw-semibold" id="supplier_info_name">No supplier selected</div>
                  <div class="small text-muted" id="supplier_info_meta">Choose a supplier to preview contact details.</div>
                </div>

                <div class="row g-3">
                  <div class="col-md-6">
                    <label class="form-label">Expected arrival</label>
                    <input class="form-control" type="datetime-local" name="expected_arrival_at" <?= $supplierOrdersReady ? 'required' : 'disabled' ?>>
                  </div>
                  <div class="col-md-6">
                    <label class="form-label">Reference no.</label>
                    <input class="form-control" type="text" name="reference_no" maxlength="120" placeholder="Invoice, PO, tracking no." <?= $supplierOrdersReady ? '' : 'disabled' ?>>
                  </div>
                </div>

                <div>
                  <label class="form-label">Notes</label>
                  <textarea class="form-control" name="order_notes" rows="2" maxlength="255" placeholder="Delivery instructions or procurement note" <?= $supplierOrdersReady ? '' : 'disabled' ?>></textarea>
                </div>

                <div class="soft-panel">
                  <div class="d-flex justify-content-between align-items-center mb-2">
                    <div>
                      <div class="fw-semibold">Order items</div>
                      <div class="text-muted small">Add the products expected from this supplier.</div>
                    </div>
                    <button class="btn btn-sm btn-outline-dark" type="button" id="btnAddOrderRow" <?= $supplierOrdersReady ? '' : 'disabled' ?>>Add item</button>
                  </div>
                  <div id="supplierOrderItems"></div>
                </div>

                <button class="btn btn-dark" type="submit" <?= $supplierOrdersReady ? '' : 'disabled' ?>>Schedule supplier order</button>
              </form>
            </div>
          </div>

          <div class="card">
            <div class="card-body p-4">
              <h5 class="mb-1">Receive scheduled order</h5>
              <div class="text-muted small mb-3">Choose an open supplier order, enter received quantities, and save them into stock.</div>

              <form method="post" id="receiveOrderForm" class="d-grid gap-3">
                <input type="hidden" name="action" value="receive_supplier_order">

                <div>
                  <label class="form-label">Supplier order</label>
                  <select class="form-select" name="receive_order_id" id="receive_order_id" <?= $supplierOrdersReady ? 'required' : 'disabled' ?>>
                    <option value="0">Select scheduled order</option>
                    <?php foreach ($scheduledOrders as $order): ?>
                      <?php if (!in_array((string)$order['status'], ['SCHEDULED', 'PARTIAL'], true)) continue; ?>
                      <option value="<?= (int)$order['id'] ?>">
                        <?= h($order['order_code']) ?> · <?= h($order['supplier_name']) ?> · ETA <?= h((string)$order['expected_arrival_at']) ?>
                      </option>
                    <?php endforeach; ?>
                  </select>
                </div>

                <div class="soft-panel">
                  <div class="small text-muted mb-1">Selected order info</div>
                  <div class="fw-semibold" id="receive_order_info_name">No order selected</div>
                  <div class="small text-muted" id="receive_order_info_meta">Choose an order to view ETA, supplier details, and remaining quantities.</div>
                </div>

                <div id="receiveOrderLines" class="d-grid gap-2"></div>

                <div>
                  <label class="form-label">Receiving note</label>
                  <input class="form-control" type="text" name="receive_note" maxlength="255" placeholder="Condition, batch, reference, or receiving note" <?= $supplierOrdersReady ? '' : 'disabled' ?>>
                </div>

                <button class="btn btn-dark" type="submit" <?= $supplierOrdersReady ? '' : 'disabled' ?>>Receive selected quantities</button>
              </form>
            </div>
          </div>
        </div>

        <div class="col-12 col-xl-7">
          <div class="card">
            <div class="card-body p-4">
              <h5 class="mb-1">Scheduled supplier orders</h5>
              <div class="text-muted small mb-3">ETA monitoring, supplier contact details, and receipt progress.</div>

              <div class="table-responsive">
                <table class="table align-middle">
                  <thead>
                    <tr>
                      <th>Order</th>
                      <th>Supplier</th>
                      <th>ETA</th>
                      <th>Progress</th>
                      <th>Status</th>
                    </tr>
                  </thead>
                  <tbody>
                    <?php if (!$scheduledOrders): ?>
                      <tr><td colspan="5" class="text-muted"><?= $supplierOrdersReady ? 'No supplier orders yet.' : 'Supplier scheduled orders are not installed yet.' ?></td></tr>
                    <?php else: ?>
                      <?php foreach ($scheduledOrders as $order): ?>
                        <?php
                          $orderedTotal = (int)$order['ordered_total'];
                          $receivedTotal = (int)$order['received_total'];
                          $remainingTotal = max(0, $orderedTotal - $receivedTotal);
                        ?>
                        <tr>
                          <td>
                            <div class="fw-semibold"><?= h($order['order_code']) ?></div>
                            <div class="small text-muted"><?= h($order['reference_no'] ?: 'No reference') ?></div>
                            <div class="small text-muted">Lines: <?= (int)$order['line_count'] ?></div>
                          </td>
                          <td>
                            <div class="fw-semibold"><?= h($order['supplier_name']) ?></div>
                            <div class="small text-muted"><?= h($order['contact_person'] ?: 'No contact person') ?></div>
                            <div class="small text-muted"><?= h($order['phone'] ?: 'No phone') ?><?= $order['email'] ? ' · ' . h($order['email']) : '' ?></div>
                          </td>
                          <td>
                            <div><?= h($order['expected_arrival_at'] ?: '—') ?></div>
                            <div class="small text-muted"><?= h(trim(implode(', ', array_filter([$order['city'], $order['country']])))) ?></div>
                          </td>
                          <td>
                            <div class="fw-semibold"><?= $receivedTotal ?> / <?= $orderedTotal ?></div>
                            <div class="small text-muted">Remaining: <?= $remainingTotal ?></div>
                          </td>
                          <td>
                            <span class="status-pill status-<?= h((string)$order['status']) ?>"><?= h((string)$order['status']) ?></span>
                          </td>
                        </tr>
                        <?php if (!empty($order['notes'])): ?>
                          <tr>
                            <td colspan="5" class="pt-0">
                              <div class="small text-muted"><strong>Notes:</strong> <?= h($order['notes']) ?></div>
                            </td>
                          </tr>
                        <?php endif; ?>
                      <?php endforeach; ?>
                    <?php endif; ?>
                  </tbody>
                </table>
              </div>

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

<template id="supplierOrderItemTemplate">
  <div class="row g-2 align-items-start supplier-order-row mb-2">
    <div class="col-12 col-md-6">
      <select class="form-select" name="order_product_id[]" required>
        <option value="0">Select product</option>
        <?php foreach ($products as $product): ?>
          <option
            value="<?= (int)$product['id'] ?>"
            data-sku="<?= h($product['sku']) ?>"
            data-supplier-id="<?= (int)($product['supplier_id'] ?? 0) ?>"
            data-supplier-name="<?= h($product['supplier_name'] ?? '') ?>"
            data-unit="<?= h($product['unit'] ?? 'pcs') ?>"
          >
            <?= h($product['name']) ?> (<?= h($product['sku']) ?>)
          </option>
        <?php endforeach; ?>
      </select>
      <div class="small text-muted supplier-order-hint mt-1">Select a product.</div>
    </div>
    <div class="col-6 col-md-3">
      <input class="form-control" type="number" min="1" step="1" name="order_quantity[]" placeholder="Qty" required>
    </div>
    <div class="col-4 col-md-2">
      <input class="form-control" type="number" min="0" step="0.01" name="order_unit_cost[]" placeholder="Unit cost">
    </div>
    <div class="col-2 col-md-1 d-grid">
      <button class="btn btn-outline-danger remove-supplier-order-row" type="button">×</button>
    </div>
  </div>
</template>

<?php require_once __DIR__ . '/../templates/footer.php'; ?>
<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_code');
  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 selectedNameEl = document.getElementById('selected_name');
  const selectedMetaEl = document.getElementById('selected_meta');
  const btnCamera = document.getElementById('btnCamera');
  const modalEl = document.getElementById('cameraModal');
  const videoEl = document.getElementById('barcode_video');
  const statusEl = document.getElementById('scan_status');
  const cameraModal = new bootstrap.Modal(modalEl);
  let controls = null;
  let cameraStream = null;
  let scanTimer = null;
  let zxingReader = null;

  function setSelected(product) {
    if (!product) {
      selectEl.value = '0';
      selectedNameEl.textContent = 'No product selected';
      selectedMetaEl.textContent = 'Scan a barcode or choose a product below.';
      stockEl.value = '-';
      return;
    }

    if (product.id) {
      selectEl.value = String(product.id);
    }

    selectedNameEl.textContent = product.name || 'Selected product';
    const bits = [];
    if (product.sku) bits.push('SKU ' + product.sku);
    if (product.barcode_value) bits.push('Barcode ' + product.barcode_value);
    if (product.unit) bits.push(product.unit);
    if (product.supplier_name) bits.push('Supplier ' + product.supplier_name);
    selectedMetaEl.textContent = bits.join(' · ') || 'Product matched.';
    stockEl.value = String(product.current_stock ?? '-');
  }

  function digitsOnly(value) {
    return String(value || '').replace(/\D+/g, '');
  }

  function buildLookupCandidates(value) {
    const raw = String(value || '').trim();
    if (!raw) return [];

    const digits = digitsOnly(raw);
    const candidates = [];
    const push = (candidate) => {
      candidate = String(candidate || '').trim();
      if (candidate && !candidates.includes(candidate)) {
        candidates.push(candidate);
      }
    };

    push(raw);
    push(digits);

    if (digits) {
      push(digits.replace(/^0+/, ''));
      if (digits.length === 13 && digits.startsWith('0')) {
        push(digits.slice(1));
      }
      if (digits.length === 12) {
        push('0' + digits);
      }
    }

    return candidates.filter(Boolean);
  }

  function optionToProduct(option) {
    if (!option || !option.value || option.value === '0') {
      return null;
    }

    return {
      id: Number(option.value || 0),
      name: option.dataset.name || String(option.textContent || '').split(' (')[0].trim(),
      sku: option.dataset.sku || '',
      barcode_value: option.dataset.barcode || '',
      unit: option.dataset.unit || '',
      supplier_name: option.dataset.supplier || '',
      current_stock: option.dataset.stock !== undefined && option.dataset.stock !== '' ? Number(option.dataset.stock) : '-',
    };
  }

  function findLocalProduct(code) {
    const candidates = buildLookupCandidates(code);
    if (!candidates.length) return null;

    for (const option of Array.from(selectEl.options)) {
      const product = optionToProduct(option);
      if (!product) continue;

      const productCandidates = new Set([
        ...buildLookupCandidates(product.barcode_value),
        ...buildLookupCandidates(product.sku),
      ]);

      for (const candidate of candidates) {
        if (productCandidates.has(candidate)) {
          return product;
        }
      }
    }

    return null;
  }

  function maybeAutoSubmit() {
    const pid = Number(selectEl.value || 0);
    const qty = Number(qtyEl.value || 0);
    if (autoSubmitEl.checked && pid > 0 && qty > 0) {
      formEl.submit();
    }
  }

  async function lookupProduct(code, focusQty = true) {
    const value = String(code || '').trim();
    if (!value) {
      setSelected(null);
      return false;
    }

    const localProduct = findLocalProduct(value);
    if (localProduct) {
      setSelected(localProduct);
      statusEl.textContent = 'Matched ' + localProduct.name;
      if (focusQty) qtyEl.focus();
      maybeAutoSubmit();
    }

    try {
      const res = await fetch(`stock_in.php?ajax=lookup&code=${encodeURIComponent(value)}`, {
        headers: { 'Accept': 'application/json' }
      });
      const data = await res.json();
      if (!data.ok) {
        if (localProduct) {
          return true;
        }
        setSelected(null);
        statusEl.textContent = data.error || 'Product not found.';
        return false;
      }

      const product = data.product;
      setSelected(product);
      statusEl.textContent = 'Matched ' + product.name;
      if (focusQty) qtyEl.focus();
      maybeAutoSubmit();
      return true;
    } catch (error) {
      if (localProduct) {
        return true;
      }
      statusEl.textContent = 'Lookup failed.';
      return false;
    }
  }

  let lookupTimer = null;

  function scheduleLookup(delay = 250, focusQty = false) {
    const code = String(scanInput.value || '').trim();
    window.clearTimeout(lookupTimer);

    if (!code) {
      setSelected(null);
      return;
    }

    lookupTimer = window.setTimeout(() => {
      lookupProduct(code, focusQty);
    }, delay);
  }

  scanInput.addEventListener('keydown', function (event) {
    if (event.key === 'Enter') {
      event.preventDefault();
      window.clearTimeout(lookupTimer);
      lookupProduct(scanInput.value, true);
    }
  });

  scanInput.addEventListener('input', function () {
    scheduleLookup(250, false);
  });

  scanInput.addEventListener('change', function () {
    scheduleLookup(0, false);
  });

  scanInput.addEventListener('blur', function () {
    scheduleLookup(0, false);
  });

  scanInput.addEventListener('paste', function () {
    window.setTimeout(() => scheduleLookup(0, false), 0);
  });

  selectEl.addEventListener('change', function () {
    const option = selectEl.options[selectEl.selectedIndex];
    const preferred = option?.dataset?.barcode || option?.dataset?.sku || '';
    if (!preferred) {
      setSelected(null);
      return;
    }
    lookupProduct(preferred, false);
  });

  qtyEl.addEventListener('input', maybeAutoSubmit);

  async function stopCamera() {
    try {
      if (scanTimer) {
        window.clearInterval(scanTimer);
      }
    } catch (error) {}
    scanTimer = null;

    try {
      if (controls && typeof controls.stop === 'function') {
        controls.stop();
      }
    } catch (error) {}
    controls = null;

    try {
      if (zxingReader && typeof zxingReader.reset === 'function') {
        zxingReader.reset();
      }
    } catch (error) {}
    zxingReader = null;

    try {
      if (cameraStream) {
        cameraStream.getTracks().forEach((track) => track.stop());
      }
    } catch (error) {}
    cameraStream = null;

    try {
      videoEl.pause();
      videoEl.srcObject = null;
      videoEl.removeAttribute('src');
      videoEl.load();
    } catch (error) {}
  }

  function normalizeScannedCode(value) {
    return String(value || '').replace(/\s+/g, '').trim();
  }

  async function handleDetectedCode(rawText) {
    const text = normalizeScannedCode(rawText);
    if (!text) return;
    statusEl.textContent = 'Detected ' + text;
    scanInput.value = text;
    await stopCamera();
    cameraModal.hide();
    lookupProduct(text, true);
  }

  async function startBarcodeDetectorScanner() {
    const supportedFormats = [
      'ean_13', 'ean_8', 'upc_a', 'upc_e', 'code_128', 'code_39', 'codabar', 'itf'
    ];
    const detector = new BarcodeDetector({ formats: supportedFormats });

    cameraStream = await navigator.mediaDevices.getUserMedia({
      audio: false,
      video: {
        facingMode: { ideal: 'environment' },
        width: { ideal: 1280 },
        height: { ideal: 720 }
      }
    });

    videoEl.setAttribute('autoplay', 'autoplay');
    videoEl.setAttribute('muted', 'muted');
    videoEl.setAttribute('playsinline', 'playsinline');
    videoEl.srcObject = cameraStream;
    await videoEl.play();

    statusEl.textContent = 'Scanning... point the barcode clearly inside the camera.';

    scanTimer = window.setInterval(async function () {
      if (!videoEl.videoWidth || !videoEl.videoHeight) {
        return;
      }

      try {
        const barcodes = await detector.detect(videoEl);
        if (barcodes && barcodes.length > 0) {
          const raw = barcodes[0].rawValue || '';
          if (raw) {
            await handleDetectedCode(raw);
          }
        }
      } catch (error) {
        statusEl.textContent = 'Scanning...';
      }
    }, 300);
  }

  async function startZXingScanner() {
    if (!window.ZXingBrowser || !window.ZXing) {
      throw new Error('Scanner library failed to load.');
    }

    const formats = [
      ZXing.BarcodeFormat.UPC_A,
      ZXing.BarcodeFormat.UPC_E,
      ZXing.BarcodeFormat.EAN_13,
      ZXing.BarcodeFormat.EAN_8,
      ZXing.BarcodeFormat.CODE_128,
      ZXing.BarcodeFormat.CODE_39,
      ZXing.BarcodeFormat.CODE_93,
      ZXing.BarcodeFormat.ITF,
      ZXing.BarcodeFormat.CODABAR,
      ZXing.BarcodeFormat.QR_CODE,
    ];

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

    zxingReader = new ZXingBrowser.BrowserMultiFormatReader(hints);

    const devices = await ZXingBrowser.BrowserCodeReader.listVideoInputDevices();
    let preferredDeviceId = null;
    if (devices && devices.length) {
      const rear = devices.find((device) => /back|rear|environment/i.test(device.label || ''));
      preferredDeviceId = (rear || devices[0]).deviceId;
    }

    statusEl.textContent = 'Scanning... point the barcode clearly inside the camera.';
    controls = await zxingReader.decodeFromVideoDevice(preferredDeviceId, videoEl, async (result, err) => {
      if (result) {
        const text = result.getText ? result.getText() : String(result);
        await handleDetectedCode(text);
        return;
      }

      if (err && err.name && err.name !== 'NotFoundException') {
        statusEl.textContent = 'Trying to focus camera...';
      }
    });
  }

  async function startCamera() {
    if (!window.isSecureContext) {
      alert('Phone camera scanning needs HTTPS. Open the site with https:// first.');
      return;
    }

    if (!navigator.mediaDevices || !navigator.mediaDevices.getUserMedia) {
      alert('This browser does not support camera scanning on this page.');
      return;
    }

    await stopCamera();
    cameraModal.show();
    statusEl.textContent = 'Starting camera...';

    try {
      if ('BarcodeDetector' in window) {
        await startBarcodeDetectorScanner();
      } else {
        await startZXingScanner();
      }
    } catch (error) {
      console.error('Camera scanner error:', error);
      statusEl.textContent = error && error.message ? error.message : 'Camera failed to start.';
    }
  }

  btnCamera.addEventListener('click', startCamera);
  modalEl.addEventListener('hidden.bs.modal', stopCamera);
  window.addEventListener('load', function () {
    scanInput.focus();
  });
})();

(function () {
  const supplierSelect = document.getElementById('supplier_id');
  const supplierInfoName = document.getElementById('supplier_info_name');
  const supplierInfoMeta = document.getElementById('supplier_info_meta');
  const itemsContainer = document.getElementById('supplierOrderItems');
  const itemTemplate = document.getElementById('supplierOrderItemTemplate');
  const addRowBtn = document.getElementById('btnAddOrderRow');

  if (!supplierSelect || !itemsContainer || !itemTemplate || !addRowBtn) {
    return;
  }

  function refreshSupplierInfo() {
    const option = supplierSelect.options[supplierSelect.selectedIndex];
    if (!option || !option.value || option.value === '0') {
      supplierInfoName.textContent = 'No supplier selected';
      supplierInfoMeta.textContent = 'Choose a supplier to preview contact details.';
      return;
    }

    supplierInfoName.textContent = option.textContent.trim();
    const meta = [
      option.dataset.contact || '',
      option.dataset.phone || '',
      option.dataset.email || '',
      [option.dataset.address || '', option.dataset.city || '', option.dataset.country || ''].filter(Boolean).join(', ')
    ].filter(Boolean).join(' · ');
    supplierInfoMeta.textContent = meta || 'No extra supplier info available.';
  }

  function refreshOrderHint(row) {
    const select = row.querySelector('select[name="order_product_id[]"]');
    const hint = row.querySelector('.supplier-order-hint');
    const option = select.options[select.selectedIndex];

    if (!option || !option.value || option.value === '0') {
      hint.textContent = 'Select a product.';
      return;
    }

    const bits = [];
    if (option.dataset.sku) bits.push('SKU ' + option.dataset.sku);
    if (option.dataset.unit) bits.push(option.dataset.unit);
    if (option.dataset.supplierName) bits.push('Default supplier ' + option.dataset.supplierName);
    hint.textContent = bits.join(' · ');
  }

  function bindOrderRow(row) {
    row.querySelector('.remove-supplier-order-row').addEventListener('click', () => {
      if (itemsContainer.children.length > 1) {
        row.remove();
      } else {
        row.querySelector('select[name="order_product_id[]"]').value = '0';
        row.querySelector('input[name="order_quantity[]"]').value = '';
        row.querySelector('input[name="order_unit_cost[]"]').value = '';
        refreshOrderHint(row);
      }
    });

    row.querySelector('select[name="order_product_id[]"]').addEventListener('change', function () {
      refreshOrderHint(row);
      const option = this.options[this.selectedIndex];
      const productSupplierId = Number(option?.dataset?.supplierId || 0);
      if (productSupplierId > 0 && Number(supplierSelect.value || 0) === 0) {
        supplierSelect.value = String(productSupplierId);
        refreshSupplierInfo();
      }
    });
  }

  function addOrderRow() {
    const fragment = itemTemplate.content.cloneNode(true);
    const row = fragment.querySelector('.supplier-order-row');
    bindOrderRow(row);
    itemsContainer.appendChild(fragment);
  }

  if (!addRowBtn.disabled) {
    addRowBtn.addEventListener('click', addOrderRow);
    addOrderRow();
  }

  supplierSelect.addEventListener('change', refreshSupplierInfo);
  refreshSupplierInfo();
})();

(function () {
  const orders = <?= json_encode($scheduledOrders, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE) ?>;
  const orderItemsMap = <?= json_encode($orderItemsMap, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE) ?>;

  const select = document.getElementById('receive_order_id');
  const infoName = document.getElementById('receive_order_info_name');
  const infoMeta = document.getElementById('receive_order_info_meta');
  const linesWrap = document.getElementById('receiveOrderLines');

  if (!select || !infoName || !infoMeta || !linesWrap) {
    return;
  }

  function renderOrder() {
    const id = Number(select.value || 0);
    const order = orders.find(o => Number(o.id) === id);

    linesWrap.innerHTML = '';

    if (!order) {
      infoName.textContent = 'No order selected';
      infoMeta.textContent = 'Choose an order to view ETA, supplier details, and remaining quantities.';
      return;
    }

    infoName.textContent = `${order.order_code} · ${order.supplier_name}`;
    infoMeta.textContent = [
      order.expected_arrival_at ? 'ETA ' + order.expected_arrival_at : '',
      order.contact_person || '',
      order.phone || '',
      order.email || '',
      order.reference_no ? 'Ref ' + order.reference_no : ''
    ].filter(Boolean).join(' · ');

    const items = orderItemsMap[String(id)] || orderItemsMap[id] || [];
    if (!items.length) {
      linesWrap.innerHTML = '<div class="text-muted small">No order lines found.</div>';
      return;
    }

    items.forEach((item) => {
      const remaining = Math.max(0, Number(item.quantity_remaining || 0));
      const div = document.createElement('div');
      div.className = 'soft-panel';

      div.innerHTML = `
        <input type="hidden" name="receive_line_id[]" value="${Number(item.id)}">
        <div class="d-flex flex-wrap justify-content-between gap-2">
          <div>
            <div class="fw-semibold">${String(item.name || '')}</div>
            <div class="small text-muted">SKU ${String(item.sku || '')}${item.barcode_value ? ' · ' + String(item.barcode_value) : ''}</div>
            <div class="small text-muted">Ordered ${Number(item.quantity_ordered || 0)} · Received ${Number(item.quantity_received || 0)} · Remaining ${remaining}</div>
          </div>
          <div style="min-width: 140px;">
            <label class="form-label small">Receive now</label>
            <input class="form-control" type="number" min="0" max="${remaining}" step="1" name="receive_quantity[]" value="${remaining > 0 ? remaining : 0}">
          </div>
        </div>
      `;

      linesWrap.appendChild(div);
    });
  }

  select.addEventListener('change', renderOrder);
  renderOrder();
})();
</script>