<?php

namespace App\Http\Livewire\Tenant;

use App\Enums\Weekday;
use App\Models\Employee;
use App\Models\Schedule;
use App\Support\Tenant;
use Livewire\Component;

class SchedulesEditor extends Component
{
    public ?int $employeeId = null;

    /** @var array<int, array<int, array{start: string, end: string, active: bool}>> */
    public array $schedules = [];

    public function mount(): void
    {
        $requested = request()->query('employee');
        $first     = Employee::active()->orderBy('id')->first();
        $this->employeeId = $requested ? (int)$requested : $first?->id;
        $this->loadSchedules();
    }

    public function selectEmployee(int $id): void
    {
        $this->employeeId = $id;
        $this->loadSchedules();
    }

    public function updatedEmployeeId(): void
    {
        $this->loadSchedules();
    }

    public function loadSchedules(): void
    {
        $this->schedules = [];
        if (! $this->employeeId) return;

        $current = Schedule::where('employee_id', $this->employeeId)->get()->groupBy('weekday');

        foreach (Weekday::cases() as $day) {
            $rows = $current->get($day->value, collect());
            $this->schedules[$day->value] = $rows->map(fn ($s) => [
                'id'     => $s->id,
                'start'  => substr($s->start_time, 0, 5),
                'end'    => substr($s->end_time, 0, 5),
                'active' => (bool) $s->is_active,
            ])->all();
        }
    }

    public function addRow(int $weekday): void
    {
        $this->schedules[$weekday][] = [
            'id' => null, 'start' => '09:00', 'end' => '18:00', 'active' => true,
        ];
    }

    public function removeRow(int $weekday, int $idx): void
    {
        unset($this->schedules[$weekday][$idx]);
        $this->schedules[$weekday] = array_values($this->schedules[$weekday]);
    }

    public function save(): void
    {
        if (! $this->employeeId) return;

        $companyId = Tenant::id();
        $branchId  = Employee::find($this->employeeId)?->branch_id;

        Schedule::where('employee_id', $this->employeeId)->delete();

        foreach ($this->schedules as $weekday => $rows) {
            foreach ($rows as $row) {
                $start = $row['start'] ?? '';
                $end   = $row['end']   ?? '';
                if ($start === '' || $end === '') continue;

                Schedule::create([
                    'company_id'  => $companyId,
                    'branch_id'   => $branchId,
                    'employee_id' => $this->employeeId,
                    'weekday'     => (int) $weekday,
                    'start_time'  => $start,
                    'end_time'    => $end,
                    'is_active'   => filter_var($row['active'] ?? true, FILTER_VALIDATE_BOOLEAN),
                ]);
            }
        }

        $this->dispatch('sileo:toast', type: 'success', message: 'Horarios guardados correctamente.');
    }

    public function render()
    {
        return view('livewire.tenant.schedules-editor', [
            'employees' => Employee::active()->orderBy('first_name')->get(),
            'days'      => Weekday::cases(),
        ]);
    }
}
