<?php
require_once 'config.php';
require_once '../includes/Auth.php';

$auth = new Auth();
$user = $auth->requireAuth();

try {
    // Determine the upload directory based on the 'type' parameter
    $type = $_POST['type'] ?? 'others';
    $allowed_types = ['profiles', 'shops', 'products', 'slides', 'others'];
    if (!in_array($type, $allowed_types)) {
        throw new Exception('Invalid upload type specified.');
    }

    // Check if a file was uploaded
    if (!isset($_FILES['image']) || $_FILES['image']['error'] !== UPLOAD_ERR_OK) {
        throw new Exception('File upload error or no file selected.');
    }

    $file = $_FILES['image'];

    // Validate file size (e.g., 5MB max)
    if ($file['size'] > 5 * 1024 * 1024) {
        throw new Exception('File is too large. Maximum size is 5MB.');
    }

    // Validate file type
    $finfo = new finfo(FILEINFO_MIME_TYPE);
    $mime = $finfo->file($file['tmp_name']);
    $allowed_mimes = ['image/jpeg', 'image/png', 'image/gif', 'image/webp'];
    if (!in_array($mime, $allowed_mimes)) {
        throw new Exception('Invalid file type. Only JPG, PNG, GIF, and WEBP are allowed.');
    }

    // Define the base upload directory
    // Note: The path is relative to this file's location in `api/`
    $upload_dir_base = '../assets/images/';
    $upload_dir = $upload_dir_base . $type . '/';

    // Create the directory if it doesn't exist
    if (!is_dir($upload_dir)) {
        if (!mkdir($upload_dir, 0775, true)) {
            throw new Exception('Failed to create upload directory.');
        }
    }

    // Generate a unique filename to prevent overwrites
    $extension = pathinfo($file['name'], PATHINFO_EXTENSION);
    $unique_filename = uniqid('img_', true) . '.' . $extension;
    $destination = $upload_dir . $unique_filename;

    // Move the uploaded file
    if (!move_uploaded_file($file['tmp_name'], $destination)) {
        throw new Exception('Failed to save the uploaded file.');
    }

    // Return the public URL of the uploaded file
    $public_url = 'assets/images/' . $type . '/' . $unique_filename;
    jsonResponse(['success' => true, 'url' => $public_url]);

} catch (Exception $e) {
    jsonResponse(['success' => false, 'message' => $e->getMessage()], 400);
}
?>