<?php
/**
 * RST Innovations - Dynamic XML Sitemap
 * Serves as: https://www.rstinnovations.com/sitemap.xml
 * Covers: static pages, services, sectors, locations, blog posts, products, campaigns
 */

include "import/db.php";

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

$base_url = 'https://www.rstinnovations.com';
$today    = date('Y-m-d');

// ── Helpers ───────────────────────────────────────────────────────────────
function url($loc, $lastmod, $changefreq = 'monthly', $priority = '0.6') {
    echo "  <url>\n";
    echo "    <loc>" . htmlspecialchars($loc) . "</loc>\n";
    echo "    <lastmod>" . $lastmod . "</lastmod>\n";
    echo "    <changefreq>" . $changefreq . "</changefreq>\n";
    echo "    <priority>" . $priority . "</priority>\n";
    echo "  </url>\n";
}

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

// ════════════════════════════════════════════════════════════
// 1. CORE / STATIC PAGES
// ════════════════════════════════════════════════════════════
$static_pages = [
    ['/',                       '2026-04-24', 'weekly',   '1.0'],
    ['/about-us',               '2026-04-24', 'monthly',  '0.8'],
    ['/services',               '2026-04-24', 'monthly',  '0.9'],
    ['/manufacturing-facility', '2026-04-19', 'monthly',  '0.8'],
    ['/certifications',         '2026-04-19', 'monthly',  '0.7'],
    ['/directors-message',      '2026-04-19', 'monthly',  '0.6'],
    ['/our-team',               '2026-04-19', 'monthly',  '0.6'],
    ['/clients-testimonials',   '2026-04-19', 'monthly',  '0.7'],
    ['/faqs',                   '2026-04-19', 'monthly',  '0.7'],
    ['/contact-us',             '2026-04-19', 'monthly',  '0.8'],
    ['/projects',               '2026-04-19', 'weekly',   '0.7'],
    ['/products',               '2026-04-19', 'weekly',   '0.8'],
    ['/blogs',                  '2026-04-19', 'daily',    '0.8'],
    ['/case-studies',           '2026-04-19', 'monthly',  '0.7'],
    ['/privacy-policy',         '2026-04-19', 'yearly',   '0.3'],
    ['/terms-of-service',       '2026-04-19', 'yearly',   '0.3'],
];

echo "\n  <!-- ══ CORE PAGES ══ -->\n";
foreach ($static_pages as $p) {
    url($base_url . $p[0], $p[1], $p[2], $p[3]);
}

// ════════════════════════════════════════════════════════════
// 2. SERVICE PAGES - from DB (existing) + new (hardcoded)
// ════════════════════════════════════════════════════════════
echo "\n  <!-- ══ SERVICE PAGES ══ -->\n";

// Existing services from DB
$svc_result = mysqli_query($con, "SELECT service_slug, updated_at FROM services WHERE (status='published' OR status IS NULL OR status='') ORDER BY id");
while ($row = mysqli_fetch_assoc($svc_result)) {
    if (!empty($row['service_slug'])) {
        $lm = !empty($row['updated_at']) ? date('Y-m-d', strtotime($row['updated_at'])) : $today;
        url($base_url . '/service/' . $row['service_slug'], $lm, 'monthly', '0.9');
    }
}

// All 34 service slugs now live in DB - this array is a future-proofing fallback
// for any services added here before they reach the DB.
$new_services = [];

// Fetch existing slugs to avoid duplicates
$existing_slugs = [];
$ex_res = mysqli_query($con, "SELECT service_slug FROM services WHERE (status='published' OR status IS NULL OR status='')");
while ($row = mysqli_fetch_row($ex_res)) {
    $existing_slugs[] = $row[0];
}

foreach ($new_services as $slug) {
    if (!in_array($slug, $existing_slugs)) {
        url($base_url . '/service/' . $slug, $today, 'monthly', '0.9');
    }
}

// ════════════════════════════════════════════════════════════
// 3. SECTOR PAGES - active DB sectors, fallback hardcoded list
// ════════════════════════════════════════════════════════════
echo "\n  <!-- ══ SECTOR PAGES ══ -->\n";

url($base_url . '/sectors', $today, 'monthly', '0.8');
$sector_slugs = [];
$sec_res = @$con->query("SELECT slug, updated_at FROM sectors WHERE is_active = 1 ORDER BY sort_order, name");
if ($sec_res && $sec_res->num_rows) {
    while ($row = mysqli_fetch_assoc($sec_res)) {
        if (empty($row['slug'])) continue;
        $sector_slugs[] = $row['slug'];
        $lm = !empty($row['updated_at']) ? date('Y-m-d', strtotime($row['updated_at'])) : $today;
        url($base_url . '/sectors/' . $row['slug'], $lm, 'monthly', '0.8');
    }
}
if (!$sector_slugs) {
    $sectors = [
        'retail', 'corporate', 'events', 'hospitality',
        'healthcare', 'education', 'government', 'transport',
        'sports', 'religious', 'automobile', 'election-campaigns',
        'broadcast-media', 'banking-finance', 'real-estate',
        'industrial', 'outdoor-advertising',
    ];
    foreach ($sectors as $s) {
        url($base_url . '/sectors/' . $s, $today, 'monthly', '0.8');
    }
}

// ════════════════════════════════════════════════════════════
// 4. LOCATION PAGES - DB states/cities when available
// ════════════════════════════════════════════════════════════
echo "\n  <!-- ══ LOCATION PAGES ══ -->\n";

$location_services = [
    'indoor-led-video-wall',
    'outdoor-led-video-wall',
    'led-vehicle-display',
    'led-display-rental',
    'digital-signage-solutions',
    'fine-pitch-led-display',
    'stage-led-display',
];

$states_map = [];
$st_res = @$con->query('SELECT id, slug FROM states WHERE is_active = 1 ORDER BY sort_order, name');
if ($st_res && $st_res->num_rows) {
    while ($st = mysqli_fetch_assoc($st_res)) {
        $cities = [];
        $cid = (int) $st['id'];
        $ct_res = @$con->query("SELECT slug FROM cities WHERE state_id = $cid AND is_active = 1 ORDER BY sort_order, name");
        if ($ct_res) {
            while ($ct = mysqli_fetch_assoc($ct_res)) {
                if (!empty($ct['slug'])) $cities[] = $ct['slug'];
            }
        }
        if (!empty($st['slug'])) {
            $states_map[$st['slug']] = $cities;
        }
    }
}
if (!$states_map) {
    $states_map = [
        'kerala' => [
            'kollam', 'thiruvananthapuram', 'kochi', 'kozhikode',
            'thrissur', 'kannur', 'palakkad', 'malappuram',
            'kottayam', 'alappuzha',
        ],
        'tamil-nadu' => ['chennai', 'coimbatore', 'madurai', 'salem'],
        'karnataka' => ['bangalore', 'mysore'],
        'andhra-pradesh' => ['visakhapatnam', 'vijayawada'],
        'telangana' => ['hyderabad'],
    ];
}

url($base_url . '/locations', $today, 'monthly', '0.7');

foreach ($states_map as $state => $cities) {
    url($base_url . '/locations/' . $state, $today, 'monthly', '0.8');
    foreach ($cities as $city) {
        url($base_url . '/locations/' . $state . '/' . $city, $today, 'monthly', '0.9');
        foreach ($location_services as $svc) {
            url($base_url . '/locations/' . $state . '/' . $city . '/' . $svc, $today, 'monthly', '0.9');
        }
    }
}

// ════════════════════════════════════════════════════════════
// 5. BLOG / ARTICLE PAGES
// ════════════════════════════════════════════════════════════
echo "\n  <!-- ══ BLOG POSTS ══ -->\n";

$blog_result = mysqli_query($con,
    "SELECT blog_slug, blog_date, updated_at FROM blogs WHERE (status='published' OR status IS NULL OR status='') ORDER BY id DESC");
while ($row = mysqli_fetch_assoc($blog_result)) {
    if (!empty($row['blog_slug'])) {
        if (!empty($row['updated_at'])) {
            $lastmod = date('Y-m-d', strtotime($row['updated_at']));
        } elseif (!empty($row['blog_date'])) {
            $lastmod = date('Y-m-d', strtotime($row['blog_date']));
        } else {
            $lastmod = $today;
        }
        url($base_url . '/blog/' . $row['blog_slug'], $lastmod, 'monthly', '0.7');
    }
}

// ════════════════════════════════════════════════════════════
// 6. PRODUCT PAGES
// ════════════════════════════════════════════════════════════
echo "\n  <!-- ══ PRODUCT PAGES ══ -->\n";

$prod_result = mysqli_query($con,
    "SELECT id, product_name, product_slug, updated_at FROM products WHERE (status='published' OR status IS NULL OR status='') ORDER BY id");
while ($row = mysqli_fetch_assoc($prod_result)) {
    $slug = $row['product_slug'] ?: strtolower(trim(preg_replace('/[^a-z0-9]+/i', '-', $row['product_name']), '-'));
    $lm = !empty($row['updated_at']) ? date('Y-m-d', strtotime($row['updated_at'])) : $today;
    url($base_url . '/product/' . $row['id'] . '/' . $slug, $lm, 'monthly', '0.7');
}

// ════════════════════════════════════════════════════════════
// 7. PROJECT PAGES - from DB
// ════════════════════════════════════════════════════════════
echo "\n  <!-- ══ PROJECT PAGES ══ -->\n";

$proj_result = mysqli_query($con,
    "SELECT project_slug, updated_at FROM projects WHERE project_slug != '' AND (status='published' OR status IS NULL OR status='') ORDER BY id DESC");
while ($row = mysqli_fetch_assoc($proj_result)) {
    $lm = !empty($row['updated_at']) ? date('Y-m-d', strtotime($row['updated_at'])) : $today;
    url($base_url . '/project/' . $row['project_slug'], $lm, 'monthly', '0.6');
}

// ════════════════════════════════════════════════════════════
// 8. CAMPAIGN / LANDING PAGES
// ════════════════════════════════════════════════════════════
echo "\n  <!-- ══ CAMPAIGN PAGES ══ -->\n";

$campaign_pages = [
    '/led-van-for-election',
    '/led-display-for-onam',
    '/led-display-for-christmas',
    '/get-free-site-survey',
    '/led-display-price-india',
];

foreach ($campaign_pages as $cp) {
    url($base_url . $cp, $today, 'monthly', '0.8');
}

// ════════════════════════════════════════════════════════════
// 9. CASE STUDY PAGES (dynamic - from DB if table exists)
// ════════════════════════════════════════════════════════════
$case_table = mysqli_query($con, "SHOW TABLES LIKE 'case_studies'");
if (mysqli_num_rows($case_table) > 0) {
    echo "\n  <!-- ══ CASE STUDY DETAILS ══ -->\n";
    $cs_result = mysqli_query($con, "SELECT slug, updated_at FROM case_studies WHERE (status='published' OR status IS NULL OR status='') ORDER BY id DESC");
    while ($row = mysqli_fetch_assoc($cs_result)) {
        if (!empty($row['slug'])) {
            url($base_url . '/case-study/' . $row['slug'], $today, 'monthly', '0.7');
        }
    }
}

// ════════════════════════════════════════════════════════════
// 10. CMS PAGES - published /page/{slug}
// ════════════════════════════════════════════════════════════
$cms_table = @$con->query("SHOW TABLES LIKE 'cms_pages'");
if ($cms_table && $cms_table->num_rows > 0) {
    echo "\n  <!-- ══ CMS PAGES ══ -->\n";
    $cms_res = mysqli_query($con, "SELECT slug, updated_at FROM cms_pages WHERE (status='published' OR status IS NULL OR status='') ORDER BY slug");
    if ($cms_res) {
        while ($row = mysqli_fetch_assoc($cms_res)) {
            if (empty($row['slug'])) continue;
            $lm = !empty($row['updated_at']) ? date('Y-m-d', strtotime($row['updated_at'])) : $today;
            url($base_url . '/page/' . $row['slug'], $lm, 'monthly', '0.5');
        }
    }
}

echo "\n</urlset>\n";
?>
