<?php

use Livewire\Component;
use Livewire\WithPagination;
use Livewire\Attributes\Url;
use App\Models\BreakingNews;

return new class extends Component
{
    use WithPagination;

    #[Url(history: true)]
    public $search = '';

    #[Url(history: true)]
    public $statusFilter = '';

    public function render()
    {
        if (!auth()->user()->can('view breaking news')) {
            abort(403);
        }
        return $this->view()->layout('layouts::auth');
    }

    public function delete($id)
    {
        if (!auth()->user()->can('delete breaking news')) {
            session()->flash('error', 'Unauthorized.');
            return;
        }
        BreakingNews::find($id)->delete();
        session()->flash('message', 'Breaking news deleted successfully.');
    }

    public function toggleStatus($id)
    {
        if (!auth()->user()->can('edit breaking news')) {
            session()->flash('error', 'Unauthorized.');
            return;
        }
        $item = BreakingNews::find($id);
        if ($item) {
            $item->update(['is_active' => !$item->is_active]);
        }
    }

    public function with(): array
    {
        $query = BreakingNews::latest();

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

        if ($this->statusFilter) {
            $query->where('is_active', $this->statusFilter === 'active');
        }

        return [
            'items' => $query->paginate(15),
        ];
    }

    public function updatingSearch() { $this->resetPage(); }
    public function updatingStatusFilter() { $this->resetPage(); }

    protected function view($data = [])
    {
        return app('view')->file('D:\02-my freelance\00-DR_Padhi\DR_PADHI\storage\framework/views/livewire/views/5b1cd8f2.blade.php', $data);
    }
};
