<?php
declare(strict_types=1);
namespace App\Services;
use App\Repositories\BillingRateRepository;
use InvalidArgumentException;
final class BillingRateService {
    public function __construct(private ?BillingRateRepository $repo=null){$this->repo??=new BillingRateRepository();}
    public function data(int $patientId):array{$this->repo->ensureDefaults($patientId);return ['patients'=>$this->repo->patients(),'services'=>$this->repo->services(),'rates'=>$this->repo->rates($patientId)];}
    public function save(array $d):void{$p=(int)($d['patient_id']??0);$s=(int)($d['service_id']??0);$r=trim((string)($d['rate']??''));if($p<1||$s<1)throw new InvalidArgumentException('Select a patient and service.');if(!preg_match('/^\d+(?:\.\d{1,2})?$/',$r))throw new InvalidArgumentException('Enter a valid rate.');$this->repo->save($p,$s,(float)$r,trim((string)($d['label']??'')));}
    public function delete(int $id):void{$this->repo->delete($id);}
    public function rateFor(int $p,int $s):?float{$this->repo->ensureDefaults($p);return $this->repo->rateFor($p,$s);}
}
