<?php
// Set execution limits for large sitemap
set_time_limit(300); // 5 minutes
ini_set('memory_limit', '512M');

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

require_once __DIR__ . '/includes/db.php';
require_once __DIR__ . '/includes/mysmiley_sitemap_config.php';
require_once __DIR__ . '/includes/mysmiley_static_page_seo.php';
require_once __DIR__ . '/includes/mysmiley_shop_public_item_slugs.php';

$mrwSitemapMinPriceEur = mysmiley_shop_listing_min_price_eur();

mysmiley_sitemap_feature_seed_missing($db);
mysmiley_static_page_seo_ensure_table($db);

$baseUrl = 'https://mysmiley.nl';
try {
    $stBase = $db->query('SELECT mainUrl FROM tblgeneralsettings LIMIT 1');
    $rowBase = $stBase ? $stBase->fetch(PDO::FETCH_ASSOC) : false;
    if ($stBase) {
        $stBase->closeCursor();
    }
    if ($rowBase && trim((string) ($rowBase['mainUrl'] ?? '')) !== '') {
        $baseUrl = rtrim(trim($rowBase['mainUrl']), '/');
    }
} catch (Throwable $e) {
    // keep default
}

// Get current date for lastmod
$currentDate = date('Y-m-d');

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

// Statische routes uit Pages SEO (mysmiley_page_seo.include_in_sitemap)
$pageSeoDefs = mysmiley_static_page_seo_definitions();
uasort(
    $pageSeoDefs,
    static function (array $a, array $b): int {
        return ($a['sort'] ?? 0) <=> ($b['sort'] ?? 0);
    }
);
foreach ($pageSeoDefs as $routeKey => $def) {
    if (!mysmiley_static_page_seo_route_in_sitemap($db, $routeKey)) {
        continue;
    }
    $path = (string) $def['path'];
    $prio = mysmiley_static_page_seo_sitemap_priority($routeKey);
    mysmiley_sitemap_write_url_entry($baseUrl, $path, $currentDate, 'daily', $prio);
}
echo '<!-- Static URLs from Pages SEO (include_in_sitemap) -->' . "\n";

mysmiley_sitemap_emit_url($db, 'static_shop_artikelen', $baseUrl, '/shop/rubriek/artikelen', $currentDate, 'daily', '0.9');
mysmiley_sitemap_emit_url($db, 'static_shop_vouchers', $baseUrl, '/shop/rubriek/vouchers', $currentDate, 'daily', '0.9');
mysmiley_sitemap_emit_url($db, 'static_blog_overview', $baseUrl, '/blog', $currentDate, 'daily', '0.85');

// VidaXL: alleen product-URL’s (/shop/product/…), geen categorie-filters (?main_cat=) in de sitemap
try {
    // VidaXL: only parents that are actually offered in shop (enabled + buyable + ≥1 active variant + category not disabled)
    $vidaxlProductWhere = "
        p.enabled = -1
        AND p.buyable = 1
        AND p.slug IS NOT NULL AND p.slug != ''
        AND EXISTS (
            SELECT 1 FROM new_vidaxl_variants v
            WHERE v.parentProductID = p.ID AND v.enabled = -1
        )
        AND (
            p.vidaxlCategorieID IS NULL
            OR EXISTS (
                SELECT 1 FROM tblvidaxl_categories c
                WHERE c.ID = p.vidaxlCategorieID AND c.enabled = -1
            )
        )
        AND (p.minPrice + 0) >= " . $mrwSitemapMinPriceEur . "
    ";

    $totalProducts = 0;
    if (mysmiley_sitemap_feature_is_enabled($db, 'vidaxl_product_urls')) {
        $countQuery = "SELECT COUNT(*) FROM new_vidaxl_parent_products p WHERE $vidaxlProductWhere";
        $sthCount = $db->prepare($countQuery);
        $sthCount->execute();
        $totalProducts = (int) $sthCount->fetchColumn();
        $sthCount->closeCursor();
    }

    echo '<!-- Total VidaXL products (active/buyable): ' . $totalProducts . ' -->' . "\n\n";

    if ($totalProducts > 0 && mysmiley_sitemap_feature_is_enabled($db, 'vidaxl_product_urls')) {
        $productsQuery = "
            SELECT p.slug 
            FROM new_vidaxl_parent_products p
            WHERE $vidaxlProductWhere
            ORDER BY p.slug ASC
            LIMIT 50000
        ";
        $sthProducts = $db->prepare($productsQuery);
        $sthProducts->execute();

        $productCount = 0;
        while ($product = $sthProducts->fetch(PDO::FETCH_ASSOC)) {
            $productCount++;
            $lastmod = $currentDate;

            echo '  <url>' . "\n";
            echo '    <loc>' . htmlspecialchars($baseUrl . '/shop/product/' . $product['slug'], ENT_XML1 | ENT_QUOTES, 'UTF-8') . '</loc>' . "\n";
            echo '    <lastmod>' . $lastmod . '</lastmod>' . "\n";
            echo '    <changefreq>daily</changefreq>' . "\n";
            echo '    <priority>0.7</priority>' . "\n";
            echo '  </url>' . "\n\n";

            if ($productCount % 100 == 0) {
                flush();
            }
        }

        echo '<!-- Products added to sitemap: ' . $productCount . ' -->' . "\n\n";
        $sthProducts->closeCursor();
    } else {
        echo '<!-- No products found in database or VidaXL product URLs disabled -->' . "\n\n";
    }
} catch (Exception $e) {
    error_log('Sitemap generation error: ' . $e->getMessage());
    echo '<!-- Error: ' . htmlspecialchars($e->getMessage()) . ' -->' . "\n";
}

// Touch Premium (artikelen) + Touch Tickets (vouchers): zelfde filters als /shop/rubriek/vouchers en artikelen
try {
    if (mysmiley_sitemap_feature_is_enabled($db, 'touch_product_urls')) {
        $vSql = mysmiley_shop_sql_touch_voucher_slugs(true);
        $a1 = mysmiley_shop_sql_touch_artikel_slug_branch_single_variant(true);
        $a2 = mysmiley_shop_sql_touch_artikel_slug_branch_multi_variant(true);
        $touchCombinedQuery = '
        SELECT DISTINCT TRIM(u.s) AS slug
        FROM (
            (' . $vSql . ')
            UNION ALL
            (' . $a1 . ' UNION ALL ' . $a2 . ')
        ) AS u
        WHERE u.s IS NOT NULL AND TRIM(u.s) <> \'\'
        ORDER BY slug ASC
        LIMIT 50000
        ';
        $sthTouch = $db->prepare($touchCombinedQuery);
        $sthTouch->execute();
        $touchItemCount = 0;
        while ($row = $sthTouch->fetch(PDO::FETCH_ASSOC)) {
            $touchItemCount++;
            $slug = $row['slug'];
            echo '  <url>' . "\n";
            echo '    <loc>' . htmlspecialchars($baseUrl . '/shop/item/' . $slug, ENT_XML1 | ENT_QUOTES, 'UTF-8') . '</loc>' . "\n";
            echo '    <lastmod>' . $currentDate . '</lastmod>' . "\n";
            echo '    <changefreq>daily</changefreq>' . "\n";
            echo '    <priority>0.7</priority>' . "\n";
            echo '  </url>' . "\n\n";
            if ($touchItemCount % 100 == 0) {
                flush();
            }
        }
        $sthTouch->closeCursor();
        echo '<!-- Touch /shop/item URLs: min ' . (int) mysmiley_shop_listing_min_voucher_peaks() . ' peaks (vouchers), min €' . htmlspecialchars((string) $mrwSitemapMinPriceEur, ENT_QUOTES, 'UTF-8') . ' (artikelen); ' . $touchItemCount . ' URLs -->' . "\n\n";
    } else {
        echo '<!-- Touch product URLs disabled in sitemap settings -->' . "\n\n";
    }
} catch (Exception $e) {
    error_log('Sitemap Touch products error: ' . $e->getMessage());
    echo '<!-- Touch sitemap error: ' . htmlspecialchars($e->getMessage()) . ' -->' . "\n";
}

// Blog: same slugs as /blog (tblcontent SHOP_BLOG|slug with listVisible in infoText)
try {
    require_once __DIR__ . '/includes/shop_home_blog_teasers.php';
    if ($db instanceof PDO) {
        $blogVisibleRows = mysmiley_shop_blog_visible_articles_newest_first($db, 0);
        $blogLastModByCode = [];
        $sthBlogDates = $db->query("SELECT code, lastUpdateDate FROM tblcontent WHERE code LIKE 'SHOP_BLOG|%'");
        if ($sthBlogDates) {
            while ($rowBlogDate = $sthBlogDates->fetch(PDO::FETCH_ASSOC)) {
                $blogCode = isset($rowBlogDate['code']) ? (string) $rowBlogDate['code'] : '';
                $rawDate = isset($rowBlogDate['lastUpdateDate']) ? trim((string) $rowBlogDate['lastUpdateDate']) : '';
                if ($blogCode !== '' && $rawDate !== '' && strpos($blogCode, 'SHOP_BLOG|') === 0) {
                    $slugPart = substr($blogCode, strlen('SHOP_BLOG|'));
                    if (preg_match('/^[a-z0-9-]+$/', $slugPart)) {
                        $blogLastModByCode[$blogCode] = substr(preg_replace('/\s.*$/', '', $rawDate), 0, 10);
                    }
                }
            }
            $sthBlogDates->closeCursor();
        }
        $blogPostCount = 0;
        if (mysmiley_sitemap_feature_is_enabled($db, 'blog_post_urls')) {
            foreach ($blogVisibleRows as $blogRow) {
                $blogSlug = isset($blogRow['slug']) ? (string) $blogRow['slug'] : '';
                if ($blogSlug === '' || !preg_match('/^[a-z0-9-]+$/', $blogSlug)) {
                    continue;
                }
                $blogPostCount++;
                $blogCodeKey = 'SHOP_BLOG|' . $blogSlug;
                $blogLastMod = isset($blogLastModByCode[$blogCodeKey]) ? $blogLastModByCode[$blogCodeKey] : $currentDate;
                echo '  <url>' . "\n";
                echo '    <loc>' . htmlspecialchars($baseUrl . '/blog/' . $blogSlug, ENT_XML1 | ENT_QUOTES, 'UTF-8') . '</loc>' . "\n";
                echo '    <lastmod>' . htmlspecialchars($blogLastMod, ENT_XML1 | ENT_QUOTES, 'UTF-8') . '</lastmod>' . "\n";
                echo '    <changefreq>daily</changefreq>' . "\n";
                echo '    <priority>0.75</priority>' . "\n";
                echo '  </url>' . "\n\n";
            }
        }
        echo '<!-- Blog posts (list-visible on /blog): ' . $blogPostCount . ' -->' . "\n";
    }
} catch (Exception $e) {
    error_log('Sitemap blog error: ' . $e->getMessage());
    echo '<!-- Blog sitemap error: ' . htmlspecialchars($e->getMessage()) . ' -->' . "\n";
}

echo '</urlset>';
