<?php
ob_start();
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

session_start();
include('includes/db.php');
include('includes/header.php');

// ---------------- CSRF Token ----------------
if (empty($_SESSION['csrf_token'])) {
    $_SESSION['csrf_token'] = bin2hex(random_bytes(32));
}
$csrf = $_SESSION['csrf_token'];

// ---------------- ROLE CHECK ----------------
$user_role = $_SESSION['user_role'] ?? '';
if (!in_array($user_role, ['Admin','Super_admin','Pharmacist'])) {
    die("Access denied.");
}

// ---------------- FACILITY ----------------
$facilityId = (int)($_SESSION['facility_id'] ?? 0);
if ($facilityId <= 0) {
    die("Facility not assigned.");
}

// ---------------- Fetch Products ----------------
$stmt = $pdo->prepare("
    SELECT id, name, category_type, status
    FROM products
    WHERE category_type IN ('drug','consumable')
      AND facility_id = ?
    ORDER BY name ASC
");
$stmt->execute([$facilityId]);
$products = $stmt->fetchAll(PDO::FETCH_ASSOC);

// ---------------- Calculate Dashboard Metrics ----------------
$totalProducts = count($products);
$totalStockIn = $pdo->prepare("SELECT SUM(stock_in) FROM stock WHERE facility_id = ?");
$totalStockIn->execute([$facilityId]);
$totalStockIn = (int)$totalStockIn->fetchColumn();

$totalStockOut = $pdo->prepare("SELECT SUM(stock_out) FROM stock WHERE facility_id = ?");
$totalStockOut->execute([$facilityId]);
$totalStockOut = (int)$totalStockOut->fetchColumn();

$remainingStock = $totalStockIn - $totalStockOut;

// Low stock alerts
$lowStockProducts = [];
$expiredProducts = [];

foreach ($products as $p) {
    if ($p['status'] !== 'enabled') continue;

    $stmt = $pdo->prepare("
        SELECT stock_in, stock_out, expiration_date
        FROM stock
        WHERE product_id = ? AND status='enabled' AND facility_id=?
        ORDER BY created_at DESC
        LIMIT 1
    ");
    $stmt->execute([$p['id'], $facilityId]);
    $lastStock = $stmt->fetch(PDO::FETCH_ASSOC);
    if (!$lastStock) continue;

    $remaining = $lastStock['stock_in'] - $lastStock['stock_out'];

    if ($remaining <= 15) {
        $lowStockProducts[] = [
            'name' => $p['name'],
            'remaining' => $remaining
        ];
    }

    if (!empty($lastStock['expiration_date']) && strtotime($lastStock['expiration_date']) < time()) {
        $expiredProducts[] = [
            'name' => $p['name'],
            'expiry' => $lastStock['expiration_date']
        ];
    }
}
?>

<!-- HTML Dashboard -->
<nav class="header-navbar navbar navbar-with-menu navbar-fixed-top navbar-semi-dark navbar-shadow">
    <?php include('includes/navbar.php'); ?>
</nav>

<div class="main-menu menu-fixed menu-dark menu-accordion menu-shadow">
    <?php include('includes/sidebar.php'); ?>
</div>

<div class="app-content content container-fluid">
<div class="content-wrapper">

<!-- Dashboard Cards -->
<div class="row mb-3">
    <div class="col-md-3">
        <div class="card text-white bg-primary mb-3">
            <div class="card-body">
                <h5 class="card-title">Total Products</h5>
                <p class="card-text display-4"><?= $totalProducts ?></p>
            </div>
        </div>
    </div>
    <div class="col-md-3">
        <div class="card text-white bg-success mb-3">
            <div class="card-body">
                <h5 class="card-title">Remaining Stock</h5>
                <p class="card-text display-4"><?= $remainingStock ?></p>
            </div>
        </div>
    </div>
    <div class="col-md-3">
        <div class="card text-white bg-warning mb-3">
            <div class="card-body">
                <h5 class="card-title">Low Stock Items</h5>
                <p class="card-text display-4"><?= count($lowStockProducts) ?></p>
            </div>
        </div>
    </div>
    <div class="col-md-3">
        <div class="card text-white bg-danger mb-3">
            <div class="card-body">
                <h5 class="card-title">Expired Items</h5>
                <p class="card-text display-4"><?= count($expiredProducts) ?></p>
            </div>
        </div>
    </div>
</div>

<!-- Low Stock & Expired Products Table -->
<div class="row">
    <div class="col-md-6">
        <div class="card">
            <div class="card-header">Low Stock Products</div>
            <div class="card-body table-responsive">
                <table class="table table-striped">
                    <thead>
                        <tr>
                            <th>Product</th>
                            <th>Remaining</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($lowStockProducts as $p): ?>
                        <tr>
                            <td><?= htmlspecialchars($p['name']) ?></td>
                            <td><?= $p['remaining'] ?></td>
                        </tr>
                        <?php endforeach; ?>
                        <?php if (empty($lowStockProducts)): ?>
                        <tr><td colspan="2">No low stock items.</td></tr>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>
    <div class="col-md-6">
        <div class="card">
            <div class="card-header">Expired Products</div>
            <div class="card-body table-responsive">
                <table class="table table-striped">
                    <thead>
                        <tr>
                            <th>Product</th>
                            <th>Expiry Date</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($expiredProducts as $p): ?>
                        <tr>
                            <td><?= htmlspecialchars($p['name']) ?></td>
                            <td><?= $p['expiry'] ?></td>
                        </tr>
                        <?php endforeach; ?>
                        <?php if (empty($expiredProducts)): ?>
                        <tr><td colspan="2">No expired items.</td></tr>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>
</div>

</div>
</div>

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