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

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

// ==============================================================================
// 1. FETCH FILTER DICTIONARIES
// ==============================================================================
$insurances = $conn->query("SELECT id, insurance_name FROM insurance_type WHERE LOWER(insurance_name) NOT IN ('nhis', 'cash') AND is_active = 1 ORDER BY insurance_name ASC")->fetch_all(MYSQLI_ASSOC);
$formulations = $conn->query("SELECT DISTINCT drug_formulation FROM service_catalog WHERE service_type = 'Drug' AND drug_formulation IS NOT NULL ORDER BY drug_formulation 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 & STRICT MATRIX FILTER
// ==============================================================================
$search_text = $_GET['search'] ?? '';
$filter_formulation = $_GET['formulation'] ?? '';
$filter_ins_id = !empty($_GET['provider_id']) ? (int)$_GET['provider_id'] : null;
$filter_category = !empty($_GET['category_id']) ? (int)$_GET['category_id'] : null;

// Build query with subquery to get Total Global Stock across all locations
$query = "SELECT sc.*, d.department_name, ic.category_name, 
          (SELECT COALESCE(SUM(quantity), 0) FROM inventory_stock WHERE service_id = sc.id) AS total_stock ";

if ($filter_ins_id) {
    $query .= ", sct.tariff_amount AS corp_tariff, sct.is_copay_required AS corp_req, sct.copay_amount AS corp_copay ";
}

$query .= "FROM service_catalog sc 
           LEFT JOIN departments d ON sc.department_id = d.id 
           LEFT JOIN item_categories ic ON sc.category_id = ic.id ";

if ($filter_ins_id) {
    $query .= "INNER JOIN service_corporate_tariffs sct ON sc.id = sct.service_id AND sct.insurance_type_id = ? ";
}

$conditions = ["sc.service_type = 'Drug'"];
$params = [];
$types = "";

if ($filter_ins_id) {
    $params[] = $filter_ins_id;
    $types .= "i";
}
if ($filter_category) {
    $conditions[] = "sc.category_id = ?";
    $params[] = $filter_category;
    $types .= "i";
}
if ($search_text !== '') {
    $conditions[] = "(sc.service_name LIKE ? OR sc.nhis_drug_code LIKE ?)";
    $search_param = "%{$search_text}%";
    array_push($params, $search_param, $search_param);
    $types .= "ss";
}
if ($filter_formulation !== '') {
    $conditions[] = "sc.drug_formulation = ?";
    $params[] = $filter_formulation;
    $types .= "s";
}

$query .= " WHERE " . implode(" AND ", $conditions) . " ORDER BY sc.service_name ASC";

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

// ==============================================================================
// 3. KPI DASHBOARD CALCULATION
// ==============================================================================
$kpis = [
    'total_items' => count($medicines),
    'active_drugs' => 0,
    'active_consumables' => 0,
    'low_stock_alerts' => 0
];

foreach ($medicines as $m) {
    if ($m['category_id'] == 1) $kpis['active_drugs']++;
    else $kpis['active_consumables']++;
    
    if ($m['total_stock'] <= $m['alert_quantity']) $kpis['low_stock_alerts']++;
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Pharmacy Formulary & Global Catalog</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; }
    
    .admin-toolbar { background: #fff; padding: 12px 20px; border-radius: 10px; margin-bottom: 20px; border: 1px solid var(--border); box-shadow: 0 4px 6px rgba(0,0,0,0.02); display: flex; justify-content: space-between; align-items: center; }
    .dict-links { display: flex; gap: 15px; align-items: center; }
    .dict-link { font-size: 13px; font-weight: 700; color: #475569; text-decoration: none; padding: 8px 15px; background: #f1f5f9; border-radius: 6px; transition: 0.2s; border: 1px solid #e2e8f0; }
    .dict-link:hover { background: #e2e8f0; color: var(--e-blue); border-color: #cbd5e1; }
    
    .header-bar { display: flex; justify-content: space-between; align-items: center; margin-bottom: 20px; }
    .header-bar h2 { color: var(--e-blue); 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; }
    .btn-action-top:hover { transform: translateY(-2px); box-shadow: 0 6px 12px rgba(0,0,0,0.15); }
    .bg-add { background: var(--e-green); }
    .bg-price { background: #0f172a; }
    .bg-store { background: #0284c7; }

    .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 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: var(--e-blue); box-shadow: 0 0 0 3px #eff6ff; }
    .btn-filter { background: var(--e-blue); 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: 1300px; }
    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; }
    tr.inactive { opacity: 0.6; background: #f8fafc; }
    
    .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-blue { background: #dbeafe; color: #1e40af; border: 1px solid #bfdbfe; }
    .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-view { background: #eff6ff; color: #1e40af; border: 1px solid #bfdbfe; }
    .btn-edit { background: #f0fdf4; color: #166534; border: 1px solid #bbf7d0; }
    .btn-provider { background: #e0f2fe; color: #0284c7; border: 1px solid #bae6fd; }
    .btn-toggle { background: #fef3c7; color: #b45309; border: 1px solid #fde68a; }
    .btn-delete { background: #fee2e2; color: #991b1b; border: 1px solid #fecaca; }

    .matrix-alert { background: #eff6ff; color: #1e40af; padding: 12px 20px; border-radius: 8px; margin-bottom: 20px; font-size: 14px; font-weight: 700; border: 1px solid #bfdbfe; display: flex; align-items: center; gap: 10px; }
</style>
</head>
<body>


<div class="page-wrapper">

    <div class="admin-toolbar">
        <div style="font-size:13px; font-weight:800; color:#0f172a; text-transform:uppercase;"><i class="fa-solid fa-cogs" style="color:#64748b;"></i> System Configurations</div>
        <div class="dict-links">
            <a href="drugFormulation.php" class="dict-link"><i class="fa-solid fa-mortar-pestle"></i> Formulations</a>
            <a href="UnitOfMeasure.php" class="dict-link"><i class="fa-solid fa-scale-balanced"></i> Units</a>
            <a href="drugPrescribeLevel.php" class="dict-link"><i class="fa-solid fa-user-doctor"></i> Prescribing Levels</a>
        </div>
    </div>

    <div class="header-bar">
        <h2><i class="fa-solid fa-book-medical"></i> Master Item Catalog</h2>
        <div class="primary-actions">
            <!-- New Route to Stores -->
            <a href="../../../views/system_setup/stores/manageProducts.php" class="btn-action-top bg-store"><i class="fa-solid fa-boxes-stacked"></i> Manage Stores & Transfers</a>
            <a href="updateMedicinePrice.php" class="btn-action-top bg-price"><i class="fa-solid fa-tags"></i> Bulk Price Update</a>
            <a href="addMedicine.php" class="btn-action-top bg-add"><i class="fa-solid fa-plus"></i> Add New Item</a>
        </div>
    </div>

    <div class="kpi-grid">
        <div class="kpi-card">
            <div class="kpi-info"><h3>Total Items</h3><p><?= number_format($kpis['total_items']) ?></p></div>
            <i class="fa-solid fa-clipboard-list kpi-icon"></i>
        </div>
        <div class="kpi-card green">
            <div class="kpi-info"><h3>Active Drugs</h3><p><?= number_format($kpis['active_drugs']) ?></p></div>
            <i class="fa-solid fa-pills kpi-icon"></i>
        </div>
        <div class="kpi-card purple">
            <div class="kpi-info"><h3>Consumables</h3><p><?= number_format($kpis['active_consumables']) ?></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 Alerts</h3><p style="color:#b91c1c;"><?= number_format($kpis['low_stock_alerts']) ?></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 Item</label>
                    <input type="text" name="search" class="filter-control" placeholder="Search name, code..." value="<?= htmlspecialchars($search_text) ?>">
                </div>
                <div class="filter-group">
                    <label>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 class="filter-group">
                    <label>Formulation (Drugs)</label>
                    <select name="formulation" class="filter-control">
                        <option value="">All Formulations</option>
                        <?php foreach($formulations as $f): ?>
                            <option value="<?= htmlspecialchars($f['drug_formulation']) ?>" <?= $filter_formulation == $f['drug_formulation'] ? 'selected' : '' ?>><?= htmlspecialchars($f['drug_formulation']) ?></option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div class="filter-group">
                    <label style="color:#1e40af;">Insurance Matrix View</label>
                    <select name="provider_id" class="filter-control" style="border-color:#3b82f6; background:#eff6ff; font-weight:600; color:#1e40af;">
                        <option value="">NHIS & Cash Standard</option>
                        <?php foreach($insurances as $ins): ?>
                            <option value="<?= $ins['id'] ?>" <?= $filter_ins_id == $ins['id'] ? 'selected' : '' ?>><?= htmlspecialchars($ins['insurance_name']) ?> Policy</option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div>
                    <button type="submit" class="btn-filter"><i class="fa-solid fa-filter"></i> Filter</button>
                    <?php if($search_text || $filter_formulation || $filter_ins_id || $filter_category): ?>
                        <a href="listMedicine.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>

    <?php if($filter_ins_id): ?>
        <div class="matrix-alert">
            <i class="fa-solid fa-building-shield"></i> You are currently viewing isolated pricing matrices strictly mapped to the selected Corporate Provider.
        </div>
    <?php endif; ?>

    <div class="table-card">
        <table>
            <thead>
                <tr>
                    <th style="width: 40px;">#</th>
                    <th>Item Identity & Details</th>
                    <th>Category & Dispense Base</th>
                    <th>Global Stock & Alerts</th>
                    <th>Current Price</th>
                    
                    <?php if($filter_ins_id): ?>
                        <th style="background:#e0f2fe; color:#0284c7;">Provider Tariff</th>
                        <th style="background:#e0f2fe; color:#0284c7;">Provider Co-Pay</th>
                    <?php else: ?>
                        <th>NHIS Rules</th>
                        <th>NHIS Tariff & Co-Pay</th>
                    <?php endif; ?>
                    
                    <th style="text-align:right; width:180px;">Actions</th>
                </tr>
            </thead>
            <tbody>
                <?php if(empty($medicines)): ?>
                    <tr><td colspan="10" style="text-align:center; padding:40px; color:#94a3b8; font-weight:600;"><i class="fa-solid fa-boxes-packing" style="font-size:30px; margin-bottom:10px; display:block;"></i> No items match your filter criteria.</td></tr>
                <?php else: 
                    $sn = 1; 
                    foreach ($medicines as $m): 
                        // Determine stock status badges
                        $stock = $m['total_stock'];
                        $alert = $m['alert_quantity'];
                        $reorder = $m['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-blue'; $stock_icon = 'fa-cubes'; }
                ?>
                <tr class="<?= $m['is_active'] == 0 ? 'inactive' : '' ?>">
                    <td style="font-weight:bold; color:#64748b;"><?= $sn++ ?></td>
                    <td style="font-weight:700; color:#0f172a;">
                        <div style="display:flex; align-items:center; gap:8px;">
                            <?php 
                                $icon = 'fa-box-open'; // Default consumable
                                if ($m['category_id'] == 1) { // It's a drug
                                    $icon = 'fa-pills';
                                    if (strtolower($m['drug_formulation']) == 'injection') $icon = 'fa-syringe';
                                    elseif (strtolower($m['drug_formulation']) == 'syrup' || strtolower($m['drug_formulation']) == 'suspension') $icon = 'fa-prescription-bottle';
                                }
                            ?>
                            <i class="fa-solid <?= $icon ?>" style="color:#64748b;"></i> 
                            <?= htmlspecialchars($m['service_name']) ?>
                        </div>
                        <?php if($m['category_id'] == 1): ?>
                            <span style="font-size:11px; color:#64748b; font-weight:700; margin-top:4px; display:inline-block; margin-left:24px;">
                                <?= htmlspecialchars($m['drug_strength']) ?> <?= htmlspecialchars($m['strength_unit']) ?>
                            </span>
                        <?php endif; ?>
                    </td>
                    
                    <td>
                        <span class="badge bg-gray"><?= htmlspecialchars($m['category_name'] ?: 'General') ?></span><br>
                        <span style="font-size:12px; color:#475569; font-weight:700; display:block; margin-top:4px;">Base: <?= htmlspecialchars($m['unit_of_pricing'] ?: '--') ?></span>
                    </td>

                    <td>
                        <span class="badge <?= $stock_badge ?>" style="font-size:13px; padding:5px 10px;">
                            <i class="fa-solid <?= $stock_icon ?>"></i> <?= number_format($stock) ?> in stock
                        </span>
                        <div style="font-size:10px; color:#94a3b8; font-weight:700; margin-top:4px;">
                            Reorder: <?= $reorder ?> | Alert: <?= $alert ?>
                        </div>
                    </td>

                    <td>
                        <span style="font-weight:800; color:#16a34a;">GHS <?= number_format($m['cash_price'], 2) ?></span>
                    </td>
                    
                    <?php if($filter_ins_id): ?>
                        <td>
                            <?= isset($m['corp_tariff']) ? '<strong style="color:#0284c7;">GHS ' . number_format($m['corp_tariff'], 2) . '</strong>' : '<span class="badge bg-gray">Not Mapped</span>' ?>
                        </td>
                        <td>
                            <?php 
                            if(isset($m['corp_req']) && $m['corp_req'] == 1) echo "<span class='badge bg-red'>Co-Pay: GHS " . number_format($m['corp_copay'], 2) . "</span>"; 
                            else if(isset($m['corp_req'])) echo "<span class='badge bg-green'><i class=".'fa-solid fa-check'."></i> Fully Covered</span>";
                            else echo "<span style='color:#cbd5e1;'>--</span>";
                            ?>
                        </td>
                    <?php else: ?>
                        <td>
                            <?php if($m['nhis_covered'] == 1): ?>
                                <span class="badge bg-blue"><?= htmlspecialchars($m['nhis_drug_code'] ?: 'No Code') ?></span><br>
                                <span style="font-size:11px; color:#475569; font-weight:700; display:block; margin-top:3px;">Level: <?= htmlspecialchars($m['prescribing_level'] ?: 'Any') ?></span>
                            <?php else: ?>
                                <span class="badge bg-gray">Not Covered</span>
                            <?php endif; ?>
                        </td>
                        <td>
                            <?php if($m['nhis_covered'] == 1): ?>
                                <span style="color:#0284c7; font-weight:800; display:block; margin-bottom:4px;">GHS <?= number_format($m['tariff_adult'], 2) ?></span>
                                <?php if($m['is_copay_required'] == 1): ?>
                                    <span class='badge bg-red'>+ GHS <?= number_format($m['copay_amount'], 2) ?> Co-Pay</span>
                                <?php else: ?>
                                    <span class='badge bg-green'>Fully Covered</span>
                                <?php endif; ?>
                            <?php else: ?>
                                <span style="color:#cbd5e1;">--</span>
                            <?php endif; ?>
                        </td>
                    <?php endif; ?>

                    <td style="text-align:right;">
                        <div class="action-group">
                            <a href="viewMedicine.php?id=<?= $m['id'] ?>" class="btn-action btn-view" title="View Profile"><i class="fa-solid fa-eye"></i></a>
                            <a href="updateMedicine.php?id=<?= $m['id'] ?>" class="btn-action btn-edit" title="Edit Catalog Data"><i class="fa-solid fa-pen-to-square"></i></a>
                            <a href="mapMedicineIns.php?id=<?= $m['id'] ?>" class="btn-action btn-provider" title="Map New Insurance Provider"><i class="fa-solid fa-shield-plus"></i></a>
                            
                            <button class="btn-action btn-toggle" title="<?= $m['is_active'] ? 'Deactivate' : 'Activate' ?>" onclick="toggleStatus(<?= $m['id'] ?>, <?= $m['is_active'] ?>)">
                                <i class="fa-solid <?= $m['is_active'] ? 'fa-toggle-on' : 'fa-toggle-off' ?>"></i>
                            </button>
                            <button class="btn-action btn-delete" title="Delete Formally" onclick="confirmDelete(<?= $m['id'] ?>)"><i class="fa-solid fa-trash-can"></i></button>
                        </div>
                    </td>
                </tr>
                <?php endforeach; endif; ?>
            </tbody>
        </table>
    </div>
</div>

<script>
function toggleStatus(id, currentStatus) {
    const action = currentStatus === 1 ? 'deactivate' : 'activate';
    if(confirm(`Are you sure you want to ${action} this item?`)) {
        alert("Status toggle endpoint to be connected.");
    }
}

function confirmDelete(id) {
    if(confirm("DANGER: Are you sure you want to permanently delete this item? \n\nIf it has historical inventory or billing records, Deactivate it instead.")) {
        window.location.href = `deleteMedicine.php?id=${id}`;
    }
}
</script>

</body>
</html>