<?php

namespace App\Livewire\Projects;

use App\Models\Project;
use Illuminate\Support\Facades\Auth;
use Livewire\Attributes\Layout;
use Livewire\Component;
use Livewire\WithPagination;

#[Layout('layouts.app')]
class ProjectList extends Component
{
    use WithPagination;

    public $search = '';

    public $statusFilter = '';

    public function deleteProject($id)
    {
        $project = Project::findOrFail($id);
        if (Auth::user()->can('delete projects')) {
            $project->delete();
            session()->flash('message', 'Proyecto eliminado');
        }
    }

    public function render()
    {
        $query = Project::accessibleBy(Auth::user());
        if ($this->search) {
            $query->where('name', 'like', '%'.$this->search.'%');
        }
        if ($this->statusFilter) {
            $query->where('status', $this->statusFilter);
        }
        $projects = $query->with('phases')->latest()->paginate(10);

        return view('livewire.projects.project-list', ['projects' => $projects]);
    }
}
