<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Xml_controler extends CI_Controller {
    function __construct() {
        parent::__construct();
    }
    public function sitemap()
    {

        $sql = $this->db->get('product');
        $data['products'] = $sql->result();

        $products_tag = $this->db->get('category');
        $data['category'] = $products_tag->result();

        $this->load->view('sitemap', $data);
    }
    
    //  public function tag_sitemap()
    // {

    //     $sql = $this->db->get('product');
    //     $data['products'] = $sql->result();

    //     // $products_tag = $this->db->get('category');
    //     // $data['category'] = $products_tag->result();

    //     $this->load->view('tag_sitemap', $data);
    // }
    public function tag_sitemap()
{
     $sql = $this->db->get('product');
    $products = $sql->result();
    
    $chunkSize = 2500;
    $currentChunk = 1;
    $tagIndex = 0;

    while ($tagIndex < count($products)) {
        $xml = '<?xml version="1.0" encoding="UTF-8"?><urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">';
        $linksCount = 0;

        for ($i = 0; $i < $chunkSize && $tagIndex < count($products); $i++) {
            $product = $products[$tagIndex];
            $tags = explode(",", $product->tags);

            foreach ($tags as $tag) {
                $tag = str_replace("&", "and", $tag);
                // $tag = urlencode(trim($tag)); // Ensure valid URL format
                $url = base_url('tag') . '/' . preg_replace('/[^a-z0-9]+/i','-', $tag );

                $xml .= '<url>
                    <loc>' . $url . '</loc>
                    <priority>1.0</priority>
                    <changefreq>daily</changefreq>
                    </url>';

                $linksCount++;
                if ($linksCount >= $chunkSize) {
                    break 2; // Break both inner and outer loops
                }
            }

            $tagIndex++;
        }

        $xml .= '</urlset>';
        $filename = "tag_sitemap_{$currentChunk}.xml";
        $filepath = $filename;

        file_put_contents($filepath, $xml);
        $currentChunk++;
    }
    
    echo '<h1>Sitemaps generated successfully</h1>';
    // return response()->json(['message' => 'Sitemaps generated successfully']);
}
}

?>