<?php

namespace App\Models;

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

class Activite extends Model
{
    use HasFactory;

    protected $table = 'activites';
    protected $primaryKey = 'id';

    protected $fillable = [
		'groupe_id',
        'code',
        'nom',
        'datedebut',
        'datefin',
        'montant',
        'structure_id',
        'valide',
        'action_id',
		'resultat_id',
        'actif',
        'ouvert',
        'created_at',
        'updated_at',
    ];

    public $timestamps = false;

    // Relation avec Structure
    public function structureresponsable()
    {
        return $this->belongsTo(Structure::class, 'structure_id', 'id');
    }
	
	public function structurespartenaires()
    {
        return $this->belongsToMany(Structure::class, 'structure_activite', 'activite_id', 'structure_id')
			->wherePivot('is_active', true)
			->withPivot('id', 'is_active', 'datedebut', 'datefin');
    }

    // Relation avec Action
    public function action()
    {
        return $this->belongsTo(Action::class, 'action_id', 'id');
    }

    // Relation avec Résultat
    public function resultat()
    {
        return $this->belongsTo(Resultat::class, 'resultat_id', 'id');
    }

    // Relation avec Evaluations
    public function evaluations()
    {
	    return $this->hasMany(Evaluation::class, 'activite_id', 'id')
			->orderBy('taux_realisation', 'asc');
    }
	
	public function groupeactivite()
	{
		return $this->belongsTo(GroupeActivite::class, 'groupe_id');
	}

	public function etapes()
	{
		// On récupère les étapes via le modèle lié
		return $this->hasManyThrough(
			Etape::class,
			GroupeActivite::class,
			'id',                
			'groupeactivite_id', 
			'groupe_id',         
			'id'                
		);
	}
	
	
	public function previsions()
    {
        return $this->hasMany(PrevisionActivite::class, 'activite_id', 'id');
    }
	
	public function extrants()
    {
        return $this->hasMany(Extrant::class, 'activite_id', 'id')
					->orderBy('debut', 'asc'); 
    }
	
	public function structurearchives()
    {
        return $this->belongsToMany(Structure::class, 'structure_activite', 'activite_id', 'structure_id')
			->wherePivot('is_active', false)
			->withPivot('id', 'is_active', 'datedebut', 'datefin');
    }
}

