<?php

namespace App\Components\LeadSource;

use App\Models\LeadSource\LeadSource;
use App\Services\HistoryService;
use Livewire\Component;

class Edit extends Component {

    public $display_name;
    public LeadSource $leadSource;

    public function mount() {
        $this->authorize('sources.edit', $this->leadSource);
        $this->display_name = $this->leadSource->display_name;
    }

    public function saveSource(HistoryService $history) {
        $data = $this->validate([
            'display_name' => 'required|max:255|string|unique:lead_sources,display_name,' . $this->leadSource->id,
        ]);

        $before = $this->leadSource->display_name;
        $this->leadSource->update($data);

        if ($before !== $this->leadSource->display_name) {
            $history->addForActor("Renamed lead source '{$before}' to '{$this->leadSource->display_name}'", [
                'lead_source_id' => $this->leadSource->id,
                'from'           => $before,
                'to'             => $this->leadSource->display_name,
            ]);
        }

        return redirect()->route('sources.show', $this->leadSource);
    }

    public function render() {
        return view('components.lead-source.edit');
    }
}
