<?php
// upload.php
session_start();

header('Content-Type: application/json');

// Check authentication
if (!isset($_SESSION['admin_logged_in']) || $_SESSION['admin_logged_in'] !== true) {
    echo json_encode(['success' => false, 'message' => 'Unauthorized access. Please log in first.']);
    exit;
}

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    echo json_encode(['success' => false, 'message' => 'Invalid request method.']);
    exit;
}

if (!isset($_FILES['file']) || $_FILES['file']['error'] !== UPLOAD_ERR_OK) {
    $errCode = isset($_FILES['file']['error']) ? $_FILES['file']['error'] : UPLOAD_ERR_NO_FILE;
    echo json_encode(['success' => false, 'message' => 'No file uploaded or file upload error. Code: ' . $errCode]);
    exit;
}

$file = $_FILES['file'];
$uploadDir = __DIR__ . '/upload/';

// Create directory if it doesn't exist
if (!file_exists($uploadDir)) {
    if (!mkdir($uploadDir, 0755, true)) {
        echo json_encode(['success' => false, 'message' => 'Failed to create upload directory.']);
        exit;
    }
}

// Generate unique file name
$ext = pathinfo($file['name'], PATHINFO_EXTENSION);
$allowedExtensions = ['jpg', 'jpeg', 'png', 'gif', 'webp', 'mp4', 'svg'];
$extLower = strtolower($ext);

if (!in_array($extLower, $allowedExtensions)) {
    echo json_encode(['success' => false, 'message' => 'File extension not allowed. Allowed: ' . implode(', ', $allowedExtensions)]);
    exit;
}

// Generate a unique name using random bytes to guarantee uniqueness
$uniqueName = bin2hex(random_bytes(16)) . '.' . $extLower;
$destination = $uploadDir . $uniqueName;

if (move_uploaded_file($file['tmp_name'], $destination)) {
    // Return relative path
    $relativeUrl = 'upload/' . $uniqueName;
    echo json_encode(['success' => true, 'url' => $relativeUrl]);
} else {
    echo json_encode(['success' => false, 'message' => 'Failed to save the uploaded file.']);
}
