<?php

namespace App\Livewire\Merchants;

use App\Models\{Setting, Province, City};
use Illuminate\Support\Facades\DB;
use Livewire\Attributes\Validate;
use Livewire\Component;

class EditAddress extends Component
{
    #[Validate('required|exists:provinces,id')]
    public ?int $merchant_province_id = null;

    #[Validate('required|exists:cities,id')]
    public ?int $merchant_city_id = null;

    #[Validate('nullable|string|max:500')]
    public ?string $merchant_address = null;

    #[Validate('nullable|numeric')]
    public $merchant_latitude = null;

    #[Validate('nullable|numeric')]
    public $merchant_longitude = null;

    public array $provinces = [];
    public array $cities = [];
    public bool $success = false;
    public bool $loading = false;
    public bool $locationLoading = false;
    public bool $disabled = false;

    public function rules(): array
    {
        return [
            'merchant_province_id' => ['required', 'exists:provinces,id'],
            'merchant_city_id' => ['required', 'exists:cities,id'],
            'merchant_address' => ['nullable', 'string', 'max:500'],
            'merchant_latitude' => ['nullable', 'numeric'],
            'merchant_longitude' => ['nullable', 'numeric'],
        ];
    }

    public function mount(): void
    {
        $this->loadProvinces();
        $settings = Setting::first();
        $this->disabled = isMerchantActive();

        if ($settings) {
            $this->merchant_province_id = $settings->merchant_province_id;
            $this->merchant_address = $settings->merchant_address;
            $this->merchant_latitude = $settings->merchant_latitude;
            $this->merchant_longitude = $settings->merchant_longitude;

            if ($this->merchant_province_id) {
                $this->loadCities();
                $this->merchant_city_id = $settings->merchant_city_id;
            }
        }
    }

    public function loadProvinces(): void
    {
        $this->provinces = Province::orderBy('name')->get(['id', 'name'])->toArray();
    }

    public function loadCities(): void
    {
        if ($this->merchant_province_id) {
            $this->cities = City::where('province_id', $this->merchant_province_id)
                ->orderBy('name')
                ->get(['id', 'name'])
                ->toArray();
        } else {
            $this->cities = [];
        }
        $this->merchant_city_id = null;
    }

    public function updatedMerchantProvinceId($value): void
    {
        $this->merchant_city_id = null;
        $this->loadCities();
    }

    public function setLocation($lat, $lng): void
    {
        $this->merchant_latitude = $lat;
        $this->merchant_longitude = $lng;
    }

    public function save(): void
    {
        if ($this->disabled) {
            return;
        }

        $this->resetErrorBag();
        $this->validate();
        $this->loading = true;

        try {
            DB::transaction(function () {
                $settings = Setting::first();

                if ($settings) {
                    $settings->update([
                        'merchant_province_id' => $this->merchant_province_id,
                        'merchant_city_id' => $this->merchant_city_id,
                        'merchant_address' => $this->merchant_address,
                        'merchant_latitude' => $this->merchant_latitude,
                        'merchant_longitude' => $this->merchant_longitude,
                    ]);
                } else {
                    Setting::create([
                        'merchant_province_id' => $this->merchant_province_id,
                        'merchant_city_id' => $this->merchant_city_id,
                        'merchant_address' => $this->merchant_address,
                        'merchant_latitude' => $this->merchant_latitude,
                        'merchant_longitude' => $this->merchant_longitude,
                    ]);
                }
            });

            $this->success = true;
        } catch (\Throwable $e) {
            report($e);
            $this->addError('error', "Une erreur est survenue lors de la mise à jour de l'adresse.");
        } finally {
            $this->loading = false;
        }
    }

    public function render(): \Illuminate\Contracts\View\View
    {
        return view('livewire.merchants.edit-address');
    }
}


