<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use Mtc\Cms\Models\Page;
use Mtc\Shop\Brand;
use Mtc\Shop\Category;
use Mtc\Shop\Item;
use Spatie\Sitemap\Sitemap;

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

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Generate sitemap.xml file';

    /**
     * Execute the console command.
     */
    public function handle()
    {
        $sitemap = Sitemap::create();

        $this->generateForCms($sitemap);
        $this->generateForItems($sitemap);
        $this->generateForBrands($sitemap);
        $this->generateForCategories($sitemap);

        $sitemap->writeToFile(public_path('sitemap.xml'));

        return Command::SUCCESS;
    }

    /**
     * Generate sitemap entries for brands.
     *
     * @param Sitemap $sitemap The sitemap instance to add entries to.
     * @return void
     * */
    private function generateForBrands(Sitemap $sitemap)
    {
        $brands = Brand::active();
        $brands = $brands->get();
        $sitemap->add($brands);
    }

    /**
     * Generate sitemap entries for categories.
     *
     * @param Sitemap $sitemap The sitemap instance to add entries to.
     * @return void
     * */
    private function generateForCategories(Sitemap $sitemap)
    {
        $cats = Category::active();
        $cats = $cats->get();
        $sitemap->add($cats);
    }

    /**
     * Generate sitemap entries for items.
     *
     * @param Sitemap $sitemap The sitemap instance to add entries to.
     * @return void
     * */
    private function generateForItems(Sitemap $sitemap)
    {
        $query = Item::active();
        $items = $query->get();
        $sitemap->add($items);
    }

    /**
     * Generate sitemap entries for CMS pages.
     *
     * @param Sitemap $sitemap The sitemap instance to add entries to.
     * @return void
     * */
    private function generateForCms(Sitemap $sitemap)
    {
        $query = Page::published();
        $query = $query->default();
        $pages = $query->get();
        $sitemap->add($pages);
    }
}
