<?php

namespace App\Controllers;

use App\Core\Controller;
use App\Services\ApkService;

class SitemapController extends Controller {
    
    public function index() {
        $apkService = new ApkService();
        $apks = $apkService->getAllApks();
        
        $db = db_pdo();
        $categories = $db->query("SELECT * FROM categories")->fetchAll();
        
        header("Content-Type: application/xml; charset=utf-8");
        
        $baseUrl = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? "https" : "http") . "://$_SERVER[HTTP_HOST]";
        
        echo '<?xml version="1.0" encoding="UTF-8"?>';
        echo '<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">';
        
        // Home
        echo '<url>';
        echo '<loc>' . $baseUrl . '/</loc>';
        echo '<priority>1.0</priority>';
        echo '<changefreq>daily</changefreq>';
        echo '</url>';
        
        // APKs
        foreach ($apks as $apk) {
            echo '<url>';
            echo '<loc>' . $baseUrl . '/apk/' . htmlspecialchars($apk['slug']) . '</loc>';
            echo '<lastmod>' . date('Y-m-d', strtotime($apk['created_at'] ?? 'now')) . '</lastmod>';
            echo '<priority>0.8</priority>';
            echo '<changefreq>weekly</changefreq>';
            echo '</url>';
        }
        
        // Blog Posts
        $posts = $db->query("SELECT * FROM posts WHERE status = 'published'")->fetchAll();
        foreach ($posts as $post) {
            echo '<url>';
            echo '<loc>' . $baseUrl . '/blog/' . htmlspecialchars($post['slug']) . '</loc>';
            echo '<lastmod>' . date('Y-m-d', strtotime($post['created_at'] ?? 'now')) . '</lastmod>';
            echo '<priority>0.7</priority>';
            echo '<changefreq>monthly</changefreq>';
            echo '</url>';
        }

        // Categories (if you have category pages, assuming /category/slug)
        foreach ($categories as $category) {
            echo '<url>';
            echo '<loc>' . $baseUrl . '/?category=' . htmlspecialchars($category['slug']) . '</loc>';
            echo '<priority>0.6</priority>';
            echo '<changefreq>weekly</changefreq>';
            echo '</url>';
        }
        
        echo '</urlset>';
    }
}
