<?php

namespace App\Components\LeadSource;

use App\Models\LeadSource\LeadSource;
use Livewire\Attributes\Lazy;
use Livewire\Component;

#[Lazy]
class View extends Component {
    public LeadSource $leadSource;

    public ?string $dateFrom = null;
    public ?string $dateTo = null;

    protected $rules = [
        'leadSource.display_name' => 'required|string|max:255',
        'leadSource.status' => 'string|in:active,inactive',
    ];

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

    public function toggleStatus(): void
    {
        $this->leadSource->status =
            $this->leadSource->status === 'active'
                ? 'inactive'
                : 'active';

        $this->leadSource->save();

        $this->dispatch(
            'toast',
            type: 'success',
            message: $this->leadSource->status === 'active'
                ? 'Lead source activated'
                : 'Lead source paused'
        );
    }


    public function getLeadsProperty() {
        return $this->leadSource
            ->leads()
            ->when($this->dateFrom, fn($q) => $q->whereDate('created_at', '>=', $this->dateFrom))
            ->when($this->dateTo, fn($q) => $q->whereDate('created_at', '<=', $this->dateTo))
            ->latest()
            ->get();
    }

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