<?php

namespace App\Components\LeadSource;

use App\Models\LeadSource\LeadSource;
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
use Livewire\Attributes\Lazy;
use Livewire\Component;
use Livewire\WithPagination;

#[Lazy]
class Index extends Component {
    use WithPagination, AuthorizesRequests;

    public $search = '';
    public $sortColumn = 'display_name';
    public $sortDirection = 'asc';
    public $perPage = 10;

    public function mount(): void {
        $this->authorize('sources.view');
    }

    public function placeholder() {
        return <<<'HTML'
        <div class="row">
            <div class="col-12">
                <div class="card">
                    <div class="card-body">
                        <div class="placeholder placeholder-wave w-100"></div>
                        <div class="placeholder placeholder-wave w-100"></div>
                        <div class="placeholder placeholder-wave w-100"></div>
                        <div class="placeholder placeholder-wave w-100"></div>
                        <div class="placeholder placeholder-wave w-75"></div>
                        <div class="placeholder placeholder-wave w-50"></div>
                    </div>
                </div>
            </div>
        </div>
        HTML;
    }

    public function deleteLeadSource($id): void {
        $this->authorize('sources.delete');

        $ls = LeadSource::findOrFail($id);
        $ls->delete();
    }

    public function render() {
        $sources = LeadSource::query();

        if($this->search) {
            $sources->where('display_name', 'like', '%'.$this->search.'%');
        }

        $sources = $sources->paginate($this->perPage);
        return view('components.lead-source.lead-source-list', compact('sources'));
    }
}
