<?php

namespace App\Http\Controllers;

use App\Models\Post;
use App\Models\AdPlacement;
use App\Models\Setting;
use Illuminate\Http\Request;
use Inertia\Inertia;

class NewsController extends Controller
{
    public function show($slug)
    {
        $post = Post::with(['user', 'category', 'images', 'rssFeed'])
            ->withCount('comments')
            ->where('slug', $slug)
            ->where('status', 'published')
            ->firstOrFail();

        return $this->renderPostView($post);
    }

    public function showById($id)
    {
        $post = Post::with(['user', 'category', 'images', 'rssFeed'])
            ->withCount('comments')
            ->where('id', $id)
            ->where('status', 'published')
            ->firstOrFail();

        return $this->renderPostView($post);
    }

    private function renderPostView($post)
    {
        $sessionKey = 'viewed_post_' . $post->id;
        if (!session()->has($sessionKey)) {
            $post->increment('views_count');
            session()->put($sessionKey, true);
        }

        $userVote = null;
        if (auth()->check()) {
            $vote = \App\Models\Vote::where('post_id', $post->id)
                ->where('user_id', auth()->id())
                ->first();
            $userVote = $vote ? $vote->type : null;
        }
        $post->setAttribute('user_vote', $userVote);

        $ads = AdPlacement::where('is_active', true)
            ->whereIn('placement_key',[
                'article_header',
                'article_mobile_top',
                'article_after_cover',
                'article_sidebar_top',
                'article_sidebar_bottom'
            ])
            ->get()
            ->keyBy('placement_key');

        $inlineRelated =[];
        $enableInline = Setting::where('group', 'post')->where('key', 'enable_inline_related')->value('value');

        if ($enableInline !== 'false') {
            $inlineRelated = Post::select('id', 'title', 'slug', 'image_path', 'created_at', 'category_id')
                ->where('category_id', $post->category_id)
                ->where('id', '!=', $post->id)
                ->where('status', 'published')
                ->inRandomOrder()
                ->take(4)
                ->get();
        }

        $showRightSidebar = Setting::where('group', 'post')->where('key', 'show_right_sidebar')->value('value') !== 'false';
        $sidebarData = ['you_may_like' => [], 'same_category' =>[]];

        if ($showRightSidebar) {
            $trending = Post::select('id', 'title', 'slug', 'image_path', 'created_at', 'views_count')
                ->where('status', 'published')
                ->where('id', '!=', $post->id)
                ->where('created_at', '>=', now()->subDays(7))
                ->orderBy('views_count', 'desc')
                ->take(3)
                ->get();
                
            if ($trending->isEmpty()) {
                $trending = Post::select('id', 'title', 'slug', 'image_path', 'created_at', 'views_count')
                    ->where('status', 'published')
                    ->where('id', '!=', $post->id)
                    ->orderBy('views_count', 'desc')
                    ->take(3)
                    ->get();
            }

            $sameCategory =[];
            if ($post->category_id) {
                $sameCategory = Post::select('id', 'title', 'slug', 'image_path', 'created_at')
                    ->where('status', 'published')
                    ->where('category_id', $post->category_id)
                    ->where('id', '!=', $post->id)
                    ->latest()
                    ->take(3)
                    ->get();
            }

            $sidebarData =[
                'you_may_like' => $trending,
                'same_category' => $sameCategory
            ];
        }

        return Inertia::render('News/Show',[
            'post' => $post,
            'ads' => $ads,
            'inlineRelated' => $inlineRelated,
            'initialSidebarData' => $sidebarData,
        ]);
    }

    /**
     * Search Posts
     */
    public function search(Request $request)
    {
        $query = $request->input('q');

        $posts = Post::with(['user', 'category', 'rssFeed']) 
            ->where('status', 'published')
            ->where(function($q) use ($query) {
                $q->where('title', 'like', "%{$query}%")
                  ->orWhere('meta_description', 'like', "%{$query}%")
                  ->orWhere('content', 'like', "%{$query}%");
            })
            ->latest()
            ->paginate(12)
            ->withQueryString();

        return Inertia::render('News/Search',[
            'query' => $query,
            'posts' => $posts,
        ]);
    }
}