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

require_once '../../../dripend/includes/db.php';

// ==============================================================================
// 1. FETCH DICTIONARIES FOR FILTERS
// ==============================================================================
$locations = $conn->query("SELECT id, location_name, location_type FROM inventory_locations WHERE is_active = 1 ORDER BY location_name ASC")->fetch_all(MYSQLI_ASSOC);
$categories = $conn->query("SELECT id, category_name FROM item_categories WHERE is_active = 1 ORDER BY id ASC")->fetch_all(MYSQLI_ASSOC);

// ==============================================================================
// 2. DYNAMIC SQL SEARCH & FILTER
// ==============================================================================
$search_text = $_GET['search'] ?? '';
$filter_location = !empty($_GET['location_id']) ? (int)$_GET['location_id'] : null;
$filter_category = !empty($_GET['category_id']) ? (int)$_GET['category_id'] : null;

// Base query joining local stock, master catalog, locations, and categories
$query = "SELECT s.id as stock_id, s.quantity, s.last_updated, 
                 c.id as service_id, c.service_name, c.unit_of_pricing, c.reorder_level, c.alert_quantity, 
                 l.id as location_id, l.location_name, l.location_type, 
                 ic.category_name
          FROM inventory_stock s
          JOIN service_catalog c ON s.service_id = c.id
          JOIN inventory_locations l ON s.location_id = l.id
          JOIN item_categories ic ON c.category_id = ic.id
          WHERE 1=1 ";

$params = [];
$types = "";

if ($filter_location) {
    $query .= " AND s.location_id = ? ";
    $params[] = $filter_location;
    $types .= "i";
}
if ($filter_category) {
    $query .= " AND c.category_id = ? ";
    $params[] = $filter_category;
    $types .= "i";
}
if ($search_text !== '') {
    $query .= " AND c.service_name LIKE ? ";
    $search_param = "%{$search_text}%";
    $params[] = $search_param;
    $types .= "s";
}

$query .= " ORDER BY l.location_type DESC, l.location_name ASC, c.service_name ASC";

$stmt = $conn->prepare($query);
if (!empty($params)) {
    $stmt->bind_param($types, ...$params);
}
$stmt->execute();
$inventory = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);
$stmt->close();

// KPI Calculations
$kpis = [
    'total_stock_lines' => count($inventory),
    'items_low_stock' => 0,
    'drugs_count' => 0,
    'consumables_count' => 0
];

foreach ($inventory as $item) {
    if ($item['quantity'] <= $item['alert_quantity']) $kpis['items_low_stock']++;
    if ($item['category_name'] == 'Drugs & Medications') $kpis['drugs_count']++;
    else $kpis['consumables_count']++;
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Store Inventory Dashboard | Enterprise</title>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.0/css/all.min.css">
<style>
    :root { --sidebar-width: 240px; --e-blue: #1e3a8a; --e-green: #16a34a; --bg: #f8fafc; --border: #e2e8f0; --text: #334155; }
    body { font-family: "Segoe UI", system-ui, sans-serif; background: var(--bg); margin: 0; padding: 0; color: var(--text); overflow-x: hidden; }
    .page-wrapper { position: absolute; top: 0; left: var(--sidebar-width); width: calc(100% - var(--sidebar-width)); min-height: 100vh; padding: 30px; box-sizing: border-box; }
    
    .header-bar { display: flex; justify-content: space-between; align-items: center; margin-bottom: 20px; }
    .header-bar h2 { color: #0f172a; margin: 0; font-size: 24px; font-weight: 800; text-transform: uppercase; display:flex; align-items:center; gap:10px; }
    
    .primary-actions { display: flex; gap: 12px; }
    .btn-action-top { padding: 12px 18px; text-decoration: none; border-radius: 8px; font-weight: bold; box-shadow: 0 4px 6px rgba(0,0,0,0.1); transition: 0.2s; display: inline-flex; align-items: center; gap: 8px; border:none; color:#fff; font-size:14px; cursor: pointer;}
    .btn-action-top:hover { transform: translateY(-2px); box-shadow: 0 6px 12px rgba(0,0,0,0.15); }
    .bg-add { background: #0284c7; }
    .bg-transfer { background: #f59e0b; }
    .bg-stores { background: #4f46e5; } /* New Purple/Indigo color for Stores management */

    .kpi-grid { display: grid; grid-template-columns: repeat(4, 1fr); gap: 15px; margin-bottom: 25px; }
    .kpi-card { background: #fff; padding: 20px; border-radius: 12px; border: 1px solid var(--border); border-left: 5px solid var(--e-blue); box-shadow: 0 4px 10px rgba(0,0,0,0.02); display: flex; justify-content: space-between; align-items: center; }
    .kpi-card.green { border-left-color: var(--e-green); }
    .kpi-card.purple { border-left-color: #8b5cf6; }
    .kpi-card.red { border-left-color: #dc2626; background: #fef2f2; }
    .kpi-info h3 { margin: 0 0 5px 0; font-size: 13px; color: #64748b; text-transform: uppercase; font-weight: 700; }
    .kpi-info p { margin: 0; font-size: 26px; font-weight: 800; color: #0f172a; }
    .kpi-icon { font-size: 30px; color: #e2e8f0; }
    .kpi-card.red .kpi-icon { color: #fca5a5; }

    .filter-panel { background: #fff; padding: 20px; border-radius: 12px; margin-bottom: 25px; border: 1px solid var(--border); box-shadow: 0 4px 10px rgba(0,0,0,0.02); }
    .filter-grid { display: grid; grid-template-columns: 2fr 1.5fr 1.5fr auto; gap: 15px; align-items: end; }
    .filter-group { display: flex; flex-direction: column; gap: 6px; }
    .filter-group label { font-size: 12px; font-weight: 700; color: #64748b; text-transform: uppercase; }
    .filter-control { padding: 11px 12px; border-radius: 6px; border: 1px solid #cbd5e1; outline: none; font-size: 14px; background: #fff; }
    .filter-control:focus { border-color: #0284c7; box-shadow: 0 0 0 3px #e0f2fe; }
    .btn-filter { background: #0284c7; color: #fff; border: none; padding: 12px 25px; border-radius: 6px; font-weight: bold; cursor: pointer; transition: 0.2s; height: 42px; }

    .table-card { background: #fff; border-radius: 12px; box-shadow: 0 4px 15px rgba(0,0,0,0.03); overflow-x: auto; border: 1px solid var(--border); }
    table { width: 100%; border-collapse: collapse; min-width: 1000px; }
    th { background: #f8fafc; color: #475569; padding: 15px; font-size: 12px; text-transform: uppercase; border-bottom: 2px solid var(--border); text-align: left; white-space: nowrap; font-weight:800; }
    td { padding: 15px; border-bottom: 1px solid var(--border); font-size: 14px; vertical-align: middle; }
    tr:hover { background: #f0f9ff; }
    
    .badge { padding: 4px 8px; border-radius: 6px; font-size: 11px; font-weight: 800; display: inline-flex; align-items: center; gap: 5px; white-space: nowrap; }
    .bg-green { background: #dcfce7; color: #166534; border: 1px solid #bbf7d0; }
    .bg-red { background: #fee2e2; color: #991b1b; border: 1px solid #fecaca; }
    .bg-yellow { background: #fef3c7; color: #b45309; border: 1px solid #fde68a; }
    .bg-gray { background: #f1f5f9; color: #475569; border: 1px solid #e2e8f0; }

    .action-group { display: flex; gap: 6px; justify-content: flex-end; }
    .btn-action { width: 34px; height: 34px; border-radius: 6px; border: none; display: flex; align-items: center; justify-content: center; cursor: pointer; transition: 0.2s; font-size: 14px; text-decoration:none; }
    .btn-edit { background: #f0fdf4; color: #166534; border: 1px solid #bbf7d0; }
    .btn-edit:hover { background: #dcfce7; }
    .btn-transfer { background: #fef3c7; color: #b45309; border: 1px solid #fde68a; }
    .btn-transfer:hover { background: #fde68a; }
</style>
</head>
<body>

<?php include('../../../dripend/statpages/sidebar.php'); ?>

<div class="page-wrapper">

    <div class="header-bar">
        <h2><i class="fa-solid fa-boxes-stacked" style="color:#0284c7;"></i> Location Inventory Dashboard</h2>
        <div class="primary-actions">
            <a href="storesAndDispensary.php" class="btn-action-top bg-stores"><i class="fa-solid fa-shop"></i> Manage Stores/Dispensaries</a>
            
            <a href="requisitions.php" class="btn-action-top bg-transfer"><i class="fa-solid fa-truck-fast"></i> Internal Requisitions</a>
            
            <a href="addProduct.php" class="btn-action-top bg-add"><i class="fa-solid fa-cloud-arrow-down"></i> Pull from Central Catalog</a>
        </div>
    </div>

    <div class="kpi-grid">
        <div class="kpi-card">
            <div class="kpi-info"><h3>Total Stocked Lines</h3><p><?= count($inventory) ?></p></div>
            <i class="fa-solid fa-cubes kpi-icon"></i>
        </div>
        <div class="kpi-card green">
            <div class="kpi-info"><h3>Drugs Line Items</h3><p><?= number_format($kpis['drugs_count']) ?></p></div>
            <i class="fa-solid fa-pills kpi-icon"></i>
        </div>
        <div class="kpi-card purple">
            <div class="kpi-info"><h3>Consumables Lines</h3><p><?= number_format($kpis['consumables_count']) ?></p></div>
            <i class="fa-solid fa-box-open kpi-icon"></i>
        </div>
        <div class="kpi-card red">
            <div class="kpi-info"><h3 style="color:#b91c1c;">Low Stock Warning</h3><p style="color:#b91c1c;"><?= number_format($kpis['items_low_stock']) ?></p></div>
            <i class="fa-solid fa-triangle-exclamation kpi-icon"></i>
        </div>
    </div>

    <div class="filter-panel">
        <form method="GET" action="">
            <div class="filter-grid">
                <div class="filter-group">
                    <label>Search Local Item</label>
                    <input type="text" name="search" class="filter-control" placeholder="Item name..." value="<?= htmlspecialchars($search_text) ?>">
                </div>
                <div class="filter-group">
                    <label>Location (Store/Dispensary)</label>
                    <select name="location_id" class="filter-control">
                        <option value="">All Locations</option>
                        <?php foreach($locations as $loc): ?>
                            <option value="<?= $loc['id'] ?>" <?= $filter_location == $loc['id'] ? 'selected' : '' ?>><?= htmlspecialchars($loc['location_name']) ?></option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div class="filter-group">
                    <label>Item Category</label>
                    <select name="category_id" class="filter-control">
                        <option value="">All Categories</option>
                        <?php foreach($categories as $cat): ?>
                            <option value="<?= $cat['id'] ?>" <?= $filter_category == $cat['id'] ? 'selected' : '' ?>><?= htmlspecialchars($cat['category_name']) ?></option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div>
                    <button type="submit" class="btn-filter"><i class="fa-solid fa-filter"></i> Apply View</button>
                    <?php if($search_text || $filter_location || $filter_category): ?>
                        <a href="manage_products.php" style="display:block; text-align:center; margin-top:8px; font-size:12px; color:#dc2626; text-decoration:none; font-weight:700;">Reset Filters</a>
                    <?php endif; ?>
                </div>
            </div>
        </form>
    </div>

    <div class="table-card">
        <table>
            <thead>
                <tr>
                    <th style="width: 40px;">#</th>
                    <th>Inventory Location</th>
                    <th>Item Description</th>
                    <th>Category</th>
                    <th>Current Shelf Quantity</th>
                    <th>Last Activity</th>
                    <th style="text-align:right;">Actions</th>
                </tr>
            </thead>
            <tbody>
                <?php if(empty($inventory)): ?>
                    <tr><td colspan="7" style="text-align:center; padding:40px; color:#94a3b8; font-weight:600;"><i class="fa-solid fa-box-open" style="font-size:30px; margin-bottom:10px; display:block;"></i> No stock available in selected locations.</td></tr>
                <?php else: 
                    $sn = 1; 
                    foreach ($inventory as $item): 
                        $stock = $item['quantity'];
                        $alert = $item['alert_quantity'];
                        $reorder = $item['reorder_level'];
                        
                        if ($stock <= $alert) { $stock_badge = 'bg-red'; $stock_icon = 'fa-triangle-exclamation'; }
                        elseif ($stock <= $reorder) { $stock_badge = 'bg-yellow'; $stock_icon = 'fa-arrow-trend-down'; }
                        else { $stock_badge = 'bg-green'; $stock_icon = 'fa-check'; }
                ?>
                <tr>
                    <td style="font-weight:bold; color:#64748b;"><?= $sn++ ?></td>
                    <td>
                        <strong style="color:#0f172a;"><?= htmlspecialchars($item['location_name']) ?></strong><br>
                        <span style="font-size:11px; color:#64748b; font-weight:700; text-transform:uppercase;"><?= htmlspecialchars($item['location_type']) ?></span>
                    </td>
                    <td style="font-weight:700; color:#0f172a;"><?= htmlspecialchars($item['service_name']) ?></td>
                    <td><span class="badge bg-gray"><?= htmlspecialchars($item['category_name']) ?></span></td>
                    
                    <td>
                        <span class="badge <?= $stock_badge ?>" style="font-size:14px; padding:6px 12px;">
                            <i class="fa-solid <?= $stock_icon ?>"></i> <?= number_format($stock) ?> <?= htmlspecialchars($item['unit_of_pricing']) ?>
                        </span>
                        <div style="font-size:10px; color:#94a3b8; font-weight:700; margin-top:4px;">
                            Reorder: <?= $reorder ?> | Alert: <?= $alert ?>
                        </div>
                    </td>
                    <td style="font-size:12px; color:#64748b; font-weight:600;"><?= date('d M Y, H:i', strtotime($item['last_updated'])) ?></td>
                    <td style="text-align:right;">
                        <div class="action-group">
                            <button class="btn-action btn-edit" title="Manual Stock Audit/Correction"><i class="fa-solid fa-sliders"></i></button>
                            <a href="requisitions.php?item_id=<?= $item['service_id'] ?>&from_loc=<?= $item['location_id'] ?>" class="btn-action btn-transfer" title="Create Requisition (Transfer Stock)"><i class="fa-solid fa-dolly"></i></a>
                        </div>
                    </td>
                </tr>
                <?php endforeach; endif; ?>
            </tbody>
        </table>
    </div>
</div>

</body>
</html>