<?php

namespace App\Http\Controllers\Legacy;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Services\ArtworkService;
use App\Models\Category;
use Illuminate\Support\Str;
use Illuminate\Database\Eloquent\ModelNotFoundException;

class CategoryController extends Controller
{
    protected ArtworkService $artworkService;

    public function __construct(ArtworkService $artworkService)
    {
        $this->artworkService = $artworkService;
    }

    public function show(Request $request, $id, $slug = null, $group = null)
    {
        // Parse request path after '/category' to support unlimited depth and legacy routes
        $path = trim($request->path(), '/');
        $segments = array_values(array_filter(explode('/', $path)));

        // Expecting segments like ['category', '{contentType}', '{...categorySlugs}']
        if (count($segments) < 2 || strtolower($segments[0]) !== 'category') {
            return view('legacy::placeholder');
        }

        $parts = array_slice($segments, 1);

        // If first part is numeric, attempt id->category resolution and redirect to canonical slug URL
        $first = $parts[0] ?? null;
        if ($first !== null && ctype_digit((string) $first)) {
            try {
                $category = Category::findOrFail((int) $first);
                $contentTypeSlug = $category->contentType->slug ?? null;
                $canonical = '/' . strtolower($contentTypeSlug) . '/' . $category->full_slug_path;
                return redirect($canonical, 301);
            } catch (ModelNotFoundException $e) {
                abort(404);
            }
        }

        // Build slug list: first element is content type slug, rest are category slugs
        $contentTypeSlug = array_shift($parts);
        $slugs = array_merge([$contentTypeSlug], $parts);

        $perPage = (int) $request->get('per_page', 40);
        $sort = (string) $request->get('sort', 'latest');

        try {
            $artworks = $this->artworkService->getArtworksByCategoryPath($slugs, $perPage, $sort);
        } catch (ModelNotFoundException $e) {
            abort(404);
        }

        // Resolve Category model for page meta and subcategories
        // Use the contentType + path traversal to find the category
        try {
            $category = Category::whereHas('contentType', function ($q) use ($contentTypeSlug) {
                $q->where('slug', strtolower($contentTypeSlug));
            })->whereNull('parent_id')->where('slug', strtolower($parts[0] ?? ''))->first();

            // If deeper path exists, traverse
            if ($category && count($parts) > 1) {
                $cur = $category;
                foreach (array_slice($parts, 1) as $slugPart) {
                    $cur = $cur->children()->where('slug', strtolower($slugPart))->first();
                    if (! $cur) {
                        abort(404);
                    }
                }
                $category = $cur;
            }
        } catch (\Throwable $e) {
            $category = null;
        }

        if (! $category) {
            // Category resolution failed
            abort(404);
        }

        $subcategories = $category->children()->orderBy('sort_order')->orderBy('name')->get();

        $page_title = $category->name;
        $page_meta_description = $category->description ?? ($category->contentType->name . ' artworks on Skinbase');
        $page_meta_keywords = strtolower($category->contentType->slug) . ', skinbase, artworks, wallpapers, skins, photography';

        return view('legacy::category', compact(
            'page_title',
            'page_meta_description',
            'page_meta_keywords',
            'group',
            'category',
            'subcategories',
            'artworks'
        ));
    }

    public function browseCategories()
    {
        $data = $this->legacy->browseCategories();
        return view('legacy::categories', $data);
    }
}
