<?php

namespace App\Models;

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

class Resolution extends Model
{
    use HasFactory, SoftDeletes;

    protected $fillable = [
        'plainte_id',
        'resolution',
        'statut',
        'date_proposition',
        'date_validation',
        'commentaire',
        'propose_par',
    ];

    protected $casts = [
        'date_proposition' => 'datetime',
        'date_validation' => 'datetime',
    ];

    /**
     * Get the plainte that owns the resolution.
     */
    public function plainte()
    {
        return $this->belongsTo(Plainte::class);
    }

    /**
     * Get the user who proposed the resolution.
     */
    public function proposer()
    {
        return $this->belongsTo(User::class, 'propose_par');
    }

    /**
     * Get the media for the resolution.
     */
    public function media()
    {
        return $this->morphMany(Media::class, 'mediable');
    }

    /**
     * Scope a query to only include pending resolutions.
     */
    public function scopePending($query)
    {
        return $query->where('statut', 'en_attente');
    }

    /**
     * Check if the resolution is still pending.
     */
    public function isPending(): bool
    {
        return $this->statut === 'en_attente' && 
               $this->date_proposition && 
               $this->date_proposition->addDays(7)->isFuture();
    }

    /**
     * Accept the resolution.
     */
    public function accept(?string $comment = null): bool
    {
        return $this->update([
            'statut' => 'acceptee',
            'date_validation' => now(),
            'commentaire' => $comment,
        ]);
    }

    /**
     * Reject the resolution.
     */
    public function reject(string $comment): bool
    {
        return $this->update([
            'statut' => 'refusee',
            'date_validation' => now(),
            'commentaire' => $comment,
        ]);
    }
}