<?php
require_once __DIR__ . '/../config.php';
header('Content-Type: application/json');

if (!isset($_SESSION['user_id']) || ($_SESSION['user_role'] ?? '') !== 'admin') {
    http_response_code(401);
    echo json_encode(['success' => false, 'message' => 'Not authenticated']);
    exit;
}

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

if (!isset($_FILES['image']) || !is_uploaded_file($_FILES['image']['tmp_name'])) {
    http_response_code(400);
    echo json_encode(['success' => false, 'message' => 'No image file uploaded']);
    exit;
}

$file = $_FILES['image'];
$max_size = 5 * 1024 * 1024; // 5MB
if (($file['size'] ?? 0) <= 0 || $file['size'] > $max_size) {
    http_response_code(400);
    echo json_encode(['success' => false, 'message' => 'Invalid file size. Max 5MB allowed']);
    exit;
}

$allowed_extensions = ['jpg', 'jpeg', 'png', 'webp', 'gif'];
$original_name = $file['name'] ?? '';
$extension = strtolower(pathinfo($original_name, PATHINFO_EXTENSION));
if (!in_array($extension, $allowed_extensions, true)) {
    http_response_code(400);
    echo json_encode(['success' => false, 'message' => 'Invalid image format']);
    exit;
}

$finfo = finfo_open(FILEINFO_MIME_TYPE);
$mime = finfo_file($finfo, $file['tmp_name']);
finfo_close($finfo);
$allowed_mimes = ['image/jpeg', 'image/png', 'image/webp', 'image/gif'];
if (!in_array($mime, $allowed_mimes, true)) {
    http_response_code(400);
    echo json_encode(['success' => false, 'message' => 'Invalid image MIME type']);
    exit;
}

$upload_dir_abs = __DIR__ . '/../assets/img/hero/uploads';
$upload_dir_rel = 'assets/img/hero/uploads';
if (!is_dir($upload_dir_abs) && !mkdir($upload_dir_abs, 0755, true)) {
    http_response_code(500);
    echo json_encode(['success' => false, 'message' => 'Failed to create upload directory']);
    exit;
}

$safe_filename = 'hero_' . date('Ymd_His') . '_' . bin2hex(random_bytes(4)) . '.' . $extension;
$target_abs = $upload_dir_abs . '/' . $safe_filename;
$target_rel = $upload_dir_rel . '/' . $safe_filename;

if (!move_uploaded_file($file['tmp_name'], $target_abs)) {
    http_response_code(500);
    echo json_encode(['success' => false, 'message' => 'Failed to upload image']);
    exit;
}

echo json_encode([
    'success' => true,
    'message' => 'Image uploaded successfully',
    'image_url' => $target_rel
]);
?>
