<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Auth;
use App\User;
use App\model\Leadclient;
use App\model\Leadclientcalculation;
use Illuminate\Support\Facades\Session;
use Illuminate\Support\Facades\DB;
use Illuminate\Pagination\LengthAwarePaginator;
use App\Http\Controllers\AgentincomeController;
use App\Http\Controllers\DistributordashboardController;

// Include helper functions
require_once app_path('Helper/helper.php');

class UnifiedIncomeController extends Controller
{
    public function __construct()
    {
        $this->middleware('auth');
    }

    public function index(Request $request)
    {
        $id = Auth::user()->id; 
        $user_role = Auth::user()->user_role;
        
        // Set default active tab based on user role
        $active_tab = $request->get('tab', 'admin');
        if($active_tab == 'admin' && ($user_role != 1 && $user_role != 2)) {
            if($user_role == 3) {
                $active_tab = 'agent';
            } elseif($user_role == 4) {
                $active_tab = 'ar';
            } elseif(Auth::user()->manage_manager == 1) {
                $active_tab = 'team';
            } elseif(Auth::user()->manage_distributor == 1) {
                $active_tab = 'distributor';
            }
        }
        
        // Initialize data array
        $data = [
            'active_tab' => $active_tab,
            'user_role' => $user_role,
            'user_id' => $id,
            'admin_data' => null,
            'agent_data' => null,
            'ar_data' => null,
            'team_data' => null,
            'show_agent_list' => 0,
            'useraragents' => collect(),
            'managers' => collect(),
        ];

        // Get user agents based on role for admin income
        if($user_role == 1) { // SUPERADMIN
            $data['useraragents'] = User::where('user_role', '=', 2)
                ->where('status', '=', 1)
                ->orderBy('name', 'ASC')
                ->get();
            $data['show_agent_list'] = 1;
        } elseif($user_role == 2) { // ADMIN
            $data['useraragents'] = User::where('user_role', '=', 2)
                ->where('id', '=', $id)
                ->where('status', '=', 1)
                ->orderBy('name', 'ASC')
                ->get();
        } else {
            $data['useraragents'] = User::where('id', '=', $id)
                ->where('status', '=', 1)
                ->orderBy('name', 'ASC')
                ->get();
        }

        // Get agents for agent income tab (same logic as AgentincomeController@index)
        $data['agent_income_agents'] = collect();
        $data['show_agent_dropdown'] = 0; // Show dropdown only for SUPERADMIN (1) or ADMIN (2)
        
        if($user_role == 1) { // SUPERADMIN
            $data['agent_income_agents'] = User::where('user_role', '=', 3)
                ->orderBy('name', 'ASC')
                ->get();
            $data['show_agent_dropdown'] = 1;
        } elseif($user_role == 2) { // ADMIN
            $data['agent_income_agents'] = User::where('user_role', '=', 3)
                ->where('create_by_user', '=', $id)
                ->orderBy('name', 'ASC')
                ->get();
            $data['show_agent_dropdown'] = 1;
        } elseif($user_role == 4) { // ARUSER
            $data['agent_income_agents'] = User::where('user_role', '=', 3)
                ->where('assign_to_ar', '=', $id)
                ->orderBy('name', 'ASC')
                ->get();
            $data['show_agent_dropdown'] = 1;
        } else {
            // AGENT (role 3) - no dropdown, just show their own data
            $data['agent_income_agents'] = User::where('user_role', '=', 3)
                ->where('id', '=', $id)
                ->orderBy('name', 'ASC')
                ->get();
            $data['show_agent_dropdown'] = 0;
        }

        // Get managers for team income (same logic as UserController@teamIncome)
        $data['managers'] = collect();
        if($user_role == 1) {
            $data['managers'] = User::where('manage_manager', 1)->get();
        } elseif($user_role == 2) {
            $data['managers'] = User::where([['company', Auth::user()->company], ['manage_manager', 1]])->get();
        } elseif(Auth::user()->manage_manager == 1) {
            // For managers themselves, show their own data
            $data['managers'] = User::where('id', $id)->get();
        }

        // Get distributors for distributor income (same logic as DistributordashboardController@distributorIncome)
        $data['distributors'] = collect();
        if($user_role == 1) { // SUPERADMIN
            $data['distributors'] = User::where('user_role','=',3)
                ->where('manage_distributor','=',1)
                ->where('status','=',1)
                ->get();
        } elseif($user_role == 2) { // ADMIN
            $data['distributors'] = User::where('user_role','=',3)
                ->where('manage_distributor','=',1)
                ->where('status','=',1)
                ->where('create_by_user','=',$id)
                ->get();
        } elseif($user_role == 4) { // ARUSER
            $data['distributors'] = User::where('user_role','=',3)
                ->where('manage_distributor','=',1)
                ->where('status','=',1)
                ->where('assign_by_user','=',$id)
                ->get();
        } elseif($user_role == 3 && Auth::user()->manage_distributor == 1) {
            // For distributors themselves
            $data['distributors'] = User::where('id', $id)->get();
        }
        
        // Get agents for distributor income (will be populated based on selected distributor)
        $data['distributor_agents'] = collect();
        $data['show_distributor_dropdown'] = 0;
        $data['show_agent_dropdown'] = 0;
        
        if($user_role == 1 || $user_role == 2) {
            $data['show_distributor_dropdown'] = 1;
            $data['show_agent_dropdown'] = 1;
        } elseif($user_role == 4) {
            $data['show_distributor_dropdown'] = 1;
            $data['show_agent_dropdown'] = 1;
        } elseif($user_role == 3 && Auth::user()->manage_distributor == 1) {
            // Distributor viewing their own data - no dropdowns needed
            $data['show_distributor_dropdown'] = 0;
            $data['show_agent_dropdown'] = 0;
        }
        
        // Get AR users for AR income tab (same logic as AgentincomeController@arincome)
        $data['ar_income_users'] = collect();
        $data['show_ar_dropdown'] = 0; // Show dropdown only for SUPERADMIN (1) or ADMIN (2)
        
        if($user_role == 1) { // SUPERADMIN
            $data['ar_income_users'] = User::where('user_role', '=', 4)
                ->where('status', '=', 1)
                ->orderBy('name', 'ASC')
                ->get();
            $data['show_ar_dropdown'] = 1;
        } elseif($user_role == 2) { // ADMIN
            $data['ar_income_users'] = User::where('user_role', '=', 4)
                ->where('create_by_user', '=', $id)
                ->orderBy('name', 'ASC')
                ->get();
            $data['show_ar_dropdown'] = 1;
        } else {
            // ARUSER (role 4) - no dropdown, just show their own data
            $data['ar_income_users'] = User::where('user_role', '=', 4)
                ->where('id', '=', $id)
                ->where('status', '=', 1)
                ->orderBy('name', 'ASC')
                ->get();
            $data['show_ar_dropdown'] = 0;
        }

        return view('agentincome.unified_dashboard', compact('data'));
    }

    public function getIncomeData(Request $request)
    {
        $tab = $request->get('tab', 'admin');
        $id = Auth::user()->id; 
        $user_role = Auth::user()->user_role;
        
        switch($tab) {
            case 'admin':
                return $this->getAdminIncomeData($request);
            case 'agent':
                return $this->getAgentIncomeData($request);
            case 'ar':
                return $this->getArIncomeData($request);
            case 'team':
                return $this->getTeamIncomeData($request);
            case 'distributor':
                return $this->getDistributorIncomeData($request);
            default:
                return response()->json(['error' => 'Invalid tab'], 400);
        }
    }

    private function getAdminIncomeData(Request $request)
    {
        // Use income_list method to get all data in DataTables format
        // This will return all records formatted for client-side DataTables
        $agentIncomeController = new AgentincomeController();
        
        // Set $_REQUEST parameters that income_list expects (it uses $_REQUEST directly)
        $_REQUEST['draw'] = 1;
        $_REQUEST['start'] = 0;
        $_REQUEST['length'] = 999999; // Get all records
        $_REQUEST['order'] = [['column' => 0, 'dir' => 'desc']];
        $_REQUEST['search'] = ['value' => '', 'regex' => false];
        $_REQUEST['columns'] = [
            ['data' => 0, 'name' => '', 'searchable' => true, 'orderable' => true, 'search' => ['value' => '', 'regex' => false]],
            ['data' => 1, 'name' => '', 'searchable' => true, 'orderable' => true, 'search' => ['value' => '', 'regex' => false]],
            ['data' => 2, 'name' => '', 'searchable' => true, 'orderable' => false, 'search' => ['value' => '', 'regex' => false]],
            ['data' => 3, 'name' => '', 'searchable' => true, 'orderable' => true, 'search' => ['value' => '', 'regex' => false]],
            ['data' => 4, 'name' => '', 'searchable' => true, 'orderable' => false, 'search' => ['value' => '', 'regex' => false]],
            ['data' => 5, 'name' => '', 'searchable' => true, 'orderable' => true, 'search' => ['value' => '', 'regex' => false]],
            ['data' => 6, 'name' => '', 'searchable' => true, 'orderable' => false, 'search' => ['value' => '', 'regex' => false]],
            ['data' => 7, 'name' => '', 'searchable' => true, 'orderable' => false, 'search' => ['value' => '', 'regex' => false]],
            ['data' => 8, 'name' => '', 'searchable' => true, 'orderable' => false, 'search' => ['value' => '', 'regex' => false]],
            ['data' => 9, 'name' => '', 'searchable' => true, 'orderable' => true, 'search' => ['value' => '', 'regex' => false]]
        ];
        $_REQUEST['income'] = 'all';
        $_REQUEST['income_url'] = 'adminincome';
        $_REQUEST['reseturl'] = 'adminincome';
        $_REQUEST['search_start_date'] = $request->get('search_start_date', '');
        $_REQUEST['search_end_date'] = $request->get('search_end_date', '');
        $_REQUEST['client_name'] = $request->get('client_name', '');
        $_REQUEST['client_id'] = $request->get('client_id', '');
        
        // Call income_list which returns DataTables format with all data
        return $agentIncomeController->income_list();
    }

    private function getAgentIncomeData(Request $request)
    {
        // Copy of AgentincomeController@index function logic
        // Returns data in DataTables format for client-side processing
        return $this->getAgentIncomeDataFromIndex($request);
    }
    
    /**
     * Private function - Copy of AgentincomeController@index
     * Returns agent income data in DataTables format for client-side processing
     */
    private function getAgentIncomeDataFromIndex(Request $request)
    {
        $id = Auth::user()->id; 
        $user_role = Auth::user()->user_role;
        $items = 999999; // Get all records for client-side processing
        
        $sort = isset($request->sort) ? $request->sort : 'id';
        $direction = isset($request->direction) ? $request->direction : 'DESC';
        
        $role_for = "AGENT";
        Session::put('role_for', $role_for);

        $leadclients = Leadclient::join('users', 'users.id', '=', 'lead_client.agent_id')
            ->leftjoin('lead_status_history', 'lead_status_history.lead_id', 'lead_client.id')
            ->select('lead_client.*', 'users.name', 'users.last_name', 'lead_status_history.date as paid_date');

        $leadclientstotal = Leadclient::join('users', 'users.id', '=', 'lead_client.agent_id')
            ->leftjoin('lead_status_history', 'lead_status_history.lead_id', 'lead_client.id')
            ->select('lead_client.*', 'users.name', 'users.last_name');

        $useraragent = '';
        // Use same logic as AgentincomeController@index
        if($user_role == 1) { // SUPERADMIN
            $useraragent = User::where('user_role', '=', 3)
                ->orderBy('name', 'ASC')
                ->get();
        } else if($user_role == 4) { // ARUSER
            $useraragent = User::where('user_role', '=', 3)
                ->where('assign_to_ar', '=', $id)
                ->orderBy('name', 'ASC')
                ->get();
        } elseif ($user_role == 2) { // ADMIN
            $admin_id = Auth::User()->id;
            $useraragent = User::where('user_role', '=', 3)
                ->where('create_by_user', '=', $admin_id)
                ->orderBy('name', 'ASC')
                ->get();
        } else {
            // AGENT role
            $useraragent = User::where('user_role', '=', 3)
                ->where('id', '=', $id)
                ->orderBy('name', 'ASC')
                ->get();
        }

        // Handle agent selection from request or session
        if($request->filled('agent_id')) {
            Session::put('aragentsearch', $request->agent_id);
        } elseif(session('aragentsearch') == '') {
        $firstuser = $useraragent->first(); 
            if(!empty($firstuser) && $firstuser->id != '') {
                Session::put('aragentsearch', $firstuser->id);
            } else {
                Session::put('aragentsearch', 0);
            }
        } else if(session('aragentsearch') && Auth::user()->user_role == 3 && Auth::user()->id != session('aragentsearch')) {
            $firstuser = $useraragent->first();
            if(!empty($firstuser) && $firstuser->id != '') {
                Session::put('aragentsearch', $firstuser->id);
            } else {
                Session::put('aragentsearch', 0);
            }
        }

        $agent_id = session('aragentsearch');
        
        // If no agent selected and user is SUPERADMIN/ADMIN, return empty
        if(($user_role == 1 || $user_role == 2) && (empty($agent_id) || $agent_id == 0)) {
            return response()->json([
                'draw' => 1,
                'recordsTotal' => 0,
                'recordsFiltered' => 0,
                'data' => [],
                'total_data' => [
                    'outstanding' => '$0.00',
                    'gross_revenue' => '$0.00',
                    'agent_income' => '$0.00'
                ]
            ]);
        }
        
        $leadclients = $leadclients->where('agent_id', '=', $agent_id);
        $leadclientstotal = $leadclientstotal->where('agent_id', '=', $agent_id);
        
        $search_start_date = '';
        $search_end_date = '';
        $searchform = $request->input('search_agent');
        
        if(isset($searchform) || $request->filled('search_start_date') || $request->filled('search_end_date')) {
            $statusarry = ['Invoiced', 'Pay Received', 'Paid Out', 'Sold', 'Sale Closing', 'Lease Confirmed', 'MIC', '9', '12', '13', '14', '11', '10', '21', 'Past Due'];
            
            $client_name = $request->input('client_name', '');
            $client_id = $request->input('client_id', '');
            
            if($client_name != '') {
            $arr = explode(" ", $client_name);
            $c_fname = $arr[0] ?? '';
            $c_lname = $arr[1] ?? '';
            
            if($c_fname != '') {
                $leadclients = $leadclients->where('lead_client.fname', $c_fname);
                $leadclientstotal = $leadclientstotal->where('lead_client.fname', $c_fname);
            }
            if($c_lname != '') {
                $leadclients = $leadclients->where('lead_client.lname', $c_lname);
                $leadclientstotal = $leadclientstotal->where('lead_client.lname', $c_lname);
            }
        }

            if($client_id != '') {
                $leadclients = $leadclients->where('lead_client.id', $client_id);
                $leadclientstotal = $leadclientstotal->where('lead_client.id', $client_id);
            }
            
            $search_start_date = setdbdate($request->input('search_start_date', ''));
            $search_end_date = setdbdate($request->input('search_end_date', ''));
            
            if($search_start_date != '' && $search_end_date != '') {
                $leadclients = $leadclients->whereBetween('lead_status_history.date', [$search_start_date, $search_end_date]);
                $leadclientstotal = $leadclientstotal->whereIn('lead_client.curr_status', $statusarry);
                $leadclientstotal = $leadclientstotal->whereBetween('lead_status_history.date', [$search_start_date, $search_end_date]);
            }
            
            $leadclients = $leadclients->whereIn('lead_status_history.status', $statusarry);
        } else {
            $statusarry = ['Invoiced', 'Pay Received', 'Paid Out', 'Collections', 'Sold', 'Sale Closing', 'Lease Confirmed', 'MIC', '9', '12', '13', '14', '11', '10', '23', '22', '21', 'Past Due'];
            $statusarry123 = ['Invoiced', 'Pay Received', 'Paid Out', 'Sold', 'Sale Closing', 'Lease Confirmed', 'MIC', 'Collections', '9', '12', '13', '14', '11', '10', '23', '22', '21', 'Past Due'];
            
            $leadclients = $leadclients->whereIn('lead_client.curr_status', $statusarry);
            $leadclientstotal = $leadclientstotal->whereIn('lead_client.curr_status', $statusarry123);
        }
        
        $leadclients = $leadclients->selectSub(function ($query) {
            $query->select('date')
                ->from('lead_status_history')
                ->where('status', '=', 'Paid Out')
                ->whereColumn('lead_id', '=', 'lead_client.id')
                ->orderByRaw('id desc')
                ->limit(1);
        }, 'paid_out_date');
        
        if($sort === 'inv_date') {
            $leadclientsall = $leadclients->orderBy('paid_out_date', $direction)->groupBy('lead_client.id')->get();
            $leadclients = $leadclients->orderBy('paid_out_date', $direction)->groupBy('lead_client.id')->get();
        } else {
            $leadclientsall = $leadclients
                ->orderby('lead_client.' . $sort, $direction)
                ->groupBy('lead_client.id')
                ->get();
            
            $leadclients = $leadclients
                ->orderby('lead_client.' . $sort, $direction)
                ->groupBy('lead_client.id')
                ->get();
        }
        
        $statusarry123 = ['Invoiced', 'Sold', 'Sale Closing', 'Lease Confirmed', 'MIC', 'Collections', '9', '12', '13', '14', '11', '10', '23', '22', '21', 'Past Due'];
        
        $leadclientstotal = $leadclientstotal->whereIn('curr_status', $statusarry123)
            ->orderby('lead_client.' . $sort, $direction)
            ->groupBy('lead_client.id')
                ->get();
        
        $outsatnginamt = 0;
        foreach($leadclientstotal as $valuetotal) {
            $caculation = AgentincomeController::getcalculation($valuetotal->id);
            if(!empty($caculation)) {
                $newres_comm = (float)$caculation['paidamount'];
        } else {
                $newres_comm = 0;
            }
            $outsatnginamt += $newres_comm;
        }
        
        $total_incoe = array();
        foreach($leadclientsall as $leadclient) {
            $leadcalculation = lead_calculate($leadclient->id);
            array_push($total_incoe, $leadcalculation['agent_paid']);
        }
        
        $income_detail = get_income_calculation_admin(json_decode(json_encode($leadclientsall), true), 'agentincome');
        
        // Format data for DataTables (client-side processing)
        $datas = array();
        foreach($leadclientsall as $row) {
            $nestedData = array();
            
            $client = '<a href="' . url('/') . '/editclientlead/' . $row->id . '/1" target="_blank">#' . $row->id . '</a>';
            $name = ucfirst($row->fname) . ' ' . ucfirst($row->lname);
            
            $paid_out = $row->paid_out_date ?? '';
            if($paid_out == '01/01/1970' || $paid_out == '01-01-1970') {
                $paid_out = '';
            }
            
            $lead_calculate = lead_calculate($row->id);
            $agentIncomeController = new AgentincomeController();
            $deduction = $agentIncomeController->deduction($lead_calculate, $row->id);
            
            if(is_numeric($row->curr_status)) {
                $status = set_status_name($row->curr_status);
            } else {
                $status = set_status_name($row->curr_status);
            }
            
            $dates = payout_payreceived_date($row->status_history);
            
            $nestedData[] = $client;
            $nestedData[] = $name;
            $nestedData[] = ($row->invoiced_total != 0) ? '$' . number_format($row->invoiced_total, 2) : (($lead_calculate['invoiced_total'] != 0) ? '$' . number_format($lead_calculate['invoiced_total'], 2) : '$0.00');
            $nestedData[] = '$' . number_format($row->payment, 2);
            $nestedData[] = (!empty($dates['paid_rec']) ? $dates['paid_rec'] : '');
            $nestedData[] = (!empty($status) ? $status : '');
            $nestedData[] = $deduction['string'];
            $nestedData[] = '$' . number_format($lead_calculate['agent_paid'], 2);
            $nestedData[] = (!empty($dates['paid_out']) ? $dates['paid_out'] : '');
            
            $datas[] = $nestedData;
        }

        return response()->json([
            'draw' => 1,
            'recordsTotal' => count($leadclientsall),
            'recordsFiltered' => count($leadclientsall),
            'data' => $datas,
            'total_data' => [
                'outstanding' => $income_detail['outstanding'] ?? '$0.00',
                'gross_revenue' => $income_detail['gross_revenue'] ?? '$0.00',
                'agent_income' => $income_detail['agent_income'] ?? '$0.00'
            ]
        ]);
    }

    private function getArIncomeData(Request $request)
    {
        // Copy of AgentincomeController@arincome function logic
        // Returns data in DataTables format for client-side processing
        return $this->getArIncomeDataFromArincome($request);
    }
    
    /**
     * Private function - Exact copy of AgentincomeController@arincome
     * Returns AR income data in DataTables format for client-side processing
     */
    private function getArIncomeDataFromArincome(Request $request)
    {
        // EXACT COPY OF AgentincomeController@arincome function
        $id = Auth::user()->id; 
        $user_role = Auth::user()->user_role;
        $role_for = "ARUSER";
        $items = $request->items ?? 25;
        
        unset($request->ids);
        
        $sort = isset($request->sort) ? $request->sort : 'id';
        $direction = isset($request->direction) ? $request->direction : 'DESC';

        Session::put('role_for', $role_for);
        
        if(!empty($request->input('get_invoices_count')) && $request->input('get_invoices_count') == 'getInvoiceCount'){
        $leadclients = Leadclient::join('users', 'users.id', '=', 'lead_client.agent_id')
                ->join('lead_status_history', 'lead_status_history.lead_id', 'lead_client.id')
                ->select('lead_client.*', 'users.name', 'users.last_name', DB::raw('MAX(`lead_status_history`.`date`) as `paid_date`'));
        } else {
            $leadclients = Leadclient::join('users', 'users.id', '=', 'lead_client.agent_id')
                ->join('lead_status_history', 'lead_status_history.lead_id', 'lead_client.id')
                ->select('lead_client.*', 'users.name', 'users.last_name', 'lead_status_history.date as paid_date');
        }

        $leadclientstotal = Leadclient::join('users', 'users.id', '=', 'lead_client.agent_id')
            ->leftjoin('lead_status_history', 'lead_status_history.lead_id', 'lead_client.id')
            ->select('lead_client.*', 'users.name', 'users.last_name');

        $useraragent = '';
        $data['show_agent_list'] = 0;
        if($user_role == SUPERADMIN){
            $useraragent = User::where('user_role', '=', ARUSER)
                ->where('status', '=', 1)
                ->orderBy('name', 'ASC')
                ->get();
            $data['show_agent_list'] = 1;
        } elseif($user_role == ADMIN){
            $useraragent = User::where('user_role', '=', 4)
                ->where('users.create_by_user', '=', $id)
                ->orderBy('name', 'ASC')
                ->get();
            $data['show_agent_list'] = 1;
        } else {
            $useraragent = User::where('user_role', '=', ARUSER)
                ->where('id', '=', $id)
                ->where('status', '=', 1)
                ->orderBy('name', 'ASC')
                ->get();
        }

        // Get AR user ID from request parameter (ar_user_id) instead of session
        $ar_user_id = $request->input('ar_user_id', '');
        
        // If no ar_user_id provided, use current user's ID for ARUSER role
        if(empty($ar_user_id) && $user_role == 4) {
            $ar_user_id = $id;
        }
        
        // For SUPERADMIN/ADMIN, if no ar_user_id provided, use first user
        if(empty($ar_user_id) && ($user_role == 1 || $user_role == 2)) {
            $firstuser = $useraragent->first();
            if(!empty($firstuser) && $firstuser->id != ''){
                $ar_user_id = $firstuser->id;
            } else {
                $ar_user_id = 0;
            }
        }
        
        // If no AR user selected and user is SUPERADMIN/ADMIN, return empty
        if(($user_role == 1 || $user_role == 2) && (empty($ar_user_id) || $ar_user_id == 0)) {
            return response()->json([
                'draw' => 1,
                'recordsTotal' => 0,
                'recordsFiltered' => 0,
                'data' => [],
                'total_data' => [
                    'outstanding' => '$0.00',
                    'gross_revenue' => '$0.00',
                    'ar_income' => '$0.00'
                ]
            ]);
        }
        
        $agent_id = $ar_user_id;
        
        $arUser = User::select('id')->where('assign_to_ar', '=', $agent_id);
        
        $leadclients = $leadclients->whereIn('agent_id', function ($query) use ($agent_id) {
            $query->select('id')->from('users')->Where('assign_to_ar', $agent_id);
        });
        
        $leadclientstotal = $leadclientstotal->whereIn('agent_id', function ($query) use ($agent_id) {
            $query->select('id')->from('users')->Where('assign_to_ar', $agent_id);
        });
        
        if(!empty($request->input('get_invoices_count')) && $request->input('get_invoices_count') == 'getInvoiceCount'){
            $leadclients = $leadclients->selectSub(function($query) {
                $query->select(DB::raw('MAX(`date`)'))
                    ->from('lead_status_history')
                    ->whereIn('status', ["'Invoiced','12','Invoice 30','Invoice 60','Invoice 90','Past Due','Payment OTW','Collections','18','19','20','21','22','23'"])
                    ->whereColumn('lead_id', '=', 'lead_client.id')
                    ->orderBy('id', 'asc')
                    ->limit(1);
            }, 'newdate');
            
            $leadclientstotal = $leadclientstotal->selectSub(function($query) {
                $query->select(DB::raw('MAX(`date`)'))
                    ->from('lead_status_history')
                    ->whereIn('status', ['Invoiced', '12', 'Invoice 30', 'Invoice 60', 'Invoice 90', 'Past Due', 'Payment OTW','Collections', '18', '19', '20', '21', '22','23'])
                    ->whereColumn('lead_id', '=', 'lead_client.id')
                    ->orderBy('id', 'asc')
                    ->limit(1);
            }, 'newdate');
        } else {
            $leadclients = $leadclients->selectSub(function($query) {
                $query->select('date')
                    ->from('lead_status_history')
                    ->Where('status', '=', 'Paid Out')
                    ->Where('lead_id', '=', 'lead_client.id')
                    ->orderByRaw('id desc')
                    ->limit(1);
            }, 'newdate');
            
            $leadclientstotal = $leadclientstotal->selectSub(function($query) {
                $query->select('date')
                    ->from('lead_status_history')
                    ->Where('status', '=', 'Paid Out')
                    ->Where('lead_id', '=', 'lead_client.id')
                    ->orderByRaw('id desc')
                    ->limit(1);
            }, 'newdate');
        }
        
        $search_start_date = '';
        $search_end_date = '';
        $searchform = $request->input('search_agent');
        
        if(!empty($searchform) && $searchform == 'submit'){
            $client_name = $request->input('client_name');
            $client_id = $request->input('client_id');
            $arr = explode(" ", $client_name);
            
            @$c_fname = $arr[0];
            @$c_lname = $arr[1];
            
            if($client_name != ''){
                $leadclients = $leadclients->where('lead_client.fname', $c_fname);
                $leadclients = $leadclients->where('lead_client.lname', $c_lname);
                $leadclientstotal = $leadclientstotal->where('lead_client.fname', $c_fname);
                $leadclientstotal = $leadclientstotal->where('lead_client.lname', $c_lname);
            }
            if($client_id != ''){
                $leadclients = $leadclients->where('lead_client.id', $client_id);
                $leadclientstotal = $leadclientstotal->where('lead_client.id', $client_id);
            }
            
            $statusarry = ['Paid Out', '14'];
            $search_start_date = setdbdate($request->input('search_start_date'));
            $search_end_date = setdbdate($request->input('search_end_date'));
            
            if($search_start_date != '' && $search_end_date != ''){
                $leadclients = $leadclients->whereIn('lead_client.curr_status', $statusarry);
                $leadclients = $leadclients->whereBetween('lead_client.newpaid_date', [$search_start_date, $search_end_date]);
                
                $leadclientstotal = $leadclientstotal->whereIn('lead_client.curr_status', $statusarry);
                $leadclientstotal = $leadclientstotal->whereBetween('lead_client.newpaid_date', [$search_start_date, $search_end_date]);
            }
        } elseif(!empty($request->input('get_invoices_count')) && $request->input('get_invoices_count') == 'getInvoiceCount'){
            $statusarry = ['Invoiced', '12', 'Invoice 30', 'Invoice 60', 'Invoice 90', 'Past Due', 'Payment OTW', 'Collections', '18', '19', '20', '21', '22', '23'];
            $search_start_date = setdbdate($request->input('invoice_start_date'));
            $search_end_date = setdbdate($request->input('invoice_end_date'));
            
            if($search_start_date != '' && $search_end_date != ''){
                $leadclients = $leadclients->whereIn('lead_status_history.status', $statusarry);
                $leadclients = $leadclients->whereRaw("`lead_status_history`.`date` BETWEEN '$search_start_date' AND '$search_end_date'");
                $leadclientstotal = $leadclientstotal->whereIn('lead_status_history.status', $statusarry);
                $leadclientstotal = $leadclientstotal->whereRaw("`lead_status_history`.`date` BETWEEN '$search_start_date' AND '$search_end_date'");
            }
        } else {
            $statusarry = ['Sold', 'Invoiced', 'Pay Received', 'MIC', 'Paid Out', 'Collections', '9', '12', '13', '14', '11', '23'];
            $leadclients = $leadclients->whereIn('lead_client.curr_status', $statusarry);
            $leadclientstotal = $leadclientstotal->whereIn('lead_status_history.status', $statusarry);
        }
        
        // Get all records (matching original - gets leadclientsall before pagination)
        $leadclientsall = $leadclients->orderby('lead_client.' . $sort, $direction)
            ->groupBy('lead_client.id')
            ->get();
        
        $leadclientstotal = $leadclientstotal->orderby('lead_client.id', 'DESC')
            ->distinct()
            ->get();
        
        $income_detail = get_income_calculation_admin(json_decode(json_encode($leadclientstotal), true), 'arincome');
        
        // Format data for DataTables (client-side processing)
        $datas = array();
        foreach($leadclientsall as $row) {
            $nestedData = array();
            
            $client = '<a href="' . url('/') . '/editclientlead/' . $row->id . '/1" target="_blank">#' . $row->id . '</a>';
            $name = ucfirst($row->fname) . ' ' . ucfirst($row->lname);
            
            $paid_out = $row->newdate ?? '';
            if($paid_out == '01/01/1970' || $paid_out == '01-01-1970') {
                $paid_out = '';
            }
            
            $lead_calculate = lead_calculate($row->id);
            $agentIncomeController = new AgentincomeController();
            $deduction = $agentIncomeController->deduction($lead_calculate, $row->id);
            $company_income = $agentIncomeController->aroradmin($lead_calculate, 'arincome', $row->id);
            
            if(is_numeric($row->curr_status)) {
                $status = set_status_name($row->curr_status);
            } else {
                $status = set_status_name($row->curr_status);
            }
            
            $dates = payout_payreceived_date($row->status_history);
            
            $nestedData[] = $client;
            $nestedData[] = $name;
            $nestedData[] = ($row->invoiced_total != 0) ? '$' . number_format($row->invoiced_total, 2) : (($lead_calculate['invoiced_total'] != 0) ? '$' . number_format($lead_calculate['invoiced_total'], 2) : '$0.00');
            $nestedData[] = '$' . number_format($row->payment, 2);
            $nestedData[] = (!empty($dates['paid_rec']) ? $dates['paid_rec'] : '');
            $nestedData[] = (!empty($status) ? $status : '');
            $nestedData[] = $deduction['string'];
            $nestedData[] = '$' . number_format($lead_calculate['agent_paid'], 2);
            $nestedData[] = (!empty($company_income) && isset($company_income['string']) ? $company_income['string'] : '$0.00');
            $nestedData[] = (!empty($dates['paid_out']) ? $dates['paid_out'] : '');
            
            $datas[] = $nestedData;
        }

        return response()->json([
            'draw' => 1,
            'recordsTotal' => count($leadclientsall),
            'recordsFiltered' => count($leadclientsall),
            'data' => $datas,
            'total_data' => [
                'outstanding' => $income_detail['outstanding'] ?? '$0.00',
                'gross_revenue' => $income_detail['gross_revenue'] ?? '$0.00',
                'ar_income' => $income_detail['company_income'] ?? '$0.00' // For AR income, company_income is the AR income
            ]
        ]);
    }

    private function getTeamIncomeData(Request $request)
    {
        // Copy of UserController@teamIncome function logic
        // Returns data in DataTables format for client-side processing
        return $this->getTeamIncomeDataFromTeamIncome($request);
    }
    
    /**
     * Private function - Copy of UserController@teamIncome
     * Returns team income data in DataTables format for client-side processing
     */
    private function getTeamIncomeDataFromTeamIncome(Request $request)
    {
        $user_role = Auth::user()->user_role;
        
        // Handle manager selection from request or session
        if($request->filled('select_manager')) {
            $userId = $request->select_manager;
        Session::put('teamsearch', $userId);
        } else {
            // For SUPERADMIN/ADMIN, require manager selection
            if($user_role == 1 || $user_role == 2) {
                $userId = session('teamsearch');
                if(empty($userId)) {
                    return response()->json([
                        'draw' => 1,
                        'recordsTotal' => 0,
                        'recordsFiltered' => 0,
                        'data' => [],
                        'total_data' => [
                            'total_invoiced' => '$0.00',
                            'total_payment' => '$0.00',
                            'team_income' => '$0.00'
                        ]
                    ]);
                }
            } else {
                $userId = auth()->id();
                Session::put('teamsearch', $userId);
            }
        }
        
        $agent_id = session('teamsearch');
        $search_start_date = setdbdate($request->input('search_start_date', ''));
        $search_end_date = setdbdate($request->input('search_end_date', ''));

        $query = Leadclient::where('team_user_id', $userId);

        if ($request->filled('search_start_date') && $request->filled('search_end_date')) {
            $query->whereBetween('inv_date', [$search_start_date, $search_end_date]);
        }

        $sortBy = $request->get('sort_by', 'id');
        $sortOrder = $request->get('sort_order', 'desc');

        if (in_array($sortBy, ['id', 'curr_status'])) {
            $query->orderBy($sortBy, $sortOrder);
        } else {
            $query->orderBy('id', 'desc');
        }

        // Get all records (for client-side processing)
        $userWithLeadClients = $query->get();
        $leadClientsCollection = collect($userWithLeadClients);

        // Initialize lead listing array and total sum variable
        $leadListing = [];
        $totalSum = 0;

        // Iterate through the collection of lead clients
        $leadClientsCollection->each(function ($leadclient) use (&$leadListing, &$totalSum) {
            $lead_calculate = lead_calculate($leadclient->id);
            $totalSum += (float) $lead_calculate['team_agent_paid'];

            // Calculate agent income
            $leadcalculation = AgentincomeController::getcalculation($leadclient->id);
            
            // Add only if the lead is not a repeat and has valid team info
            if ($leadclient->curr_status !== "Repeat" && $leadclient->team_id !== null && $leadclient->team_cost_charge !== null) {
                $leadclient->agent_name = optional($leadclient->agent)->name;
                $leadListing[] = [
                    'leadclient' => $leadclient,
                    'leadcalculatdata' => $lead_calculate,
                    'leadcalculation' => $leadcalculation,
                ];
            }
        });

        // Calculate totals for all records (not just current page)
        $totalInvoiced = 0;
        $totalPayment = 0;
        $totalAgentIncome = 0;
        $totalTeamIncome = 0;

        foreach ($leadListing as $item) {
            // Check if 'invoiced_total' is set and not an empty string
                $invoicedTotal = isset($item['leadcalculatdata']['invoiced_total']) && $item['leadcalculatdata']['invoiced_total'] !== ''
                    ? (float)$item['leadcalculatdata']['invoiced_total']
                    : 0;

            // Add to total, ensuring that 'invoiced_total' is treated as zero if empty
                $totalInvoiced += $invoicedTotal;
            
            // Calculate sum for 'payment' key
                $totalPayment += $item['leadclient']->payment;
            
            // Calculate sum for 'agent_paid' key
                $totalAgentIncome += lead_calculate($item['leadclient']->id)['agent_paid'] ?? 0;
            
            // Calculate sum for 'team_agent_paid' key
                $totalTeamIncome += lead_calculate($item['leadclient']->id)['team_agent_paid'] ?? 0;
        }
        
        // Format data for DataTables (client-side processing)
        $datas = array();
        foreach($leadListing as $item) {
            $row = $item['leadclient'];
            $lead_calculate = $item['leadcalculatdata'];
            
            $nestedData = array();
            
            $client = '<a href="' . url('/') . '/editclientlead/' . $row->id . '/1" target="_blank">#' . $row->id . '</a>';
            $name = ucfirst($row->fname) . ' ' . ucfirst($row->lname);
            
            // Get agent name - same logic as UserController@teamIncome
            $agent_name = '';
            if(isset($row->agent_name)) {
                $agent_name = $row->agent_name;
            } else {
                $agent = User::find($row->agent_id);
                if($agent) {
                    $agent_name = $agent->name . ' ' . $agent->last_name;
                }
            }
            
            $paid_out = $row->paid_out ?? '';
            if($paid_out == '01/01/1970' || $paid_out == '01-01-1970') {
                $paid_out = '';
            }
            
            if(is_numeric($row->curr_status)) {
                $status = set_status_name($row->curr_status);
            } else {
                $status = set_status_name($row->curr_status);
            }
            
            $dates = payout_payreceived_date($row->status_history);
            
            $nestedData[] = $client;
            $nestedData[] = $name;
            $nestedData[] = $agent_name;
            $nestedData[] = '$' . number_format($row->payment, 2);
            $nestedData[] = (!empty($dates['paid_rec']) ? $dates['paid_rec'] : '');
            $nestedData[] = (!empty($status) ? $status : '');
            $nestedData[] = '$' . number_format($lead_calculate['team_agent_paid'] ?? 0, 2);
            $nestedData[] = (!empty($dates['paid_out']) ? $dates['paid_out'] : '');
            
            $datas[] = $nestedData;
        }

        return response()->json([
            'draw' => 1,
            'recordsTotal' => count($leadListing),
            'recordsFiltered' => count($leadListing),
            'data' => $datas,
            'total_data' => [
                'total_invoiced' => '$' . number_format($totalInvoiced, 2),
                'total_payment' => '$' . number_format($totalPayment, 2),
                'team_income' => '$' . number_format($totalTeamIncome, 2)
            ]
        ]);
    }

    private function getDistributorIncomeData(Request $request)
    {
        // Copy of DistributordashboardController@distributorIncome function logic
        // Returns data in DataTables format for client-side processing
        return $this->getDistributorIncomeDataFromDistributorIncome($request);
    }
    
    /**
     * Private function - Exact copy of DistributordashboardController@distributorIncome
     * Returns distributor income data in DataTables format for client-side processing
     */
    private function getDistributorIncomeDataFromDistributorIncome(Request $request)
    {
        // EXACT COPY OF DistributordashboardController@distributorIncome function
        $id = Auth::user()->id; 
        $user_role = Auth::user()->user_role;
        $items = $request->items ?? 500000;
        $role_for = "AGENT";
        $is_distributor = false;
        
        $outstanding = $request->input('outstanding');
        $gross = $request->input('gross');
        $totaln = $request->input('total');
        
        Session::put('role_for', $role_for);
        $useraragent = '';
        $distributors = '';
        
        $distributors = User::where('user_role','=',AGENT)
            ->where('manage_distributor','=',1)
            ->where('status','=',1);

        if($user_role == SUPERADMIN){
            $distributors = $distributors->get();
        } elseif($user_role == ADMIN){
            $distributors = $distributors->where('create_by_user','=',$id)->get();
        } elseif($user_role == ARUSER){
            $distributors = $distributors->where('assign_by_user','=',$id)->get();
        }
        
        $distbt = $distributors->first();
        
        if(empty($distributors->first())){
            // No distributors available
        }
        
        // Use URL parameters instead of session - distributor_id and agent_id from request
        $distributor_id_from_request = $request->input('distributor_id');
        $agent_id_from_request = $request->input('agent_id');
        
        // Set distributor_id - use from request, or default to first distributor, or current user if they are a distributor
        $dist_id = '';
        if(!empty($distributor_id_from_request)) {
            $dist_id = $distributor_id_from_request;
        } elseif($user_role == 3 && Auth::user()->manage_distributor == 1) {
            // If user is an agent with manage_distributor=1, they are a distributor
            $dist_id = Auth::user()->id;
        } else {
            $dist_id = $distbt->id ?? 0;
        }
        
        // Set disagentsearch (distributor session) for compatibility with original logic
        $disagentsearch = $dist_id;
        
        // Set agent_id - use from request, or empty
        $aragentsearch = !empty($agent_id_from_request) ? $agent_id_from_request : '';
        
        // Build query - use parameters instead of session
        if(empty($aragentsearch) && !empty($disagentsearch)){
            $firstdistributor = $disagentsearch;
            $agents_of_distri = User::where('user_role','=',AGENT)
                ->where('status','=',1)
                ->where('lead_source_access_to_gent', 'LIKE', '%' . $firstdistributor . '%')
                ->orderBy('name','ASC')
                ->pluck('id')
                ->toArray();

            $leadclients = Leadclient::whereIn('agent_id', $agents_of_distri)
                ->where('source_id', $disagentsearch)
            ->join('users', 'users.id', '=', 'lead_client.agent_id')
            ->leftjoin('lead_status_history','lead_status_history.lead_id','lead_client.id')
            ->select('lead_client.*', 'users.name', 'users.last_name','lead_status_history.date as paid_date');

            $leadclientstotal = Leadclient::whereIn('agent_id', $agents_of_distri)
                ->where('source_id', $disagentsearch)
            ->join('users', 'users.id', '=', 'lead_client.agent_id')
            ->leftjoin('lead_status_history','lead_status_history.lead_id','lead_client.id')
                ->select('lead_client.*', 'users.name', 'users.last_name','lead_status_history.date as paid_date');
        } else {
            $leadclients = Leadclient::where('agent_id', $aragentsearch)
                ->where('source_id', $disagentsearch)
                ->join('users', 'users.id', '=', 'lead_client.agent_id')
                ->leftjoin('lead_status_history','lead_status_history.lead_id','lead_client.id')
                ->select('lead_client.*', 'users.name', 'users.last_name','lead_status_history.date as paid_date');
            
            $leadclientstotal = Leadclient::where('agent_id', $aragentsearch)
                ->where('source_id', $disagentsearch)
                ->join('users', 'users.id', '=', 'lead_client.agent_id')
                ->leftjoin('lead_status_history','lead_status_history.lead_id','lead_client.id')
                ->select('lead_client.*', 'users.name', 'users.last_name','lead_status_history.date as paid_date');
        }
        
        $distributor_id = $disagentsearch;
        $agent_id = $aragentsearch;
        
        // Get agents for the selected distributor (for dropdown) - same as original line 367-374
        // This is the simple query that populates the agent dropdown
        $useraragent = collect();
        if(($user_role == SUPERADMIN || $user_role == ADMIN) && !empty($distributor_id) && $distributor_id != 0){
            $useraragent = User::where('user_role','=',AGENT)
                ->where('lead_source_access_to_gent', 'LIKE', '%' . $distributor_id . '%')
                ->where('status','=',1)
                ->orderBy('name','ASC')
                ->get();
        }
        
        $search_start_date = '';
        $search_end_date = '';
        $searchform = $request->input('search_agent');
        
        if(isset($searchform)){
            $statusarry = ['Invoiced','Pay Received','Paid Out','Sold','Lease Confirmed','MIC','Collections'];
            
            $client_name = $request->input('client_name');
            $client_id = $request->input('client_id');
            $arr = explode(" ", $client_name);
            
            @$c_fname = $arr[0];
            @$c_lname = $arr[1];
            
            if($client_name != ''){
                $leadclients = $leadclients->where('lead_client.fname', $c_fname)
                    ->where('lead_client.lname', $c_lname);
                $leadclientstotal = $leadclientstotal->where('lead_client.fname', $c_fname)
                    ->where('lead_client.lname', $c_lname);
            }
            
            if($client_id != ''){
                $leadclients = $leadclients->where('lead_client.id', $client_id);
                $leadclientstotal = $leadclientstotal->where('lead_client.id', $client_id);
            }
            
            $search_start_date = setdbdate($request->input('search_start_date'));
            $search_end_date = setdbdate($request->input('search_end_date'));
            
            if($search_start_date != '' && $search_end_date != ''){
                $leadclients = $leadclients->whereIn('lead_status_history.status', $statusarry);
                $leadclients = $leadclients->whereBetween('lead_status_history.date', [$search_start_date, $search_end_date]);
                
                $leadclientstotal = $leadclientstotal->whereIn('lead_status_history.status', $statusarry);
                $leadclientstotal = $leadclientstotal->whereBetween('lead_status_history.date', [$search_start_date, $search_end_date]);
            }
        } else {
            $statusarry = ['Invoiced','Pay Received','Paid Out','Sold','Lease Confirmed','MIC','Collections'];
            $statusarry123 = ['Invoiced','Sold','Lease Confirmed','MIC','Collections','12','9','10','11'];
            
            $leadclients = $leadclients->whereIn('lead_status_history.status', $statusarry);
            $leadclientstotal = $leadclientstotal->whereIn('lead_status_history.status', $statusarry123);
        }
        
        // Get all records (for client-side processing) - match original structure
        $leadclientsall = $leadclients
            ->orderby('lead_client.id', 'DESC')
            ->groupBy('lead_client.id')
            ->get();
        
        $statusarry123 = ['Invoiced','Sold','Lease Confirmed','Collections','MIC','12','9','10','11','23'];
        
        $leadclientstotal = $leadclientstotal->whereIn('curr_status', $statusarry123)
            ->orderby('lead_client.id', 'ASC')
            ->groupBy('lead_client.id')
            ->get();
        
        $tot_net = 0;
        $tot_invoiced = 0;
        $tot_paid = 0;
        $outsatnginamt = 0;
        $newres_comm = 0;
        
        foreach($leadclientstotal as $keytotal => $valuetotal) {
            $caculation = DistributordashboardController::getcalculation($valuetotal->id);
            if(!empty($caculation)){
                $newres_comm = (float) $caculation['paidamount'];
            } else {
                $newres_comm = 0;
            }
            $outsatnginamt += $newres_comm;
        }
        
        $total_incoe = array();
        foreach($leadclientsall as $leadclient){
            $leadcalculation = DistributordashboardController::getcalculation($leadclient->id);
            $lead_cost = lead_calculate($leadclient->id)['lead_cost'];
            array_push($total_incoe, $lead_cost);
        }
        
        // Get agents list (same complex logic as original lines 555-638)
        // This is additional logic for different user roles - but we already have $useraragent from above
        // The original uses this complex logic to override $useraragent in certain cases
        // We'll keep the simple query result unless we need to override it
        if($user_role != AGENT){
            if($user_role == ADMIN){
                $company = Auth::user()->company;
            } else {
                $company = $distributors->first()->company ?? '';
            }
            
            $useraragent_complex = User::where('user_role','=',AGENT)->where('status',1)->where('company','=',$company)->get();
            
            $agents = array();
            foreach($useraragent_complex as $value) {
                $agent = $value->lead_source_access_to_gent;
                
                if($agent != NULL || $agent != ''){
                    $agent = explode(',', $agent);
                    
                    if(in_array($dist_id, $agent)){
                        array_push($agents, $value->id);
                    }
                }
            }
            
            // Only override if we have agents from complex logic
            if(!empty($agents)){
                $useraragent = User::where('user_role','=',AGENT)->whereIn('id', $agents)->get();
            }
        } elseif($user_role == AGENT){
            $distri = Auth::user()->lead_source_access_to_gent;
            
            if($distri == NULL || $distri == ''){
                $distri = array(0);
            } else {
                $distri = explode(',', $distri);
            }
            
            $useraragent_complex = User::where('user_role','=',AGENT)
                ->where('status',1)
                ->where('company','=',Auth::user()->company)
                ->get();
            
            $agents = array();
            foreach($useraragent_complex as $value) {
                $distributor = $value->lead_source_access_to_gent;
                if($distributor != NULL || $distributor != ''){
                    $distributor = explode(',', $distributor);
                    
                    if(in_array(Auth::user()->id, $distributor)){
                        array_push($agents, $value->id);
                    }
                }
            }
            if(!empty($agents)){
                $useraragent = User::where('user_role','=',AGENT)->where('status',1)->whereIn('id', $agents)->get();
            }
        }
        
        if($user_role == AGENT){
            $distributorss = User::where('id','=',Auth::user()->id)->get();
            $agents_ids = (!empty($distributorss[0]->agents_to_manager) ? $distributorss[0]->agents_to_manager : '');
            
            if(!empty($agents_ids)){
                $agentid = explode(',', $agents_ids);
                $useraragent = User::whereIn('id', $agentid)->get();
            }
        }
        
        $totalincome = array_sum($total_incoe);
        
        // Format data for DataTables (client-side processing) - EXACT MATCH to original view structure
        $datas = array();
        foreach($leadclientsall as $row) {
            $nestedData = array();
            
            // Same as original view line 214
            $client = '<a href="' . url('/') . '/editclientlead/' . $row->id . '/1" target="_blank">#' . $row->id . '</a>';
            // Same as original view line 215
            $name = ucfirst($row->fname) . ' ' . ucfirst($row->lname);
            
            // Agent name (only shown if distributor and no agent selected - handled in view)
            $agent_name = $row->name . ' ' . $row->last_name;
            
            // Get calculation - same as original view line 199
            $leadcalculation = DistributordashboardController::getcalculation($row->id);
            
            // Paid date from calculation - same as original view line 202
            $paid_date = $leadcalculation['paid_date'] ?? '';
            if($paid_date == '01/01/1970' || $paid_date == '01-01-1970') {
                $paid_date = '';
            }
            
            // Paid out from calculation - same as original view line 207
            $paid_out = $leadcalculation['paid_out'] ?? '';
            if($paid_out == '01/01/1970' || $paid_out == '01-01-1970') {
                $paid_out = '';
            }
            
            // Set paid date - same as original view line 211
            DistributordashboardController::setPaidDate($row->id, $row->paid_date);
            
            // Calculate deduction - same as original view lines 225-264
            $lead_calculate = lead_calculate($row->id);
            $str = '';
            $total = array();
            
            if(!empty($lead_calculate['agent_invoice_cost'])){
                $str .= "<tr><td>Invoice Fee</td><td>$".number_format($lead_calculate['agent_invoice_cost'],2).'</td></tr>';
                array_push($total, $lead_calculate['agent_invoice_cost']);
            }
            
            if(!empty($lead_calculate['commercial_transaction'])){
                $str .= "<tr><td>Commercial Transaction Fee (Tiered) </td><td>$".number_format($lead_calculate['commercial_transaction'],2).'</td></tr>';
                array_push($total, $lead_calculate['commercial_transaction']);
            }
            
            if(!empty($lead_calculate['broker_splite'])){
                $str .= "<tr><td>Broker Cost </td><td>$".number_format($lead_calculate['broker_splite'],2).'</td></tr>';
                array_push($total, $lead_calculate['broker_splite']);
            }
            
            if(!empty($lead_calculate['agent_paid'])){
                $str .= "<tr><td>Agent Paid </td><td>$".number_format($lead_calculate['agent_paid'],2).'</td></tr>';
                array_push($total, $lead_calculate['agent_paid']);
            }
            
            if(!empty($lead_calculate['incentive'])){
                $str .= "<tr><td>Incentive</td><td>$".number_format($lead_calculate['incentive'],2).'</td></tr>';
                array_push($total, $lead_calculate['incentive']);
            }
            
            if(!empty($lead_calculate['transaction_coordination_lease_verify'])){
                $str .= "<tr><td>Optional Fee </td><td>$".number_format($lead_calculate['transaction_coordination_lease_verify'],2).'</td></tr>';
                array_push($total, $lead_calculate['transaction_coordination_lease_verify']);
            }
            $str .= "<tr><th>Total Deductions </th><td>$".number_format(array_sum($total),2).'</td></tr>';
            
            // Deduction link - same as original view line 267
            $deduction_link = '<a href="javascript:void(0);" data-toggle="modal" data-target="#showdeduct" onclick="view_deduct(\''.addslashes($str).'\');" style="cursor: pointer;text-decoration: none;" title="View Deductions">$' . number_format(array_sum($total), 2) . '</a>';
            
            // Net Income (Distributor Income) - same as original view line 268
            $net_income = lead_calculate($row->id)['lead_cost'] ?? 0;
            
            // Build nestedData array - match original view column order
            $nestedData[] = $client; // Client
            $nestedData[] = $name; // Client Name
            // Agent Name column - only shown if distributor and no agent selected (handled in view)
            $nestedData[] = $agent_name; // Agent Name (always include, view will conditionally show)
            $nestedData[] = '$' . number_format($leadcalculation['paidamount'] ?? 0, 2); // Res. commission - same as original line 219
            $nestedData[] = '$' . number_format($row->payment, 2); // Paid Amt - same as original line 220
            $nestedData[] = $paid_date; // Paid Date - same as original line 221
            $nestedData[] = $deduction_link; // Deduction - same as original line 267
            $nestedData[] = '$' . number_format($net_income, 2); // Net Income (Distributor Income) - same as original line 268
            $nestedData[] = $paid_out; // Paid Out - same as original line 269
            
            $datas[] = $nestedData;
        }
        
        // Format agents for dropdown (same as original - return id, name, last_name)
        $agents_array = array();
        foreach($useraragent as $agent) {
            $agents_array[] = [
                'id' => $agent->id,
                'name' => $agent->name,
                'last_name' => $agent->last_name
            ];
        }

        return response()->json([
            'draw' => 1,
            'recordsTotal' => count($leadclientsall),
            'recordsFiltered' => count($leadclientsall),
            'data' => $datas,
            'total_data' => [
                'outstanding' => '$' . number_format($outsatnginamt, 2),
                'gross_revenue' => '$' . number_format($outsatnginamt, 2),
                'distributor_income' => '$' . number_format($totalincome, 2)
            ],
            'agents' => $agents_array
        ]);
    }
    
    /**
     * Get agents for a selected distributor (for dropdown population)
     * This is called when distributor dropdown changes
     */
    public function getDistributorAgents(Request $request)
    {
        $distributor_id = $request->input('distributor_id');
        $user_role = Auth::user()->user_role;
        
        if(empty($distributor_id) || $distributor_id == 0) {
            return response()->json([
                'status' => false,
                'message' => 'Invalid distributor ID',
                'agents' => []
            ]);
        }
        
        // Set distributor in session (same as original)
        Session::put('distributor', $distributor_id);
        Session::put('disagentsearch', $distributor_id);
        
        // Get agents for the selected distributor - same logic as original line 367-374
        $useraragent = collect();
        if($user_role == SUPERADMIN || $user_role == ADMIN){
            $useraragent = User::where('user_role','=',AGENT)
                ->where('lead_source_access_to_gent', 'LIKE', '%' . $distributor_id . '%')
                ->where('status','=',1)
                ->orderBy('name','ASC')
                ->get();
        }
        
        // Format agents for dropdown
        $agents_array = array();
        foreach($useraragent as $agent) {
            $agents_array[] = [
                'id' => $agent->id,
                'name' => $agent->name,
                'last_name' => $agent->last_name
            ];
        }
        
        return response()->json([
            'status' => true,
            'agents' => $agents_array
        ]);
    }

    public function downloadIncome(Request $request)
    {
        $tab = $request->get('tab', 'admin');
        $format = $request->get('format', 'pdf');
        
        // Get the data based on tab
        $data = null;
        switch($tab) {
            case 'admin':
                $data = $this->getAdminIncomeData($request);
                break;
            case 'agent':
                $data = $this->getAgentIncomeData($request);
                break;
            case 'ar':
                $data = $this->getArIncomeData($request);
                break;
            case 'team':
                $data = $this->getTeamIncomeData($request);
                break;
            case 'distributor':
                $data = $this->getDistributorIncomeData($request);
                break;
        }
        
        if ($format === 'csv') {
            return $this->downloadCsv($tab, $data);
        } else {
            return $this->downloadPdf($tab, $data);
        }
    }

    private function downloadCsv($tab, $data)
    {
        $filename = $tab . '_income_' . date('Y-m-d') . '.csv';
        
        $headers = [
            'Content-Type' => 'text/csv',
            'Content-Disposition' => 'attachment; filename="' . $filename . '"',
        ];
        
        $callback = function() use ($data, $tab) {
            $file = fopen('php://output', 'w');
            
            // Write headers based on tab
            if ($tab === 'team') {
                fputcsv($file, ['ID', 'Client Name', 'Agent', 'Invoice Date', 'Amount', 'Status', 'Team Income']);
                
                if (isset($data['leadListingPaginated']['data'])) {
                    foreach ($data['leadListingPaginated']['data'] as $item) {
                        fputcsv($file, [
                            $item['leadclient']['id'],
                            $item['leadclient']['client_name'],
                            $item['leadclient']['agent_name'],
                            $item['leadclient']['inv_date'],
                            $item['leadclient']['payment'],
                            $item['leadclient']['curr_status'],
                            $item['leadcalculatdata']['team_agent_paid']
                        ]);
                    }
                }
            } else {
                fputcsv($file, ['ID', 'Client Name', 'Agent', 'Invoice Date', 'Amount', 'Status', 'Paid Date']);
                
                if (isset($data['leadclients']['data'])) {
                    foreach ($data['leadclients']['data'] as $item) {
                        fputcsv($file, [
                            $item['id'],
                            $item['client_name'],
                            $item['name'] . ' ' . $item['last_name'],
                            $item['inv_date'],
                            $item['payment'],
                            $item['curr_status'],
                            $item['paid_date']
                        ]);
                    }
                }
            }
            
            fclose($file);
        };
        
        return response()->stream($callback, 200, $headers);
    }

    private function downloadPdf($tab, $data)
    {
        // Use existing PDF generation logic from AgentincomeController
        $agentIncomeController = new AgentincomeController();
        return $agentIncomeController->downloadPdf($tab, $data);
    }
}
