<?php

namespace App\Http\Controllers\Marketplace;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\Category;
use App\Models\Product;
use Inertia\Inertia;

class CategoryViewController extends Controller
{
    public function show(Request $request, $slug)
    {
        // 1. Find the category
        $category = Category::with('parent')->where('slug', $slug)->where('is_active', true)->firstOrFail();

        // 2. Determine sorting
        $sort = $request->query('sort', 'latest');

        // 3. Gather Category IDs
        $categoryIds = [$category->id];
        if (is_null($category->parent_id)) {
            $childIds = Category::where('parent_id', $category->id)->pluck('id')->toArray();
            $categoryIds = array_merge($categoryIds, $childIds);
        }

        // 4. Build Product Query (UPDATED to include flash_sale_percentage)
        $productsQuery = Product::with(['images', 'seller:id,company_name,name,country_id,flash_sale_percentage', 'seller.country'])
            ->where(function($q) use ($categoryIds) {
                $q->whereIn('category_id', $categoryIds)
                  ->orWhereIn('subcategory_id', $categoryIds);
            });

        // 5. Apply Sorting
        switch ($sort) {
            case 'price_low':
                $productsQuery->orderBy('price', 'asc');
                break;
            case 'price_high':
                $productsQuery->orderBy('price', 'desc');
                break;
            case 'latest':
            default:
                $productsQuery->latest();
                break;
        }

        $products = $productsQuery->paginate(16)->withQueryString();

        // --- SEO DATA ---
        $seoProps = [
            'title' => $category->name . ' Products',
            'description' => $category->meta_description ?: "Browse our wide range of products in the {$category->name} category.",
            'url' => url()->current(),
        ];
        if ($category->image_path) {
            $seoProps['images'] = [asset('storage/' . $category->image_path)];
        }

        return Inertia::render('Marketplace/Category', [
            'category' => $category,
            'products' => $products,
            'currentSort' => $sort,
            'seo' => $seoProps 
        ]);
    }
}