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

$pageTitle = '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('inv_table_exists')) {
    function inv_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('inv_column_exists')) {
    function inv_column_exists(PDO $pdo, string $tableName, string $columnName): bool {
        $stmt = $pdo->prepare("SELECT COUNT(*) FROM information_schema.columns WHERE table_schema = DATABASE() AND table_name = :t AND column_name = :c");
        $stmt->execute([':t' => $tableName, ':c' => $columnName]);
        return (int)$stmt->fetchColumn() > 0;
    }
}
if (!function_exists('inv_flash')) {
    function inv_flash(string $type, string $message): void {
        $_SESSION['inventory_items_flash'][] = ['type' => $type, 'message' => $message];
    }
}
if (!function_exists('inv_get_flash')) {
    function inv_get_flash(): array {
        $items = $_SESSION['inventory_items_flash'] ?? [];
        unset($_SESSION['inventory_items_flash']);
        return $items;
    }
}
if (!function_exists('inv_bool')) {
    function inv_bool($value): int {
        return in_array((string)$value, ['1','yes','true','on'], true) ? 1 : 0;
    }
}
if (!function_exists('inv_next_item_code')) {
    function inv_next_item_code(PDO $pdo, string $itemName = ''): string {
        $base = strtoupper(substr(preg_replace('/[^A-Za-z0-9]/', '', $itemName), 0, 3));
        if ($base === '') {
            $base = 'ITM';
        }

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

        return $code;
    }
}

$errors = [];

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_item_subcategories (
        id INT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
        category_id INT UNSIGNED NOT NULL,
        subcategory_name VARCHAR(150) NOT NULL,
        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_subcategory_category_name (category_id, subcategory_name),
        INDEX idx_inventory_subcategory_category (category_id),
        INDEX idx_inventory_subcategory_active (is_active)
    ) 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,
        subcategory_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),
        INDEX idx_inventory_item_subcategory (subcategory_id),
        INDEX idx_inventory_item_pos (is_pos_item),
        INDEX idx_inventory_item_active (is_active)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4");

    if (!inv_column_exists($pdo, 'inventory_items', 'subcategory_id')) {
        $pdo->exec("ALTER TABLE inventory_items ADD COLUMN subcategory_id INT UNSIGNED NULL AFTER category_id");
    }
    try {
        $pdo->exec("ALTER TABLE inventory_items ADD INDEX idx_inventory_item_subcategory (subcategory_id)");
    } catch (Throwable $ignored) {}

    $pdo->exec("CREATE TABLE IF NOT EXISTS inventory_item_conversions (
        id INT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
        source_item_id INT UNSIGNED NOT NULL,
        destination_item_id INT UNSIGNED NOT NULL,
        source_qty DECIMAL(14,4) NOT NULL DEFAULT 1.0000,
        destination_qty DECIMAL(14,4) NOT NULL DEFAULT 1.0000,
        allow_fractional_source TINYINT(1) NOT NULL DEFAULT 0,
        round_source_up TINYINT(1) NOT NULL DEFAULT 0,
        conversion_name VARCHAR(180) NULL,
        notes TEXT NULL,
        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_conversion (source_item_id, destination_item_id),
        INDEX idx_conversion_source (source_item_id),
        INDEX idx_conversion_destination (destination_item_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),
        INDEX idx_store_location_active (is_active)
    ) 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),
        INDEX idx_stock_reference (reference_type, reference_id)
    ) 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'],['TOT','Tot / Shot'],['SERVE','Serving'],['GLASS','Glass']] as $u) {
        $stmt->execute([':code' => $u[0], ':name' => $u[1]]);
    }

    $stmt = $pdo->prepare("INSERT IGNORE INTO inventory_item_categories (category_name, category_type) VALUES (:name, :type)");
    foreach ([['Beverages','bar'],['Food Items','food'],['Curios','curio'],['Cleaning Materials','consumable'],['Guest Amenities','consumable'],['Maintenance','stock'],['Restaurant Menu','food'],['Bar Stock','bar']] as $c) {
        $stmt->execute([':name' => $c[0], ':type' => $c[1]]);
    }

    $stmt = $pdo->prepare("INSERT IGNORE INTO store_locations (location_code, location_name, location_type, is_pos_location) VALUES (:code, :name, :type, :pos)");
    foreach ([['MAIN','Main Store','main_store',0],['BAR','Bar Store','bar',1],['REST','Restaurant','restaurant',1],['CURIO','Curio Shop','curio',1],['KITCH','Kitchen','kitchen',0]] as $s) {
        $stmt->execute([':code' => $s[0], ':name' => $s[1], ':type' => $s[2], ':pos' => $s[3]]);
    }

} catch (Throwable $e) {
    $errors[] = 'Could not prepare inventory tables: ' . $e->getMessage();
}

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

        if ($action === 'save_category') {
            $categoryName = trim((string)($_POST['category_name'] ?? ''));
            $categoryType = (string)($_POST['category_type'] ?? 'stock');
            if ($categoryName === '') throw new RuntimeException('Category name is required.');
            if (!in_array($categoryType, ['stock','food','bar','curio','consumable','service','other'], true)) $categoryType = 'stock';

            $stmt = $pdo->prepare("INSERT INTO inventory_item_categories (category_name, category_type, is_active)
                VALUES (:n, :t, 1)
                ON DUPLICATE KEY UPDATE category_type = VALUES(category_type), is_active = 1");
            $stmt->execute([':n' => $categoryName, ':t' => $categoryType]);

            inv_flash('success', 'Category saved successfully.');
            header('Location: inventory_items.php');
            exit;
        }

        if ($action === 'save_subcategory') {
            $categoryId = (int)($_POST['category_id'] ?? 0);
            $subcategoryName = trim((string)($_POST['subcategory_name'] ?? ''));

            if ($categoryId <= 0) throw new RuntimeException('Please select a category for this subcategory.');
            if ($subcategoryName === '') throw new RuntimeException('Subcategory name is required.');

            $stmt = $pdo->prepare("SELECT COUNT(*) FROM inventory_item_categories WHERE id = :id AND is_active = 1");
            $stmt->execute([':id' => $categoryId]);
            if ((int)$stmt->fetchColumn() <= 0) throw new RuntimeException('Selected category is not valid or inactive.');

            $stmt = $pdo->prepare("INSERT INTO inventory_item_subcategories (category_id, subcategory_name, is_active)
                VALUES (:category_id, :subcategory_name, 1)
                ON DUPLICATE KEY UPDATE subcategory_name = VALUES(subcategory_name), is_active = 1");
            $stmt->execute([':category_id' => $categoryId, ':subcategory_name' => $subcategoryName]);

            inv_flash('success', 'Subcategory saved successfully.');
            header('Location: inventory_items.php');
            exit;
        }

        if ($action === 'save_conversion') {
            $id = (int)($_POST['id'] ?? 0);
            $sourceItemId = (int)($_POST['source_item_id'] ?? 0);
            $destinationItemId = (int)($_POST['destination_item_id'] ?? 0);
            $sourceQty = (float)($_POST['source_qty'] ?? 0);
            $destinationQty = (float)($_POST['destination_qty'] ?? 0);
            $allowFractionalSource = inv_bool($_POST['allow_fractional_source'] ?? 0);
            $roundSourceUp = inv_bool($_POST['round_source_up'] ?? 0);
            $conversionName = trim((string)($_POST['conversion_name'] ?? ''));
            $notes = trim((string)($_POST['notes'] ?? ''));
            $isActive = inv_bool($_POST['is_active'] ?? 1);

            if ($sourceItemId <= 0) throw new RuntimeException('Please select the source / bulk item.');
            if ($destinationItemId <= 0) throw new RuntimeException('Please select the destination / outlet item.');
            if ($sourceItemId === $destinationItemId) throw new RuntimeException('Source and destination item cannot be the same.');
            if ($sourceQty <= 0) throw new RuntimeException('Source quantity must be greater than zero.');
            if ($destinationQty <= 0) throw new RuntimeException('Destination quantity must be greater than zero.');

            $stmt = $pdo->prepare("SELECT COUNT(*) FROM inventory_items WHERE id IN (:source_id, :destination_id) AND is_active = 1");
            // MySQL/PDO cannot bind one placeholder twice inside IN reliably in all modes, so validate separately.
            $stmtSource = $pdo->prepare("SELECT COUNT(*) FROM inventory_items WHERE id = :id AND is_active = 1");
            $stmtSource->execute([':id' => $sourceItemId]);
            if ((int)$stmtSource->fetchColumn() <= 0) throw new RuntimeException('Source item was not found or is inactive.');
            $stmtSource->execute([':id' => $destinationItemId]);
            if ((int)$stmtSource->fetchColumn() <= 0) throw new RuntimeException('Destination item was not found or is inactive.');

            if ($id > 0) {
                $stmt = $pdo->prepare("
                    UPDATE inventory_item_conversions
                    SET source_item_id = :source_item_id,
                        destination_item_id = :destination_item_id,
                        source_qty = :source_qty,
                        destination_qty = :destination_qty,
                        allow_fractional_source = :allow_fractional_source,
                        round_source_up = :round_source_up,
                        conversion_name = :conversion_name,
                        notes = :notes,
                        is_active = :is_active
                    WHERE id = :id
                ");
                $stmt->execute([
                    ':source_item_id' => $sourceItemId,
                    ':destination_item_id' => $destinationItemId,
                    ':source_qty' => $sourceQty,
                    ':destination_qty' => $destinationQty,
                    ':allow_fractional_source' => $allowFractionalSource,
                    ':round_source_up' => $roundSourceUp,
                    ':conversion_name' => $conversionName !== '' ? $conversionName : null,
                    ':notes' => $notes !== '' ? $notes : null,
                    ':is_active' => $isActive,
                    ':id' => $id,
                ]);
                inv_flash('success', 'Item conversion updated successfully.');
            } else {
                $stmt = $pdo->prepare("
                    INSERT INTO inventory_item_conversions
                    (source_item_id, destination_item_id, source_qty, destination_qty, allow_fractional_source, round_source_up, conversion_name, notes, is_active)
                    VALUES
                    (:source_item_id, :destination_item_id, :source_qty, :destination_qty, :allow_fractional_source, :round_source_up, :conversion_name, :notes, :is_active)
                    ON DUPLICATE KEY UPDATE
                        source_qty = VALUES(source_qty),
                        destination_qty = VALUES(destination_qty),
                        allow_fractional_source = VALUES(allow_fractional_source),
                        round_source_up = VALUES(round_source_up),
                        conversion_name = VALUES(conversion_name),
                        notes = VALUES(notes),
                        is_active = VALUES(is_active)
                ");
                $stmt->execute([
                    ':source_item_id' => $sourceItemId,
                    ':destination_item_id' => $destinationItemId,
                    ':source_qty' => $sourceQty,
                    ':destination_qty' => $destinationQty,
                    ':allow_fractional_source' => $allowFractionalSource,
                    ':round_source_up' => $roundSourceUp,
                    ':conversion_name' => $conversionName !== '' ? $conversionName : null,
                    ':notes' => $notes !== '' ? $notes : null,
                    ':is_active' => $isActive,
                ]);
                inv_flash('success', 'Item conversion saved successfully.');
            }

            header('Location: inventory_items.php');
            exit;
        }

        if ($action === 'delete_conversion') {
            $id = (int)($_POST['id'] ?? 0);
            if ($id <= 0) throw new RuntimeException('Invalid conversion selected.');

            $stmt = $pdo->prepare("UPDATE inventory_item_conversions SET is_active = 0 WHERE id = :id");
            $stmt->execute([':id' => $id]);

            inv_flash('warning', 'Item conversion deactivated.');
            header('Location: inventory_items.php');
            exit;
        }

        if ($action === 'save_item') {
            $id = (int)($_POST['id'] ?? 0);
            $itemName = trim((string)($_POST['item_name'] ?? ''));
            $categoryId = (int)($_POST['category_id'] ?? 0);
            $subcategoryId = (int)($_POST['subcategory_id'] ?? 0);
            $unitId = (int)($_POST['unit_id'] ?? 0);
            $itemType = (string)($_POST['item_type'] ?? 'stock');

            if ($itemName === '') throw new RuntimeException('Item name is required.');
            if ($categoryId <= 0) throw new RuntimeException('Please select an item category.');
            if ($unitId <= 0) throw new RuntimeException('Please select a unit.');
            if ($subcategoryId > 0) {
                $stmt = $pdo->prepare("SELECT COUNT(*) FROM inventory_item_subcategories WHERE id = :id AND category_id = :category_id AND is_active = 1");
                $stmt->execute([':id' => $subcategoryId, ':category_id' => $categoryId]);
                if ((int)$stmt->fetchColumn() <= 0) throw new RuntimeException('Selected subcategory does not belong to the selected category.');
            }
            if (!in_array($itemType, ['stock','food','bar','curio','consumable','service','recipe','other'], true)) $itemType = 'stock';

            if ($id > 0) {
                $stmtExistingCode = $pdo->prepare("SELECT item_code FROM inventory_items WHERE id = :id LIMIT 1");
                $stmtExistingCode->execute([':id' => $id]);
                $itemCode = trim((string)($stmtExistingCode->fetchColumn() ?: ''));
                if ($itemCode === '') {
                    $itemCode = inv_next_item_code($pdo, $itemName);
                }
            } else {
                $itemCode = inv_next_item_code($pdo, $itemName);
            }

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

            $payload = [
                ':item_code' => $itemCode,
                ':item_name' => $itemName,
                ':category_id' => $categoryId,
                ':subcategory_id' => $subcategoryId > 0 ? $subcategoryId : null,
                ':unit_id' => $unitId,
                ':item_type' => $itemType,
                ':barcode' => null,
                ':description' => trim((string)($_POST['description'] ?? '')) ?: null,
                ':cost_price' => $costPrice,
                ':avg_cost' => $avgCost,
                ':selling_price' => (float)($_POST['selling_price'] ?? 0),
                ':tax_rate' => (float)($_POST['tax_rate'] ?? 0),
                ':reorder_level' => (float)($_POST['reorder_level'] ?? 0),
                ':reorder_qty' => (float)($_POST['reorder_qty'] ?? 0),
                ':is_stock_item' => inv_bool($_POST['is_stock_item'] ?? 0),
                ':is_pos_item' => inv_bool($_POST['is_pos_item'] ?? 0),
                ':allow_room_charge' => inv_bool($_POST['allow_room_charge'] ?? 0),
                ':track_expiry' => inv_bool($_POST['track_expiry'] ?? 0),
                ':is_active' => inv_bool($_POST['is_active'] ?? 0),
            ];

            if ($id > 0) {
                $payload[':id'] = $id;
                $stmt = $pdo->prepare("UPDATE inventory_items SET
                    item_code=:item_code,item_name=:item_name,category_id=:category_id,subcategory_id=:subcategory_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");
                $stmt->execute($payload);
                inv_flash('success', 'Inventory item updated successfully.');
            } else {
                $stmt = $pdo->prepare("INSERT INTO inventory_items
                    (item_code,item_name,category_id,subcategory_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,:subcategory_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)");
                $stmt->execute($payload);
                inv_flash('success', 'Inventory item created successfully.');
            }

            header('Location: inventory_items.php');
            exit;
        }

        if ($action === 'toggle_item') {
            $id = (int)($_POST['id'] ?? 0);
            if ($id <= 0) throw new RuntimeException('Invalid item selected.');
            $stmt = $pdo->prepare("UPDATE inventory_items SET is_active = CASE WHEN is_active = 1 THEN 0 ELSE 1 END WHERE id = :id");
            $stmt->execute([':id' => $id]);
            inv_flash('success', 'Item status updated.');
            header('Location: inventory_items.php');
            exit;
        }

        if ($action === 'delete_item') {
            $id = (int)($_POST['id'] ?? 0);
            if ($id <= 0) throw new RuntimeException('Invalid item selected.');

            $stmt = $pdo->prepare("UPDATE inventory_items SET is_active = 0 WHERE id = :id");
            $stmt->execute([':id' => $id]);

            inv_flash('warning', 'Item deactivated successfully. It was not erased from the system.');

            header('Location: inventory_items.php');
            exit;
        }

    } catch (Throwable $e) {
        inv_flash('danger', $e->getMessage());
        header('Location: inventory_items.php');
        exit;
    }
}

$categories = $subcategories = $units = [];
try {
    $categories = $pdo->query("SELECT * FROM inventory_item_categories WHERE is_active=1 ORDER BY category_type, category_name")->fetchAll(PDO::FETCH_ASSOC);
    $subcategories = $pdo->query("SELECT sc.*, c.category_name FROM inventory_item_subcategories sc INNER JOIN inventory_item_categories c ON c.id = sc.category_id WHERE sc.is_active=1 ORDER BY c.category_name, sc.subcategory_name")->fetchAll(PDO::FETCH_ASSOC);
    $units = $pdo->query("SELECT * FROM inventory_units WHERE is_active=1 ORDER BY unit_code")->fetchAll(PDO::FETCH_ASSOC);
} catch (Throwable $e) {
    $errors[] = 'Could not load categories/units: ' . $e->getMessage();
}

$editId = (int)($_GET['edit_id'] ?? 0);
$editItem = null;
if ($editId > 0) {
    $stmt = $pdo->prepare("SELECT * FROM inventory_items WHERE id = :id LIMIT 1");
    $stmt->execute([':id' => $editId]);
    $editItem = $stmt->fetch(PDO::FETCH_ASSOC) ?: null;
}

$editConversionId = (int)($_GET['edit_conversion_id'] ?? 0);
$editConversion = null;
if ($editConversionId > 0 && inv_table_exists($pdo, 'inventory_item_conversions')) {
    $stmt = $pdo->prepare("SELECT * FROM inventory_item_conversions WHERE id = :id LIMIT 1");
    $stmt->execute([':id' => $editConversionId]);
    $editConversion = $stmt->fetch(PDO::FETCH_ASSOC) ?: null;
}

/*
 * Persistent inventory filters
 * ----------------------------
 * Applied searches remain active through edits, saves, status changes and
 * page refreshes. They are cleared only by the explicit Remove Filters action.
 */
$inventoryFilterSessionKey = 'inventory_items_filters';

if (isset($_GET['reset_inventory_filters']) && (string)$_GET['reset_inventory_filters'] === '1') {
    unset($_SESSION[$inventoryFilterSessionKey]);
    header('Location: inventory_items.php');
    exit;
}

$inventoryFilterKeys = [
    'category_id',
    'subcategory_id',
    'item_type',
    'status',
    'pos',
    'q',
];

$inventoryFiltersSubmitted = false;
foreach ($inventoryFilterKeys as $inventoryFilterKey) {
    if (array_key_exists($inventoryFilterKey, $_GET)) {
        $inventoryFiltersSubmitted = true;
        break;
    }
}

if ($inventoryFiltersSubmitted) {
    $savedInventoryFilters = [];
    foreach ($inventoryFilterKeys as $inventoryFilterKey) {
        $value = $_GET[$inventoryFilterKey] ?? '';
        if (!is_array($value)) {
            $savedInventoryFilters[$inventoryFilterKey] = trim((string)$value);
        }
    }
    $_SESSION[$inventoryFilterSessionKey] = $savedInventoryFilters;
} elseif (!empty($_SESSION[$inventoryFilterSessionKey]) && is_array($_SESSION[$inventoryFilterSessionKey])) {
    foreach ($_SESSION[$inventoryFilterSessionKey] as $inventoryFilterKey => $value) {
        if (in_array($inventoryFilterKey, $inventoryFilterKeys, true)
            && !array_key_exists($inventoryFilterKey, $_GET)) {
            $_GET[$inventoryFilterKey] = (string)$value;
        }
    }
}

$filterCategory = (int)($_GET['category_id'] ?? 0);
$filterSubcategory = (int)($_GET['subcategory_id'] ?? 0);
$filterType = trim((string)($_GET['item_type'] ?? ''));
$filterStatus = trim((string)($_GET['status'] ?? ''));
$filterPos = trim((string)($_GET['pos'] ?? ''));
$search = trim((string)($_GET['q'] ?? ''));

$where = "1=1";
$params = [];

if ($filterCategory > 0) {
    $where .= " AND ii.category_id = :category_id";
    $params[':category_id'] = $filterCategory;
}

if ($filterSubcategory > 0) {
    $where .= " AND ii.subcategory_id = :subcategory_id";
    $params[':subcategory_id'] = $filterSubcategory;
}

if ($filterType !== '') {
    $where .= " AND ii.item_type = :item_type";
    $params[':item_type'] = $filterType;
}

if ($filterStatus !== '') {
    $where .= " AND ii.is_active = :is_active";
    $params[':is_active'] = (int)$filterStatus;
}

if ($filterPos !== '') {
    $where .= " AND ii.is_pos_item = :is_pos_item";
    $params[':is_pos_item'] = (int)$filterPos;
}

if ($search !== '') {
    $where .= " AND (
        ii.item_name LIKE :q_name
        OR ii.item_code LIKE :q_code
        OR CONCAT_WS(' ', ii.item_code, ii.item_name) LIKE :q_all
    )";

    $likeSearch = '%' . $search . '%';
    $params[':q_name'] = $likeSearch;
    $params[':q_code'] = $likeSearch;
    $params[':q_all'] = $likeSearch;
}

if (isset($_GET['export']) && $_GET['export'] === 'csv') {
    try {
        $stmt = $pdo->prepare("SELECT
            ii.item_code,
            ii.item_name,
            COALESCE(c.category_name, '') AS category_name,
            COALESCE(sc.subcategory_name, '') AS subcategory_name,
            ii.item_type,
            COALESCE(u.unit_code, '') AS unit_code,
            ii.cost_price,
            ii.avg_cost,
            ii.selling_price,
            ii.tax_rate,
            ii.reorder_level,
            ii.reorder_qty,
            ii.is_stock_item,
            ii.is_pos_item,
            ii.allow_room_charge,
            ii.track_expiry,
            ii.is_active,
            COALESCE(sb.balance_qty,0) AS stock_balance,
            COALESCE(sb.stock_value,0) AS stock_value
            FROM inventory_items ii
            LEFT JOIN inventory_item_categories c ON c.id=ii.category_id
            LEFT JOIN inventory_item_subcategories sc ON sc.id=ii.subcategory_id
            LEFT JOIN inventory_units u ON u.id=ii.unit_id
            LEFT JOIN (
                SELECT item_id, SUM(qty_in-qty_out) AS balance_qty, SUM((qty_in-qty_out)*unit_cost) AS stock_value
                FROM stock_movements GROUP BY item_id
            ) sb ON sb.item_id=ii.id
            WHERE $where
            ORDER BY ii.is_active DESC, c.category_name ASC, sc.subcategory_name ASC, ii.item_name ASC");
        $stmt->execute($params);

        $filename = 'inventory_items_' . date('Ymd_His') . '.csv';
        header('Content-Type: text/csv; charset=utf-8');
        header('Content-Disposition: attachment; filename="' . $filename . '"');

        $out = fopen('php://output', 'w');
        fputcsv($out, [
            'Item Code','Item Name','Category','Subcategory','Item Type','Unit',
            'Cost Price','Avg Cost','Selling Price','Tax Rate','Reorder Level','Reorder Qty',
            'Stock Item','POS Item','Allow Room Charge','Track Expiry','Active','Stock Balance','Stock Value'
        ]);

        while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
            fputcsv($out, [
                $row['item_code'],
                $row['item_name'],
                $row['category_name'],
                $row['subcategory_name'],
                $row['item_type'],
                $row['unit_code'],
                $row['cost_price'],
                $row['avg_cost'],
                $row['selling_price'],
                $row['tax_rate'],
                $row['reorder_level'],
                $row['reorder_qty'],
                (int)$row['is_stock_item'] === 1 ? 'Yes' : 'No',
                (int)$row['is_pos_item'] === 1 ? 'Yes' : 'No',
                (int)$row['allow_room_charge'] === 1 ? 'Yes' : 'No',
                (int)$row['track_expiry'] === 1 ? 'Yes' : 'No',
                (int)$row['is_active'] === 1 ? 'Active' : 'Inactive',
                $row['stock_balance'],
                $row['stock_value'],
            ]);
        }
        fclose($out);
        exit;
    } catch (Throwable $e) {
        inv_flash('danger', 'Export failed: ' . $e->getMessage());
        header('Location: inventory_items.php');
        exit;
    }
}

$items = [];
$summary = ['total'=>0,'active'=>0,'pos'=>0,'stock'=>0,'avg_value'=>0];

try {
    $stmt = $pdo->prepare("SELECT ii.*, c.category_name, c.category_type, sc.subcategory_name, u.unit_code, u.unit_name,
        COALESCE(sb.balance_qty,0) AS stock_balance,
        COALESCE(sb.stock_value,0) AS stock_value
        FROM inventory_items ii
        LEFT JOIN inventory_item_categories c ON c.id=ii.category_id
        LEFT JOIN inventory_item_subcategories sc ON sc.id=ii.subcategory_id
        LEFT JOIN inventory_units u ON u.id=ii.unit_id
        LEFT JOIN (
            SELECT item_id, SUM(qty_in-qty_out) AS balance_qty, SUM((qty_in-qty_out)*unit_cost) AS stock_value
            FROM stock_movements GROUP BY item_id
        ) sb ON sb.item_id=ii.id
        WHERE $where
        ORDER BY ii.is_active DESC, c.category_name ASC, sc.subcategory_name ASC, ii.item_name ASC
        LIMIT 500");
    $stmt->execute($params);
    $items = $stmt->fetchAll(PDO::FETCH_ASSOC);

    foreach ($items as $row) {
        $summary['total']++;
        if ((int)$row['is_active'] === 1) $summary['active']++;
        if ((int)$row['is_pos_item'] === 1) $summary['pos']++;
        if ((int)$row['is_stock_item'] === 1) $summary['stock']++;
        $summary['avg_value'] += (float)$row['stock_value'];
    }
} catch (Throwable $e) {
    $errors[] = 'Could not load inventory items: ' . $e->getMessage();
}

$allItemsForSelect = [];
$conversions = [];

try {
    $allItemsForSelect = $pdo->query("
        SELECT ii.id, ii.item_code, ii.item_name, ii.is_active, u.unit_code
        FROM inventory_items ii
        LEFT JOIN inventory_units u ON u.id = ii.unit_id
        WHERE ii.is_active = 1
        ORDER BY ii.item_name ASC
    ")->fetchAll(PDO::FETCH_ASSOC);

    if (inv_table_exists($pdo, 'inventory_item_conversions')) {
        $conversions = $pdo->query("
            SELECT
                c.*,
                src.item_name AS source_item_name,
                src.item_code AS source_item_code,
                su.unit_code AS source_unit_code,
                dst.item_name AS destination_item_name,
                dst.item_code AS destination_item_code,
                du.unit_code AS destination_unit_code
            FROM inventory_item_conversions c
            INNER JOIN inventory_items src ON src.id = c.source_item_id
            INNER JOIN inventory_items dst ON dst.id = c.destination_item_id
            LEFT JOIN inventory_units su ON su.id = src.unit_id
            LEFT JOIN inventory_units du ON du.id = dst.unit_id
            ORDER BY c.is_active DESC, src.item_name ASC, dst.item_name ASC
        ")->fetchAll(PDO::FETCH_ASSOC);
    }
} catch (Throwable $e) {
    $errors[] = 'Could not load item conversions: ' . $e->getMessage();
}

$flashes = inv_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-box-seam"></i> Stores &amp; POS Inventory</div>
            <div class="hero-title mt-2">Inventory Items</div>
            <div class="hero-subtitle mt-2">Manage stock, bar, curio and restaurant items with costs, average costs and POS prices.</div>
        </div>
        <div class="col-lg-4 text-lg-end">
            <div class="d-inline-flex gap-2 flex-wrap justify-content-lg-end">
                <a href="inventory_items_import.php" class="btn btn-light" title="Import inventory items">
                    <i class="bi bi-upload me-2"></i>Import Items
                </a>
                <a href="inventory_items_template.csv" class="btn btn-outline-light" title="Download import template">
                    <i class="bi bi-download me-2"></i>Template
                </a>
                <a href="store_locations.php" class="btn btn-outline-light" title="Manage store locations">
                    <i class="bi bi-shop me-2"></i>Stores
                </a>
                <a href="stock_movements.php" class="btn btn-outline-light" title="View stock movements">
                    <i class="bi bi-arrow-left-right me-2"></i>Movements
                </a>
            </div>
        </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; ?>

<?php if ($errors): ?>
    <div class="alert alert-danger">
        <div class="fw-bold mb-2">Please fix the following:</div>
        <ul class="mb-0">
            <?php foreach ($errors as $err): ?>
                <li><?php echo h($err); ?></li>
            <?php endforeach; ?>
        </ul>
    </div>
<?php endif; ?>

<div class="row g-4 mb-4">
    <div class="col-md-6 col-xl-3">
        <div class="metric-card">
            <div class="metric-icon bg-primary-subtle text-primary"><i class="bi bi-boxes"></i></div>
            <div>
                <div class="metric-label">Items Listed</div>
                <div class="metric-value"><?php echo (int)$summary['total']; ?></div>
            </div>
        </div>
    </div>

    <div class="col-md-6 col-xl-3">
        <div class="metric-card">
            <div class="metric-icon bg-success-subtle text-success"><i class="bi bi-check-circle"></i></div>
            <div>
                <div class="metric-label">Active</div>
                <div class="metric-value"><?php echo (int)$summary['active']; ?></div>
            </div>
        </div>
    </div>

    <div class="col-md-6 col-xl-3">
        <div class="metric-card">
            <div class="metric-icon bg-warning-subtle text-warning"><i class="bi bi-phone"></i></div>
            <div>
                <div class="metric-label">POS Items</div>
                <div class="metric-value"><?php echo (int)$summary['pos']; ?></div>
            </div>
        </div>
    </div>

    <div class="col-md-6 col-xl-3">
        <div class="metric-card">
            <div class="metric-icon bg-info-subtle text-info"><i class="bi bi-cash-stack"></i></div>
            <div>
                <div class="metric-label">Stock Value</div>
                <div class="metric-value small-value"><?php echo money_fmt($summary['avg_value']); ?></div>
            </div>
        </div>
    </div>
</div>

<div class="inventory-workspace-bar">
    <div class="inventory-workspace-copy">
        <span class="inventory-workspace-kicker">Inventory Workspace</span>
        <strong>Search and manage the item master</strong>
        <small>The item list is now the primary workspace. Setup tools remain available from the shortcuts.</small>
    </div>
    <div class="inventory-workspace-actions">
        <button type="button" class="inventory-jump active" data-jump-target="inventory-filter-card">
            <i class="bi bi-search"></i><span>Find Items</span>
        </button>
        <button type="button" class="inventory-jump" data-jump-target="inventory-item-editor-card">
            <i class="bi bi-plus-square"></i><span>New Item</span>
        </button>
        <button type="button" class="inventory-jump" data-jump-target="inventory-conversions-card">
            <i class="bi bi-shuffle"></i><span>Conversions</span>
        </button>
        <button type="button" class="inventory-jump" data-jump-target="inventory-category-card">
            <i class="bi bi-tags"></i><span>Categories</span>
        </button>
        <a class="inventory-jump" href="stock_movements.php">
            <i class="bi bi-arrow-left-right"></i><span>Movements</span>
        </a>
        <a class="inventory-jump" href="inventory_items_import.php">
            <i class="bi bi-upload"></i><span>Import</span>
        </a>
    </div>
</div>

<div class="row g-4 inventory-workspace-grid">
    <div class="col-xl-4">
        <div class="card panel-card mb-4 inventory-focus-card" id="inventory-item-editor-card">
            <div class="card-header">
                <h5 class="mb-0"><?php echo $editItem ? 'Edit Inventory Item' : 'Add Inventory Item'; ?></h5>
            </div>
            <div class="card-body">
                <form method="post">
                    <?php if (function_exists('csrf_field')) echo csrf_field(); ?>
                    <input type="hidden" name="action" value="save_item">
                    <input type="hidden" name="id" value="<?php echo (int)($editItem['id'] ?? 0); ?>">

                    <div class="alert alert-light border small mb-3">
                        <i class="bi bi-upc-scan me-1"></i>
                        Item code is generated automatically when saving. Barcode is hidden and not required.
                    </div>

                    <div class="mt-3">
                        <label class="form-label">Item Name</label>
                        <input type="text" name="item_name" class="form-control" required value="<?php echo h($editItem['item_name'] ?? ''); ?>" placeholder="Castle Lager 330ml">
                    </div>

                    <div class="row g-3 mt-0">
                        <div class="col-md-4">
                            <label class="form-label">Category</label>
                            <select name="category_id" id="item_category_id" class="form-select" required>
                                <option value="">Select category</option>
                                <?php foreach ($categories as $cat): ?>
                                    <option value="<?php echo (int)$cat['id']; ?>" <?php echo (int)($editItem['category_id'] ?? 0) === (int)$cat['id'] ? 'selected' : ''; ?>>
                                        <?php echo h($cat['category_name']); ?> (<?php echo h($cat['category_type']); ?>)
                                    </option>
                                <?php endforeach; ?>
                            </select>
                        </div>

                        <div class="col-md-4">
                            <label class="form-label">Subcategory <span class="text-muted">(optional)</span></label>
                            <select name="subcategory_id" id="item_subcategory_id" class="form-select">
                                <option value="">No subcategory</option>
                                <?php foreach ($subcategories as $sub): ?>
                                    <option value="<?php echo (int)$sub['id']; ?>"
                                            data-category-id="<?php echo (int)$sub['category_id']; ?>"
                                            <?php echo (int)($editItem['subcategory_id'] ?? 0) === (int)$sub['id'] ? 'selected' : ''; ?>>
                                        <?php echo h($sub['subcategory_name']); ?>
                                    </option>
                                <?php endforeach; ?>
                            </select>
                        </div>

                        <div class="col-md-4">
                            <label class="form-label">Unit</label>
                            <select name="unit_id" class="form-select" required>
                                <option value="">Select unit</option>
                                <?php foreach ($units as $unit): ?>
                                    <option value="<?php echo (int)$unit['id']; ?>" <?php echo (int)($editItem['unit_id'] ?? 0) === (int)$unit['id'] ? 'selected' : ''; ?>>
                                        <?php echo h($unit['unit_code']); ?> - <?php echo h($unit['unit_name']); ?>
                                    </option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                    </div>

                    <div class="mt-3">
                        <label class="form-label">Item Type</label>
                        <select name="item_type" class="form-select">
                            <?php foreach (['stock'=>'Stock','food'=>'Food','bar'=>'Bar','curio'=>'Curio','consumable'=>'Consumable','service'=>'Service','recipe'=>'Recipe/Menu Item','other'=>'Other'] as $value => $label): ?>
                                <option value="<?php echo h($value); ?>" <?php echo (($editItem['item_type'] ?? 'stock') === $value) ? 'selected' : ''; ?>>
                                    <?php echo h($label); ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                    </div>

                    <div class="row g-3 mt-0">
                        <div class="col-md-4">
                            <label class="form-label">Cost</label>
                            <input type="number" step="0.0001" name="cost_price" class="form-control" value="<?php echo h($editItem['cost_price'] ?? '0'); ?>">
                        </div>
                        <div class="col-md-4">
                            <label class="form-label">Avg Cost</label>
                            <input type="number" step="0.0001" name="avg_cost" class="form-control" value="<?php echo h($editItem['avg_cost'] ?? '0'); ?>">
                        </div>
                        <div class="col-md-4">
                            <label class="form-label">Selling</label>
                            <input type="number" step="0.0001" name="selling_price" class="form-control" value="<?php echo h($editItem['selling_price'] ?? '0'); ?>">
                        </div>
                    </div>

                    <div class="row g-3 mt-0">
                        <div class="col-md-4">
                            <label class="form-label">Tax %</label>
                            <input type="number" step="0.0001" name="tax_rate" class="form-control" value="<?php echo h($editItem['tax_rate'] ?? '0'); ?>">
                        </div>
                        <div class="col-md-4">
                            <label class="form-label">Reorder Level</label>
                            <input type="number" step="0.0001" name="reorder_level" class="form-control" value="<?php echo h($editItem['reorder_level'] ?? '0'); ?>">
                        </div>
                        <div class="col-md-4">
                            <label class="form-label">Reorder Qty</label>
                            <input type="number" step="0.0001" name="reorder_qty" class="form-control" value="<?php echo h($editItem['reorder_qty'] ?? '0'); ?>">
                        </div>
                    </div>

                    <div class="mt-3">
                        <label class="form-label">Description</label>
                        <textarea name="description" class="form-control" rows="2"><?php echo h($editItem['description'] ?? ''); ?></textarea>
                    </div>

                    <div class="settings-check-grid mt-3">
                        <?php
                        $checks = [
                            'is_stock_item'=>['Stock Item',1],
                            'is_pos_item'=>['Sell on POS',0],
                            'allow_room_charge'=>['Allow Room Charge',1],
                            'track_expiry'=>['Track Expiry',0],
                            'is_active'=>['Active',1]
                        ];
                        ?>
                        <?php foreach ($checks as $field => $info): ?>
                            <label class="setting-check">
                                <input type="checkbox" name="<?php echo h($field); ?>" value="1" <?php echo (int)($editItem[$field] ?? $info[1]) === 1 ? 'checked' : ''; ?>>
                                <span><?php echo h($info[0]); ?></span>
                            </label>
                        <?php endforeach; ?>
                    </div>

                    <div class="d-grid gap-2 mt-4">
                        <button class="btn btn-primary" title="<?php echo $editItem ? 'Update this inventory item' : 'Create new inventory item'; ?>">
                            <i class="bi bi-save me-2"></i><?php echo $editItem ? 'Update Item' : 'Create Item'; ?>
                        </button>

                        <?php if ($editItem): ?>
                            <a href="inventory_items.php" class="btn btn-outline-secondary" title="Cancel editing">Cancel Edit</a>
                        <?php endif; ?>
                    </div>
                </form>
            </div>
        </div>

        <div class="card panel-card inventory-collapsible" id="inventory-category-card" data-default-collapsed="1">
            <div class="card-header">
                <h5 class="mb-0">Quick Category</h5>
            </div>
            <div class="card-body">
                <form method="post">
                    <?php if (function_exists('csrf_field')) echo csrf_field(); ?>
                    <input type="hidden" name="action" value="save_category">

                    <div class="mb-3">
                        <label class="form-label">Category Name</label>
                        <input type="text" name="category_name" class="form-control" placeholder="Wine / Spirits / Curios">
                    </div>

                    <div class="mb-3">
                        <label class="form-label">Category Type</label>
                        <select name="category_type" class="form-select">
                            <option value="stock">Stock</option>
                            <option value="food">Food</option>
                            <option value="bar">Bar</option>
                            <option value="curio">Curio</option>
                            <option value="consumable">Consumable</option>
                            <option value="service">Service</option>
                            <option value="other">Other</option>
                        </select>
                    </div>

                    <button class="btn btn-outline-primary w-100" title="Add new item category">
                        <i class="bi bi-plus-circle me-2"></i>Add Category
                    </button>
                </form>
            </div>
        </div>

        <div class="card panel-card mt-3 inventory-collapsible" id="inventory-subcategory-card" data-default-collapsed="1">
            <div class="card-header">
                <h5 class="mb-0">Quick Subcategory</h5>
            </div>
            <div class="card-body">
                <form method="post">
                    <?php if (function_exists('csrf_field')) echo csrf_field(); ?>
                    <input type="hidden" name="action" value="save_subcategory">

                    <div class="mb-3">
                        <label class="form-label">Parent Category</label>
                        <select name="category_id" class="form-select" required>
                            <option value="">Select category</option>
                            <?php foreach ($categories as $cat): ?>
                                <option value="<?php echo (int)$cat['id']; ?>">
                                    <?php echo h($cat['category_name']); ?> (<?php echo h($cat['category_type']); ?>)
                                </option>
                            <?php endforeach; ?>
                        </select>
                    </div>

                    <div class="mb-3">
                        <label class="form-label">Subcategory Name</label>
                        <input type="text" name="subcategory_name" class="form-control" placeholder="Red Wine / Soft Drinks / Snacks" required>
                    </div>

                    <button class="btn btn-outline-primary w-100" title="Add new subcategory">
                        <i class="bi bi-diagram-3 me-2"></i>Add Subcategory
                    </button>
                </form>
            </div>
        </div>

        <div class="card panel-card mt-3 inventory-collapsible" id="inventory-conversion-editor-card" data-default-collapsed="1">
            <div class="card-header">
                <h5 class="mb-0"><i class="bi bi-shuffle me-2"></i><?php echo $editConversion ? 'Edit Item Conversion' : 'Item Conversion'; ?></h5>
            </div>
            <div class="card-body">
                <form method="post">
                    <?php if (function_exists('csrf_field')) echo csrf_field(); ?>
                    <input type="hidden" name="action" value="save_conversion">
                    <input type="hidden" name="id" value="<?php echo (int)($editConversion['id'] ?? 0); ?>">

                    <div class="alert alert-light border small">
                        Use this for bulk-to-outlet items, e.g. <strong>1 Rum Bottle = 40 Tots</strong>.
                    </div>

                    <div class="mb-3">
                        <label class="form-label">Source / Bulk Item</label>
                        <select name="source_item_id" class="form-select searchable-stock-select" required data-placeholder="Search source / bulk item">
                            <option value="">Select source item</option>
                            <?php foreach ($allItemsForSelect as $item): ?>
                                <option value="<?php echo (int)$item['id']; ?>" <?php echo ((int)($editConversion['source_item_id'] ?? 0) === (int)$item['id']) ? 'selected' : ''; ?>>
                                    <?php echo h($item['item_name']); ?><?php echo !empty($item['item_code']) ? ' - ' . h($item['item_code']) : ''; ?><?php echo !empty($item['unit_code']) ? ' (' . h($item['unit_code']) . ')' : ''; ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                    </div>

                    <div class="mb-3">
                        <label class="form-label">Destination / Outlet Item</label>
                        <select name="destination_item_id" class="form-select searchable-stock-select" required data-placeholder="Search destination / outlet item">
                            <option value="">Select destination item</option>
                            <?php foreach ($allItemsForSelect as $item): ?>
                                <option value="<?php echo (int)$item['id']; ?>" <?php echo ((int)($editConversion['destination_item_id'] ?? 0) === (int)$item['id']) ? 'selected' : ''; ?>>
                                    <?php echo h($item['item_name']); ?><?php echo !empty($item['item_code']) ? ' - ' . h($item['item_code']) : ''; ?><?php echo !empty($item['unit_code']) ? ' (' . h($item['unit_code']) . ')' : ''; ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                    </div>

                    <div class="row g-2">
                        <div class="col-6">
                            <label class="form-label">Source Qty</label>
                            <input type="number" step="0.0001" min="0.0001" name="source_qty" class="form-control" value="<?php echo h($editConversion['source_qty'] ?? '1'); ?>" required>
                        </div>
                        <div class="col-6">
                            <label class="form-label">Destination Qty</label>
                            <input type="number" step="0.0001" min="0.0001" name="destination_qty" class="form-control" value="<?php echo h($editConversion['destination_qty'] ?? '40'); ?>" required>
                        </div>
                    </div>

                    <div class="mt-3">
                        <label class="form-label">Conversion Name</label>
                        <input type="text" name="conversion_name" class="form-control" value="<?php echo h($editConversion['conversion_name'] ?? ''); ?>" placeholder="1L bottle to 40 tots">
                    </div>

                    <div class="settings-check-grid mt-3">
                        <label class="setting-check">
                            <input type="checkbox" name="allow_fractional_source" value="1" <?php echo !empty($editConversion['allow_fractional_source']) ? 'checked' : ''; ?>>
                            <span>Allow fractional source</span>
                        </label>
                        <label class="setting-check">
                            <input type="checkbox" name="round_source_up" value="1" <?php echo !empty($editConversion['round_source_up']) ? 'checked' : ''; ?>>
                            <span>Round source up</span>
                        </label>
                        <label class="setting-check">
                            <input type="checkbox" name="is_active" value="1" <?php echo ((int)($editConversion['is_active'] ?? 1) === 1) ? 'checked' : ''; ?>>
                            <span>Active</span>
                        </label>
                    </div>

                    <div class="mt-3">
                        <label class="form-label">Notes</label>
                        <textarea name="notes" class="form-control" rows="2" placeholder="Optional control notes"><?php echo h($editConversion['notes'] ?? ''); ?></textarea>
                    </div>

                    <button class="btn btn-outline-primary w-100 mt-3">
                        <i class="bi bi-save me-2"></i><?php echo $editConversion ? 'Update Conversion' : 'Save Conversion'; ?>
                    </button>
                    <?php if ($editConversion): ?>
                        <a href="inventory_items.php" class="btn btn-outline-secondary w-100 mt-2">
                            Cancel Conversion Edit
                        </a>
                    <?php endif; ?>
                </form>
            </div>
        </div>
    </div>

    <div class="col-xl-8">
        <div class="card panel-card mb-4 inventory-collapsible" id="inventory-conversions-card" data-default-collapsed="1">
            <div class="card-header d-flex justify-content-between align-items-center">
                <h5 class="mb-0"><i class="bi bi-shuffle me-2"></i>Bulk / Outlet Conversions</h5>
                <span class="badge text-bg-light"><?php echo count($conversions); ?> rule(s)</span>
            </div>
            <div class="card-body p-0">
                <div class="table-responsive conversion-table-wrap">
                    <table class="table table-modern align-middle mb-0">
                        <thead>
                            <tr>
                                <th>Source / Bulk</th>
                                <th>Destination / Outlet</th>
                                <th>Conversion</th>
                                <th>Rules</th>
                                <th>Status</th>
                                <th class="text-end">Action</th>
                            </tr>
                        </thead>
                        <tbody>
                        <?php if (!$conversions): ?>
                            <tr><td colspan="6" class="text-center text-muted py-4">No item conversions configured yet.</td></tr>
                        <?php else: ?>
                            <?php foreach ($conversions as $conv): ?>
                                <tr>
                                    <td>
                                        <strong><?php echo h($conv['source_item_name']); ?></strong>
                                        <div class="small text-muted">
                                            <?php echo h($conv['source_item_code'] ?: ''); ?>
                                            <?php echo h($conv['source_unit_code'] ?: ''); ?>
                                        </div>
                                    </td>
                                    <td>
                                        <strong><?php echo h($conv['destination_item_name']); ?></strong>
                                        <div class="small text-muted">
                                            <?php echo h($conv['destination_item_code'] ?: ''); ?>
                                            <?php echo h($conv['destination_unit_code'] ?: ''); ?>
                                        </div>
                                    </td>
                                    <td>
                                        <strong>
                                            <?php echo h(number_format((float)$conv['source_qty'], 4)); ?>
                                            <?php echo h($conv['source_unit_code'] ?: ''); ?>
                                            =
                                            <?php echo h(number_format((float)$conv['destination_qty'], 4)); ?>
                                            <?php echo h($conv['destination_unit_code'] ?: ''); ?>
                                        </strong>
                                        <div class="small text-muted"><?php echo h($conv['conversion_name'] ?: 'Conversion rule'); ?></div>
                                    </td>
                                    <td>
                                        <?php if ((int)$conv['allow_fractional_source'] === 1): ?>
                                            <span class="badge text-bg-info">Fractional allowed</span>
                                        <?php elseif ((int)$conv['round_source_up'] === 1): ?>
                                            <span class="badge text-bg-warning">Round source up</span>
                                        <?php else: ?>
                                            <span class="badge text-bg-secondary">Full source unit only</span>
                                        <?php endif; ?>
                                    </td>
                                    <td>
                                        <span class="badge <?php echo (int)$conv['is_active'] === 1 ? 'text-bg-success' : 'text-bg-secondary'; ?>">
                                            <?php echo (int)$conv['is_active'] === 1 ? 'Active' : 'Inactive'; ?>
                                        </span>
                                    </td>
                                    <td class="text-end">
                                        <a href="inventory_items.php?edit_conversion_id=<?php echo (int)$conv['id']; ?>"
                                           class="btn btn-sm btn-outline-primary"
                                           title="Edit conversion">
                                            <i class="bi bi-pencil"></i>
                                        </a>
                                        <?php if ((int)$conv['is_active'] === 1): ?>
                                            <form method="post" class="d-inline" onsubmit="return confirm('Deactivate this conversion?');">
                                                <?php if (function_exists('csrf_field')) echo csrf_field(); ?>
                                                <input type="hidden" name="action" value="delete_conversion">
                                                <input type="hidden" name="id" value="<?php echo (int)$conv['id']; ?>">
                                                <button class="btn btn-sm btn-outline-danger"><i class="bi bi-trash"></i></button>
                                            </form>
                                        <?php else: ?>
                                            —
                                        <?php endif; ?>
                                    </td>
                                </tr>
                            <?php endforeach; ?>
                        <?php endif; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>

        <div class="card panel-card mb-4 inventory-focus-card" id="inventory-filter-card">
            <div class="card-body">
                <?php
                $activeInventoryFilterCount = 0;
                foreach ([
                    $filterCategory,
                    $filterSubcategory,
                    $filterType,
                    $filterStatus,
                    $filterPos,
                    $search
                ] as $activeInventoryFilterValue) {
                    if ((string)$activeInventoryFilterValue !== ''
                        && (string)$activeInventoryFilterValue !== '0') {
                        $activeInventoryFilterCount++;
                    }
                }
                ?>
                <?php if ($activeInventoryFilterCount > 0): ?>
                    <div class="inventory-active-filter-banner">
                        <div>
                            <i class="bi bi-funnel-fill me-2"></i>
                            <strong><?php echo $activeInventoryFilterCount; ?> active filter<?php echo $activeInventoryFilterCount === 1 ? '' : 's'; ?></strong>
                            <span>These results remain active until you remove the filters.</span>
                        </div>
                        <a href="inventory_items.php?reset_inventory_filters=1" class="btn btn-sm btn-outline-danger">
                            <i class="bi bi-x-circle me-1"></i>Remove Filters
                        </a>
                    </div>
                <?php endif; ?>
                <form method="get" class="row g-3 align-items-end inventory-filter-form">
                    <div class="col-md-3">
                        <label class="form-label">Search</label>
                        <input type="text" name="q" class="form-control" value="<?php echo h($search); ?>" placeholder="Name / auto code">
                    </div>

                    <div class="col-md-2">
                        <label class="form-label">Category</label>
                        <select name="category_id" id="filter_category_id" class="form-select">
                            <option value="0">All categories</option>
                            <?php foreach ($categories as $cat): ?>
                                <option value="<?php echo (int)$cat['id']; ?>" <?php echo $filterCategory === (int)$cat['id'] ? 'selected' : ''; ?>>
                                    <?php echo h($cat['category_name']); ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                    </div>

                    <div class="col-md-2">
                        <label class="form-label">Subcategory</label>
                        <select name="subcategory_id" id="filter_subcategory_id" class="form-select">
                            <option value="0">All</option>
                            <?php foreach ($subcategories as $sub): ?>
                                <option value="<?php echo (int)$sub['id']; ?>"
                                        data-category-id="<?php echo (int)$sub['category_id']; ?>"
                                        <?php echo $filterSubcategory === (int)$sub['id'] ? 'selected' : ''; ?>>
                                    <?php echo h($sub['subcategory_name']); ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                    </div>

                    <div class="col-md-2">
                        <label class="form-label">Type</label>
                        <select name="item_type" class="form-select">
                            <option value="">All</option>
                            <?php foreach (['stock'=>'Stock','food'=>'Food','bar'=>'Bar','curio'=>'Curio','consumable'=>'Consumable','service'=>'Service','recipe'=>'Recipe','other'=>'Other'] as $value => $label): ?>
                                <option value="<?php echo h($value); ?>" <?php echo $filterType === $value ? 'selected' : ''; ?>>
                                    <?php echo h($label); ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                    </div>

                    <div class="col-md-2">
                        <label class="form-label">POS</label>
                        <select name="pos" class="form-select">
                            <option value="">All</option>
                            <option value="1" <?php echo $filterPos === '1' ? 'selected' : ''; ?>>POS Only</option>
                            <option value="0" <?php echo $filterPos === '0' ? 'selected' : ''; ?>>Non POS</option>
                        </select>
                    </div>

                    <div class="col-md-1">
                        <label class="form-label">Status</label>
                        <select name="status" class="form-select">
                            <option value="">All</option>
                            <option value="1" <?php echo $filterStatus === '1' ? 'selected' : ''; ?>>Active</option>
                            <option value="0" <?php echo $filterStatus === '0' ? 'selected' : ''; ?>>Inactive</option>
                        </select>
                    </div>

                    <div class="col-md-1 d-grid">
                        <button class="btn btn-primary" title="Search / filter items">
                            <i class="bi bi-funnel"></i>
                        </button>
                    </div>

                    <div class="col-md-1 d-grid">
                        <button type="submit" name="export" value="csv" class="btn btn-success" title="Export all stock items matching this filter">
                            <i class="bi bi-file-earmark-spreadsheet"></i>
                        </button>
                    </div>

                    <div class="col-md-2 d-grid">
                        <a href="inventory_items.php?reset_inventory_filters=1"
                           class="btn btn-outline-secondary"
                           title="Clear the saved search and all filters">
                            <i class="bi bi-x-circle me-1"></i>Remove Filters
                        </a>
                    </div>
                </form>
            </div>
        </div>

        <div class="card panel-card inventory-focus-card" id="inventory-list-card">
            <div class="card-header d-flex justify-content-between align-items-center">
                <h5 class="mb-0">Inventory Item Master</h5>
                <span class="text-muted small">Showing latest 500 matching items</span>
            </div>

            <div class="card-body p-0">
                <div class="items-table-wrap">
                    <table class="table table-modern align-middle mb-0">
                        <thead>
                            <tr>
                                <th>Item</th>
                                <th>Category</th>
                                <th>Unit</th>
                                <th class="text-end">Cost</th>
                                <th class="text-end">Avg Cost</th>
                                <th class="text-end">Selling</th>
                                <th class="text-end">Balance</th>
                                <th>Flags</th>
                                <th class="text-end">Actions</th>
                            </tr>
                        </thead>

                        <tbody>
                        <?php if (!$items): ?>
                            <tr>
                                <td colspan="9" class="text-center text-muted py-4">
                                    No inventory items found.
                                </td>
                            </tr>
                        <?php else: ?>
                            <?php foreach ($items as $row): ?>
                                <?php
                                    $lowStock = (int)$row['is_stock_item'] === 1
                                        && (float)$row['reorder_level'] > 0
                                        && (float)$row['stock_balance'] <= (float)$row['reorder_level'];
                                ?>
                                <tr class="<?php echo $lowStock ? 'table-warning' : ''; ?>">
                                    <td>
                                        <strong>
                                            <?php echo h($row['item_code']); ?>
                                            <?php if (!empty($row['item_code'])): ?> - <?php endif; ?>
                                            <?php echo h($row['item_name']); ?>
                                        </strong>
                                    
                                        <div class="small text-muted">
                                            <?php echo h(ucwords($row['item_type'])); ?> item
                                        </div>
                                    </td>

                                    <td>
                                        <?php echo h($row['category_name'] ?: 'Uncategorised'); ?>
                                        <div class="small text-muted">
                                            <?php echo h($row['subcategory_name'] ?: 'No subcategory'); ?> • <?php echo h(ucwords($row['item_type'])); ?>
                                        </div>
                                    </td>

                                    <td><?php echo h($row['unit_code'] ?: ''); ?></td>

                                    <td class="text-end"><?php echo money_fmt($row['cost_price']); ?></td>
                                    <td class="text-end"><?php echo money_fmt($row['avg_cost']); ?></td>
                                    <td class="text-end fw-bold"><?php echo money_fmt($row['selling_price']); ?></td>

                                    <td class="text-end">
                                        <strong><?php echo money_fmt($row['stock_balance']); ?></strong>
                                        <?php if ($lowStock): ?>
                                            <div class="small text-danger fw-bold">Low stock</div>
                                        <?php endif; ?>
                                    </td>

                                    <td>
                                        <div class="d-flex flex-wrap gap-1">
                                            <?php if ((int)$row['is_stock_item'] === 1): ?>
                                                <span class="badge text-bg-primary">Stock</span>
                                            <?php endif; ?>

                                            <?php if ((int)$row['is_pos_item'] === 1): ?>
                                                <span class="badge text-bg-success">POS</span>
                                            <?php endif; ?>

                                            <?php if ((int)$row['allow_room_charge'] === 1): ?>
                                                <span class="badge text-bg-info">Room</span>
                                            <?php endif; ?>

                                            <span class="badge <?php echo (int)$row['is_active'] === 1 ? 'text-bg-success' : 'text-bg-secondary'; ?>">
                                                <?php echo (int)$row['is_active'] === 1 ? 'Active' : 'Inactive'; ?>
                                            </span>
                                        </div>
                                    </td>

                                    <td class="text-end">
                                        <div class="btn-group btn-group-sm action-btns">
                                            <a href="inventory_items.php?edit_id=<?php echo (int)$row['id']; ?>"
                                               class="btn btn-outline-primary"
                                               title="Edit Item"
                                               aria-label="Edit Item">
                                                <i class="bi bi-pencil"></i>
                                            </a>

                                            <form method="post" class="d-inline">
                                                <?php if (function_exists('csrf_field')) echo csrf_field(); ?>
                                                <input type="hidden" name="action" value="toggle_item">
                                                <input type="hidden" name="id" value="<?php echo (int)$row['id']; ?>">

                                                <button class="btn btn-outline-secondary"
                                                        title="<?php echo (int)$row['is_active'] === 1 ? 'Deactivate Item' : 'Activate Item'; ?>"
                                                        aria-label="<?php echo (int)$row['is_active'] === 1 ? 'Deactivate Item' : 'Activate Item'; ?>">
                                                    <i class="bi <?php echo (int)$row['is_active'] === 1 ? 'bi-toggle-on' : 'bi-toggle-off'; ?>"></i>
                                                </button>
                                            </form>

                                            <form method="post" class="d-inline" onsubmit="return confirm('Deactivate this item? It will remain in the system.');">
                                                <?php if (function_exists('csrf_field')) echo csrf_field(); ?>
                                                <input type="hidden" name="action" value="delete_item">
                                                <input type="hidden" name="id" value="<?php echo (int)$row['id']; ?>">

                                                <button class="btn btn-outline-danger"
                                                        title="Deactivate Item"
                                                        aria-label="Deactivate Item">
                                                    <i class="bi bi-trash"></i>
                                                </button>
                                            </form>
                                        </div>
                                    </td>
                                </tr>
                            <?php endforeach; ?>
                        <?php endif; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>

        <div class="alert alert-info mt-4">
            <strong>Workflow note:</strong> Balances come from <code>stock_movements</code>. GRNs, transfers, stock takes and POS sales will create movement rows.
        </div>
    </div>
</div>

<script>
(function () {
    /*
     * Put daily management first:
     * search/list, then add/edit, followed by less-frequent setup functions.
     */
    var workspaceGrid = document.querySelector('.inventory-workspace-grid');
    if (workspaceGrid) {
        [
            'inventory-filter-card',
            'inventory-list-card',
            'inventory-item-editor-card',
            'inventory-conversions-card',
            'inventory-conversion-editor-card',
            'inventory-category-card',
            'inventory-subcategory-card'
        ].forEach(function(id){
            var card = document.getElementById(id);
            if (card) workspaceGrid.appendChild(card);
        });

        Array.prototype.slice.call(workspaceGrid.children).forEach(function(child){
            if (child.classList
                && (child.classList.contains('col-xl-4') || child.classList.contains('col-xl-8'))) {
                while (child.firstChild) workspaceGrid.appendChild(child.firstChild);
                child.remove();
            }
        });
    }

    var panelStateKey = 'inventory_items_panel_state_v2';
    var panelState = {};
    try { panelState = JSON.parse(localStorage.getItem(panelStateKey) || '{}'); }
    catch (e) { panelState = {}; }

    function savePanelState(){
        try { localStorage.setItem(panelStateKey, JSON.stringify(panelState)); }
        catch (e) {}
    }

    document.querySelectorAll('.inventory-collapsible').forEach(function(card){
        var header = card.querySelector(':scope > .card-header');
        if (!header) return;

        var cardId = card.id || '';
        var defaultCollapsed = card.getAttribute('data-default-collapsed') === '1';
        var collapsed = Object.prototype.hasOwnProperty.call(panelState, cardId)
            ? !!panelState[cardId]
            : defaultCollapsed;

        var toggle = document.createElement('button');
        toggle.type = 'button';
        toggle.className = 'inventory-collapse-toggle';
        toggle.title = 'Show or hide this section';
        toggle.innerHTML = '<i class="bi bi-chevron-down"></i>';
        header.appendChild(toggle);

        card.classList.toggle('is-collapsed', collapsed);

        header.addEventListener('click', function(event){
            if (event.target.closest('a')
                || event.target.closest('button:not(.inventory-collapse-toggle)')
                || event.target.closest('input')
                || event.target.closest('select')) {
                return;
            }
            card.classList.toggle('is-collapsed');
            panelState[cardId] = card.classList.contains('is-collapsed');
            savePanelState();
        });
    });

    document.querySelectorAll('.inventory-jump[data-jump-target]').forEach(function(button){
        button.addEventListener('click', function(){
            var target = document.getElementById(this.getAttribute('data-jump-target') || '');
            if (!target) return;

            if (target.classList.contains('is-collapsed')) {
                target.classList.remove('is-collapsed');
                panelState[target.id] = false;
                savePanelState();
            }

            document.querySelectorAll('.inventory-jump').forEach(function(item){
                item.classList.remove('active');
            });
            this.classList.add('active');

            target.scrollIntoView({behavior:'smooth', block:'start'});
            target.classList.remove('inventory-panel-highlight');
            void target.offsetWidth;
            target.classList.add('inventory-panel-highlight');
            window.setTimeout(function(){
                target.classList.remove('inventory-panel-highlight');
            }, 1400);
        });
    });

    var panelSubtitles = {
        'inventory-filter-card':'Search and filters remain active until removed',
        'inventory-list-card':'Review and edit the latest 500 matching items',
        'inventory-item-editor-card':'Create a new item or update the selected item',
        'inventory-conversions-card':'Review bulk-to-outlet conversion rules',
        'inventory-conversion-editor-card':'Create or change one conversion rule',
        'inventory-category-card':'Add or reactivate an item category',
        'inventory-subcategory-card':'Add a subcategory beneath a category'
    };
    Object.keys(panelSubtitles).forEach(function(id){
        var card = document.getElementById(id);
        var title = card ? card.querySelector(':scope > .card-header h5') : null;
        if (title && !title.querySelector('.inventory-panel-subtitle')) {
            var subtitle = document.createElement('span');
            subtitle.className = 'inventory-panel-subtitle';
            subtitle.textContent = panelSubtitles[id];
            title.appendChild(subtitle);
        }
    });

    function filterSubcategories(categorySelectId, subcategorySelectId, allLabelValue) {
        var categorySelect = document.getElementById(categorySelectId);
        var subcategorySelect = document.getElementById(subcategorySelectId);
        if (!categorySelect || !subcategorySelect) return;

        function applyFilter() {
            var categoryId = categorySelect.value || '0';
            var selectedOption = subcategorySelect.options[subcategorySelect.selectedIndex];
            var selectedHidden = false;

            Array.prototype.forEach.call(subcategorySelect.options, function (opt) {
                if (!opt.value || opt.value === allLabelValue) {
                    opt.hidden = false;
                    return;
                }

                var optionCategory = opt.getAttribute('data-category-id') || '';
                var shouldHide = categoryId !== '0' && categoryId !== '' && optionCategory !== categoryId;
                opt.hidden = shouldHide;

                if (opt.selected && shouldHide) selectedHidden = true;
            });

            if (selectedHidden) subcategorySelect.value = allLabelValue;
        }

        categorySelect.addEventListener('change', applyFilter);
        applyFilter();
    }

    filterSubcategories('item_category_id', 'item_subcategory_id', '');
    filterSubcategories('filter_category_id', 'filter_subcategory_id', '0');

    <?php if ($editItem): ?>
    window.setTimeout(function(){
        var editor = document.getElementById('inventory-item-editor-card');
        if (editor) editor.scrollIntoView({behavior:'smooth', block:'start'});
    }, 120);
    <?php elseif ($editConversion): ?>
    window.setTimeout(function(){
        var conversionEditor = document.getElementById('inventory-conversion-editor-card');
        if (conversionEditor) {
            conversionEditor.classList.remove('is-collapsed');
            conversionEditor.scrollIntoView({behavior:'smooth', block:'start'});
        }
    }, 120);
    <?php endif; ?>

    function makeSearchableStockSelect(select) {
        if (!select || select.dataset.searchReady === '1') return;
        select.dataset.searchReady = '1';

        var originalName = select.getAttribute('name') || '';
        var selectedValue = select.value || '';

        /*
         * Keep the original select only as an option data source.
         * Remove its name/required and hide it so the user sees one clean control only.
         */
        select.removeAttribute('name');
        select.removeAttribute('required');
        select.classList.add('stock-source-select-hidden');

        var wrapper = document.createElement('div');
        wrapper.className = 'stock-search-combo';
        select.parentNode.insertBefore(wrapper, select);
        wrapper.appendChild(select);

        var hidden = document.createElement('input');
        hidden.type = 'hidden';
        hidden.name = originalName;
        hidden.value = selectedValue;

        var inputWrap = document.createElement('div');
        inputWrap.className = 'stock-search-input-wrap';

        var search = document.createElement('input');
        search.type = 'text';
        search.className = 'form-control stock-search-input';
        search.placeholder = select.getAttribute('data-placeholder') || 'Search item';
        search.autocomplete = 'off';

        var clearBtn = document.createElement('button');
        clearBtn.type = 'button';
        clearBtn.className = 'stock-search-clear';
        clearBtn.innerHTML = '&times;';
        clearBtn.title = 'Clear selected item';

        var dropdown = document.createElement('div');
        dropdown.className = 'stock-search-results';
        dropdown.style.display = 'none';

        inputWrap.appendChild(search);
        inputWrap.appendChild(clearBtn);

        wrapper.insertBefore(hidden, select);
        wrapper.insertBefore(inputWrap, select);
        wrapper.appendChild(dropdown);

        function optionLabel(opt) {
            return opt ? (opt.text || '').replace(/\s+/g, ' ').trim() : '';
        }

        function selectedText() {
            if (!hidden.value) return '';
            for (var i = 0; i < select.options.length; i++) {
                if (select.options[i].value === hidden.value) {
                    return optionLabel(select.options[i]);
                }
            }
            return '';
        }

        function setValue(value, label) {
            hidden.value = value || '';
            select.value = value || '';
            search.value = label || '';
            dropdown.style.display = 'none';
        }

        function renderResults() {
            var q = search.value.toLowerCase().trim();
            dropdown.innerHTML = '';

            var matches = [];
            Array.prototype.forEach.call(select.options, function (opt, idx) {
                if (idx === 0 || !opt.value) return;

                var label = optionLabel(opt);
                if (q === '' || label.toLowerCase().indexOf(q) !== -1) {
                    matches.push({ value: opt.value, label: label });
                }
            });

            if (!matches.length) {
                var empty = document.createElement('div');
                empty.className = 'stock-search-empty';
                empty.textContent = 'No matching items';
                dropdown.appendChild(empty);
                dropdown.style.display = 'block';
                return;
            }

            matches.slice(0, 60).forEach(function (row) {
                var item = document.createElement('button');
                item.type = 'button';
                item.className = 'stock-search-result';
                item.textContent = row.label;
                item.addEventListener('mousedown', function (ev) {
                    ev.preventDefault();
                    setValue(row.value, row.label);
                });
                dropdown.appendChild(item);
            });

            dropdown.style.display = 'block';
        }

        search.addEventListener('focus', function () {
            renderResults();
        });

        search.addEventListener('input', function () {
            /*
             * If user starts typing after a previous selection, clear the old value
             * unless the typed text still equals the selected label.
             */
            if (hidden.value && search.value !== selectedText()) {
                hidden.value = '';
                select.value = '';
            }
            renderResults();
        });

        search.addEventListener('keydown', function (ev) {
            if (ev.key === 'Escape') {
                dropdown.style.display = 'none';
                search.value = selectedText();
            }
        });

        clearBtn.addEventListener('click', function () {
            setValue('', '');
            search.focus();
            renderResults();
        });

        document.addEventListener('click', function (ev) {
            if (!wrapper.contains(ev.target)) {
                dropdown.style.display = 'none';
                search.value = selectedText();
            }
        });

        var form = wrapper.closest('form');
        if (form && !form.dataset.stockSearchValidationReady) {
            form.dataset.stockSearchValidationReady = '1';
            form.addEventListener('submit', function (ev) {
                var missing = false;
                Array.prototype.forEach.call(form.querySelectorAll('.stock-search-combo input[type="hidden"]'), function (hid) {
                    if (!hid.value) missing = true;
                });
                if (missing) {
                    ev.preventDefault();
                    alert('Please select both Source / Bulk Item and Destination / Outlet Item from the search results.');
                }
            });
        }

        search.value = selectedText();
    }

    Array.prototype.forEach.call(document.querySelectorAll('.searchable-stock-select'), makeSearchableStockSelect);
})();
</script>

<style>
.small-value {
    font-size: 1rem !important;
    letter-spacing: 0 !important;
}

.settings-check-grid {
    display: grid;
    grid-template-columns: repeat(2, minmax(0, 1fr));
    gap: 10px;
}

.setting-check {
    display: flex;
    align-items: center;
    gap: 8px;
    border: 1px solid rgba(15,23,42,.10);
    background: #fff;
    border-radius: 14px;
    padding: 10px 12px;
    font-weight: 800;
    font-size: 13px;
    color: #475569;
    cursor: pointer;
}

.setting-check input {
    width: 16px;
    height: 16px;
}

.action-btns .btn {
    min-width: 34px;
}

@media (max-width:575.98px) {
    .settings-check-grid {
        grid-template-columns: 1fr;
    }
}



/* =========================================================
   FINAL INVENTORY POLISH - UX ONLY, NO LOGIC CHANGES
   ========================================================= */

/* Compact top hero only */
.hero-band{
    padding:12px 16px !important;
    margin-bottom:10px !important;
}
.hero-title{
    font-size:1.35rem !important;
    margin:2px 0 !important;
    line-height:1.15 !important;
}
.hero-subtitle{
    font-size:.82rem !important;
    line-height:1.25 !important;
    margin-top:2px !important;
}
.page-eyebrow{
    font-size:.72rem !important;
    letter-spacing:.08em !important;
}
.hero-band .btn{
    padding:6px 10px !important;
    font-size:.8rem !important;
    border-radius:10px !important;
}
.hero-band .row.g-4{
    --bs-gutter-y:.5rem !important;
}

/* KPI cards compact */
.row.g-4.mb-4{
    margin-bottom:10px !important;
    --bs-gutter-x:.75rem !important;
    --bs-gutter-y:.75rem !important;
}
.metric-card{
    padding:9px 10px !important;
    gap:8px !important;
    min-height:58px !important;
}
.metric-icon{
    width:32px !important;
    height:32px !important;
    font-size:13px !important;
    border-radius:10px !important;
}
.metric-value{
    font-size:1rem !important;
    line-height:1.05 !important;
}
.metric-label{
    font-size:.72rem !important;
    margin-bottom:1px !important;
}
.small-value{
    font-size:.92rem !important;
    letter-spacing:0 !important;
}

/* Cards and forms tighter */
.card.panel-card{
    margin-bottom:10px !important;
    border-radius:16px !important;
}
.panel-card .card-header{
    padding:10px 12px !important;
}
.panel-card .card-header h5{
    font-size:.95rem !important;
}
.panel-card .card-body{
    padding:10px !important;
}
.form-label{
    font-size:.72rem !important;
    margin-bottom:2px !important;
    font-weight:700 !important;
}
.form-control,
.form-select{
    height:32px !important;
    min-height:32px !important;
    font-size:.82rem !important;
    padding:4px 8px !important;
    border-radius:9px !important;
}
textarea.form-control{
    height:auto !important;
    min-height:48px !important;
}
.row.g-3{
    --bs-gutter-x:.65rem !important;
    --bs-gutter-y:.55rem !important;
}
.mt-3{ margin-top:.55rem !important; }
.mt-4{ margin-top:.75rem !important; }
.mb-3{ margin-bottom:.55rem !important; }
.mb-4{ margin-bottom:.75rem !important; }
.alert{
    padding:8px 12px !important;
    margin-bottom:10px !important;
    border-radius:12px !important;
}

/* Compact checkbox grid */
.settings-check-grid{
    gap:7px !important;
}
.setting-check{
    padding:7px 9px !important;
    border-radius:10px !important;
    font-size:.76rem !important;
}
.setting-check input{
    width:14px !important;
    height:14px !important;
}

/* Table scroll + frozen header */
.items-table-wrap{
    max-height:calc(100vh - 245px);
    overflow:auto;
    border-radius:0 0 16px 16px;
}
.table-modern{
    border-collapse:separate;
    border-spacing:0;
    font-size:.84rem;
}
.table-modern thead th{
    position:sticky;
    top:0;
    z-index:8;
    background:linear-gradient(180deg,#ffffff,#f8fafc) !important;
    color:#64748b;
    border-bottom:2px solid #e5e7eb !important;
    text-transform:uppercase;
    letter-spacing:.06em;
    font-weight:850;
    white-space:nowrap;
}
.table-modern th,
.table-modern td{
    padding:7px 9px !important;
    vertical-align:middle !important;
}
.table-modern th{
    font-size:.72rem !important;
}
.table-modern td{
    font-size:.82rem !important;
}
.table-modern td strong{
    font-size:.86rem !important;
}
.table-modern .small{
    font-size:.68rem !important;
    line-height:1.15 !important;
}
.table-modern tbody tr:hover{
    background:#f8fafc !important;
}
.table-warning{
    background:#fff7ed !important;
}
.badge{
    font-size:.64rem !important;
    padding:4px 6px !important;
    border-radius:999px !important;
}

/* Compact actions */
.action-btns .btn{
    min-width:29px !important;
    padding:4px 6px !important;
    border-radius:8px !important;
}
.action-btns i{
    font-size:.84rem !important;
}

/* Sticky left form on desktop */
@media(min-width:1200px){
    .col-xl-4{
        position:sticky;
        top:10px;
        align-self:flex-start;
        height:fit-content;
        z-index:4;
    }
}

@media(max-width:575.98px){
    .hero-band .btn{
        width:100%;
        justify-content:center;
    }
    .items-table-wrap{
        max-height:calc(100vh - 220px);
    }
}


/* Clean one-control searchable stock item picker for conversion form */
.stock-search-combo{
    position:relative;
}
.stock-source-select-hidden{
    display:none !important;
}
.stock-search-input-wrap{
    position:relative;
}
.stock-search-input-wrap .stock-search-input{
    padding-right:32px !important;
    cursor:text;
}
.stock-search-clear{
    position:absolute;
    right:7px;
    top:50%;
    transform:translateY(-50%);
    width:20px;
    height:20px;
    border:0;
    border-radius:50%;
    background:#e5e7eb;
    color:#475569;
    font-weight:900;
    line-height:18px;
    font-size:14px;
    cursor:pointer;
}
.stock-search-clear:hover{
    background:#cbd5e1;
}
.stock-search-results{
    position:absolute;
    left:0;
    right:0;
    top:calc(100% + 4px);
    z-index:9999;
    max-height:260px;
    overflow:auto;
    background:#fff;
    border:1px solid #dbe3ef;
    border-radius:12px;
    box-shadow:0 18px 38px rgba(15,23,42,.18);
    padding:5px;
}
.stock-search-result{
    display:block;
    width:100%;
    border:0;
    background:#fff;
    text-align:left;
    padding:8px 10px;
    border-radius:9px;
    font-size:.82rem;
    color:#0f172a;
    cursor:pointer;
}
.stock-search-result:hover{
    background:#eff6ff;
    color:#1d4ed8;
}
.stock-search-empty{
    padding:10px;
    color:#64748b;
    font-size:.82rem;
}

/* Elite, full-width inventory workspace */
.inventory-workspace-bar{
    position:sticky;
    top:72px;
    z-index:32;
    display:flex;
    align-items:center;
    justify-content:space-between;
    gap:16px;
    margin:0 0 14px;
    padding:12px 14px;
    border:1px solid #dbe3ef;
    border-radius:18px;
    background:rgba(255,255,255,.96);
    box-shadow:0 12px 30px rgba(15,23,42,.08);
    backdrop-filter:blur(14px);
}
.inventory-workspace-copy{
    min-width:250px;
}
.inventory-workspace-copy strong{
    display:block;
    color:#0f172a;
    font-size:.96rem;
    line-height:1.2;
}
.inventory-workspace-copy small{
    display:block;
    margin-top:2px;
    color:#64748b;
    font-size:.72rem;
}
.inventory-workspace-kicker{
    display:block;
    margin-bottom:2px;
    color:#2563eb;
    font-size:.63rem;
    font-weight:950;
    text-transform:uppercase;
    letter-spacing:.1em;
}
.inventory-workspace-actions{
    display:flex;
    align-items:center;
    justify-content:flex-end;
    gap:6px;
    flex-wrap:wrap;
}
.inventory-jump{
    border:1px solid #dbe3ef;
    background:#f8fafc;
    color:#334155;
    border-radius:12px;
    padding:7px 10px;
    min-width:76px;
    display:inline-flex;
    flex-direction:column;
    align-items:center;
    gap:2px;
    font-size:.66rem;
    font-weight:900;
    text-decoration:none;
    transition:.16s ease;
}
.inventory-jump i{
    font-size:.94rem;
}
.inventory-jump:hover,
.inventory-jump.active{
    border-color:#2563eb;
    background:#eff6ff;
    color:#1d4ed8;
    transform:translateY(-1px);
}
.inventory-workspace-grid{
    display:block!important;
}
.inventory-workspace-grid>.col-xl-4,
.inventory-workspace-grid>.col-xl-8{
    display:contents;
}
.inventory-workspace-grid .panel-card{
    width:100%;
    margin-top:14px!important;
}
#inventory-filter-card{
    margin-top:0!important;
}
#inventory-list-card{
    margin-top:12px!important;
}
#inventory-item-editor-card{
    margin-top:14px!important;
}
.inventory-filter-form{
    padding:10px;
    border:1px solid #e2e8f0;
    border-radius:14px;
    background:#f8fafc;
}
.inventory-active-filter-banner{
    display:flex;
    align-items:center;
    justify-content:space-between;
    gap:12px;
    padding:9px 11px;
    margin-bottom:10px;
    border:1px solid #bfdbfe;
    border-radius:12px;
    background:#eff6ff;
    color:#1e3a8a;
    font-size:.78rem;
}
.inventory-active-filter-banner span{
    margin-left:6px;
    color:#475569;
}
.inventory-focus-card{
    border-color:#cbd5e1;
    box-shadow:0 14px 34px rgba(15,23,42,.075);
}
.inventory-collapsible>.card-header{
    cursor:pointer;
    user-select:none;
}
.inventory-collapse-toggle{
    width:30px;
    height:30px;
    margin-left:auto;
    border:1px solid #dbe3ef;
    border-radius:10px;
    background:#f8fafc;
    color:#475569;
    display:inline-flex;
    align-items:center;
    justify-content:center;
}
.inventory-collapsible.is-collapsed>.card-body,
.inventory-collapsible.is-collapsed>.table-responsive,
.inventory-collapsible.is-collapsed .conversion-table-wrap{
    display:none!important;
}
.inventory-collapsible.is-collapsed>.card-header{
    border-bottom:0;
}
.inventory-collapsible.is-collapsed .inventory-collapse-toggle i{
    transform:rotate(-90deg);
}
.inventory-collapse-toggle i{
    transition:transform .16s ease;
}
#inventory-list-card .items-table-wrap{
    max-height:600px;
    overflow:auto;
}
#inventory-list-card thead th{
    position:sticky;
    top:0;
    z-index:5;
    background:#f8fafc;
    box-shadow:0 1px 0 #e2e8f0;
}
.inventory-panel-subtitle{
    display:block;
    margin-top:2px;
    color:#64748b;
    font-size:.68rem;
    font-weight:600;
}
.inventory-panel-highlight{
    animation:inventoryPanelPulse 1.25s ease;
}
@keyframes inventoryPanelPulse{
    0%{box-shadow:0 0 0 0 rgba(37,99,235,.26)}
    45%{box-shadow:0 0 0 7px rgba(37,99,235,.08)}
    100%{box-shadow:0 12px 28px rgba(15,23,42,.07)}
}
@media (max-width:991.98px){
    .inventory-workspace-bar{
        position:static;
        display:block;
    }
    .inventory-workspace-actions{
        justify-content:flex-start;
        margin-top:10px;
    }
    .inventory-jump{
        flex:1 1 72px;
    }
}
@media (max-width:767.98px){
    .inventory-active-filter-banner{
        align-items:flex-start;
        flex-direction:column;
    }
    #inventory-list-card .items-table-wrap{
        max-height:none;
    }
}

</style>

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