<?php
$settings = require __DIR__ . '/config.php';
$id = isset($_GET['id']) ? (int) $_GET['id'] : 0;

if ($id <= 0) {
    http_response_code(404);
    exit('Imagen no encontrada');
}

$db = $settings['db'];
$mysqli = @new mysqli($db['host'], $db['user'], $db['pass'], $db['name'], (int) $db['port']);
if ($mysqli->connect_errno) {
    http_response_code(500);
    exit('Error de conexion');
}

$mysqli->set_charset($db['charset']);

$stmt = $mysqli->prepare('SELECT file_name, file_data FROM phppos_app_files WHERE file_id = ? LIMIT 1');
if (!$stmt) {
    http_response_code(500);
    exit('Error de consulta');
}

$stmt->bind_param('i', $id);
$stmt->execute();
$stmt->bind_result($fileName, $fileData);
$rowFound = $stmt->fetch();
$stmt->close();
$mysqli->close();

if (!$rowFound || empty($fileData)) {
    http_response_code(404);
    exit('Imagen no encontrada');
}

$filename = strtolower((string) $fileName);
$contentType = 'application/octet-stream';
if (preg_match('/\.(jpe?g)$/', $filename)) {
    $contentType = 'image/jpeg';
} elseif (preg_match('/\.(png)$/', $filename)) {
    $contentType = 'image/png';
} elseif (preg_match('/\.(gif)$/', $filename)) {
    $contentType = 'image/gif';
} elseif (preg_match('/\.(webp)$/', $filename)) {
    $contentType = 'image/webp';
}

header('Content-Type: ' . $contentType);
header('Cache-Control: public, max-age=86400');
echo $fileData;
