<?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['id'])) {
    http_response_code(400);
    echo json_encode(['success' => false, 'error' => 'Image ID is required']);
    exit;
}

$images = readJSON(GALLERY_FILE);
$found = false;

foreach ($images as &$img) {
    if ($img['id'] === $input['id']) {
        $img['url']        = trim(htmlspecialchars($input['url'] ?? $img['url'], ENT_QUOTES, 'UTF-8'));
        $img['title']      = trim(htmlspecialchars($input['title'] ?? $img['title'], ENT_QUOTES, 'UTF-8'));
        $img['category']   = trim(htmlspecialchars($input['category'] ?? $img['category'], ENT_QUOTES, 'UTF-8'));
        $img['caption']    = trim(htmlspecialchars($input['caption'] ?? $img['caption'], ENT_QUOTES, 'UTF-8'));
        $img['alt']        = trim(htmlspecialchars($input['alt'] ?? $img['alt'], ENT_QUOTES, 'UTF-8'));
        $img['featured']   = !empty($input['featured']);
        $img['sort_order'] = intval($input['sort_order'] ?? $img['sort_order'] ?? 0);
        $found = true;
        break;
    }
}

if (!$found) {
    http_response_code(404);
    echo json_encode(['success' => false, 'error' => 'Image not found']);
    exit;
}

writeJSON(GALLERY_FILE, $images);
echo json_encode(['success' => true, 'image' => $img]);
exit;
