<?php
include '../../includes/header.php';


$auth = new Auth($conn);
if ($_SESSION['role'] === 'warehouse' || $_SESSION['role'] === 'admin') {

} else {
    $auth->isBranchManager($_SESSION['user_id']);
}


$database = new Database();
$conn = $database->getConnection();


require_once __DIR__ . '/../../classes/Sales.php';
require_once __DIR__ . '/../../classes/Branch.php';

$sales = new Sales($conn);
$branch = new Branch($conn);


if ($_SESSION['role'] === 'warehouse' || $_SESSION['role'] === 'admin') {
    $selectedBranchId = isset($_GET['branch_id']) ? (int)$_GET['branch_id'] : null;
    if (!$selectedBranchId) {

        $branchesResult = $branch->getAllBranches();
        $branches = $branchesResult->fetchAll(PDO::FETCH_ASSOC);
        $selectedBranchId = $branches[0]['branch_id'] ?? null;
    }
} else {
    $selectedBranchId = $auth->getUserBranch($_SESSION['user_id']);
}


$lowStockStats = $sales->getLowStockItems($selectedBranchId);
?>

<style>
    .low-stock-item {
        border-left: 4px solid #dc3545;
        background-color: #fff5f5;
    }

    .stock-count {
        font-weight: bold;
        color: #dc3545;
    }

    .threshold-info {
        background-color: #f8f9fa;
        padding: 10px;
        border-radius: 5px;
        margin-bottom: 20px;
    }

    .item-value {
        color: #28a745;
        font-weight: bold;
    }
</style>

<div class="container mt-4">
    <div class="row mb-4">
        <div class="col-12">
            <nav aria-label="breadcrumb">
                <ol class="breadcrumb">
                    <li class="breadcrumb-item"><a href="../dashboard/<?php echo $_SESSION['role']; ?>.php">Dashboard</a></li>
                    <li class="breadcrumb-item active">Low Stock Items<?php
                        if (($_SESSION['role'] === 'warehouse' || $_SESSION['role'] === 'admin') && $selectedBranchId) {
                            $branchesResult = $branch->getAllBranches();
                            $allBranches = $branchesResult->fetchAll(PDO::FETCH_ASSOC);
                            $selectedBranch = array_filter($allBranches, function($b) use ($selectedBranchId) {
                                return $b['branch_id'] == $selectedBranchId;
                            });
                            $selectedBranch = reset($selectedBranch);
                            echo ' - ' . htmlspecialchars($selectedBranch['branch_name']);
                        }
                    ?></li>
                </ol>
            </nav>
        </div>
    </div>

    <div class="row mb-4">
        <div class="col-12">
            <h2><i class="fas fa-exclamation-triangle text-warning"></i> Low Stock Alert</h2>
            <p class="text-muted">Items that need immediate restocking attention</p>
        </div>
    </div>

    <?php if ($_SESSION['role'] === 'warehouse' || $_SESSION['role'] === 'admin'): ?>
    <div class="row mb-4">
        <div class="col-12">
            <div class="card">
                <div class="card-body">
                    <form method="GET" action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']); ?>" class="row g-3">
                        <div class="col-md-6">
                            <label for="branch_id" class="form-label">Select Branch</label>
                            <select name="branch_id" id="branch_id" class="form-select" onchange="this.form.submit()">
                                <?php
                                $branchesResult = $branch->getAllBranches();
                                $allBranches = $branchesResult->fetchAll(PDO::FETCH_ASSOC);
                                foreach ($allBranches as $b): ?>
                                    <option value="<?php echo $b['branch_id']; ?>" <?php echo ($selectedBranchId == $b['branch_id']) ? 'selected' : ''; ?>>
                                        <?php echo htmlspecialchars($b['branch_name']); ?>
                                    </option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>
    <?php endif; ?>

    <div class="threshold-info">
        <div class="row">
            <div class="col-md-6">
                <strong>Low Stock Threshold:</strong> <?php echo $lowStockStats['low_stock_threshold']; ?> units
            </div>
            <div class="col-md-6 text-end">
                <strong>Total Items Needing Restock:</strong> <?php echo $lowStockStats['total_low_stock_items']; ?>
                <br>
                <small class="text-muted">Total Value: MWK <?php echo number_format($lowStockStats['total_low_stock_value'], 2); ?></small>
            </div>
        </div>
    </div>

    <?php if (empty($lowStockStats['low_stock_items'])): ?>
        <div class="card">
            <div class="card-body text-center">
                <i class="fas fa-check-circle fa-4x text-success mb-3"></i>
                <h4 class="text-success">All Items Well Stocked!</h4>
                <p class="text-muted">No items are currently below the low stock threshold.</p>
                <a href="../dashboard/branch.php" class="btn btn-primary">
                    <i class="fas fa-arrow-left"></i> Back to Dashboard
                </a>
            </div>
        </div>
    <?php else: ?>
        <div class="row">
            <?php foreach ($lowStockStats['low_stock_items'] as $item): ?>
                <div class="col-md-6 col-lg-4 mb-4">
                    <div class="card low-stock-item">
                        <div class="card-body">
                            <h5 class="card-title"><?php echo htmlspecialchars($item['item_name']); ?></h5><p><strong>Details:</strong> <?php echo htmlspecialchars($item['item_details'] ?? 'N/A'); ?></p>
                            <div class="row">
                                <div class="col-6">
                                    <small class="text-muted">Current Stock</small>
                                    <div class="stock-count"><?php echo $item['item_count']; ?> units</div>
                                </div>
                                <div class="col-6">
                                    <small class="text-muted">Avg Price</small>
                                    <div class="item-value">MWK <?php echo number_format($item['avg_price'], 2); ?></div>
                                </div>
                            </div>
                            <hr>
                            <div class="row">
                                <div class="col-12">
                                    <small class="text-muted">Total Value</small>
                                    <div class="item-value">MWK <?php echo number_format($item['total_value'], 2); ?></div>
                                </div>
                            </div>
                            <div class="mt-3">
                                <span class="badge bg-danger">
                                    <?php echo $lowStockStats['low_stock_threshold'] - $item['item_count']; ?> units needed
                                </span>
                            </div>
                        </div>
                    </div>
                </div>
            <?php endforeach; ?>
        </div>

        <div class="row mt-4">
            <div class="col-12 text-center">
                <a href="../dashboard/<?php echo $_SESSION['role']; ?>.php" class="btn btn-secondary">
                    <i class="fas fa-arrow-left"></i> Back to Dashboard
                </a>
                <button class="btn btn-primary" onclick="window.print()">
                    <i class="fas fa-print"></i> Print Report
                </button>
            </div>
        </div>
    <?php endif; ?>
</div>

<style>
@media print {
    .breadcrumb, .btn, nav {
        display: none !important;
    }

    .container {
        margin: 0;
        padding: 0;
    }

    .card {
        border: 1px solid #ddd;
        margin-bottom: 10px;
    }

    .low-stock-item {
        border-left: 4px solid #dc3545;
        background-color: white;
    }
}
</style>

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