<?php

namespace App\Livewire\User;

use App\Models\Category;
use App\Models\Product;
use Livewire\Attributes\Layout;
use Livewire\Component;
use Livewire\WithPagination;

#[Layout('components.user-layout')]
class ProductByCategory extends Component
{
    use WithPagination;

    public $categories;
    public $category;
    public $categorySlug;

    public function mount($slug = null)
    {
        $this->categorySlug = $slug;
        $this->loadData();
    }

    public function loadData()
    {
        // Load all categories
        $this->categories = Category::orderBy('id', 'asc')->get();

        // Find the current category
        if ($this->categorySlug) {
            $this->category = Category::where('slug', $this->categorySlug)->first();
            
            // If no category is found, redirect to homepage
            if (!$this->category) {
                return redirect()->route('index')->with('error', 'Category not found');
            }
        } else {
            // If no slug provided, redirect to homepage
            return redirect()->route('index')->with('error', 'Category not specified');
        }

        // Load other categories (excluding current)
        $this->categories = Category::where('slug', '!=', $this->categorySlug)
            ->orderBy('id', 'asc')
            ->get();
    }

    public function refreshData()
    {
        $this->loadData();
        $this->dispatch('data-refreshed');
    }

    public function render()
    {
        // Get products for the current category with pagination
        $products = Product::where('category_id', $this->category->id)
            ->paginate(50);

        return view('livewire.user.product-by-category', [
            'products' => $products
        ]);
    }
}