<?php
require_once '../../includes/config.php';
require_once '../../includes/auth.php';
require_once '../../includes/stories.php';

// Vérification de l'authentification
if (!Auth::check()) {
    http_response_code(401);
    exit(json_encode(['error' => 'Non autorisé']));
}

$input = json_decode(file_get_contents('php://input'), true);
$storyId = $input['storyId'] ?? '';
$chapterId = $input['chapterId'] ?? '';

if (!$storyId || !$chapterId) {
    http_response_code(400);
    exit(json_encode(['error' => 'Paramètres manquants']));
}

try {
    $story = Stories::get($storyId);
    if (!$story) {
        throw new Exception('Roman non trouvé');
    }

    // Filtrer les chapitres pour retirer celui à supprimer
    $story['chapters'] = array_values(array_filter($story['chapters'], function($chapter) use ($chapterId) {
        return $chapter['id'] !== $chapterId;
    }));

    // Sauvegarder les modifications
    Stories::save($story);

    echo json_encode(['success' => true]);
} catch (Exception $e) {
    http_response_code(500);
    echo json_encode(['error' => $e->getMessage()]);
}