<?php

namespace App\Livewire;

use Livewire\Component;
use Livewire\WithPagination;
use App\Models\User;

class UserTable extends Component
{
    use WithPagination;

    public $sortField = 'first_name';
    public $sortDirection = 'asc';

    public $columns = [
        'full_name' => true,
        'is_active' => true,
        'username' => true,
        'email' => true,
        'phone' => false,
        'access_start' => false,
        'created_at' => false,
        'is_active' => false,
    ];

    public $filters = [
        'full_name' => '',
        'is_active' => '',
        'username' => '',
        'email' => '',
        'phone' => '',
        'access_start' => '',
        'created_at' => ''
    ];

    protected $queryString = [
        'filters' => ['except' => ''],
        'columns' => ['except' => '']
    ];

    public function mount()
    {
        // Recuperar preferencias de columnas de la sesión
        $this->columns = session('user_columns', $this->columns);
    }

    public function updatedColumns()
    {
        // Guardar preferencias en sesión
        session(['user_columns' => $this->columns]);
    }

    public function sortBy($field)
    {
        if ($this->sortField === $field) {
            $this->sortDirection = $this->sortDirection === 'asc' ? 'desc' : 'asc';
        } else {
            $this->sortDirection = 'asc';
        }
        
        $this->sortField = $field;
    }

    public function render()
    {
        $users = User::query()
            ->when($this->filters['full_name'], fn($q, $search) => 
                $q->whereRaw("CONCAT(title, ' ', first_name, ' ', last_name) LIKE ?", ["%$search%"]))
            ->when($this->sortField === 'full_name', fn($q) => 
                $q->orderByRaw("CONCAT(title, ' ', first_name, ' ', last_name) " . $this->sortDirection)
            )
            ->when($this->sortField === 'created_at', fn($q) => 
                $q->orderBy('created_at', $this->sortDirection)
            )
            ->when($this->sortField === 'access_start', fn($q) => 
                $q->orderBy('access_start', $this->sortDirection)
            )
            ->when(in_array($this->sortField, ['username', 'email', 'phone']), fn($q) => 
                $q->orderBy($this->sortField, $this->sortDirection)
            )
            ->when($this->filters['full_name'], fn($q, $search) => 
                $q->whereRaw("CONCAT(title, ' ', first_name, ' ', last_name) LIKE ?", ["%$search%"]))
            ->when($this->filters['username'], fn($q, $search) => 
                $q->where('username', 'LIKE', "%$search%"))
            ->when($this->filters['email'], fn($q, $search) => 
                $q->where('email', 'LIKE', "%$search%"))
            ->when($this->filters['phone'], fn($q, $search) => 
                $q->where('phone', 'LIKE', "%$search%"))
            ->when($this->filters['access_start'], fn($q, $date) => 
                $q->whereDate('access_start', $date))
            ->when($this->filters['created_at'], fn($q, $date) => 
                $q->whereDate('created_at', $date))
            ->paginate(10);

        return view('livewire.user-table', [
            'users' => $users,
            'available_columns' => [
                'full_name' => 'Nombre Completo',
                'username' => 'Usuario',
                'email' => 'Correo',
                'phone' => 'Teléfono',
                'access_start' => 'Fecha de acceso',
                'created_at' => 'Fecha creación',
                'is_active' => 'Estado'
            ]
        ]);
    }
}