<?php
require_once __DIR__ . '/../../includes/bootstrap.php';
require_login();

$pageTitle = 'Import Inventory Items';

if (!function_exists('h')) {
    function h($value): string { return htmlspecialchars((string)$value, ENT_QUOTES, 'UTF-8'); }
}
if (!function_exists('money_fmt')) {
    function money_fmt($amount): string { return number_format((float)$amount, 2); }
}
if (!function_exists('imp_bool')) {
    function imp_bool($value): int {
        $value = strtolower(trim((string)$value));
        return in_array($value, ['1','yes','true','on','active','y'], true) ? 1 : 0;
    }
}
if (!function_exists('imp_float')) {
    function imp_float($value): float {
        $value = trim((string)$value);
        if ($value === '') return 0.0;
        $value = str_replace([',', '$'], ['', ''], $value);
        return (float)$value;
    }
}
if (!function_exists('imp_table_exists')) {
    function imp_table_exists(PDO $pdo, string $tableName): bool {
        $stmt = $pdo->prepare("SELECT COUNT(*) FROM information_schema.tables WHERE table_schema = DATABASE() AND table_name = :t");
        $stmt->execute([':t' => $tableName]);
        return (int)$stmt->fetchColumn() > 0;
    }
}
if (!function_exists('imp_flash')) {
    function imp_flash(string $type, string $message): void {
        $_SESSION['inventory_import_flash'][] = ['type'=>$type, 'message'=>$message];
    }
}
if (!function_exists('imp_get_flash')) {
    function imp_get_flash(): array {
        $items = $_SESSION['inventory_import_flash'] ?? [];
        unset($_SESSION['inventory_import_flash']);
        return $items;
    }
}
if (!function_exists('imp_normalize_header')) {
    function imp_normalize_header(string $value): string {
        $value = strtolower(trim($value));
        $value = preg_replace('/[^a-z0-9]+/', '_', $value);
        return trim($value, '_');
    }
}
if (!function_exists('imp_generate_code')) {
    function imp_generate_code(PDO $pdo, string $itemName): string {
        $prefix = strtoupper(substr(preg_replace('/[^A-Za-z0-9]/', '', $itemName), 0, 3));
        if ($prefix === '') $prefix = 'ITM';

        do {
            $code = $prefix . '-' . date('ymdHis') . '-' . random_int(100, 999);
            $stmt = $pdo->prepare("SELECT COUNT(*) FROM inventory_items WHERE item_code = :code");
            $stmt->execute([':code' => $code]);
        } while ((int)$stmt->fetchColumn() > 0);

        return $code;
    }
}
if (!function_exists('imp_get_category_id')) {
    function imp_get_category_id(PDO $pdo, string $categoryName, string $itemType): int {
        $categoryName = trim($categoryName);
        if ($categoryName === '') $categoryName = 'Imported Items';

        $map = [
            'stock'=>'stock','food'=>'food','bar'=>'bar','curio'=>'curio',
            'consumable'=>'consumable','service'=>'service','recipe'=>'food','other'=>'other'
        ];
        $categoryType = $map[$itemType] ?? 'stock';

        $stmt = $pdo->prepare("SELECT id FROM inventory_item_categories WHERE category_name = :name LIMIT 1");
        $stmt->execute([':name' => $categoryName]);
        $id = (int)($stmt->fetchColumn() ?: 0);
        if ($id > 0) return $id;

        $stmt = $pdo->prepare("INSERT INTO inventory_item_categories (category_name, category_type, is_active) VALUES (:name, :type, 1)");
        $stmt->execute([':name' => $categoryName, ':type' => $categoryType]);
        return (int)$pdo->lastInsertId();
    }
}
if (!function_exists('imp_get_unit_id')) {
    function imp_get_unit_id(PDO $pdo, string $unitCode): int {
        $unitCode = strtoupper(trim($unitCode));
        if ($unitCode === '') $unitCode = 'EA';

        $stmt = $pdo->prepare("SELECT id FROM inventory_units WHERE unit_code = :code LIMIT 1");
        $stmt->execute([':code' => $unitCode]);
        $id = (int)($stmt->fetchColumn() ?: 0);
        if ($id > 0) return $id;

        $stmt = $pdo->prepare("INSERT INTO inventory_units (unit_code, unit_name, is_active) VALUES (:code, :name, 1)");
        $stmt->execute([':code' => $unitCode, ':name' => ucfirst(strtolower($unitCode))]);
        return (int)$pdo->lastInsertId();
    }
}
if (!function_exists('imp_get_store_id')) {
    function imp_get_store_id(PDO $pdo, string $storeCode): int {
        $storeCode = strtoupper(trim($storeCode));
        if ($storeCode === '') $storeCode = 'MAIN';

        $stmt = $pdo->prepare("SELECT id FROM store_locations WHERE location_code = :code LIMIT 1");
        $stmt->execute([':code' => $storeCode]);
        $id = (int)($stmt->fetchColumn() ?: 0);
        if ($id > 0) return $id;

        $stmt = $pdo->prepare("INSERT INTO store_locations (location_code, location_name, location_type, is_pos_location, is_active) VALUES (:code, :name, 'main_store', 0, 1)");
        $stmt->execute([':code' => $storeCode, ':name' => $storeCode . ' Store']);
        return (int)$pdo->lastInsertId();
    }
}

/* Ensure destination tables exist, matching inventory_items.php */
try {
    $pdo->exec("CREATE TABLE IF NOT EXISTS inventory_item_categories (
        id INT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
        category_name VARCHAR(120) NOT NULL,
        category_type ENUM('stock','food','bar','curio','consumable','service','other') NOT NULL DEFAULT 'stock',
        is_active TINYINT(1) NOT NULL DEFAULT 1,
        created_at TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP,
        updated_at TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
        UNIQUE KEY uq_inventory_category_name (category_name)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4");

    $pdo->exec("CREATE TABLE IF NOT EXISTS inventory_units (
        id INT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
        unit_code VARCHAR(30) NOT NULL,
        unit_name VARCHAR(80) NOT NULL,
        is_active TINYINT(1) NOT NULL DEFAULT 1,
        created_at TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP,
        UNIQUE KEY uq_inventory_unit_code (unit_code)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4");

    $pdo->exec("CREATE TABLE IF NOT EXISTS inventory_items (
        id INT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
        item_code VARCHAR(60) NULL,
        item_name VARCHAR(180) NOT NULL,
        category_id INT UNSIGNED NULL,
        unit_id INT UNSIGNED NULL,
        item_type ENUM('stock','food','bar','curio','consumable','service','recipe','other') NOT NULL DEFAULT 'stock',
        barcode VARCHAR(100) NULL,
        description TEXT NULL,
        cost_price DECIMAL(14,4) NOT NULL DEFAULT 0.0000,
        avg_cost DECIMAL(14,4) NOT NULL DEFAULT 0.0000,
        selling_price DECIMAL(14,4) NOT NULL DEFAULT 0.0000,
        tax_rate DECIMAL(7,4) NOT NULL DEFAULT 0.0000,
        reorder_level DECIMAL(14,4) NOT NULL DEFAULT 0.0000,
        reorder_qty DECIMAL(14,4) NOT NULL DEFAULT 0.0000,
        is_stock_item TINYINT(1) NOT NULL DEFAULT 1,
        is_pos_item TINYINT(1) NOT NULL DEFAULT 0,
        allow_room_charge TINYINT(1) NOT NULL DEFAULT 1,
        track_expiry TINYINT(1) NOT NULL DEFAULT 0,
        is_active TINYINT(1) NOT NULL DEFAULT 1,
        created_at TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP,
        updated_at TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
        UNIQUE KEY uq_inventory_item_code (item_code),
        INDEX idx_inventory_item_name (item_name),
        INDEX idx_inventory_item_category (category_id)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4");

    $pdo->exec("CREATE TABLE IF NOT EXISTS store_locations (
        id INT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
        location_code VARCHAR(50) NULL,
        location_name VARCHAR(150) NOT NULL,
        location_type ENUM('main_store','bar','restaurant','curio','kitchen','housekeeping','maintenance','other') NOT NULL DEFAULT 'main_store',
        is_pos_location TINYINT(1) NOT NULL DEFAULT 0,
        is_active TINYINT(1) NOT NULL DEFAULT 1,
        created_at TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP,
        updated_at TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
        UNIQUE KEY uq_store_location_code (location_code)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4");

    $pdo->exec("CREATE TABLE IF NOT EXISTS stock_movements (
        id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
        item_id INT UNSIGNED NOT NULL,
        store_id INT UNSIGNED NOT NULL,
        movement_type ENUM('OPENING','GRN','ISSUE','SALE','TRANSFER_IN','TRANSFER_OUT','ADJUSTMENT_IN','ADJUSTMENT_OUT','WASTAGE','RETURN') NOT NULL,
        qty_in DECIMAL(14,4) NOT NULL DEFAULT 0.0000,
        qty_out DECIMAL(14,4) NOT NULL DEFAULT 0.0000,
        unit_cost DECIMAL(14,4) NOT NULL DEFAULT 0.0000,
        total_cost DECIMAL(14,4) NOT NULL DEFAULT 0.0000,
        reference_type VARCHAR(60) NULL,
        reference_id BIGINT UNSIGNED NULL,
        notes TEXT NULL,
        movement_date DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
        created_at TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP,
        INDEX idx_stock_item_store (item_id, store_id),
        INDEX idx_stock_movement_date (movement_date)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4");

    $stmt = $pdo->prepare("INSERT IGNORE INTO inventory_units (unit_code, unit_name) VALUES (:code, :name)");
    foreach ([['EA','Each'],['KG','Kilogram'],['G','Gram'],['L','Litre'],['ML','Millilitre'],['BTL','Bottle'],['CAN','Can'],['PKT','Packet'],['BOX','Box'],['CASE','Case']] as $u) {
        $stmt->execute([':code'=>$u[0], ':name'=>$u[1]]);
    }
} catch (Throwable $e) {
    imp_flash('danger', 'Could not prepare import tables: ' . $e->getMessage());
}

$requiredHeaders = ['item_name'];
$allowedHeaders = [
    'item_code','item_name','category_name','unit_code','item_type','barcode','cost_price','avg_cost',
    'selling_price','tax_rate','reorder_level','reorder_qty','opening_qty','opening_store_code',
    'is_stock_item','is_pos_item','allow_room_charge','track_expiry','is_active','description'
];

$previewRows = [];
$previewErrors = [];
$importStats = ['created'=>0,'updated'=>0,'skipped'=>0,'opening'=>0];

if (($_SERVER['REQUEST_METHOD'] ?? 'GET') === 'POST') {
    try {
        if (function_exists('verify_csrf')) verify_csrf();

        $action = (string)($_POST['action'] ?? '');

        if (!isset($_FILES['import_file']) || ($_FILES['import_file']['error'] ?? UPLOAD_ERR_NO_FILE) !== UPLOAD_ERR_OK) {
            throw new RuntimeException('Please upload a CSV file.');
        }

        $tmp = $_FILES['import_file']['tmp_name'];
        $name = (string)($_FILES['import_file']['name'] ?? '');
        $ext = strtolower(pathinfo($name, PATHINFO_EXTENSION));

        if ($ext !== 'csv') {
            throw new RuntimeException('Please upload a CSV file. Save Excel files as CSV before importing.');
        }

        $handle = fopen($tmp, 'r');
        if (!$handle) throw new RuntimeException('Could not read uploaded file.');

        $rawHeaders = fgetcsv($handle);
        if (!$rawHeaders) throw new RuntimeException('CSV file has no header row.');

        $headers = [];
        foreach ($rawHeaders as $h) {
            $headers[] = imp_normalize_header((string)$h);
        }

        foreach ($requiredHeaders as $required) {
            if (!in_array($required, $headers, true)) {
                throw new RuntimeException('Missing required column: ' . $required);
            }
        }

        $rowNo = 1;
        $rows = [];
        while (($data = fgetcsv($handle)) !== false) {
            $rowNo++;
            $row = ['_row_no' => $rowNo];

            foreach ($headers as $idx => $header) {
                if ($header === '') continue;
                $row[$header] = trim((string)($data[$idx] ?? ''));
            }

            if (implode('', array_map('strval', $row)) === (string)$rowNo) {
                continue;
            }

            $itemName = trim((string)($row['item_name'] ?? ''));
            if ($itemName === '') {
                $row['_status'] = 'error';
                $row['_message'] = 'Item name is required.';
                $previewErrors[] = 'Row ' . $rowNo . ': Item name is required.';
            } else {
                $row['_status'] = 'ok';
                $row['_message'] = 'Ready';
            }

            $rows[] = $row;
        }
        fclose($handle);

        if ($action === 'preview_import') {
            $previewRows = array_slice($rows, 0, 200);
            if (count($rows) > 200) {
                $previewErrors[] = 'Preview is showing first 200 rows only. Full file has ' . count($rows) . ' rows.';
            }
        }

        if ($action === 'run_import') {
            if ($previewErrors) {
                throw new RuntimeException('Import has validation errors. Please preview and fix the file first.');
            }

            $pdo->beginTransaction();

            $findByCode = $pdo->prepare("SELECT id FROM inventory_items WHERE item_code = :code LIMIT 1");
            $findByName = $pdo->prepare("SELECT id FROM inventory_items WHERE item_name = :name LIMIT 1");

            $insertItem = $pdo->prepare("INSERT INTO inventory_items
                (item_code,item_name,category_id,unit_id,item_type,barcode,description,cost_price,avg_cost,selling_price,tax_rate,reorder_level,reorder_qty,is_stock_item,is_pos_item,allow_room_charge,track_expiry,is_active)
                VALUES
                (:item_code,:item_name,:category_id,:unit_id,:item_type,:barcode,:description,:cost_price,:avg_cost,:selling_price,:tax_rate,:reorder_level,:reorder_qty,:is_stock_item,:is_pos_item,:allow_room_charge,:track_expiry,:is_active)");

            $updateItem = $pdo->prepare("UPDATE inventory_items SET
                item_name=:item_name,category_id=:category_id,unit_id=:unit_id,item_type=:item_type,barcode=:barcode,description=:description,
                cost_price=:cost_price,avg_cost=:avg_cost,selling_price=:selling_price,tax_rate=:tax_rate,reorder_level=:reorder_level,reorder_qty=:reorder_qty,
                is_stock_item=:is_stock_item,is_pos_item=:is_pos_item,allow_room_charge=:allow_room_charge,track_expiry=:track_expiry,is_active=:is_active
                WHERE id=:id");

            $openingExists = $pdo->prepare("SELECT COUNT(*) FROM stock_movements WHERE item_id=:item_id AND store_id=:store_id AND movement_type='OPENING' AND reference_type='IMPORT_OPENING'");
            $insertOpening = $pdo->prepare("INSERT INTO stock_movements
                (item_id,store_id,movement_type,qty_in,qty_out,unit_cost,total_cost,reference_type,reference_id,notes,movement_date)
                VALUES
                (:item_id,:store_id,'OPENING',:qty_in,0,:unit_cost,:total_cost,'IMPORT_OPENING',NULL,:notes,NOW())");

            foreach ($rows as $row) {
                if (($row['_status'] ?? '') !== 'ok') {
                    $importStats['skipped']++;
                    continue;
                }

                $itemName = trim((string)($row['item_name'] ?? ''));
                $itemType = strtolower(trim((string)($row['item_type'] ?? 'stock')));
                if (!in_array($itemType, ['stock','food','bar','curio','consumable','service','recipe','other'], true)) $itemType = 'stock';

                $categoryId = imp_get_category_id($pdo, (string)($row['category_name'] ?? ''), $itemType);
                $unitId = imp_get_unit_id($pdo, (string)($row['unit_code'] ?? 'EA'));

                $itemCode = trim((string)($row['item_code'] ?? ''));
                if ($itemCode === '') $itemCode = imp_generate_code($pdo, $itemName);

                $costPrice = imp_float($row['cost_price'] ?? 0);
                $avgCost = imp_float($row['avg_cost'] ?? 0);
                if ($avgCost <= 0 && $costPrice > 0) $avgCost = $costPrice;

                $payload = [
                    ':item_code' => $itemCode,
                    ':item_name' => $itemName,
                    ':category_id' => $categoryId,
                    ':unit_id' => $unitId,
                    ':item_type' => $itemType,
                    ':barcode' => trim((string)($row['barcode'] ?? '')) ?: null,
                    ':description' => trim((string)($row['description'] ?? '')) ?: null,
                    ':cost_price' => $costPrice,
                    ':avg_cost' => $avgCost,
                    ':selling_price' => imp_float($row['selling_price'] ?? 0),
                    ':tax_rate' => imp_float($row['tax_rate'] ?? 0),
                    ':reorder_level' => imp_float($row['reorder_level'] ?? 0),
                    ':reorder_qty' => imp_float($row['reorder_qty'] ?? 0),
                    ':is_stock_item' => isset($row['is_stock_item']) && $row['is_stock_item'] !== '' ? imp_bool($row['is_stock_item']) : 1,
                    ':is_pos_item' => isset($row['is_pos_item']) && $row['is_pos_item'] !== '' ? imp_bool($row['is_pos_item']) : 0,
                    ':allow_room_charge' => isset($row['allow_room_charge']) && $row['allow_room_charge'] !== '' ? imp_bool($row['allow_room_charge']) : 1,
                    ':track_expiry' => isset($row['track_expiry']) && $row['track_expiry'] !== '' ? imp_bool($row['track_expiry']) : 0,
                    ':is_active' => isset($row['is_active']) && $row['is_active'] !== '' ? imp_bool($row['is_active']) : 1,
                ];

                $itemId = 0;
                if ($itemCode !== '') {
                    $findByCode->execute([':code' => $itemCode]);
                    $itemId = (int)($findByCode->fetchColumn() ?: 0);
                }

                if ($itemId <= 0) {
                    $findByName->execute([':name' => $itemName]);
                    $itemId = (int)($findByName->fetchColumn() ?: 0);
                }

                if ($itemId > 0) {
                    $updatePayload = $payload;
                    unset($updatePayload[':item_code']);
                    $updatePayload[':id'] = $itemId;
                    $updateItem->execute($updatePayload);
                    $importStats['updated']++;
                } else {
                    $insertItem->execute($payload);
                    $itemId = (int)$pdo->lastInsertId();
                    $importStats['created']++;
                }

                $openingQty = imp_float($row['opening_qty'] ?? 0);
                if ($openingQty > 0 && $itemId > 0) {
                    $storeId = imp_get_store_id($pdo, (string)($row['opening_store_code'] ?? 'MAIN'));
                    $unitCost = $avgCost > 0 ? $avgCost : $costPrice;

                    $openingExists->execute([':item_id'=>$itemId, ':store_id'=>$storeId]);
                    if ((int)$openingExists->fetchColumn() === 0) {
                        $insertOpening->execute([
                            ':item_id' => $itemId,
                            ':store_id' => $storeId,
                            ':qty_in' => $openingQty,
                            ':unit_cost' => $unitCost,
                            ':total_cost' => round($openingQty * $unitCost, 4),
                            ':notes' => 'Opening stock imported from migration file',
                        ]);
                        $importStats['opening']++;
                    }
                }
            }

            $pdo->commit();

            imp_flash('success', 'Import completed. Created: ' . $importStats['created'] . ', Updated: ' . $importStats['updated'] . ', Opening balances posted: ' . $importStats['opening'] . ', Skipped: ' . $importStats['skipped'] . '.');
            header('Location: inventory_items_import.php');
            exit;
        }

    } catch (Throwable $e) {
        if ($pdo->inTransaction()) $pdo->rollBack();
        imp_flash('danger', $e->getMessage());
        header('Location: inventory_items_import.php');
        exit;
    }
}

$flashes = imp_get_flash();
require_once __DIR__ . '/../../includes/header.php';
?>

<div class="hero-band">
    <div class="row g-4 align-items-center">
        <div class="col-lg-8">
            <div class="page-eyebrow text-white-50"><i class="bi bi-upload"></i> Inventory Migration</div>
            <div class="hero-title mt-2">Import Inventory Items</div>
            <div class="hero-subtitle mt-2">Bulk import item masters, categories, units and opening stock balances from CSV.</div>
        </div>
        <div class="col-lg-4 text-lg-end">
            <a href="inventory_items.php" class="btn btn-light me-2"><i class="bi bi-arrow-left me-2"></i>Back to Items</a>
            <a href="inventory_items_template.csv" class="btn btn-outline-light"><i class="bi bi-download me-2"></i>Template</a>
        </div>
    </div>
</div>

<?php foreach ($flashes as $flash): ?>
    <div class="alert alert-<?php echo h($flash['type']); ?>"><?php echo h($flash['message']); ?></div>
<?php endforeach; ?>

<div class="row g-4">
    <div class="col-xl-4">
        <div class="card panel-card mb-4">
            <div class="card-header"><h5 class="mb-0">Upload CSV</h5></div>
            <div class="card-body">
                <form method="post" enctype="multipart/form-data" class="mb-3">
                    <?php if (function_exists('csrf_field')) echo csrf_field(); ?>
                    <input type="hidden" name="action" value="preview_import">
                    <label class="form-label">CSV File</label>
                    <input type="file" name="import_file" class="form-control" accept=".csv" required>
                    <button class="btn btn-outline-primary w-100 mt-3"><i class="bi bi-eye me-2"></i>Preview File</button>
                </form>

                <form method="post" enctype="multipart/form-data">
                    <?php if (function_exists('csrf_field')) echo csrf_field(); ?>
                    <input type="hidden" name="action" value="run_import">
                    <label class="form-label">CSV File</label>
                    <input type="file" name="import_file" class="form-control" accept=".csv" required>
                    <button class="btn btn-primary w-100 mt-3" onclick="return confirm('Import this file now? Existing matching items will be updated.');">
                        <i class="bi bi-upload me-2"></i>Import Now
                    </button>
                </form>
            </div>
        </div>

        <div class="card panel-card">
            <div class="card-header"><h5 class="mb-0">Required Format</h5></div>
            <div class="card-body">
                <div class="small text-muted mb-2">Required column:</div>
                <code>item_name</code>

                <hr>

                <div class="small text-muted mb-2">Recommended columns:</div>
                <div class="template-columns">
                    <?php foreach ($allowedHeaders as $hcol): ?>
                        <span><?php echo h($hcol); ?></span>
                    <?php endforeach; ?>
                </div>

                <div class="alert alert-info mt-3 mb-0 small">
                    Opening quantities are posted as <strong>OPENING</strong> rows in <code>stock_movements</code>. They are not saved directly on the item master.
                </div>
            </div>
        </div>
    </div>

    <div class="col-xl-8">
        <?php if ($previewRows): ?>
            <div class="card panel-card mb-4">
                <div class="card-header d-flex justify-content-between align-items-center">
                    <h5 class="mb-0">Preview</h5>
                    <span class="text-muted small"><?php echo count($previewRows); ?> row(s)</span>
                </div>
                <div class="card-body p-0">
                    <?php if ($previewErrors): ?>
                        <div class="alert alert-warning m-3">
                            <strong>Warnings:</strong>
                            <ul class="mb-0">
                                <?php foreach ($previewErrors as $err): ?><li><?php echo h($err); ?></li><?php endforeach; ?>
                            </ul>
                        </div>
                    <?php endif; ?>

                    <div class="table-responsive">
                        <table class="table table-modern align-middle mb-0">
                            <thead>
                                <tr>
                                    <th>Row</th>
                                    <th>Status</th>
                                    <th>Item</th>
                                    <th>Category</th>
                                    <th>Unit</th>
                                    <th>Type</th>
                                    <th class="text-end">Cost</th>
                                    <th class="text-end">Opening</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php foreach ($previewRows as $r): ?>
                                    <tr>
                                        <td><?php echo (int)$r['_row_no']; ?></td>
                                        <td>
                                            <span class="badge <?php echo ($r['_status'] ?? '') === 'ok' ? 'text-bg-success' : 'text-bg-danger'; ?>">
                                                <?php echo h($r['_message'] ?? ''); ?>
                                            </span>
                                        </td>
                                        <td><strong><?php echo h($r['item_name'] ?? ''); ?></strong><div class="small text-muted"><?php echo h($r['item_code'] ?? 'Auto'); ?></div></td>
                                        <td><?php echo h($r['category_name'] ?? 'Imported Items'); ?></td>
                                        <td><?php echo h($r['unit_code'] ?? 'EA'); ?></td>
                                        <td><?php echo h($r['item_type'] ?? 'stock'); ?></td>
                                        <td class="text-end"><?php echo money_fmt(imp_float($r['cost_price'] ?? 0)); ?></td>
                                        <td class="text-end"><?php echo money_fmt(imp_float($r['opening_qty'] ?? 0)); ?></td>
                                    </tr>
                                <?php endforeach; ?>
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        <?php endif; ?>

        <div class="card panel-card">
            <div class="card-header"><h5 class="mb-0">Import Rules</h5></div>
            <div class="card-body">
                <div class="rule-grid">
                    <div class="rule-box"><strong>Duplicates</strong><span>Matched by item_code first, then item_name. Existing items are updated.</span></div>
                    <div class="rule-box"><strong>Categories</strong><span>Missing categories are created automatically.</span></div>
                    <div class="rule-box"><strong>Units</strong><span>Missing unit codes are created automatically.</span></div>
                    <div class="rule-box"><strong>Opening Stock</strong><span>Posted once per item/store as IMPORT_OPENING.</span></div>
                </div>
            </div>
        </div>
    </div>
</div>

<style>
.template-columns{display:flex;flex-wrap:wrap;gap:6px}
.template-columns span{background:#f1f5f9;border:1px solid #e2e8f0;border-radius:999px;padding:4px 8px;font-size:12px;font-weight:700;color:#475569}
.rule-grid{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:12px}
.rule-box{border:1px solid #e5e7eb;border-radius:16px;padding:14px;background:#fbfdff}
.rule-box strong{display:block;color:#0f172a;margin-bottom:4px}
.rule-box span{font-size:13px;color:#64748b}
@media(max-width:767.98px){.rule-grid{grid-template-columns:1fr}}
</style>

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