<?php

namespace App\Http\Livewire;

use Livewire\Component;
use App\Models\User;
use App\Models\District;
use App\Models\Vidhansabha;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Auth;

class Authentication extends Component
{
    public $showForm = false, $username, $name, $age, $blood_group, $district, $assembly, $village_city_name, $referal_user;

    public $districts;
    public $assemblies;


    protected $rules = [
        'username' => 'required|unique:users',
        'name' => 'required',
        'age' => 'required',
        'blood_group' => 'required',
    ];
 
    protected $messages = [
        'username.required' => 'The Phone number cannot be empty.',
        'username.unique' => 'The Phone number already registered.',
    ];

    public function checkUser($username) {
        $user = User::where('username', $username)->first();
        if ($user) {
            $this->showForm = false;
            Auth::login($user);
            return redirect()->route('home');
        } else {
            $this->showForm = true;
        }
    }

    public function mount($referal_user)
    {
        $this->referal_user = $referal_user;
        $this->districts = District::all();
        $this->assemblies = collect();
    }

    public function updatedDistrict($district)
    {
        $this->assemblies = Vidhansabha::where('district_id', $district)->get();
    }

    public function saveUser()
    {
        $validatedData = $this->validate();
        // dd($this->username);
        $user = User::create([
            'email' => $this->username,
            'username' => $this->username,
            'password' => Hash::make($this->username),
            'name' => $this->name,
            'age' => $this->age,
            'blood_group' => $this->blood_group,
            'district' => $this->district,
            'assembly' => $this->assembly,
            'village_city_name' => $this->village_city_name,
            'referal_user' => $this->referal_user,
        ]);

        Auth::login($user);
        return redirect()->route('home');
 
    }

    public function render()
    {
        return view('livewire.authentication');
    }
}
