<?php

namespace App\Http\Controllers;

use App\Models\Article;
use App\Models\Category;
use App\Models\Tag;
use Illuminate\Http\Request;
use Inertia\Inertia;
use Inertia\Response;

class PipopaBlogController extends Controller
{
    private int $_articleType = 1;

    /**
     * Display a listing of blog posts.
     */
    public function index(Request $request): Response
    {
        $categories = Category::where('type', $this->_articleType)->get();

        // Get category filter
        $categoryFilter = $request->get('category', 'all');

        // Build query
        $query = Article::published()
            ->where('type', $this->_articleType)
            ->with(['user', 'categories', 'tags'])
            ->orderBy('created_at', 'desc');

        // Apply category filter
        if ($categoryFilter !== 'all') {
            $query->whereHas('categories', function ($q) use ($categoryFilter) {
                $q->where('type', $this->_articleType)->where('slug', $categoryFilter);
            });
        }

        // Paginate results
        $articles = $query->paginate(6);

        // Get featured article (most viewed)
        $featuredArticle = Article::published()
            ->where('type', $this->_articleType)
            ->with(['user', 'categories', 'tags'])
            ->orderBy('views', 'desc')
            ->first();

        // Transform data for frontend
        $articlesData = $articles->through(function ($article) {
            return [
                'id'       => $article->id,
                'title'    => $article->title,
                'slug'     => $article->slug,
                'excerpt'  => $article->description,
                'content'  => $article->content,
                'category' => $article->categories->first()?->name ?? 'お知らせ',
                'date'     => $article->created_at->format('Y年n月j日'),
                'readTime' => $article->view_time,
                'image'    => $article->image ?: 'https://placehold.co/400x250/6366F1/FFFFFF?text=Blog+' . $article->id,
                'views'    => $article->views,
                'author'   => [
                    'name'   => $article->user->name,
                    'avatar' => $article->user->avatar ?? 'https://placehold.co/64x64/E5E7EB/6B7280?text=Author',
                ],
                'tags' => $article->tags->pluck('name')->toArray(),
            ];
        });

        // Categories for frontend
        $categoriesData = collect([
            ['id' => 'all', 'name' => 'すべて'],
        ])->merge($categories->map(function ($category) {
            return [
                'id'   => $category->slug,
                'name' => $category->name,
            ];
        }));

        // Transform featured article data
        $featuredArticleData = $featuredArticle ? [
            'id'          => $featuredArticle->id,
            'title'       => $featuredArticle->title,
            'slug'        => $featuredArticle->slug,
            'description' => $featuredArticle->description,
            'category'    => $featuredArticle->categories->first()?->name ?? 'お知らせ',
            'date'        => $featuredArticle->created_at->format('Y年n月j日'),
            'readTime'    => $featuredArticle->view_time . '分で読める',
            'image'       => $featuredArticle->image ?: 'https://placehold.co/600x400/6366F1/FFFFFF?text=Featured+Article',
            'views'       => $featuredArticle->views,
        ] : null;

        return Inertia::render('pipopa/Blog', [
            'articles'        => $articlesData,
            'categories'      => $categoriesData,
            'currentCategory' => $categoryFilter,
            'featuredArticle' => $featuredArticleData,
            'pagination'      => [
                'current_page' => $articles->currentPage(),
                'last_page'    => $articles->lastPage(),
                'per_page'     => $articles->perPage(),
                'total'        => $articles->total(),
                'from'         => $articles->firstItem(),
                'to'           => $articles->lastItem(),
            ],
        ]);
    }

    /**
     * Display the specified blog post.
     */
    public function show(Request $request, string $slug): Response
    {
        // Check if preview parameter is provided
        $previewKey = $request->get('preview');

        // Build query based on whether it's a preview or not
        if ($previewKey) {
            // For preview: check both published and unpublished articles with matching preview key
            $article = Article::where('type', $this->_articleType)
                ->with(['user', 'categories', 'tags'])
                ->where('slug', $slug)
                ->where('preview_key', $previewKey)
                ->firstOrFail();
        } else {
            // For normal view: only published articles
            $article = Article::published()
                ->where('type', $this->_articleType)
                ->with(['user', 'categories', 'tags'])
                ->where('slug', $slug)
                ->firstOrFail();
        }

        // Track view with IP-based session limit
        $ipAddress = $request->ip();
        $article->trackView($ipAddress);

        // Get related articles
        $relatedArticles = Article::published()
            ->where('type', $this->_articleType)
            ->with(['user', 'categories'])
            ->where('id', '!=', $article->id)
            ->whereHas('categories', function ($query) use ($article) {
                $categoryIds = $article->categories->pluck('id');
                $query->whereIn('categories.id', $categoryIds);
            })
            ->orderBy('created_at', 'desc')
            ->limit(3)
            ->get();

        // Generate SEO keywords from categories and tags
        $categoryNames = $article->categories->pluck('name')->toArray();
        $tagNames = $article->tags->pluck('name')->toArray();
        $keywords = array_merge($categoryNames, $tagNames, ['AI', 'チャットボット', 'pipopa']);
        $keywordsString = implode(', ', array_unique($keywords));

        // Transform article data
        $articleData = [
            'id'          => $article->id,
            'title'       => $article->title,
            'slug'        => $article->slug,
            'description' => $article->description,
            'content'     => $article->content,
            'category'    => $article->categories->first()?->name ?? 'お知らせ',
            'date'        => $article->created_at->format('Y年n月j日'),
            'readTime'    => $article->view_time . '分で読める',
            'image'       => $article->image ?
                (str_starts_with($article->image, 'http') ? $article->image : request()->getSchemeAndHttpHost() . $article->image) :
                'https://placehold.co/600x400/6366F1/FFFFFF?text=Blog+' . $article->id,
            'views'  => $article->views,
            'author' => [
                'name'   => $article->user->name,
                'role'   => $article->user->role ?? 'pipopaマーケティング部',
                'avatar' => $article->user->avatar ?? 'https://placehold.co/64x64/E5E7EB/6B7280?text=Author',
            ],
            'tags' => $article->tags->map(function ($tag) {
                return [
                    'name' => $tag->name,
                    'slug' => $tag->slug,
                ];
            })->toArray(),
            'keywords' => $keywordsString,
        ];

        // Transform related articles
        $relatedArticlesData = $relatedArticles->map(function ($relatedArticle) {
            return [
                'id'          => $relatedArticle->id,
                'title'       => $relatedArticle->title,
                'slug'        => $relatedArticle->slug,
                'description' => $relatedArticle->description,
                'category'    => $relatedArticle->categories->first()?->name ?? 'お知らせ',
                'date'        => $relatedArticle->created_at->format('Y年n月j日'),
                'image'       => $relatedArticle->image ?: 'https://placehold.co/400x250/6366F1/FFFFFF?text=Blog+' . $relatedArticle->id,
            ];
        });

        return Inertia::render('pipopa/BlogDetail', [
            'article'         => $articleData,
            'relatedArticles' => $relatedArticlesData,
        ]);
    }

    /**
     * Display blog posts by category.
     */
    public function category(string $category): Response
    {
        $categories = Category::where('type', $this->_articleType)->get();

        // Get category filter
        $categoryFilter = $category;

        // Build query
        $query = Article::published()
            ->where('type', $this->_articleType)
            ->with(['user', 'categories', 'tags'])
            ->orderBy('created_at', 'desc');

        // Apply category filter
        $query->whereHas('categories', function ($q) use ($categoryFilter) {
            $q->where('type', $this->_articleType)->where('slug', $categoryFilter);
        });

        // Paginate results
        $articles = $query->paginate(6);

        // Get featured article (most viewed in this category)
        $featuredArticle = Article::published()
            ->where('type', $this->_articleType)
            ->with(['user', 'categories', 'tags'])
            ->whereHas('categories', function ($q) use ($categoryFilter) {
                $q->where('type', $this->_articleType)->where('slug', $categoryFilter);
            })
            ->orderBy('views', 'desc')
            ->first();

        // Transform data for frontend
        $articlesData = $articles->through(function ($article) {
            return [
                'id'       => $article->id,
                'title'    => $article->title,
                'slug'     => $article->slug,
                'excerpt'  => $article->description,
                'content'  => $article->content,
                'category' => $article->categories->first()?->name ?? 'お知らせ',
                'date'     => $article->created_at->format('Y年n月j日'),
                'readTime' => $article->view_time,
                'image'    => $article->image ?: 'https://placehold.co/400x250/6366F1/FFFFFF?text=Blog+' . $article->id,
                'views'    => $article->views,
                'author'   => [
                    'name'   => $article->user->name,
                    'avatar' => $article->user->avatar ?? 'https://placehold.co/64x64/E5E7EB/6B7280?text=Author',
                ],
                'tags' => $article->tags->pluck('name')->toArray(),
            ];
        });

        // Categories for frontend
        $categoriesData = collect([
            ['id' => 'all', 'name' => 'すべて'],
        ])->merge($categories->map(function ($categoryItem) {
            return [
                'id'   => $categoryItem->slug,
                'name' => $categoryItem->name,
            ];
        }));

        // Transform featured article data
        $featuredArticleData = $featuredArticle ? [
            'id'          => $featuredArticle->id,
            'title'       => $featuredArticle->title,
            'slug'        => $featuredArticle->slug,
            'description' => $featuredArticle->description,
            'category'    => $featuredArticle->categories->first()?->name ?? 'お知らせ',
            'date'        => $featuredArticle->created_at->format('Y年n月j日'),
            'readTime'    => $featuredArticle->view_time . '分で読める',
            'image'       => $featuredArticle->image ?: 'https://placehold.co/600x400/6366F1/FFFFFF?text=Featured+Article',
            'views'       => $featuredArticle->views,
        ] : null;

        return Inertia::render('pipopa/Blog', [
            'articles'        => $articlesData,
            'categories'      => $categoriesData,
            'currentCategory' => $categoryFilter,
            'featuredArticle' => $featuredArticleData,
            'pagination'      => [
                'current_page' => $articles->currentPage(),
                'last_page'    => $articles->lastPage(),
                'per_page'     => $articles->perPage(),
                'total'        => $articles->total(),
                'from'         => $articles->firstItem(),
                'to'           => $articles->lastItem(),
            ],
        ]);
    }

    /**
     * Display blog posts by tag.
     */
    public function tag(Request $request, string $tag): Response
    {
        $tags = Tag::where('type', $this->_articleType)->get();

        // Get tag filter
        $tagFilter = $tag;

        // Build query
        $query = Article::published()
            ->where('type', $this->_articleType)
            ->with(['user', 'categories', 'tags'])
            ->orderBy('created_at', 'desc');

        // Apply tag filter
        $query->whereHas('tags', function ($q) use ($tagFilter) {
            $q->where('type', $this->_articleType)->where('slug', $tagFilter);
        });

        // Paginate results
        $articles = $query->paginate(6);

        // Get featured article (most viewed in this tag)
        $featuredArticle = Article::published()
            ->where('type', $this->_articleType)
            ->with(['user', 'categories', 'tags'])
            ->whereHas('tags', function ($q) use ($tagFilter) {
                $q->where('type', $this->_articleType)->where('slug', $tagFilter);
            })
            ->orderBy('views', 'desc')
            ->first();

        // Transform data for frontend
        $articlesData = $articles->through(function ($article) {
            return [
                'id'       => $article->id,
                'title'    => $article->title,
                'slug'     => $article->slug,
                'excerpt'  => $article->description,
                'content'  => $article->content,
                'category' => $article->categories->first()?->name ?? 'お知らせ',
                'date'     => $article->created_at->format('Y年n月j日'),
                'readTime' => $article->view_time,
                'image'    => $article->image ?: 'https://placehold.co/400x250/6366F1/FFFFFF?text=Blog+' . $article->id,
                'views'    => $article->views,
                'author'   => [
                    'name'   => $article->user->name,
                    'avatar' => $article->user->avatar ?? 'https://placehold.co/64x64/E5E7EB/6B7280?text=Author',
                ],
                'tags' => $article->tags->pluck('name')->toArray(),
            ];
        });

        // Tags for frontend
        $tagsData = collect([
            ['id' => 'all', 'name' => 'すべて'],
        ])->merge($tags->map(function ($tagItem) {
            return [
                'id'   => $tagItem->slug,
                'name' => $tagItem->name,
            ];
        }));

        // Transform featured article data
        $featuredArticleData = $featuredArticle ? [
            'id'          => $featuredArticle->id,
            'title'       => $featuredArticle->title,
            'slug'        => $featuredArticle->slug,
            'description' => $featuredArticle->description,
            'category'    => $featuredArticle->categories->first()?->name ?? 'お知らせ',
            'date'        => $featuredArticle->created_at->format('Y年n月j日'),
            'readTime'    => $featuredArticle->view_time . '分で読める',
            'image'       => $featuredArticle->image ?: 'https://placehold.co/600x400/6366F1/FFFFFF?text=Featured+Article',
            'views'       => $featuredArticle->views,
        ] : null;

        return Inertia::render('pipopa/BlogTag', [
            'articles'        => $articlesData,
            'tags'            => $tagsData,
            'currentTag'      => $tagFilter,
            'featuredArticle' => $featuredArticleData,
            'pagination'      => [
                'current_page' => $articles->currentPage(),
                'last_page'    => $articles->lastPage(),
                'per_page'     => $articles->perPage(),
                'total'        => $articles->total(),
                'from'         => $articles->firstItem(),
                'to'           => $articles->lastItem(),
            ],
        ]);
    }
}
