<?php

namespace App\Http\Controllers\Blog\Articles;

use App\Http\Controllers\Controller;
use App\Models\Article;
use App\Models\Template;
use App\Services\Blog\Articles\ArticleService;
use App\Services\Blog\Articles\ArticlesService;
use App\Services\Blog\BlogService;
use Illuminate\Http\Request;
use Inertia\Inertia;

class ArticlesController extends Controller
{
    /**
     * articles archive
     */
    public function index(Request $request, ArticlesService $articlesService)
    {
        $articles = $articlesService->getArticles($request);
        $seo = $articles['seo'];

        $view = Inertia::render("Blog/Articles/List", [
            'seo' => $seo,
            'articles' => fn() => $articles['articles'],
            'keywords' => fn() => $articlesService->getKeywords($request),
            'page' => fn() => $request->page,
        ]);

        $view->title(str_replace('%', '', $seo['title']))
            ->tag('<link rel="canonical" href="' . ($seo['canonical'] != null ? str_replace('%', '', urldecode($seo['canonical'])) : urldecode(url()->full())) . '" />');

        if ($seo['description'] != null) {
            $view->description(str_replace('%', '', $seo['description']));
        }
        if ($seo['image'] != null) {
            $view->image($seo['image']);
        }
        if ($seo['author'] != null) {
            $view->tag('<meta name="author" content="' . str_replace('%', '', $seo['author']) . '" />');
        }

        // og and twitter card
        $view->ogMeta()
            ->ogUrl(urldecode(url()->full()))
            ->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

        if ($seo['type'] != null) {
            $view->ogType($seo['type']);
        }

        return $view;
    }

    /**
     * show article
     */
    public function show(Request $request, Article $article, ArticleService $articleService, BlogService $blogService)
    {
        /** check product status */
        if ($article->status != 'publish') {
            abort(404);
        }

        // increase article view count
        $article->update([
            'view_count' => $article->view_count + 1
        ]);
        $seo = $articleService->seo($article);

        $view = Inertia::render("Blog/Articles/Show", [
            'seo' => $seo,
            'article' => fn() => [
                'id' => $article->id,
                'uuid' => $article->uuid,
                'title' => $article->title,
                'slug' => $article->slug,
                'get_content' => $article->get_content,
                'source' => $article->source,
                'read_time' => $article->read_time,
                'type' => $article->type,
                'get_image' => $article->get_image,
                'get_video' => $article->get_video,
                'get_podcast' => $article->get_podcast,
                'seo_title' => $article->seo_title,
                'seo_description' => $article->seo_description,
                'get_seo_keywords' => $article->get_seo_keywords,
                'seo_canonical' => $article->seo_canonical,
                'view_count' => $article->view_count,
                'get_formatted_view_count' => $article->get_formatted_view_count,
                'comment_status' => $article->comment_status,
                'comments_info' => $article->comments_info,
                'editor_choice' => $article->editor_choice,
                'vote' => $article->vote,
                'is_voted' => $article->is_voted,
                'status' => $article->status,
                'jalali_created_at' => $article->jalali_created_at,

                'user' => $article->get_user,
                'brand' => $article->brand != null ? [
                    'id' => $article->brand->id,
                    'uuid' => $article->brand->uuid,
                    'title' => $article->brand->title,
                    'slug' => $article->brand->slug,
                    'get_logo' => $article->brand->get_logo,
                ] : null,
                'category' => $article->get_category,
                'tags' => $article->articleTags->map(fn($tag) => [
                    'id' => $tag->id,
                    'title' => $tag->title,
                    'slug' => $tag->slug,
                ])
            ],
            'random_articles' => fn() => $articleService->getRandomArticles($article),
            'latest_articles' => fn() => $articleService->getLatestArticles($article),
            'hashtags' => fn() => $blogService->getHashtags(),
            'comments' => fn() => $articleService->getArticleComments($article),
        ]);

        $view->title($seo['title'])
            ->tag('<link rel="canonical" href="' . ($seo['canonical'] != null ? urldecode($seo['canonical']) : urldecode(url()->full())) . '" />');

        if ($seo['description'] != null) {
            $view->description($seo['description']);
        }
        if ($seo['image'] != null) {
            $view->image($seo['image']);
        }
        if ($seo['author'] != null) {
            $view->tag('<meta name="author" content="' . $seo['author'] . '" />');
        }

        // og and twitter card
        $view->ogMeta()
            ->ogUrl(urldecode(url()->full()))
            ->ogLocale('fa_IR')
            ->tag('<meta property="og:site_name" content="' . $seo['site_name'] . '" />')
            ->twitterLargeCard()
            ->twitterSite($request->url());

        if ($seo['author'] != null) {
            $view->twitterCreator($seo['author']);
        }
        if ($seo['type'] != null) {
            $view->ogType($seo['type']);
        }

        // schema
        if ($seo['schema'] != null) {
            if (array_key_exists('breadcrumb', $seo['schema'])) {
                $view->tag('<script type="application/ld+json">' . str_replace('%', '%%', $seo['schema']['breadcrumb']) . '</script>');
            }
            if (array_key_exists('article', $seo['schema'])) {
                $view->tag('<script type="application/ld+json">' . str_replace('%', '%%', $seo['schema']['article']) . '</script>');
            }
        }

        return $view;
    }

    /** vote article */
    public function vote(Request $request, Article $article)
    {
        /** add article to voted list */
        $votedArticles = $request->session()->get('voted_articles', []);
        if (array_key_exists($article->id, $votedArticles)) {
            return response()->json([
                'status' => true,
                'vote' => $article->vote,
            ]);
        }
        $votedArticles[$article->id] = $article->id;
        session(['voted_articles' => $votedArticles]);
        /************************************/

        $newVotes = $article->vote + 1;
        $article->update([
            'vote' => $newVotes,
        ]);

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