<?php
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

require_once __DIR__ . '/../../classes/Database.php';
require_once __DIR__ . '/../../classes/Inventory.php';
require_once __DIR__ . '/../../classes/Suppliers.php';
require_once __DIR__ . '/../../classes/MraEisCompliance.php';
require_once __DIR__ . '/../../classes/SystemSettings.php';
require_once __DIR__ . '/../../includes/auth.php';

$database = new Database();
$conn = $database->getConnection();
$auth = new Auth($conn);

if (!isset($_SESSION['user_id'])) {
    header('Location: ../../login.php');
    exit();
}

$auth->enforceSuperAdminOrWarehousePrivileges($_SESSION['user_id']);

include '../../includes/header.php';

$inventory = new Inventory($conn);
$suppliers = new Suppliers($conn);
$systemSettings = new SystemSettings($conn);
$imsOnly = $systemSettings->imsOnly();
$message = null;
$messageType = 'success';
$createdCodes = [];
$search = trim($_GET['search'] ?? '');
$supplierList = $suppliers->getSuppliers('active');

function psTableExists(PDO $conn): bool {
    $stmt = $conn->prepare("
        SELECT COUNT(*)
        FROM information_schema.tables
        WHERE table_schema = DATABASE()
          AND table_name = 'product_stock'
    ");
    $stmt->execute();
    return (int)$stmt->fetchColumn() > 0;
}

function psColumns(PDO $conn): array {
    $stmt = $conn->query("SHOW COLUMNS FROM product_stock");
    $columns = [];
    foreach ($stmt->fetchAll(PDO::FETCH_ASSOC) as $row) {
        $columns[] = $row['Field'];
    }
    return $columns;
}

function psColumn(array $columns, array $candidates): ?string {
    foreach ($candidates as $candidate) {
        if (in_array($candidate, $columns, true)) {
            return $candidate;
        }
    }
    return null;
}

function psExpr(?string $column, string $fallback = "''"): string {
    return $column ? "ps.`{$column}`" : $fallback;
}

function psFetchRows(PDO $conn, array $columns, string $search = '', int $limit = 200): array {
    $idCol = psColumn($columns, ['id', 'stock_id', 'product_stock_id']);
    $barcodeCol = psColumn($columns, ['barcode', 'product_code', 'code']);
    $nameCol = psColumn($columns, ['product_name', 'item_name', 'name']);
    $descCol = psColumn($columns, ['product_description', 'description', 'category']);
    $qtyCol = psColumn($columns, ['available_quantity', 'quantity', 'qty', 'stock_quantity']);
    $priceCol = psColumn($columns, ['unit_price', 'selling_price', 'price']);
    $branchIdCol = psColumn($columns, ['branch_id', 'location_id']);
    $branchNameCol = psColumn($columns, ['branch_name', 'location_name']);

    $idExpr = psExpr($idCol, '0');
    $barcodeExpr = psExpr($barcodeCol);
    $nameExpr = psExpr($nameCol);
    $descExpr = psExpr($descCol);
    $qtyExpr = psExpr($qtyCol, '0');
    $priceExpr = psExpr($priceCol, '0');
    $branchIdExpr = psExpr($branchIdCol, '7');
    $branchNameExpr = $branchNameCol ? psExpr($branchNameCol) : "COALESCE(b.branch_name, 'Warehouse')";

    $join = (!$branchNameCol && $branchIdCol) ? " LEFT JOIN branches b ON b.branch_id = ps.`{$branchIdCol}`" : '';
    $where = [];
    $params = [];

    if ($search !== '') {
        $searchable = array_filter([$barcodeCol, $nameCol, $descCol, $branchNameCol]);
        foreach ($searchable as $column) {
            $where[] = "ps.`{$column}` LIKE :search";
        }
        if (!$branchNameCol && $branchIdCol) {
            $where[] = 'b.branch_name LIKE :search';
        }
        $params[':search'] = '%' . $search . '%';
    }

    $generatedWhere = [
        "i.technical_specs LIKE CONCAT('Imported from product_stock row ', {$idExpr}, ' barcode:%')",
        "i.comment = CONCAT('Generated from product_stock row ', {$idExpr})"
    ];

    if ($barcodeCol) {
        $generatedWhere[] = "i.technical_specs = CONCAT('Imported from product_stock barcode: ', {$barcodeExpr})";
    }

    $sql = "
        SELECT {$idExpr} AS product_stock_id,
               {$barcodeExpr} AS barcode,
               {$nameExpr} AS product_name,
               {$descExpr} AS product_description,
               {$qtyExpr} AS available_quantity,
               {$priceExpr} AS unit_price,
               {$branchIdExpr} AS branch_id,
               {$branchNameExpr} AS branch_name
        FROM product_stock ps
        {$join}
    ";

    $where[] = "NOT EXISTS (
        SELECT 1
        FROM items i
        WHERE " . implode(' OR ', $generatedWhere) . "
    )";

    if (!empty($where)) {
        $sql .= ' WHERE ' . implode(' OR ', $where);
    }

    $sql .= " ORDER BY {$nameExpr}, {$barcodeExpr} LIMIT " . max(1, min(500, $limit));
    $stmt = $conn->prepare($sql);
    foreach ($params as $key => $value) {
        $stmt->bindValue($key, $value, PDO::PARAM_STR);
    }
    $stmt->execute();
    return $stmt->fetchAll(PDO::FETCH_ASSOC);
}

function psFetchOne(PDO $conn, array $columns, $productStockId): ?array {
    $idCol = psColumn($columns, ['id', 'stock_id', 'product_stock_id']);
    if (!$idCol) {
        return null;
    }

    $barcodeCol = psColumn($columns, ['barcode', 'product_code', 'code']);
    $nameCol = psColumn($columns, ['product_name', 'item_name', 'name']);
    $descCol = psColumn($columns, ['product_description', 'description', 'category']);
    $qtyCol = psColumn($columns, ['available_quantity', 'quantity', 'qty', 'stock_quantity']);
    $priceCol = psColumn($columns, ['unit_price', 'selling_price', 'price']);
    $branchIdCol = psColumn($columns, ['branch_id', 'location_id']);
    $branchNameCol = psColumn($columns, ['branch_name', 'location_name']);

    $branchNameExpr = $branchNameCol ? psExpr($branchNameCol) : "COALESCE(b.branch_name, 'Warehouse')";
    $join = (!$branchNameCol && $branchIdCol) ? " LEFT JOIN branches b ON b.branch_id = ps.`{$branchIdCol}`" : '';
    $sql = "
        SELECT ps.`{$idCol}` AS product_stock_id,
               " . psExpr($barcodeCol) . " AS barcode,
               " . psExpr($nameCol) . " AS product_name,
               " . psExpr($descCol) . " AS product_description,
               " . psExpr($qtyCol, '0') . " AS available_quantity,
               " . psExpr($priceCol, '0') . " AS unit_price,
               " . psExpr($branchIdCol, '7') . " AS branch_id,
               {$branchNameExpr} AS branch_name
        FROM product_stock ps
        {$join}
        WHERE ps.`{$idCol}` = :product_stock_id
        LIMIT 1
    ";
    $stmt = $conn->prepare($sql);
    $stmt->bindValue(':product_stock_id', $productStockId);
    $stmt->execute();
    $row = $stmt->fetch(PDO::FETCH_ASSOC);
    return $row ?: null;
}

function parseManualCodes(string $manualCodes): array {
    $parts = preg_split('/[\r\n,]+/', $manualCodes);
    $codes = [];
    foreach ($parts as $part) {
        $code = trim($part);
        if ($code !== '') {
            $codes[] = $code;
        }
    }
    return $codes;
}

function duplicateCodes(PDO $conn, array $codes): array {
    if (empty($codes)) {
        return [];
    }
    $placeholders = implode(',', array_fill(0, count($codes), '?'));
    $stmt = $conn->prepare("SELECT unique_code FROM items WHERE unique_code IN ({$placeholders})");
    $stmt->execute(array_values($codes));
    return $stmt->fetchAll(PDO::FETCH_COLUMN);
}

function normalizeCategory(?string $category): string {
    $category = trim((string)$category);
    return $category !== '' ? substr($category, 0, 50) : 'other';
}

try {
    $productStockReady = psTableExists($conn);
    $productStockColumns = $productStockReady ? psColumns($conn) : [];

    if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['create_codes'])) {
        if (!$productStockReady) {
            throw new RuntimeException('The product_stock table was not found.');
        }

        $productStockId = $_POST['product_stock_id'] ?? '';
        $stockRow = psFetchOne($conn, $productStockColumns, $productStockId);
        if (!$stockRow) {
            throw new RuntimeException('The selected product stock record was not found.');
        }

        $quantity = (int)($_POST['quantity'] ?? 0);
        $availableQuantity = max(0, (int)floor((float)($stockRow['available_quantity'] ?? 0)));
        if ($quantity < 1) {
            throw new RuntimeException('Enter a quantity greater than zero.');
        }
        if ($availableQuantity > 0 && $quantity > $availableQuantity) {
            throw new RuntimeException('Quantity cannot be greater than the available product_stock quantity.');
        }

        $unitPrice = (float)($_POST['unit_price'] ?? $stockRow['unit_price'] ?? 0);
        if ($unitPrice < 0) {
            throw new RuntimeException('Unit price cannot be negative.');
        }

        $codeMode = $_POST['code_mode'] ?? 'prefix';
        if ($codeMode === 'manual') {
            $codes = parseManualCodes($_POST['manual_codes'] ?? '');
            if (count($codes) !== $quantity) {
                throw new RuntimeException('Manual unique codes must match the quantity selected.');
            }
        } else {
            $prefix = trim($_POST['prefix'] ?? '');
            if ($prefix === '') {
                throw new RuntimeException('Enter a prefix to generate unique codes.');
            }
            $codes = $inventory->generateUniqueCodes($prefix, $quantity);
            if ($codes === false || count($codes) !== $quantity) {
                throw new RuntimeException('Unable to generate unique codes for the selected quantity.');
            }
        }

        $codes = array_values(array_unique(array_map('trim', $codes)));
        if (count($codes) !== $quantity) {
            throw new RuntimeException('Unique codes cannot be blank or repeated.');
        }
        foreach ($codes as $code) {
            if (strlen($code) > 50) {
                throw new RuntimeException("Unique code {$code} is longer than 50 characters.");
            }
        }

        $existingCodes = duplicateCodes($conn, $codes);
        if (!empty($existingCodes)) {
            throw new RuntimeException('These unique codes already exist: ' . implode(', ', $existingCodes));
        }

        $items = [];
        foreach ($codes as $code) {
            $items[] = [
                'unique_code' => $code,
                'product_code' => trim((string)($stockRow['barcode'] ?? '')),
                'item_name' => trim((string)$stockRow['product_name']),
                'category' => normalizeCategory($stockRow['product_description'] ?? ''),
                'condition_status' => $_POST['condition_status'] ?? 'NEW',
                'unit_price' => $unitPrice,
                'description' => trim((string)($stockRow['product_description'] ?? '')),
                'comment' => 'Generated from product_stock row ' . (string)$stockRow['product_stock_id'],
                'technical_specs' => 'Imported from product_stock row ' . (string)$stockRow['product_stock_id'] . ' barcode: ' . trim((string)($stockRow['barcode'] ?? '')),
            ];
        }

        if (!$inventory->addItemsToWarehouse($items, (int)$_SESSION['user_id'])) {
            throw new RuntimeException($inventory->getLastError());
        }

        $createdCodes = $codes;
        $message = count($codes) . ' item code(s) created and inserted into items.';
        $messageType = 'success';

        if ($imsOnly) {
            $message .= ' IMS Only: no MRA EIS transaction was created.';
        } else {
            // Auto-queue this stock receipt as an MRA EIS informal purchase (goods receiving).
            // Never lets an EIS problem turn the already-successful stock add into an error -
            // a bad/incomplete receiving batch just lands in the outbox as 'blocked' for review.
            try {
            $compliance = new MraEisCompliance($conn);
            $eisWarehouseBranchId = $systemSettings->eisWarehouseBranchId();
            $eisItems = [[
                'item_code' => trim((string)($stockRow['barcode'] ?? '')),
                'description' => trim((string)($stockRow['product_description'] ?? '')) ?: trim((string)$stockRow['product_name']),
                'quantity' => count($codes),
                'unit_price' => $unitPrice,
            ]];
            $receivingMeta = [
                'supplier_id' => (int)($_POST['supplier_id'] ?? 0),
                'delivery_note_number' => trim((string)($_POST['delivery_note_number'] ?? '')),
                'purchase_order_number' => trim((string)($_POST['purchase_order_number'] ?? '')),
                'received_by' => trim((string)($_POST['received_by'] ?? ($_SESSION['username'] ?? ''))),
                'receiving_date' => date('Y-m-d H:i:s'),
                'unit_of_measure' => trim((string)($_POST['unit_of_measure'] ?? 'EACH')),
                'notes' => trim((string)($_POST['notes'] ?? '')),
                'is_finished_product' => !empty($_POST['is_finished_product']),
            ];
            $eisResult = $compliance->prepareInformalPurchaseBatch($eisWarehouseBranchId, $eisItems, $receivingMeta, (int)$_SESSION['user_id']);
            $message .= ' MRA EIS: ' . $eisResult['status'] . ($eisResult['last_error'] ? ' - ' . $eisResult['last_error'] : '.');
            } catch (Throwable $e) {
                error_log('MRA EIS informal purchase queueing failed: ' . $e->getMessage());
                $message .= ' (MRA EIS queueing failed - see logs.)';
            }
        }
    }
} catch (Exception $e) {
    $message = $e->getMessage();
    $messageType = 'danger';
}

$productRows = [];
if (!isset($productStockReady)) {
    $productStockReady = psTableExists($conn);
    $productStockColumns = $productStockReady ? psColumns($conn) : [];
}
if ($productStockReady) {
    try {
        $productRows = psFetchRows($conn, $productStockColumns, $search, 200);
    } catch (Exception $e) {
        $message = 'Could not load product_stock rows: ' . $e->getMessage();
        $messageType = 'danger';
    }
}
?>

<style>
    body { background: #f4f6f8; }
    .stock-code-shell { max-width: 1440px; margin: 28px auto; }
    .stock-code-topbar { display: flex; align-items: center; justify-content: space-between; gap: 16px; margin-bottom: 20px; }
    .stock-code-title { font-weight: 800; color: #172033; }
    .stock-code-card { border: 0; border-radius: 8px; box-shadow: 0 2px 12px rgba(15, 23, 42, 0.08); }
    .stock-code-card .card-header { background: #1f2937; color: #fff; border-radius: 8px 8px 0 0; }
    .stock-meta { color: #667085; font-size: 0.875rem; line-height: 1.45; }
    .table td, .table th { vertical-align: middle; }
    .code-form-grid { display: grid; grid-template-columns: 90px 120px 130px 160px minmax(220px, 1fr) 132px; gap: 8px; align-items: end; }
    .manual-codes { min-height: 38px; resize: vertical; }
    .generated-codes { display: flex; flex-wrap: wrap; gap: 6px; }
    @media (max-width: 1200px) {
        .code-form-grid { grid-template-columns: repeat(2, minmax(0, 1fr)); }
    }
    @media (max-width: 768px) {
        .stock-code-topbar { display: block; }
        .code-form-grid { grid-template-columns: 1fr; }
    }
</style>

<div class="stock-code-shell">
    <div class="stock-code-topbar">
        <div>
            <h2 class="stock-code-title mb-1"><i class="fas fa-tags"></i> Product Stock Code Generator</h2>
            <p class="text-muted mb-0">Read product_stock records and create item-level unique codes in inventory.</p>
        </div>
        <a href="../dashboard/warehouse.php" class="btn btn-outline-secondary">
            <i class="fas fa-arrow-left"></i> Back to Dashboard
        </a>
    </div>

    <?php if ($message): ?>
        <div class="alert alert-<?php echo htmlspecialchars($messageType); ?> alert-dismissible fade show" role="alert">
            <?php echo htmlspecialchars($message); ?>
            <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
        </div>
    <?php endif; ?>

    <?php if (!empty($createdCodes)): ?>
        <div class="card stock-code-card mb-4">
            <div class="card-header"><h5 class="mb-0"><i class="fas fa-check-circle"></i> Created Codes</h5></div>
            <div class="card-body generated-codes">
                <?php foreach ($createdCodes as $code): ?>
                    <span class="badge bg-success"><?php echo htmlspecialchars($code); ?></span>
                <?php endforeach; ?>
            </div>
        </div>
    <?php endif; ?>

    <?php if ($imsOnly): ?>
        <div class="alert alert-info">IMS Only is enabled. Created item codes are saved locally without creating or submitting an MRA EIS transaction.</div>
    <?php else: ?>
    <div class="card stock-code-card mb-4">
        <div class="card-header"><h5 class="mb-0"><i class="fas fa-file-invoice"></i> Receiving Details (MRA EIS)</h5></div>
        <div class="card-body">
            <p class="stock-meta mb-3">Applied to whichever row you create codes for below - queued to MRA EIS as an informal purchase (goods receiving) once codes are created.</p>
            <div class="row g-3">
                <div class="col-md-4">
                    <label class="form-label" for="sharedSupplierId">Supplier</label>
                    <select class="form-select" id="sharedSupplierId">
                        <option value="">Select supplier...</option>
                        <?php foreach ($supplierList as $supplierOption): ?>
                            <option value="<?php echo (int)$supplierOption['supplier_id']; ?>">
                                <?php echo htmlspecialchars($supplierOption['supplier_name']); ?><?php echo empty($supplierOption['eis_supplier_id']) ? ' (no EIS ID set)' : ''; ?>
                            </option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div class="col-md-4">
                    <label class="form-label" for="sharedDeliveryNote">Delivery Note Number</label>
                    <input type="text" class="form-control" id="sharedDeliveryNote">
                </div>
                <div class="col-md-4">
                    <label class="form-label" for="sharedPoNumber">Purchase Order Number</label>
                    <input type="text" class="form-control" id="sharedPoNumber">
                </div>
                <div class="col-md-4">
                    <label class="form-label" for="sharedReceivedBy">Received By</label>
                    <input type="text" class="form-control" id="sharedReceivedBy" value="<?php echo htmlspecialchars($_SESSION['username'] ?? ''); ?>">
                </div>
                <div class="col-md-3">
                    <label class="form-label" for="sharedUom">Unit of Measure</label>
                    <input type="text" class="form-control" id="sharedUom" value="EACH">
                </div>
                <div class="col-md-3 d-flex align-items-end">
                    <div class="form-check">
                        <input type="checkbox" class="form-check-input" id="sharedIsFinished" checked>
                        <label class="form-check-label" for="sharedIsFinished">Finished product</label>
                    </div>
                </div>
                <div class="col-md-5">
                    <label class="form-label" for="sharedNotes">Notes</label>
                    <input type="text" class="form-control" id="sharedNotes">
                </div>
            </div>
        </div>
    </div>
    <?php endif; ?>

    <div class="card stock-code-card mb-4">
        <div class="card-header"><h5 class="mb-0"><i class="fas fa-filter"></i> Search Product Stock</h5></div>
        <div class="card-body">
            <form method="GET" class="row g-3 align-items-end">
                <div class="col-md-10">
                    <label for="search" class="form-label">Search</label>
                    <input type="text" class="form-control" id="search" name="search" value="<?php echo htmlspecialchars($search); ?>" placeholder="Barcode, product name, category, or branch">
                </div>
                <div class="col-md-2">
                    <button type="submit" class="btn btn-primary w-100">
                        <i class="fas fa-search"></i> Search
                    </button>
                </div>
            </form>
        </div>
    </div>

    <div class="card stock-code-card">
        <div class="card-header d-flex justify-content-between align-items-center">
            <h5 class="mb-0"><i class="fas fa-boxes"></i> Product Stock</h5>
            <span class="badge bg-light text-dark"><?php echo count($productRows); ?> shown</span>
        </div>
        <div class="card-body">
            <?php if (!$productStockReady): ?>
                <div class="alert alert-warning mb-0">The product_stock table was not found in this database.</div>
            <?php elseif (empty($productRows)): ?>
                <div class="alert alert-info mb-0">No product_stock rows matched this search.</div>
            <?php else: ?>
                <div class="table-responsive">
                    <table class="table table-striped table-bordered mb-0">
                        <thead>
                            <tr>
                                <th>Product</th>
                                <th>Location</th>
                                <th>Available</th>
                                <th>Create Unique Codes</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach ($productRows as $row): ?>
                                <?php
                                    $rowId = (string)$row['product_stock_id'];
                                    $available = max(0, (int)floor((float)($row['available_quantity'] ?? 0)));
                                    $formId = 'code-form-' . preg_replace('/[^a-zA-Z0-9_-]/', '-', $rowId);
                                ?>
                                <tr>
                                    <td>
                                        <strong><?php echo htmlspecialchars($row['product_name'] ?: 'Unnamed product'); ?></strong>
                                        <div class="stock-meta">
                                            Barcode: <?php echo htmlspecialchars($row['barcode'] ?: 'N/A'); ?><br>
                                            <?php echo htmlspecialchars($row['product_description'] ?: 'No description'); ?>
                                        </div>
                                    </td>
                                    <td><?php echo htmlspecialchars($row['branch_name'] ?: 'Warehouse'); ?></td>
                                    <td><?php echo number_format($available); ?></td>
                                    <td>
                                        <form method="POST" class="receiving-form" id="<?php echo htmlspecialchars($formId); ?>">
                                            <input type="hidden" name="product_stock_id" value="<?php echo htmlspecialchars($rowId); ?>">
                                            <input type="hidden" name="supplier_id">
                                            <input type="hidden" name="delivery_note_number">
                                            <input type="hidden" name="purchase_order_number">
                                            <input type="hidden" name="received_by">
                                            <input type="hidden" name="unit_of_measure">
                                            <input type="hidden" name="is_finished_product">
                                            <input type="hidden" name="notes">
                                            <div class="code-form-grid">
                                                <div>
                                                    <label class="form-label" for="quantity-<?php echo htmlspecialchars($formId); ?>">Qty</label>
                                                    <input type="number" class="form-control" id="quantity-<?php echo htmlspecialchars($formId); ?>" name="quantity" min="1" max="<?php echo $available > 0 ? $available : 999; ?>" value="<?php echo $available > 0 ? min($available, 1) : 1; ?>" required>
                                                </div>
                                                <div>
                                                    <label class="form-label" for="condition-<?php echo htmlspecialchars($formId); ?>">Condition</label>
                                                    <select class="form-select" id="condition-<?php echo htmlspecialchars($formId); ?>" name="condition_status">
                                                        <option value="NEW">NEW</option>
                                                        <option value="OPEN_BOX">OPEN BOX</option>
                                                        <option value="USED">USED</option>
                                                    </select>
                                                </div>
                                                <div>
                                                    <label class="form-label" for="price-<?php echo htmlspecialchars($formId); ?>">Unit Price</label>
                                                    <input type="number" step="0.01" min="0" class="form-control" id="price-<?php echo htmlspecialchars($formId); ?>" name="unit_price" value="<?php echo htmlspecialchars((string)($row['unit_price'] ?? 0)); ?>" required>
                                                </div>
                                                <div>
                                                    <label class="form-label" for="mode-<?php echo htmlspecialchars($formId); ?>">Mode</label>
                                                    <select class="form-select code-mode" id="mode-<?php echo htmlspecialchars($formId); ?>" name="code_mode" data-target="<?php echo htmlspecialchars($formId); ?>">
                                                        <option value="prefix">Prefix Sequence</option>
                                                        <option value="manual">Manual Codes</option>
                                                    </select>
                                                </div>
                                                <div>
                                                    <label class="form-label prefix-field" for="prefix-<?php echo htmlspecialchars($formId); ?>">Prefix</label>
                                                    <input type="text" class="form-control prefix-input" id="prefix-<?php echo htmlspecialchars($formId); ?>" name="prefix" placeholder="AC/">
                                                    <textarea class="form-control manual-codes d-none" name="manual_codes" placeholder="One code per line or comma-separated"></textarea>
                                                </div>
                                                <div>
                                                    <button type="submit" name="create_codes" value="1" class="btn btn-success w-100">
                                                        <i class="fas fa-plus-circle"></i> Create
                                                    </button>
                                                </div>
                                            </div>
                                        </form>
                                    </td>
                                </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
            <?php endif; ?>
        </div>
    </div>
</div>

<script>
<?php if (!$imsOnly): ?>
document.querySelectorAll('.receiving-form').forEach(function(form) {
    form.addEventListener('submit', function() {
        form.querySelector('[name="supplier_id"]').value = document.getElementById('sharedSupplierId').value;
        form.querySelector('[name="delivery_note_number"]').value = document.getElementById('sharedDeliveryNote').value;
        form.querySelector('[name="purchase_order_number"]').value = document.getElementById('sharedPoNumber').value;
        form.querySelector('[name="received_by"]').value = document.getElementById('sharedReceivedBy').value;
        form.querySelector('[name="unit_of_measure"]').value = document.getElementById('sharedUom').value;
        form.querySelector('[name="notes"]').value = document.getElementById('sharedNotes').value;
        form.querySelector('[name="is_finished_product"]').value = document.getElementById('sharedIsFinished').checked ? '1' : '';
    });
});
<?php endif; ?>

document.querySelectorAll('.code-mode').forEach(function(select) {
    select.addEventListener('change', function() {
        var form = document.getElementById(select.dataset.target);
        if (!form) {
            return;
        }
        var manual = form.querySelector('.manual-codes');
        var prefix = form.querySelector('.prefix-input');
        var prefixLabel = form.querySelector('.prefix-field');
        var manualMode = select.value === 'manual';
        manual.classList.toggle('d-none', !manualMode);
        prefix.classList.toggle('d-none', manualMode);
        prefixLabel.textContent = manualMode ? 'Manual Codes' : 'Prefix';
    });
});
</script>

<?php include '../../includes/footer.php'; ?>
