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

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    echo json_encode(['success' => false, 'error' => 'Method not allowed']);
    exit;
}

$input = json_decode(file_get_contents('php://input'), true) ?? $_POST;

if (empty($input['url']) || empty($input['title'])) {
    http_response_code(400);
    echo json_encode(['success' => false, 'error' => 'URL and title are required']);
    exit;
}

$images = readJSON(GALLERY_FILE);
$newImage = [
    'id'         => 'img-' . strtoupper(substr(uniqid(), -4)),
    'filename'   => 'gallery_' . (count($images) + 1),
    'url'        => trim(htmlspecialchars($input['url'], ENT_QUOTES, 'UTF-8')),
    'title'      => trim(htmlspecialchars($input['title'], ENT_QUOTES, 'UTF-8')),
    'category'   => trim(htmlspecialchars($input['category'] ?? 'expo', ENT_QUOTES, 'UTF-8')),
    'caption'    => trim(htmlspecialchars($input['caption'] ?? '', ENT_QUOTES, 'UTF-8')),
    'alt'        => trim(htmlspecialchars($input['alt'] ?? $input['title'], ENT_QUOTES, 'UTF-8')),
    'featured'   => !empty($input['featured']),
    'sort_order' => intval($input['sort_order'] ?? count($images) + 1),
    'uploaded_at'=> date('Y-m-d')
];

$images[] = $newImage;
writeJSON(GALLERY_FILE, $images);

echo json_encode(['success' => true, 'image' => $newImage]);
exit;
