<?php
/**
 * Serves profile photo images so the app can load them from the API origin.
 * Usage: get_profile_photo.php?path=storage/user_profile/xxx.jpg
 */
require_once __DIR__ . '/../config/cors.php';

$path = isset($_GET['path']) ? trim($_GET['path']) : '';
if ($path === '' || preg_match('/\.\./', $path)) {
    http_response_code(400);
    exit('Invalid path');
}

if (strpos($path, 'storage/user_profile/') !== 0) {
    http_response_code(403);
    exit('Forbidden');
}

$baseDir = dirname(__DIR__);
$fullPath = $baseDir . DIRECTORY_SEPARATOR . str_replace('/', DIRECTORY_SEPARATOR, $path);

if (!is_file($fullPath)) {
    http_response_code(404);
    exit('Not found');
}

$ext = strtolower(pathinfo($fullPath, PATHINFO_EXTENSION));
$mimes = [
    'png' => 'image/png',
    'jpg' => 'image/jpeg',
    'jpeg' => 'image/jpeg',
    'gif' => 'image/gif',
    'webp' => 'image/webp',
];
$mime = $mimes[$ext] ?? 'image/jpeg';

header('Content-Type: ' . $mime);
header('Cache-Control: private, max-age=86400');
readfile($fullPath);
exit;
