<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\SoftDeletes;

// Importa los modelos relacionados
use App\Models\Section;
use App\Models\Fractional;
use App\Models\User;
use App\Models\Image;

class Project extends Model
{
    use HasFactory, SoftDeletes;

    protected $fillable = [
        'name',
        'description',
        'location',
        'image_id',
        'company_name',
        'company_description',
        'company_phone',
        'company_email',
        'company_address',
        'company_logo',
    ];

    // Relaciones
    public function fractionals()
    {
        return $this->hasMany(Fractional::class);
    }

    public function sections()
    {
        return $this->hasMany(Section::class);
    }

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

    public function image()
    {
        return $this->belongsTo(Image::class);
    }

    /**
     * Scope: cargar secciones y sus fractionals con orden predefinido.
     * Uso:
     *   Project::withSectionsAndFractionals()->findOrFail($id);
     */
    public function scopeWithSectionsAndFractionals($query)
    {
        return $query->with([
            'sections' => function ($q) {
                $q->orderBy('code'); // ordena secciones por código
            },
            'sections.fractionals' => function ($q) {
                $q->orderBy('name'); // ordena fractionals por nombre
            },
        ]);
    }
}
