<?php

namespace Core;

use Models\Page;

class SSG
{
    public static function generate($baseUrl)
    {
        $exportDir = __DIR__ . '/../../static_export/';
        if (!is_dir($exportDir)) mkdir($exportDir, 0777, true);

        $pages = Page::all();
        foreach ($pages as $page) {
            if ($page['status'] !== 'published') continue;

            $slug = $page['slug'] === 'home' ? 'index' : $page['slug'];
            $url = $baseUrl . '/' . ($page['slug'] === 'home' ? '' : $page['slug']);
            
            $content = file_get_contents($url);
            file_put_contents($exportDir . $slug . '.html', $content);
        }

        // Copy assets
        self::copyDir(__DIR__ . '/../../public/uploads', $exportDir . 'uploads');
        
        return $exportDir;
    }

    private static function copyDir($src, $dst)
    {
        if (!is_dir($src)) return;
        @mkdir($dst);
        $files = scandir($src);
        foreach ($files as $file) {
            if ($file != "." && $file != "..") {
                if (is_dir("$src/$file")) self::copyDir("$src/$file", "$dst/$file");
                else copy("$src/$file", "$dst/$file");
            }
        }
    }
}
