<?php

namespace App\Livewire\Proclamatori;

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

class ProclamatoreIndex extends Component
{
    use WithPagination;

    public string $search = '';
    public string $filtroStato = '';
    public string $sortField = 'cognome';
    public string $sortDirection = 'asc';

    protected $queryString = [
        'search' => ['except' => ''],
        'filtroStato' => ['except' => ''],
    ];

    public function updatingSearch()
    {
        $this->resetPage();
    }

    public function updatingFiltroStato()
    {
        $this->resetPage();
    }

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

    public function toggleActive(int $id)
    {
        $proclamatore = Proclamatore::findOrFail($id);
        $proclamatore->update(['attivo' => !$proclamatore->attivo]);
    }

    public function deleteProclamatore(int $id)
    {
        $proclamatore = Proclamatore::findOrFail($id);

        if ($proclamatore->assegnazioni()->aperte()->exists()) {
            session()->flash('error', "Il proclamatore {$proclamatore->nome_completo} ha assegnazioni aperte. Rientra prima i territori.");
            return;
        }

        $proclamatore->delete();
        session()->flash('success', "Proclamatore {$proclamatore->nome_completo} spostato nel cestino.");
    }

    public function anonimizza(int $id)
    {
        $proclamatore = Proclamatore::findOrFail($id);
        $proclamatore->anonimizza();
        session()->flash('success', "Dati personali del proclamatore anonimizzati (GDPR).");
    }

    public function render()
    {
        $query = Proclamatore::query();

        if ($this->search !== '') {
            // In-memory filter because nome/cognome are encrypted
            $all = $query->get();
            $filtered = $all->filter(function ($p) {
                return str_contains(
                    mb_strtolower($p->nome . ' ' . $p->cognome),
                    mb_strtolower($this->search)
                );
            });

            if ($this->filtroStato === 'attivo') {
                $filtered = $filtered->where('attivo', true);
            } elseif ($this->filtroStato === 'inattivo') {
                $filtered = $filtered->where('attivo', false);
            }

            // Sort in-memory
            $filtered = $filtered->sortBy(function ($p) {
                return match ($this->sortField) {
                    'nome' => mb_strtolower($p->nome),
                    'cognome' => mb_strtolower($p->cognome),
                    default => mb_strtolower($p->cognome),
                };
            }, SORT_REGULAR, $this->sortDirection === 'desc');

            // Manual pagination
            $page = $this->getPage();
            $perPage = 20;
            $items = $filtered->slice(($page - 1) * $perPage, $perPage)->values();
            $proclamatori = new \Illuminate\Pagination\LengthAwarePaginator(
                $items, $filtered->count(), $perPage, $page,
                ['path' => request()->url()]
            );
        } else {
            if ($this->filtroStato === 'attivo') {
                $query->where('attivo', true);
            } elseif ($this->filtroStato === 'inattivo') {
                $query->where('attivo', false);
            }

            // cognome/nome encrypted, so sort in-memory
            $all = $query->get()->sortBy(function ($p) {
                return match ($this->sortField) {
                    'nome' => mb_strtolower($p->nome),
                    'cognome' => mb_strtolower($p->cognome),
                    default => mb_strtolower($p->cognome),
                };
            }, SORT_REGULAR, $this->sortDirection === 'desc');

            $page = $this->getPage();
            $perPage = 20;
            $items = $all->slice(($page - 1) * $perPage, $perPage)->values();
            $proclamatori = new \Illuminate\Pagination\LengthAwarePaginator(
                $items, $all->count(), $perPage, $page,
                ['path' => request()->url()]
            );
        }

        return view('livewire.proclamatori.proclamatore-index', [
            'proclamatori' => $proclamatori,
        ]);
    }
}
