<?php

namespace App\Http\Livewire\Pages\Auth;

use App\Http\Controllers\MailController;
use App\Models\User;
use Exception;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Log;
use Illuminate\Validation\Rules\Password;
use Livewire\Component;

class Register extends Component
{
    public $name;
    public $email;
    public $password;
    public $zipcode;
    public $country;
    public $address;
    public $phone_number;

    public $responseText;
    public $responseCode;

    public function mount()
    {
        //todo
    }

    public function rules()
    {
        return [
            'name' => ['required', 'string', 'min:3', 'max:64'],
            'email' => ['required', 'string', 'email', 'unique:users', 'min:4'],
            'password' => ['required', 'string', 'min:6', 'max:64', Password::min(6)->numbers()],
            'zipcode' => ['required', 'string', 'min:3', 'max:12'],
            'address' => ['required', 'string', 'min:3', 'max:120'],
            'country' => ['required', 'string', 'min:3', 'max:64'],
            'phone_number' => ['required', 'string', 'min:8', 'max:16'],
        ];
    }

    public function updated($property)
    {
        $this->validateOnly($property);
    }

    public function register()
    {
        $data = $this->validate();

        $data['password'] = Hash::make($data['password']);

        $mailer = app(MailController::class);

        try {
            $user = User::create($data);
            auth()->login($user);
            
            if ($user) {

                try {
                    $mailer->welcome($user);

                } catch (Exception $e) {
                    Log::info($e->getMessage());
                }
                return redirect()->to('login')->with('message', 'Sign Up Successful');
            }
        } catch (\Exception $e) {
            Log::error($e->getMessage());
            $this->responseText = "Couldn't create an account at the moment, please try again later.";
        }
    }

    public function render()
    {
        return view('livewire.pages.auth.register');
    }
}
