<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;

class Activity extends Model
{
    protected $fillable = [
        'title', 'description', 'start_date', 'end_date',
        'created_by', 'status', 'approved_by', 'approved_at',
        'executed_at', 'execution_notes',
    ];

    protected $casts = [
        'start_date'  => 'date',
        'end_date'    => 'date',
        'approved_at' => 'datetime',
        'executed_at' => 'datetime',
    ];

    protected static function booted(): void
    {
        static::creating(function (Activity $activity) {
            $activity->created_by ??= auth()->id();
            $activity->status ??= 'draft';
        });
    }

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

    public function approver(): BelongsTo
    {
        return $this->belongsTo(User::class, 'approved_by');
    }

    public function participants(): BelongsToMany
    {
        return $this->belongsToMany(User::class, 'activity_member')
            ->withPivot('status', 'notes');
    }
}
