<?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);
$originalCount = count($images);
$images = array_values(array_filter($images, fn($img) => $img['id'] !== $input['id']));

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

writeJSON(GALLERY_FILE, $images);
echo json_encode(['success' => true, 'deleted_id' => $input['id'], 'remaining' => count($images)]);
exit;
