<?php
declare(strict_types=1);

/**
 * Quick diagnostics for api/image-variant.php requirements.
 * Open in browser: /api/check-image-proxy.php
 * Remove or protect this file on production if you prefer not to expose server info.
 */

header('Content-Type: application/json; charset=utf-8');

$cacheDir = dirname(__DIR__) . DIRECTORY_SEPARATOR . 'data' . DIRECTORY_SEPARATOR . 'image-cache';
$checks = [
    'phpVersion' => PHP_VERSION,
    'extension_curl' => extension_loaded('curl'),
    'extension_gd' => extension_loaded('gd'),
    'cacheDir_path' => $cacheDir,
    'cacheDir_exists' => is_dir($cacheDir),
    'cacheDir_writable' => is_dir($cacheDir) && is_writable($cacheDir),
    'function_imagecreatefromstring' => function_exists('imagecreatefromstring'),
    'function_curl_init' => function_exists('curl_init'),
];

$checks['ready_for_image_variant'] = $checks['extension_curl']
    && $checks['extension_gd']
    && $checks['cacheDir_exists']
    && $checks['cacheDir_writable']
    && $checks['function_imagecreatefromstring']
    && $checks['function_curl_init'];

// Optional: tiny write test (same dir image-variant.php uses)
$writeTest = ['ok' => false, 'message' => ''];
if ($checks['cacheDir_writable']) {
    $probe = $cacheDir . DIRECTORY_SEPARATOR . '.write_probe_' . bin2hex(random_bytes(4));
    if (@file_put_contents($probe, 'ok') !== false) {
        @unlink($probe);
        $writeTest['ok'] = true;
        $writeTest['message'] = 'probe_write_delete_ok';
    } else {
        $writeTest['message'] = 'file_put_contents_failed';
    }
} else {
    $writeTest['message'] = 'cache_dir_not_writable';
}

$checks['write_probe'] = $writeTest;

if (!$checks['cacheDir_exists']) {
    $checks['hint'] = 'Create folder: data/image-cache/ (755 or 775) and upload data/image-cache/index.php from the repo.';
} elseif (!$checks['cacheDir_writable']) {
    $checks['hint'] = 'chmod data/image-cache to 755 or 775 in cPanel File Manager.';
} elseif (!$checks['extension_gd'] || !$checks['extension_curl']) {
    $checks['hint'] = 'cPanel → Select PHP Version → enable extensions: gd, curl.';
} else {
    $checks['hint'] = 'All checks passed. Homepage images via api/image-variant.php should work.';
}

echo json_encode($checks, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES);
