<?php
/*
 * Dynamic XML Sitemap — GuatemalaPhotoStock
 * Includes: static pages, public galleries, all active media
 * Submit to Google Search Console: https://guatemalaphotostock.com/sitemap.php
 */

error_reporting(0);
ini_set('display_errors', '0');

define('BASE_PATH', dirname(__FILE__));

/* ------------------------------------------------------------------ */
/* Minimal bootstrap — DB only, skip full initialize.php              */
/* ------------------------------------------------------------------ */

require_once BASE_PATH . '/assets/includes/db.config.php';

// db.conn.php needs $config and $page to be present to avoid notices
$config = [];
$page   = '';
require_once BASE_PATH . '/assets/includes/db.conn.php';

// Functions we need
require_once BASE_PATH . '/assets/includes/enc.functions.php';

// Inline cleanForSEO — avoids loading full public.functions.php in CLI context
if (!function_exists('cleanForSEO')) {
    function cleanForSEO($input) {
        $clean = str_replace('/', '', $input);
        $clean = str_replace(' ', '-', $clean);
        $clean = str_replace("'", '', $clean);
        $clean = str_replace('%', '', $clean);
        $clean = str_replace('"', '', $clean);
        return $clean;
    }
}

// Get site URL directly from DB
$_settingsRow = mysqli_fetch_assoc(mysqli_query($db,
    "SELECT site_url FROM {$dbinfo['pre']}settings WHERE settings_id = 1"));

$siteURL    = rtrim($_settingsRow['site_url'] ?? '', '/');
$galSlug    = 'gallery';     // matches .htaccess RewriteRule
$galsSlug   = 'galleries';  // matches .htaccess RewriteRule
$encryptIDs = false;         // site uses plain numeric IDs in SEO URLs

/* ------------------------------------------------------------------ */
/* Helpers                                                              */
/* ------------------------------------------------------------------ */

function sitemapEsc($str) {
    return htmlspecialchars(html_entity_decode(strip_tags((string)$str), ENT_QUOTES | ENT_HTML5, 'UTF-8'), ENT_XML1, 'UTF-8');
}

function sitemapUrl($loc, $lastmod = '', $changefreq = 'weekly', $priority = '0.7') {
    $out  = "  <url>\n";
    $out .= '    <loc>' . sitemapEsc($loc) . "</loc>\n";
    if ($lastmod) $out .= '    <lastmod>' . date('Y-m-d', strtotime($lastmod)) . "</lastmod>\n";
    $out .= '    <changefreq>' . $changefreq . "</changefreq>\n";
    $out .= '    <priority>' . $priority . "</priority>\n";
    $out .= "  </url>\n";
    return $out;
}

/* ------------------------------------------------------------------ */
/* Output                                                               */
/* ------------------------------------------------------------------ */

header('Content-Type: application/xml; charset=utf-8');

echo '<?xml version="1.0" encoding="UTF-8"?>' . "\n";
echo '<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">' . "\n";

/* --- Static pages -------------------------------------------------- */
echo sitemapUrl($siteURL . '/',                         '',  'daily',   '1.0');
echo sitemapUrl($siteURL . '/' . $galsSlug . '/',       '',  'weekly',  '0.8');
echo sitemapUrl($siteURL . '/newest.media.php',         '',  'daily',   '0.8');
echo sitemapUrl($siteURL . '/search.php',               '',  'monthly', '0.5');
echo sitemapUrl($siteURL . '/contributors.php',         '',  'weekly',  '0.5');
echo sitemapUrl($siteURL . '/contact.php',              '',  'monthly', '0.4');
echo sitemapUrl($siteURL . '/about.php',                '',  'monthly', '0.4');
echo sitemapUrl($siteURL . '/purchase.agreement.php',   '',  'monthly', '0.3');
echo sitemapUrl($siteURL . '/privacy.policy.php',       '',  'monthly', '0.3');
echo sitemapUrl($siteURL . '/terms.of.use.php',         '',  'monthly', '0.3');

/* --- Galleries ------------------------------------------------------ */
$galResult = mysqli_query($db,
    "SELECT gallery_id, name, created
     FROM {$dbinfo['pre']}galleries
     WHERE active = 1
       AND album = 0
       AND (password = '' OR password IS NULL)
     ORDER BY sort_number, gallery_id"
);
if ($galResult) {
    while ($gal = mysqli_fetch_assoc($galResult)) {
        $id      = $encryptIDs ? k_encrypt($gal['gallery_id']) : $gal['gallery_id'];
        $seoName = cleanForSEO($gal['name'] ?: 'gallery');
        $url     = $siteURL . '/' . $galSlug . '/' . $seoName . '/' . $id . '/';
        echo sitemapUrl($url, $gal['created'], 'weekly', '0.7');
    }
}

/* --- Media detail pages -------------------------------------------- */
$mediaResult = mysqli_query($db,
    "SELECT media_id, title, date_added
     FROM {$dbinfo['pre']}media
     WHERE active = 1
       AND approval_status = 1
     ORDER BY date_added DESC
     LIMIT 49000"
);
if ($mediaResult) {
    while ($row = mysqli_fetch_assoc($mediaResult)) {
        $id      = $encryptIDs ? k_encrypt($row['media_id']) : $row['media_id'];
        $seoName = cleanForSEO($row['title'] ?: 'photo');
        $url     = $siteURL . '/photo/' . $id . '/' . $seoName;
        echo sitemapUrl($url, $row['date_added'], 'monthly', '0.9');
    }
}

echo '</urlset>' . "\n";
