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

$pageTitle = 'Smart Reorder Suggestions';

if (file_exists(__DIR__ . '/../../includes/permission_check.php')) {
    require_once __DIR__ . '/../../includes/permission_check.php';
    if (function_exists('require_permission')) {
        require_permission($pdo, 'purchase_orders', 'view');
    }
}

if (!function_exists('h')) {
    function h($v): string { return htmlspecialchars((string)$v, ENT_QUOTES, 'UTF-8'); }
}
if (!function_exists('money_fmt')) {
    function money_fmt($v): string { return number_format((float)$v, 2); }
}
if (!function_exists('qty_fmt')) {
    function qty_fmt($v): string { return number_format((float)$v, 4); }
}
if (!function_exists('sr_flash')) {
    function sr_flash(string $type, string $message): void {
        $_SESSION['smart_reorder_flash'][] = ['type' => $type, 'message' => $message];
    }
}
if (!function_exists('sr_get_flash')) {
    function sr_get_flash(): array {
        $items = $_SESSION['smart_reorder_flash'] ?? [];
        unset($_SESSION['smart_reorder_flash']);
        return $items;
    }
}
if (!function_exists('sr_table_exists')) {
    function sr_table_exists(PDO $pdo, string $table): bool {
        $stmt = $pdo->prepare("SELECT COUNT(*) FROM information_schema.tables WHERE table_schema=DATABASE() AND table_name=:t");
        $stmt->execute([':t' => $table]);
        return (int)$stmt->fetchColumn() > 0;
    }
}
if (!function_exists('sr_col_exists')) {
    function sr_col_exists(PDO $pdo, string $table, string $column): 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' => $table, ':c' => $column]);
        return (int)$stmt->fetchColumn() > 0;
    }
}
if (!function_exists('sr_po_no')) {
    function sr_po_no(PDO $pdo): string {
        $prefix = 'PO-' . date('ymd') . '-';
        $stmt = $pdo->prepare("SELECT COUNT(*) FROM purchase_orders WHERE po_no LIKE :p");
        $stmt->execute([':p' => $prefix . '%']);
        return $prefix . str_pad((string)((int)$stmt->fetchColumn() + 1), 4, '0', STR_PAD_LEFT);
    }
}
if (!function_exists('sr_insert_flexible')) {
    function sr_insert_flexible(PDO $pdo, string $table, array $data): int {
        $cols = [];
        $marks = [];
        $params = [];
        foreach ($data as $col => $value) {
            if (sr_col_exists($pdo, $table, $col)) {
                $cols[] = "`$col`";
                $marks[] = ':' . $col;
                $params[':' . $col] = $value;
            }
        }
        if (!$cols) throw new RuntimeException("No matching columns for {$table}.");
        $stmt = $pdo->prepare("INSERT INTO `$table` (" . implode(',', $cols) . ") VALUES (" . implode(',', $marks) . ")");
        $stmt->execute($params);
        return (int)$pdo->lastInsertId();
    }
}

$errors = [];

try {
    $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,
        allow_room_charge TINYINT(1) NOT NULL DEFAULT 1,
        is_active TINYINT(1) NOT NULL DEFAULT 1,
        notes TEXT NULL,
        created_at TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP,
        updated_at TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
        UNIQUE KEY uq_store_location_code (location_code)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4");

    $pdo->exec("CREATE TABLE IF NOT EXISTS 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_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_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,
        supplier_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)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4");

    if (!sr_col_exists($pdo, 'inventory_items', 'supplier_id')) {
        $pdo->exec("ALTER TABLE inventory_items ADD COLUMN supplier_id INT UNSIGNED NULL AFTER unit_id");
    }

    // Use the main supplier master table used by suppliers.php.
    $pdo->exec("CREATE TABLE IF NOT EXISTS inventory_suppliers (
        id INT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
        supplier_code VARCHAR(60) NULL,
        supplier_name VARCHAR(180) NOT NULL,
        contact_person VARCHAR(120) NULL,
        phone VARCHAR(60) NULL,
        email VARCHAR(160) NULL,
        payment_terms VARCHAR(120) NULL,
        is_active TINYINT(1) NOT NULL DEFAULT 1,
        notes TEXT NULL,
        created_at TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP,
        updated_at TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
        UNIQUE KEY uq_inventory_supplier_code (supplier_code)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4");

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

    $pdo->exec("CREATE TABLE IF NOT EXISTS purchase_orders (
        id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
        po_no VARCHAR(60) NOT NULL,
        supplier_id INT UNSIGNED NULL,
        store_id INT UNSIGNED NULL,
        po_date DATE NOT NULL,
        expected_date DATE NULL,
        status ENUM('draft','ordered','part_received','received','cancelled') NOT NULL DEFAULT 'draft',
        subtotal DECIMAL(14,2) NOT NULL DEFAULT 0.00,
        tax_amount DECIMAL(14,2) NOT NULL DEFAULT 0.00,
        total_amount DECIMAL(14,2) NOT NULL DEFAULT 0.00,
        notes TEXT NULL,
        created_by INT UNSIGNED NULL,
        created_at TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP,
        updated_at TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
        UNIQUE KEY uq_po_no (po_no),
        INDEX idx_po_supplier (supplier_id),
        INDEX idx_po_store (store_id),
        INDEX idx_po_status (status)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4");

    $pdo->exec("CREATE TABLE IF NOT EXISTS purchase_order_items (
        id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
        purchase_order_id BIGINT UNSIGNED NOT NULL,
        item_id INT UNSIGNED NOT NULL,
        item_name VARCHAR(180) NOT NULL,
        qty DECIMAL(14,4) NOT NULL DEFAULT 0.0000,
        unit_cost DECIMAL(14,4) NOT NULL DEFAULT 0.0000,
        line_total DECIMAL(14,2) NOT NULL DEFAULT 0.00,
        received_qty DECIMAL(14,4) NOT NULL DEFAULT 0.0000,
        created_at TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP,
        INDEX idx_poi_po (purchase_order_id),
        INDEX idx_poi_item (item_id)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4");

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

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

        if (($_POST['action'] ?? '') === 'create_po') {
            if (function_exists('require_permission')) {
                require_permission($pdo, 'purchase_orders', 'create');
            }

            $storeId = (int)($_POST['store_id'] ?? 0);
            $supplierId = (int)($_POST['supplier_id'] ?? 0);
            $selected = $_POST['selected'] ?? [];
            $qtys = $_POST['qty'] ?? [];
            $costs = $_POST['cost'] ?? [];

            if ($storeId <= 0) throw new RuntimeException('Please select a store.');
            if ($supplierId <= 0) throw new RuntimeException('Please select supplier.');
            if (!is_array($selected) || !$selected) throw new RuntimeException('Please select at least one item to reorder.');

            $itemIds = array_map('intval', array_keys($selected));
            $itemIds = array_values(array_filter($itemIds));
            if (!$itemIds) throw new RuntimeException('No valid items selected.');

            $placeholders = implode(',', array_fill(0, count($itemIds), '?'));
            $stmt = $pdo->prepare("SELECT * FROM inventory_items WHERE id IN ($placeholders) AND is_active=1");
            $stmt->execute($itemIds);
            $items = [];
            foreach ($stmt->fetchAll(PDO::FETCH_ASSOC) as $it) {
                $items[(int)$it['id']] = $it;
            }

            $pdo->beginTransaction();

            $poNo = sr_po_no($pdo);
            $subtotal = 0;
            $lines = [];

            foreach ($itemIds as $itemId) {
                if (!isset($items[$itemId])) continue;

                $qty = (float)($qtys[$itemId] ?? 0);
                $cost = (float)($costs[$itemId] ?? 0);

                if ($qty <= 0) continue;
                if ($cost <= 0) {
                    $cost = (float)($items[$itemId]['avg_cost'] ?: $items[$itemId]['cost_price']);
                }

                $lineTotal = round($qty * $cost, 2);
                $subtotal += $lineTotal;

                $lines[] = [
                    'item_id' => $itemId,
                    'item_name' => $items[$itemId]['item_name'],
                    'qty' => $qty,
                    'unit_cost' => $cost,
                    'line_total' => $lineTotal,
                ];
            }

            if (!$lines) throw new RuntimeException('Selected items have invalid reorder quantities.');

            $poId = sr_insert_flexible($pdo, 'purchase_orders', [
                'po_no' => $poNo,
                'supplier_id' => $supplierId,
                'store_id' => $storeId,
                'po_date' => date('Y-m-d'),
                'expected_date' => null,
                'status' => 'draft',
                'subtotal' => $subtotal,
                'tax_amount' => 0,
                'total_amount' => $subtotal,
                'notes' => 'Auto-created from Smart Reorder Suggestions on ' . date('Y-m-d H:i:s'),
                'created_by' => $_SESSION['user_id'] ?? null,
                'created_at' => date('Y-m-d H:i:s'),
            ]);

            foreach ($lines as $line) {
                sr_insert_flexible($pdo, 'purchase_order_items', [
                    'purchase_order_id' => $poId,
                    'item_id' => $line['item_id'],
                    'item_name' => $line['item_name'],
                    'qty' => $line['qty'],
                    'unit_cost' => $line['unit_cost'],
                    'line_total' => $line['line_total'],
                    'received_qty' => 0,
                    'created_at' => date('Y-m-d H:i:s'),
                ]);
            }

            $pdo->commit();

            sr_flash('success', 'Draft purchase order created: ' . $poNo);
            header('Location: purchase_orders.php?po_id=' . $poId);
            exit;
        }

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

$storeId = (int)($_GET['store_id'] ?? 0);
$supplierId = (int)($_GET['supplier_id'] ?? 0);
$itemType = trim((string)($_GET['item_type'] ?? ''));
$onlyShort = (int)($_GET['only_short'] ?? 1);
$daysLookback = max(7, min(365, (int)($_GET['days'] ?? 30)));
$search = trim((string)($_GET['q'] ?? ''));

$stores = [];
$suppliers = [];
$suggestions = [];
$summary = [
    'short_items' => 0,
    'estimated_cost' => 0,
    'critical_items' => 0,
    'suggested_qty' => 0,
];

try {
    $stores = $pdo->query("SELECT id, location_name FROM store_locations WHERE is_active=1 ORDER BY location_name ASC")->fetchAll(PDO::FETCH_ASSOC);
    $suppliers = $pdo->query("SELECT id, supplier_name FROM inventory_suppliers WHERE is_active=1 ORDER BY supplier_name ASC")->fetchAll(PDO::FETCH_ASSOC);

    if ($storeId <= 0 && $stores) {
        $storeId = (int)$stores[0]['id'];
    }

    $where = "ii.is_active=1 AND ii.is_stock_item=1";
    $params = [':store_id' => $storeId, ':lookback_date' => date('Y-m-d', strtotime('-' . $daysLookback . ' days'))];

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

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

    if ($search !== '') {
        // Use unique placeholders for each LIKE clause.
        // Some PDO/MySQL setups throw SQLSTATE[HY093] when the same named placeholder is reused.
        $where .= " AND (
            ii.item_name LIKE :q_item
            OR ii.item_code LIKE :q_code
            OR s.supplier_name LIKE :q_supplier
        )";
        $likeSearch = '%' . $search . '%';
        $params[':q_item'] = $likeSearch;
        $params[':q_code'] = $likeSearch;
        $params[':q_supplier'] = $likeSearch;
    }

    $stmt = $pdo->prepare("
        SELECT
            ii.id,
            ii.item_code,
            ii.item_name,
            ii.item_type,
            ii.reorder_level,
            ii.reorder_qty,
            COALESCE(NULLIF(ii.avg_cost,0), ii.cost_price, 0) AS resolved_cost,
            u.unit_code,
            s.id AS supplier_id,
            s.supplier_name,
            COALESCE(bal.current_qty,0) AS current_qty,
            COALESCE(cons.avg_daily_out,0) AS avg_daily_out,
            COALESCE(cons.period_out,0) AS period_out
        FROM inventory_items ii
        LEFT JOIN inventory_units u ON u.id=ii.unit_id
        LEFT JOIN inventory_suppliers s ON s.id=ii.supplier_id
        LEFT JOIN (
            SELECT item_id, SUM(qty_in - qty_out) AS current_qty
            FROM stock_movements
            WHERE store_id=:store_id
            GROUP BY item_id
        ) bal ON bal.item_id=ii.id
        LEFT JOIN (
            SELECT
                item_id,
                SUM(qty_out) AS period_out,
                SUM(qty_out) / :days_for_avg AS avg_daily_out
            FROM stock_movements
            WHERE store_id=:store_for_cons
              AND DATE(movement_date) >= :lookback_date
              AND movement_type IN ('SALE','ISSUE','TRANSFER_OUT','WASTAGE','ADJUSTMENT_OUT')
            GROUP BY item_id
        ) cons ON cons.item_id=ii.id
        WHERE {$where}
        ORDER BY
            CASE WHEN COALESCE(bal.current_qty,0) <= ii.reorder_level THEN 0 ELSE 1 END,
            ii.item_name ASC
    ");

    $execParams = $params;
    $execParams[':days_for_avg'] = $daysLookback;
    $execParams[':store_for_cons'] = $storeId;

    $stmt->execute($execParams);
    $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);

    foreach ($rows as $row) {
        $currentQty = (float)$row['current_qty'];
        $reorderLevel = (float)$row['reorder_level'];
        $reorderQty = (float)$row['reorder_qty'];
        $avgDailyOut = (float)$row['avg_daily_out'];
        $resolvedCost = (float)$row['resolved_cost'];

        $isShort = $currentQty <= $reorderLevel;
        $critical = $currentQty <= max(0, $reorderLevel * 0.50);

        $targetQty = max($reorderQty, $reorderLevel + ($avgDailyOut * 7));
        if ($targetQty <= 0) $targetQty = max(1, $reorderLevel);

        $suggestedQty = max(0, $targetQty - $currentQty);

        if ($onlyShort && !$isShort) continue;

        $row['is_short'] = $isShort;
        $row['critical'] = $critical;
        $row['suggested_qty'] = $suggestedQty;
        $row['estimated_cost'] = $suggestedQty * $resolvedCost;
        $row['days_cover'] = $avgDailyOut > 0 ? ($currentQty / $avgDailyOut) : null;

        $suggestions[] = $row;

        if ($isShort) $summary['short_items']++;
        if ($critical) $summary['critical_items']++;
        $summary['suggested_qty'] += $suggestedQty;
        $summary['estimated_cost'] += $row['estimated_cost'];
    }

} catch (Throwable $e) {
    $errors[] = 'Could not load smart reorder suggestions: ' . $e->getMessage();
}

$flashes = sr_get_flash();

require_once __DIR__ . '/../../includes/header.php';
?>

<div class="hero-band no-print">
    <div class="row g-4 align-items-center">
        <div class="col-lg-8">
            <div class="page-eyebrow text-white-50"><i class="bi bi-magic"></i> Smart Purchasing</div>
            <div class="hero-title mt-2">Smart Reorder Suggestions</div>
            <div class="hero-subtitle mt-2">
                Auto-detect low stock, estimate reorder quantities, and create draft purchase orders.
            </div>
        </div>
        <div class="col-lg-4 text-lg-end">
            <a href="purchase_orders.php" class="btn btn-light me-2">
                <i class="bi bi-file-earmark-text me-2"></i>Purchase Orders
            </a>
            <a href="low_stock_report.php" class="btn btn-outline-light">
                <i class="bi bi-exclamation-triangle me-2"></i>Low Stock
            </a>
        </div>
    </div>
</div>

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

<?php if ($errors): ?>
    <div class="alert alert-danger no-print">
        <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="card panel-card mb-4 no-print">
    <div class="card-body">
        <form method="get" class="row g-3 align-items-end">
            <div class="col-md-2">
                <label class="form-label">Store</label>
                <select name="store_id" class="form-select">
                    <?php foreach ($stores as $store): ?>
                        <option value="<?php echo (int)$store['id']; ?>" <?php echo $storeId === (int)$store['id'] ? 'selected' : ''; ?>>
                            <?php echo h($store['location_name']); ?>
                        </option>
                    <?php endforeach; ?>
                </select>
            </div>

            <div class="col-md-2">
                <label class="form-label">Supplier</label>
                <select name="supplier_id" class="form-select">
                    <option value="0">All suppliers</option>
                    <?php foreach ($suppliers as $supplier): ?>
                        <option value="<?php echo (int)$supplier['id']; ?>" <?php echo $supplierId === (int)$supplier['id'] ? 'selected' : ''; ?>>
                            <?php echo h($supplier['supplier_name']); ?>
                        </option>
                    <?php endforeach; ?>
                </select>
            </div>

            <div class="col-md-2">
                <label class="form-label">Item Type</label>
                <select name="item_type" class="form-select">
                    <option value="">All</option>
                    <?php foreach (['stock','food','bar','curio','consumable','service','recipe','other'] as $type): ?>
                        <option value="<?php echo h($type); ?>" <?php echo $itemType === $type ? 'selected' : ''; ?>>
                            <?php echo h(ucwords($type)); ?>
                        </option>
                    <?php endforeach; ?>
                </select>
            </div>

            <div class="col-md-2">
                <label class="form-label">Usage Days</label>
                <input type="number" name="days" class="form-control" value="<?php echo (int)$daysLookback; ?>" min="7" max="365">
            </div>

            <div class="col-md-2">
                <label class="form-label">Search</label>
                <input type="text" name="q" class="form-control" value="<?php echo h($search); ?>">
            </div>

            <div class="col-md-1">
                <label class="form-label">Short</label>
                <select name="only_short" class="form-select">
                    <option value="1" <?php echo $onlyShort === 1 ? 'selected' : ''; ?>>Yes</option>
                    <option value="0" <?php echo $onlyShort === 0 ? 'selected' : ''; ?>>All</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="row g-4 mb-4">
    <div class="col-md-6 col-xl-3">
        <div class="metric-card">
            <div class="metric-icon bg-danger-subtle text-danger"><i class="bi bi-exclamation-triangle"></i></div>
            <div><div class="metric-label">Short Items</div><div class="metric-value"><?php echo (int)$summary['short_items']; ?></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-fire"></i></div>
            <div><div class="metric-label">Critical Items</div><div class="metric-value"><?php echo (int)$summary['critical_items']; ?></div></div>
        </div>
    </div>
    <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">Suggested Qty</div><div class="metric-value small-value"><?php echo qty_fmt($summary['suggested_qty']); ?></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-cash-stack"></i></div>
            <div><div class="metric-label">Estimated Cost</div><div class="metric-value small-value"><?php echo money_fmt($summary['estimated_cost']); ?></div></div>
        </div>
    </div>
</div>

<form method="post" id="createPoForm">
    <?php if (function_exists('csrf_field')) echo csrf_field(); ?>
    <input type="hidden" name="action" value="create_po">
    <input type="hidden" name="store_id" value="<?php echo (int)$storeId; ?>">

    <div class="card panel-card">
        <div class="card-header d-flex justify-content-between align-items-center">
            <div>
                <h5 class="mb-0">Suggested Reorder List</h5>
                <div class="small text-muted">
                    Tick items and create a draft purchase order. For best results, filter by one supplier first.
                </div>
            </div>
            <div class="d-flex gap-2 align-items-center no-print">
                <select name="supplier_id" class="form-select form-select-sm" required style="min-width:220px">
                    <option value="">Create PO for supplier...</option>
                    <?php foreach ($suppliers as $supplier): ?>
                        <option value="<?php echo (int)$supplier['id']; ?>" <?php echo $supplierId === (int)$supplier['id'] ? 'selected' : ''; ?>>
                            <?php echo h($supplier['supplier_name']); ?>
                        </option>
                    <?php endforeach; ?>
                </select>
                <button class="btn btn-success btn-sm" onclick="return confirm('Create draft purchase order for selected items?');">
                    <i class="bi bi-file-earmark-plus me-1"></i>Create Draft PO
                </button>
            </div>
        </div>

        <div class="card-body p-0">
            <div class="table-responsive reorder-table-wrap">
                <table class="table table-modern align-middle mb-0">
                    <thead>
                    <tr>
                        <th class="no-print"><input type="checkbox" id="checkAll"></th>
                        <th>Item</th>
                        <th>Supplier</th>
                        <th>Type</th>
                        <th class="text-end">Current</th>
                        <th class="text-end">Reorder Level</th>
                        <th class="text-end">Avg Daily Out</th>
                        <th class="text-end">Days Cover</th>
                        <th class="text-end">Suggested Qty</th>
                        <th class="text-end">Unit Cost</th>
                        <th class="text-end">Est. Cost</th>
                        <th>Status</th>
                    </tr>
                    </thead>
                    <tbody>
                    <?php if (!$suggestions): ?>
                        <tr><td colspan="12" class="text-center text-muted py-4">No reorder suggestions found.</td></tr>
                    <?php else: foreach ($suggestions as $s): ?>
                        <tr class="<?php echo $s['critical'] ? 'table-danger' : ($s['is_short'] ? 'table-warning' : ''); ?>">
                            <td class="no-print">
                                <input type="checkbox" name="selected[<?php echo (int)$s['id']; ?>]" value="1" class="row-check" <?php echo $s['is_short'] ? 'checked' : ''; ?>>
                            </td>
                            <td>
                                <strong><?php echo h($s['item_name']); ?></strong>
                                <div class="small text-muted"><?php echo h($s['item_code'] ?? ''); ?></div>
                            </td>
                            <td><?php echo h($s['supplier_name'] ?: 'No supplier'); ?></td>
                            <td><span class="badge text-bg-light border"><?php echo h(ucwords($s['item_type'])); ?></span></td>
                            <td class="text-end"><?php echo qty_fmt($s['current_qty']); ?> <?php echo h($s['unit_code'] ?? ''); ?></td>
                            <td class="text-end"><?php echo qty_fmt($s['reorder_level']); ?></td>
                            <td class="text-end"><?php echo qty_fmt($s['avg_daily_out']); ?></td>
                            <td class="text-end">
                                <?php echo $s['days_cover'] === null ? '—' : number_format((float)$s['days_cover'], 1); ?>
                            </td>
                            <td class="text-end no-print">
                                <input type="number" step="0.0001" min="0" name="qty[<?php echo (int)$s['id']; ?>]" class="form-control form-control-sm text-end qty-input" value="<?php echo h(number_format((float)$s['suggested_qty'], 4, '.', '')); ?>">
                            </td>
                            <td class="text-end no-print">
                                <input type="number" step="0.0001" min="0" name="cost[<?php echo (int)$s['id']; ?>]" class="form-control form-control-sm text-end cost-input" value="<?php echo h(number_format((float)$s['resolved_cost'], 4, '.', '')); ?>">
                            </td>
                            <td class="text-end fw-bold"><?php echo money_fmt($s['estimated_cost']); ?></td>
                            <td>
                                <?php if ($s['critical']): ?>
                                    <span class="badge text-bg-danger">Critical</span>
                                <?php elseif ($s['is_short']): ?>
                                    <span class="badge text-bg-warning">Reorder</span>
                                <?php else: ?>
                                    <span class="badge text-bg-success">OK</span>
                                <?php endif; ?>
                            </td>
                        </tr>
                    <?php endforeach; endif; ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>
</form>

<style>
/* Ultra compact top section + tighter working area */
.hero-band{
    padding:10px 14px!important;
    margin-bottom:8px!important;
    border-radius:16px!important;
}
.hero-band .row{
    --bs-gutter-x:.75rem!important;
    --bs-gutter-y:.5rem!important;
}
.hero-title{
    font-size:1.25rem!important;
    line-height:1.1!important;
    margin-top:2px!important;
}
.hero-subtitle{
    font-size:.78rem!important;
    line-height:1.2!important;
    margin-top:2px!important;
    opacity:.9;
}
.page-eyebrow{
    font-size:.68rem!important;
    letter-spacing:.06em!important;
}
.hero-band .btn{
    padding:5px 9px!important;
    font-size:.78rem!important;
    border-radius:8px!important;
}

/* Compact cards, filters and metrics */
.panel-card{
    border-radius:14px!important;
}
.panel-card .card-header{
    padding:8px 10px!important;
}
.panel-card .card-header h5{
    font-size:1rem!important;
    line-height:1.15!important;
}
.panel-card .card-body{
    padding:8px 10px!important;
}
.card.panel-card.mb-4{
    margin-bottom:8px!important;
}
.form-label{
    font-size:.7rem!important;
    margin-bottom:1px!important;
    font-weight:600!important;
}
.form-control,
.form-select{
    height:30px!important;
    min-height:30px!important;
    font-size:.8rem!important;
    padding:3px 6px!important;
    border-radius:8px!important;
}
.form-select-sm,
.form-control-sm{
    height:28px!important;
    min-height:28px!important;
    font-size:.78rem!important;
    padding:2px 6px!important;
}
.row.g-3{
    --bs-gutter-x:.5rem!important;
    --bs-gutter-y:.4rem!important;
}
.row.g-4{
    --bs-gutter-x:.75rem!important;
    --bs-gutter-y:.75rem!important;
}
.row.g-4.mb-4{
    margin-bottom:8px!important;
}
.metric-card{
    padding:8px 10px!important;
    gap:6px!important;
    min-height:52px!important;
    border-radius:14px!important;
}
.metric-icon{
    width:30px!important;
    height:30px!important;
    border-radius:8px!important;
    font-size:12px!important;
}
.metric-label{
    font-size:.68rem!important;
    margin-bottom:0!important;
}
.metric-value{
    font-size:.95rem!important;
    line-height:1.05!important;
}
.small-value{
    font-size:.9rem!important;
    letter-spacing:0!important;
}
.alert{
    padding:7px 10px!important;
    margin-bottom:8px!important;
    font-size:.82rem!important;
    border-radius:10px!important;
}

/* Reorder table closer to top with frozen header */
.reorder-table-wrap{
    max-height:calc(100vh - 245px);
    overflow:auto;
}
.reorder-table-wrap thead th{
    position:sticky;
    top:0;
    z-index:10;
    background:linear-gradient(180deg,#ffffff,#f8fafc)!important;
    border-bottom:2px solid #e5e7eb!important;
    white-space:nowrap;
}
.table-modern th,
.table-modern td{
    padding:6px 8px!important;
    font-size:.82rem!important;
    vertical-align:middle!important;
}
.table-modern .small{
    font-size:.7rem!important;
}
.badge{
    font-size:.68rem!important;
    padding:.28em .48em!important;
}
.qty-input,
.cost-input{
    min-width:95px;
}
#createPoForm .card-header{
    gap:8px!important;
}
#createPoForm .card-header .small{
    font-size:.72rem!important;
}
#createPoForm .card-header .form-select{
    min-width:190px!important;
}
#createPoForm .btn-sm{
    padding:4px 8px!important;
    font-size:.76rem!important;
    border-radius:8px!important;
}

@media (max-width: 991.98px){
    .hero-band .col-lg-4{text-align:left!important}
    .hero-subtitle{display:none!important}
    #createPoForm .card-header{align-items:flex-start!important;flex-direction:column!important}
    #createPoForm .card-header .d-flex{width:100%;flex-wrap:wrap!important}
    #createPoForm .card-header .form-select{min-width:100%!important}
}
@media print{
    .no-print,.sidebar,.enterprise-sidebar,.app-sidebar,.topbar,.navbar,.header,.footer{display:none!important}
    body{background:#fff!important}
    .panel-card,.card,.metric-card{box-shadow:none!important}
    .reorder-table-wrap{max-height:none!important;overflow:visible!important}
    .reorder-table-wrap thead th{position:static!important;background:#fff!important}
}
</style>

<script>
document.addEventListener('DOMContentLoaded', function(){
    const checkAll = document.getElementById('checkAll');
    if (checkAll) {
        checkAll.addEventListener('change', function(){
            document.querySelectorAll('.row-check').forEach(cb => cb.checked = checkAll.checked);
        });
    }
});
</script>

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