<?php

namespace App\Http\Controllers\Frontend;

use App\Http\Controllers\Controller;
use App\Models\Product;
use App\Models\ProductCategory;

class ShopController extends Controller
{
    public function index()
    {
        $query = Product::select('products.*')->withAvg('reviews', 'rating');

        
        // Apply Filters & Sort
        $this->applyFiltersAndSort($query);

        // Filter by Category (Specific to Index)
        if (request()->filled('category')) {
            $categorySlugs = (array) request()->input('category');
            $categoryIds = ProductCategory::whereIn('slug', $categorySlugs)->pluck('id');
            $query->whereIn('category_id', $categoryIds);
        }

        // Setup Meta Data
        $data['title'] = __('shop.title|All Products');
        $data['subtitle'] = __('shop.Discover our complete collection of premium digital products');

        if (request()->filled('q')) {
            $data['title'] = __('shop.title|Search results for: ":query"', ['query' => request('q')]);

            $data['subtitle'] = __('shop.Showing results matching your search criteria');
        } elseif (request()->filled('category')) {
            $categorySlugs = (array) request()->input('category');
            if (count($categorySlugs) === 1) {
                $selectedCat = ProductCategory::where('slug', $categorySlugs[0])->first();
                if ($selectedCat) {
                    $data['title'] = $selectedCat->name;
                    $data['subtitle'] = $selectedCat->description;
                }
            }
        }

        $data['categories'] = ProductCategory::whereHas('products')->orderBy('name')->get();
        $data['products'] = $query->paginate(setting('products.per_page', 9));
        $data['selectedCategory'] = request()->input('category', []);
        $data['q'] = request()->input('q');

        $data['pageHeader'] = [
            'title' => $data['title'],
            'subtitle' => $data['subtitle'],
            'breadcrumbs' => [
                ['label' => __('general.Home'), 'url' => url('/')],
                ['label' => __('shop.Shop')],
            ]
        ];

        return view('theme::pages.shop.index', $data);
    }

    public function category($slug)
    {
        $category = ProductCategory::where('slug', $slug)->firstOrFail();
        
        $query = Product::select('products.*')->where('category_id', $category->id)->withAvg('reviews', 'rating');
        
        // Apply Filters & Sort
        $this->applyFiltersAndSort($query);

        $data['title'] = $category->name;
        $data['subtitle'] = $category->description;
        $data['categories'] = ProductCategory::whereHas('products')->orderBy('name')->get();
        $data['products'] = $query->paginate(setting('products.per_page', 9));
        $data['selectedCategory'] = [$category->slug];
        $data['q'] = '';

        $data['pageHeader'] = [
            'title' => $category->name,
            'subtitle' => $category->description ?? __('shop.Browse products in :category', ['category' => $category->name]),
            'breadcrumbs' => [
                ['label' => __('general.Home'), 'url' => url('/')],
                ['label' => __('shop.Shop'), 'url' => route('frontend.products.all')],
                ['label' => $category->name],
            ]
        ];

        return view('theme::pages.shop.index', $data);
    }

    private function applyFiltersAndSort($query)
    {
        // Filter by Search
        if (request()->filled('q')) {
            $search = request()->input('q');
            $query->where(function ($q) use ($search) {
                $q->where('name', 'LIKE', "%{$search}%")
                    ->orWhere('description', 'LIKE', "%{$search}%");
            });
        }

        // Sorting
        $sort = request()->input('sort', 'newest');
        switch ($sort) {
            case 'oldest':
                $query->oldest('products.created_at');
                break;
            case 'price_asc':
                $query->leftJoin('plans', function($join) {
                        $join->on('products.id', '=', 'plans.product_id')
                             ->where('plans.is_default', 1);
                    })
                      ->leftJoin('pricing_tiers', 'plans.id', '=', 'pricing_tiers.plan_id')
                      ->orderBy('pricing_tiers.price', 'asc');
                break;
            case 'price_desc':
                $query->leftJoin('plans', function($join) {
                        $join->on('products.id', '=', 'plans.product_id')
                             ->where('plans.is_default', 1);
                    })
                      ->leftJoin('pricing_tiers', 'plans.id', '=', 'pricing_tiers.plan_id')
                      ->orderBy('pricing_tiers.price', 'desc');
                break;
            case 'rating':
                $query->orderByDesc('reviews_avg_rating');
                break;
            case 'newest':
            default:
                $query->latest('products.created_at');
                break;
        }
    }
}
