<?php
// Start output buffering to prevent any stray whitespace from breaking the XML.
ob_start();

// Suppress PHP errors from displaying, as they would invalidate the XML format.
ini_set('display_errors', 0);
ini_set('display_startup_errors', 0);
error_reporting(0);

// Set the correct XML header for the sitemap.
header('Content-Type: application/xml; charset=UTF-8');

// Output the XML declaration and the root <urlset> element with its namespace.
echo '<?xml version="1.0" encoding="UTF-8"?>';
echo '<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">';

// --- Configuration ---
// Base URL of your website. This is prepended to all relative URLs.
$baseUrl = 'https://www.swarnavahini.lk/';

// --- Static Pages ---
// An array of your website's main static pages.
// The `lastmod` date is now dynamically generated based on the file's actual modification time.
$staticPages = [
    ['url' => '', 'priority' => '1.0'],
    ['url' => 'pages/teledramas.php', 'priority' => '0.8'],
    ['url' => 'pages/programmes.php', 'priority' => '0.8'],
    ['url' => 'pages/contact_form_with_map.php', 'priority' => '0.6'],
    ['url' => 'pages/live.php', 'priority' => '0.9']
];

$allPages = [];
foreach ($staticPages as $page) {
    // Construct the full file path to check its modification time.
    $filePath = __DIR__ . '/' . ltrim($page['url'], '/');
    if (file_exists($filePath)) {
        // Use the file's modification time for <lastmod>, formatted to W3C Datetime standard.
        $page['lastmod'] = date('c', filemtime($filePath));
    } else {
        // Fallback to the current date if the file doesn't exist for some reason.
        $page['lastmod'] = date('c');
    }
    $allPages[] = $page;
}


// --- Dynamic Pages from Database ---
// Include your database connection script. Ensure the path is correct.
require_once __DIR__ . '/components/db_connect.php';

/**
 * Fetches dynamic URLs from a given database table and adds them to the pages array.
 *
 * @param PDO $connection The active PDO database connection.
 * @param array &$pages The array of pages to append to.
 * @param string $tableName The name of the database table to query.
 * @param float $priority The SEO priority to assign to these URLs.
 */
function fetchDynamicUrls($connection, &$pages, $tableName, $priority) {
    try {
        // Prepare and execute the query to select URLs and their last modification dates.
        $stmt = $connection->query("SELECT url, last_modified FROM " . $tableName);
        while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
            // Ensure the URL from the database is not empty.
            if (!empty($row['url'])) {
                // Check if last_modified is valid, otherwise use current date as a fallback.
                $lastmod = !empty($row['last_modified']) && strtotime($row['last_modified']) !== false
                    ? date('c', strtotime($row['last_modified']))
                    : date('c');
                
                // Add the dynamic page to the main pages array.
                $pages[] = [
                    'url'      => $row['url'],
                    'lastmod'  => $lastmod,
                    'priority' => $priority
                ];
            }
        }
    } catch (Exception $e) {
        // If the query fails, we fail silently to prevent breaking the XML output.
        // In a real-world scenario, you might want to log this error.
        // error_log("Sitemap generation failed for table '$tableName': " . $e->getMessage());
    }
}

// Fetch URLs from the 'teledramas', 'programmes', and 'news' tables.
fetchDynamicUrls($conn, $allPages, 'teledramas', '0.7');
fetchDynamicUrls($conn, $allPages, 'programmes', '0.7');
fetchDynamicUrls($conn, $allPages, 'news', '0.6');


// --- Generate and Output the Final XML ---
foreach ($allPages as $page) {
    // Construct the full, absolute URL.
    $loc = rtrim($baseUrl, '/') . '/' . ltrim($page['url'], '/');

    echo '<url>';
    // Use htmlspecialchars to escape any special XML characters in the URL.
    echo '<loc>' . htmlspecialchars($loc, ENT_XML1, 'UTF-8') . '</loc>';
    echo '<lastmod>' . $page['lastmod'] . '</lastmod>';
    // Assuming content is updated weekly; you can change this to 'daily', 'monthly', etc.
    echo '<changefreq>weekly</changefreq>';
    echo '<priority>' . htmlspecialchars($page['priority'], ENT_XML1, 'UTF-8') . '</priority>';
    echo '</url>';
}

// Close the <urlset> root element.
echo '</urlset>';

// Flush the output buffer and send the complete XML to the browser.
ob_end_flush();
exit;
