<?php

namespace App\Http\Livewire\Frontend\User;

use App\Models\LocalizationManagement\City;
use App\Models\LocalizationManagement\Country;
use App\Models\LocalizationManagement\Quarter;
use App\Models\LocalizationManagement\State;
use App\Models\LocalizationManagement\Address;
use Gloudemans\Shoppingcart\Facades\Cart;
use Jantinnerezo\LivewireAlert\LivewireAlert;
use Livewire\Component;

class AddressesComponent extends Component{
    use LivewireAlert;

    public $showForm = false;
    public $editMode = false;
    public $address_id = '';
    public $title = '';
    public $default = '';
    public $contact_full_name = '';
    public $last_name = '';
    public $contact_email = '';
    public $contact_phone = '';
    public $address = '';
    public $address2 = '';
    public $countries;
    public $states = [];
    public $cities = [];
    public $quarters = [];
    public $country_id;
    public $state_id;
    public $city_id;
    public $quarter_id;
    public $zip_code = '';
    public $po_box = '';

    public function rules(){
        return [
            'title' => ['required', 'string'],
            'contact_full_name' => ['required', 'string', "min:4"],
            'contact_email' => ['required', 'email'],
            'contact_phone' => ['required', 'numeric'],
            'address' => ['required', 'string'],
            'address2' => ['nullable', 'string',"min:4"],
            'country_id' => ['required'],
            'quarter_id' => ['nullable'],
            'state_id' => ['required'],
            'city_id' => ['required'],
            'zip_code' => ['nullable', 'numeric', ],
            'po_box' => ['nullable', 'numeric',],
        ];
    }

    public function validationAttributes(){
        return [
            'country_id' => __("Country"),
            'quarter_id' => __("Quarter"),
            'state_id' => __("State"),
            'city_id' => __("City"),
            'zip_code' => __('ZIP Code'),
            'po_box' => __('P.O Box'),
        ];
    }
    protected $listeners = [
        'refresh_select' => 'mount'
    ];


    public function mount(){

        if ($this->country_id){
            $this->states = State::active()->whereCountryId($this->country_id)->pluck('id', 'name');
            if ($this->state_id){
                $this->cities = City::active()->whereStateId($this->state_id)->pluck('id', 'name');
            }

            if ($this->city_id){
                $this->quarters = Quarter::active()->whereCityId($this->city_id)->pluck('id', 'name');
            }
        }
    }

    public function getStatesByCountryId($id){
        $this->country_id = $id;
        $this->states = State::active()->whereCountryId($this->country_id)->get('id', 'name');
        return $this->states;
    }


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

        $address = auth(activeGuard())->user()->addresses()->create($this->formData());

        if ($this->default) {
            auth(activeGuard())->user()->addresses()->where('id', '!=', $address->id)->update([
                'default' => false,
            ]);
        }

        $this->resetForm();
        $this->showForm = false;
        $type = 'success';
        $message = __("Address created successfully");

        $cart = Cart::instance('default')->content();

        if ($cart->isNotEmpty()){
            return $this->flash($type,$message,[],route('checkout.index'));
        }
        $this->alert($type, $message);
    }

    public function editAddress($id){
        $address = Address::find($id);

        $this->address_id = $address->id;
        $this->title = $address->title;
        $this->default = $address->default;
        $this->contact_full_name = $address->contact_full_name;
        $this->contact_email = $address->contact_email;
        $this->contact_phone = $address->contact_phone;
        $this->address = $address->address;
        $this->address2 = $address->address2;
        $this->country_id = $address->country_id;
        $this->state_id = $address->state_id;
        $this->city_id = $address->city_id;
        $this->quarter_id = $address->quarter_id;
        $this->zip_code = $address->zip_code;
        $this->po_box = $address->po_box;

        $this->showForm = true;
        $this->editMode = true;
    }

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

        $customer = auth(activeGuard())->user();

        $customer->addresses()
            ->where('id', $this->address_id)
            ->update($this->formData());

        if ($this->default) {
            $customer->addresses()
                    ->where('id', '!=', $this->address_id)
                     ->update(['default' => false,]);
        }

        $this->resetForm();
        $this->showForm = false;
        $this->alert('success', __('Address updated successfully'));
    }

    public function deleteAddress($id){
        $address = auth(activeGuard())->user()->addresses()->where('id', $id)->first();
        if ($address->default) {
            auth(activeGuard())->user()->addresses()->first()->update(['default' => true]);
        }
        $address->delete();
        $this->alert('success', 'Address deleted successfully');
    }

    public function resetForm(){
        $this->reset();
        $this->resetValidation();
    }

    public function formData(): array{
        return [
            'title' => $this->title,
            'default' => $this->default ?? false,
            'contact_full_name' => $this->contact_full_name ?? null,
            'contact_email' => $this->contact_email ?? null,
            'contact_phone' => $this->contact_phone ?? null,
            'address' => $this->address ?? null,
            'address2' => $this->address2 ?? null,
            'country_id' => $this->country_id ?? null,
            'state_id' => $this->state_id ?? null,
            'quarter_id' => $this->quarter_id ?? null,
            'city_id' => $this->city_id ?? null,
            'zip_code' => $this->zip_code ?? null,
            'po_box' => $this->po_box ?? null,
        ];
    }

    public function render(){
        $this->countries = Country::active()->get(['id', 'name']);
        $this->states = filled($this->country_id) ? State::active()->whereCountryId($this->country_id)->get(['id', 'name']) : [];
        $this->cities =  filled($this->state_id) ? City::active()->whereStateId($this->state_id)->get(['id', 'name']) : [];

        $this->contact_full_name = (empty($this->contact_full_name)) ? auth(activeGuard())->user()->contact_full_name : $this->contact_full_name ;

        return view('livewire.frontend.user.addresses-component', [
            'addresses' => auth(activeGuard())->user()->addresses,
            'countries' => $this->countries,
            'states' => $this->states,
            'cities' => $this->cities,
            'quarters' => $this->quarters,
        ]);
    }
}
