<?php
class Stories {
    private static $storiesDir = __DIR__ . '/../stories/';
    
    public static function getAll() {
        $stories = [];
        foreach (glob(self::$storiesDir . '*.json') as $file) {
            $story = json_decode(file_get_contents($file), true);
            $stories[] = $story;
        }
        return $stories;
    }
    
    public static function get($id) {
        $file = self::$storiesDir . $id . '.json';
        if (!file_exists($file)) {
            return null;
        }
        return json_decode(file_get_contents($file), true);
    }

    public static function formatDate($date) {
        if (strlen($date) > 10) { // Si la date contient aussi l'heure
            $datetime = DateTime::createFromFormat('Y-m-d H:i:s', $date);
            return $datetime ? $datetime->format('d/m/Y H:i') : '';
        } else { // Pour les anciennes dates sans heure
            $datetime = DateTime::createFromFormat('Y-m-d', $date);
            return $datetime ? $datetime->format('d/m/Y') : '';
        }
    }
    
    public static function save($story) {
        // Mise à jour de la date standard pour tout changement
        $story['updated'] = date('Y-m-d H:i:s');
        
        // Vérification si c'est une création initiale
        $isNew = !file_exists(self::$storiesDir . $story['id'] . '.json');
        
        // Vérification si un nouveau chapitre a été ajouté ou un chapitre est passé de draft à publié
        $existingStory = $isNew ? null : self::get($story['id']);
        $updatePublicDate = $isNew; // Déjà true si c'est un nouveau roman
        
        if (!$isNew && isset($existingStory['chapters']) && isset($story['chapters'])) {
            // Vérifier les nouveaux chapitres ou changements de statut
            foreach ($story['chapters'] as $chapter) {
                $found = false;
                foreach ($existingStory['chapters'] as $oldChapter) {
                    if ($oldChapter['id'] === $chapter['id']) {
                        $found = true;
                        // Chapitre passé de brouillon à publié
                        if (($oldChapter['draft'] ?? false) && !($chapter['draft'] ?? false)) {
                            $updatePublicDate = true;
                            // Ajouter une date de publication au chapitre
                            $chapter['published'] = date('Y-m-d H:i:s');
                        }
                        break;
                    }
                }
                // Nouveau chapitre
                if (!$found && !($chapter['draft'] ?? false)) {
                    $updatePublicDate = true;
                    // S'assurer que le nouveau chapitre a une date de publication
                    if (!isset($chapter['published'])) {
                        $chapter['published'] = date('Y-m-d H:i:s');
                    }
                }
            }
        }
        
        // Mettre à jour la date publique si nécessaire
        if ($updatePublicDate) {
            $story['publicUpdated'] = date('Y-m-d H:i:s');
        } else if (!isset($story['publicUpdated'])) {
            // S'assurer que le champ existe
            $story['publicUpdated'] = $story['created'] ?? date('Y-m-d H:i:s');
        }
        
        $file = self::$storiesDir . $story['id'] . '.json';
        return file_put_contents($file, json_encode($story, JSON_PRETTY_PRINT));
    }
}