<?php
declare(strict_types=1);

require_once __DIR__ . '/../../security/auth_guard_web.php';
require_once __DIR__ . '/../../config/database.php';
require_once __DIR__ . '/../../core/Response.php';

if (empty($_POST['product_id']) || empty($_FILES['image'])) {
    Response::error('product_id and image required', 422);
}

$productId = (int)$_POST['product_id'];

$rootPath = dirname(__DIR__, 3);
$uploadDir = $rootPath . '/uploads/retail-products/' . $productId . '/sections/';

if (!is_dir($uploadDir)) {
    mkdir($uploadDir, 0775, true);
}

$file = $_FILES['image'];
$allowed = ['image/jpeg','image/png','image/webp'];

if (!in_array($file['type'], $allowed, true)) {
    Response::error('Invalid image type', 422);
}

$ext = pathinfo($file['name'], PATHINFO_EXTENSION);
$name = uniqid('section_', true) . '.' . $ext;

if (!move_uploaded_file($file['tmp_name'], $uploadDir . $name)) {
    Response::error('Upload failed', 500);
}

Response::success('Uploaded', [
    'file_path' => '/uploads/retail-products/' . $productId . '/sections/' . $name
]);
