<?php

namespace App\Components\Solicitor;

use App\Models\Solicitor\Solicitor;
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() {
        $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]);

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

    public function deleteLogo() {
        $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]);
        $this->dispatch('toast', message: 'Logo removed.', type: 'success');
    }

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