<?php

namespace App\Http\Controllers\Main;

use App\Http\Controllers\Controller;
use App\Http\Requests\Main\NewsletterSubscribeRequest;
use App\Models\Newsletter;
use App\Models\Story;
use App\Models\Template;
use App\Services\Main\MainService;
use App\Services\Main\Mobile\CategoriesService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Log;
use Inertia\Inertia;

class MainController extends Controller
{
    /**
     * shop index page
     */
    public function index(Request $request, MainService $mainService)
    {
        /** active template */
        $template = Template::where('status', 'active')->first();
        $seo = $mainService->seo();

        return Inertia::render('Main/Index', [
            'stories' => fn() => $mainService->getStories(),
            'components' => fn() => $mainService->getComponents($template),
            'seo' => $seo
        ])
            ->title($seo['title'])
            ->description($seo['description'] != null ? $seo['description'] : __('messages.sentence.not_completed'))
            ->image($seo['image'] != null ? $seo['image'] : __('messages.sentence.not_completed'))
            ->tag('<link rel="canonical" href="' . urldecode(url()->full()) . '" />')
            ->ogMeta()
            ->ogUrl(urldecode(url()->full()))
            ->ogType('website')
            ->ogLocale('fa_IR')
            ->tag('<meta property="og:site_name" content="' . $seo['site_name'] . '" />')
            ->twitterSummaryCard()
            ->twitterSite($request->url())
            ->twitterCreator($seo['site_name'])
            ->tag('<script type="application/ld+json">' . str_replace('%', '', $seo['schema']) . '</script>'); // schema
    }

    /**
     * search typing
     */
    public function search(Request $request, MainService $mainService)
    {
        // check keyword and return null data if keyword is empty
        if (!$request->exists('keyword') || $request->keyword == null || $request->keyword == '')
            return response([
                'categories' => [],
                'products' => [],
            ]);

        return response([
            'categories' => $mainService->getSearchProductCategory($request),
            'products' => $mainService->getSearchProduct($request),
        ]);
    }

    /**
     * category list
     */
    public function categories(CategoriesService $categoriesService)
    {
        $seo = $categoriesService->seo();

        return Inertia::render('Main/Mobile/Categories', [
            'productCategories' => $categoriesService->productCategoryList(),
            'articleCategories' => $categoriesService->articleCategoryList(),
            'brands' => $categoriesService->brandList(),
        ])->title($seo['title']);
    }

    /**
     * subscribe to newsletter
     */
    public function subscribe(NewsletterSubscribeRequest $request)
    {
        $input = $request->validated()['email_or_phone'];

        $data = [];
        if (filter_var($input, FILTER_VALIDATE_EMAIL)) {
            $data['email'] = strtolower($input);
        } else {
            $data['phone'] = $input;
        }

        Newsletter::create($data);

        return redirect()->back()->with('message', [__('messages.email_subscribed_on_newsletter')]);
    }

    /**
     * subscribe to newsletter
     */
    public function like_story(Request $request, Story $story)
    {
        /** add article to voted list */
        $likeStories = $request->session()->get('liked_stories', []);
        if (array_key_exists($story->id, $likeStories)) {
            return response()->json([
                'status' => true,
                'like' => $story->like,
            ]);
        }
        $likeStories[$story->id] = $story->id;
        session(['liked_stories' => $likeStories]);
        /************************************/

        $newLikes = $story->like + 1;
        $story->update([
            'like' => $newLikes,
        ]);

        return response()->json([
            'status' => true,
            'like' => $newLikes,
        ]);
    }
}
