<?php

namespace Modules\MedSurgery\Entities;

use Illuminate\Database\Eloquent\Model;

/**
 * One WHO safety-checklist phase for a case (sign_in / time_out / sign_out).
 * `items` is [{label, checked, by}]. A phase is "complete" when every item is
 * checked; ChecklistService signs it (stamps completed_by/at).
 */
class MedsxChecklist extends Model
{
    protected $table = 'medsx_checklists';

    protected $guarded = ['id'];

    protected $casts = [
        'items'        => 'array',
        'completed_at' => 'datetime',
    ];

    public const PHASES = ['sign_in', 'time_out', 'sign_out'];

    public function surgicalCase()
    {
        return $this->belongsTo(MedsxCase::class, 'case_id');
    }

    /** Every item ticked? */
    public function allChecked(): bool
    {
        $items = $this->items ?? [];
        if (empty($items)) {
            return false;
        }

        foreach ($items as $item) {
            if (empty($item['checked'])) {
                return false;
            }
        }

        return true;
    }

    /** Signed off (all items checked and stamped). */
    public function isComplete(): bool
    {
        return $this->completed_at !== null && $this->allChecked();
    }
}
