<?php
namespace App\Controllers;

use App\Models\ProductModel;
use App\Models\SaleModel;
use App\Models\UserModel;

class SearchController extends BaseController
{
    public function index()
    {
        $query = trim($this->request->getGet('q'));
        if (strlen($query) < 1) {
            return redirect()->to('/dashboard');
        }

        $productModel = new ProductModel();
        $saleModel = new SaleModel();
        $userModel = new UserModel();

        $products = $productModel->searchProducts($query);

        $db = \Config\Database::connect();
        $sales = $db->table('ventas v')
            ->select('v.*, u.username')
            ->join('usuarios u', 'u.id_usuario = v.id_usuario')
            ->like('v.id_venta', $query)
            ->orLike('v.observaciones', $query)
            ->orLike('u.username', $query)
            ->orderBy('v.id_venta', 'DESC')
            ->limit(20)
            ->get()
            ->getResultArray();

        $users = $db->table('usuarios u')
            ->select('u.*, r.nombre_rol')
            ->join('roles r', 'r.id_rol = u.id_rol')
            ->like('u.username', $query)
            ->orLike('u.email', $query)
            ->orderBy('u.id_usuario', 'DESC')
            ->limit(10)
            ->get()
            ->getResultArray();

        $data = [
            'title' => "Resultados: $query",
            'query' => $query,
            'products' => $products,
            'sales' => $sales,
            'users' => $users,
        ];

        return view('search/results', $data);
    }
}
