<?php

namespace App\Http\Controllers\Front;

use App\Http\Controllers\Controller;
use App\Models\AiTool;
use App\Models\Category;
use Artesaos\SEOTools\Facades\SEOMeta;
use Artesaos\SEOTools\Facades\SEOTools;
use Illuminate\Http\Request;
use JsonLd\Context;

class FrontDiscoverController extends Controller
{
    public function discover(Request $request, $category_slug = null)
    {
        $tools_count = round_to_nearest_base(700);

        $category = null;

        if (! is_empty($category_slug)) {
            $category = Category::where('slug', $category_slug)->first();

            if (is_null($category)) {
                return abort(404);
            }
        }

        if (! is_null($category)) {
            $breadcrumbs = collect([
                ['name' => 'Home', 'url' => route('front.home')],
                ['name' => 'Discover AI Tools', 'url' => route('front.discover.home')],
                ['name' => $category->name.' AI Tools', 'url' => null],
            ]);

            SEOTools::metatags();
            SEOTools::twitter();
            SEOTools::opengraph();
            SEOTools::jsonLd();
            SEOTools::setTitle($category->name.' AI Tools', false);
        //SEOTools::setDescription($description);
        } else {
            $breadcrumbs = collect([
                ['name' => 'Home', 'url' => route('front.home')],
                ['name' => 'Discover AI Tools', 'url' => null],
            ]);

            SEOTools::metatags();
            SEOTools::twitter();
            SEOTools::opengraph();
            SEOTools::jsonLd();
            SEOTools::setTitle("{$tools_count} over AI Tools for you", false);
            //SEOTools::setDescription($description);
        }

        // breadcrumb json ld
        $listItems = [];

        foreach ($breadcrumbs as $index => $breadcrumb) {
            $listItems[] = [
                'name' => $breadcrumb['name'],
                'url' => $breadcrumb['url'],
            ];
        }

        $breadcrumb_context = Context::create('breadcrumb_list', [
            'itemListElement' => $listItems,
        ]);

        $ai_tools = AiTool::when(! is_null($category), function ($query) use ($category) {
            $query->where('category_id', $category->id);
        })
            ->orderBy('updated_at', 'DESC')->paginate(6);

        if ($ai_tools->count() <= 0) {
            SEOMeta::setRobots('noindex');
        }

        return view('front.discover', compact('breadcrumbs', 'breadcrumb_context', 'category', 'ai_tools'));
    }
}
