<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Carbon\Carbon;
use App\Models\Setting;

class VesselRecord extends Model
{
    protected $fillable = [
        'vessel_id',
        'date',
        'invoice_no',
        'port',
        'description',
        'amount',
        'due_date',
        'company',
        'status_id',
        'created_by'
    ];

    protected $casts = [
        'date' => 'date',
        'due_date' => 'date',
        'amount' => 'decimal:2'
    ];

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

    public function status(): BelongsTo
    {
        return $this->belongsTo(StatusOption::class, 'status_id');
    }

    public function attachments(): HasMany
    {
        return $this->hasMany(RecordAttachment::class, 'record_id');
    }

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

    public function getDueDateStatusAttribute(): string
    {
        if (!$this->due_date) {
            return 'none';
        }

        $today = Carbon::today();
        $daysDiff = $today->diffInDays($this->due_date, false);

        if ($daysDiff < 0) {
            return 'overdue';
        }

        // Get settings from database
        $criticalDays = Setting::getValue('critical_days', 2);
        $warningDays = Setting::getValue('warning_days', 7);

        if ($daysDiff <= $criticalDays) {
            return 'critical';
        } elseif ($daysDiff <= $warningDays) {
            return 'warning';
        }

        return 'normal';
    }
}
