<?php

namespace App\Models;

use Carbon\Carbon;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Support\Facades\Auth;
use Spatie\Activitylog\LogOptions;
use Spatie\Activitylog\Traits\LogsActivity;
use Spatie\MediaLibrary\HasMedia;
use Spatie\MediaLibrary\InteractsWithMedia;

class OrderAgreement extends Model implements HasMedia
{
    use HasFactory, InteractsWithMedia, LogsActivity;

    protected $fillable = [
        'order_id',
        'contract_number',
        'total_contract_value',
        'start_date',
        'created_by',
    ];

    protected $casts = [
        'total_contract_value' => 'decimal:2',
        'start_date' => 'datetime',
        'created_at' => 'datetime',
        'updated_at' => 'datetime',
    ];

    protected $appends = [
        'end_date',
    ];

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

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

    /**
     * Get the calculated end date (start_date + execution_duration from order finance)
     * تاريخ نهاية العقد المحسوب
     */
    public function getEndDateAttribute(): ?Carbon
    {
        if (! $this->start_date || ! $this->order || ! $this->order->finance || ! $this->order->finance->execution_duration) {
            return null;
        }

        $startDate = Carbon::parse($this->attributes['start_date']);

        return $startDate->addDays($this->order->finance->execution_duration);
    }

    /**
     * Get execution duration in days from related order finance
     * مدة التنفيذ بالأيام من مالية الطلب
     */
    public function getExecutionDurationAttribute(): ?int
    {
        return $this->order?->finance?->execution_duration;
    }

    public function getActivitylogOptions(): LogOptions
    {
        return LogOptions::defaults()
            ->useLogName('order_agreement');
    }

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

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