<?php

/**
 * @author Pratik Dev <webmaster.pratik@gmail.com>
 */
header('Content-Type: application/json');
require_once __DIR__ . '/config/init.php';
if (Input('submit') == 'genarateSitemap') {

    $files = $db->where('status', 1)->orderBy('id', 'ASC')->get(TABLE_FILES, 20000, 'id,slug,created_at');
    $cats = $db->where('status', 1)->where('is_cat', 1)->orderBy('id', 'ASC')->get(TABLE_CAT, 1000, 'id,slug,created_at');
    $albums = $db->where('status', 1)->where('is_cat', 0)->orderBy('id', 'ASC')->get(TABLE_CAT, 10000, 'id,slug,created_at');
    $artist =  $db->where('status', 1)->orderBy('id', 'ASC')->get('artist', 5000, 'id,slug,created_at');
    
    $str = '<?xml version="1.0" encoding="UTF-8"?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
<url>
<loc>' . APP_URL . '</loc>
<lastmod>' . date('Y-m-d') . '</lastmod>
</url>';
    foreach ($cats as $c) {
        $url = APP_URL . '/categorie/' . $c['slug'] . ROUTE_END;
        $publish = date('Y-m-d', strtotime($c['created_at']));
        $str .= " 
<url>
<loc>$url</loc>
<lastmod>$publish</lastmod>
</url>";
    }

    $str .= "</urlset>";

    WriteFile($RootPath . '/sitemap.xml', $str);

    if (file_exists($RootPath . '/sitemap.xml')) {
        $url = 'http://google.com/ping?sitemap=' . APP_URL . '/sitemap.xml';
        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_TIMEOUT, 5);
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        $data = curl_exec($ch);
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        curl_close($ch);
        if ($httpCode == 200)
            $mgs = 'Successfuly Sitemap Submited and Ping';
        else {
            $mgs = 'Successfuly Sitemap Submited';
        }
        echo  json_encode(['status' => '1', 'message' => $mgs]);
    } else {
        echo  json_encode(['status' => '0', 'message' => 'Unable Creating Sitemap']);
    }
}
