<?php

namespace App\Livewire\Merchants;

use App\Models\Setting;
use Illuminate\Support\Facades\DB;
use Livewire\Attributes\Validate;
use Livewire\Component;

class EditContact extends Component
{
    #[Validate('required|string|max:255')]
    public string $merchant_phone = '';

    #[Validate('required|email|max:255')]
    public string $merchant_email = '';

    public bool $success = false;
    public bool $loading = false;
    public bool $disabled = false;

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

        if ($settings) {
            $this->merchant_phone = (string) $settings->merchant_phone;
            $this->merchant_email = (string) $settings->merchant_email;
        }
    }

    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_phone' => $this->merchant_phone,
                        'merchant_email' => $this->merchant_email,
                    ]);
                } else {
                    Setting::create([
                        'merchant_name' => 'Ma Pharmacie',
                        'merchant_type' => 'pharmacy',
                        'merchant_phone' => $this->merchant_phone,
                        'merchant_email' => $this->merchant_email,
                        'merchant_status' => true,
                        'has_active_subscription' => false,
                    ]);
                }
            });

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

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


