<?php
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: POST, OPTIONS");
header("Access-Control-Allow-Headers: Content-Type, Authorization");
if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') { exit(0); }
header('Content-Type: application/json');

include_once '../middleware/auth.php';

$user = get_user_from_token();
if (!$user || $user->role !== 'admin') {
    http_response_code(403);
    echo json_encode(['message' => 'Forbidden: Admin access required.']);
    exit();
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (isset($_FILES['image']) && $_FILES['image']['error'] === UPLOAD_ERR_OK) {
        $fileTmpPath = $_FILES['image']['tmp_name'];
        $fileName = $_FILES['image']['name'];
        $fileSize = $_FILES['image']['size'];

        $fileNameCmps = explode(".", $fileName);
        $fileExtension = strtolower(end($fileNameCmps));
        $allowedfileExtensions = ['jpg', 'jpeg', 'png', 'gif', 'svg', 'webp'];

        if (!in_array($fileExtension, $allowedfileExtensions)) {
            http_response_code(400);
            echo json_encode(['message' => 'Upload failed. Allowed file types: ' . implode(', ', $allowedfileExtensions)]);
            exit();
        }
        if ($fileSize > 5000000) {
            http_response_code(400);
            echo json_encode(['message' => 'File exceeds maximum size of 5MB.']);
            exit();
        }

        $originalName = pathinfo($fileName, PATHINFO_FILENAME);
        $sanitizedOriginalName = preg_replace("/[^a-zA-Z0-9-_]/", "", $originalName); // Remove dot for better security
        $newFileName = $sanitizedOriginalName . '-' . time() . '.' . $fileExtension;
        $uploadFileDir = '../public/uploads/';
        $dest_path = $uploadFileDir . $newFileName;

        // Ensure upload directory exists
        if (!is_dir($uploadFileDir)) {
            if (!mkdir($uploadFileDir, 0755, true)) {
                http_response_code(500);
                echo json_encode(['message' => 'Failed to create upload directory.']);
                exit();
            }
        }

        if (move_uploaded_file($fileTmpPath, $dest_path)) {
            $publicPath = '/public/uploads/' . $newFileName;
            http_response_code(201);
            echo json_encode(['message' => 'Image uploaded successfully.', 'path' => $publicPath]);
        } else {
            http_response_code(500);
            echo json_encode(['message' => 'There was some error moving the file to the upload directory.']);
        }
    } else {
        http_response_code(400);
        echo json_encode(['message' => 'No file was sent or there was an upload error.']);
    }
}
?>