<?php
require_once dirname(__DIR__, 3) . '/dripend/config/config.php';
require_once dirname(__DIR__, 3) . '/dripend/includes/db.php';

// CRITICAL FIX: Capture exact routing states
$current_cat = $_GET['cat'] ?? 'stores';
$current_page = $_GET['page'] ?? 'inventory/listOpeningAllocations.php';

// Extract filters safely
$filter_status = $_GET['status'] ?? '';
$filter_type = $_GET['location_type'] ?? '';
$search = isset($_GET['search']) ? trim($conn->real_escape_string($_GET['search'])) : '';

$where_clauses = ["1=1"];
if (!empty($filter_status)) {
    $where_clauses[] = "o.status = '" . $conn->real_escape_string($filter_status) . "'";
}
if (!empty($filter_type)) {
    $where_clauses[] = "o.location_type = '" . $conn->real_escape_string($filter_type) . "'";
}
if (!empty($search)) {
    $where_clauses[] = "(o.reference_number LIKE '%$search%' OR o.remarks LIKE '%$search%')";
}
$where_sql = implode(" AND ", $where_clauses);

$query = "
    SELECT o.*, 
           CASE 
             WHEN o.location_type = 'Store' THEN (SELECT store_name FROM stores WHERE id = o.location_id)
             WHEN o.location_type = 'Department' THEN (SELECT department_name FROM departments WHERE id = o.location_id)
             WHEN o.location_type = 'Dispensary' THEN (SELECT location_name FROM inventory_locations WHERE id = o.location_id)
           END as destination_name,
           (SELECT COUNT(id) FROM opening_allocation_items WHERE allocation_id = o.id) as total_items,
           (SELECT SUM(quantity) FROM opening_allocation_items WHERE allocation_id = o.id) as total_qty,
           (SELECT CONCAT(first_name, ' ', last_name) FROM staff WHERE staff_id = o.created_by) as operator_name
    FROM opening_allocations o
    WHERE $where_sql
    ORDER BY o.id DESC
";
$result = $conn->query($query);
?>

<div class="container-fluid py-4 px-4">
    <div class="d-flex justify-content-between align-items-center mb-4 pb-3 border-bottom">
        <div>
            <h2 class="h4 text-dark fw-bold m-0"><i class="fa-solid fa-list-check text-primary me-2"></i>Opening Inventory Ledger Logs</h2>
            <p class="text-muted small m-0 mt-1">Audit historical initialization entries and balances across hospital nodes.</p>
        </div>
        <a href="inventory/addOpeningAllocation.php" class="btn btn-primary fw-bold shadow-sm">
            <i class="fa-solid fa-circle-plus me-2"></i> Add Opening Stock
        </a>
    </div>

    <div class="bg-white p-3 rounded border shadow-sm mb-4">
        <!-- CRITICAL FIX: Form action locked to systemSetup.php with preserved parameters -->
        <form method="GET" action="systemSetup.php" class="row g-3 align-items-end">
            <input type="hidden" name="cat" value="<?= htmlspecialchars($current_cat) ?>">
            <input type="hidden" name="page" value="<?= htmlspecialchars($current_page) ?>">
            
            <div class="col-md-3">
                <label class="form-label small fw-bold text-muted text-uppercase">Search Reference / Notes</label>
                <input type="text" name="search" class="form-control form-control-sm" value="<?= htmlspecialchars($search) ?>" placeholder="OIA-2026-...">
            </div>
            <div class="col-md-3">
                <label class="form-label small fw-bold text-uppercase <?= !empty($filter_type) ? 'text-primary' : 'text-muted' ?>">Filter Location Topography</label>
                <select name="location_type" class="form-select form-select-sm <?= !empty($filter_type) ? 'border-primary' : '' ?>">
                    <option value="">-- View All Topographies --</option>
                    <option value="Store" <?= $filter_type === 'Store' ? 'selected' : '' ?>>Store Grid Nodes</option>
                    <option value="Department" <?= $filter_type === 'Department' ? 'selected' : '' ?>>Department Points</option>
                    <option value="Dispensary" <?= $filter_type === 'Dispensary' ? 'selected' : '' ?>>Dispensaries</option>
                </select>
            </div>
            <div class="col-md-2">
                <label class="form-label small fw-bold text-muted text-uppercase">Status Check</label>
                <select name="status" class="form-select form-select-sm">
                    <option value="">-- All Records --</option>
                    <option value="Draft" <?= $filter_status === 'Draft' ? 'selected' : '' ?>>Draft Mode</option>
                    <option value="Posted" <?= $filter_status === 'Posted' ? 'selected' : '' ?>>Posted (Locked)</option>
                </select>
            </div>
            <div class="col-md-4 d-flex gap-2">
                <button type="submit" class="btn btn-sm btn-secondary w-100 fw-bold"><i class="fa-solid fa-filter me-1"></i> Apply Filters</button>
                <a href="systemSetup.php?cat=<?= htmlspecialchars($current_cat) ?>&page=<?= htmlspecialchars($current_page) ?>" class="btn btn-sm btn-light border w-100 fw-bold text-muted text-center text-decoration-none pt-1">Clear</a>
            </div>
        </form>
    </div>

    <div class="bg-white rounded border shadow-sm">
        <div class="table-responsive">
            <table class="table table-hover align-middle m-0 table-sm">
                <thead class="table-light border-bottom small text-uppercase">
                    <tr>
                        <th class="text-center py-3" style="width: 5%">#</th>
                        <th style="width: 15%">Reference Number</th>
                        <th style="width: 15%">Target Topography Node</th>
                        <th style="width: 12%">Allocation Date</th>
                        <th class="text-center" style="width: 10%">Line Items</th>
                        <th class="text-center" style="width: 12%">Total Handled Qty</th>
                        <th style="width: 15%">Authorized By</th>
                        <th class="text-center" style="width: 10%">Status</th>
                    </tr>
                </thead>
                <tbody class="small">
                    <?php 
                    if ($result && $result->num_rows > 0): 
                        $rowNumber = 1;
                        while ($row = $result->fetch_assoc()): 
                            $badgeClass = ($row['status'] === 'Posted') ? 'bg-success-subtle text-success border border-success' : 'bg-warning-subtle text-warning border border-warning';
                    ?>
                        <tr>
                            <td class="text-center fw-bold text-muted border-end"><?= $rowNumber++ ?></td>
                            <td class="fw-bold text-dark font-monospace"><?= $row['reference_number'] ?></td>
                            <td>
                                <span class="badge bg-light text-secondary border small fw-normal mb-1"><?= $row['location_type'] ?></span><br>
                                <strong class="text-primary-emphasis"><?= htmlspecialchars($row['destination_name'] ?? 'System Orphan') ?></strong>
                            </td>
                            <td><?= date('d-M-Y', strtotime($row['allocation_date'])) ?></td>
                            <td class="text-center fw-bold"><?= number_format($row['total_items']) ?></td>
                            <td class="text-center fw-bold text-info"><?= number_format($row['total_qty'] ?? 0) ?></td>
                            <td><span class="text-dark fw-medium"><i class="fa-solid fa-user-shield me-1 text-muted small"></i> <?= htmlspecialchars($row['operator_name'] ?? 'System Superuser') ?></span></td>
                            <td class="text-center">
                                <span class="badge rounded-pill px-3 py-1 text-uppercase <?= $badgeClass ?>"><?= $row['status'] ?></span>
                            </td>
                        </tr>
                    <?php 
                        endwhile; 
                    else: 
                    ?>
                        <tr>
                            <td colspan="8" class="text-center py-5 text-muted">
                                <i class="fa-solid fa-folder-open fs-2 mb-3 d-block text-black-50"></i>
                                No allocations found matching current criteria.
                            </td>
                        </tr>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>
    </div>
</div>