<?php
/**
 * Serves RM signature image files so the app can load them from the API origin
 * (avoids wrong paths and CORS when loading from storage/ directly).
 * Usage: get_signature.php?path=storage/rm_signatures/sig_1_2_123.png
 */
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');
}

// Only allow paths under storage/rm_signatures/ or storage/assignments_signatures/
$allowed = false;
if (strpos($path, 'storage/rm_signatures/') === 0)
    $allowed = true;
if (strpos($path, 'storage/assignments_signatures/') === 0)
    $allowed = true;
if (strpos($path, 'storage/officers_signature/') === 0)
    $allowed = true;

if (!$allowed) {
    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',
];
$mime = $mimes[$ext] ?? 'application/octet-stream';

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