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

// Récupération de l'ID du roman depuis l'URL
$storyId = $_GET['id'] ?? '';
if (!$storyId) {
    header('Location: index.php');
    exit;
}

// Chargement du roman
$story = Stories::get($storyId);
if (!$story) {
    header('Location: index.php');
    exit;
}

// Fonction pour convertir le contenu Delta en HTML
function deltaToHtml($content) {
    if (empty($content)) return '';
    
    // Si le contenu est déjà en HTML
    if (is_string($content) && !isJson($content)) {
        // Nettoyer les URLs des images dans le HTML
        return preg_replace_callback(
            '/<img[^>]+src=([\'"])((?:\.\.\/)*(?:assets\/[^"\']+))\1[^>]*>/',
            function($matches) {
                // $matches[2] contient l'URL
                $cleanUrl = preg_replace('/^(?:\.\.\/)+/', '', $matches[2]);
                return str_replace($matches[2], $cleanUrl, $matches[0]);
            },
            $content
        );
    }
    
    // Convertir la chaîne JSON en tableau si nécessaire
    if (is_string($content)) {
        $delta = json_decode($content, true);
    } else {
        $delta = $content;
    }
    
    if (!isset($delta['ops'])) return '';
    
    $html = '';
    foreach ($delta['ops'] as $op) {
        if (is_string($op['insert'])) {
            $text = htmlspecialchars($op['insert']);
            
            // Gérer les styles de texte
            if (isset($op['attributes'])) {
                if (!empty($op['attributes']['bold'])) {
                    $text = "<strong>{$text}</strong>";
                }
                if (!empty($op['attributes']['italic'])) {
                    $text = "<em>{$text}</em>";
                }
                if (!empty($op['attributes']['underline'])) {
                    $text = "<u>{$text}</u>";
                }
                // Ajouter d'autres styles si nécessaire
            }
            
            // Convertir les retours à la ligne en paragraphes
            if ($text === "\n") {
                $html .= "<br>";
            } else {
                $html .= $text;
            }
        } 
        // Gérer les images
            elseif (is_array($op['insert']) && isset($op['insert']['image'])) {
                $imageUrl = $op['insert']['image'];
                error_log('URL originale: ' . $imageUrl);
                // Retirer tous les "../" au début de l'URL
                $imageUrl = preg_replace('/^(?:\.\.\/)+/', '', $imageUrl);
                error_log('URL nettoyée: ' . $imageUrl);
                $html .= "<img src=\"{$imageUrl}\" alt=\"Image du chapitre\">";
            }
    }
    
    // Envelopper le contenu dans des balises p si nécessaire
    if (!empty($html)) {
        $paragraphs = explode("\n\n", $html);
        $html = '';
        foreach ($paragraphs as $p) {
            if (trim($p) !== '') {
                $html .= "<p>{$p}</p>";
            }
        }
    }
    
    return $html;
}

function isJson($string) {
    json_decode($string);
    return json_last_error() === JSON_ERROR_NONE;
}

$config = Config::load();
?>
<!DOCTYPE html>
<html lang="fr">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?= htmlspecialchars($story['title']) ?> - <?= htmlspecialchars($config['site']['name']) ?></title>
    
    <?php if (file_exists(__DIR__ . '/assets/images/site/favicon.png')): ?>
        <link rel="icon" type="image/png" href="assets/images/site/favicon.png">
    <?php endif; ?>
    
    <link rel="stylesheet" href="assets/css/public.css">
    
    <meta name="description" content="<?= htmlspecialchars(strip_tags($story['description'])) ?>">
</head>
<body>
    <!-- En-tête avec image de fond -->
    <header class="novel-header">
        <?php if (!empty($story['cover'])): ?>
            <div class="novel-header-background" style="background-image: url('<?= htmlspecialchars($story['cover']) ?>');"></div>
        <?php endif; ?>
        <h1><?= htmlspecialchars($story['title']) ?></h1>
    </header>

    <!-- Contenu principal -->
    <div class="novel-content">
        <div class="novel-description">
            <?= deltaToHtml($story['description']) ?>
        </div>

        <aside class="chapters-menu">
            <h2>Chapitres</h2>
            <?php if (!empty($story['chapters'])): ?>
                <ul class="chapters-list">
                    <?php foreach ($story['chapters'] as $index => $chapter): ?>
                        <li>
                            <a href="chapitre.php?story=<?= urlencode($story['id']) ?>&chapter=<?= urlencode($chapter['id']) ?>">
                                <?= htmlspecialchars($chapter['title']) ?>
                            </a>
                        </li>
                    <?php endforeach; ?>
                </ul>
            <?php else: ?>
                <p>Aucun chapitre disponible pour le moment.</p>
            <?php endif; ?>
        </aside>
    </div>

    <?php if (!empty($config['site']['name'])): ?>
        <div class="back-to-home">
            <a href="index.php">&larr; Retour à l'accueil</a>
        </div>
    <?php endif; ?>
</body>
</html>