<?php

namespace App\Livewire\Public;

use App\Domain\Website\Models\ContactSubmission;
use Illuminate\Support\Facades\RateLimiter;
use Livewire\Component;

/**
 * Public contact form rendered by the contact_form block.
 *
 * Unauthenticated and internet-facing, so it is rate limited by IP and carries
 * a honeypot; submissions land in the existing admin inbox unchanged.
 */
class WebsiteContactForm extends Component
{
    public ?int $blockId = null;

    public bool $showSubject = true;

    public bool $showPhone = true;

    public bool $requirePhone = false;

    public ?string $submitLabel = null;

    public ?string $successMessage = null;

    public string $name = '';

    public string $email = '';

    public string $phone = '';

    public string $subject = '';

    public string $message = '';

    /** Bots fill hidden fields; humans do not. */
    public string $website = '';

    public bool $sent = false;

    protected function rules(): array
    {
        return [
            'name' => 'required|string|min:3|max:120',
            'email' => 'required|email|max:180',
            'phone' => ($this->requirePhone ? 'required' : 'nullable').'|string|max:30',
            'subject' => ($this->showSubject ? 'nullable' : 'nullable').'|string|max:200',
            'message' => 'required|string|min:10|max:5000',
        ];
    }

    protected function messages(): array
    {
        return [
            'name.required' => __('الاسم مطلوب'),
            'name.min' => __('الاسم قصير جدًا'),
            'email.required' => __('البريد الإلكتروني مطلوب'),
            'email.email' => __('البريد الإلكتروني غير صالح'),
            'phone.required' => __('رقم الهاتف مطلوب'),
            'message.required' => __('الرسالة مطلوبة'),
            'message.min' => __('الرسالة قصيرة جدًا'),
        ];
    }

    public function submit(): void
    {
        if (filled($this->website)) {
            // Honeypot tripped — report success without persisting anything.
            $this->sent = true;

            return;
        }

        $key = 'website-contact:'.request()->ip();

        if (RateLimiter::tooManyAttempts($key, 5)) {
            $this->addError('message', __('لقد أرسلت رسائل كثيرة. برجاء المحاولة لاحقًا.'));

            return;
        }

        $data = $this->validate();
        RateLimiter::hit($key, 3600);

        ContactSubmission::create([
            'name' => $data['name'],
            'email' => $data['email'],
            'phone' => $data['phone'] ?: null,
            'subject' => $this->showSubject ? ($data['subject'] ?: null) : null,
            'message' => $data['message'],
            'status' => 'new',
        ]);

        $this->reset(['name', 'email', 'phone', 'subject', 'message']);
        $this->sent = true;
    }

    public function render()
    {
        return view('livewire.public.website-contact-form');
    }
}
