<?php

declare(strict_types=1);

/*
|--------------------------------------------------------------------------
| AZRAQ TECH XML Sitemap
|--------------------------------------------------------------------------
| Production sitemap
| Includes:
| - Static pages
| - Services
| - Industries
| - Projects
| - Blog posts
|--------------------------------------------------------------------------
*/

/*
|--------------------------------------------------------------------------
| Prevent PHP warnings/notices from corrupting XML
|--------------------------------------------------------------------------
*/

ini_set('display_errors', '0');
ini_set('display_startup_errors', '0');
error_reporting(0);

/*
|--------------------------------------------------------------------------
| Load application
|--------------------------------------------------------------------------
*/

require_once __DIR__ . '/../vendor/autoload.php';
require_once __DIR__ . '/../bootstrap.php';

use App\Core\Database;

/*
|--------------------------------------------------------------------------
| Configuration
|--------------------------------------------------------------------------
*/

$baseUrl = 'https://azraqtech.com';

/*
|--------------------------------------------------------------------------
| XML response
|--------------------------------------------------------------------------
*/

header('Content-Type: text/xml; charset=UTF-8');
header('Cache-Control: public, max-age=3600');

/*
|--------------------------------------------------------------------------
| XML escaping
|--------------------------------------------------------------------------
*/

function xmlEscape(?string $value): string
{
    if ($value === null) {
        return '';
    }

    return htmlspecialchars(
        $value,
        ENT_XML1 | ENT_QUOTES | ENT_SUBSTITUTE,
        'UTF-8'
    );
}

/*
|--------------------------------------------------------------------------
| Date validation
|--------------------------------------------------------------------------
*/

function sitemapDate(?string $date): ?string
{
    if (empty($date)) {
        return null;
    }

    $timestamp = strtotime($date);

    if ($timestamp === false) {
        return null;
    }

    return date('Y-m-d', $timestamp);
}

/*
|--------------------------------------------------------------------------
| Add URL
|--------------------------------------------------------------------------
*/

function addSitemapUrl(
    string $baseUrl,
    string $path,
    ?string $lastmod = null
): void {

    $path = '/' . ltrim($path, '/');

    $url = rtrim($baseUrl, '/') . $path;

    echo "    <url>\n";

    echo "        <loc>";
    echo xmlEscape($url);
    echo "</loc>\n";

    if ($lastmod !== null) {
        echo "        <lastmod>";
        echo xmlEscape($lastmod);
        echo "</lastmod>\n";
    }

    echo "    </url>\n";
}

/*
|--------------------------------------------------------------------------
| XML document
|--------------------------------------------------------------------------
*/

echo '<?xml version="1.0" encoding="UTF-8"?>';
echo "\n";

echo '<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">';
echo "\n";

/*
|--------------------------------------------------------------------------
| STATIC PAGES
|--------------------------------------------------------------------------
|
| Only include pages that should be publicly indexed.
|
*/

$staticPages = [
    '/',
    '/about',
    '/services',
    '/industries',
    '/projects',
    '/blog',
    '/faq',
    '/contact',

    '/equipment',
    '/maintenance',
    '/inspection-certification',
    '/technical-consulting',
    '/embedded-systems',
    '/agricultural-machinery',
];

/*
|--------------------------------------------------------------------------
| Add static pages
|--------------------------------------------------------------------------
*/

foreach ($staticPages as $page) {

    addSitemapUrl(
        $baseUrl,
        $page
    );
}

/*
|--------------------------------------------------------------------------
| SERVICES
|--------------------------------------------------------------------------
*/

try {

    $services = Database::fetchAll(
        "
        SELECT
            slug,
            updated_at
        FROM services
        WHERE is_active = 1
        AND slug IS NOT NULL
        AND slug != ''
        "
    );

    foreach ($services as $service) {

        $slug = trim(
            (string) ($service['slug'] ?? '')
        );

        if ($slug === '') {
            continue;
        }

        /*
        | Do not encode the complete URL.
        | Encode only the slug.
        */

        $slug = rawurlencode($slug);

        $lastmod = sitemapDate(
            $service['updated_at'] ?? null
        );

        addSitemapUrl(
            $baseUrl,
            '/services/' . $slug,
            $lastmod
        );
    }

} catch (\Throwable $e) {

    /*
    | Sitemap should continue even if
    | database content has a problem.
    */
}

/*
|--------------------------------------------------------------------------
| INDUSTRIES
|--------------------------------------------------------------------------
*/

try {

    $industries = Database::fetchAll(
        "
        SELECT
            slug,
            updated_at
        FROM industries
        WHERE is_active = 1
        AND slug IS NOT NULL
        AND slug != ''
        "
    );

    foreach ($industries as $industry) {

        $slug = trim(
            (string) ($industry['slug'] ?? '')
        );

        if ($slug === '') {
            continue;
        }

        $slug = rawurlencode($slug);

        $lastmod = sitemapDate(
            $industry['updated_at'] ?? null
        );

        addSitemapUrl(
            $baseUrl,
            '/industries/' . $slug,
            $lastmod
        );
    }

} catch (\Throwable $e) {
}

/*
|--------------------------------------------------------------------------
| PROJECTS
|--------------------------------------------------------------------------
*/

try {

    $projects = Database::fetchAll(
        "
        SELECT
            slug,
            updated_at
        FROM projects
        WHERE status = 'completed'
        AND slug IS NOT NULL
        AND slug != ''
        "
    );

    foreach ($projects as $project) {

        $slug = trim(
            (string) ($project['slug'] ?? '')
        );

        if ($slug === '') {
            continue;
        }

        $slug = rawurlencode($slug);

        $lastmod = sitemapDate(
            $project['updated_at'] ?? null
        );

        addSitemapUrl(
            $baseUrl,
            '/projects/' . $slug,
            $lastmod
        );
    }

} catch (\Throwable $e) {
}

/*
|--------------------------------------------------------------------------
| BLOG POSTS
|--------------------------------------------------------------------------
*/

try {

    $posts = Database::fetchAll(
        "
        SELECT
            slug,
            published_at
        FROM blog_posts
        WHERE status = 'published'
        AND slug IS NOT NULL
        AND slug != ''
        "
    );

    foreach ($posts as $post) {

        $slug = trim(
            (string) ($post['slug'] ?? '')
        );

        if ($slug === '') {
            continue;
        }

        $slug = rawurlencode($slug);

        $lastmod = sitemapDate(
            $post['published_at'] ?? null
        );

        addSitemapUrl(
            $baseUrl,
            '/blog/' . $slug,
            $lastmod
        );
    }

} catch (\Throwable $e) {
}

/*
|--------------------------------------------------------------------------
| CLOSE XML
|--------------------------------------------------------------------------
*/

echo '</urlset>';

exit;