<?php

namespace App\Livewire\Territori;

use Livewire\Component;
use Livewire\WithFileUploads;
use App\Models\Territorio;
use App\Models\Zona;
use App\Models\Tipologia;
use App\Services\TerritorioThumbnailService;

class TerritorioCreate extends Component
{
    use WithFileUploads;

    public string $numero = '';
    public ?int $zona_id = null;
    public ?int $tipologia_id = null;
    public string $note = '';
    public string $confini = '';
    public $pdf;
    public bool $prioritario = false;

    protected function rules(): array
    {
        return [
            'numero' => 'required|string|max:20|unique:territori,numero',
            'zona_id' => 'nullable|exists:zone,id',
            'tipologia_id' => 'nullable|exists:tipologie,id',
            'note' => 'nullable|string|max:5000',
            'confini' => 'nullable|string|max:5000',
            'pdf' => 'nullable|file|mimes:pdf|max:10240',
            'prioritario' => 'boolean',
        ];
    }

    public function save()
    {
        $this->validate();

        $data = [
            'numero' => $this->numero,
            'zona_id' => $this->zona_id,
            'tipologia_id' => $this->tipologia_id,
            'note' => $this->note ?: null,
            'confini' => $this->confini ?: null,
            'prioritario' => $this->prioritario,
            'attivo' => true,
        ];

        if ($this->pdf) {
            $pdfPath = $this->pdf->store('territori-pdf', 'public');
            $data['pdf_path'] = $pdfPath;
            $data['thumbnail_path'] = app(TerritorioThumbnailService::class)->generate($pdfPath);
        }

        $territorio = Territorio::create($data);

        activity()->causedBy(auth()->user())
            ->performedOn($territorio)
            ->withProperties(['numero' => $territorio->numero])
            ->log('created');

        session()->flash('success', "Territorio {$territorio->numero} creato.");
        return redirect()->route('territori.index');
    }

    public function render()
    {
        return view('livewire.territori.territorio-form', [
            'zone' => Zona::attive()->get(),
            'tipologie' => Tipologia::attive()->get(),
            'isEdit' => false,
            'title' => 'Nuovo Territorio',
        ]);
    }
}
