<?php

namespace App\Policies;

use App\Models\Project;
use App\Models\User;
use Illuminate\Auth\Access\Response;

class ProjectPolicy
{
    /**
     * Determine whether the user can view any models.
     */
    public function viewAny(User $user): bool
    {
        return $user->hasPermissionTo('project.view');
    }

    /**
     * Determine whether the user can view the model.
     */
    public function view(User $user, Project $project): bool
    {
        // Admin ve todo, otros usuarios solo proyectos asignados
        /*
        return $user->hasRole('admin') || 
            $project->users->contains($user->id) ||
            $project->manager_id === $user->id;*/

        return $user->hasPermissionTo('project.view') && 
               $this->hasProjectAccess($user, $project);
    }

    /**
     * Determine whether the user can create models.
     */
    public function create(User $user): bool
    {
        return $user->hasPermissionTo('project.create');
    }

    /**
     * Determine whether the user can update the model.
     */
    public function update(User $user, Project $project): bool
    {
        return $user->hasPermissionTo('project.edit') && 
               $this->hasProjectAccess($user, $project);
    }

    /**
     * Determine whether the user can delete the model.
     */
    public function delete(User $user, Project $project): bool
    {
        return $user->hasPermissionTo('project.delete') && 
               $this->hasProjectAccess($user, $project);
    }

    /**
     * Determine whether the user can restore the model.
     */
    public function restore(User $user, Project $project): bool
    {
        return false;
    }

    /**
     * Determine whether the user can permanently delete the model.
     */
    public function forceDelete(User $user, Project $project): bool
    {
        return false;
    }

    protected function hasProjectAccess(User $user, Project $project)
    {
        // Verificar si el usuario es creador, gestor o tiene acceso directo
        return $project->creator_id === $user->id ||
               $project->managers->contains($user->id) ||
               $project->users->contains($user->id);
    }

    public function managePermissions(User $user, Project $project)
    {
        return $user->hasPermissionToResource($project, 'manage_permissions');
    }
    
}
