<?php

namespace App\Services\Accounting;

use App\Enums\DocumentStatus;
use App\Models\DriverAdvance;
use App\Services\Audit\AuditLogger;
use Illuminate\Support\Facades\DB;

final class DriverAdvancePostingService
{
    public function __construct(private readonly AuthorizationGuard $authorization,private readonly DocumentApprovalGuard $guard,private readonly JournalPostingService $journals,private readonly AuditLogger $audit){}
    public function post(DriverAdvance $advance):DriverAdvance{return DB::transaction(function()use($advance){$advance=DriverAdvance::query()->lockForUpdate()->findOrFail($advance->id);$this->authorization->ensureCan('driver_advances.post',(int)$advance->company_id,(int)$advance->branch_id);$this->guard->ensureApproved($advance);$this->journals->post($advance,['company_id'=>$advance->company_id,'branch_id'=>$advance->branch_id,'posting_date'=>$advance->advance_date,'document_date'=>$advance->advance_date,'reference_number'=>$advance->advance_number,'source_module'=>'driver_advances','description'=>'Driver advance '.$advance->advance_number],[['account_id'=>$advance->advance_account_id,'debit'=>$advance->amount,'description'=>'Driver advance issued'],['account_id'=>$advance->cash_bank_account_id,'credit'=>$advance->amount,'description'=>'Cash/bank paid']]);$advance->forceFill(['status'=>DocumentStatus::POSTED,'posted_at'=>now()])->save();$this->audit->log('posted','driver_advances',$advance,[],['status'=>'posted']);return$advance->refresh();},3);}
}
