<?php

namespace App\Livewire\Merchants;

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

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

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

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

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

    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_name = (string) $settings->merchant_name;
            $this->merchant_slogan = $settings->merchant_slogan;
            $this->merchant_type = (string) $settings->merchant_type;
            $this->merchant_cnop = $settings->merchant_cnop;
        }
    }

    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_name' => $this->merchant_name,
                        'merchant_slogan' => $this->merchant_slogan,
                        'merchant_type' => $this->merchant_type,
                        'merchant_cnop' => $this->merchant_cnop,
                    ]);
                } else {
                    Setting::create([
                        'merchant_name' => $this->merchant_name,
                        'merchant_slogan' => $this->merchant_slogan,
                        'merchant_type' => $this->merchant_type,
                        'merchant_cnop' => $this->merchant_cnop,
                    ]);
                }
            });

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

    public function render(): \Illuminate\Contracts\View\View
    {
        $merchantTypes = collect(\App\Models\Merchant::MERCHANT_TYPES)
            ->map(fn ($t) => (object) ['id' => $t['id'], 'name' => $t['name']]);

        return view('livewire.merchants.edit-general', compact('merchantTypes'));
    }
}


