<?php
// build/generate_index.php

$dir = __DIR__ . '/../content/';
$files = glob($dir . '*.md');
$articles = [];

foreach ($files as $file) {
    $content = file_get_contents($file);
    $filename = basename($file, '.md');
    
    $lines = explode("\n", $content);
    $title = isset($lines[0]) && strpos($lines[0], '#') === 0 ? trim(substr($lines[0], 1)) : ucfirst($filename);
    $slug = $filename;
    $date = date('Y-m-d');

    $articles[] = [
        'title' => $title,
        'slug' => $slug,
        'date' => $date,
        'excerpt' => substr(strip_tags($content), 0, 150) . '...'
    ];
}

usort($articles, function($a, $b) {
    return strtotime($b['date']) - strtotime($a['date']);
});

// OPRAVA CESTY: Uložit do public/data/
$outputDir = __DIR__ . '/../public/data/';

// Vytvoř složku, pokud neexistuje
if (!is_dir($outputDir)) {
    mkdir($outputDir, 0755, true);
}

file_put_contents($outputDir . 'articles.json', json_encode($articles, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE));
echo "Index vygenerován: " . count($articles) . " článků do " . $outputDir . "articles.json\n";