<?php

namespace App\Console\Commands;

use Carbon\Carbon;
use Illuminate\Console\Command;

class GenerateSiteMap extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'make:sitemap';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Auto generate sitemap';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {

        $sitemapCate = \App::make("sitemap");
        $categories = \DB::table('categories')->whereNull('parent_id')
            ->orderBy('created_at', 'desc')->get();
        $categoryAdd = ['/', 'download', 'pricing', 'huong-dan-su-dung', 'blog'];

        foreach ($categories as $category) {
            $sitemapCate->add(\URL::to('/blog/danh-muc'). '/' . $category->slug, Carbon::now()->toW3cString(), '1.0', 'hourly');
        }

        foreach ($categoryAdd as $add) {
            $sitemapCate->add(\URL::to($add), Carbon::now()->toW3cString(), '1.0', 'hourly');
        }

        $sitemapCate->store('xml','sitemapcate');


        $sitemapPost = \App::make("sitemap");
        $blogs = \DB::table('blogs')->where('status', 1)
            ->orderBy('created_at', 'desc')->get();

        foreach ($blogs as $blog) {
            $image  = [
                [
                    'url' => $blog->image ? \URL::to('/files/' . $blog->image) : \URL::to('/frontend3/assets/img/placeholder.png'),
                    'title' => $blog->title
                ]
            ];

            $sitemapPost->add(\URL::to('/blog'). '/' . $blog->slug, Carbon::now()->toW3cString(), '0.64', 'daily', $image);
        }

        $sitemapPost->store('xml','sitemapblog');

        $sitemap = \App::make ("sitemap");

        // add sitemaps (loc, lastmod (optional))
        $sitemap->addSitemap(\URL::to('sitemapcate.xml'));
        $sitemap->addSitemap(\URL::to('sitemapblog.xml'));

        // create file sitemap.xml in your public folder (format, filename)
        $sitemap->store('sitemapindex','sitemap');

    }
}
