<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;

class Project extends Model
{
    protected $fillable = [
        'reference',
        'name',
        'description',
        'creator_id', 
        'status',
        'project_image_path',
        'address',
        'province',
        'country',
        'postal_code',
        'latitude',
        'longitude',
        'icon',
        'start_date',
        'deadline',
        'company_id',
        // Agrega cualquier otro campo nuevo aquí
    ];

    public function folders() {
        return $this->hasMany(Folder::class);
    }
    
    public function currentFolder()
    {
        return $this->belongsTo(Folder::class);
    }
    
    public function documents() {
        return $this->hasMany(Document::class);
    }

    public function rootFolders()
    {
        return $this->folders()->whereNull('parent_id')->with('children');
    }

    public function creator()
    {
        return $this->belongsTo(User::class, 'creator_id');
    }

    public function managers()
    {
        return $this->belongsToMany(User::class, 'project_managers');
    }

    public function users()
    {
        return $this->belongsToMany(User::class, 'project_users');
    }

    
    public function scopeFilter(Builder $query, array $filters)
    {
        $query->when($filters['search'] ?? false, function($query, $search) {
            $query->where(function($query) use ($search) {
                $query->where('name', 'like', "%{$search}%")
                    ->orWhere('description', 'like', "%{$search}%");
            });
        });
        
        // Agrega más filtros según necesites
        /*
        $query->when($filters['status'] ?? false, function($query, $status) {
            $query->where('status', $status);
        });
        */
    }

    public function categories()
    {
        return $this->belongsToMany(Category::class);
    }

    public function company()
    {
        return $this->belongsTo(Company::class);
    }
}
