<?php
header('Content-Type: application/json');
header('Cache-Control: public, max-age=120');
header('X-Cache-TTL: 120');
if (!headers_sent()) {
    ob_start('ob_gzhandler');
}

require_once __DIR__ . '/../config/database.php';
require_once __DIR__ . '/fast.php';

$cacheKey = 'ppe_list_' . md5(json_encode($_GET));
$cached = $fastCache->get($cacheKey);
if ($cached !== null) {
    echo json_encode($cached);
    exit;
}

$limit = min($_GET['limit'] ?? 500, 1000);
$offset = $_GET['offset'] ?? 0;

$sql = "SELECT id, item_name, category, quantity, min_stock, expiry_date, supplier_name FROM ppe_inventory ORDER BY id DESC LIMIT ? OFFSET ?";
$data = fastQuery($sql, [$limit, $offset], 120);

// Transform database field names to match frontend expectations
$transformedData = array_map(function($item) {
    return [
        '__backendId' => $item['id'],
        'ppeName' => $item['item_name'],
        'ppeCategory' => $item['category'],
        'ppeQuantity' => (string)$item['quantity'],
        'ppeMinStock' => (string)$item['min_stock'],
        'ppeExpiry' => $item['expiry_date'],
        'ppeSupplierName' => $item['supplier_name'],
        'recordType' => 'ppe_inventory'
    ];
}, $data);

$fastCache->set($cacheKey, $transformedData, 120);
echo json_encode($transformedData);
?>
