<?php

namespace Modules\Account\Controllers;


use App\Controllers\BaseController;
use App\Libraries\UserCheck;
use Modules\Account\Models\AccountModel;
use Modules\Account\Models\PayagentModel;
use Modules\User\Models\UserDetailModel;
use Modules\Agent\Models\AgentModel;
use Modules\Paymethod\Models\PaymethodModel;
use Modules\Agent\Models\AgenttotalModel;
use Modules\Company\Models\CompanyModel;

use App\Libraries\Rolepermission;

class Payagent extends BaseController
{
    protected $Viewpath;
	protected $accountModel;
	protected $userdetailModel;
	protected $agentModel;
	protected $db;
	protected $paymethod;
    protected $agentTotal;
    protected $agentPayment;
    protected $companyModel;
	
	public function __construct()
    {

        $this->Viewpath = "Modules\Account\Views";
		$this->accountModel = new AccountModel();
		$this->userdetailModel = new UserDetailModel();
		$this->agentModel = new AgentModel();
		$this->paymethod = new PaymethodModel();
		$this->db = \Config\Database::connect();

        $this->agentTotal = new AgenttotalModel();
        $this->agentPayment = new PayagentModel();
        $this->companyModel = new CompanyModel();
      
    }

    function new ()
	 {
        $userchek = new UserCheck();
		$userType = $userchek->getUserType();
        if ($userType == 2) {
			
            $currentUserId =  $this->session->get('user_id');
		    $agentDetail = 	$this->agentModel->where('user_id',$currentUserId)->first();
		  //  print_r($agentDetail);die;
            $agentid = $agentDetail->id;
            $allTranSaction = $this->agentTotal->where('agent_id',$agentid)->findAll();
            // print_r('allTranSaction',$allTranSaction);die;
            $givenMoney = $this->agentPayment->where('agent_id',$agentid)->findAll();
            // print_r($givenMoney);
            $givenTotalMoney = array_sum(array_column($givenMoney, 'amount'));
            // print_r($givenTotalMoney);
            $agentIncomeTotal = array_sum(array_column($allTranSaction, 'income'));
            // print_r($agentIncomeTotal);
            $agentExpenseTotal = array_sum(array_column($allTranSaction, 'expense'));
            // print_r($agentExpenseTotal);die;
            $keepMoney = $agentIncomeTotal - $agentExpenseTotal;
            // print_r($agentExpenseTotal);die;
            $keepMoney = $keepMoney - $givenTotalMoney;
            if (0 == 0) {

                $data['keepMoney'] = $agentDetail->wallet;
                $data['pageheading'] = lang("Localize.agent_payment");

                $data['companies'] = $this->companyModel->where("FIND_IN_SET($currentUserId, user_id) >", 0)->where('status', 1)->findAll();

                $data['module'] =    lang("Localize.account") ; 
                $data['title']  =    lang("Localize.agent_payment") ;
                echo view($this->Viewpath . '\payagent/new',$data);
            }
            else{

                return redirect()->back()->with("fail","Dont Have Money to Submit Request");
            }
           
		}

        else{
            return redirect()->back()->with("fail","Dont Have Permission");
        }

		
        


    }

    public function index()
    {
        $role_id =  $this->session->get('role_id');
        $user_id =  $this->session->get('user_id');
        $userId = $this->session->get('user_id');
        $userRole = $this->session->get('role_id');

        $session = session();
        $allSessionData = $session->get();
        // /echo "<pre>";print_r($allSessionData);exit;

        $company_login = 0;
        $agent_login = 0;
        $admin_login = 0;
        $agent_agent_id = 0;
        $agent_company_id = 0;
        $company_company_id = 0;
        $companyBalancesArray = [];

        if($role_id == 2) {
            
            $agent_login = 1;
            
            $agentDetail = 	$this->agentModel->where('user_id',$user_id)->first();
            $agent_agent_id = $agentDetail->id;

            $agent_company_id = $this->session->get('company_id');
        } else if($role_id == 7) {
            
            $company_login = 1;
            $company_company_id = $this->session->get('company_id');
        } else if($role_id == 1){
            
            $admin_login = 1;
        } else {
            return redirect()->back()->with("fail","Dont Have Permission");
        }


        $startData = date('Y-m-01');
		$endDate = date('Y-m-d');
        // 		print_r($endDate);die;
		$fromDate = $startData; //$this->request->getVar('start_date');
		$toDate = $endDate; //$this->request->getVar('end_date');

        $agetntPay = $this->agentPayment->select('agents.id as agentId,agents.*,payagents.*, companies.name AS company_name, concat(user_details.first_name, "  ", user_details.last_name) AS approved_by')
						->join('agents', 'agents.id = payagents.agent_id','left')
                        ->join('companies', 'companies.id = payagents.company_id','left')
                        ->join('user_details', 'user_details.user_id = payagents.approved_id','left')
						->where('DATE(payagents.created_at) >=', $fromDate)
                        #->where('payagents.status',1)
                        ->where('DATE(payagents.created_at) <=', $toDate);
        // if($agent_login){
        //     $agetntPay = $agetntPay->where('agent_id', $agent_agent_id)->orWhere('company_id', $agent_company_id);
        // } else if($company_login) {
        //     $agetntPay = $agetntPay->where('company_id', $company_company_id);
        // }
        if (!in_array($userRole,[1,2,7])) {
            $rolepermissionLibrary = new Rolepermission();
            if (!$rolepermissionLibrary->create('all_tickets')) {
                $agetntPay = $agetntPay->where('agent_id', $agent_agent_id);
            }else{
                $agetntPay = $agetntPay->where('payagents.company_id', $company_company_id);
            }
        }else{
            if(in_array($userRole,[7])){
              $agetntPay = $agetntPay->where('payagents.company_id', $company_company_id);
            }
            if(in_array($userRole,[2])){
              $agetntPay = $agetntPay->where('agent_id', $agent_agent_id);
              // ->orWhere('payagents.company_id', $agent_company_id);
            }
        }
        $agetntPay = $this->enrichPayagentRows($agetntPay->findAll());

        if($agent_login){
            $companyBalancesArray = $this->getResolvedCompanyBalances($agent_agent_id);
        }

        $userchek = new UserCheck();
		$userType = $userchek->getUserType();
        $data['userType'] = $role_id;
        $data['pageheading'] = lang("Localize.transaction_list");

		$data['module'] =    lang("Localize.account") ; 
		$data['title']  =    lang("Localize.agent_payment") ;

        $rolepermissionLibrary = new Rolepermission();
        $add_data = "agent_payment";
        $list_data = "agent_payment";

        $data['add_data'] = $rolepermissionLibrary->create($add_data); 
        $data['edit_data'] = $rolepermissionLibrary->edit($list_data); 
        $data['delete_data'] = $rolepermissionLibrary->delete($list_data);

        $data['payagent'] = array_reverse($agetntPay);
        $data['companyBalances'] = $companyBalancesArray; // Pass the company balances array to the view

		echo view($this->Viewpath . '\payagent/index',$data);
    }



    public function create()
	{
        $currentUserId =  $this->session->get('user_id');
        $agentDetail = 	$this->agentModel->where('user_id',$currentUserId)->first();
        $agentid = $agentDetail->id;


		$amount = $this->request->getVar('amount');
        $company_id = $this->request->getVar('company_id');



		$data= array(
			"agent_id"=> $agentid,
            "company_id" => $company_id,
			"amount"=> $amount,
			"status"=> 0,
			
		);

	
		
		if($this->validation->run($data, 'agentpay'))
		{
			
			$this->agentPayment->insert($data);  
			return redirect()->route('index-payagent')->with("success","Data Save");
		}
		
		
		else
		{

            $allTranSaction = $this->agentTotal->where('agent_id',$agentid)->findAll();
            $agentIncomeTotal = array_sum(array_column($allTranSaction, 'income'));
            $agentExpenseTotal = array_sum(array_column($allTranSaction, 'expense'));
            $keepMoney = $agentIncomeTotal - $agentExpenseTotal;
			$data['keepMoney'] = $keepMoney;
			$data['validation'] = $this->validation;
            $data['module'] =    lang("Localize.account") ; 
            $data['title']  =    lang("Localize.agent_payment") ;
            echo view($this->Viewpath . '\payagent/new',$data);

		}
		
	}

    public function status($id,$value,$amount,$agentid)
    {
		
		$db = \Config\Database::connect();
		$agentinfo = $this->agentModel->find($agentid);
		$systemuserid = $agentinfo->user_id;
        // print_r($systemuserid);die;
        // $user_id =  $this->session->get('user_id');
        
        if($value == 1)
        {
            // (type, detail, amount, system_user_id) VALUES (?, ?, ?, ?)
            $sqlagents = "INSERT INTO accounts (booking_id, transaction_type, type, detail, amount, system_user_id) VALUES (NULL, ?, ?, ?, ?, ?) ";
            $db->query($sqlagents, ['recharge', 'income', 'recharge by admin', $amount, $systemuserid]);
            
            $lastInsertId = $db->insertID();

            // Get the company_id from the payagent record being approved
            $payagentRecord = $this->agentPayment->find($id);
            $approvedCompanyId = $payagentRecord ? $payagentRecord->company_id : 0;

            // Compute per-company running balance
            $lastCompanyRecord = $this->agentPayment
                ->select('total_balance')
                ->where('agent_id', $agentid)
                ->where('company_id', $approvedCompanyId)
                ->where('status', 1)
                ->orderBy('id', 'DESC')
                ->first();
            $currentCompanyBalance = $lastCompanyRecord ? (float)$lastCompanyRecord->total_balance : 0;
            $newCompanyBalance = $currentCompanyBalance + $amount;

            // Also update global wallet
            $currentGlobalWallet = $agentinfo->wallet;
            $globalNewWallet = $currentGlobalWallet + $amount;
            
            $data= array(
                "id" => $id,
                "status"=> $value,
                "account_id"=>$lastInsertId,
                "approved_id"=> session()->get('user_id'),
                "accepted_date" => date("y-m-d H:i:s"),
                "total_balance" => $newCompanyBalance,
            );
            
            $this->agentPayment->save($data);
            
            
            $sqlagentstotal = "INSERT INTO agenttotals (agent_id, booking_id, account_id, income, expense, detail) VALUES (?, ?, ?, ?, ?, ?)";
            $db->query($sqlagentstotal, [$agentid, 'recharge', $lastInsertId, $amount, 0, 'recharge by admin']);
        
        
// 		print_r("success");die;
        
        
        // print_r($agentinfo);die;
        
        // print_r($newamt);die;
        
        $agentData['wallet'] = $globalNewWallet;
        
        $sql = "UPDATE agents SET wallet = ? WHERE id = ?";

            // Execute the query
            $result = $db->query($sql, [$globalNewWallet, $agentid]);
            
            
        }else 
        {
            // Get the company_id from the payagent record being rejected
            $payagentRejectRecord = $this->agentPayment->find($id);
            $rejectCompanyId = $payagentRejectRecord ? $payagentRejectRecord->company_id : 0;

            // Compute per-company balance after reversal: look up last balance then subtract the amount
            $lastCompanyRecordReject = $this->agentPayment
                ->select('total_balance')
                ->where('agent_id', $agentid)
                ->where('company_id', $rejectCompanyId)
                ->where('status', 1)
                ->orderBy('id', 'DESC')
                ->first();
            $currentCompanyBalanceReject = $lastCompanyRecordReject ? (float)$lastCompanyRecordReject->total_balance : 0;
            $newCompanyBalanceReject = $currentCompanyBalanceReject - $amount;

            // Reverse global wallet too
            $globalWalletAfterReject = $agentinfo->wallet - $amount;

            $data= array(
			"id" => $id,
			"status"=> $value,
            "total_balance" => $newCompanyBalanceReject,
		);
		
        $this->agentPayment->save($data);
        
        $payagents = $this->agentPayment->find($id);
        
        $account_id = $payagents->account_id;
                  
            
            // (type, detail, amount, system_user_id) VALUES (?, ?, ?, ?)
            
            
            
        $sqlagents = "DELETE  FROM accounts WHERE id=$account_id";
        $db->query($sqlagents);
        
        
		
        
        
        $sqlagentstotal = "DELETE FROM agenttotals WHERE account_id=$account_id";
        $db->query($sqlagentstotal);
        
        
        $agentData['wallet'] = $globalWalletAfterReject;
        
        $sql = "UPDATE agents SET wallet = ? WHERE id = ?";

            // Execute the query
            $result = $db->query($sql, [$globalWalletAfterReject, $agentid]);
        }
        
        
		return redirect()->route('index-payagent')->with("success","Data Save");
    }

    public function delete($id)
	{
		$this->agentPayment->delete($id);
		return redirect()->route('index-payagent')->with("fail","Data Deleted");
	}



    public function range()
    {

        $startData = $this->request->getVar('start_date');
		$endDate = $this->request->getVar('end_date');
		$fromDate = $startData; //$this->request->getVar('start_date');
		$toDate = $endDate; //$this->request->getVar('end_date');
        
        $role_id =  $this->session->get('role_id');
        $user_id =  $this->session->get('user_id');

        $session = session();
        $allSessionData = $session->get();

        $company_login = 0;
        $agent_login = 0;
        $admin_login = 0;
        $agent_agent_id = 0;
        $agent_company_id = 0;
        $company_company_id = 0;
        $companyBalancesArray = [];

        if($role_id == 2) {
            
            $agent_login = 1;
            
            $agentDetail =  $this->agentModel->where('user_id',$user_id)->first();
            $agent_agent_id = $agentDetail->id;

            $agent_company_id = $this->session->get('company_id');
        } else if($role_id == 7) {
            
            $company_login = 1;
            $company_company_id = $this->session->get('company_id');
        } else if($role_id == 1){
            
            $admin_login = 1;
        } else {
            return redirect()->back()->with("fail","Dont Have Permission");
        }

        $agetntPay = $this->agentPayment->select('agents.id as agentId,agents.*,payagents.*, companies.name AS company_name, concat(user_details.first_name, "  ", user_details.last_name) AS approved_by')
						->join('agents', 'agents.id = payagents.agent_id','left')
                        ->join('companies', 'companies.id = payagents.company_id','left')
                        ->join('user_details', 'user_details.user_id = payagents.approved_id','left')
						->where('DATE(payagents.created_at) >=', $fromDate. " 00:00:00")->where('DATE(payagents.created_at) <=', $toDate." 00:00:00");

        if($agent_login){
        $agetntPay = $agetntPay->groupStart()
                                ->where('agent_id', $agent_agent_id)
                                ->orWhere('payagents.company_id', $agent_company_id)
                                ->groupEnd();
        } else if($company_login) {
            $agetntPay = $agetntPay->where('payagents.company_id', $company_company_id);
        }
        $agetntPay = $this->enrichPayagentRows($agetntPay->findAll());

        // $db = \Config\Database::connect();
        // echo $db->getLastQuery();
        // exit;

        $userchek = new UserCheck();
		$userType = $userchek->getUserType();
        $data['userType'] = $userType;
        $data['pageheading'] = lang("Localize.transaction_list");

		$data['module'] =    lang("Localize.account") ; 
		$data['title']  =    lang("Localize.agent_payment") ;

        $rolepermissionLibrary = new Rolepermission();
        $add_data = "agent_payment";
        $list_data = "agent_payment";

        $data['add_data'] = $rolepermissionLibrary->create($add_data); 
        $data['edit_data'] = $rolepermissionLibrary->edit($list_data); 
        $data['delete_data'] = $rolepermissionLibrary->delete($list_data);

        $data['payagent'] = $agetntPay;
		echo view($this->Viewpath . '\payagent/index',$data);
    }



    public function edit($id)
	{
		 
		$data['agentpay'] = $this->agentPayment->find($id);
		$data['module'] =    lang("Localize.account") ; 

		$heading = lang("Localize.tranjection").' '.lang("Localize.edit");
		$data['pageheading'] = $heading;

		echo view($this->Viewpath.'\payagent/edit',$data);
	}



    public function update($id)
	{
        
		$amount = $this->request->getVar('amount');

		$data= array(
            "id" => $id,
			"amount"=> $amount,
		);

        $agentPay = $this->agentPayment->find($id);

        $validData= array(
			"agent_id"=> $agentPay->agent_id ,
			"amount"=> $amount,
			"status"=> $agentPay->status,
			
		);
	
		
		if($this->validation->run($validData, 'agentpay'))
		{
			
			$this->agentPayment->save($data);
			return redirect()->route('index-payagent')->with("success","Data Save");
		}
		
		
		else
		{

            $data['agentpay'] = $this->agentPayment->find($id);
            $data['module'] =    lang("Localize.account") ; 

            $heading = lang("Localize.tranjection").' '.lang("Localize.edit");
            $data['pageheading'] = $heading;

            echo view($this->Viewpath . '\payagent/edit',$data);

		}
		
	}



    public function show($agentId)
    {

        $allTranSaction = $this->agentTotal->where('agent_id',$agentId)->findAll();

        $givenMoney = $this->agentPayment->where('agent_id',$agentId)->findAll();
        $givenTotalMoney = array_sum(array_column($givenMoney, 'amount'));
        $agentIncomeTotal = array_sum(array_column($allTranSaction, 'income'));
        $agentExpenseTotal = array_sum(array_column($allTranSaction, 'expense'));
        $totalMoney = $agentIncomeTotal - $agentExpenseTotal;
        $dueMoney = $totalMoney - $givenTotalMoney;
        $data['givenMoney'] = $givenTotalMoney;
        $data['totalMoney'] = $totalMoney;
        $data['dueMoney'] =  $dueMoney;

        $startData = date('Y-m-01');
		$endDate = date('Y-m-d');
		$fromDate = $startData; //$this->request->getVar('start_date');
		$toDate = $endDate; //$this->request->getVar('end_date');

        $agetntPay = $this->agentPayment->select('agents.id as agentId,agents.*,payagents.*, companies.name AS company_name')
						->join('agents', 'agents.id = payagents.agent_id','left')
                        ->join('companies', 'companies.id = payagents.company_id','left')
                        ->where('payagents.agent_id',$agentId)
						->where('DATE(payagents.created_at) >=', $fromDate)->where('DATE(payagents.created_at) <=', $toDate)
						->findAll();


        $data['pageheading'] = lang("Localize.transaction_list");

		$data['module'] =    lang("Localize.account") ; 
		$data['title']  =    lang("Localize.agent_payment") ;

        $data['agentid'] =  $agentId;
        $data['payagent'] = $this->enrichPayagentRows($agetntPay);
		echo view($this->Viewpath . '\payagent/singleagent',$data);
    }



    public function singleagentrange()
    {
        $agentId = $this->request->getVar('agentid');
        $allTranSaction = $this->agentTotal->where('agent_id',$agentId)->findAll();

        $givenMoney = $this->agentPayment->where('agent_id',$agentId)->findAll();
        $givenTotalMoney = array_sum(array_column($givenMoney, 'amount'));
        $agentIncomeTotal = array_sum(array_column($allTranSaction, 'income'));
        $agentExpenseTotal = array_sum(array_column($allTranSaction, 'expense'));
        $totalMoney = $agentIncomeTotal - $agentExpenseTotal;
        $dueMoney = $totalMoney - $givenTotalMoney;
        $data['givenMoney'] = $givenTotalMoney;
        $data['totalMoney'] = $totalMoney;
        $data['dueMoney'] =  $dueMoney;

        $startData = $this->request->getVar('start_date');
		$endDate = $this->request->getVar('end_date');
		$fromDate = $startData; //$this->request->getVar('start_date');
		$toDate = $endDate; //$this->request->getVar('end_date');

        $agetntPay = $this->agentPayment->select('agents.id as agentId,agents.*,payagents.*, companies.name AS company_name')
						->join('agents', 'agents.id = payagents.agent_id','left')
                        ->join('companies', 'companies.id = payagents.company_id','left')
                        ->where('payagents.agent_id',$agentId)
						->where('DATE(payagents.created_at) >=', $fromDate)->where('DATE(payagents.created_at) <=', $toDate)
						->findAll();


        $data['pageheading'] = lang("Localize.transaction_list");

		$data['module'] =    lang("Localize.account") ; 
		$data['title']  =    lang("Localize.agent_payment") ;

        $data['agentid'] =  $agentId;
        $data['payagent'] = $this->enrichPayagentRows($agetntPay);
		echo view($this->Viewpath . '\payagent/singleagent',$data);
    }

    /**
     * Geidea / gateway wallet top-ups store payment reference as a UUID in transaction_id (not a ticket booking_id).
     */
    private function isMerchantPaymentReference(string $transactionId): bool
    {
        $transactionId = trim($transactionId);

        return $transactionId !== '' && (bool) preg_match(
            '/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i',
            $transactionId
        );
    }

    private function enrichPayagentRows(array $rows): array
    {
        foreach ($rows as $row) {
            $bookingId = trim((string) ($row->transaction_id ?? ''));
            $companyId = (int) ($row->company_id ?? 0);
            $isMerchantRef = $this->isMerchantPaymentReference($bookingId);

            if (!$isMerchantRef && $companyId <= 0 && $bookingId !== '') {
                $ticketCompany = $this->db->table('tickets')
                    ->select('trips.company_id, companies.name AS company_name')
                    ->join('trips', 'trips.id = tickets.trip_id', 'left')
                    ->join('companies', 'companies.id = trips.company_id', 'left')
                    ->where('tickets.booking_id', $bookingId)
                    ->get()
                    ->getRow();

                if ($ticketCompany) {
                    $companyId = (int) ($ticketCompany->company_id ?? 0);
                    $row->company_id = $companyId;
                    $row->company_name = $ticketCompany->company_name ?? ($row->company_name ?? '');
                }
            }

            if ($isMerchantRef) {
                $row->cancel_amount = null;
                $sessionId = $bookingId;
                $resolvedMerchant = trim((string) ($row->merchant_reference_id ?? ''));
                if ($resolvedMerchant === '') {
                    $pg = $this->db->table('paystatusgeidea')
                        ->select('merchant_id')
                        ->where('sessionId', $sessionId)
                        ->orderBy('id', 'DESC')
                        ->limit(1)
                        ->get()
                        ->getRow();
                    if ($pg && trim((string) ($pg->merchant_id ?? '')) !== '') {
                        $resolvedMerchant = trim((string) $pg->merchant_id);
                    }
                }
                // transaction_id = Geidea session UUID; merchant_reference_id = order ref (order…)
                $row->reference_display = $resolvedMerchant !== '' ? $resolvedMerchant : $sessionId;
                $row->detail = 'recharge balance (' . ($resolvedMerchant !== '' ? $resolvedMerchant : $sessionId) . ')';
            } elseif ($bookingId !== '') {
                $cancel = $this->db->table('cancels')
                    ->select('cancel_fee')
                    ->where('booking_id', $bookingId)
                    ->orderBy('id', 'DESC')
                    ->get()
                    ->getRow();

                $refund = $this->db->table('refunds')
                    ->select('refund_fee')
                    ->where('booking_id', $bookingId)
                    ->orderBy('id', 'DESC')
                    ->get()
                    ->getRow();

                $hasCancelOrRefund = ($cancel !== null) || ($refund !== null);
                $cancelAmount = $cancel->cancel_fee ?? $refund->refund_fee ?? null;
                $row->cancel_amount = $cancelAmount;

                if (empty($row->detail)) {
                    if ($hasCancelOrRefund) {
                        $row->detail = 'Cancelation (' . $bookingId . ')';
                        if ($cancelAmount !== null && $cancelAmount !== '') {
                            $row->detail .= ' Fee Amount: ' . $cancelAmount;
                        }
                    } else {
                        $row->detail = lang('Localize.ticket_booking') . ' (' . $bookingId . ')';
                    }
                } elseif (!$hasCancelOrRefund && preg_match('/^\s*Cancelation\s*\(/i', (string) $row->detail)) {
                    $row->detail = lang('Localize.ticket_booking') . ' (' . $bookingId . ')';
                }
            } else {
                $row->cancel_amount = null;
            }

            if ($companyId > 0 && (int) ($row->status ?? 0) === 1) {
                $balance = $this->db->table('payagents p')
                    ->select('SUM(CAST(p.amount AS DECIMAL(10,2))) AS total_balance')
                    ->join('tickets t', 't.booking_id = p.transaction_id', 'left')
                    ->join('trips tr', 'tr.id = t.trip_id', 'left')
                    ->where('p.agent_id', (int) ($row->agent_id ?? 0))
                    ->where('p.status', 1)
                    ->where('p.deleted_at IS NULL', null, false)
                    ->where('p.id <=', (int) ($row->id ?? 0))
                    ->groupStart()
                        ->where('p.company_id', $companyId)
                        ->orGroupStart()
                            ->where('p.company_id', 0)
                            ->where('tr.company_id', $companyId)
                        ->groupEnd()
                    ->groupEnd()
                    ->get()
                    ->getRow();

                $row->total_balance = $balance->total_balance ?? $row->total_balance;
            }
        }

        return $rows;
    }

    private function getResolvedCompanyBalances(int $agentId): array
    {
        $rows = $this->db->table('payagents p')
            ->select('p.company_id, p.transaction_id, p.amount, direct_company.name AS direct_company_name, ticket_company.id AS ticket_company_id, ticket_company.name AS ticket_company_name')
            ->join('companies direct_company', 'direct_company.id = p.company_id', 'left')
            ->join('tickets t', 't.booking_id = p.transaction_id', 'left')
            ->join('trips tr', 'tr.id = t.trip_id', 'left')
            ->join('companies ticket_company', 'ticket_company.id = tr.company_id', 'left')
            ->where('p.agent_id', $agentId)
            ->where('p.status', 1)
            ->where('p.deleted_at IS NULL', null, false)
            ->get()
            ->getResult();

        $balances = [];
        foreach ($rows as $row) {
            $companyId = (int) ($row->company_id ?? 0);
            $companyName = $row->direct_company_name ?? '';

            if ($companyId <= 0 && !empty($row->ticket_company_id)) {
                $companyId = (int) $row->ticket_company_id;
                $companyName = $row->ticket_company_name ?? '';
            }

            if ($companyId <= 0 || $companyName === '') {
                continue;
            }

            if (!isset($balances[$companyName])) {
                $balances[$companyName] = 0;
            }

            $balances[$companyName] += (float) ($row->amount ?? 0);
        }

        return $balances;
    }





}
