<?php
declare(strict_types=1);

require_once __DIR__ . '/includes/bootstrap.php';

$id = trim((string) ($_GET['id'] ?? ''));
$product = $id !== '' ? store_find('products', $id) : null;

if (!$product || ($product['status'] ?? '') === 'hidden') {
    http_response_code(404);
    header('Content-Type: text/plain; charset=utf-8');
    echo 'Not found';
    exit;
}

$path = product_og_card_build($product);

// GD yoksa veya üretim başarısızsa ham ürün fotoğrafı
if ($path === false || !is_file($path)) {
    $fallback = product_image_filesystem_path($product);
    if ($fallback !== '' && is_file($fallback)) {
        $mime = (string) (new finfo(FILEINFO_MIME_TYPE))->file($fallback);
        header('Content-Type: ' . ($mime !== '' ? $mime : 'image/jpeg'));
        header('Cache-Control: public, max-age=86400');
        readfile($fallback);
        exit;
    }
    http_response_code(404);
    exit;
}

header('Content-Type: image/jpeg');
header('Cache-Control: public, max-age=604800, immutable');
header('Content-Length: ' . (string) filesize($path));
readfile($path);
exit;
