<?php
// Business logic (validation, DB writes, and any header('Location: ...') redirects)
// must run before includes/header.php, since that include emits HTML immediately.
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

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

$db = new Database();
$conn = $db->getConnection();

$auth = new Auth($conn);
$auth->requireLogin();

$role = strtolower((string)($_SESSION['role'] ?? ''));
if (!in_array($role, ['admin', 'warehouse'], true)) {
    header('Location: /IMS/unauthorized.php');
    exit;
}

$systemSettings = new SystemSettings($conn);
$imsOnly = $systemSettings->imsOnly();
$vatPercentage = $systemSettings->vatPercentage();
$vatRate = $systemSettings->vatRate();
$profitPercentageDefault = $systemSettings->profitPercentage();

$logger = new Logger($conn, $_SESSION['user_id'], $_SESSION['username'], $_SESSION['role']);
$inventory = new Inventory($conn, $logger);
$suppliersModel = new Suppliers($conn);
$compliance = $imsOnly ? null : new MraEisCompliance($conn);

$supplierList = $suppliersModel->getSuppliers('active');

$stmt = $conn->prepare("SELECT branch_id FROM branches WHERE branch_name LIKE '%warehouse%' LIMIT 1");
$stmt->execute();
$branch_id = $stmt->fetchColumn() ?: 7;

$stmt = $conn->prepare("SELECT branch_name FROM branches WHERE branch_id = ?");
$stmt->execute([$branch_id]);
$branch_name = $stmt->fetchColumn() ?: 'Warehouse';

$categoriesStmt = $inventory->getAllCategories();
$categoryOptions = array_values(array_filter(array_map(
    fn($row) => $row['category_name'] ?? null,
    $categoriesStmt->fetchAll(PDO::FETCH_ASSOC)
)));

$CONDITION_OPTIONS = ['NEW', 'OPEN_BOX', 'USED'];

$errors = [];
$view = 'lines';
$initialLines = [];
$batchHeader = [
    'supplier_id' => '',
    'delivery_note_number' => '',
    'purchase_order_number' => '',
    'received_by' => $_SESSION['username'] ?? '',
    'receiving_date' => date('Y-m-d'),
    'unit_of_measure' => 'EACH',
    'notes' => '',
];

$action = $_SERVER['REQUEST_METHOD'] === 'POST' ? ($_POST['action'] ?? '') : '';

/**
 * Reads and re-applies posted batch header fields shared by build_details/save.
 */
function readBatchHeader(array $post, string $defaultReceivedBy): array {
    return [
        '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'] ?? '')) ?: $defaultReceivedBy,
        'receiving_date' => trim((string)($post['receiving_date'] ?? '')) ?: date('Y-m-d'),
        'unit_of_measure' => trim((string)($post['unit_of_measure'] ?? '')) ?: 'EACH',
        'notes' => trim((string)($post['notes'] ?? '')),
    ];
}

if ($action === 'build_details') {
    $batchHeader = readBatchHeader($_POST, $_SESSION['username'] ?? '');
    $rawLines = array_values($_POST['lines'] ?? []);

    if (empty($rawLines)) {
        $errors[] = 'Add at least one item line before continuing.';
    }
    if (!$imsOnly && $batchHeader['supplier_id'] <= 0) {
        $errors[] = 'Please select a supplier for this receiving batch.';
    }

    $preparedLines = [];
    $reservedGeneratedCodes = [];
    foreach ($rawLines as $rawLine) {
        $name = trim((string)($rawLine['name'] ?? ''));
        $category = trim((string)($rawLine['category'] ?? ''));
        $codeMethod = trim((string)($rawLine['code_method'] ?? ''));
        $preCode = trim((string)($rawLine['pre_code'] ?? ''));
        $quantity = filter_var($rawLine['quantity'] ?? '', FILTER_VALIDATE_INT, ['options' => ['min_range' => 1, 'max_range' => 1000]]);
        $landingPrice = filter_var($rawLine['landing_price'] ?? '', FILTER_VALIDATE_FLOAT);
        $profitPercentage = filter_var($rawLine['profit_percentage'] ?? '', FILTER_VALIDATE_FLOAT);
        $warranty = trim((string)($rawLine['warranty'] ?? ''));
        $eisCode = trim((string)($rawLine['eis_code'] ?? ''));
        $eisDescription = trim((string)($rawLine['eis_description'] ?? ''));
        $lineUnitOfMeasure = trim((string)($rawLine['unit_of_measure'] ?? ''));
        $finishedProduct = ($rawLine['finished_product'] ?? 'yes') === 'yes';

        $label = $name !== '' ? htmlspecialchars($name) : 'an item line';

        if ($name === '') { $errors[] = "Item name is required for {$label}."; continue; }
        if (!in_array($codeMethod, ['auto', 'manual'], true)) { $errors[] = "Invalid code assignment method for {$label}."; continue; }
        if ($codeMethod === 'auto' && $preCode === '') { $errors[] = "Pre-Universal Code is required for auto-generated codes on {$label}."; continue; }
        if ($category === '') { $errors[] = "Category is required for {$label}."; continue; }
        if ($quantity === false) { $errors[] = "Invalid quantity (1-1000) for {$label}."; continue; }
        if ($landingPrice === false || $landingPrice <= 0) { $errors[] = "Invalid landing price for {$label}. Must be greater than 0."; continue; }
        if ($profitPercentage === false || $profitPercentage < 0) { $errors[] = "Invalid profit percentage for {$label}."; continue; }
        if (!$imsOnly && $eisCode === '') { $errors[] = "No MRA EIS product was selected for {$label} - search and select one, or enter the code manually."; continue; }

        $profitAmount = $landingPrice * ($profitPercentage / 100);
        $subtotal = $landingPrice + $profitAmount;
        $vatAmount = $subtotal * $vatRate;
        $unitPrice = round($subtotal + $vatAmount, 2);

        if ($codeMethod === 'auto') {
            $codes = $inventory->generateUniqueCodes($preCode, $quantity, $reservedGeneratedCodes);
            if ($codes === false) { $errors[] = "Failed to generate unique codes for {$label}."; continue; }
            $reservedGeneratedCodes = array_merge($reservedGeneratedCodes, $codes);
        } else {
            $codes = array_fill(0, $quantity, '');
        }

        $preparedLines[] = [
            'name' => $name,
            'category' => $category,
            'code_method' => $codeMethod,
            'quantity' => $quantity,
            'landing_price' => $landingPrice,
            'profit_percentage' => $profitPercentage,
            'profit_amount' => $profitAmount,
            'subtotal' => $subtotal,
            'vat_amount' => $vatAmount,
            'unit_price' => $unitPrice,
            'warranty' => $warranty,
            'eis_code' => $eisCode,
            'eis_description' => $eisDescription,
            'unit_of_measure' => $lineUnitOfMeasure,
            'finished_product' => $finishedProduct,
            'unique_codes' => $codes,
        ];
    }

    if (empty($errors) && empty($preparedLines)) {
        $errors[] = 'No valid item lines to review.';
    }

    if (empty($errors)) {
        $view = 'details';
    } else {
        $view = 'lines';
        $initialLines = $rawLines;
    }
}

elseif (in_array($action, ['save', 'save_print'], true)) {
    $batchHeader = readBatchHeader($_POST, $_SESSION['username'] ?? '');
    $rawLines = array_values($_POST['lines'] ?? []);

    $finalLines = [];
    $allUniqueCodes = [];

    foreach ($rawLines as $rawLine) {
        $name = trim((string)($rawLine['name'] ?? ''));
        $category = trim((string)($rawLine['category'] ?? ''));
        $codeMethod = trim((string)($rawLine['code_method'] ?? ''));
        $quantity = filter_var($rawLine['quantity'] ?? '', FILTER_VALIDATE_INT, ['options' => ['min_range' => 1, 'max_range' => 1000]]);
        $landingPrice = filter_var($rawLine['landing_price'] ?? '', FILTER_VALIDATE_FLOAT);
        $unitPrice = filter_var($rawLine['unit_price'] ?? '', FILTER_VALIDATE_FLOAT);
        $profitPercentage = filter_var($rawLine['profit_percentage'] ?? '', FILTER_VALIDATE_FLOAT);
        $warranty = trim((string)($rawLine['warranty'] ?? ''));
        $eisCode = trim((string)($rawLine['eis_code'] ?? ''));
        $eisDescription = trim((string)($rawLine['eis_description'] ?? ''));
        $lineUnitOfMeasure = trim((string)($rawLine['unit_of_measure'] ?? ''));
        $finishedProduct = ($rawLine['finished_product'] ?? 'yes') === 'yes';

        $uniqueCodes = array_map('trim', $rawLine['unique_codes'] ?? []);
        $conditionStatuses = array_map('trim', $rawLine['condition_status'] ?? []);
        $brands = $rawLine['brands'] ?? [];
        $models = $rawLine['models'] ?? [];
        $serials = $rawLine['serials'] ?? [];
        $descriptions = $rawLine['descriptions'] ?? [];
        $technicalSpecs = $rawLine['technical_specs'] ?? [];

        $label = $name !== '' ? htmlspecialchars($name) : 'an item line';

        if ($name === '' || $category === '' || $quantity === false || $landingPrice === false || $unitPrice === false) {
            $errors[] = "Missing required data for {$label}.";
            continue;
        }
        if (count($uniqueCodes) !== $quantity) {
            $errors[] = "Number of unique codes must match quantity for {$label}.";
            continue;
        }
        if ($codeMethod === 'manual' && in_array('', $uniqueCodes, true)) {
            $errors[] = "All unique codes must be provided for {$label}.";
            continue;
        }
        if (count($conditionStatuses) !== $quantity || in_array('', $conditionStatuses, true)) {
            $errors[] = "Condition must be selected for every unit of {$label}.";
            continue;
        }

        $allUniqueCodes = array_merge($allUniqueCodes, $uniqueCodes);
        $finalLines[] = [
            'name' => $name, 'category' => $category, 'codeMethod' => $codeMethod, 'quantity' => $quantity,
            'landingPrice' => $landingPrice, 'unitPrice' => $unitPrice, 'profitPercentage' => $profitPercentage,
            'warranty' => $warranty, 'eisCode' => $eisCode, 'eisDescription' => $eisDescription,
            'lineUnitOfMeasure' => $lineUnitOfMeasure, 'finishedProduct' => $finishedProduct,
            'uniqueCodes' => $uniqueCodes, 'conditionStatuses' => $conditionStatuses,
            'brands' => $brands, 'models' => $models, 'serials' => $serials,
            'descriptions' => $descriptions, 'technicalSpecs' => $technicalSpecs,
        ];
    }

    if (empty($errors) && empty($finalLines)) {
        $errors[] = 'No items to save.';
    }

    if (empty($errors)) {
        if (count(array_unique($allUniqueCodes)) !== count($allUniqueCodes)) {
            $errors[] = 'Duplicate unique codes detected across items.';
        } else {
            $placeholders = implode(',', array_fill(0, count($allUniqueCodes), '?'));
            $stmt = $conn->prepare("SELECT unique_code FROM items WHERE unique_code IN ($placeholders)");
            $stmt->execute($allUniqueCodes);
            $existingCodes = $stmt->fetchAll(PDO::FETCH_COLUMN);
            if (!empty($existingCodes)) {
                $errors[] = 'Codes already exist: ' . implode(', ', $existingCodes);
            }
        }
    }

    if (empty($errors)) {
        $allItems = [];
        foreach ($finalLines as $line) {
            for ($j = 0; $j < $line['quantity']; $j++) {
                $allItems[] = [
                    'unique_code' => $line['uniqueCodes'][$j],
                    'item_name' => $line['name'],
                    'category' => $line['category'],
                    'condition_status' => $line['conditionStatuses'][$j],
                    'landing_price' => $line['landingPrice'],
                    'unit_price' => $line['unitPrice'],
                    'profit_percentage' => $line['profitPercentage'],
                    'warranty_months' => $line['warranty'],
                    'brand' => $line['brands'][$j] ?? null,
                    'model' => $line['models'][$j] ?? null,
                    'serial_number' => $line['serials'][$j] ?? null,
                    'description' => $line['descriptions'][$j] ?? null,
                    'technical_specs' => $line['technicalSpecs'][$j] ?? null,
                    'product_code' => $line['eisCode'] !== '' ? $line['eisCode'] : null,
                ];
            }
        }

        $createdBy = (int)$_SESSION['user_id'];
        try {
            $saveOk = $inventory->addItemsToWarehouse($allItems, $createdBy, $branch_id);
            if (!$saveOk) {
                throw new Exception('Failed to add items to warehouse: ' . $inventory->getLastError());
            }

            $newlyAddedItems = [];
            $placeholders = implode(',', array_fill(0, count($allUniqueCodes), '?'));
            $stmt = $conn->prepare("SELECT unique_code, barcode_image_path FROM items WHERE unique_code IN ($placeholders)");
            $stmt->execute($allUniqueCodes);
            foreach ($stmt->fetchAll(PDO::FETCH_ASSOC) as $row) {
                $newlyAddedItems[$row['unique_code']] = $row['barcode_image_path'];
            }

            if ($imsOnly) {
                $eisStatus = 'ims_only';
                $eisMessage = 'IMS Only: items were saved locally and no MRA EIS transaction was created.';
            } else {
                // Auto-queue this receiving batch as one MRA EIS informal purchase covering
                // every distinct item type. Never lets an EIS problem turn the already-successful
                // stock add into an error - a bad/incomplete batch just lands in the outbox as
                // 'blocked' for review.
                try {
                $eisWarehouseBranchId = $systemSettings->eisWarehouseBranchId();
                $eisItems = [];
                foreach ($finalLines as $line) {
                    $eisItems[] = [
                        'item_code' => $line['eisCode'],
                        'description' => $line['eisDescription'] !== '' ? $line['eisDescription'] : $line['name'],
                        'quantity' => $line['quantity'],
                        // The informal purchase records what was paid to acquire the goods,
                        // not the marked-up retail price they'll later sell for.
                        'unit_price' => $line['landingPrice'],
                        'is_finished_product' => $line['finishedProduct'],
                        'unit_of_measure' => $line['lineUnitOfMeasure'],
                    ];
                }
                $receivingMeta = [
                    'supplier_id' => $batchHeader['supplier_id'],
                    'delivery_note_number' => $batchHeader['delivery_note_number'],
                    'purchase_order_number' => $batchHeader['purchase_order_number'],
                    'received_by' => $batchHeader['received_by'],
                    'receiving_date' => $batchHeader['receiving_date'],
                    'unit_of_measure' => $batchHeader['unit_of_measure'],
                    'notes' => $batchHeader['notes'],
                    'is_finished_product' => true,
                ];
                $eisResult = $compliance->prepareInformalPurchaseBatch($eisWarehouseBranchId, $eisItems, $receivingMeta, $createdBy);
                $eisStatus = $eisResult['status'];
                if ($eisStatus === 'ready' && !empty($eisResult['id'])) {
                    // Submit live immediately rather than leaving it queued for a superadmin
                    // to manually click "Submit" later on the EIS outbox page. A submission
                    // failure here never escalates - it just leaves the row 'ready'/'failed'
                    // for that same manual-retry fallback to pick up.
                    try {
                        $submitResult = $compliance->submitOutbox((int)$eisResult['id'], $createdBy);
                        if (!empty($submitResult['success'])) {
                            $eisStatus = 'submitted';
                            $eisMessage = 'MRA EIS: informal purchase submitted successfully (' . count($eisItems) . ' item type(s), ' . count($allItems) . ' unit(s)).';
                        } else {
                            $eisStatus = !empty($submitResult['queued']) ? 'queued' : 'failed';
                            $eisMessage = 'MRA EIS: submission queued for retry - ' . ($submitResult['message'] ?: 'submission did not complete.') . ' Review and resubmit from the EIS outbox.';
                        }
                    } catch (Throwable $e) {
                        error_log('MRA EIS informal purchase submission failed: ' . $e->getMessage());
                        $eisStatus = 'failed';
                        $eisMessage = 'MRA EIS: submission failed and will need a manual retry from the EIS outbox - ' . $e->getMessage();
                    }
                } else {
                    $eisMessage = 'MRA EIS: submission blocked - ' . ($eisResult['last_error'] ?: 'unknown issue') . ' Review and resubmit from the EIS outbox.';
                }
                } catch (Throwable $e) {
                    error_log('MRA EIS informal purchase queueing failed: ' . $e->getMessage());
                    $eisStatus = 'error';
                    $eisMessage = 'MRA EIS queueing failed - see logs. This receipt was NOT submitted to EIS.';
                }
            }

            $totalUnits = count($allItems);
            $totalRetailValue = 0.0;
            $totalPurchaseValue = 0.0;
            foreach ($finalLines as $line) {
                $totalRetailValue += $line['unitPrice'] * $line['quantity'];
                $totalPurchaseValue += $line['landingPrice'] * $line['quantity'];
            }

            $view = $action === 'save_print' ? 'print' : 'success';
        } catch (Exception $e) {
            error_log('Warehouse inventory addition error in add_items.php: ' . $e->getMessage());
            $errors[] = 'Error saving data: ' . $e->getMessage();
        }
    }

    if (!empty($errors)) {
        $view = 'save_error';
    }
}

/**
 * Renders one item-line's input fields (used both for the live starting row(s)
 * and, with $idx = '__IDX__', for the JS clone <template>).
 */
function renderLineCard($idx, array $v, array $categoryOptions, float $profitDefault, bool $imsOnly) {
    $name = htmlspecialchars($v['name'] ?? '');
    $category = $v['category'] ?? '';
    $codeMethod = $v['code_method'] ?? 'auto';
    $preCode = htmlspecialchars($v['pre_code'] ?? '');
    $quantity = htmlspecialchars((string)($v['quantity'] ?? 1));
    $landingPrice = htmlspecialchars((string)($v['landing_price'] ?? ''));
    $profitPercentage = htmlspecialchars((string)($v['profit_percentage'] ?? $profitDefault));
    $warranty = htmlspecialchars($v['warranty'] ?? '');
    $eisCode = htmlspecialchars($v['eis_code'] ?? '');
    $eisDescription = htmlspecialchars($v['eis_description'] ?? '');
    $unitOfMeasure = htmlspecialchars($v['unit_of_measure'] ?? '');
    $finishedProduct = ($v['finished_product'] ?? 'yes') === 'yes' ? 'yes' : 'no';
    $hasSelection = $eisCode !== '';
    ?>
    <div class="card line-card mb-3" data-idx="<?php echo $idx; ?>">
        <div class="card-header d-flex justify-content-between align-items-center bg-light">
            <strong>Item Line #<span class="line-number"><?php echo is_numeric($idx) ? $idx + 1 : 1; ?></span></strong>
            <button type="button" class="btn btn-sm btn-outline-danger remove-line-btn" onclick="removeLine(this)">&times; Remove</button>
        </div>
        <div class="card-body">
            <?php if (!$imsOnly): ?>
            <div class="mb-3 eis-search-wrap position-relative">
                <label class="form-label fw-semibold">Search MRA EIS Product (barcode, name, or description)</label>
                <input type="text" class="form-control eis-search-input" placeholder="Start typing a barcode, product name, or description..." autocomplete="off">
                <div class="eis-search-results list-group position-absolute w-100 shadow-sm" style="z-index:20; display:none; max-height:260px; overflow-y:auto;"></div>
                <div class="eis-selected-info small mt-1" style="<?php echo $hasSelection ? '' : 'display:none;'; ?>">
                    <span class="badge bg-success">Selected</span>
                    <span class="eis-selected-text"><?php echo $eisDescription !== '' ? $eisDescription : $eisCode; ?> (<?php echo $eisCode; ?>)</span>
                    <a href="#" class="ms-2 clear-eis-selection">change</a>
                </div>
                <div class="manual-eis-code mt-2" style="<?php echo $hasSelection ? 'display:none;' : ''; ?>">
                    <a href="#" class="small toggle-manual-code">Can't find it? Enter the EIS product code manually</a>
                    <input type="text" class="form-control form-control-sm mt-1 manual-eis-code-input" style="display:none;" placeholder="EIS product code (barcode)" value="<?php echo $hasSelection ? '' : $eisCode; ?>">
                </div>
                <input type="hidden" name="lines[<?php echo $idx; ?>][eis_code]" class="eis-code-field" value="<?php echo $eisCode; ?>">
                <input type="hidden" name="lines[<?php echo $idx; ?>][eis_description]" class="eis-description-field" value="<?php echo $eisDescription; ?>">
            </div>
            <?php else: ?>
                <input type="hidden" name="lines[<?php echo $idx; ?>][eis_code]" value="">
                <input type="hidden" name="lines[<?php echo $idx; ?>][eis_description]" value="">
            <?php endif; ?>

            <div class="row g-3">
                <div class="col-md-4">
                    <label class="form-label">Item Name</label>
                    <input type="text" class="form-control item-name-field" name="lines[<?php echo $idx; ?>][name]" value="<?php echo $name; ?>" required>
                </div>
                <div class="col-md-4">
                    <label class="form-label">Category</label>
                    <select class="form-select" name="lines[<?php echo $idx; ?>][category]" required>
                        <option value="">Select category...</option>
                        <?php foreach ($categoryOptions as $cat): ?>
                            <option value="<?php echo htmlspecialchars($cat); ?>" <?php echo $cat === $category ? 'selected' : ''; ?>><?php echo htmlspecialchars($cat); ?></option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div class="col-md-4">
                    <label class="form-label">Quantity</label>
                    <input type="number" class="form-control quantity-field" name="lines[<?php echo $idx; ?>][quantity]" value="<?php echo $quantity; ?>" min="1" max="1000" required>
                </div>

                <div class="col-md-3">
                    <label class="form-label">Landing Price (Cost)</label>
                    <input type="number" step="0.01" min="0.01" class="form-control landing-price-field" name="lines[<?php echo $idx; ?>][landing_price]" value="<?php echo $landingPrice; ?>" required>
                </div>
                <div class="col-md-3">
                    <label class="form-label">Profit %</label>
                    <input type="number" step="0.1" min="0" class="form-control profit-field" name="lines[<?php echo $idx; ?>][profit_percentage]" value="<?php echo $profitPercentage; ?>" required>
                </div>
                <div class="col-md-3">
                    <label class="form-label">Selling Price (preview)</label>
                    <input type="text" class="form-control unit-price-preview" value="MWK 0.00" readonly tabindex="-1">
                </div>
                <div class="col-md-3">
                    <label class="form-label">Warranty (months)</label>
                    <input type="text" class="form-control" name="lines[<?php echo $idx; ?>][warranty]" value="<?php echo $warranty; ?>">
                </div>

                <div class="col-md-3">
                    <label class="form-label">Unit of Measure</label>
                    <input type="text" class="form-control" name="lines[<?php echo $idx; ?>][unit_of_measure]" value="<?php echo $unitOfMeasure; ?>" placeholder="Uses batch default if blank">
                </div>
                <div class="col-md-3">
                    <label class="form-label">Finished Product?</label>
                    <select class="form-select" name="lines[<?php echo $idx; ?>][finished_product]">
                        <option value="yes" <?php echo $finishedProduct === 'yes' ? 'selected' : ''; ?>>Yes</option>
                        <option value="no" <?php echo $finishedProduct === 'no' ? 'selected' : ''; ?>>No (raw material/component)</option>
                    </select>
                </div>
                <div class="col-md-3">
                    <label class="form-label">Code Assignment</label>
                    <select class="form-select code-method-field" name="lines[<?php echo $idx; ?>][code_method]" onchange="togglePreCode(this)">
                        <option value="auto" <?php echo $codeMethod === 'auto' ? 'selected' : ''; ?>>Auto-generate codes</option>
                        <option value="manual" <?php echo $codeMethod === 'manual' ? 'selected' : ''; ?>>Enter codes manually</option>
                    </select>
                </div>
                <div class="col-md-3 pre-code-group" style="<?php echo $codeMethod === 'auto' ? '' : 'display:none;'; ?>">
                    <label class="form-label">Pre-Universal Code</label>
                    <input type="text" class="form-control" name="lines[<?php echo $idx; ?>][pre_code]" value="<?php echo $preCode; ?>" placeholder="e.g., USB/">
                </div>
            </div>
        </div>
    </div>
    <?php
}
?>
<?php include __DIR__ . '/../../includes/header.php'; ?>

<link rel="stylesheet" href="../../assets/css/simple.css">
<style>
    @media print {
        body * { visibility: hidden; }
        .printable-area, .printable-area * { visibility: visible; }
        .printable-area { position: absolute; left: 0; top: 0; width: 100%; }
        .sticker-grid { display: grid; grid-template-columns: repeat(6, 1fr); gap: 3mm; padding: 5mm; }
        .sticker-preview { border: 1px solid #000; padding: 2mm; page-break-inside: avoid; width: 25mm; height: 15mm; display: flex; flex-direction: column; justify-content: center; align-items: center; font-size: 8pt; }
        .sticker-preview img { max-width: 20mm; height: 8mm; margin-bottom: 1mm; }
        .sticker-code { font-size: 6pt; font-weight: bold; margin-top: 1mm; }
        .print-controls, .preview-header { display: none; }
        .barcode-error { display: none; }
    }
    .back-link { display: inline-block; margin: 15px 15px 15px 0; padding: 10px 15px; background-color: #3498db; color: #fff; text-decoration: none; border-radius: 5px; }
    .back-link:hover { background-color: #2980b9; color: #fff; }
    .eis-search-results .list-group-item { cursor: pointer; }
    .eis-search-results .list-group-item:hover { background-color: #f1f5f9; }
    .print-preview { background-color: #f8f9fa; border: 2px solid #007bff; border-radius: 10px; padding: 20px; margin: 20px 0; }
    .preview-header { text-align: center; background-color: #007bff; color: #fff; padding: 15px; border-radius: 8px; margin-bottom: 20px; }
    .sticker-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(120px, 1fr)); gap: 10px; margin: 20px 0; }
    .sticker-preview { border: 1px solid #6c757d; padding: 8px; text-align: center; background-color: #fff; border-radius: 5px; box-shadow: 0 1px 3px rgba(0,0,0,0.1); min-height: 80px; display: flex; flex-direction: column; justify-content: center; align-items: center; }
    .sticker-preview img { max-width: 100%; height: 25px; object-fit: contain; margin-bottom: 5px; }
    .sticker-code { font-weight: bold; font-size: 10px; color: #333; margin-top: 3px; word-break: break-all; }
    .print-controls { text-align: center; margin: 20px 0; }
    .barcode-error { background-color: #f8d7da; color: #721c24; padding: 5px; border-radius: 3px; margin: 2px 0; font-size: 8px; border: 1px solid #f5c6cb; }
    .detail-table input, .detail-table select { min-width: 110px; }
</style>

<div class="container-fluid px-3 py-3">

<a href="choose_warehouse_form.php" class="back-link">&larr; Back to Form Selection</a>
<h2>Add Items to Warehouse: <?php echo htmlspecialchars($branch_name); ?></h2>

<?php if (!empty($errors)): ?>
    <div class="alert alert-danger">
        <strong>Please fix the following before continuing:</strong>
        <ul class="mb-0">
            <?php foreach ($errors as $err): ?><li><?php echo htmlspecialchars($err); ?></li><?php endforeach; ?>
        </ul>
    </div>
<?php endif; ?>

<?php if ($view === 'lines'): ?>

    <?php if ($imsOnly): ?>
        <div class="alert alert-info">IMS Only is enabled. Items added here are saved only in the inventory system; no MRA EIS product lookup, outbox record, or API submission will occur.</div>
    <?php else: ?>
        <p class="text-muted">Record a goods-receiving batch here the same way it's captured on the MRA EIS informal-purchase screen: one supplier/delivery per batch, with as many different item lines as you like. Search each item against the MRA EIS product catalog so the receipt submits cleanly; items left unmatched are still saved locally but held for review in the EIS outbox.</p>
    <?php endif; ?>

    <form method="post" action="" id="linesForm">
        <input type="hidden" name="action" value="build_details">

        <div class="card mb-3">
            <div class="card-header bg-light"><strong>Receiving Details<?php echo $imsOnly ? ' (IMS Only)' : ' (MRA EIS)'; ?></strong></div>
            <div class="card-body">
                <div class="row g-3">
                    <div class="col-md-4">
                        <label class="form-label">Supplier</label>
                        <div class="d-flex gap-2">
                            <select name="supplier_id" id="supplierSelect" class="form-select" <?php echo $imsOnly ? '' : 'required'; ?>>
                                <option value="">Select supplier...</option>
                                <?php foreach ($supplierList as $supplierOption):
                                    $isSynced = !empty($supplierOption['eis_supplier_id']);
                                ?>
                                    <option value="<?php echo (int)$supplierOption['supplier_id']; ?>" <?php echo (int)$batchHeader['supplier_id'] === (int)$supplierOption['supplier_id'] ? 'selected' : ''; ?>>
                                        <?php echo htmlspecialchars($supplierOption['supplier_name']); ?><?php echo !$imsOnly ? ($isSynced ? ' — EIS #' . (int)$supplierOption['eis_supplier_id'] : ' (not synced with MRA EIS)') : ''; ?>
                                    </option>
                                <?php endforeach; ?>
                            </select>
                            <?php if (!$imsOnly): ?>
                                <button type="button" id="syncSuppliersBtn" class="btn btn-outline-primary" style="white-space:nowrap;" onclick="syncEisSuppliers()">&#8635; Sync</button>
                            <?php endif; ?>
                        </div>
                        <p class="text-muted small mt-1 mb-0"><?php echo $imsOnly ? 'Supplier is optional in IMS Only mode.' : 'Suppliers marked "EIS #" have a confirmed MRA EIS Supplier ID and can be used for informal-purchase submissions.'; ?></p>
                        <div id="syncSuppliersNotice" class="small mt-1"></div>
                    </div>
                    <div class="col-md-4">
                        <label class="form-label">Delivery Note Number</label>
                        <input type="text" class="form-control" name="delivery_note_number" value="<?php echo htmlspecialchars($batchHeader['delivery_note_number']); ?>">
                    </div>
                    <div class="col-md-4">
                        <label class="form-label">Purchase Order Number</label>
                        <input type="text" class="form-control" name="purchase_order_number" value="<?php echo htmlspecialchars($batchHeader['purchase_order_number']); ?>">
                    </div>
                    <div class="col-md-4">
                        <label class="form-label">Received By</label>
                        <input type="text" class="form-control" name="received_by" value="<?php echo htmlspecialchars($batchHeader['received_by']); ?>">
                    </div>
                    <div class="col-md-4">
                        <label class="form-label">Receiving Date</label>
                        <input type="date" class="form-control" name="receiving_date" value="<?php echo htmlspecialchars($batchHeader['receiving_date']); ?>">
                    </div>
                    <div class="col-md-4">
                        <label class="form-label">Default Unit of Measure</label>
                        <input type="text" class="form-control" name="unit_of_measure" value="<?php echo htmlspecialchars($batchHeader['unit_of_measure']); ?>">
                        <p class="text-muted small mt-1 mb-0">Used for any item line that doesn't specify its own.</p>
                    </div>
                    <div class="col-12">
                        <label class="form-label">Notes</label>
                        <textarea class="form-control" name="notes" rows="2"><?php echo htmlspecialchars($batchHeader['notes']); ?></textarea>
                    </div>
                </div>
            </div>
        </div>

        <h4>Item Lines <a href="add_category_form.php" class="small">(+ add new category)</a></h4>
        <div id="linesContainer">
            <?php
            if (!empty($initialLines)) {
                foreach ($initialLines as $idx => $lineValues) {
                    renderLineCard($idx, $lineValues, $categoryOptions, $profitPercentageDefault, $imsOnly);
                }
            } else {
                renderLineCard(0, [], $categoryOptions, $profitPercentageDefault, $imsOnly);
            }
            ?>
        </div>

        <template id="lineTemplate">
            <?php renderLineCard('__IDX__', [], $categoryOptions, $profitPercentageDefault, $imsOnly); ?>
        </template>

        <div class="mb-3">
            <button type="button" class="btn btn-outline-secondary" onclick="addLine()">+ Add Another Item</button>
        </div>

        <div class="d-flex gap-2">
            <button type="submit" class="btn btn-primary">Review Items &rarr;</button>
            <a href="choose_warehouse_form.php" class="btn btn-secondary">Cancel</a>
        </div>
    </form>

<?php elseif ($view === 'details'): ?>

    <?php
    $sumRetail = 0.0; $sumPurchase = 0.0; $sumQty = 0;
    foreach ($preparedLines as $l) { $sumRetail += $l['unit_price'] * $l['quantity']; $sumPurchase += $l['landing_price'] * $l['quantity']; $sumQty += $l['quantity']; }
    ?>
    <h3>Review and Add Unit Details (Warehouse: <?php echo htmlspecialchars($branch_name); ?>)</h3>

    <div class="card mb-3">
        <div class="card-body">
            <div class="row text-center">
                <div class="col-md-3"><div class="text-muted small">Item Types</div><strong><?php echo count($preparedLines); ?></strong></div>
                <div class="col-md-3"><div class="text-muted small">Total Units</div><strong><?php echo $sumQty; ?></strong></div>
                <div class="col-md-3"><div class="text-muted small">Total Purchase Value</div><strong>MWK <?php echo number_format($sumPurchase, 2); ?></strong></div>
                <div class="col-md-3"><div class="text-muted small">Total Retail Value</div><strong class="text-success">MWK <?php echo number_format($sumRetail, 2); ?></strong></div>
            </div>
        </div>
    </div>

    <form method="post" action="" id="detailsForm">
        <input type="hidden" name="action" id="formAction" value="save">
        <input type="hidden" name="supplier_id" value="<?php echo (int)$batchHeader['supplier_id']; ?>">
        <input type="hidden" name="delivery_note_number" value="<?php echo htmlspecialchars($batchHeader['delivery_note_number']); ?>">
        <input type="hidden" name="purchase_order_number" value="<?php echo htmlspecialchars($batchHeader['purchase_order_number']); ?>">
        <input type="hidden" name="received_by" value="<?php echo htmlspecialchars($batchHeader['received_by']); ?>">
        <input type="hidden" name="receiving_date" value="<?php echo htmlspecialchars($batchHeader['receiving_date']); ?>">
        <input type="hidden" name="unit_of_measure" value="<?php echo htmlspecialchars($batchHeader['unit_of_measure']); ?>">
        <input type="hidden" name="notes" value="<?php echo htmlspecialchars($batchHeader['notes']); ?>">

        <?php foreach ($preparedLines as $i => $line): ?>
            <div class="card mb-3">
                <div class="card-header bg-light">
                    <strong><?php echo htmlspecialchars($line['name']); ?></strong>
                    <span class="text-muted">— <?php echo htmlspecialchars($line['category']); ?><?php if (!$imsOnly): ?> · EIS code: <?php echo htmlspecialchars($line['eis_code']); ?><?php endif; ?> · Qty: <?php echo $line['quantity']; ?></span>
                    <span class="float-end">Selling MWK <?php echo number_format($line['unit_price'], 2); ?> / unit &nbsp; Total MWK <?php echo number_format($line['unit_price'] * $line['quantity'], 2); ?></span>
                </div>
                <div class="card-body">
                    <input type="hidden" name="lines[<?php echo $i; ?>][name]" value="<?php echo htmlspecialchars($line['name']); ?>">
                    <input type="hidden" name="lines[<?php echo $i; ?>][category]" value="<?php echo htmlspecialchars($line['category']); ?>">
                    <input type="hidden" name="lines[<?php echo $i; ?>][code_method]" value="<?php echo htmlspecialchars($line['code_method']); ?>">
                    <input type="hidden" name="lines[<?php echo $i; ?>][quantity]" value="<?php echo (int)$line['quantity']; ?>">
                    <input type="hidden" name="lines[<?php echo $i; ?>][landing_price]" value="<?php echo htmlspecialchars($line['landing_price']); ?>">
                    <input type="hidden" name="lines[<?php echo $i; ?>][unit_price]" value="<?php echo htmlspecialchars($line['unit_price']); ?>">
                    <input type="hidden" name="lines[<?php echo $i; ?>][profit_percentage]" value="<?php echo htmlspecialchars($line['profit_percentage']); ?>">
                    <input type="hidden" name="lines[<?php echo $i; ?>][warranty]" value="<?php echo htmlspecialchars($line['warranty']); ?>">
                    <input type="hidden" name="lines[<?php echo $i; ?>][eis_code]" value="<?php echo htmlspecialchars($line['eis_code']); ?>">
                    <input type="hidden" name="lines[<?php echo $i; ?>][eis_description]" value="<?php echo htmlspecialchars($line['eis_description']); ?>">
                    <input type="hidden" name="lines[<?php echo $i; ?>][unit_of_measure]" value="<?php echo htmlspecialchars($line['unit_of_measure']); ?>">
                    <input type="hidden" name="lines[<?php echo $i; ?>][finished_product]" value="<?php echo $line['finished_product'] ? 'yes' : 'no'; ?>">

                    <div class="table-responsive">
                        <table class="table table-bordered table-sm detail-table">
                            <thead>
                                <tr>
                                    <th>#</th><th>Unique Code</th><th>Condition</th><th>Brand</th><th>Model</th><th>Serial Number</th><th>Description</th><th>Technical Specs</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php for ($j = 0; $j < $line['quantity']; $j++): ?>
                                <tr>
                                    <td><?php echo $j + 1; ?></td>
                                    <td>
                                        <?php if ($line['code_method'] === 'auto'): ?>
                                            <input type="text" name="lines[<?php echo $i; ?>][unique_codes][]" value="<?php echo htmlspecialchars($line['unique_codes'][$j]); ?>" readonly>
                                        <?php else: ?>
                                            <input type="text" class="unique-code-input" name="lines[<?php echo $i; ?>][unique_codes][]" required>
                                            <div class="validation-message small"></div>
                                        <?php endif; ?>
                                    </td>
                                    <td>
                                        <select name="lines[<?php echo $i; ?>][condition_status][]" required>
                                            <option value="">Select...</option>
                                            <?php foreach ($CONDITION_OPTIONS as $cond): ?>
                                                <option value="<?php echo $cond; ?>"><?php echo $cond; ?></option>
                                            <?php endforeach; ?>
                                        </select>
                                    </td>
                                    <td><input type="text" name="lines[<?php echo $i; ?>][brands][]"></td>
                                    <td><input type="text" name="lines[<?php echo $i; ?>][models][]"></td>
                                    <td><input type="text" name="lines[<?php echo $i; ?>][serials][]"></td>
                                    <td><textarea name="lines[<?php echo $i; ?>][descriptions][]" rows="1"></textarea></td>
                                    <td><textarea name="lines[<?php echo $i; ?>][technical_specs][]" rows="1"></textarea></td>
                                </tr>
                                <?php endfor; ?>
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        <?php endforeach; ?>

        <div class="d-flex gap-2 mb-4">
            <button type="submit" class="btn btn-primary">Save Items</button>
            <button type="button" class="btn btn-info" onclick="submitAs('save_print')">Save &amp; Print Labels</button>
            <a href="choose_warehouse_form.php" class="btn btn-secondary">Cancel</a>
        </div>
    </form>

<?php elseif ($view === 'save_error'): ?>

    <div class="alert alert-danger">
        <h4>Could not save this batch</h4>
        <p>The issues above need to be corrected. Nothing was submitted to MRA EIS.</p>
        <a href="add_items.php" class="btn btn-secondary">Start Over</a>
    </div>

<?php elseif ($view === 'success'): ?>

    <div class="alert alert-success">
        <h3>Success!</h3>
        <p><strong><?php echo $totalUnits; ?> unit(s)</strong> across <strong><?php echo count($finalLines); ?> item type(s)</strong> have been added to the warehouse inventory.</p>
        <p><strong>Total Purchase Value:</strong> MWK <?php echo number_format($totalPurchaseValue, 2); ?> &nbsp;|&nbsp; <strong>Total Retail Value:</strong> MWK <?php echo number_format($totalRetailValue, 2); ?></p>
        <?php if (isset($eisMessage)): ?>
            <div class="alert <?php echo in_array($eisStatus, ['submitted', 'ims_only'], true) ? 'alert-success' : 'alert-warning'; ?> mt-2 mb-0">
                <strong><?php echo in_array($eisStatus, ['submitted', 'ims_only'], true) ? '✅' : '⚠️'; ?> <?php echo htmlspecialchars($eisMessage); ?></strong>
            </div>
        <?php endif; ?>
        <div class="text-center mt-3">
            <a href="add_items.php" class="back-link">&larr; Add More Items</a>
            <a href="../../inventory/view_inventory.php" class="back-link" style="background-color:#28a745;">View Inventory</a>
        </div>
    </div>

<?php elseif ($view === 'print'): ?>

    <div class="print-preview">
        <div class="preview-header">
            <h2>Item Labels Preview</h2>
            <p><?php echo $totalUnits; ?> unit(s) across <?php echo count($finalLines); ?> item type(s) added to the warehouse inventory.</p>
            <p><strong>Total Purchase Value:</strong> MWK <?php echo number_format($totalPurchaseValue, 2); ?> &nbsp;|&nbsp; <strong>Total Retail Value:</strong> MWK <?php echo number_format($totalRetailValue, 2); ?></p>
            <?php if (isset($eisMessage)): ?>
                <div class="alert <?php echo in_array($eisStatus, ['submitted', 'ims_only'], true) ? 'alert-success' : 'alert-warning'; ?> mb-0">
                    <strong><?php echo in_array($eisStatus, ['submitted', 'ims_only'], true) ? '✅' : '⚠️'; ?> <?php echo htmlspecialchars($eisMessage); ?></strong>
                </div>
            <?php endif; ?>
        </div>

        <div class="print-controls">
            <button class="btn btn-success" onclick="window.print()">🖨️ Print All Labels</button>
            <button class="btn btn-secondary" onclick="window.location.href='choose_warehouse_form.php'">&larr; Back to Form Selection</button>
        </div>

        <div class="printable-area">
            <div class="sticker-grid">
                <?php
                $barcode_errors = 0; $barcode_success = 0;
                $allCodesFlat = [];
                foreach ($finalLines as $line) { $allCodesFlat = array_merge($allCodesFlat, $line['uniqueCodes']); }
                foreach ($allCodesFlat as $code): ?>
                    <div class="sticker-preview">
                        <?php
                        if (!empty($newlyAddedItems[$code])) {
                            $barcodePath = '/IMS/' . $newlyAddedItems[$code];
                            $fullServerPath = $_SERVER['DOCUMENT_ROOT'] . $barcodePath;
                            if (file_exists($fullServerPath)) {
                                $barcode_success++;
                                echo '<img src="' . htmlspecialchars($barcodePath) . '" alt="Barcode for ' . htmlspecialchars($code) . '" onerror="this.style.display=\'none\'; this.nextElementSibling.style.display=\'block\';">';
                                echo '<div style="display:none;color:red;font-size:8px;">No Barcode</div>';
                            } else {
                                $barcode_errors++;
                                echo '<div class="barcode-error">File Missing</div>';
                            }
                        } else {
                            $barcode_errors++;
                            echo '<div class="barcode-error">No Barcode</div>';
                        }
                        ?>
                        <div class="sticker-code"><?php echo htmlspecialchars($code); ?></div>
                    </div>
                <?php endforeach; ?>
            </div>
        </div>

        <?php if ($barcode_errors > 0 || $barcode_success > 0): ?>
            <div class="border rounded p-3 my-3">
                <h4>Barcode Generation Summary</h4>
                <div class="d-flex justify-content-around text-center">
                    <div class="text-success"><strong><?php echo $barcode_success; ?></strong><br><small>Successful</small></div>
                    <div class="text-danger"><strong><?php echo $barcode_errors; ?></strong><br><small>Errors</small></div>
                    <div class="text-secondary"><strong><?php echo count($allCodesFlat); ?></strong><br><small>Total Items</small></div>
                </div>
                <?php if ($barcode_errors > 0): ?>
                    <div class="alert alert-warning mt-3 mb-0"><strong>Note:</strong> Some barcodes could not be displayed, but all items were saved successfully. Refresh this page in a few seconds if needed.</div>
                <?php endif; ?>
            </div>
        <?php endif; ?>

        <div class="text-center my-4">
            <a href="add_items.php" class="back-link">&larr; Add More Items</a>
            <a href="../../inventory/view_inventory.php" class="back-link" style="background-color:#28a745;">View Inventory</a>
        </div>
    </div>

<?php endif; ?>

</div>

<script>
const vatRate = <?php echo json_encode($vatRate); ?>;
let lineCounter = <?php echo max(1, count($initialLines)); ?>;
const searchEndpoint = '../../api/inventory/search_eis_product.php';
let searchDebounceTimer = null;

document.addEventListener('DOMContentLoaded', () => {
    document.querySelectorAll('#linesContainer .line-card').forEach(wireLineCard);
    document.querySelectorAll('.unique-code-input').forEach(wireUniqueCodeInput);
});

function addLine() {
    const template = document.getElementById('lineTemplate');
    if (!template) return;
    const clone = template.content.cloneNode(true);
    const html = clone.querySelector('.line-card').outerHTML.replace(/__IDX__/g, lineCounter);
    const wrapper = document.createElement('div');
    wrapper.innerHTML = html;
    const card = wrapper.firstElementChild;
    document.getElementById('linesContainer').appendChild(card);
    wireLineCard(card);
    lineCounter++;
    renumberLines();
}

function removeLine(btn) {
    const container = document.getElementById('linesContainer');
    if (container.querySelectorAll('.line-card').length <= 1) {
        alert('At least one item line is required.');
        return;
    }
    btn.closest('.line-card').remove();
    renumberLines();
}

function renumberLines() {
    document.querySelectorAll('#linesContainer .line-card').forEach((card, i) => {
        const numEl = card.querySelector('.line-number');
        if (numEl) numEl.textContent = i + 1;
    });
}

function togglePreCode(select) {
    const card = select.closest('.line-card');
    const group = card.querySelector('.pre-code-group');
    group.style.display = select.value === 'auto' ? '' : 'none';
}

function wireLineCard(card) {
    const landing = card.querySelector('.landing-price-field');
    const profit = card.querySelector('.profit-field');
    const preview = card.querySelector('.unit-price-preview');

    function recalc() {
        const landingPrice = parseFloat(landing.value) || 0;
        const profitPct = parseFloat(profit.value) || 0;
        const profitAmount = landingPrice * (profitPct / 100);
        const subtotal = landingPrice + profitAmount;
        const vatAmount = subtotal * vatRate;
        const unitPrice = Math.round((subtotal + vatAmount) * 100) / 100;
        preview.value = 'MWK ' + unitPrice.toFixed(2);
    }
    landing.addEventListener('input', recalc);
    profit.addEventListener('input', recalc);
    recalc();

    if (!card.querySelector('.eis-search-input')) return;

    wireEisSearch(card);

    const manualToggle = card.querySelector('.toggle-manual-code');
    const manualInput = card.querySelector('.manual-eis-code-input');
    const codeField = card.querySelector('.eis-code-field');
    const descField = card.querySelector('.eis-description-field');
    manualToggle.addEventListener('click', (e) => {
        e.preventDefault();
        manualInput.style.display = manualInput.style.display === 'none' ? '' : 'none';
        manualInput.focus();
    });
    manualInput.addEventListener('input', () => {
        codeField.value = manualInput.value.trim();
        descField.value = '';
    });

    const clearLink = card.querySelector('.clear-eis-selection');
    clearLink.addEventListener('click', (e) => {
        e.preventDefault();
        codeField.value = '';
        descField.value = '';
        card.querySelector('.eis-selected-info').style.display = 'none';
        card.querySelector('.eis-search-input').value = '';
        card.querySelector('.manual-eis-code').style.display = '';
    });
}

function wireEisSearch(card) {
    const input = card.querySelector('.eis-search-input');
    const results = card.querySelector('.eis-search-results');
    const codeField = card.querySelector('.eis-code-field');
    const descField = card.querySelector('.eis-description-field');
    const nameField = card.querySelector('.item-name-field');
    const uomField = card.querySelector('input[name*="[unit_of_measure]"]');
    const selectedInfo = card.querySelector('.eis-selected-info');
    const selectedText = card.querySelector('.eis-selected-text');
    const manualBlock = card.querySelector('.manual-eis-code');

    input.addEventListener('input', () => {
        clearTimeout(searchDebounceTimer);
        const q = input.value.trim();
        if (q.length < 2) { results.style.display = 'none'; results.innerHTML = ''; return; }
        searchDebounceTimer = setTimeout(() => runSearch(q), 300);
    });

    document.addEventListener('click', (e) => {
        if (!results.contains(e.target) && e.target !== input) {
            results.style.display = 'none';
        }
    });

    function runSearch(q) {
        fetch(searchEndpoint + '?q=' + encodeURIComponent(q))
            .then(r => r.json())
            .then(data => {
                results.innerHTML = '';
                if (!data.success || !data.products || data.products.length === 0) {
                    results.innerHTML = '<div class="list-group-item text-muted small">No matching MRA EIS products found.</div>';
                    results.style.display = '';
                    return;
                }
                data.products.forEach(p => {
                    const item = document.createElement('div');
                    item.className = 'list-group-item';
                    item.innerHTML = '<strong>' + escapeHtml(p.product_name || p.product_code) + '</strong>'
                        + '<div class="small text-muted">Code: ' + escapeHtml(p.product_code) + (p.description ? ' — ' + escapeHtml(p.description) : '') + '</div>'
                        + '<div class="small text-muted">EIS price: MWK ' + parseFloat(p.price || 0).toFixed(2) + (p.unit_of_measure ? ' / ' + escapeHtml(p.unit_of_measure) : '') + '</div>';
                    item.addEventListener('click', () => selectProduct(p));
                    results.appendChild(item);
                });
                results.style.display = '';
            })
            .catch(() => {
                results.innerHTML = '<div class="list-group-item text-danger small">Search failed. Try again.</div>';
                results.style.display = '';
            });
    }

    function selectProduct(p) {
        codeField.value = p.product_code || '';
        descField.value = p.description || p.product_name || '';
        if (!nameField.value.trim()) nameField.value = p.product_name || '';
        if (uomField && !uomField.value.trim() && p.unit_of_measure) uomField.value = p.unit_of_measure;
        selectedText.textContent = (p.product_name || p.product_code) + ' (' + p.product_code + ')';
        selectedInfo.style.display = '';
        manualBlock.style.display = 'none';
        results.style.display = 'none';
        input.value = '';
    }

    function escapeHtml(s) {
        const div = document.createElement('div');
        div.textContent = s == null ? '' : String(s);
        return div.innerHTML;
    }
}

async function syncEisSuppliers() {
    const btn = document.getElementById('syncSuppliersBtn');
    const notice = document.getElementById('syncSuppliersNotice');
    const select = document.getElementById('supplierSelect');
    const previousValue = select.value;

    btn.disabled = true;
    btn.textContent = 'Syncing...';
    notice.textContent = '';

    try {
        const response = await fetch('../../api/inventory/sync_eis_suppliers.php', { method: 'POST' });
        const data = await response.json();

        if (!data.success) {
            notice.className = 'small mt-1 text-danger';
            notice.textContent = data.error || 'Sync failed.';
            return;
        }

        select.innerHTML = '<option value="">Select supplier...</option>';
        data.suppliers.forEach(s => {
            const opt = document.createElement('option');
            opt.value = s.supplier_id;
            opt.textContent = s.supplier_name + (s.eis_supplier_id ? ' — EIS #' + s.eis_supplier_id : ' (not synced with MRA EIS)');
            select.appendChild(opt);
        });
        select.value = previousValue;

        notice.className = 'small mt-1 text-success';
        notice.textContent = data.message;
    } catch (e) {
        notice.className = 'small mt-1 text-danger';
        notice.textContent = 'Sync failed. Please try again.';
    } finally {
        btn.disabled = false;
        btn.innerHTML = '&#8635; Sync';
    }
}

function submitAs(action) {
    document.getElementById('formAction').value = action;
    document.getElementById('detailsForm').submit();
}

async function validateUniqueCode(uniqueCode) {
    try {
        const response = await fetch('../../api/inventory/validate-unique-code.php', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({ unique_code: uniqueCode })
        });
        if (!response.ok) throw new Error('Network response was not ok');
        return await response.json();
    } catch (error) {
        console.error('Error validating unique code:', error);
        return { success: false, message: 'Error validating code. Please try again.' };
    }
}

function wireUniqueCodeInput(input) {
    input.addEventListener('blur', async () => {
        const uniqueCode = input.value.trim();
        const existingMessage = input.parentNode.querySelector('.validation-message');
        if (existingMessage) existingMessage.remove();
        input.style.borderColor = '';
        if (!uniqueCode) return;

        const result = await validateUniqueCode(uniqueCode);
        const messageElement = document.createElement('div');
        messageElement.className = 'validation-message small';

        if (!result.success && result.exists) {
            messageElement.textContent = result.message;
            messageElement.style.color = 'red';
            input.style.borderColor = 'red';
        } else if (result.success) {
            messageElement.textContent = result.message;
            messageElement.style.color = 'green';
            input.style.borderColor = 'green';
        } else {
            messageElement.textContent = result.message;
            messageElement.style.color = 'orange';
        }
        input.parentNode.appendChild(messageElement);
    });
}
</script>

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