<?php

use Livewire\Component;
use Livewire\WithPagination;
use Livewire\Attributes\Url;
use App\Models\Post;
use App\Models\Category;

return new class extends Component
{
    use WithPagination;

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

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

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

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

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

    public $dateFrom = '';
    public $dateTo = '';

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

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

    public function with(): array
    {
        $query = Post::with('category')->latest();

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

        if ($this->categoryFilter) {
            $query->where('category_id', $this->categoryFilter);
        }

        if ($this->statusFilter) {
            $query->where('status', $this->statusFilter);
        }

        if ($this->featuredFilter !== '') {
            $query->where('is_featured', filter_var($this->featuredFilter, FILTER_VALIDATE_BOOLEAN));
        }

        if ($this->breakingFilter !== '') {
            $query->where('is_breaking', filter_var($this->breakingFilter, FILTER_VALIDATE_BOOLEAN));
        }

        if ($this->dateFrom) {
            $query->whereDate('created_at', '>=', $this->dateFrom);
        }

        if ($this->dateTo) {
            $query->whereDate('created_at', '<=', $this->dateTo);
        }

        return [
            'posts' => $query->paginate(15),
            'categories' => Category::orderBy('name')->pluck('name', 'id'),
        ];
    }

    public function updatingSearch() { $this->resetPage(); }
    public function updatingCategoryFilter() { $this->resetPage(); }
    public function updatingStatusFilter() { $this->resetPage(); }
    public function updatingFeaturedFilter() { $this->resetPage(); }
    public function updatingBreakingFilter() { $this->resetPage(); }
    public function updatingDateFrom() { $this->resetPage(); }
    public function updatingDateTo() { $this->resetPage(); }

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