<?php

namespace App\Models;

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

class Action extends Model
{
    use HasFactory;

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

    protected $fillable = [
        'programme_id',
        'code',
        'nom',
        'description',
        'prog_actif',
        'prog_ouvert',
        'created_at',
        'updated_at',
    ];

    public $timestamps = false;

    // Relation avec Programme
    public function programme()
    {
        return $this->belongsTo(Programme::class, 'programme_id', 'id');
    }

    // Relation avec Resultats
    public function resultats()
    {
        return $this->hasMany(Resultat::class, 'action_id', 'id');
    }
	
	protected static function boot()
    {
        parent::boot();

        static::deleting(function ($groupe) {
            if ($groupe->activites()->exists()) {
                throw new \Exception("Suppression impossible : cette action possède encore des activités associées.");
            }
			if ($groupe->structures()->exists()) {
                throw new \Exception("Suppression impossible : cette action possède encore des structures intervenant.");
            }
        });
    }

    // Relation avec Activites
    public function activites()
    {
        return $this->hasMany(Activite::class, 'action_id', 'id');
    }
	
	//Table pivot
	public function structures()
    {
        return $this->belongsToMany(Structure::class, 'structure_action', 'action_id', 'structure_id')
			->wherePivot('is_active', true)
			->withPivot('id', 'is_active', 'datedebut', 'datefin');
    }
	
	public function structurearchives()
    {
        return $this->belongsToMany(Structure::class, 'structure_action', 'action_id', 'structure_id')
			->wherePivot('is_active', false)
			->withPivot('id', 'is_active', 'datedebut', 'datefin');
    }
}
