<?php

namespace App\Http\Controllers\Front;

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

class FrontToolController extends Controller
{
    public function show(Request $request, $ai_tool_slug)
    {
        $ai_tool = AiTool::where('slug', $ai_tool_slug)->where('status','live')->first();

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

        // if (is_empty($ai_tool->screenshot_img))
        // {
        //   return ;
        // }

        $ai_tool->load('category');

        $breadcrumbs = collect([
            ['name' => 'Home', 'url' => route('front.home')],
            ['name' => 'AI Tools', 'url' => route('front.discover.home')],
            ['name' => $ai_tool->category->name, 'url' => route('front.discover.category', ['category_slug' => $ai_tool->category->slug])],
            ['name' => $ai_tool->tool_name, 'url' => null],
        ]);

        // breadcrumb json ld
        $listItems = [];

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

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

        $applicationCategory = '';

        if ($ai_tool->is_app_web_both == 'both') {
            $applicationCategory = 'App & Web Application';
        } else {
            $applicationCategory = ucwords($ai_tool->is_app_web_both).' Application';
        }

        $qnaMainEntity = [];

        foreach ($ai_tool->qna as $qna) {
            $qnaMainEntity[] = [
                '@type' => 'Question',
                'name' => $qna->q,
                'acceptedAnswer' => [
                    '@type' => 'Answer',
                    'text' => $qna->a,
                ],
            ];
        }

        $faqData = [
            'mainEntity' => $qnaMainEntity,
        ];

        $faq_context = Context::create(FAQPage::class, $faqData);

        SEOTools::setTitle($ai_tool->tool_name . ": ". $ai_tool->tagline, false);
        SEOTools::setDescription(implode(" ",str_extract_sentences($ai_tool->summary, 2)));
        SEOTools::metatags();
        SEOTools::twitter()->addImage($ai_tool->screenshot_img);
        SEOTools::opengraph()->addImage($ai_tool->screenshot_img);
        SEOTools::jsonLd()->addImage($ai_tool->screenshot_img);

        //dd($faq_context);

        return view('front.aitool', compact('ai_tool', 'breadcrumb_context', 'breadcrumbs', 'faq_context'));
    }
}
