<?php
/**
 * Dynamic Sitemap Generator for City-Service Pages
 * Full Absolute URL Fix - 2026 Updated
 */

require_once __DIR__ . '/includes/pdo.php';
include 'includes/url-helper.php';

// Set the base URL (Ensure no trailing slash)
$baseUrl = 'https://www.finggu.com'; 

/**
 * Helper function to ensure URLs are absolute
 */
function ensureAbsoluteUrl($url, $baseUrl) {
    $url = trim($url);
    // If the URL already starts with http or https, return it
    if (strpos($url, 'http') === 0) {
        return $url;
    }
    // Otherwise, prepend the baseUrl and clean up double slashes
    return $baseUrl . '/' . ltrim($url, '/');
}

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

// 1. Add Main Static Pages
$mainPages = [
    '' => ['priority' => '1.0', 'changefreq' => 'daily', 'file' => 'index.php'],
    'services.php' => ['priority' => '0.9', 'changefreq' => 'weekly', 'file' => 'services.php'],
    'about.php' => ['priority' => '0.8', 'changefreq' => 'monthly', 'file' => 'about.php'],
    'contact.php' => ['priority' => '0.8', 'changefreq' => 'monthly', 'file' => 'contact.php'],
    'portfolio.php' => ['priority' => '0.7', 'changefreq' => 'weekly', 'file' => 'portfolio.php'],
    'testimonials.php' => ['priority' => '0.7', 'changefreq' => 'weekly', 'file' => 'testimonials.php'],
    'city-services.php' => ['priority' => '0.9', 'changefreq' => 'weekly', 'file' => 'city-services.php']
];

foreach ($mainPages as $path => $settings) {
    $fullUrl = ensureAbsoluteUrl($path, $baseUrl);
    $lastmod = file_exists($settings['file']) ? date('Y-m-d', filemtime($settings['file'])) : date('Y-m-d');
    
    $xml .= "  <url>\n";
    $xml .= "    <loc>" . htmlspecialchars($fullUrl, ENT_QUOTES, 'UTF-8') . "</loc>\n";
    $xml .= "    <lastmod>{$lastmod}</lastmod>\n";
    $xml .= "    <changefreq>{$settings['changefreq']}</changefreq>\n";
    $xml .= "    <priority>{$settings['priority']}</priority>\n";
    $xml .= "  </url>\n";
}

// 2. Add Individual PHP Service Pages
$servicePages = [
    'services/web-design.php',
    'services/web-development.php',
    'services/ecommerce.php',
    'services/seo.php',
    'services/digital-marketing.php',
    'services/mobile-apps.php'
];

foreach ($servicePages as $page) {
    $fullUrl = ensureAbsoluteUrl($page, $baseUrl);
    $xml .= "  <url>\n";
    $xml .= "    <loc>" . htmlspecialchars($fullUrl, ENT_QUOTES, 'UTF-8') . "</loc>\n";
    $xml .= "    <lastmod>" . date('Y-m-d') . "</lastmod>\n";
    $xml .= "    <changefreq>weekly</changefreq>\n";
    $xml .= "    <priority>0.8</priority>\n";
    $xml .= "  </url>\n";
}

// 3. Add City-Service Combinations (Dynamic)
try {
    $stmt = $pdo->query("
        SELECT c.slug as city_slug, s.slug as service_slug, 
               COALESCE(cs.updated_at, cs.created_at, NOW()) as updated_at
        FROM city_service cs
        JOIN cities c ON cs.city_id = c.id
        JOIN services s ON cs.service_id = s.id
        ORDER BY c.name, s.name
    ");

    while ($row = $stmt->fetch()) {
        $lastmod = date('Y-m-d', strtotime($row['updated_at']));
        // Force absolute path using helper
        $relativeUrl = getCityServiceUrl($row['city_slug'], $row['service_slug']);
        $fullUrl = ensureAbsoluteUrl($relativeUrl, $baseUrl);
        
        $xml .= "  <url>\n";
        $xml .= "    <loc>" . htmlspecialchars($fullUrl, ENT_QUOTES, 'UTF-8') . "</loc>\n";
        $xml .= "    <lastmod>{$lastmod}</lastmod>\n";
        $xml .= "    <changefreq>weekly</changefreq>\n";
        $xml .= "    <priority>0.8</priority>\n";
        $xml .= "  </url>\n";
    }
} catch (PDOException $e) {
    // Silently log error or handle as needed
}

// 4. Add City Landing Pages
$cities = $pdo->query("SELECT slug FROM cities ORDER BY name")->fetchAll();
foreach ($cities as $city) {
    $relativeUrl = getCityServicesUrl($city['slug']);
    $fullUrl = ensureAbsoluteUrl($relativeUrl, $baseUrl);
    
    $xml .= "  <url>\n";
    $xml .= "    <loc>" . htmlspecialchars($fullUrl, ENT_QUOTES, 'UTF-8') . "</loc>\n";
    $xml .= "    <lastmod>" . date('Y-m-d') . "</lastmod>\n";
    $xml .= "    <changefreq>weekly</changefreq>\n";
    $xml .= "    <priority>0.7</priority>\n";
    $xml .= "  </url>\n";
}

// 5. Add Service Landing Pages
$services = $pdo->query("SELECT slug FROM services ORDER BY name")->fetchAll();
foreach ($services as $service) {
    $relativeUrl = getServiceCitiesUrl($service['slug']);
    $fullUrl = ensureAbsoluteUrl($relativeUrl, $baseUrl);
    
    $xml .= "  <url>\n";
    $xml .= "    <loc>" . htmlspecialchars($fullUrl, ENT_QUOTES, 'UTF-8') . "</loc>\n";
    $xml .= "    <lastmod>" . date('Y-m-d') . "</lastmod>\n";
    $xml .= "    <changefreq>weekly</changefreq>\n";
    $xml .= "    <priority>0.7</priority>\n";
    $xml .= "  </url>\n";
}

$xml .= '</urlset>';

// Save sitemap
file_put_contents('sitemap.xml', $xml);

// Update/Create robots.txt
$robots = "User-agent: *\nAllow: /\nDisallow: /admin/\nDisallow: /includes/\n\nSitemap: {$baseUrl}/sitemap.xml\n";
file_put_contents('robots.txt', $robots);

echo "✅ Sitemap generated with Absolute URLs!\n";
echo "📊 Total URLs: " . substr_count($xml, '<url>') . "\n";
?>