<?php
/**
 * Dynamic XML Sitemap Generator for BeBacklink.com
 * Lightweight version - Direct database access
 * @package    BeBacklink
 * @copyright  Copyright (C) 2026 BeBacklink.com. All rights reserved.
 * @license    GNU General Public License version 2 or later
 */

// Set correct header for XML
header('Content-Type: application/xml; charset=utf-8');

// Load Joomla configuration
define('_JEXEC', 1);
require_once __DIR__ . '/configuration.php';

$config = new JConfig();

// Connect to database
try {
    $mysqli = new mysqli($config->host, $config->user, $config->password, $config->db);
    if ($mysqli->connect_error) {
        die('Connection failed: ' . $mysqli->connect_error);
    }
    $mysqli->set_charset('utf8mb4');
} catch (Exception $e) {
    die('Database error: ' . $e->getMessage());
}

// Get base URL - try to detect from server or use live_site
$baseUrl = !empty($config->live_site) ? rtrim($config->live_site, '/') : 'https://bebacklink.com';

// Function to create SEF URL
function createUrl($link, $baseUrl) {
    // Simple URL builder
    if (strpos($link, 'index.php?') === 0) {
        parse_str(substr($link, 10), $params);

        if (isset($params['option']) && $params['option'] === 'com_content') {
            if (isset($params['view']) && $params['view'] === 'article' && isset($params['id'])) {
                // Get article alias from database
                global $mysqli, $config;
                $id = (int)$params['id'];
                $result = $mysqli->query("SELECT alias FROM {$config->dbprefix}content WHERE id = $id");
                if ($result && $row = $result->fetch_assoc()) {
                    return $baseUrl . '/' . $row['alias'];
                }
            } elseif (isset($params['view']) && $params['view'] === 'category' && isset($params['id'])) {
                // Category view
                global $mysqli, $config;
                $id = (int)$params['id'];
                $result = $mysqli->query("SELECT alias FROM {$config->dbprefix}categories WHERE id = $id");
                if ($result && $row = $result->fetch_assoc()) {
                    return $baseUrl . '/category/' . $row['alias'];
                }
            }
        } elseif (isset($params['option']) && $params['option'] === 'com_contact') {
            return $baseUrl . '/contact';
        } elseif (isset($params['option']) && $params['option'] === 'com_users') {
            if (isset($params['view']) && $params['view'] === 'login') {
                return $baseUrl . '/login';
            } elseif (isset($params['view']) && $params['view'] === 'registration') {
                return $baseUrl . '/register';
            }
        }
    }

    return $baseUrl . '/' . ltrim($link, '/');
}

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

$processedUrls = [];

// 1. Homepage - Highest priority
echo "  <url>\n";
echo "    <loc>" . htmlspecialchars($baseUrl) . "/</loc>\n";
echo "    <lastmod>" . date('c') . "</lastmod>\n";
echo "    <changefreq>daily</changefreq>\n";
echo "    <priority>1.0</priority>\n";
echo "  </url>\n";
$processedUrls[] = $baseUrl . '/';

// 2. Get all published articles
$query = "SELECT a.id, a.title, a.alias, a.catid, a.created, a.modified, a.images
          FROM {$config->dbprefix}content AS a
          WHERE a.state = 1
          ORDER BY a.created DESC";

$result = $mysqli->query($query);

if ($result) {
    while ($article = $result->fetch_assoc()) {
        $url = $baseUrl . '/' . $article['alias'];

        // Skip if already processed
        if (in_array($url, $processedUrls)) {
            continue;
        }
        $processedUrls[] = $url;

        // Use modified date if available, otherwise created date
        $lastmod = ($article['modified'] !== '0000-00-00 00:00:00' && !empty($article['modified']))
            ? date('c', strtotime($article['modified']))
            : date('c', strtotime($article['created']));

        echo "  <url>\n";
        echo "    <loc>" . htmlspecialchars($url) . "</loc>\n";
        echo "    <lastmod>" . $lastmod . "</lastmod>\n";
        echo "    <changefreq>monthly</changefreq>\n";
        echo "    <priority>0.7</priority>\n";

        // Add image if available
        if (!empty($article['images'])) {
            $images = json_decode($article['images'], true);
            if (isset($images['image_fulltext']) && !empty($images['image_fulltext'])) {
                $imageUrl = $baseUrl . '/' . ltrim($images['image_fulltext'], '/');
                echo "    <image:image>\n";
                echo "      <image:loc>" . htmlspecialchars($imageUrl) . "</image:loc>\n";
                if (isset($images['image_fulltext_alt']) && !empty($images['image_fulltext_alt'])) {
                    echo "      <image:caption>" . htmlspecialchars($images['image_fulltext_alt']) . "</image:caption>\n";
                }
                echo "    </image:image>\n";
            }
        }

        echo "  </url>\n";
    }
}

// 3. Get all published categories
$query = "SELECT c.id, c.title, c.alias, c.modified_time
          FROM {$config->dbprefix}categories AS c
          WHERE c.published = 1
          AND c.extension = 'com_content'
          AND c.id > 1
          ORDER BY c.lft ASC";

$result = $mysqli->query($query);

if ($result) {
    while ($category = $result->fetch_assoc()) {
        $url = $baseUrl . '/category/' . $category['alias'];

        // Skip if already processed
        if (in_array($url, $processedUrls)) {
            continue;
        }
        $processedUrls[] = $url;

        $lastmod = ($category['modified_time'] !== '0000-00-00 00:00:00' && !empty($category['modified_time']))
            ? date('c', strtotime($category['modified_time']))
            : date('c');

        echo "  <url>\n";
        echo "    <loc>" . htmlspecialchars($url) . "</loc>\n";
        echo "    <lastmod>" . $lastmod . "</lastmod>\n";
        echo "    <changefreq>weekly</changefreq>\n";
        echo "    <priority>0.6</priority>\n";
        echo "  </url>\n";
    }
}

// 4. Add important static pages
$staticPages = [
    ['url' => '/about', 'priority' => '0.8', 'changefreq' => 'monthly'],
    ['url' => '/contact', 'priority' => '0.9', 'changefreq' => 'monthly'],
    ['url' => '/blog', 'priority' => '0.8', 'changefreq' => 'daily'],
    ['url' => '/services', 'priority' => '0.9', 'changefreq' => 'weekly'],
    ['url' => '/pricing', 'priority' => '0.9', 'changefreq' => 'weekly'],
    ['url' => '/privacy-policy', 'priority' => '0.5', 'changefreq' => 'yearly'],
    ['url' => '/terms-service', 'priority' => '0.5', 'changefreq' => 'yearly'],
];

foreach ($staticPages as $page) {
    $fullUrl = $baseUrl . $page['url'];

    // Skip if already processed
    if (in_array($fullUrl, $processedUrls)) {
        continue;
    }
    $processedUrls[] = $fullUrl;

    echo "  <url>\n";
    echo "    <loc>" . htmlspecialchars($fullUrl) . "</loc>\n";
    echo "    <lastmod>" . date('c') . "</lastmod>\n";
    echo "    <changefreq>" . $page['changefreq'] . "</changefreq>\n";
    echo "    <priority>" . $page['priority'] . "</priority>\n";
    echo "  </url>\n";
}

// Close database connection
$mysqli->close();

// Close XML
echo "</urlset>";
