<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Spatie\Activitylog\Traits\LogsActivity;
use Spatie\Activitylog\LogOptions;

class Plainte extends Model
{
    use HasFactory, LogsActivity;

    protected $fillable = [
        'numero', 'reference', 'plaignant_id', 'objet', 'description', 'preuves',
        'canal_reception', 'type_plainte', 'niveau_sensibilite',
        'statut', 'date_reception', 'date_accuse_reception',
        'niveau_traitement', 'assigned_to', 'decision', 'mesures_correctives',
        'est_anonyme', 'est_lanceur_alerte', 'remarques', 'commentaire_decision',
        'resolution_proposee', 'statut_resolution', 'date_proposition_resolution',
        'date_validation_resolution', 'commentaire_validation', 'propose_par'
    ];

    protected $casts = [
        'preuves' => 'array',
        'mesures_correctives' => 'array',
        'date_reception' => 'datetime',
        'date_accuse_reception' => 'datetime',
        'date_resolution' => 'datetime',
        'date_cloture' => 'datetime',
        'date_proposition_resolution' => 'datetime',
        'date_validation_resolution' => 'datetime',
        'est_anonyme' => 'boolean',
        'est_lanceur_alerte' => 'boolean',
    ];

    protected static function boot()
    {
        parent::boot();
        
        static::creating(function ($plainte) {
            $plainte->numero = 'PL-' . date('Y') . '-' . str_pad(
                static::whereYear('created_at', date('Y'))->count() + 1, 
                4, '0', STR_PAD_LEFT
            );
            $plainte->reference = 'PL-' . date('Y') . '-' . str_pad(
                (static::whereYear('created_at', date('Y'))->count() + 1)."-".now()->timestamp, 
                20, '0', STR_PAD_LEFT
            );
        });
    }
    public function media(){
        return $this->morphMany(Media::class,'mediable');
    }
    public function plaignant()
    {
        return $this->belongsTo(Plaignant::class, 'plaignant_id');
    }

    public function getActivitylogOptions(): LogOptions
    {
        return LogOptions::defaults()
            ->logOnly(['statut', 'niveau_traitement', 'assigned_to', 'decision', 'statut_resolution'])
            ->logOnlyDirty()
            ->dontSubmitEmptyLogs();
    }
    
    /**
     * Get the resolution token for secure URL generation
     * 
     * @return string
     */
    public function getResolutionToken(): string
    {
        return hash_hmac('sha256', $this->id . $this->updated_at, config('app.key'));
    }
    public function resolutions()
    {
        return $this->hasMany(Resolution::class);
    }
    

    public function investigations()
    {
        return $this->hasMany(Investigation::class);
    }

    public function appeals()
    {
        return $this->hasMany(Appel::class);
    }

    public function communications()
    {
        return $this->hasMany(Communication::class);
    }

    // Méthodes pour les délais
    public function getDelaiTraitementAttribute()
    {
        $delai_max = match($this->niveau_sensibilite) {
            'sensible' => 7,    // 7 jours pour les plaintes sensibles
            'non_sensible' => 15, // 15 jours pour les plaintes ordinaires
            default => 15
        };
        if($this->date_reception!=null){
            return $this->date_reception->addDays($delai_max);
        }
        return 0;
    }
    public function getDelaiTraitementHumansAttribute()
    {
        return $this->delai_traitement->diffForHumans();
    }

    public function getTempsTraitementAttribute()
    {
        if($this->date_reception!=null){
            return $this->date_reception->diffInDays(now());
        }
        return 0;
    }
    public function isDelaiDepasse()
    {
        $delai_max = match($this->niveau_sensibilite) {
            'sensible' => 7,    // 7 jours pour les plaintes sensibles
            'non_sensible' => 15, // 15 jours pour les plaintes ordinaires
            default => 15
        };
        
        return $this->temps_traitement  > $delai_max && !in_array($this->statut, ['resolu', 'clos']);
    }

    public function canBeAppealed()
    {
        return in_array($this->statut, ['resolu', 'irrecevable']) 
               && !$this->appeals()->exists()
               && $this->date_resolution->diffInDays(now()) <= 7;
    }
}
