<?php
require_once __DIR__ . '/../config/auth.php';
require_once __DIR__ . '/../includes/functions.php';

// Allow both stock_view OR product_management
requireLogin();
$has_access = hasPermission('stock_view') || hasPermission('product_management');
if (!$has_access) {
    $_SESSION['error'] = 'You do not have permission to access this page.';
    header('Location: ' . getRedirectUrl());
    exit;
}

$pdo = getDB();

$where = "p.current_stock <= p.low_stock_qty AND p.status = 1";
$params = [];

if (!empty($_GET['product_type'])) {
    $where .= " AND p.product_type = ?";
    $params[] = $_GET['product_type'];
}

$stmt = $pdo->prepare("
    SELECT p.*, c.category_name, b.brand_name
    FROM products p
    LEFT JOIN categories c ON p.category_id = c.id
    LEFT JOIN brands b ON p.brand_id = b.id
    WHERE $where
    ORDER BY (p.low_stock_qty - p.current_stock) DESC
");
$stmt->execute($params);
$low_stock_products = $stmt->fetchAll();

include __DIR__ . '/../includes/header.php';
include __DIR__ . '/../includes/sidebar.php';
?>
<div class="content-wrapper">
    <div class="container-fluid">
        <div class="d-flex justify-content-between align-items-center mb-3">
            <h4 class="page-title mb-0"><i class="fas fa-exclamation-triangle me-2"></i>Low Stock Products</h4>
            <div>
                <button class="btn btn-info" onclick="window.print()"><i class="fas fa-print me-1"></i>Print</button>
                <a href="products.php" class="btn btn-secondary"><i class="fas fa-arrow-left me-1"></i>All Products</a>
            </div>
        </div>

        <?php if (isset($_SESSION['success'])): ?><div class="alert alert-success alert-dismissible"><?= $_SESSION['success']; unset($_SESSION['success']); ?><button type="button" class="btn-close" data-bs-dismiss="alert"></button></div><?php endif; ?>
        <?php if (isset($_SESSION['error'])): ?><div class="alert alert-danger alert-dismissible"><?= $_SESSION['error']; unset($_SESSION['error']); ?><button type="button" class="btn-close" data-bs-dismiss="alert"></button></div><?php endif; ?>

        <!-- Filter -->
        <div class="card mb-3">
            <div class="card-body">
                <form method="GET" class="row g-3">
                    <div class="col-md-3">
                        <label class="form-label">Product Type</label>
                        <select name="product_type" class="form-select">
                            <option value="">All Types</option>
                            <option value="Phone" <?= (isset($_GET['product_type']) && $_GET['product_type'] == 'Phone') ? 'selected' : '' ?>>Phone</option>
                            <option value="Accessory" <?= (isset($_GET['product_type']) && $_GET['product_type'] == 'Accessory') ? 'selected' : '' ?>>Accessory</option>
                            <option value="Spare Part" <?= (isset($_GET['product_type']) && $_GET['product_type'] == 'Spare Part') ? 'selected' : '' ?>>Spare Part</option>
                        </select>
                    </div>
                    <div class="col-md-3 d-flex align-items-end">
                        <button type="submit" class="btn btn-primary me-2"><i class="fas fa-filter me-1"></i>Filter</button>
                        <a href="low_stock.php" class="btn btn-secondary"><i class="fas fa-undo me-1"></i>Reset</a>
                    </div>
                </form>
            </div>
        </div>

        <div class="card">
            <div class="card-body">
                <div class="table-responsive">
                    <table class="table table-hover datatable" id="lowStockTable">
                        <thead>
                            <tr>
                                <th>Product Code</th>
                                <th>Product Name</th>
                                <th>Category</th>
                                <th>Brand</th>
                                <th>Type</th>
                                <th>Current Stock</th>
                                <th>Low Stock Qty</th>
                                <th>Status</th>
                                <th>Action</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php if (!empty($low_stock_products)): ?>
                            <?php foreach ($low_stock_products as $p): ?>
                            <tr>
                                <td><?= htmlspecialchars($p['product_code'] ?? '-') ?></td>
                                <td><strong><?= htmlspecialchars($p['product_name']) ?></strong><?= $p['model'] ? '<br><small class="text-muted">' . htmlspecialchars($p['model']) . '</small>' : '' ?></td>
                                <td><?= htmlspecialchars($p['category_name'] ?? '-') ?></td>
                                <td><?= htmlspecialchars($p['brand_name'] ?? '-') ?></td>
                                <td><span class="badge bg-<?= $p['product_type'] == 'Phone' ? 'primary' : ($p['product_type'] == 'Accessory' ? 'success' : 'warning') ?>"><?= htmlspecialchars($p['product_type']) ?></span></td>
                                <td><span class="badge bg-<?= $p['current_stock'] <= 0 ? 'danger' : 'warning' ?>"><?= (int)$p['current_stock'] ?></span></td>
                                <td><?= (int)$p['low_stock_qty'] ?></td>
                                <td><?= getStockBadge($p['current_stock'], $p['low_stock_qty']) ?></td>
                                <td>
                                    <a href="view_product.php?id=<?= $p['id'] ?>" class="btn btn-sm btn-info"><i class="fas fa-eye"></i></a>
                                    <a href="add_product.php?id=<?= $p['id'] ?>" class="btn btn-sm btn-primary"><i class="fas fa-edit"></i></a>
                                    <span class="text-muted small d-block mt-1">Purchase</span>
                                </td>
                            </tr>
                            <?php endforeach; ?>
                            <?php endif; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>
</div>

<style media="print">
    .sidebar, .navbar, .footer, .btn, .card-header, form, .datatable_filter, .datatable_length, .datatable_paginate { display: none; }
    .content-wrapper { margin-left: 0 !important; }
    .card { border: 1px solid #ddd; }
    .table { font-size: 12px; }
</style>

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