<?php

namespace App\Modules\Frontend\Controllers;

use App\Controllers\BaseCLontroller;
use App\Modules\Frontend\Models\TourModel;
use App\Modules\Frontend\Models\BlogPostModel;
use CodeIgniter\HTTP\Response;

class SeoController extends BaseController
{
    public function sitemap()
    {
        $tourModel = new TourModel();
        $blogModel = new BlogPostModel();

        $tours = $tourModel->where('is_active', 1)->findAll();
        $posts = $blogModel->where('is_published', 1)->findAll();

        $urls = [];

        // Home
        $urls[] = [
            'loc' => base_url(),
            'lastmod' => date('Y-m-d'),
            'changefreq' => 'daily',
            'priority' => '1.0'
        ];

        // Tours
        foreach ($tours as $tour) {
            $urls[] = [
                'loc' => base_url("tours/{$tour['slug']}"),
                'lastmod' => date('Y-m-d', strtotime($tour['created_at'])),
                'changefreq' => 'monthly',
                'priority' => '0.8'
            ];
        }

        // Blog posts
        foreach ($posts as $post) {
            $urls[] = [
                'loc' => base_url("blog/{$post['slug']}"),
                'lastmod' => date('Y-m-d', strtotime($post['created_at'])),
                'changefreq' => 'monthly',
                'priority' => '0.7'
            ];
        }

        $xml = '<?xml version="1.0" encoding="UTF-8"?>' . "\n";
        $xml .= '<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">' . "\n";

        foreach ($urls as $url) {
            $xml .= "  <url>\n";
            $xml .= "    <loc>" . esc($url['loc'], 'html') . "</loc>\n";
            $xml .= "    <lastmod>{$url['lastmod']}</lastmod>\n";
            $xml .= "    <changefreq>{$url['changefreq']}</changefreq>\n";
            $xml .= "    <priority>{$url['priority']}</priority>\n";
            $xml .= "  </url>\n";
        }

        $xml .= '</urlset>';

        return $this->response
            ->setHeader('Content-Type', 'application/xml')
            ->setBody($xml);
    }
}