<?php
declare(strict_types=1);

require_once __DIR__ . '/../../security/auth_guard.php';
require_once __DIR__ . '/../../config/constants.php';
require_once __DIR__ . '/../../core/Response.php';
require_once __DIR__ . '/../../core/Validator.php';

/**
 * ----------------------------
 * Method check
 * ----------------------------
 */
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    Response::error('Invalid request method', 405);
}

/**
 * ----------------------------
 * Required fields
 * ----------------------------
 */
Validator::required($_POST, ['file_type']);

$fileType = $_POST['file_type']; // Image | Video

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

/**
 * ----------------------------
 * Validators
 * ----------------------------
 */
function validateImage(array $file): void
{
    if ($file['error'] !== UPLOAD_ERR_OK) {
        Response::error('Image upload failed');
    }

    if ($file['size'] > MAX_IMAGE_SIZE) {
        Response::error('Image size exceeds limit');
    }

    $mime = mime_content_type($file['tmp_name']);
    if (!in_array($mime, ALLOWED_IMAGE_TYPES, true)) {
        Response::error('Invalid image type');
    }
}

function validateVideo(array $file): void
{
    if ($file['error'] !== UPLOAD_ERR_OK) {
        Response::error('Video upload failed');
    }

    if ($file['size'] > MAX_VIDEO_SIZE) {
        Response::error('Video size exceeds limit');
    }

    $mime = mime_content_type($file['tmp_name']);
    if (!in_array($mime, ALLOWED_VIDEO_TYPES, true)) {
        Response::error('Invalid video type');
    }
}

/**
 * ----------------------------
 * Base upload directory
 * ----------------------------
 */
$baseUploadDir = BASE_PATH . '/uploads/retail-products/';
$basePublicUrl = UPLOAD_BASE_URL . '/retail-products/';

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

/**
 * ----------------------------
 * IMAGE UPLOAD
 * ----------------------------
 */
if ($fileType === 'Image') {

    if (empty($_FILES['file']['tmp_name'])) {
        Response::error('Image file is required', 422);
    }

    validateImage($_FILES['file']);

    $dir = $baseUploadDir . 'images/';
    if (!is_dir($dir)) {
        mkdir($dir, 0775, true);
    }

    $fileName = 'section_' . uniqid('', true) . '.webp';

    if (!move_uploaded_file($_FILES['file']['tmp_name'], $dir . $fileName)) {
        Response::error('Failed to upload image');
    }

    Response::success('Image uploaded successfully', [
        'file_path' => $basePublicUrl . 'images/' . $fileName,
        'thumbnail_path' => null
    ]);
}

/**
 * ----------------------------
 * VIDEO UPLOAD
 * ----------------------------
 */
if ($fileType === 'Video') {

    if (empty($_FILES['file']['tmp_name'])) {
        Response::error('Video file is required', 422);
    }

    validateVideo($_FILES['file']);

    $videoDir = $baseUploadDir . 'videos/';
    $thumbDir = $baseUploadDir . 'thumbnails/';

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

    $videoName = 'section_' . uniqid('', true) . '.mp4';

    if (!move_uploaded_file($_FILES['file']['tmp_name'], $videoDir . $videoName)) {
        Response::error('Failed to upload video');
    }

    /**
     * Optional thumbnail
     */
    $thumbnailPath = null;
    if (!empty($_FILES['thumbnail']['tmp_name'])) {

        validateImage($_FILES['thumbnail']);

        $thumbName = 'thumb_' . uniqid('', true) . '.webp';

        if (!move_uploaded_file(
            $_FILES['thumbnail']['tmp_name'],
            $thumbDir . $thumbName
        )) {
            Response::error('Failed to upload video thumbnail');
        }

        $thumbnailPath = $basePublicUrl . 'thumbnails/' . $thumbName;
    }

    Response::success('Video uploaded successfully', [
        'file_path' => $basePublicUrl . 'videos/' . $videoName,
        'thumbnail_path' => $thumbnailPath
    ]);
}
