<?php

namespace Modules\VetClinic\Entities;

use Illuminate\Database\Eloquent\Model;

/**
 * One physical stocktake of a controlled medicine batch. If the count differs
 * from the system-expected qty, a paired `adjust` row in
 * vc_controlled_stock_movements absorbs the variance and keeps the running
 * balance honest. The reference (CR-RC-…) is unique per business.
 */
class VcControlledReconciliation extends Model
{
    protected $table = 'vc_controlled_reconciliations';
    protected $guarded = ['id'];

    protected $casts = [
        'stocktake_at' => 'datetime',
        'expected_qty' => 'float',
        'counted_qty'  => 'float',
        'variance'     => 'float',
    ];

    public function medicine()
    {
        return $this->belongsTo(VcMedicine::class, 'medicine_id');
    }

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

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

    public function movement()
    {
        return $this->belongsTo(VcControlledMovement::class, 'movement_id');
    }

    /** Allocate the next stocktake reference for a business. */
    public static function nextReference(int $businessId): string
    {
        return \DB::transaction(function () use ($businessId) {
            $last = static::where('business_id', $businessId)
                ->lockForUpdate()
                ->orderByDesc('id')->value('reference');
            $n = 1;
            if ($last && preg_match('/-(\d+)$/', $last, $m)) {
                $n = ((int) $m[1]) + 1;
            }
            return 'CR-RC-' . $businessId . '-' . str_pad((string) $n, 7, '0', STR_PAD_LEFT);
        });
    }
}
