<?php

namespace App\Http\Controllers;

use App\Models\Product;
use App\Models\ProductCategory;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class AmazingController extends Controller
{
    public function index(Request $request)
    {
        $sort       = $request->input('sort', 'default');
        $catIds     = array_values(array_filter(array_map('intval', (array) $request->input('categories', []))));
        $priceMin   = (int) $request->input('price_min', 0);
        $priceMax   = (int) $request->input('price_max', 0);
        $search     = trim($request->input('q', ''));

        $query = Product::where('is_active', true)
            ->where('is_amazing_offer', true)
            ->with(['variants' => fn($q) => $q->where('is_active', true)->orderBy('price'), 'images']);

        if (!empty($catIds)) {
            $query->whereHas('categories', fn($q) => $q->whereIn('id', $catIds));
        }

        if ($search !== '') {
            $query->where(function ($q) use ($search) {
                $q->where('title', 'like', "%{$search}%")
                  ->orWhere('title_en', 'like', "%{$search}%")
                  ->orWhere('tags', 'like', "%{$search}%");
            });
        }

        if ($priceMin > 0 || $priceMax > 0) {
            $query->whereHas('variants', function ($q) use ($priceMin, $priceMax) {
                $q->where('is_active', true);
                if ($priceMin > 0) $q->where('price', '>=', $priceMin);
                if ($priceMax > 0) $q->where('price', '<=', $priceMax);
            });
        }

        $query->orderInStockFirst();

        switch ($sort) {
            case 'popular':
                $query->orderByRaw(
                    '(SELECT COALESCE(AVG(rating), 0) FROM product_reviews WHERE product_id = products.id AND status = "approved") DESC'
                );
                break;
            case 'best_sellers':
                $query->orderByDesc('sales');
                break;
            case 'newest':
                $query->latest();
                break;
            case 'cheapest':
                $query->orderByRaw(
                    '(SELECT MIN(price) FROM product_variants WHERE product_id = products.id AND is_active = 1) ASC'
                );
                break;
            case 'most_expensive':
                $query->orderByRaw(
                    '(SELECT MAX(price) FROM product_variants WHERE product_id = products.id AND is_active = 1) DESC'
                );
                break;
            default:
                $query->orderBy('sort_order')->orderByDesc('id');
                break;
        }

        $products = $query->paginate(12)->withQueryString();

        $categoryTree = ProductCategory::flatTree();

        $maxPrice = (int) (DB::table('product_variants')->where('is_active', true)->max('price') ?? 50000000);
        if ($maxPrice < 1000) {
            $maxPrice = 50000000;
        }

        return view('site.amazing', compact(
            'products', 'categoryTree', 'maxPrice',
            'sort', 'catIds', 'priceMin', 'priceMax', 'search'
        ));
    }
}
