<?php

namespace App\Livewire\Public;

use App\Domain\Event\Models\Event;
use App\Domain\Event\Services\EventRegistrationService;
use App\Domain\Shared\Exceptions\DomainException;
use Livewire\Component;

class EventRegistrationForm extends Component
{
    public Event $event;
    public array $fields = [];
    public bool $submitted = false;
    public ?string $registrationNumber = null;

    public function mount(Event $event): void
    {
        $this->event = $event;
        $this->initFields();
    }

    private function initFields(): void
    {
        foreach ($this->event->form_fields as $field) {
            $default = match ($field['type']) {
                'checkbox' => false,
                'multi_select' => [],
                default => '',
            };
            $this->fields[$field['key']] = $default;
        }
    }

    public function submit(EventRegistrationService $service): void
    {
        $validation = $service->validateFormData($this->event, $this->fields);
        $this->validate($validation['rules'], $validation['messages']);

        $name = $this->fields['name'] ?? $this->fields['player_name'] ?? $this->fields['participant_name'] ?? ($this->fields['first_name'] ?? '') . ' ' . ($this->fields['last_name'] ?? '');
        $phone = $this->fields['phone'] ?? $this->fields['mobile'] ?? '';
        $email = $this->fields['email'] ?? null;

        if (empty(trim($name))) {
            $name = 'مسجل';
        }

        try {
            $registration = $service->register($this->event, $this->fields, [
                'name' => trim($name),
                'phone' => $phone,
                'email' => $email,
                'ip' => request()->ip(),
            ]);

            $this->submitted = true;
            $this->registrationNumber = $registration->registration_number;
        } catch (DomainException $e) {
            $this->addError('form', $e->getMessage());
        }
    }

    public function render()
    {
        return view('livewire.public.event-registration-form');
    }
}
