Lectures/admin/api/save-chapter.php

49 lines
1.3 KiB
PHP

<?php
require_once '../../includes/config.php';
require_once '../../includes/auth.php';
require_once '../../includes/stories.php';
if (!Auth::check()) {
http_response_code(401);
exit('Non autorisé');
}
$input = json_decode(file_get_contents('php://input'), true);
$storyId = $input['storyId'] ?? null;
$chapterId = $input['chapterId'] ?? null;
$title = $input['title'] ?? '';
$content = $input['content'] ?? '';
try {
$story = Stories::get($storyId);
if (!$story) {
throw new Exception('Roman non trouvé');
}
if ($chapterId) {
// Mise à jour d'un chapitre existant
foreach ($story['chapters'] as &$chapter) {
if ($chapter['id'] == $chapterId) {
$chapter['title'] = $title;
$chapter['content'] = $content;
$chapter['updated'] = date('Y-m-d');
break;
}
}
} else {
// Nouveau chapitre
$story['chapters'][] = [
'id' => uniqid(),
'title' => $title,
'content' => $content,
'created' => date('Y-m-d'),
'updated' => date('Y-m-d')
];
}
Stories::save($story);
echo json_encode(['success' => true]);
} catch (Exception $e) {
http_response_code(500);
echo json_encode(['error' => $e->getMessage()]);
}