<?php

namespace App\Livewire\Forms;

use App\Models\Role;
use App\Models\User;
use App\Models\Country;
use App\Services\Pos\PosWaitersCache;
use Livewire\Component;
use Illuminate\Support\Facades\Log;
use App\Notifications\StaffWelcomeEmail;
use Jantinnerezo\LivewireAlert\LivewireAlert;

class AddStaff extends Component
{

    use LivewireAlert;

    public $roles;
    public $memberName;
    public $memberEmail;
    public $memberRole;
    public $memberPassword;
    public $phoneNumber;
    public $restaurantPhoneCode;
    public $phoneCodeDetected = false;
    public $phoneCodeSearch = '';
    public $phoneCodeIsOpen = false;
    public $allPhoneCodes;
    public $filteredPhoneCodes;
    public $customerPhoneCode;

    public function mount()
    {
        $this->roles = Role::where('display_name', '<>', 'Super Admin')->get();
        $this->memberRole = $this->roles->first()->name;

        // Initialize phone codes
        $this->allPhoneCodes = collect(Country::pluck('phonecode')->unique()->filter()->values());
        $this->filteredPhoneCodes = $this->allPhoneCodes;
        $detectedPhoneCode = (new User())->getPhoneCodeFromIp();
        $this->phoneCodeDetected = !empty($detectedPhoneCode);
        $this->restaurantPhoneCode = $detectedPhoneCode
            ?? restaurant()->country->phonecode
            ?? $this->allPhoneCodes->first();

    }

    public function updatedPhoneCodeIsOpen($value)
    {
        if (!$value) {
            $this->reset(['phoneCodeSearch']);
            $this->updatedPhoneCodeSearch();
        }
    }

    public function updatedPhoneCodeSearch()
    {
        $this->filteredPhoneCodes = $this->allPhoneCodes->filter(function ($phonecode) {
            return str_contains($phonecode, $this->phoneCodeSearch);
        })->values();
    }

    public function selectPhoneCode($phonecode)
    {
        $this->restaurantPhoneCode = $phonecode;
        $this->phoneCodeIsOpen = false;
        $this->phoneCodeSearch = '';
        $this->updatedPhoneCodeSearch();
    }

    public function submitForm()
    {
        $this->validate([
            'memberName' => 'required',
            'phoneNumber' => [
                'required',
                'regex:/^[0-9\s]{5,20}$/',
            ],
            'restaurantPhoneCode' => 'required',
            'memberPassword' => 'required',
            'memberEmail' => 'required|unique:users,email'
        ]);

        $user = User::create([
            'name' => $this->memberName,
            'email' => $this->memberEmail,
            'phone_number' => $this->phoneNumber,
            'phone_code' => $this->restaurantPhoneCode,
            'password' => bcrypt($this->memberPassword),
        ]);

        $user->assignRole($this->memberRole);

        try {
            $user->notify(new StaffWelcomeEmail($user->restaurant, $this->memberPassword));
        } catch (\Exception $e) {
            Log::error('Error sending staff welcome email: ' . $e->getMessage());
        }

        if ($user->restaurant_id) {
            cache()->forget('restaurant_' . $user->restaurant_id . '_staff_stats');
        }

        PosWaitersCache::forgetForRestaurant((int) $user->restaurant_id);

        // Reset the value
        $this->memberName = '';
        $this->memberEmail = '';
        $this->memberRole = '';
        $this->memberPassword = '';
        $this->phoneNumber = '';
        $this->restaurantPhoneCode = '';

        $this->dispatch('hideAddStaff');
        $this->dispatch('closeAddStaffModal');

        $this->alert('success', __('messages.memberAdded'), [
            'toast' => true,
            'position' => 'top-end',
            'showCancelButton' => false,
            'cancelButtonText' => __('app.close')
        ]);
    }

    public function render()
    {
        return view('livewire.forms.add-staff', [
            'phonecodes' => $this->filteredPhoneCodes,
        ]);
    }

}
