<?php

namespace App\Livewire\Home;

use App\Models\Contact;
use App\Settings\GeneralSettings;
use Livewire\Attributes\Title;
use Livewire\Component;

#[Title('Hubungi Kami')]
class ContactUs extends Component
{
    public string $name = '';

    public string $email = '';

    public ?string $subject = null;

    public string $message = '';

    public string $pageTitle = 'Hubungi Kami';

    public string $pageDescription = 'Kami siap membantu dan menjawab pertanyaan Anda.';

    public function rules()
    {
        return [
            'name' => ['required', 'max:100'],
            'email' => ['required', 'email', 'max:254'],
            'subject' => 'nullable',
            'message' => 'required',
        ];
    }

    public function validationAttributes()
    {
        return [
            'name' => 'name',
            'email' => 'alamat surel',
            'subject' => 'subyek',
            'message' => 'pesan',
        ];
    }

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

        // Anti-spam: check if this email has submitted in the last 24 hours
        $exists = Contact::where('email', $this->email)
            ->where('created_at', '>=', now()->subDay())
            ->exists();

        if ($exists) {
            $this->addError('email', 'Maaf, Anda hanya dapat mengirim pesan sekali dalam 24 jam.');

            return;
        }

        Contact::create([
            'name' => $this->name,
            'email' => $this->email,
            'subject' => $this->subject,
            'message' => $this->message,
        ]);

        $this->reset(['name', 'email', 'subject', 'message']);

        session()->flash('success', 'Pesan Anda telah terkirim!');
    }

    public function render(GeneralSettings $settings)
    {
        return view('livewire.home.contact-us', [
            'settings' => $settings,
        ]);
    }
}
