<?php

namespace Modules\ClinicCore\Entities;

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

class ClcPreferredDoctorHistory extends Model
{
    protected $table = 'clc_preferred_doctor_history';
    protected $guarded = ['id'];

    public function owner()
    {
        return $this->belongsTo(Contact::class, 'contact_id');
    }

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

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

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

    public function changedBy()
    {
        return $this->belongsTo(\App\User::class, 'changed_by');
    }

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

    /**
     * Record a preferred-doctor change. No-ops when nothing actually changed.
     */
    public static function record(array $attrs): ?self
    {
        $old = $attrs['old_doctor_id'] ?? null;
        $new = $attrs['new_doctor_id'] ?? null;
        if ((int) $old === (int) $new) {
            return null;
        }
        return self::create(array_merge([
            'changed_by' => auth()->id(),
            'source'     => 'manual',
        ], $attrs));
    }
}
