<?php

namespace App\Components\Solicitor;

use App\Models\Solicitor\Solicitor;
use App\Services\HistoryService;
use Illuminate\Support\Facades\Storage;
use Livewire\Component;
use Livewire\WithFileUploads;

class LogoManager extends Component {
    use WithFileUploads;

    public Solicitor $solicitor;

    public $logo;

    public function uploadLogo(HistoryService $history) {
        $this->authorize('solicitors.edit');
        if (!isset($this->solicitor) || !$this->solicitor->exists) {
            return;
        }

        $this->validate([
            'logo' => ['required', 'image', 'mimes:png,jpg,jpeg,svg,webp', 'max:2048'],
        ]);

        if ($this->solicitor->logo_path) {
            Storage::delete($this->solicitor->logo_path);
        }

        $ext  = $this->logo->getClientOriginalExtension();
        $path = $this->logo->storeAs("solicitors/{$this->solicitor->id}", "logo.{$ext}");

        $this->solicitor->update(['logo_path' => $path]);

        $history->add($this->solicitor, 'Logo uploaded', ['logo_path' => $path]);

        $this->reset('logo');
        $this->dispatch('toast', message: 'Logo uploaded successfully.', type: 'success');
    }

    public function deleteLogo(HistoryService $history) {
        $this->authorize('solicitors.edit');
        if (!isset($this->solicitor) || !$this->solicitor->exists) {
            return;
        }

        if (!$this->solicitor->logo_path) {
            return;
        }

        Storage::delete($this->solicitor->logo_path);
        $this->solicitor->update(['logo_path' => null]);

        $history->add($this->solicitor, 'Logo removed');

        $this->dispatch('toast', message: 'Logo removed.', type: 'success');
    }

    public function render() {
        return view('components.solicitor.logo-manager');
    }
}