<?php

namespace App\Livewire;

use App\Models\Application;
use App\Models\Upload;

use Livewire\Component;
use Livewire\WithFileUploads;
use Livewire\Attributes\Layout;
use Illuminate\Support\Str;

use Mews\Captcha\Facades\Captcha;

#[Layout('components.layouts.guest')]
class ApplicationForm extends Component
{
    use WithFileUploads;

    public $photos = [];

    public $message = '';

    public $applicationUuid;

    public $captcha;

    public $captchaInput;

    protected $rules = [
        'photos'        => 'required|array|min:1|max:6',
        'photos.*'      => 'image|max:8192', // 8MB max per photo
        'message'       => 'required|string|max:500',
        'captchaInput'  => 'required',
    ];

    public function mount()
    {
        $this->refreshCaptcha();
    }

    public function refreshCaptcha()
    {
        $this->captcha = Captcha::src('flat');
    }

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

        // Validate captcha
        if (!captcha_check($this->captchaInput)) {
            $this->addError('captchaInput', 'Invalid CAPTCHA.');
            $this->refreshCaptcha();
            return;
        }

        // Create application
        $application = Application::create([
            'uuid' => Str::uuid(),
            'message' => $this->message,
        ]);

        // Save each uploaded photo
        foreach ($this->photos as $photo) {
            $path = $photo->store('applications/photos', 'public');

            Upload::create([
                'application_id' => $application->id,
                'file_path' => $path,
            ]);
        }

        $this->applicationUuid = (string) $application->uuid;

        $this->reset(['photos', 'message', 'captchaInput']);
    }

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