<?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_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;
    }
}

$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_units (
        id INT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
        unit_code VARCHAR(30) NOT NULL,
        unit_name VARCHAR(80) NOT NULL,
        is_active TINYINT(1) NOT NULL DEFAULT 1,
        created_at TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP,
        UNIQUE KEY uq_inventory_unit_code (unit_code)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4");

    $pdo->exec("CREATE TABLE IF NOT EXISTS inventory_items (
        id INT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
        item_code VARCHAR(60) NULL,
        item_name VARCHAR(180) NOT NULL,
        category_id INT UNSIGNED NULL,
        unit_id INT UNSIGNED NULL,
        item_type ENUM('stock','food','bar','curio','consumable','service','recipe','other') NOT NULL DEFAULT 'stock',
        barcode VARCHAR(100) NULL,
        description TEXT NULL,
        cost_price DECIMAL(14,4) NOT NULL DEFAULT 0.0000,
        avg_cost DECIMAL(14,4) NOT NULL DEFAULT 0.0000,
        selling_price DECIMAL(14,4) NOT NULL DEFAULT 0.0000,
        tax_rate DECIMAL(7,4) NOT NULL DEFAULT 0.0000,
        reorder_level DECIMAL(14,4) NOT NULL DEFAULT 0.0000,
        reorder_qty DECIMAL(14,4) NOT NULL DEFAULT 0.0000,
        is_stock_item TINYINT(1) NOT NULL DEFAULT 1,
        is_pos_item TINYINT(1) NOT NULL DEFAULT 0,
        allow_room_charge TINYINT(1) NOT NULL DEFAULT 1,
        track_expiry TINYINT(1) NOT NULL DEFAULT 0,
        is_active TINYINT(1) NOT NULL DEFAULT 1,
        created_at TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP,
        updated_at TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
        UNIQUE KEY uq_inventory_item_code (item_code),
        INDEX idx_inventory_item_name (item_name),
        INDEX idx_inventory_item_category (category_id),
        INDEX idx_inventory_item_pos (is_pos_item),
        INDEX idx_inventory_item_active (is_active)
    ) 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']] 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_item') {
            $id = (int)($_POST['id'] ?? 0);
            $itemCode = trim((string)($_POST['item_code'] ?? ''));
            $itemName = trim((string)($_POST['item_name'] ?? ''));
            $categoryId = (int)($_POST['category_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 (!in_array($itemType, ['stock','food','bar','curio','consumable','service','recipe','other'], true)) $itemType = 'stock';

            if ($itemCode === '') {
                $prefix = strtoupper(substr(preg_replace('/[^A-Za-z0-9]/', '', $itemName), 0, 3));
                $itemCode = ($prefix ?: 'ITM') . '-' . date('ymdHis');
            }

            $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,
                ':unit_id' => $unitId,
                ':item_type' => $itemType,
                ':barcode' => trim((string)($_POST['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,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,unit_id,item_type,barcode,description,cost_price,avg_cost,selling_price,tax_rate,reorder_level,reorder_qty,is_stock_item,is_pos_item,allow_room_charge,track_expiry,is_active)
                    VALUES
                    (:item_code,:item_name,:category_id,:unit_id,:item_type,:barcode,:description,:cost_price,:avg_cost,:selling_price,:tax_rate,:reorder_level,:reorder_qty,:is_stock_item,:is_pos_item,:allow_room_charge,:track_expiry,:is_active)");
                $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("SELECT COUNT(*) FROM stock_movements WHERE item_id = :id");
            $stmt->execute([':id' => $id]);
            if ((int)$stmt->fetchColumn() > 0) {
                $pdo->prepare("UPDATE inventory_items SET is_active = 0 WHERE id = :id")->execute([':id' => $id]);
                inv_flash('warning', 'Item has stock movements, so it was deactivated instead of deleted.');
            } else {
                $pdo->prepare("DELETE FROM inventory_items WHERE id = :id")->execute([':id' => $id]);
                inv_flash('success', 'Item deleted.');
            }

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

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

$categories = $units = [];
try {
    $categories = $pdo->query("SELECT * FROM inventory_item_categories WHERE is_active=1 ORDER BY category_type, category_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;
}

$filterCategory = (int)($_GET['category_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 ($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 OR ii.item_code LIKE :q OR ii.barcode LIKE :q)"; $params[':q'] = '%' . $search . '%'; }

$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, 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_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, 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();
}

$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"><i class="bi bi-upload me-2"></i>Import Items</a>
                <a href="inventory_items_template.csv" class="btn btn-outline-light"><i class="bi bi-download me-2"></i>Template</a>
                <a href="store_locations.php" class="btn btn-outline-light"><i class="bi bi-shop me-2"></i>Stores</a>
                <a href="stock_movements.php" class="btn btn-outline-light"><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="row g-4">
    <div class="col-xl-4">
        <div class="card panel-card mb-4">
            <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="row g-3">
                        <div class="col-md-5"><label class="form-label">Item Code</label><input type="text" name="item_code" class="form-control" value="<?php echo h($editItem['item_code'] ?? ''); ?>" placeholder="Auto"></div>
                        <div class="col-md-7"><label class="form-label">Barcode</label><input type="text" name="barcode" class="form-control" value="<?php echo h($editItem['barcode'] ?? ''); ?>"></div>
                    </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-6">
                            <label class="form-label">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 (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-6">
                            <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"><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">Cancel Edit</a><?php endif; ?>
                    </div>
                </form>
            </div>
        </div>

        <div class="card panel-card">
            <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"><i class="bi bi-plus-circle me-2"></i>Add Category</button>
                </form>
            </div>
        </div>
    </div>

    <div class="col-xl-8">
        <div class="card panel-card mb-4">
            <div class="card-body">
                <form method="get" class="row g-3 align-items-end">
                    <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="Item/code/barcode"></div>
                    <div class="col-md-3"><label class="form-label">Category</label><select name="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">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"><i class="bi bi-funnel"></i></button></div>
                </form>
            </div>
        </div>

        <div class="card panel-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="table-responsive">
                    <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_name']); ?></strong><div class="small text-muted">Code: <?php echo h($row['item_code'] ?: '—'); ?><?php if (!empty($row['barcode'])): ?> • Barcode: <?php echo h($row['barcode']); ?><?php endif; ?></div></td>
                                    <td><?php echo h($row['category_name'] ?: 'Uncategorised'); ?><div class="small text-muted"><?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">
                                            <a href="inventory_items.php?edit_id=<?php echo (int)$row['id']; ?>" class="btn btn-outline-primary"><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"><i class="bi bi-toggle-on"></i></button></form>
                                            <form method="post" class="d-inline" onsubmit="return confirm('Delete/deactivate this item?');"><?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"><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>

<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}
@media (max-width:575.98px){.settings-check-grid{grid-template-columns:1fr}}
</style>

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