<?php

namespace App\Services\Seo;

use Config\Database;

class SitemapService
{
    public function generate(): string
    {
        $xml = new \SimpleXMLElement('<?xml version="1.0" encoding="UTF-8"?><urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"/>');

        $this->addStaticUrls($xml);
        $this->addJobUrls($xml);
        $this->addAgencyUrls($xml);

        return $xml->asXML();
    }

    private function addStaticUrls(\SimpleXMLElement $xml): void
    {
        foreach (['/', '/jobs', '/about', '/contact'] as $path) {
            $url = $xml->addChild('url');
            $url->addChild('loc', base_url($path));
            $url->addChild('changefreq', 'daily');
        }
    }

    private function addJobUrls(\SimpleXMLElement $xml): void
    {
        $jobs = Database::connect()->table('jobs')
            ->select('seo_slug, updated_at')
            ->where('status', 'published')
            ->groupStart()->where('expires_at >=', date('Y-m-d'))->orWhere('expires_at', null)->groupEnd()
            ->get()->getResultArray();

        foreach ($jobs as $job) {
            $url = $xml->addChild('url');
            $url->addChild('loc', htmlspecialchars(base_url('jobs/' . $job['seo_slug'])));
            $url->addChild('lastmod', date('Y-m-d', strtotime($job['updated_at'])));
            $url->addChild('changefreq', 'weekly');
        }
    }

    private function addAgencyUrls(\SimpleXMLElement $xml): void
    {
        $agencies = Database::connect()->table('agencies')
            ->select('slug, updated_at')->where('status', 'active')
            ->get()->getResultArray();

        foreach ($agencies as $agency) {
            $url = $xml->addChild('url');
            $url->addChild('loc', htmlspecialchars(base_url('agencies/' . $agency['slug'])));
            $url->addChild('lastmod', date('Y-m-d', strtotime($agency['updated_at'])));
            $url->addChild('changefreq', 'monthly');
        }
    }
}
