<?php
require_once __DIR__ . '/../helpers/auth.php';
require_once __DIR__ . '/../helpers/audit.php';
require_once __DIR__ . '/../helpers/barcode_utils.php';
require_once __DIR__ . '/../helpers/inventory.php';

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

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

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(string $key): float
{
    $value = str_replace(',', '.', trim((string)($_POST[$key] ?? '0')));
    return (float)$value;
}
function product_exists_by_barcode(PDO $pdo, string $barcode, ?int $excludeId = null): bool
{
    if ($excludeId) {
        $stmt = $pdo->prepare('SELECT id FROM products WHERE barcode_value = :barcode AND id <> :id LIMIT 1');
        $stmt->execute([':barcode' => $barcode, ':id' => $excludeId]);
    } else {
        $stmt = $pdo->prepare('SELECT id FROM products WHERE barcode_value = :barcode LIMIT 1');
        $stmt->execute([':barcode' => $barcode]);
    }
    return (bool)$stmt->fetchColumn();
}
function product_exists_by_sku(PDO $pdo, string $sku, ?int $excludeId = null): bool
{
    if ($excludeId) {
        $stmt = $pdo->prepare('SELECT id FROM products WHERE sku = :sku AND id <> :id LIMIT 1');
        $stmt->execute([':sku' => $sku, ':id' => $excludeId]);
    } else {
        $stmt = $pdo->prepare('SELECT id FROM products WHERE sku = :sku LIMIT 1');
        $stmt->execute([':sku' => $sku]);
    }
    return (bool)$stmt->fetchColumn();
}
function status_pill_class(string $status): string
{
    return match (strtoupper($status)) {
        'LOW' => 'status-pill status-low',
        'OK' => 'status-pill status-ok',
        default => 'status-pill status-neutral',
    };
}
function format_money(float $amount): string
{
    return '€' . number_format($amount, 2);
}

$errors = [];
$success = '';
$q = trim((string)($_GET['q'] ?? ''));

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = post_str('action');

    if ($action === 'add') {
        $name = post_str('name');
        $sku = post_str('sku');
        $category_id = post_int('category_id') ?: null;
        $supplier_id = post_int('supplier_id') ?: null;
        $description = post_str('description');
        $unit = post_str('unit') ?: 'pcs';
        $cost_price = post_float('cost_price');
        $sell_price = post_float('sell_price');
        $reorder_level = max(0, post_int('reorder_level'));
        $is_active = post_int('is_active') ? 1 : 0;
        $barcode_value = normalize_barcode_value(post_str('barcode_value'));

        if ($name === '') {
            $errors[] = 'Product name is required.';
        }
        if ($sku === '') {
            $errors[] = 'SKU is required.';
        }
        if ($sku !== '' && product_exists_by_sku($pdo, $sku)) {
            $errors[] = 'SKU already exists.';
        }

        if ($barcode_value !== '') {
            if (!is_supported_product_barcode($barcode_value)) {
                $errors[] = 'Barcode must be numeric and at least 12 digits. Leave blank to auto-generate.';
            } elseif (product_exists_by_barcode($pdo, $barcode_value)) {
                $errors[] = 'Barcode already exists.';
            }
        }

        if (!$errors) {
            try {
                $pdo->beginTransaction();

                $stmt = $pdo->prepare('
                    INSERT INTO products
                        (category_id, supplier_id, sku, name, description, unit, cost_price, sell_price, reorder_level, is_active, barcode_value, barcode_type, barcode_generated, quantity_on_hand)
                    VALUES
                        (:category_id, :supplier_id, :sku, :name, :description, :unit, :cost_price, :sell_price, :reorder_level, :is_active, NULL, :barcode_type, 0, 0)
                ');
                $stmt->execute([
                    ':category_id' => $category_id,
                    ':supplier_id' => $supplier_id,
                    ':sku' => $sku,
                    ':name' => $name,
                    ':description' => $description !== '' ? $description : null,
                    ':unit' => $unit,
                    ':cost_price' => $cost_price,
                    ':sell_price' => $sell_price,
                    ':reorder_level' => $reorder_level,
                    ':is_active' => $is_active,
                    ':barcode_type' => 'CUSTOM',
                ]);

                $newId = (int)$pdo->lastInsertId();
                $generated = 0;
                if ($barcode_value === '') {
                    $barcode_value = generate_upc_a_from_product_id($newId, '200');
                    $generated = 1;
                }

                $barcodeType = detect_barcode_type($barcode_value, $generated === 1);

                $barcodeUpdate = $pdo->prepare('UPDATE products SET barcode_value = :barcode_value, barcode_generated = :generated, barcode_type = :barcode_type WHERE id = :id');
                $barcodeUpdate->execute([
                    ':barcode_value' => $barcode_value,
                    ':generated' => $generated,
                    ':barcode_type' => $barcodeType,
                    ':id' => $newId,
                ]);

                inventory_sync_product_quantity($pdo, $newId);
                $pdo->commit();

                audit_log('CREATE_PRODUCT', 'products', (string)$newId, json_encode([
                    'sku' => $sku,
                    'name' => $name,
                    'barcode_value' => $barcode_value,
                ], JSON_UNESCAPED_SLASHES));

                $success = 'Product added successfully. Barcode: ' . $barcode_value;
            } catch (Throwable $e) {
                if ($pdo->inTransaction()) {
                    $pdo->rollBack();
                }
                $errors[] = 'Failed to add product: ' . $e->getMessage();
            }
        }
    }

    if ($action === 'edit') {
        $id = post_int('id');
        $name = post_str('name');
        $sku = post_str('sku');
        $category_id = post_int('category_id') ?: null;
        $supplier_id = post_int('supplier_id') ?: null;
        $description = post_str('description');
        $unit = post_str('unit') ?: 'pcs';
        $cost_price = post_float('cost_price');
        $sell_price = post_float('sell_price');
        $reorder_level = max(0, post_int('reorder_level'));
        $is_active = post_int('is_active') ? 1 : 0;
        $barcode_value = normalize_barcode_value(post_str('barcode_value'));

        if ($id <= 0) {
            $errors[] = 'Invalid product ID.';
        }
        if ($name === '') {
            $errors[] = 'Product name is required.';
        }
        if ($sku === '') {
            $errors[] = 'SKU is required.';
        }
        if ($sku !== '' && product_exists_by_sku($pdo, $sku, $id)) {
            $errors[] = 'SKU already exists.';
        }
        if ($barcode_value === '') {
            $errors[] = 'Barcode is required.';
        } elseif (!is_supported_product_barcode($barcode_value)) {
            $errors[] = 'Barcode must be numeric and at least 12 digits.';
        } elseif (product_exists_by_barcode($pdo, $barcode_value, $id)) {
            $errors[] = 'Barcode already exists.';
        }

        if (!$errors) {
            try {
                $stmt = $pdo->prepare('
                    UPDATE products
                    SET
                        category_id = :category_id,
                        supplier_id = :supplier_id,
                        sku = :sku,
                        name = :name,
                        description = :description,
                        unit = :unit,
                        cost_price = :cost_price,
                        sell_price = :sell_price,
                        reorder_level = :reorder_level,
                        is_active = :is_active,
                        barcode_value = :barcode_value,
                        barcode_type = :barcode_type,
                        barcode_generated = 0
                    WHERE id = :id
                ');
                $stmt->execute([
                    ':category_id' => $category_id,
                    ':supplier_id' => $supplier_id,
                    ':sku' => $sku,
                    ':name' => $name,
                    ':description' => $description !== '' ? $description : null,
                    ':unit' => $unit,
                    ':cost_price' => $cost_price,
                    ':sell_price' => $sell_price,
                    ':reorder_level' => $reorder_level,
                    ':is_active' => $is_active,
                    ':barcode_value' => $barcode_value,
                    ':barcode_type' => detect_barcode_type($barcode_value, false),
                    ':id' => $id,
                ]);

                audit_log('UPDATE_PRODUCT', 'products', (string)$id, json_encode([
                    'sku' => $sku,
                    'name' => $name,
                    'barcode_value' => $barcode_value,
                ], JSON_UNESCAPED_SLASHES));

                $success = 'Product updated successfully.';
            } catch (Throwable $e) {
                $errors[] = 'Failed to update product: ' . $e->getMessage();
            }
        }
    }

    if ($action === 'delete') {
        $id = post_int('id');
        if ($id <= 0) {
            $errors[] = 'Invalid product ID.';
        }

        if (!$errors) {
            try {
                $pdo->beginTransaction();
                $productBeforeDelete = inventory_get_product($pdo, $id);

                $pdo->prepare('DELETE FROM inventory_movements WHERE product_id = :id')->execute([':id' => $id]);
                $pdo->prepare('DELETE FROM delivery_items WHERE product_id = :id')->execute([':id' => $id]);
                $pdo->prepare('DELETE FROM products WHERE id = :id')->execute([':id' => $id]);

                $pdo->commit();

                audit_log('DELETE_PRODUCT', 'products', (string)$id, json_encode([
                    'sku' => $productBeforeDelete['sku'] ?? null,
                    'name' => $productBeforeDelete['name'] ?? null,
                ], JSON_UNESCAPED_SLASHES));

                $success = 'Product deleted successfully.';
            } catch (Throwable $e) {
                if ($pdo->inTransaction()) {
                    $pdo->rollBack();
                }
                $errors[] = 'Failed to delete product: ' . $e->getMessage();
            }
        }
    }
}

$categories = $pdo->query('SELECT id, name FROM product_categories ORDER BY name ASC')->fetchAll(PDO::FETCH_ASSOC);
$suppliers = $pdo->query('SELECT id, name FROM suppliers WHERE is_active = 1 ORDER BY name ASC')->fetchAll(PDO::FETCH_ASSOC);

$params = [];
$where = '';
if ($q !== '') {
    $where = 'WHERE p.name LIKE :q OR p.sku LIKE :q OR p.barcode_value LIKE :q';
    $params[':q'] = '%' . $q . '%';
}

$sql = '
    SELECT
        p.*,
        c.name AS category_name,
        s.name AS supplier_name,
        COALESCE(stock_summary.current_stock, p.quantity_on_hand, 0) AS current_stock
    FROM products p
    LEFT JOIN product_categories c ON c.id = p.category_id
    LEFT JOIN suppliers s ON s.id = p.supplier_id
    LEFT JOIN (
        SELECT m.product_id, ' . inventory_stock_expression('m') . ' AS current_stock
        FROM inventory_movements m
        GROUP BY m.product_id
    ) stock_summary ON stock_summary.product_id = p.id
    ' . $where . '
    ORDER BY p.id DESC
';
$stmt = $pdo->prepare($sql);
$stmt->execute($params);
$products = $stmt->fetchAll(PDO::FETCH_ASSOC);

$totalProducts = count($products);
$activeProducts = count(array_filter($products, static fn(array $row): bool => (int)$row['is_active'] === 1));
$lowStockProducts = count(array_filter($products, static function (array $row): bool {
    $stock = (int)$row['current_stock'];
    $reorder = (int)$row['reorder_level'];
    return $reorder > 0 && $stock <= $reorder;
}));
$generatedBarcodes = count(array_filter($products, static fn(array $row): bool => (int)$row['barcode_generated'] === 1));

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">Catalog</div>
      <h1 class="page-title">Products</h1>
      <p class="page-subtitle">Manage your product master data, barcode assignments, pricing, and reorder thresholds. Stock-in and stock-out pages can now scan either the barcode or the SKU.</p>
    </div>
    <form class="d-flex gap-2 align-items-start" method="get">
      <input class="form-control" name="q" placeholder="Search name, SKU, or barcode" value="<?= h($q) ?>">
      <button class="btn btn-outline-secondary" type="submit">Search</button>
      <?php if ($q !== ''): ?>
        <a class="btn btn-outline-secondary" href="products.php">Reset</a>
      <?php endif; ?>
    </form>
  </div>

  <div class="row g-3 mb-3">
    <div class="col-12 col-sm-6 col-xl-3"><div class="stat-card"><div class="stat-label">Visible products</div><div class="stat-value"><?= $totalProducts ?></div><div class="stat-sub">Current result set</div></div></div>
    <div class="col-12 col-sm-6 col-xl-3"><div class="stat-card"><div class="stat-label">Active</div><div class="stat-value"><?= $activeProducts ?></div><div class="stat-sub">Ready for inventory transactions</div></div></div>
    <div class="col-12 col-sm-6 col-xl-3"><div class="stat-card"><div class="stat-label">Low stock</div><div class="stat-value"><?= $lowStockProducts ?></div><div class="stat-sub">At or below reorder level</div></div></div>
    <div class="col-12 col-sm-6 col-xl-3"><div class="stat-card"><div class="stat-label">Auto barcodes</div><div class="stat-value"><?= $generatedBarcodes ?></div><div class="stat-sub">Generated internally</div></div></div>
  </div>

  <?php if ($errors): ?>
    <div class="alert alert-danger mb-3">
      <ul class="mb-0 ps-3">
        <?php foreach ($errors as $error): ?>
          <li><?= h($error) ?></li>
        <?php endforeach; ?>
      </ul>
    </div>
  <?php endif; ?>

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

  <div class="row g-3 align-items-start">
    <div class="col-12 col-xl-4">
      <div class="card">
        <div class="card-body p-4">
          <div class="d-flex justify-content-between align-items-center mb-3">
            <div>
              <h5 class="mb-1">Add product</h5>
              <div class="text-muted small">Leave barcode blank to auto-generate an internal 12-digit barcode, or enter the product's real barcode (12 digits or more).</div>
            </div>
          </div>

          <form method="post" autocomplete="off" class="d-grid gap-3">
            <input type="hidden" name="action" value="add">
            <div>
              <label class="form-label">Product name</label>
              <input class="form-control" type="text" name="name" required>
            </div>
            <div class="row g-3">
              <div class="col-md-6">
                <label class="form-label">SKU</label>
                <input class="form-control" type="text" name="sku" required>
              </div>
              <div class="col-md-6">
                <label class="form-label">Unit</label>
                <input class="form-control" type="text" name="unit" value="pcs">
              </div>
            </div>
            <div class="row g-3">
              <div class="col-md-6">
                <label class="form-label">Category</label>
                <select class="form-select" name="category_id">
                  <option value="0">No category</option>
                  <?php foreach ($categories as $category): ?>
                    <option value="<?= (int)$category['id'] ?>"><?= h($category['name']) ?></option>
                  <?php endforeach; ?>
                </select>
              </div>
              <div class="col-md-6">
                <label class="form-label">Supplier</label>
                <select class="form-select" name="supplier_id">
                  <option value="0">No supplier</option>
                  <?php foreach ($suppliers as $supplier): ?>
                    <option value="<?= (int)$supplier['id'] ?>"><?= h($supplier['name']) ?></option>
                  <?php endforeach; ?>
                </select>
              </div>
            </div>
            <div class="row g-3">
              <div class="col-md-6">
                <label class="form-label">Cost price</label>
                <input class="form-control" type="number" step="0.01" min="0" name="cost_price" value="0">
              </div>
              <div class="col-md-6">
                <label class="form-label">Sell price</label>
                <input class="form-control" type="number" step="0.01" min="0" name="sell_price" value="0">
              </div>
            </div>
            <div class="row g-3">
              <div class="col-md-6">
                <label class="form-label">Reorder level</label>
                <input class="form-control" type="number" min="0" name="reorder_level" value="0">
              </div>
              <div class="col-md-6">
                <label class="form-label">Active</label>
                <select class="form-select" name="is_active">
                  <option value="1" selected>Yes</option>
                  <option value="0">No</option>
                </select>
              </div>
            </div>
            <div>
              <label class="form-label">Barcode (UPC-A)</label>
              <input class="form-control" type="text" inputmode="numeric" pattern="[0-9]*" name="barcode_value" maxlength="32" placeholder="Leave blank to auto-generate or enter 12+ digits">
            </div>
            <div>
              <label class="form-label">Description</label>
              <textarea class="form-control" name="description" rows="3"></textarea>
            </div>
            <button class="btn btn-dark w-100" type="submit">Save product</button>
          </form>
        </div>
      </div>
    </div>

    <div class="col-12 col-xl-8">
      <div class="card">
        <div class="card-body p-4">
          <div class="d-flex justify-content-between align-items-center mb-3">
            <div>
              <h5 class="mb-1">Product list</h5>
              <div class="text-muted small">Live stock is computed from inventory movements so the list stays accurate even if historical data was imported.</div>
            </div>
          </div>

          <div class="table-responsive">
            <table class="table align-middle">
              <thead>
                <tr>
                  <th>Product</th>
                  <th>Barcode</th>
                  <th>Price</th>
                  <th class="text-end">Stock</th>
                  <th>Status</th>
                  <th class="text-end">Actions</th>
                </tr>
              </thead>
              <tbody>
                <?php if (!$products): ?>
                  <tr>
                    <td colspan="6" class="text-muted">No products found.</td>
                  </tr>
                <?php else: ?>
                  <?php foreach ($products as $product): ?>
                    <?php
                    $currentStock = (int)$product['current_stock'];
                    $reorderLevel = (int)$product['reorder_level'];
                    $stockState = ($reorderLevel > 0 && $currentStock <= $reorderLevel) ? 'LOW' : 'OK';
                    ?>
                    <tr>
                      <td>
                        <div class="fw-semibold"><?= h($product['name']) ?></div>
                        <div class="small text-muted">
                          <span class="code-chip"><?= h($product['sku']) ?></span>
                          <?php if (!empty($product['category_name'])): ?>
                            · <?= h($product['category_name']) ?>
                          <?php endif; ?>
                          <?php if (!empty($product['supplier_name'])): ?>
                            · <?= h($product['supplier_name']) ?>
                          <?php endif; ?>
                        </div>
                      </td>
                      <td>
                        <div class="code-chip"><?= h($product['barcode_value']) ?></div>
                        <div class="small text-muted mt-1"><?= ((int)$product['barcode_generated'] === 1) ? 'Auto-generated' : 'Manual barcode' ?></div>
                      </td>
                      <td>
                        <div class="fw-semibold"><?= format_money((float)$product['sell_price']) ?></div>
                        <div class="small text-muted">Cost <?= format_money((float)$product['cost_price']) ?></div>
                      </td>
                      <td class="text-end">
                        <div class="fw-semibold"><?= $currentStock ?></div>
                        <div class="small text-muted">Reorder <?= $reorderLevel ?></div>
                      </td>
                      <td>
                        <div class="<?= status_pill_class($stockState) ?> mb-1"><?= $stockState === 'LOW' ? 'Low stock' : 'Healthy' ?></div>
                        <div class="small text-muted"><?= ((int)$product['is_active'] === 1) ? 'Active' : 'Inactive' ?></div>
                      </td>
                      <td class="text-end">
                        <div class="d-inline-flex gap-1 flex-wrap justify-content-end">
                          <button
                            type="button"
                            class="btn btn-sm btn-outline-primary"
                            onclick='openEdit(<?= json_encode([
                                'id' => (int)$product['id'],
                                'name' => (string)$product['name'],
                                'sku' => (string)$product['sku'],
                                'category_id' => (int)($product['category_id'] ?? 0),
                                'supplier_id' => (int)($product['supplier_id'] ?? 0),
                                'description' => (string)($product['description'] ?? ''),
                                'unit' => (string)($product['unit'] ?? 'pcs'),
                                'cost_price' => (string)$product['cost_price'],
                                'sell_price' => (string)$product['sell_price'],
                                'reorder_level' => (int)$product['reorder_level'],
                                'barcode_value' => (string)($product['barcode_value'] ?? ''),
                                'is_active' => (int)$product['is_active'],
                            ], JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_QUOT | JSON_HEX_AMP) ?>)'
                          >Edit</button>
                          <a class="btn btn-sm btn-outline-secondary" target="_blank" href="print_label.php?id=<?= (int)$product['id'] ?>&mode=both">Print</a>
                          <form method="post" class="d-inline" onsubmit="return confirm('Delete this product? This also removes related delivery items and stock history for this product.');">
                            <input type="hidden" name="action" value="delete">
                            <input type="hidden" name="id" value="<?= (int)$product['id'] ?>">
                            <button class="btn btn-sm btn-outline-danger" type="submit">Delete</button>
                          </form>
                        </div>
                      </td>
                    </tr>
                  <?php endforeach; ?>
                <?php endif; ?>
              </tbody>
            </table>
          </div>
        </div>
      </div>
    </div>
  </div>
</main>

<div class="modal fade" id="editModal" tabindex="-1" aria-hidden="true">
  <div class="modal-dialog modal-lg modal-dialog-centered modal-dialog-scrollable">
    <div class="modal-content">
      <form method="post" autocomplete="off">
        <div class="modal-header">
          <h5 class="modal-title">Edit product</h5>
          <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
        </div>
        <div class="modal-body">
          <input type="hidden" name="action" value="edit">
          <input type="hidden" name="id" id="edit_id">
          <div class="row g-3">
            <div class="col-12">
              <label class="form-label">Product name</label>
              <input class="form-control" type="text" name="name" id="edit_name" required>
            </div>
            <div class="col-md-6">
              <label class="form-label">SKU</label>
              <input class="form-control" type="text" name="sku" id="edit_sku" required>
            </div>
            <div class="col-md-6">
              <label class="form-label">Unit</label>
              <input class="form-control" type="text" name="unit" id="edit_unit">
            </div>
            <div class="col-md-6">
              <label class="form-label">Category</label>
              <select class="form-select" name="category_id" id="edit_category_id">
                <option value="0">No category</option>
                <?php foreach ($categories as $category): ?>
                  <option value="<?= (int)$category['id'] ?>"><?= h($category['name']) ?></option>
                <?php endforeach; ?>
              </select>
            </div>
            <div class="col-md-6">
              <label class="form-label">Supplier</label>
              <select class="form-select" name="supplier_id" id="edit_supplier_id">
                <option value="0">No supplier</option>
                <?php foreach ($suppliers as $supplier): ?>
                  <option value="<?= (int)$supplier['id'] ?>"><?= h($supplier['name']) ?></option>
                <?php endforeach; ?>
              </select>
            </div>
            <div class="col-md-6">
              <label class="form-label">Cost price</label>
              <input class="form-control" type="number" step="0.01" min="0" name="cost_price" id="edit_cost_price">
            </div>
            <div class="col-md-6">
              <label class="form-label">Sell price</label>
              <input class="form-control" type="number" step="0.01" min="0" name="sell_price" id="edit_sell_price">
            </div>
            <div class="col-md-6">
              <label class="form-label">Reorder level</label>
              <input class="form-control" type="number" min="0" name="reorder_level" id="edit_reorder_level">
            </div>
            <div class="col-md-6">
              <label class="form-label">Active</label>
              <select class="form-select" name="is_active" id="edit_is_active">
                <option value="1">Yes</option>
                <option value="0">No</option>
              </select>
            </div>
            <div class="col-12">
              <label class="form-label">Barcode (UPC-A)</label>
              <input class="form-control" type="text" inputmode="numeric" pattern="[0-9]*" maxlength="32" name="barcode_value" id="edit_barcode_value" required>
            </div>
            <div class="col-12">
              <label class="form-label">Description</label>
              <textarea class="form-control" name="description" id="edit_description" rows="3"></textarea>
            </div>
          </div>
        </div>
        <div class="modal-footer">
          <button class="btn btn-outline-secondary" type="button" data-bs-dismiss="modal">Cancel</button>
          <button class="btn btn-dark" type="submit">Save changes</button>
        </div>
      </form>
    </div>
  </div>
</div>

<?php require_once __DIR__ . '/../templates/footer.php'; ?>
<script>
  const editModal = new bootstrap.Modal(document.getElementById('editModal'));
  function openEdit(payload) {
    document.getElementById('edit_id').value = payload.id || '';
    document.getElementById('edit_name').value = payload.name || '';
    document.getElementById('edit_sku').value = payload.sku || '';
    document.getElementById('edit_category_id').value = payload.category_id || 0;
    document.getElementById('edit_supplier_id').value = payload.supplier_id || 0;
    document.getElementById('edit_description').value = payload.description || '';
    document.getElementById('edit_unit').value = payload.unit || 'pcs';
    document.getElementById('edit_cost_price').value = payload.cost_price || 0;
    document.getElementById('edit_sell_price').value = payload.sell_price || 0;
    document.getElementById('edit_reorder_level').value = payload.reorder_level || 0;
    document.getElementById('edit_barcode_value').value = payload.barcode_value || '';
    document.getElementById('edit_is_active').value = (payload.is_active === 1 || payload.is_active === '1') ? '1' : '0';
    editModal.show();
  }
</script>
