<?php

namespace App\Livewire\Admin;

use Livewire\Component;

class GlobalSearch extends Component
{
    public $search = '';
    public $results = [];

    // Define the models and their searchable fields
    public $searchableModels = [
        'Products' => [ // Display name for the group
            'model' => \App\Models\Product::class, // Actual model class
            'fields' => ['title', 'short_description'], // Fields to search in this model
            'display_field' => 'title', // Field to display in results
            'route_name' => 'admin.product.show', // Optional: route name for the item link
            'route_params' => ['slug' => 'slug'], // Optional: route parameters
        ],
        'Categories' => [
            'model' => \App\Models\Category::class,
            'fields' => ['name'],
            'display_field' => 'name',
            'route_name' => 'admin.categories.show',
            'route_params' => ['category' => 'id'],

        ],
        'Posts' => [
            'model' => \App\Models\Post::class,
            'fields' => ['title', 'short_desc'],
            'display_field' => 'title',
            'route_name' => 'admin.post.show',
            'route_params' => ['post' => 'id'],
        ],
        'Order' => [
            'model' => \App\Models\Order::class,
            'fields' => ['uuid', 'tracking_code', 'phone', 'email'],
            'display_field' => 'tracking_code',
            'route_name' => 'admin.orders.show',
            'route_params' => ['order' => 'id'],
        ],
        // Add more models as needed
    ];

    public function updatedSearch()
    {
        $this->results = $this->performSearch($this->search);
    }

    public function performSearch($searchTerm)
    {
        $results = [];

        if (strlen($searchTerm) >= 3) { // Consider increasing minimum search term length
            foreach ($this->searchableModels as $groupName => $config) {
                $modelClass = $config['model'];
                $query = $modelClass::query();

                foreach ($config['fields'] as $field) {
                    $query->orWhere($field, 'like', '%' . $searchTerm . '%');
                }

                $modelResults = $query->get();

                if ($modelResults->count()) {
                    $results[$groupName] = [
                        'items' => $modelResults,
                        'display_field' => $config['display_field'],
                        'route_name' => $config['route_name'] ?? null,
                    ];
                }
            }
        }

        return $results;
    }
    public function render()
    {
        return view('livewire.admin.global-search');
    }
}
