<?php

namespace Modules\ClinicCore\Entities;

use Illuminate\Database\Eloquent\Model;
use App\User;

/**
 * SIFA P4-T6 — a referral (internal / external outgoing / external incoming).
 *
 * The referral letter print view pulls the patient's active meds and allergies
 * at render time; only the referral-specific fields live on this row.
 */
class ClcReferral extends Model
{
    protected $table = 'clc_referrals';
    protected $guarded = ['id'];

    protected $casts = [
        'requested_services' => 'array',
    ];

    public const DIRECTIONS = ['internal', 'external_outgoing', 'external_incoming'];
    public const URGENCIES  = ['routine', 'urgent', 'emergency'];
    public const STATUSES    = [
        'draft', 'sent', 'received', 'accepted',
        'in_progress', 'completed', 'rejected', 'cancelled',
    ];

    /** Allowed forward status transitions per direction-agnostic workflow. */
    public const TRANSITIONS = [
        'draft'       => ['sent', 'cancelled'],
        'sent'        => ['received', 'accepted', 'rejected', 'cancelled'],
        'received'    => ['accepted', 'rejected', 'cancelled'],
        'accepted'    => ['in_progress', 'completed', 'cancelled'],
        'in_progress' => ['completed', 'cancelled'],
        'completed'   => [],
        'rejected'    => [],
        'cancelled'   => [],
    ];

    public function canTransitionTo(string $status): bool
    {
        return in_array($status, self::TRANSITIONS[$this->status] ?? [], true);
    }

    public function scopeForBusiness($query, int $businessId)
    {
        return $query->where('business_id', $businessId);
    }

    public function patient()
    {
        return $this->belongsTo(ClcPatient::class, 'patient_id');
    }

    public function appointment()
    {
        return $this->belongsTo(ClcAppointment::class, 'appointment_id');
    }

    public function fromDoctor()
    {
        return $this->belongsTo(ClcDoctor::class, 'from_doctor_id');
    }

    public function toDoctor()
    {
        return $this->belongsTo(ClcDoctor::class, 'to_doctor_id');
    }

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

    /** Next per-business referral number: REF-{biz}-{0000001}. */
    public static function nextReferralNo(int $businessId): string
    {
        return \DB::transaction(function () use ($businessId) {
            $last = static::where('business_id', $businessId)
                ->lockForUpdate()
                ->orderByDesc('id')->value('referral_no');
            $n = 1;
            if ($last && preg_match('/-(\d+)$/', $last, $m)) {
                $n = ((int) $m[1]) + 1;
            }
            return 'REF-' . $businessId . '-' . str_pad((string) $n, 7, '0', STR_PAD_LEFT);
        });
    }
}
