<?php

namespace App\Models;

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

class ProjectMilestone extends Model
{
    use HasFactory;

    protected $fillable = [
        'project_id',
        'name',
        'description',
        'planned_date',
        'actual_date',
        'planned_budget',
        'actual_cost',
        'status',
        'certified',
        'certification_notes',
        'certified_by',
        'certified_at',
        'sequence_order',
    ];

    protected $casts = [
        'planned_date' => 'datetime',
        'actual_date' => 'datetime',
        'certified_at' => 'datetime',
        'planned_budget' => 'decimal:2',
        'actual_cost' => 'decimal:2',
    ];

    public function project(): BelongsTo
    {
        return $this->belongsTo(Project::class);
    }

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

    public function certify(User $consultant, string $notes = null): void
    {
        $this->update([
            'certified' => true,
            'certified_by' => $consultant->id,
            'certified_at' => now(),
            'certification_notes' => $notes,
            'status' => 'completed',
            'actual_date' => now(),
        ]);
    }
}
