<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
use Illuminate\Support\Facades\Auth;

class InitiativeResult extends Model
{
    use HasFactory;

    protected $fillable = [
        'initiative_id',
        'expected_q1',
        'actual_q1',
        'expected_q2',
        'actual_q2',
        'expected_q3',
        'actual_q3',
        'expected_q4',
        'actual_q4',
        'created_by',
    ];

    protected $casts = [
        'expected_q1' => 'decimal:2',
        'actual_q1' => 'decimal:2',
        'expected_q2' => 'decimal:2',
        'actual_q2' => 'decimal:2',
        'expected_q3' => 'decimal:2',
        'actual_q3' => 'decimal:2',
        'expected_q4' => 'decimal:2',
        'actual_q4' => 'decimal:2',
    ];

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

    public function performanceCardResults(): BelongsToMany
    {
        return $this->belongsToMany(PerformanceCardResult::class, 'initiative_result_pcr');
    }

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

    /**
     * Boot the model
     */
    protected static function boot()
    {
        parent::boot();

        static::creating(function ($model) {
            if (Auth::check()) {
                $model->created_by = Auth::id();
            }
        });
    }
}
