<?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 MattockBlogController extends Controller
{
    private int $_articleType = 0;

    /**
     * Display a listing of blog posts.
     */
    public function index(Request $request): Response
    {
        // Handle WordPress legacy preview URLs
        if ($request->has('p') && $request->get('preview') === 'true') {
            $this->handleWordPressPreview($request);
        }

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

        // Build query
        $query = Article::published()
            ->where('type', $this->_articleType)
            ->with(['user', 'primaryCategory', '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(4);

        // Transform data for frontend
        $articlesData = $articles->through(function ($article) {
            return [
                'id'               => $article->id,
                'title'            => $article->title,
                'slug'             => $article->slug,
                'description'      => $article->description,
                'category'         => $article->categories->first()?->name ?? 'お知らせ',
                'primary_category' => [
                    'id'        => $article->primaryCategory->id ?? null,
                    'name'      => $article->primaryCategory->name ?? null,
                    'slug'      => $article->primaryCategory->slug ?? 'detail',
                    'full_slug' => $article->primaryCategory->full_slug ?? $article->primaryCategory->slug,
                    'parent'    => $article->primaryCategory->parent ?? null,
                ],
                '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(),
            ];
        });

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

        $rankingArticlesData = $rankingArticle->map(function ($article) {
            return [
                'id'               => $article->id,
                'title'            => $article->title,
                'slug'             => $article->slug,
                'description'      => $article->description,
                'category'         => $article->categories->first()?->name ?? 'お知らせ',
                'primary_category' => [
                    'id'        => $article->primaryCategory->id ?? null,
                    'name'      => $article->primaryCategory->name ?? null,
                    'slug'      => $article->primaryCategory->slug ?? 'detail',
                    'full_slug' => $article->primaryCategory->full_slug ?? $article->primaryCategory->slug,
                    'parent'    => $article->primaryCategory->parent ?? null,
                ],
                'date'     => $article->created_at->format('Y.m.d'),
                'readTime' => $article->view_time . '分で読める',
                'image'    => $article->image ?: 'https://placehold.co/600x400/6366F1/FFFFFF?text=Ranking+Article',
                'views'    => $article->views ? number_format($article->views) : 0,
                '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
        $categories = Category::where('type', $this->_articleType)
            ->with('publishedArticles')
            ->limit(8)
            ->orderBy('created_at')
            ->get();
        $categoriesData = $categories->map(function ($category) {
            return [
                'id'          => $category->slug,
                'name'        => $category->name,
                'description' => $category->description,
                'postCount'   => $category->publishedArticles ? $category->publishedArticles->count() : 0,
            ];
        });

        return Inertia::render('mattock/Blog', [
            'articles'        => $articlesData,
            'categories'      => $categoriesData,
            'currentCategory' => $categoryFilter,
            'rankingArticle'  => $rankingArticlesData,
            '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 $category, string $slug): Response
    {
        // Check if preview parameter is provided
        $previewKey = $request->get('preview');

        // Url decode slug
        $slug = urlencode($slug);

        // 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', 'primaryCategory', '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', 'primaryCategory', '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', 'primaryCategory', '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(2)
            ->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, ['mattock']);
        $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'         => $categoryNames,
            'primary_category' => [
                'id'        => $article->primaryCategory->id ?? null,
                'name'      => $article->primaryCategory->name ?? null,
                'slug'      => $article->primaryCategory->slug ?? 'detail',
                'full_slug' => $article->primaryCategory->full_slug ?? $article->primaryCategory->slug,
                'parent'    => $article->primaryCategory->parent ?? null,
            ],
            'date'     => $article->created_at->format('Y年m月d日'), // 2024年12月15日
            '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=Article+' . $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->map(function ($tag) {
                return [
                    'name' => $tag->name,
                    'slug' => $tag->slug,
                ];
            })->toArray(),
            'keywords' => $keywordsString,
        ];

        // Transform related articles
        $relatedArticlesData = $relatedArticles->map(function ($article) {
            return [
                'id'               => $article->id,
                'title'            => $article->title,
                'slug'             => $article->slug,
                'description'      => $article->description,
                'category'         => $article->categories->pluck('name')->toArray(),
                'primary_category' => [
                    'id'        => $article->primaryCategory->id ?? null,
                    'name'      => $article->primaryCategory->name ?? null,
                    'slug'      => $article->primaryCategory->slug ?? 'detail',
                    'full_slug' => $article->primaryCategory->full_slug ?? $article->primaryCategory->slug,
                    'parent'    => $article->primaryCategory->parent ?? null,
                ],
                'date'     => $article->created_at->format('Y.m.d'),
                'readTime' => "約{$article->view_time}分で読了",
                'image'    => $article->image ?: 'https://placehold.co/400x250/6366F1/FFFFFF?text=Blog+' . $article->id,
                'views'    => $article->views ? number_format($article->views) : 0,
                'author'   => [
                    'name'   => $article->user->name,
                    'avatar' => $article->user->avatar ?? 'https://placehold.co/64x64/E5E7EB/6B7280?text=Author',
                ],
                'tags' => $article->tags->pluck('name')->toArray(),
            ];
        });

        // Get featured article (most viewed)
        $rankingArticle = Article::published()
            ->with(['user', 'primaryCategory', 'categories', 'tags'])
            ->where('type', $this->_articleType)
            ->where('id', '!=', $article->id)
            ->where('views', '>', 0)
            ->orderBy('views', 'desc')
            ->limit(3)
            ->get();

        $rankingArticlesData = $rankingArticle->map(function ($article) {
            return [
                'id'               => $article->id,
                'title'            => $article->title,
                'slug'             => $article->slug,
                'description'      => $article->description,
                'category'         => $article->categories->pluck('name')->toArray(),
                'primary_category' => [
                    'id'        => $article->primaryCategory->id ?? null,
                    'name'      => $article->primaryCategory->name ?? null,
                    'slug'      => $article->primaryCategory->slug ?? 'detail',
                    'full_slug' => $article->primaryCategory->full_slug ?? $article->primaryCategory->slug,
                    'parent'    => $article->primaryCategory->parent ?? null,
                ],
                'date'     => $article->created_at->format('Y.m.d'),
                'readTime' => "約{$article->view_time}分で読了",
                'image'    => $article->image ?: 'https://placehold.co/600x400/6366F1/FFFFFF?text=Ranking+Article',
                'views'    => $article->views ? number_format($article->views) : 0,
                'author'   => [
                    'name'   => $article->user->name,
                    'avatar' => $article->user->avatar ?? 'https://placehold.co/64x64/E5E7EB/6B7280?text=Author',
                ],
                'tags' => $article->tags->pluck('name')->toArray(),
            ];
        });

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

    /**
     * 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->id,
                'slug' => $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('mattock/BlogCategory', [
            '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('mattock/Blog', [
            '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(),
            ],
        ]);
    }

    /**
     * Display the specified blog post.
     */
    public function show1(Request $request, string $category1, string $category, string $slug): Response
    {
        return $this->show($request, $category, $slug);
    }

    /**
     * Display the specified blog post.
     */
    public function show2(Request $request, string $category2, string $category1, string $category, string $slug): Response
    {
        return $this->show($request, $category, $slug);
    }

    /**
     * Display the specified blog post.
     */
    public function show3(Request $request, string $category3, string $category2, string $category1, string $category, string $slug): Response
    {
        return $this->show($request, $category, $slug);
    }

    /**
     * Display the specified blog post.
     */
    public function show4(Request $request, string $category4, string $category3, string $category2, string $category1, string $category, string $slug): Response
    {
        return $this->show($request, $category, $slug);
    }

    /**
     * Handle WordPress legacy preview URLs (?p=ID&preview=true)
     */
    private function handleWordPressPreview(Request $request): void
    {
        $articleId = $request->get('p');

        // Find article by ID
        $article = Article::where('wp_id', $articleId)->first();
		if (!$article) {
			$article = Article::find($articleId);
		}

        if (! $article) {
            abort(404, 'The article does not exist');
        }

        // Build redirect URL based on article type
        if ($article->type == 0) {
            // Normal blog post: /blog/{hierarchical_category_path}/{article_slug}
            $categoryData = $this->buildCategoryHierarchy($article->primaryCategory);
            $url = $this->buildBlogDetailUrl($categoryData, $article->slug);
        } elseif ($article->type == 1) {
            // AI Chatbot post: /blog/ai-chatbot/{article_slug}
            $url = route('blog.detail', [
                'category' => 'ai-chatbot',
                'slug'     => $article->slug,
            ]);
        } else {
	        abort(404, 'The article category does not exist');
        }

        // Add preview parameter if article is not published
        if ($article->status !== 'publish') {
            $url .= '?preview=' . $article->preview_key;
        }

        redirect($url, 301)->send();
        exit;
    }

    /**
     * Build hierarchical category path from parent to child
     */
    private function buildCategoryHierarchy($category): array
    {
        if (! $category) {
            return ['detail'];
        }

        $slugs = [];
        $current = $category;

        // Collect all parent slugs from current to root
        while ($current) {
            array_unshift($slugs, $current->slug);
            $current = $current->parent;
        }

        return $slugs;
    }

    /**
     * Build blog detail URL based on category hierarchy depth
     */
    private function buildBlogDetailUrl(array $categorySlugs, string $articleSlug): string
    {
        $depth = count($categorySlugs);

        switch ($depth) {
            case 1:
                return route('blog.detail', [
                    'category' => $categorySlugs[0],
                    'slug'     => $articleSlug,
                ]);
            case 2:
                return route('blog.detail1', [
                    'category1' => $categorySlugs[0],
                    'category'  => $categorySlugs[1],
                    'slug'      => $articleSlug,
                ]);
            case 3:
                return route('blog.detail2', [
                    'category2' => $categorySlugs[0],
                    'category1' => $categorySlugs[1],
                    'category'  => $categorySlugs[2],
                    'slug'      => $articleSlug,
                ]);
            case 4:
                return route('blog.detail3', [
                    'category3' => $categorySlugs[0],
                    'category2' => $categorySlugs[1],
                    'category1' => $categorySlugs[2],
                    'category'  => $categorySlugs[3],
                    'slug'      => $articleSlug,
                ]);
            case 5:
                return route('blog.detail4', [
                    'category4' => $categorySlugs[0],
                    'category3' => $categorySlugs[1],
                    'category2' => $categorySlugs[2],
                    'category1' => $categorySlugs[3],
                    'category'  => $categorySlugs[4],
                    'slug'      => $articleSlug,
                ]);
            default:
                // Fallback to basic route if more than 5 levels
                return route('blog.detail', [
                    'category' => end($categorySlugs),
                    'slug'     => $articleSlug,
                ]);
        }
    }
}
