<?php
// Chemin vers le fichier RSS
$rssFilePath = 'rss.xml';
$cacheDuration = 3600; // Durée de vie du cache en secondes

// Si le fichier RSS est inexistant ou le cache est expiré, on regénère le flux RSS
if (!file_exists($rssFilePath) || (time() - filemtime($rssFilePath)) > $cacheDuration) {
    
    $directoryPath = 'assets/fiches';
    $files = glob($directoryPath . '/*.html');

    // Filtrage et tri des fichiers (les plus récents en premier)
    $files = array_filter($files, function($filename) {
        return !preg_match('/\/(art_|lien_)/', $filename);
    });
    usort($files, function ($a, $b) {
        return filemtime($b) - filemtime($a);
    });
    $files = array_slice($files, 0, 20);

    // Initialisation du flux RSS
    $fluxRSS = '<?xml version="1.0" encoding="UTF-8"?>';
    $fluxRSS .= '<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom">';
    $fluxRSS .= '<channel>';
    $fluxRSS .= '<atom:link href="https://technifree.com/rss.xml" rel="self" type="application/rss+xml" />';
    $fluxRSS .= '<title>Technifree.com : Les nouveautés</title>';
    $fluxRSS .= '<link>https://technifree.com</link>';
    $fluxRSS .= '<description>Bienvenue dans un monde libre !</description>';

    // Fonctions d'extraction
    function extractDescription($filePath) {
        $content = file_get_contents($filePath);
        $startImgTag = strpos($content, 'class="imagezoom" >');
        if ($startImgTag !== false) {
            $startP = strpos($content, '<p>', $startImgTag);
            if ($startP !== false) {
                $end = strpos($content, '</p>', $startP);
                $paragraphContent = substr($content, $startP + 3, $end - $startP);
                return implode(' ', array_slice(explode(' ', strip_tags($paragraphContent)), 0, 150));
            }
        }
        return '';
    }

    function extractVersionNumber($filePath) {
        $content = file_get_contents($filePath);
        preg_match('/<li>Version <span><b>(.*?)<\/b><\/span><\/li>/', $content, $matches);
        return $matches[1] ?? 'Non spécifiée';
    }

    function getLastUpdateDate($filePath) {
        $timestamp = filemtime($filePath);
    if ($timestamp === false) {
        // Affiche un message d'erreur si filemtime échoue
        error_log("Erreur : impossible d'obtenir la date de modification pour le fichier " . $filePath);
        return 'Date inconnue';
    }
    return date("d/m/Y", $timestamp); 
}

    function extractImagePath($filePath) {
        $content = file_get_contents($filePath);
        $startSequence = strpos($content, '<hr></h4>');
        if ($startSequence !== false) {
            $startImgTag = strpos($content, '<img src="', $startSequence);
            if ($startImgTag !== false) {
                $startSrcAttr = $startImgTag + 10;
                $endSrcAttr = strpos($content, '"', $startSrcAttr);
                return substr($content, $startSrcAttr, $endSrcAttr - $startSrcAttr);
            }
        }
        return 'default-image-path';
    }

    // Génération des items RSS
    foreach ($files as $file) {
        //echo "Fichier traité : " . basename($file) . "<br>";
    
        // Génération des éléments <item> pour chaque fichier
        $fileNameWithoutExtension = basename($file, '.html');
        $title = str_replace('_', ' ', $fileNameWithoutExtension);
        $versionNumber = extractVersionNumber($file);
        $lastUpdateDate = getLastUpdateDate($file); 
        $timestamp = filemtime($file); 
        $description = extractDescription($file);
        $imagePath = extractImagePath($file);
        $link = 'https://technifree.com/' . $directoryPath . '/' . basename($file);
    
        $fluxRSS .= '<item>';
        $fluxRSS .= '<title>' . htmlspecialchars($title) . '</title>';
        $fluxRSS .= '<link>' . htmlspecialchars($link) . '</link>';
        $fluxRSS .= '<description><![CDATA[<div><br/>&bull; Version : <strong>' . htmlspecialchars($versionNumber) . '</strong><br/>&bull; Mis à jour le : <strong>' . htmlspecialchars($lastUpdateDate) . '</strong></div><br/><img src="' . htmlspecialchars($imagePath) . '" alt=""/><p>' . htmlspecialchars($description) . '</p>]]></description>';
        $fluxRSS .= '<pubDate>' . date(DATE_RSS, $timestamp) . '</pubDate>';
        $fluxRSS .= '</item>';
    }


    // Clôture du flux RSS
    $fluxRSS .= '</channel>';
    $fluxRSS .= '</rss>';

    // Écriture du flux RSS dans le fichier
    file_put_contents($rssFilePath, $fluxRSS);
}
?>
