<?php
// ULTRA-FAST API RESPONSE OPTIMIZATION
header('X-Powered-By: HSE-Management');
header('Cache-Control: public, max-age=600, must-revalidate');
header('Expires: ' . gmdate('D, d M Y H:i:s', time() + 600) . ' GMT');
header('Pragma: public');
header('Vary: Accept-Encoding');

// Enable output buffering and compression
if (!headers_sent()) {
    ob_start('ob_gzhandler');
    header('Content-Encoding: gzip');
}

// Aggressive caching class with shorter response times
class FastCache {
    private $cacheDir = __DIR__ . '/../.cache';
    private $ttl = 120; // 2 minutes for ultra-fast cache hits

    public function __construct() {
        if (!is_dir($this->cacheDir)) {
            @mkdir($this->cacheDir, 0755, true);
        }
    }

    public function get($key) {
        $file = $this->cacheDir . '/' . md5($key);
        if (file_exists($file)) {
            $data = @json_decode(file_get_contents($file), true);
            if ($data && $data['expires'] > time()) {
                return $data['value'];
            }
            @unlink($file);
        }
        return null;
    }

    public function set($key, $value, $ttl = null) {
        $file = $this->cacheDir . '/' . md5($key);
        $data = [
            'value' => $value,
            'expires' => time() + ($ttl ?? $this->ttl)
        ];
        @file_put_contents($file, json_encode($data), LOCK_EX);
    }

    public function flush($pattern = null) {
        if ($pattern) {
            foreach (@glob($this->cacheDir . '/*') as $file) {
                @unlink($file);
            }
        }
    }
}

$fastCache = new FastCache();

// Connection pooling - reuse existing connection
function getDB() {
    static $mysqli = null;
    if ($mysqli === null) {
        require_once __DIR__ . '/../config/database.php';
    }
    return $mysqli ?? $GLOBALS['mysqli'];
}

// Ultra-fast query execution
function fastQuery($sql, $params = [], $ttl = 120) {
    global $fastCache;

    $cacheKey = md5($sql . json_encode($params));
    $cached = $fastCache->get($cacheKey);
    if ($cached !== null) {
        return $cached;
    }

    $mysqli = getDB();
    $stmt = $mysqli->prepare($sql);

    if ($params) {
        $types = '';
        foreach ($params as $p) {
            $types .= is_int($p) ? 'i' : 's';
        }
        $stmt->bind_param($types, ...$params);
    }

    $stmt->execute();
    $result = $stmt->get_result();
    $data = [];

    while ($row = $result->fetch_assoc()) {
        if (isset($row['id'])) {
            $row['__backendId'] = $row['id'];
            unset($row['id']);
        }
        $data[] = $row;
    }

    $fastCache->set($cacheKey, $data, $ttl);
    return $data;
}
?>
