<?php
use App\Controllers\PlanController;
use App\Models\OrganizationModel;
use App\Models\UserModel;
use App\Models\GroupModel;
use App\Models\PolicyModel;
use App\Models\PolicyDetailsModel;
use App\Models\ServiceModel;
use App\Models\PlanStatusModel;
use App\Models\PlanModel;


if (!function_exists('palnStatusHandler')) {
    function palnStatusHandler($plan_id , $is_data_edited)
    {
        log_message('info', "palnStatusHandler() called for plan_id: {$plan_id}, is_data_edited: {$is_data_edited}");

        $planModel = new PlanModel();
        $planStatusModel = new PlanStatusModel();
        $userModel = new UserModel();
        $groupModel = new GroupModel();
        $policyModel = new PolicyModel();
        $policyDetailsModel = new PolicyDetailsModel();
        $planController = new PlanController();

        $planData = $planController->find($plan_id, 'internal');
        if (!$planData) {
            log_message('error', "No plan data found for plan_id: {$plan_id}");
            return false;
        }

        $planServices = [];
        if (count($planData['flight']))         { array_push($planServices, 1); }
        if (count($planData['train']))          { array_push($planServices, 2); }
        if (count($planData['bus']))            { array_push($planServices, 3); }
        if (count($planData['taxi']))           { array_push($planServices, 4); }
        if (count($planData['accomodation']))   { array_push($planServices, 5); }
        if (count($planData['forex']))          { array_push($planServices, 6); }
        if (count($planData['insurance']))      { array_push($planServices, 7); }
        if (count($planData['visa']))           { array_push($planServices, 8); }
        if (count($planData['miscellaneous']))  { array_push($planServices, 9); }

        log_message('debug', "Plan services found: " . json_encode($planServices));

        // $userId = $planData['user_id'] ?? $planData['traveller_id'];
        $userId = !empty($planData['user_id']) ? $planData['user_id'] : $planData['created_by'];
        $userData = $userModel->where('user_id', $userId)->first();
        if (!$userData) {
            log_message('error', "User data not found for user_id: {$userId}");
            return false;
        }

        $groupId = $userData['group_id'];
        $a1Id = $userData['first_approver'];
        $a2Id = $userData['second_approver'];
        $a3Id = $userData['third_approver'];
        $a4Id = $userData['fourth_approver'];

        $groupData = $groupModel->where('group_id', $groupId)->first();
        if (!$groupData) {
            log_message('error', "Group data not found for group_id: {$groupId}");
            return false;
        }

        $tripType = $planData['trip_type'];
        $policyId = ($tripType == 1) ? $groupData['domestic_policy_id'] : $groupData['international_policy_id'];

        $policyData = $policyModel->where('policy_id', $policyId)->first();
        if (!$policyData) {
            log_message('error', "Policy data not found for policy_id: {$policyId}");
            return false;
        }

        $priorityOrderOfService = json_decode($policyData['services_ids'], true);
        if (!is_array($priorityOrderOfService)) {
            log_message('error', "Invalid service priority list in policy_id: {$policyId}");
            return false;
        }

        foreach ($priorityOrderOfService as $key => &$value) {
            $value['priority'] = $key + 1;
        }
        unset($value);

        log_message('debug', "Service priority list: " . json_encode($priorityOrderOfService));

        // Step 1: Filter only services present in current plan
        $filtered = array_filter($priorityOrderOfService, function ($item) use ($planServices) {
            return in_array($item['service_id'], $planServices);
        });

        // Step 2: Sort by priority
        usort($filtered, function ($a, $b) {
            return $a['priority'] <=> $b['priority'];
        });

        $topPriorityService = reset($filtered);
        if (!$topPriorityService) {
            log_message('error', "No matching service found for plan_id: {$plan_id}");
            return false;
        }

        log_message('info', "Top priority service identified: " . json_encode($topPriorityService));

        $policyServiceDetails = $policyDetailsModel
            ->where('policy_id', $policyId)
            ->where('service_id', $topPriorityService['service_id'])
            ->where('is_active', 1)
            ->first();

        if (!$policyServiceDetails) {
            log_message('error', "Policy service details not found for service_id: {$topPriorityService['service_id']}, policy_id: {$policyId}");
            return false;
        }
        // dd($policyServiceDetails);


        $isExceptional = $planData['exceptional_plan_reason'] !== null  && $planData['exceptional_plan_reason'] !== '';
        // dd($isExceptional);

        if ($isExceptional) {
            $policyA1Action       = $policyServiceDetails['a1_exceptional_action'];
            $policyA2Action       = $policyServiceDetails['a2_exceptional_action'];
            $policyA3Action       = $policyServiceDetails['a3_exceptional_action'];
            $policyA4Action       = $policyServiceDetails['a4_exceptional_action'];
            $policyParallelAction = $policyServiceDetails['exceptional_parallel_process_from'];
            $policyAction         = 'Exceptional';
        } else if ($is_data_edited) {
            $policyA1Action       = $policyServiceDetails['a1_amendment_action'];
            $policyA2Action       = $policyServiceDetails['a2_amendment_action'];
            $policyA3Action       = $policyServiceDetails['a3_amendment_action'];
            $policyA4Action       = $policyServiceDetails['a4_amendment_action'];
            $policyParallelAction = $policyServiceDetails['amendment_parallel_process_from'];
            $policyAction         = 'Amendment';
        } else {
            $policyA1Action       = $policyServiceDetails['a1_action'];
            $policyA2Action       = $policyServiceDetails['a2_action'];
            $policyA3Action       = $policyServiceDetails['a3_action'];
            $policyA4Action       = 'None';
            $policyParallelAction = $policyServiceDetails['parallel_process_from'];
            $policyAction         = 'Normal';
        }


        $data = [
            'plan_id' => $plan_id,
            'service_id' => $topPriorityService['service_id'],
            'a1_id' => $a1Id,
            'a1_action' => $policyA1Action,
            'is_a1_action_done' => ($policyA1Action == 'None') ? 1 : 0,
            'a2_id' => $a2Id,
            'a2_action' => $policyA2Action,
            'is_a2_action_done' => ($policyA2Action == 'None') ? 1 : 0,
            'a3_id' => $a3Id,
            'a3_action' => $policyA3Action,
            'is_a3_action_done' => ($policyA3Action == 'None') ? 1 : 0,
            'a4_id' => $a4Id,
            'a4_action' => $policyA4Action,
            'is_a4_action_done' => ($policyA4Action == 'None') ? 1 : 0,
            'parallel_process_from' => $policyParallelAction,
            'policy_action' => $policyAction,
            'group_id'=> $groupId,
            'policy_id'=> $policyId,
        ];

        // dd($data);

        if ($is_data_edited == false) {
            log_message('info', "Creating new plan status for plan_id: {$plan_id}");
            $planStatusModel->insert($data);
        } else {
            $oldStatusData = $planStatusModel->where('plan_id', $plan_id)->where('is_active', 1)->first();
            if ($oldStatusData) {
                if ($oldStatusData['service_id'] == $topPriorityService['service_id']) {
                    log_message('info', "No status update needed; service_id unchanged for plan_id: {$plan_id}");
                } else {
                    log_message('info', "Updating plan status for edited plan_id: {$plan_id}. New service_id: {$topPriorityService['service_id']}, Old service_id: {$oldStatusData['service_id']}");
                    $planStatusModel->insert($data);
                    $planStatusModel->set(['is_active' => 0])
                        ->where('plan_id', $plan_id)
                        ->where('service_id', $oldStatusData['service_id'])
                        ->update();
                }
            } else {
                log_message('warning', "Old status data not found for edited plan_id: {$plan_id}");
                $planStatusModel->insert($data);
            }
        }

        log_message('info', "palnStatusHandler() completed for plan_id: {$plan_id}");
    }
}


// if (!function_exists('palnStatusHandler')) {
//     function palnStatusHandler($plan_id , $is_data_edited)
//     {

//         $planModel = new PlanModel();
//         $planStatusModel = new PlanStatusModel();
//         $userModel = new UserModel();
//         $groupModel = new GroupModel();
//         $policyModel = new PolicyModel();
//         $policyDetailsModel = new PolicyDetailsModel();
//         $planController = new PlanController();

//         $planData = $planController->find($plan_id, 'internal');
        
//         $planServices = [];
//         if($planData)
//         {
//             if(count($planData['flight'])){ array_push($planServices,1); }
//             if(count($planData['train'])){ array_push($planServices,2); }
//             if(count($planData['bus'])){ array_push($planServices,3); }
//             if(count($planData['taxi'])){ array_push($planServices,4); }
//             if(count($planData['accomodation'])){ array_push($planServices,5); }
//             if(count($planData['forex'])){ array_push($planServices,6); }
//             if(count($planData['insurance'])){ array_push($planServices,7); }
//             if(count($planData['visa'])){ array_push($planServices,8); }
//             if(count($planData['miscellaneous'])){ array_push($planServices,9); }

//         }
//         echo '<pre>';
//         print_r($planServices);


//         // Fetch plan data
//         if (!$planData) { return false; }
//         $userId = $planData['user_id'] ?? $planData['traveller_id'];

//         // Fetch user data
//         $userData = $userModel->where('user_id', $userId)->first();
//             if (!$userData) { return false; }
//             $groupId = $userData['group_id'];
//             $a1Id = $userData['first_approver'];
//             $a2Id = $userData['second_approver'];
//             $a3Id = $userData['third_approver'];
          

//         // Fetch group data
//         $groupData = $groupModel->where('group_id', $groupId)->first();
//             if (!$groupData) { return false; }
//             $policyId = ($planData['trip_type'] == 1) ? $groupData['domestic_policy_id'] : $groupData['international_policy_id'];
        
//         // Fetch policy service data
//         $policyData = $policyModel->where('policy_id', $policyId)->first();
//             if (!$policyData) {return false; }
           
//             $priorityOrderOfService = json_decode($policyData['services_ids'],true);
//             if (is_array($priorityOrderOfService)) {
//                 foreach ($priorityOrderOfService as $key => &$value) {
//                     $value['priority'] = $key + 1;
//                 }
//                 unset($value); // always break reference after loop
//             }
//         echo '<pre>';
//         print_r($priorityOrderOfService);
    
//         // Step 1: Filter only services you currently have
//         $filtered = array_filter($priorityOrderOfService, function($item) use ($planServices) {
//             return in_array($item['service_id'], $planServices);
//         });

//         // Step 2: Sort by priority ascending
//         usort($filtered, function($a, $b) {
//             return $a['priority'] <=> $b['priority'];
//         });

//         // Step 3: Get the top priority service
//         $topPriorityService = reset($filtered);
//         echo '<pre>';
//         print_r($topPriorityService); die;

//         $policyServiceDetails = $policyDetailsModel->where('policy_id',$policyId)->where('service_id',$topPriorityService['service_id'])->where('is_active',1)->first();
//             if (!$policyServiceDetails) { return false; }
//             $policyA1Action = $policyServiceDetails['a1_action'];
//             $policyA2Action = $policyServiceDetails['a2_action'];
//             $policyA3Action = $policyServiceDetails['a3_action'];
//             $policyParallelAction = $policyServiceDetails['parallel_process_from'];
    


   
//         if($is_data_edited == false)//plan Creation
//         {
//             $data['plan_id'] = $plan_id;
//             $data['service_id'] = $topPriorityService['service_id'];
//             $data['a1_id'] = $a1Id;
//             $data['a1_action'] = $policyA1Action;
//             $data['a2_id'] = $a2Id;
//             $data['a2_action'] = $policyA2Action;
//             $data['a3_id'] = $a3Id;
//             $data['a3_action'] = $policyA3Action;
//             $data['parallel_process_from'] = $policyParallelAction;
//             // Insert Status
//             $planStatusModel->insert($data);

//         }else{

//             $oldStatusData = $planStatusModel->where('plan_id',$plan_id)->where('is_active', 1)->first();

//             if($oldStatusData['service_id'] == $topPriorityService['service_id']){ // skip the process

//             }else{ // insert new data 

//                 //insert new service data
//                 $data['plan_id'] = $plan_id;
//                 $data['service_id'] = $topPriorityService['service_id'];
//                 $data['a1_id'] = $a1Id;
//                 $data['a1_action'] = $policyA1Action;
//                 $data['a2_id'] = $a2Id;
//                 $data['a2_action'] = $policyA2Action;
//                 $data['a3_id'] = $a3Id;
//                 $data['a3_action'] = $policyA3Action;
//                 $data['parallel_process_from'] = $policyParallelAction;
//                 // Insert Status
//                 $planStatusModel->insert($data);

//                 //update old service data is_active = 0
//                 $planStatusModel->set(['is_active'=>0])->where('plan_id',$plan_id)->where('service_id',$oldStatusData['service_id'])->update();

//             }

//         }
       
  
//     }
// }

if (!function_exists('updatePlanStatus')) {
    function updatePlanStatus($plan_id,$updated_by)
    {

        $planStatusModel = new PlanStatusModel();
        $planModel = new PlanModel();

        $a1 = $planStatusModel->where('plan_id',$plan_id)->where('a1_action','Approval')->where('is_active',1)->findAll();
        $a1ApproveSum = 0;
        $a1ApproveCount = 0;
        if(count($a1))
        {
            $a1ApproveSum = array_sum(array_column($a1, 'is_a1_action_done'));
            $a1ApproveCount = count($a1);
        }

        $a2 = $planStatusModel->where('plan_id',$plan_id)->where('a2_action','Approval')->where('is_active',1)->findAll();
        $a2ApproveSum = 0;
        $a2ApproveCount = 0;
        if(count($a2))
        {
            $a2ApproveSum = array_sum(array_column($a2, 'is_a2_action_done'));
            $a2ApproveCount = count($a2);
        }


        $a3 = $planStatusModel->where('plan_id',$plan_id)->where('a3_action','Approval')->where('is_active',1)->findAll();
        $a3ApproveSum = 0;
        $a3ApproveCount = 0;
        if(count($a3))
        {
            $a3ApproveSum = array_sum(array_column($a3, 'is_a3_action_done'));
            $a3ApproveCount = count($a3);
        }

        $a4 = $planStatusModel->where('plan_id',$plan_id)->where('a4_action','Approval')->where('is_active',1)->findAll();
        $a4ApproveSum = 0;
        $a4ApproveCount = 0;
        if(count($a4))
        {
            $a4ApproveSum = array_sum(array_column($a4, 'is_a4_action_done'));
            $a4ApproveCount = count($a4);
        }


        
        $count = ( $a1ApproveCount + $a2ApproveCount + $a3ApproveCount + $a4ApproveCount);
        $sum = ( $a1ApproveSum + $a2ApproveSum + $a3ApproveSum + $a4ApproveSum);

        // dd($a1,$a2,$a3,$a4,$count,$sum);
        if($count == $sum)
        {
           // Approved
           $planModel->set(['status'=>3,'updated_by'=>$updated_by])->where('plan_id',$plan_id)->update();
           
        }else if($count != $sum && $sum > 0)
        {
            //Partially Approved
            $planModel->set(['status'=>2,'updated_by'=>$updated_by])->where('plan_id',$plan_id)->update();
            // $planModel->updatePlan($plan_id, ['status'=>2]);
            // $db = \Config\Database::connect();
            // $db->table('m_plan')->where('plan_id', $plan_id)->update(['status' => 2]);
        }
       
        return true;

    }
}

if (!function_exists('getCurrentPlanStatus')) {
    function getCurrentPlanStatus($plan_id)
    {

        $planStatusModel = new PlanStatusModel();
        $userModel = new UserModel();
        $currentStatus = [];

        $a1 = $planStatusModel->where('plan_id',$plan_id)->where('a1_action','Approval')->where('is_active',1)->findAll();
        
        if(count($a1))
        {
            
            $user1 = $userModel->where('user_id', $a1[0]['a1_action_done_by'])->first();
            if(!$user1){
            $user1 = $userModel->where('user_id', $a1[0]['a1_id'])->first();
            }
            
            $hasRejectReason = !empty(array_filter($a1, fn($row) => !empty($row['a1_reject_reason'])));
            if($user1)
            {

                $userId = $user1['user_id'];

                $a1ApproveSum = array_sum(array_column($a1, 'is_a1_action_done'));
                $a1ApproveCount = count($a1);

                $a1Status['a1_id'] = $userId;
                if($a1ApproveSum == $a1ApproveCount)
                {
                    $a1Status['a1_status'] = 'Plan approved by '.$user1['first_name'].' '.$user1['last_name'];
                }else if($hasRejectReason){
                    $a1Status['a1_status'] = 'Plan rejected by '.$user1['first_name'].' '.$user1['last_name'].', Reason-'.$a1[0]['a1_reject_reason'];
                }else{
                    $a1Status['a1_status'] = 'Plan approval pending from '.$user1['first_name'].' '.$user1['last_name'];
                }
                array_push($currentStatus,$a1Status);
            }
            
        }


        $a2 = $planStatusModel->where('plan_id',$plan_id)->where('a2_action','Approval')->where('is_active',1)->findAll();
        if(count($a2))
        {
            $user2 = $userModel->where('user_id', $a2[0]['a2_action_done_by'])->first();
            if(!$user2){
            $user2 = $userModel->where('user_id', $a2[0]['a2_id'])->first();
            }
            $hasRejectReason = !empty(array_filter($a2, fn($row) => !empty($row['a2_reject_reason'])));
            if($user2)
            {
                $userId = $user2['user_id'];

                $a2ApproveSum = array_sum(array_column($a2, 'is_a2_action_done'));
                $a2ApproveCount = count($a2);

                $a2Status['a2_id'] = $userId;
                if($a2ApproveSum == $a2ApproveCount)
                {
                    $a2Status['a2_status'] = 'Plan approved by '.$user2['first_name'].' '.$user2['last_name'];
                }else if($hasRejectReason){
                    $a2Status['a2_status'] = 'Plan rejected by '.$user2['first_name'].' '.$user2['last_name'].', Reason-'.$a2[0]['a2_reject_reason'];
                }else{
                    $a2Status['a2_status'] = 'Plan approval pending from '.$user2['first_name'].' '.$user2['last_name'];
                }
                array_push($currentStatus,$a2Status);
            }
        }


        $a3 = $planStatusModel->where('plan_id',$plan_id)->where('a3_action','Approval')->where('is_active',1)->findAll();
        if(count($a3))
        {
            $user3 = $userModel->where('user_id', $a3[0]['a3_action_done_by'])->first();
            if(!$user3){
            $user3 = $userModel->where('user_id', $a3[0]['a3_id'])->first();
            }
            $hasRejectReason = !empty(array_filter($a3, fn($row) => !empty($row['a3_reject_reason'])));
            if($user3)
            {
                $userId = $user3['user_id'];

                $a3ApproveSum = array_sum(array_column($a3, 'is_a3_action_done'));
                $a3ApproveCount = count($a3);

                $a3Status['a3_id'] = $userId;
                if($a3ApproveSum == $a3ApproveCount)
                {
                    $a3Status['a3_status'] = 'Plan approved by '.$user3['first_name'].' '.$user3['last_name'];
                }else if($hasRejectReason){
                    $a3Status['a3_status'] = 'Plan rejected by '.$user3['first_name'].' '.$user3['last_name'].', Reason-'.$a3[0]['a3_reject_reason'];
                }else{
                    $a3Status['a3_status'] = 'Plan approval pending from '.$user3['first_name'].' '.$user3['last_name'];
                }
                array_push($currentStatus,$a3Status);
            }
        }

        $a4 = $planStatusModel->where('plan_id',$plan_id)->where('a4_action','Approval')->where('is_active',1)->findAll();
        if(count($a4))
        {
            $user4 = $userModel->where('user_id', $a4[0]['a4_action_done_by'])->first();
            if(!$user4){
            $user4 = $userModel->where('user_id', $a4[0]['a4_id'])->first();
            }
            $hasRejectReason = !empty(array_filter($a4, fn($row) => !empty($row['a4_reject_reason'])));
            if($user4)
            {
                $userId = $user4['user_id'];

                $a4ApproveSum = array_sum(array_column($a4, 'is_a4_action_done'));
                $a4ApproveCount = count($a4);

                $a4Status['a4_id'] = $userId;
                if($a4ApproveSum == $a4ApproveCount)
                {
                    $a4Status['a4_status'] = 'Plan approved by '.$user4['first_name'].' '.$user4['last_name'];
                }else if($hasRejectReason){
                    $a4Status['a4_status'] = 'Plan rejected by '.$user4['first_name'].' '.$user4['last_name'].', Reason-'.$a4[0]['a4_reject_reason'];
                }else{
                    $a4Status['a4_status'] = 'Plan approval pending from '.$user4['first_name'].' '.$user4['last_name'];
                }
                array_push($currentStatus,$a4Status);
            }
        }


        return $currentStatus;

    }
}

if (!function_exists('getPlanApproverAction')) {
    // initially written code without parallel , sequential 
    // function getPlanApproverAction($plan_id , )
    // {

    //     $planStatusModel = new PlanStatusModel();
    //     $userModel = new UserModel();
    //     $result['approver_data'] = [];
    //     $serviceIds = [];

    //     $a1 = $planStatusModel->where('plan_id',$plan_id)->whereIn('a1_action',['Approval','Notification'])->where('is_active',1)->findAll();
    //     if(count($a1))
    //     {
    //         $serviceId = array_column($a1, 'service_id');
    //         $serviceIds = array_merge($serviceIds, $serviceId);
    //         $user = $userModel->where('user_id', $a1[0]['a1_id'])->first();
    //         if($user)
    //         {
    //             $approvalCount = 0;
    //             $notificationCount = 0;

    //             foreach ($a1 as $item) {
    //                 if ($item['a1_action'] === 'Approval') {
    //                     $approvalCount++;
    //                 } elseif ($item['a1_action'] === 'Notification') {
    //                     $notificationCount++;
    //                 }
    //             }

    //             if($approvalCount != 0)
    //             {
    //                 array_push($result['approver_data'] , ['approver'=>1, 'user_id'=>$a1[0]['a1_id'], 'email'=> $user['email'], 'action'=>'Approval',  'is_action_done'=>$a1[0]['is_a1_action_done']] );
    //             }else if($notificationCount != 0){
    //                 array_push($result['approver_data'] , ['approver'=>1, 'user_id'=>$a1[0]['a1_id'], 'email'=> $user['email'], 'action'=>'Notification',  'is_action_done'=>$a1[0]['is_a1_action_done']] );
    //             }
    //         }
  
    //     }



    //     $a2 = $planStatusModel->where('plan_id',$plan_id)->whereIn('a2_action',['Approval','Notification'])->where('is_active',1)->findAll();
    //     if(count($a2))
    //     {
    //         $serviceId = array_column($a2, 'service_id');
    //         $serviceIds = array_merge($serviceIds, $serviceId);
    //         $user = $userModel->where('user_id', $a1[0]['a2_id'])->first();
    //         if($user)
    //         {
    //             $approvalCount = 0;
    //             $notificationCount = 0;

    //             foreach ($a1 as $item) {
    //                 if ($item['a2_action'] === 'Approval') {
    //                     $approvalCount++;
    //                 } elseif ($item['a2_action'] === 'Notification') {
    //                     $notificationCount++;
    //                 }
    //             }

    //             if($approvalCount != 0)
    //             {
    //                 array_push($result['approver_data'] , ['approver'=>2, 'user_id'=>$a1[0]['a2_id'], 'email'=> $user['email'], 'action'=>'Approval',  'is_action_done'=>$a2[0]['is_a2_action_done']] );
    //             }else if($notificationCount != 0){
    //                 array_push($result['approver_data'] , ['approver'=>2, 'user_id'=>$a1[0]['a2_id'], 'email'=> $user['email'], 'action'=>'Notification',  'is_action_done'=>$a2[0]['is_a2_action_done']] );
    //             }
    //         }
  
    //     }

    //     $a3 = $planStatusModel->where('plan_id',$plan_id)->whereIn('a3_action',['Approval','Notification'])->where('is_active',1)->findAll();
    //     if(count($a3))
    //     {
    //         $serviceId = array_column($a3, 'service_id');
    //         $serviceIds = array_merge($serviceIds, $serviceId);
    //         $user = $userModel->where('user_id', $a1[0]['a3_id'])->first();
    //         if($user)
    //         {
    //             $approvalCount = 0;
    //             $notificationCount = 0;

    //             foreach ($a1 as $item) {
    //                 if ($item['a3_action'] === 'Approval') {
    //                     $approvalCount++;
    //                 } elseif ($item['a3_action'] === 'Notification') {
    //                     $notificationCount++;
    //                 }
    //             }

    //             if($approvalCount != 0)
    //             {
    //                 array_push($result['approver_data'] , ['approver'=>3, 'user_id'=>$a1[0]['a3_id'], 'email'=> $user['email'], 'action'=>'Approval',  'is_action_done'=>$a3[0]['is_a3_action_done']] );
    //             }else if($notificationCount != 0){
    //                 array_push($result['approver_data'] , ['approver'=>3, 'user_id'=>$a1[0]['a3_id'], 'email'=> $user['email'], 'action'=>'Notification',  'is_action_done'=>$a3[0]['is_a3_action_done']] );
    //             }
    //         }
  
    //     }


    //     $statusData = $planStatusModel->where('plan_id',$plan_id)->where('is_active',1)->first();
    //     $result['parallel_process_from'] = $statusData['parallel_process_from'];

    //     return $result;

    // }

    // 3 level of parallel , sequential 
    // function getPlanApproverAction($plan_id)
    // {
    //     $planStatusModel = new PlanStatusModel();
    //     $userModel = new UserModel();
    //     $result = ['approver_data' => []];
    //     $serviceIds = [];
    
    //     // A1, A2, A3 - handle all same way
    //     $approverAction = [
    //         ['key' => 'a1', 'approver' => 1],
    //         ['key' => 'a2', 'approver' => 2],
    //         ['key' => 'a3', 'approver' => 3],
    //     ];
    
    //     foreach ($approverAction as $stage) {
    //         $field = $stage['key'];
    //         $approverNumber = $stage['approver'];
    //         $actionField = "{$field}_action";
    //         $idField = "{$field}_id";
    //         $doneField = "is_{$field}_action_done";
    
    //         $record = $planStatusModel->where('plan_id', $plan_id)
    //                                   ->whereIn($actionField, ['Approval', 'Notification', 'None'])
    //                                   ->where('is_active', 1)
    //                                   ->first();
    
    //         if ($record) {
    //             $user = $userModel->where('user_id', $record[$idField])->first();
    //             if ($user) {
    //                 $result['approver_data'][] = [
    //                     'approver' => $approverNumber,
    //                     'user_id' => $record[$idField],
    //                     'email' => $user['email'],
    //                     'action' => $record[$actionField],
    //                     'is_action_done' => $record[$doneField],
    //                     'where_key' => $idField,
    //                     'action_key' => $actionField,
    //                     'action_done_key' => $doneField,
    //                 ];
    //             }
    //         }
    //     }
    
    //     // Get parallel process value
    //     $statusData = $planStatusModel->where('plan_id', $plan_id)->where('is_active', 1)->first();
    //     $result['parallel_process_from'] = $statusData['parallel_process_from'] ?? null;


    //     $parallelFrom = (int) $result['parallel_process_from'];

    //     foreach ($result['approver_data'] as $key => &$approver) {
    //         $approver['status'] = 'pending'; // default

    //         if ($parallelFrom === 1) {
    //             // All parallel
    //             $approver['status'] = 'active';
    //         } elseif ($parallelFrom === 2) {
    //             if ($approver['approver'] === 1) {
    //                 $approver['status'] = 'active';
    //             } elseif (in_array($approver['approver'], [2, 3])) {
    //                 // Check if approver 1 is done
    //                 $a1Done = false;
    //                 foreach ($result['approver_data'] as $a) {
    //                     if ($a['approver'] === 1 && $a['is_action_done']) {
    //                         $a1Done = true;
    //                         break;
    //                     }
    //                 }
    //                 $approver['status'] = $a1Done ? 'active' : 'waiting';
    //             }
    //         } elseif ($parallelFrom === 3) {
    //             // Sequential: 1 -> 2 -> 3
    //             $a1Done = false;
    //             $a2Done = false;

    //             foreach ($result['approver_data'] as $a) {
    //                 if ($a['approver'] === 1 && $a['is_action_done']) $a1Done = true;
    //                 if ($a['approver'] === 2 && $a['is_action_done']) $a2Done = true;
    //             }

    //             if ($approver['approver'] === 1) {
    //                 $approver['status'] = 'active';
    //             } elseif ($approver['approver'] === 2) {
    //                 $approver['status'] = $a1Done ? 'active' : 'waiting';
    //             } elseif ($approver['approver'] === 3) {
    //                 $approver['status'] = ($a1Done && $a2Done) ? 'active' : 'waiting';
    //             }
    //         }
    //     }
    //     unset($approver); // best practice when using & reference in foreach

    
    //     return $result;
    // }


    // latest 4 level of parallel , sequential 
    function getPlanApproverAction($plan_id)
    {
        $planStatusModel = new PlanStatusModel();
        $userModel = new UserModel();
        $result = ['approver_data' => []];

        $approverAction = [
            ['key' => 'a1', 'approver' => 1],
            ['key' => 'a2', 'approver' => 2],
            ['key' => 'a3', 'approver' => 3],
            ['key' => 'a4', 'approver' => 4],
        ];

        foreach ($approverAction as $stage) {
            $field = $stage['key'];
            $approverNumber = $stage['approver'];
            $actionField = "{$field}_action";
            $idField = "{$field}_id";
            $doneField = "is_{$field}_action_done";
            $mailField = "is_{$field}_mail_send";

            $record = $planStatusModel->where('plan_id', $plan_id)
                                    ->whereIn($actionField, ['Approval', 'Notification', 'None'])
                                    ->where('is_active', 1)
                                    ->first();
            if ($record) {
                $user = $userModel->where('user_id', $record[$idField])->first();
                if ($user) {
                    $result['approver_data'][] = [
                        'approver' => $approverNumber,
                        'user_id' => $record[$idField],
                        'email' => $user['email'],
                        'action' => $record[$actionField],
                        'is_action_done' => $record[$doneField],
                        'where_key' => $idField,
                        'action_key' => $actionField,
                        'action_done_key' => $doneField,
                        'mail_send_key' => $mailField,
                        'is_mail_send' => $record[$mailField],
                    ];
                }
            }
        }

        $statusData = $planStatusModel->where('plan_id', $plan_id)->where('is_active', 1)->first();
        $result['parallel_process_from'] = $statusData['parallel_process_from'] ?? null;

        $parallelFrom = (int) $result['parallel_process_from'];

        foreach ($result['approver_data'] as &$approver) {
            $approver['status'] = 'pending'; // default

            // Flags
            $a1Done = $a2Done = $a3Done = false;
            foreach ($result['approver_data'] as $a) {
                if ($a['approver'] === 1 && $a['is_action_done']) $a1Done = true;
                if ($a['approver'] === 2 && $a['is_action_done']) $a2Done = true;
                if ($a['approver'] === 3 && $a['is_action_done']) $a3Done = true;
            }

            if ($parallelFrom === 1) {
                // All approvers active
                $approver['status'] = 'active';

            } elseif ($parallelFrom === 2) {
                if ($approver['approver'] === 1) {
                    $approver['status'] = 'active';
                } elseif (in_array($approver['approver'], [2, 3, 4])) {
                    $approver['status'] = $a1Done ? 'active' : 'waiting';
                }

            } elseif ($parallelFrom === 3) {
                if ($approver['approver'] === 1) {
                    $approver['status'] = 'active';
                } elseif ($approver['approver'] === 2) {
                    $approver['status'] = $a1Done ? 'active' : 'waiting';
                } elseif (in_array($approver['approver'], [3, 4])) {
                    $approver['status'] = ($a1Done && $a2Done) ? 'active' : 'waiting';
                }

            } elseif ($parallelFrom === 4) {
                if ($approver['approver'] === 1) {
                    $approver['status'] = 'active';
                } elseif ($approver['approver'] === 2) {
                    $approver['status'] = $a1Done ? 'active' : 'waiting';
                } elseif ($approver['approver'] === 3) {
                    $approver['status'] = ($a1Done && $a2Done) ? 'active' : 'waiting';
                } elseif ($approver['approver'] === 4) {
                    $approver['status'] = ($a1Done && $a2Done && $a3Done) ? 'active' : 'waiting';
                }
            } else {
                $approver['status'] = 'pending'; // fallback
            }
        }
        unset($approver); // clean reference

        return $result;
    }



    
    
}

if (!function_exists('getApproverCurrentAction')) {
    function getApproverCurrentAction($plan_id,$user_id)
    {

        $planStatusModel = new PlanStatusModel();
        $userModel = new UserModel();

        $a1 = $planStatusModel->where('plan_id',$plan_id)->where('a1_id',$user_id)->where('a1_action','Approval')->where('is_active',1)->findAll();
        if(count($a1))
        {
            $hasRejectReason = !empty(array_filter($a1, fn($row) => !empty($row['a1_reject_reason'])));
            $a1ApproveSum = array_sum(array_column($a1, 'is_a1_action_done'));
            $a1ApproveCount = count($a1);
         
            if($a1ApproveSum == $a1ApproveCount)
            {
                return 'Approved';
            }else if($hasRejectReason){
                return 'Rejected';
            }else{
                return 'Approval pending';
            }  
        }

        $a2 = $planStatusModel->where('plan_id',$plan_id)->where('a2_id',$user_id)->where('a2_action','Approval')->where('is_active',1)->findAll();
        if(count($a2))
        {
            $hasRejectReason = !empty(array_filter($a2, fn($row) => !empty($row['a2_reject_reason'])));
            $a2ApproveSum = array_sum(array_column($a2, 'is_a2_action_done'));
            $a2ApproveCount = count($a2);

            if($a2ApproveSum == $a2ApproveCount)
            {
                return 'Approved';
            }else if($hasRejectReason){
                return 'Rejected';
            }else{
                return 'Approval pending';
            }  
        }

        $a3 = $planStatusModel->where('plan_id',$plan_id)->where('a3_id',$user_id)->where('a3_action','Approval')->where('is_active',1)->findAll();
        if(count($a3))
        {
            $hasRejectReason = !empty(array_filter($a3, fn($row) => !empty($row['a3_reject_reason'])));
            $a3ApproveSum = array_sum(array_column($a3, 'is_a3_action_done'));
            $a3ApproveCount = count($a3);

            if($a3ApproveSum == $a3ApproveCount)
            {
                return 'Approved';
            }else if($hasRejectReason){
                return 'Rejected';
            }else{
                return 'Approval pending';
            }  
        }

        $a4 = $planStatusModel->where('plan_id',$plan_id)->where('a4_id',$user_id)->where('a4_action','Approval')->where('is_active',1)->findAll();
        if(count($a4))
        {
            $hasRejectReason = !empty(array_filter($a4, fn($row) => !empty($row['a4_reject_reason'])));
            $a4ApproveSum = array_sum(array_column($a4, 'is_a4_action_done'));
            $a4ApproveCount = count($a4);

            if($a4ApproveSum == $a4ApproveCount)
            {
                return 'Approved';
            }else if($hasRejectReason){
                return 'Rejected';
            }else{
                return 'Approval pending';
            }  
        }

    }
}

