<?php

use Modules\Account\Models\PayagentModel;
use Modules\Agent\Models\AgentModel;
use Modules\Agent\Models\Agentcommission;
use Modules\Agent\Models\AgenttotalModel;

 function agentCommission($totalprice,$agent_id)
    {
        $agentModel = new AgentModel();
        $userId = $agent_id;
        $agetnDetail =  $agentModel->where('user_id',$userId)->first();
        (double)$commission = (double)(($totalprice)* ($agetnDetail->commission/100));
        return $commission;

    }


    function agentIncomeCommission($agent_id,$totalprice,$rand,$subtripid,$passanger_id,$message, $companyId=0)
    {
        (double) $commission =  agentCommission($totalprice, $agent_id);
        $agentModel = new AgentModel();
        $agentcommissionModel = new Agentcommission();
        $payAgentModel = new PayagentModel();
        $currentdate = egypt_today();
        $agentid = $agent_id;
        $agetnDetail =  $agentModel->where('user_id', $agentid )->first();

        $agentcommission = array(
            "booking_id" => $rand,
            "subtrip_id" => $subtripid,
            "agent_id" => $agetnDetail->id,
            "user_id" => $passanger_id,  
            "grandtotal" => $totalprice,
            "commission" => $commission,
            "rate" => $agetnDetail->commission,
            "detail" => $message,
            "date" => $currentdate,
         );

         $payAgent = array(   
            "agent_id" => $agetnDetail->id,
            "amount" => $commission,
            "status" => 1,
            "approved_id" => session()->get('user_id'),
            "company_id" => $companyId,
            "transaction_id" => $rand,
         );

         // Get the last per-company balance for this agent+company
         $lastCompanyRecord = $payAgentModel
             ->select('total_balance')
             ->where('agent_id', $agetnDetail->id)
             ->where('company_id', $companyId)
             ->where('status', 1)
             ->orderBy('id', 'DESC')
             ->first();
         $currentCompanyBalance = $lastCompanyRecord ? (float)$lastCompanyRecord->total_balance : 0;
         $payAgent['total_balance'] = $currentCompanyBalance + $commission;

         $data['result'] =  $agentcommissionModel->insert($agentcommission);
         $data['payAgentResult'] =  $payAgentModel->insert($payAgent);

        $agentModel = new AgentModel();
        $agent = $agentModel
            ->select('id, wallet')
            ->where('id', $agetnDetail->id)
            ->first();

        if ($agent) {
            $newWallet = $agent->wallet + $commission;

            if ($newWallet >= 0) {
                $agentModel
                    ->where('id', $agetnDetail->id)
                    ->set(['wallet' => $newWallet])
                    ->update();
            }
        }

        return $data;

    }

    function agentExpenseTicketCharge($agent_id,$totalprice,$rand,$subtripid,$passanger_id,$message,$companyId=0)
    {
        $payAgentModel = new PayagentModel();
         $payAgent = array(   
            "agent_id" => $agent_id,
            "amount" => -abs($totalprice),
            "status" => 1,
            // "approved_id" => 1,
            "company_id" => $companyId,
            "transaction_id" => $rand,
         );

        // Get the last per-company balance for this agent+company
        $lastCompanyRecord = $payAgentModel
            ->select('total_balance')
            ->where('agent_id', $agent_id)
            ->where('company_id', $companyId)
            ->where('status', 1)
            ->orderBy('id', 'DESC')
            ->first();
        $currentCompanyBalance = $lastCompanyRecord ? (float)$lastCompanyRecord->total_balance : 0;
        $payAgent['total_balance'] = $currentCompanyBalance - $totalprice;

        $data['payAgentResult'] =  $payAgentModel->insert($payAgent);

        $agentModel = new AgentModel();
        $agent = $agentModel
            ->select('id, wallet')
            ->where('id', $agent_id)
            ->first();

        if ($agent) {
            $newWallet = $agent->wallet - $totalprice;

            if ($newWallet >= 0) {
                $agentModel
                    ->where('id', $agent_id)
                    ->set(['wallet' => $newWallet])
                    ->update();
            }
        }

        return $data;

    }
    
    function agentTotal($agent_id,$totalAmount,$rand,$type,$payment_detail_rocord)
    {
        $agentModel = new AgentModel();
        $agentTotalModel = new AgenttotalModel();

        $agentid = $agent_id;
        $agetnDetail =  $agentModel->where('user_id', $agentid )->first();

        if($type == "income")
        {
            $agentTotal = array(
                "agent_id" =>$agetnDetail->id, 
                "booking_id" => $rand,
                "income" => $totalAmount,
                "expense" => 0,  
                "detail" => $payment_detail_rocord,
                
             );

        }
        elseif($type == "expense")
        {

            $agentTotal = array(
                "agent_id" =>$agetnDetail->id, 
                "booking_id" => $rand,
                "income" => 0,
                "expense" => $totalAmount, 
                "detail" => $payment_detail_rocord,
                
             );

        }

        

        $result =  $agentTotalModel->insert($agentTotal);

        return $result;

    }



    function agentTotalNormal($agent_id,$totalAmount,$type,$payment_detail_rocord)
    {
        $agentModel = new AgentModel();
        $agentTotalModel = new AgenttotalModel();

        $agentid = $agent_id;
        $agetnDetail =  $agentModel->where('user_id', $agentid )->first();
        $agentTotal = array();

        if($type == "income")
        {
            $agentTotal = array(
                "agent_id" =>$agetnDetail->id, 
                // "booking_id" =>null ,
                "income" => $totalAmount,
                "expense" => 0,  
                "detail" => $payment_detail_rocord,
                
             );

        }
        elseif($type == "expense")
        {

            $agentTotal = array(
                "agent_id" =>$agetnDetail->id, 
                // "booking_id" =>null,
                "income" => 0,
                "expense" => $totalAmount, 
                "detail" => $payment_detail_rocord,
                
             );

        }
        
        
        $result =  $agentTotalModel->insert($agentTotal);

        return $result;

    }

    function agentRefundTicket($agent_user_id, $refundAmount, $booking_id, $detail, $companyId = 0)
    {
        $agentModel = new \Modules\Agent\Models\AgentModel();
        $payAgentModel = new \Modules\Account\Models\PayagentModel();
        
        $agetnDetail = $agentModel->where('user_id', $agent_user_id)->first();
        if (!$agetnDetail) {
            return false;
        }

        if ((int) $companyId <= 0 && !empty($booking_id)) {
            $db = \Config\Database::connect();
            $ticketCompany = $db->table('tickets')
                ->select('trips.company_id')
                ->join('trips', 'trips.id = tickets.trip_id', 'left')
                ->where('tickets.booking_id', $booking_id)
                ->get()
                ->getRow();

            $companyId = (int) ($ticketCompany->company_id ?? 0);
        }

        // 1. Update payagents table (for the transaction list)
        // Get the last per-company balance for this agent+company
        $lastCompanyRecord = $payAgentModel
            ->select('total_balance')
            ->where('agent_id', $agetnDetail->id)
            ->where('company_id', $companyId)
            ->where('status', 1)
            ->orderBy('id', 'DESC')
            ->first();
        $currentCompanyBalance = $lastCompanyRecord ? (float)$lastCompanyRecord->total_balance : 0;
        
        $payAgent = array(   
            "agent_id" => $agetnDetail->id,
            "amount" => $refundAmount,
            "status" => 1,
            "approved_id" => session()->get('user_id'),
            "company_id" => $companyId,
            "transaction_id" => $booking_id,
            "detail" => $detail,
            "total_balance" => $currentCompanyBalance + $refundAmount,
        );
        $payAgentModel->insert($payAgent);

        // 2. Update agent's global wallet
        $newWallet = $agetnDetail->wallet + $refundAmount;
        $agentModel
            ->where('id', $agetnDetail->id)
            ->set(['wallet' => $newWallet])
            ->update();

        // 3. Record in agenttotals (for the dashboard/overview)
        $agentTotalModel = new \Modules\Agent\Models\AgenttotalModel();
        $agentTotal = array(
            "agent_id" => $agetnDetail->id, 
            "booking_id" => $booking_id,
            "income" => $refundAmount,
            "expense" => 0,  
            "detail" => $detail,
        );
        $agentTotalModel->insert($agentTotal);

        return true;
    }

?>
