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

$pageTitle = 'Low Stock Report';

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); }
}

$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_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)
    ) 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");
} catch (Throwable $e) {
    $errors[] = 'Could not prepare low stock report tables: ' . $e->getMessage();
}

$stores = [];
$categories = [];

try {
    $stores = $pdo->query("SELECT * FROM store_locations WHERE is_active=1 ORDER BY location_name ASC")->fetchAll(PDO::FETCH_ASSOC);
    $categories = $pdo->query("SELECT * FROM inventory_item_categories WHERE is_active=1 ORDER BY category_name ASC")->fetchAll(PDO::FETCH_ASSOC);
} catch (Throwable $e) {
    $errors[] = 'Could not load report filters: ' . $e->getMessage();
}

$storeId = (int)($_GET['store_id'] ?? 0);
$categoryId = (int)($_GET['category_id'] ?? 0);
$alertType = trim((string)($_GET['alert_type'] ?? 'all'));
$search = trim((string)($_GET['q'] ?? ''));
$includeZeroReorder = (int)($_GET['include_zero_reorder'] ?? 0);

$where = "ii.is_active = 1 AND ii.is_stock_item = 1";
$params = [];

if ($storeId > 0) {
    $where .= " AND sl.id = :store_id";
    $params[':store_id'] = $storeId;
}
if ($categoryId > 0) {
    $where .= " AND ii.category_id = :category_id";
    $params[':category_id'] = $categoryId;
}
if ($search !== '') {
    $where .= " AND (ii.item_name LIKE :q OR ii.item_code LIKE :q OR ii.barcode LIKE :q OR c.category_name LIKE :q OR sl.location_name LIKE :q)";
    $params[':q'] = '%' . $search . '%';
}
if ($includeZeroReorder !== 1) {
    $where .= " AND ii.reorder_level > 0";
}

$having = "HAVING 1=1";
if ($alertType === 'negative') {
    $having .= " AND balance_qty < 0";
} elseif ($alertType === 'zero') {
    $having .= " AND balance_qty = 0";
} elseif ($alertType === 'low') {
    $having .= " AND balance_qty > 0 AND balance_qty <= reorder_level";
} else {
    $having .= " AND balance_qty <= reorder_level";
}

$rows = [];
$summary = [
    'alerts' => 0,
    'negative' => 0,
    'zero' => 0,
    'low' => 0,
    'suggested_qty' => 0,
    'suggested_value' => 0,
    'current_value' => 0,
];

try {
    $stmt = $pdo->prepare("
        SELECT
            ii.id AS item_id,
            ii.item_code,
            ii.item_name,
            ii.barcode,
            ii.item_type,
            ii.avg_cost,
            ii.cost_price,
            ii.selling_price,
            ii.reorder_level,
            ii.reorder_qty,
            ii.is_pos_item,
            c.category_name,
            c.category_type,
            u.unit_code,
            sl.id AS store_id,
            sl.location_name,
            sl.location_type,
            COALESCE(SUM(sm.qty_in - sm.qty_out),0) AS balance_qty,
            COALESCE(SUM((sm.qty_in - sm.qty_out) * sm.unit_cost),0) AS movement_value,
            MAX(sm.movement_date) AS last_movement_date
        FROM inventory_items ii
        CROSS JOIN store_locations sl
        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 stock_movements sm ON sm.item_id = ii.id AND sm.store_id = sl.id
        WHERE $where
          AND sl.is_active = 1
        GROUP BY ii.id, sl.id
        $having
        ORDER BY
            CASE WHEN balance_qty < 0 THEN 0 WHEN balance_qty = 0 THEN 1 ELSE 2 END ASC,
            (balance_qty - reorder_level) ASC,
            c.category_name ASC,
            ii.item_name ASC,
            sl.location_name ASC
        LIMIT 2000
    ");
    $stmt->execute($params);
    $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);

    foreach ($rows as $row) {
        $qty = (float)$row['balance_qty'];
        $reorderLevel = (float)$row['reorder_level'];
        $reorderQty = (float)$row['reorder_qty'];
        $avgCost = (float)($row['avg_cost'] ?: $row['cost_price']);
        $suggested = $reorderQty > 0 ? $reorderQty : max(0, $reorderLevel - $qty);

        $summary['alerts']++;
        if ($qty < 0) $summary['negative']++;
        elseif (abs($qty) < 0.0001) $summary['zero']++;
        else $summary['low']++;

        $summary['suggested_qty'] += $suggested;
        $summary['suggested_value'] += ($suggested * $avgCost);
        $summary['current_value'] += ($qty * $avgCost);
    }
} catch (Throwable $e) {
    $errors[] = 'Could not load low stock report: ' . $e->getMessage();
}

$categoryTotals = [];
$storeTotals = [];

foreach ($rows as $row) {
    $cat = $row['category_name'] ?: 'Uncategorised';
    $store = $row['location_name'] ?: 'Store';
    $qty = (float)$row['balance_qty'];
    $avgCost = (float)($row['avg_cost'] ?: $row['cost_price']);
    $reorderLevel = (float)$row['reorder_level'];
    $reorderQty = (float)$row['reorder_qty'];
    $suggested = $reorderQty > 0 ? $reorderQty : max(0, $reorderLevel - $qty);

    if (!isset($categoryTotals[$cat])) $categoryTotals[$cat] = ['alerts'=>0,'suggested_qty'=>0,'suggested_value'=>0];
    $categoryTotals[$cat]['alerts']++;
    $categoryTotals[$cat]['suggested_qty'] += $suggested;
    $categoryTotals[$cat]['suggested_value'] += $suggested * $avgCost;

    if (!isset($storeTotals[$store])) $storeTotals[$store] = ['alerts'=>0,'suggested_qty'=>0,'suggested_value'=>0];
    $storeTotals[$store]['alerts']++;
    $storeTotals[$store]['suggested_qty'] += $suggested;
    $storeTotals[$store]['suggested_value'] += $suggested * $avgCost;
}

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-exclamation-triangle"></i> Inventory Reports</div>
            <div class="hero-title mt-2">Low Stock Report</div>
            <div class="hero-subtitle mt-2">
                Reorder alerts, negative stock, zero stock and suggested replenishment quantities.
            </div>
        </div>
        <div class="col-lg-4 text-lg-end">
            <button onclick="window.print()" class="btn btn-light me-2"><i class="bi bi-printer me-2"></i>Print</button>
            <a href="inventory_dashboard.php" class="btn btn-outline-light"><i class="bi bi-speedometer2 me-2"></i>Dashboard</a>
        </div>
    </div>
</div>

<?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="print-title">
    <h3 class="mb-1">Low Stock Report</h3>
    <div class="text-muted">Generated <?php echo h(date('d M Y H:i')); ?></div>
</div>

<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">
                    <option value="0">All stores</option>
                    <?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">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 $categoryId === (int)$cat['id'] ? 'selected' : ''; ?>>
                            <?php echo h($cat['category_name']); ?>
                        </option>
                    <?php endforeach; ?>
                </select>
            </div>

            <div class="col-md-2">
                <label class="form-label">Alert Type</label>
                <select name="alert_type" class="form-select">
                    <option value="all" <?php echo $alertType === 'all' ? 'selected' : ''; ?>>All Alerts</option>
                    <option value="negative" <?php echo $alertType === 'negative' ? 'selected' : ''; ?>>Negative Stock</option>
                    <option value="zero" <?php echo $alertType === 'zero' ? 'selected' : ''; ?>>Zero Stock</option>
                    <option value="low" <?php echo $alertType === 'low' ? 'selected' : ''; ?>>Low Stock Only</option>
                </select>
            </div>

            <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/store/category">
            </div>

            <div class="col-md-2">
                <label class="form-label">Reorder Level</label>
                <select name="include_zero_reorder" class="form-select">
                    <option value="0" <?php echo $includeZeroReorder === 0 ? 'selected' : ''; ?>>Only configured</option>
                    <option value="1" <?php echo $includeZeroReorder === 1 ? 'selected' : ''; ?>>Include zero reorder</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">Total Alerts</div><div class="metric-value"><?php echo (int)$summary['alerts']; ?></div></div>
        </div>
    </div>
    <div class="col-md-6 col-xl-3">
        <div class="metric-card">
            <div class="metric-icon bg-dark-subtle text-dark"><i class="bi bi-dash-circle"></i></div>
            <div><div class="metric-label">Negative Stock</div><div class="metric-value"><?php echo (int)$summary['negative']; ?></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-cart-plus"></i></div>
            <div><div class="metric-label">Suggested Qty</div><div class="metric-value small-value"><?php echo money_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-info-subtle text-info"><i class="bi bi-cash-stack"></i></div>
            <div><div class="metric-label">Suggested Value</div><div class="metric-value small-value"><?php echo money_fmt($summary['suggested_value']); ?></div></div>
        </div>
    </div>
</div>

<div class="row g-4 mb-4 no-print">
    <div class="col-xl-6">
        <div class="card panel-card h-100">
            <div class="card-header"><h5 class="mb-0">Alerts by Category</h5></div>
            <div class="card-body p-0">
                <table class="table table-modern mb-0">
                    <thead><tr><th>Category</th><th class="text-end">Alerts</th><th class="text-end">Suggested Qty</th><th class="text-end">Suggested Value</th></tr></thead>
                    <tbody>
                    <?php if (!$categoryTotals): ?>
                        <tr><td colspan="4" class="text-center text-muted py-4">No category alerts.</td></tr>
                    <?php else: ?>
                        <?php foreach ($categoryTotals as $catName => $tot): ?>
                            <tr>
                                <td><strong><?php echo h($catName); ?></strong></td>
                                <td class="text-end"><?php echo (int)$tot['alerts']; ?></td>
                                <td class="text-end"><?php echo money_fmt($tot['suggested_qty']); ?></td>
                                <td class="text-end fw-bold"><?php echo money_fmt($tot['suggested_value']); ?></td>
                            </tr>
                        <?php endforeach; ?>
                    <?php endif; ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>

    <div class="col-xl-6">
        <div class="card panel-card h-100">
            <div class="card-header"><h5 class="mb-0">Alerts by Store</h5></div>
            <div class="card-body p-0">
                <table class="table table-modern mb-0">
                    <thead><tr><th>Store</th><th class="text-end">Alerts</th><th class="text-end">Suggested Qty</th><th class="text-end">Suggested Value</th></tr></thead>
                    <tbody>
                    <?php if (!$storeTotals): ?>
                        <tr><td colspan="4" class="text-center text-muted py-4">No store alerts.</td></tr>
                    <?php else: ?>
                        <?php foreach ($storeTotals as $storeName => $tot): ?>
                            <tr>
                                <td><strong><?php echo h($storeName); ?></strong></td>
                                <td class="text-end"><?php echo (int)$tot['alerts']; ?></td>
                                <td class="text-end"><?php echo money_fmt($tot['suggested_qty']); ?></td>
                                <td class="text-end fw-bold"><?php echo money_fmt($tot['suggested_value']); ?></td>
                            </tr>
                        <?php endforeach; ?>
                    <?php endif; ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>
</div>

<div class="card panel-card">
    <div class="card-header d-flex justify-content-between align-items-center">
        <h5 class="mb-0">Low Stock Detail</h5>
        <span class="text-muted small">Showing up to 2,000 rows</span>
    </div>
    <div class="card-body p-0">
        <div class="table-responsive">
            <table class="table table-modern align-middle mb-0 low-stock-table">
                <thead>
                <tr>
                    <th>Priority</th>
                    <th>Item</th>
                    <th>Category</th>
                    <th>Store</th>
                    <th class="text-end">Balance</th>
                    <th class="text-end">Reorder Level</th>
                    <th class="text-end">Reorder Qty</th>
                    <th class="text-end">Suggested Order</th>
                    <th class="text-end">Avg Cost</th>
                    <th class="text-end">Suggested Value</th>
                    <th>Last Movement</th>
                </tr>
                </thead>
                <tbody>
                <?php if (!$rows): ?>
                    <tr><td colspan="11" class="text-center text-muted py-4">No low stock alerts found.</td></tr>
                <?php else: ?>
                    <?php foreach ($rows as $row): ?>
                        <?php
                            $qty = (float)$row['balance_qty'];
                            $reorderLevel = (float)$row['reorder_level'];
                            $reorderQty = (float)$row['reorder_qty'];
                            $avgCost = (float)($row['avg_cost'] ?: $row['cost_price']);
                            $suggested = $reorderQty > 0 ? $reorderQty : max(0, $reorderLevel - $qty);
                            $suggestedValue = $suggested * $avgCost;

                            if ($qty < 0) {
                                $priority = 'Critical';
                                $badge = 'text-bg-danger';
                                $rowClass = 'table-danger';
                            } elseif (abs($qty) < 0.0001) {
                                $priority = 'Out';
                                $badge = 'text-bg-dark';
                                $rowClass = 'table-warning';
                            } else {
                                $priority = 'Low';
                                $badge = 'text-bg-warning';
                                $rowClass = '';
                            }
                        ?>
                        <tr class="<?php echo h($rowClass); ?>">
                            <td><span class="badge <?php echo h($badge); ?>"><?php echo h($priority); ?></span></td>
                            <td>
                                <strong><?php echo h($row['item_name']); ?></strong>
                                <div class="small text-muted">
                                    Code: <?php echo h($row['item_code'] ?: '—'); ?>
                                    <?php if ((int)$row['is_pos_item'] === 1): ?> • POS<?php endif; ?>
                                </div>
                            </td>
                            <td><?php echo h($row['category_name'] ?: 'Uncategorised'); ?></td>
                            <td><?php echo h($row['location_name']); ?></td>
                            <td class="text-end fw-bold"><?php echo money_fmt($qty); ?> <?php echo h($row['unit_code'] ?: ''); ?></td>
                            <td class="text-end"><?php echo money_fmt($reorderLevel); ?></td>
                            <td class="text-end"><?php echo money_fmt($reorderQty); ?></td>
                            <td class="text-end fw-bold"><?php echo money_fmt($suggested); ?></td>
                            <td class="text-end"><?php echo money_fmt($avgCost); ?></td>
                            <td class="text-end fw-bold"><?php echo money_fmt($suggestedValue); ?></td>
                            <td><?php echo $row['last_movement_date'] ? h(date('Y-m-d', strtotime($row['last_movement_date']))) : '—'; ?></td>
                        </tr>
                    <?php endforeach; ?>
                <?php endif; ?>
                </tbody>
                <tfoot>
                <tr>
                    <th colspan="7" class="text-end">Totals</th>
                    <th class="text-end"><?php echo money_fmt($summary['suggested_qty']); ?></th>
                    <th></th>
                    <th class="text-end"><?php echo money_fmt($summary['suggested_value']); ?></th>
                    <th></th>
                </tr>
                </tfoot>
            </table>
        </div>
    </div>
</div>

<div class="alert alert-info mt-4 no-print">
    <strong>Tip:</strong> Reorder quantity is used where configured. If it is zero, the report suggests enough quantity to bring stock back to reorder level.
</div>

<style>
.small-value{font-size:1rem!important;letter-spacing:0!important}
.print-title{display:none}
.low-stock-table tfoot th{background:#0f172a!important;color:#fff!important}
@media print{
    .no-print,.sidebar,.enterprise-sidebar,.app-sidebar,.topbar,.navbar,.header,.footer{display:none!important}
    .print-title{display:block;margin-bottom:16px}
    .panel-card,.card{box-shadow:none!important;border:1px solid #ddd!important}
    body{background:#fff!important}
    .table{font-size:10.5px}
    .metric-card{box-shadow:none!important;border:1px solid #ddd!important}
}
</style>

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