<?php
require_once __DIR__ . '/security.php';
enrep_require_user();

$image = enrep_safe_filename(enrep_request_string('image', '', 180));
$parts = pathinfo($image);
$name = preg_replace('/[^A-Za-z0-9_-]/', '', (string)($parts['filename'] ?? ''));
$extension = strtolower((string)($parts['extension'] ?? ''));

if ($name === '' || !in_array($extension, ['jpg', 'jpeg', 'png'], true)) {
    enrep_fail(400, 'Invalid image');
}

$dir = realpath(__DIR__ . '/../images/company/PALLET_images');
if ($dir === false) {
    enrep_fail(400, 'Image directory not found');
}

$main = $dir . DIRECTORY_SEPARATOR . $name . '.' . $extension;
$thumb = $dir . DIRECTORY_SEPARATOR . $name . '_thumb.' . $extension;

foreach ([$main, $thumb] as $file) {
    $target = realpath($file);
    if ($target !== false && strpos($target, $dir . DIRECTORY_SEPARATOR) === 0 && is_file($target)) {
        unlink($target);
    }
}

echo 'done';
