<?php

namespace App\Models;

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

class ChecklistEntry extends Model
{
    use HasFactory;

    protected $fillable = [
        'unit_id',
        'entered_by',
        'entry_date',
        'entry_time',
        'condition_status',
        'issue_found',
        'maintenance_required',
        'custom_fields',
        'notes',
        'image',
        'last_edited_by',
        'last_edited_at',
    ];

    protected function casts(): array
    {
        return [
            'custom_fields'       => 'array',
            'issue_found'         => 'boolean',
            'maintenance_required'=> 'boolean',
            'entry_date'          => 'date:Y-m-d',
            'last_edited_at'      => 'datetime',
        ];
    }

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

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

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

    public function getImageUrlAttribute(): ?string
    {
        return $this->image ? asset('storage/' . $this->image) : null;
    }

    public function canBeEditedBy(User $user): bool
    {
        if ($user->isFrozen()) {
            return false;
        }

        if ($user->isAdmin()) {
            return true;
        }

        return $this->entered_by === $user->id
            && $this->entry_date->isToday();
    }
}
