<?php

namespace App\Controllers;

use App\Models\PageModel;
use App\Models\ProductModel;
use App\Models\CategoryModel;

class Sitemap extends BaseController
{
    public function index()
    {
        $pageModel = new PageModel();
        $productModel = new ProductModel();
        $categoryModel = new CategoryModel();

        $pages = $pageModel->where('status', 1)->findAll();
        $products = $productModel->where('status', 1)->findAll();
        $categories = $categoryModel->where('status', 1)->findAll();

        $urls = [];

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

        // Pages
        foreach ($pages as $page) {
            // Home, products are already handled. About, contact, gallery are mapped.
            $slug = $page['slug'];
            if ($slug === 'home') continue;
            
            $urls[] = [
                'loc' => base_url($slug),
                'lastmod' => date('Y-m-d', strtotime($page['updated_at'] ?? date('Y-m-d'))),
                'changefreq' => 'weekly',
                'priority' => '0.8'
            ];
        }

        // Categories (could map to /products?category=ID or if they have their own route)
        // Currently categories are filtered on the products page via ?category=id
        foreach ($categories as $cat) {
            $urls[] = [
                'loc' => base_url('products?category=' . $cat['id']),
                'lastmod' => date('Y-m-d'),
                'changefreq' => 'weekly',
                'priority' => '0.7'
            ];
        }

        // Products
        foreach ($products as $prod) {
            $urls[] = [
                'loc' => base_url('product/' . $prod['slug']),
                'lastmod' => date('Y-m-d', strtotime($prod['updated_at'] ?? date('Y-m-d'))),
                'changefreq' => 'weekly',
                'priority' => '0.8'
            ];
        }

        // Return XML
        $this->response->setContentType('application/xml');
        
        $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']) . "</loc>\n";
            $xml .= "        <lastmod>" . esc($url['lastmod']) . "</lastmod>\n";
            $xml .= "        <changefreq>" . esc($url['changefreq']) . "</changefreq>\n";
            $xml .= "        <priority>" . esc($url['priority']) . "</priority>\n";
            $xml .= "    </url>\n";
        }

        $xml .= '</urlset>';

        return $xml;
    }
}
