<?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;
use App\Models\MailTemplateModel;



if (!function_exists('sendPlanCreationMail')) {
    function sendPlanCreationMail($planId , $mailOn = 'send_mail_to_traveller_and_approver')
    {
        $planModel = new PlanModel();
        $userModel = new UserModel();
        $organizationModel = new OrganizationModel();
        $planStatusModel = new PlanStatusModel();

        // Fetch plan data
        $planData = $planModel->where('plan_id', $planId)->first();
        if (!$planData) { return false; }
        $userId = isset($planData['traveller_id']) && !empty($planData['traveller_id']) ? $planData['created_by'] : $planData['user_id'];


        // Fetch user data
        $userData = $userModel->where('user_id', $userId)->first();
            if (!$userData) { return false; }

        // send mail to traveller
        if($mailOn == 'send_mail_to_traveller_and_approver')
        send_email($planData['org_id'] , $userData['email'], 'plan_creation_notification_to_traveller' , $userData , $planData);

        // send mail to approver
        $action = getPlanApproverAction($planId);
    
        foreach ($action['approver_data'] as $key => $value) {

            // Skip if not active
            if ($value['status'] !== 'active') { continue; }
            // Skip if already completed
            if ($value['is_action_done'] == 1) { continue; }
            // Skip if action is None
            if ($value['action'] === 'None') { continue; }
            // mail success check
            if ($value['is_mail_send'] == 1) { continue; }
            // skip with below condition
            if($mailOn == 'send_mail_to_only_approver' && $action['parallel_process_from'] == 1){ continue; }

           

           if($value['action'] == 'Approval'){ $template = 'plan_creation_approval_notification_to_approver'; }else if($value['action'] == 'Notification'){ $template = 'plan_creation_notification_to_approver'; }
            
            $userData = $userModel->where('user_id', $value['user_id'])->first();

            $url = urlButton($planId, $value['user_id']);
    
            $res = send_email($userData['org_id'] , $userData['email'], $template , $userData , $planData, $url);
            if($res['status'] = 'success')
            {
                $planStatusModel->set([ $value['mail_send_key'] => 1 ])->where('plan_id', $planId)->where('is_active', 1)->update(); 
            }

            // if action is notification update the action status as 1 (done)
            $parallelProcessValue =  $action['parallel_process_from'];
            if($value['action'] == 'Notification'){ 

                $planStatusModel->set([ $value['action_done_key'] => 1 ])
                                ->where('plan_id', $planId)
                                ->where($value['action_key'], 'Notification')
                                ->where('is_active', 1)
                                ->update(); 

                if($parallelProcessValue == 2 &&  $value['action_key'] == 'a1_action')
                {
                    sendPlanCreationMail($planId , 'send_mail_to_only_approver');
                }
                if($parallelProcessValue == 3 && ($value['action_key'] == 'a1_action' || $value['action_key'] == 'a2_action') )
                {
                    sendPlanCreationMail($planId , 'send_mail_to_only_approver');
                }
                if($parallelProcessValue == 4 && ($value['action_key'] == 'a1_action' || $value['action_key'] == 'a2_action' || $value['action_key'] == 'a3_action'))
                {
                    sendPlanCreationMail($planId , 'send_mail_to_only_approver');
                }

            }



            //delegation part
            $delegationUser = $userModel->where('user_id', $value['user_id'])
                                        ->where('is_active', 1)
                                        ->where('delegation_start_date <=',  date('Y-m-d'))
                                        ->where('delegation_end_date >=',  date('Y-m-d'))
                                        ->first();
            if($delegationUser){
                $delegatedToUserId = $delegationUser['delegated_to_user_id'];

                $delegatedUserData = $userModel->where('user_id', $delegatedToUserId)->first();

                $url = urlButton($planId, $value['user_id'] , $delegatedToUserId);
        
                send_email($delegatedUserData['org_id'] , $delegatedUserData['email'], $template , $delegatedUserData , $planData, $url);
            }

        }
      
        
    }
}

if (!function_exists('sendPlanApprovalOrRejectMail')) {
    function sendPlanApprovalOrRejectMail($planId,$action)
    {
        $planModel = new PlanModel();
        $userModel = new UserModel();
        $organizationModel = new OrganizationModel();

        // Fetch plan data
        $planData = $planModel->where('plan_id', $planId)->first();
        if (!$planData) { return false; }
        $userId = isset($planData['traveller_id']) && !empty($planData['traveller_id']) ? $planData['created_by'] : $planData['user_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 Organization data
        $orgData = $organizationModel->where('org_id', $planData['org_id'])->first();

        //current plan status
        $status = getCurrentPlanStatus($planId);

        $statusHtml = '<h4>Trip Status:</h4>';
        $statusHtml .= '<ul>';
        foreach ($status as $key => $value) {

            if (isset($value['a1_status'])) {
                $statusHtml .= '<li style="margin-bottom: 5px;"><strong>Approver 1:</strong> ' . $value['a1_status'] . '</li>';
            }

            if (isset($value['a2_status'])) {
                $statusHtml .= '<li style="margin-bottom: 5px;"><strong>Approver 2:</strong> ' . $value['a2_status'] . '</li>';
            }

            if (isset($value['a3_status'])) {
                $statusHtml .= '<li style="margin-bottom: 5px;"><strong>Approver 3:</strong> ' . $value['a3_status'] . '</li>';
            }

            if (isset($value['a4_status'])) {
                $statusHtml .= '<li style="margin-bottom: 5px;"><strong>Approver 4:</strong> ' . $value['a4_status'] . '</li>';
            }
        }
        $statusHtml .= '</ul>';
        $userData['status_details'] =  $statusHtml;

        if($action == 'A'){ $template = 'plan_approval_notification_to_traveller'; }else{ $template = 'plan_rejection_notification_to_traveller';  }
        
        
        // send mail to traveller
        send_email($orgData['org_id'] , $userData['email'], $template , $userData , $planData);

        
        
    }
}

if (!function_exists('sendPlanUpdationMail')) {
    function sendPlanUpdationMail($planId)
    {
        $planModel = new PlanModel();
        $userModel = new UserModel();
        $organizationModel = new OrganizationModel();
        $planStatusModel = new PlanStatusModel();

        // Fetch plan data
        $planData = $planModel->where('plan_id', $planId)->first();
        if (!$planData) { return false; }
        $userId = isset($planData['traveller_id']) && !empty($planData['traveller_id']) ? $planData['created_by'] : $planData['user_id'];

        $currentStatus = $planData['status'];
        if($currentStatus != 1){
            $planModel->set(['status'=>1])->where('plan_id', $planId)->update();
            $planStatusModel->set(['is_a1_action_done'=>0, 'a1_reject_reason'=>null, 'is_a2_action_done'=>0, 'a2_reject_reason'=>null, 'is_a3_action_done'=>0, 'a3_reject_reason'=>null,])->where('plan_id', $planId)->update();
        }

        // Fetch user data
        $userData = $userModel->where('user_id', $userId)->first();
        
        // send mail to traveller
        send_email($planData['org_id'] , $userData['email'], 'plan_updation_notification_to_traveller' , $userData , $planData);

        // send mail to approver
        $action = getPlanApproverAction($planId);
    
        foreach ($action['approver_data'] as $key => $value) {

             // Skip if not active
             if ($value['status'] !== 'active') { continue; }
             // Skip if already completed
             if ($value['is_action_done'] == 1) { continue; }
             // Skip if action is None
             if ($value['action'] === 'None') { continue; }
             // mail success check
             if ($value['is_mail_send'] === 1) { continue; }

            if($value['action'] == 'Approval'){ $template = 'plan_updation_approval_notification_to_approver'; }else if($value['action'] == 'Notification'){ $template = 'plan_updation_notification_to_approver'; }
            
            $userData = $userModel->where('user_id', $value['user_id'])->first();

            $url = urlButton($planId, $value['user_id']);
    
            $res = send_email($userData['org_id'] , $userData['email'], $template , $userData , $planData, $url);     
            if($res['status'] = 'success')
            {
                $planStatusModel->set([ $value['mail_send_key'] => 1 ])->where('plan_id', $planId)->where('is_active', 1)->update(); 
            }

            // if action is notification update the action status as 1 (done)
            $parallelProcessValue =  $action['parallel_process_from'];
            if($value['action'] == 'Notification'){ 

                $planStatusModel->set([ $value['action_done_key'] => 1 ])
                                ->where('plan_id', $planId)
                                ->where($value['action_key'], 'Notification')
                                ->where('is_active', 1)
                                ->update(); 

                if($parallelProcessValue == 2 &&  $value['action_key'] == 'a1_action')
                {
                    sendPlanCreationMail($planId , 'send_mail_to_only_approver');
                }
                if($parallelProcessValue == 3 && ($value['action_key'] == 'a1_action' || $value['action_key'] == 'a2_action') )
                {
                    sendPlanCreationMail($planId , 'send_mail_to_only_approver');
                }
                if($parallelProcessValue == 4 && ($value['action_key'] == 'a1_action' || $value['action_key'] == 'a2_action' || $value['action_key'] == 'a3_action'))
                {
                    sendPlanCreationMail($planId , 'send_mail_to_only_approver');
                }

            }

            //delegation part
            $delegationUser = $userModel->where('user_id', $value['user_id'])
                                        ->where('is_active', 1)
                                        ->where('delegation_start_date <=',  date('Y-m-d'))
                                        ->where('delegation_end_date >=',  date('Y-m-d'))
                                        ->first();
            if($delegationUser){
                $delegatedToUserId = $delegationUser['delegated_to_user_id'];

                $delegatedUserData = $userModel->where('user_id', $delegatedToUserId)->first();

                $url = urlButton($planId, $value['user_id'] , $delegatedToUserId);
        
                send_email($delegatedUserData['org_id'] , $delegatedUserData['email'], $template , $delegatedUserData , $planData, $url);
            }

        }
      
        
    }
}

if (!function_exists('sendUserCreationMail')) {
    function sendUserCreationMail($mailData)
    {

        // Fetch Organization data
        $organizationModel = new OrganizationModel();
        $orgData = $organizationModel->where('org_id', $mailData['org_id'] )->first();
        
         // Fetch Template data
         $mailTemplateModel = new MailTemplateModel();
         $templateData = $mailTemplateModel->where('org_id', $mailData['org_id'] )->where('template_name', $mailData['template'] )->first();

         //replace the placeholder
         foreach ($mailData as $key => $value) {
             $placeHolder = '%'.$key.'%';
             $templateData['body_html'] = str_replace($placeHolder, $value ?? '', $templateData['body_html']);
         }

         $subject = $templateData['subject'];
         $html = $templateData['body_html'];
         $toEmailId = $mailData['email'];


          // Set up ZeptoMail API request
          $endpoint = "https://api.zeptomail.com/v1.1/email";
          $apiKey = env('ZOHO_API_KEY');
          $sender = env('ZOHO_SENDER_MAIL');

          $payload = [
              "from" => [
                  "address" => $sender,
                  "name" => $orgData['name'] ?? "TripApprovalTool"
              ],
              "to" => [
                  ["email_address" => ["address" => $toEmailId]]
              ],
              "subject" => $subject,
              "htmlbody" => $html,
          ];

          $headers = [
              "Content-Type: application/json",
              "Authorization: Zoho-enczapikey " . $apiKey
          ];

          $ch = curl_init();
          curl_setopt($ch, CURLOPT_URL, $endpoint);
          curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
          curl_setopt($ch, CURLOPT_POST, true);
          curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($payload));
          curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

          $response = curl_exec($ch);
          $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);

          if (curl_errno($ch)) {
              $error_msg = curl_error($ch);
              log_message('error', "[EMAIL ERROR] Curl failed: {$error_msg}");
              return ['status' => 'failed', 'code' => 500, 'message' => 'Curl error', 'error' => $error_msg];
          }

          curl_close($ch);

          $resp = json_decode($response, true);

          if ($httpCode === 200 && isset($resp['request_id'])) {
              log_message('info', "[EMAIL SENT] To: {$toEmailId}, Template: {$mailData['template']}");
              return ['status' => 'success', 'code' => 200, 'message' => 'Email sent successfully', 'data' => $toEmailId];
          } else {
              log_message('error', "[EMAIL FAILED] HTTP: {$httpCode}, Response: {$response}");
              return ['status' => 'failed', 'code' => $httpCode, 'message' => 'Email sending failed', 'response' => $response];
          }


        //  $email = \Config\Services::email();
        //     $email->initialize([
        //         'protocol' => 'smtp',
        //         'SMTPHost' => $orgData['mail_host'],
        //         'SMTPUser' => $orgData['mail_user_name'],
        //         'SMTPPass' => $orgData['mail_password'],
        //         'SMTPPort' => (int)$orgData['mail_port'],
        //         'mailType' => 'html'
        //     ]);
        //     $email->setFrom($orgData['sender_email'], $orgData['name']);
        //     $email->setTo($toEmailId);
        //     $email->setSubject($subject);
        //     $email->setMessage($html);
        
          

        //     if ($email->send()) {
               
        //         log_message('debug', 'Email Success to ' . $toEmailId);
        //         return ['status' => 'success', 'code' => 200, 'message' => 'Email Sent Successfully...', 'data' => $toEmailId];
        //     } else {
        //         log_message('debug', 'Email sending failed: ' . $email->printDebugger(['headers']));
        //         return ['status' => 'failed', 'code' => 404, 'message' => 'Email Sent Failed...', 'data' => $toEmailId];
        //     }

         

    }
}

// if (!function_exists('send_email')) {
    // function send_email($org_id , $toEmailId,  $template , $userData , $planData = null, $url = null)
    // {
    //     try {

    //         // Fetch Organization data
    //         $organizationModel = new OrganizationModel();
    //         $orgData = $organizationModel->where('org_id', $org_id )->first();
    //         // Fetch Template data
    //         $mailTemplateModel = new MailTemplateModel();
    //         $templateData = $mailTemplateModel->where('org_id', $org_id )->where('template_name', $template )->first();
    //         log_message('info', "Template : ". $template ." , ToMail : ". $toEmailId);

    //         //replace the placeholder
    //         foreach ($userData as $key => $value) {
    //             $placeHolder = '%'.$key.'%';
    //             $templateData['body_html'] = str_replace($placeHolder, $value ?? '', $templateData['body_html']);
    //         }

    //         if(!empty($planData)){
    //             foreach ($planData as $key => $value) {
    //                 $placeHolder = '%'.$key.'%';
    //                 $templateData['body_html'] = str_replace($placeHolder, $value ?? '', $templateData['body_html']);
    //             }

    //             if($planData['exceptional_plan_reason'] != null && $planData['exceptional_plan_reason'] != '')
    //             {
    //                 $reasonHtmlString = '<table   style="width:100%; border-collapse:collapse; font-family:Arial, sans-serif;">           
    //                                         <tr>
    //                                             <td style="text-align:left;background-color:#ffdbdb;color:#960000;padding:7px 15px;font-weight:bold;border-top-left-radius:5px;border-top-right-radius:5px;border-bottom:1px solid #c65e56;">
    //                                             Reason for travel policy exception 
    //                                             </td>
    //                                         </tr>
    //                                         <tr>
    //                                             <td style="text-align:left;background-color:#fff5f5;color:#960000ab;padding:10px 15px;border-bottom-left-radius:5px;border-bottom-right-radius:5px;">
    //                                                 '.$planData['exceptional_plan_reason'].'
    //                                             </td>   
    //                                         </tr>
    //                                     </table>';

    //                 $templateData['body_html'] = $templateData['body_html'].''.$reasonHtmlString;
    //             }
               


    //         }

    //         if($url != null){
               
    //             $placeHolder = '%trip_review_link%';
    //             $templateData['body_html'] = str_replace($placeHolder, $url , $templateData['body_html']);
                
    //         }

    //         $subject = $templateData['subject'];
    //         $html = $templateData['body_html'];

    //         $email = \Config\Services::email(false);
    //         $email->initialize([
    //             'protocol' => 'smtp',
    //             'SMTPHost' => $orgData['mail_host'],
    //             'SMTPUser' => $orgData['mail_user_name'],
    //             'SMTPPass' => $orgData['mail_password'],
    //             'SMTPPort' => (int)$orgData['mail_port'],
    //             'SMTPCrypto' => 'tls',
    //             'mailType' => 'html',
    //             'charset' => 'utf-8',
    //             'newline' => "\r\n",
    //             'wordWrap' => true,
    //         ]);
            

    //         $email->setFrom($orgData['sender_email'], $orgData['name']);
    //         $email->setTo($toEmailId);
    //         $email->setSubject($subject);
    //         $email->setMessage($html);
        
    //         if(!empty($planData)){
    //             $email->attach($planData['pdf_file_path']);
    //         }

           

    //         // Try sending email
    //         if ($email->send()) {
    //             log_message('info', "[EMAIL SENT] To approver/traveller : {$toEmailId}, Template: {$template}");
    //             return ['status' => 'success', 'code' => 200, 'message' => 'Email sent successfully', 'data' => $toEmailId];
    //         } else {
    //             // Email send failed, log clean debug info
    //             $debugInfo = $email->printDebugger(['headers', 'subject', 'body']);
    //             log_message('error', "[EMAIL FAILED] To approver/traveller : {$toEmailId}, Template: {$template}\nError:\n" . strip_tags($debugInfo));

    //             return ['status' => 'failed', 'code' => 500, 'message' => 'Email sending failed', 'data' => $toEmailId];
    //         }

    //     } catch (\Exception $e) {
    //         log_message('critical', "[EMAIL EXCEPTION] To approver/traveller : {$toEmailId}, Error: " . $e->getMessage().$e->getLine());
    //         return ['status' => 'failed', 'code' => 500, 'message' => 'Exception: ' . $e->getMessage(), 'data' => $toEmailId];
    //     }
    // }


    // if (!function_exists('send_email')) {
    //     function send_email($org_id, $toEmailId, $template, $userData, $planData = null, $url = null)
    //     {
    //         try {
    //             // Load models
    //             $organizationModel = new \App\Models\OrganizationModel();
    //             $mailTemplateModel = new \App\Models\MailTemplateModel();
    
    //             // Fetch organization & template
    //             $orgData = $organizationModel->where('org_id', $org_id)->first();
    //             $templateData = $mailTemplateModel->where('org_id', $org_id)->where('template_name', $template)->first();
    
    //             if (!$orgData || !$templateData) {
    //                 log_message('error', "[EMAIL ERROR] Missing org/template data for org_id={$org_id}, template={$template}");
    //                 return ['status' => 'failed', 'code' => 404, 'message' => 'Missing organization or template data'];
    //             }
    
    //             // Replace placeholders from user data
    //             foreach ($userData as $key => $value) {
    //                 $templateData['body_html'] = str_replace('%' . $key . '%', $value ?? '', $templateData['body_html']);
    //             }
    
    //             // Replace placeholders from plan data
    //             if (!empty($planData)) {
    //                 foreach ($planData as $key => $value) {
    //                     $templateData['body_html'] = str_replace('%' . $key . '%', $value ?? '', $templateData['body_html']);
    //                 }
    
    //                 // Exceptional reason block
    //                 if (!empty($planData['exceptional_plan_reason'])) {
    //                     $reasonHtml = '
    //                         <table style="width:100%; border-collapse:collapse; font-family:Arial, sans-serif;">
    //                             <tr>
    //                                 <td style="text-align:left;background-color:#ffdbdb;color:#960000;padding:7px 15px;font-weight:bold;border-top-left-radius:5px;border-top-right-radius:5px;border-bottom:1px solid #c65e56;">
    //                                     Reason for travel policy exception
    //                                 </td>
    //                             </tr>
    //                             <tr>
    //                                 <td style="text-align:left;background-color:#fff5f5;color:#960000ab;padding:10px 15px;border-bottom-left-radius:5px;border-bottom-right-radius:5px;">
    //                                     ' . esc($planData['exceptional_plan_reason']) . '
    //                                 </td>
    //                             </tr>
    //                         </table>';
    //                     $templateData['body_html'] .= $reasonHtml;
    //                 }
    //             }
    
    //             // Add review URL if present
    //             if ($url !== null) {
    //                 $templateData['body_html'] = str_replace('%trip_review_link%', $url, $templateData['body_html']);
    //             }
    
    //             // Initialize email
    //             $email = \Config\Services::email(false);
    //             $email->initialize([
    //                 'protocol' => 'smtp',
    //                 'SMTPHost' => $orgData['mail_host'],
    //                 'SMTPUser' => $orgData['mail_user_name'],
    //                 'SMTPPass' => $orgData['mail_password'], 
    //                 'SMTPPort' => (int) $orgData['mail_port'],
    //                 // 'SMTPCrypto' => 'tls', // ensure STARTTLS
    //                 'mailType' => 'html',
    //                 'charset' => 'utf-8',
    //                 'newline' => "\r\n",
    //                 'wordWrap' => true,
    //             ]);
    
    //             $email->setFrom($orgData['sender_email'], $orgData['name'] ?? 'TripApprovalTool');
    //             $email->setTo($toEmailId);
    //             $email->setSubject($templateData['subject']);
    //             $email->setMessage($templateData['body_html']);
    
    //             // Attach file if exists
    //             // if (!empty($planData['pdf_file_path']) && file_exists($planData['pdf_file_path'])) {
    //             //     $email->attach($planData['pdf_file_path']);
    //             // }
    //             // $filePath = WRITEPATH . 'pdf/trips/trip_' . $planData['plan_id'] . '.pdf';
    //             // if (!empty($filePath) && file_exists($filePath) && is_readable($filePath)) {

    //             //     $email->attach($filePath, 'attachment', basename($filePath), 'application/pdf');
                    
    //             // } else {
    //             //     log_message('error', "[EMAIL] PDF file not attached. Path: {$filePath}");
    //             // }

    //             $filePath = WRITEPATH . 'pdf/trips/trip_' . $planData['plan_id'] . '.pdf';

    //             if (!empty($filePath) && file_exists($filePath) && is_readable($filePath)) {
    //                 // Read the file content
    //                 $fileContent = file_get_contents($filePath);

    //                 if ($fileContent === false) {
    //                     log_message('error', "[EMAIL] Failed to read PDF file content. Path: {$filePath}");
    //                     // Handle error: perhaps skip attachment or throw an exception
    //                 } else {
    //                     // Attach the file content directly
    //                     $email->attach($fileContent, 'attachment', basename($filePath), 'application/pdf');
    //                     log_message('info', "[EMAIL] PDF file attached successfully. Path: {$filePath}");
    //                 }
    //             } else {
    //                 log_message('error', "[EMAIL] PDF file not attached. Path: {$filePath}");
    //             }
                
    
    //             // Send email
    //             if ($email->send()) {
    //                 log_message('info', "[EMAIL SENT] To: {$toEmailId}, Template: {$template}");
    //                 $email->clear(true); // 'true' clears attachments as well
    //                 return ['status' => 'success', 'code' => 200, 'message' => 'Email sent successfully', 'data' => $toEmailId];
    //             } else {
    //                 // Log full debugger info
    //                 $debug = $email->printDebugger(['headers', 'subject', 'body']);
    //                 log_message('error', "[EMAIL FAILED] To: {$toEmailId}, Template: {$template}\n" . strip_tags($debug));
    //                 $email->clear(true); // 'true' clears attachments as well
    //                 return ['status' => 'failed', 'code' => 500, 'message' => 'Email sending failed', 'debug' => strip_tags($debug)];
    //             }
    
    //         } catch (\Throwable $e) {
    //             log_message('critical', "[EMAIL EXCEPTION] To: {$toEmailId}, Error: " . $e->getMessage() . ' on line ' . $e->getLine());
    //             return ['status' => 'failed', 'code' => 500, 'message' => 'Exception: ' . $e->getMessage()];
    //         }
    //     }
    // }
    
    
// }


// zoho api service
if (!function_exists('send_email')) {
    function send_email($org_id, $toEmailId, $template, $userData, $planData = null, $url = null)
    {
        try {
            $organizationModel = new \App\Models\OrganizationModel();
            $mailTemplateModel = new \App\Models\MailTemplateModel();

            $orgData = $organizationModel->where('org_id', $org_id)->first();
            $templateData = $mailTemplateModel->where('org_id', $org_id)->where('template_name', $template)->first();

            if (!$orgData || !$templateData) {
                log_message('error', "[EMAIL ERROR] Missing org/template data for org_id={$org_id}, template={$template}");
                return ['status' => 'failed', 'code' => 404, 'message' => 'Missing organization or template data'];
            }

            // Replace placeholders
            foreach ($userData as $key => $value) {
                $templateData['body_html'] = str_replace('%' . $key . '%', $value ?? '', $templateData['body_html']);
            }

            if (!empty($planData)) {
                foreach ($planData as $key => $value) {
                    $templateData['body_html'] = str_replace('%' . $key . '%', $value ?? '', $templateData['body_html']);
                }

                if (!empty($planData['exceptional_plan_reason'])) {
                    $templateData['body_html'] .= '
                        <table style="width:100%; border-collapse:collapse; font-family:Arial, sans-serif;">
                            <tr>
                                <td style="text-align:left;background-color:#ffdbdb;color:#960000;padding:7px 15px;font-weight:bold;">
                                    Reason for travel policy exception
                                </td>
                            </tr>
                            <tr>
                                <td style="text-align:left;background-color:#fff5f5;color:#960000ab;padding:10px 15px;">
                                    ' . esc($planData['exceptional_plan_reason']) . '
                                </td>
                            </tr>
                        </table>';
                }
            }

            if ($url !== null) {
                $templateData['body_html'] = str_replace('%trip_review_link%', $url, $templateData['body_html']);
            }

            // Set up ZeptoMail API request
            $endpoint = "https://api.zeptomail.com/v1.1/email";
            $apiKey = env('ZOHO_API_KEY');
            $sender = env('ZOHO_SENDER_MAIL');

            $attachments = [];

            if (!empty($planData)) {
                $filePath = WRITEPATH . 'pdf/trips/trip_' . $planData['plan_id'] . '.pdf';
                if (!empty($filePath) && file_exists($filePath) && is_readable($filePath)) {
                    $attachments[] = [
                        "content" => base64_encode(file_get_contents($filePath)),
                        "mime_type" => "application/pdf",
                        "name" => basename($filePath)
                    ];
                }
            }

            $payload = [
                "from" => [
                    "address" => $sender,
                    "name" => $orgData['name'] ?? "TripApprovalTool"
                ],
                "to" => [
                    ["email_address" => ["address" => $toEmailId]]
                ],
                "subject" => $templateData['subject'],
                "htmlbody" => $templateData['body_html'],
            ];

            if (!empty($attachments)) {
                $payload["attachments"] = $attachments;
            }

            $headers = [
                "Content-Type: application/json",
                "Authorization: Zoho-enczapikey " . $apiKey
            ];

            $ch = curl_init();
            curl_setopt($ch, CURLOPT_URL, $endpoint);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($ch, CURLOPT_POST, true);
            curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($payload));
            curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

            $response = curl_exec($ch);
            $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);

            if (curl_errno($ch)) {
                $error_msg = curl_error($ch);
                log_message('error', "[EMAIL ERROR] Curl failed: {$error_msg}");
                return ['status' => 'failed', 'code' => 500, 'message' => 'Curl error', 'error' => $error_msg];
            }

            curl_close($ch);

            $resp = json_decode($response, true);

            if ($httpCode === 200 && isset($resp['request_id'])) {
                log_message('info', "[EMAIL SENT] To: {$toEmailId}, Template: {$template}");
                return ['status' => 'success', 'code' => 200, 'message' => 'Email sent successfully', 'data' => $toEmailId];
            } else {
                log_message('error', "[EMAIL FAILED] HTTP: {$httpCode}, Response: {$response}");
                return ['status' => 'failed', 'code' => $httpCode, 'message' => 'Email sending failed', 'response' => $response];
            }

        } catch (\Throwable $e) {
            log_message('critical', "[EMAIL EXCEPTION] To: {$toEmailId}, Error: " . $e->getMessage() . ' on line ' . $e->getLine());
            return ['status' => 'failed', 'code' => 500, 'message' => 'Exception: ' . $e->getMessage()];
        }
    }
}

if (!function_exists('send_email_agent')) {
    function send_email_agent($org_id , $plan_id)
    {
        try {

            // Fetch Organization data
            $organizationModel = new OrganizationModel();
            $orgData = $organizationModel->where('org_id', $org_id )->first();
            // Fetch Template data
            $mailTemplateModel = new MailTemplateModel();
            $templateData = $mailTemplateModel->where('org_id', $org_id )->where('template_name', 'plan_notification_to_agent' )->first();

            //Fetch plan data
            $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); }

            // dd($planServices);



            //Fetch Agent Data
            $userModel = new UserModel();
            $userData = $userModel->where('role_id', 5)->where('is_active', 1)->findAll();
            if (!$userData) {
                log_message('error', "User data not found for agent");
                return false;
            }

           

            foreach ($userData as $key => $value) {
                $jsonString = $value['agent_supported_service_ids'];
            
                // Decode JSON string into PHP array
                $agentService = json_decode($jsonString, true);
                $agentServiceArray = [];
                if (is_array($agentService)) {
                    foreach ($agentService as $service) {
                        array_push($agentServiceArray,$service['service_id']);
                    }
                } 

                $common = array_intersect($planServices, $agentServiceArray);

                if (!empty($common)) {

                    // Create a fresh copy of template for each user
                    $htmlTemplate = $templateData['body_html'];


                   //send mail to agent
                   $placeHolderData = [
                                            'agent_name' => $value['first_name'].' '.$value['last_name']
                                      ];

                   foreach ($placeHolderData as $placeHolderkey => $placeHoldervalue) {
                        $placeHolder = '%'.$placeHolderkey.'%';
                        $htmlTemplate = str_replace($placeHolder, $placeHoldervalue ?? '', $htmlTemplate);
                    }

                    $subject = $templateData['subject'];
                    $html = $htmlTemplate;


                     // Set up ZeptoMail API request
                    $endpoint = "https://api.zeptomail.com/v1.1/email";
                    $apiKey = env('ZOHO_API_KEY');
                    $sender = env('ZOHO_SENDER_MAIL');

                    $attachments = [];

                    $filePath = WRITEPATH . 'pdf/trips/trip_' . $planData['plan_id'] . '.pdf';
                    if (!empty($filePath) && file_exists($filePath) && is_readable($filePath)) {
                        $attachments[] = [
                            "content" => base64_encode(file_get_contents($filePath)),
                            "mime_type" => "application/pdf",
                            "name" => basename($filePath)
                        ];
                    }

                    $payload = [
                        "from" => [
                            "address" => $sender,
                            "name" => $orgData['name'] ?? "TripApprovalTool"
                        ],
                        "to" => [
                            ["email_address" => ["address" => $value['email']]]
                        ],
                        "subject" => $subject,
                        "htmlbody" => $html,
                    ];

                    if (!empty($attachments)) {
                        $payload["attachments"] = $attachments;
                    }

                    $headers = [
                        "Content-Type: application/json",
                        "Authorization: Zoho-enczapikey " . $apiKey
                    ];

                    $ch = curl_init();
                    curl_setopt($ch, CURLOPT_URL, $endpoint);
                    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
                    curl_setopt($ch, CURLOPT_POST, true);
                    curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($payload));
                    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

                    $response = curl_exec($ch);
                    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);

                    if (curl_errno($ch)) {
                        $error_msg = curl_error($ch);
                        log_message('error', "[EMAIL ERROR] Curl failed: {$error_msg}");
                        return ['status' => 'failed', 'code' => 500, 'message' => 'Curl error', 'error' => $error_msg];
                    }

                    curl_close($ch);

                    $resp = json_decode($response, true);

                    if ($httpCode === 200 && isset($resp['request_id'])) {
                        log_message('debug', 'Email Success to agent plan_id = ' .$plan_id.'email = ' . $value['email']);
                    } else {
                        log_message('error', "[EMAIL FAILED]  plan_id = {$plan_id}, email = {$value['email']}, HTTP: {$httpCode}, Response: {$response}");
                    }




                    // $email = \Config\Services::email();
                    // $email->initialize([
                    //     'protocol' => 'smtp',
                    //     'SMTPHost' => $orgData['mail_host'],
                    //     'SMTPUser' => $orgData['mail_user_name'],
                    //     'SMTPPass' => $orgData['mail_password'],
                    //     'SMTPPort' => (int)$orgData['mail_port'],
                    //     'mailType' => 'html'
                    // ]);

                    // //trigger_email_to agent
                    // $email->setFrom($orgData['sender_email'], $orgData['name']);
                    // $email->setTo($value['email']);
                    // $email->setSubject($subject);
                    // $email->setMessage($html);
                
                    // if(!empty($planData)){
                    //     $email->attach($planData['pdf_file_path']);
                    // }

                    // if ($email->send()) {
                    
                    //     log_message('debug', 'Email Success to agent plan_id = ' .$plan_id.'email = ' . $value['email']);
                       
                    // } else {
                    //     log_message('debug', 'Email sending failed: agent plan_id = ' .$plan_id.'email = ' . $value['email'].'error = '.$email->printDebugger(['headers']));
                       
                    // }
                }
               
            }
            

            return true;
            
        } catch (\Exception $e) {
            log_message('debug', 'Exception occurred while sending email to agent: ' . $e->getMessage());
        }
    }
}

if (!function_exists('check_mail_config')) {
    function check_mail_config($to_email, $mail_config = [])
    {
        if (empty($mail_config['SMTPHost']) || 
            empty($mail_config['SMTPUser']) || 
            empty($mail_config['SMTPPass']) || 
            empty($mail_config['SMTPPort']) || 
            empty($mail_config['sender_email']) ) {
            return json_encode(['status' => 400, 'message' => 'Incomplete Mail Configuration']);
        }


        $email = \Config\Services::email();
        $email->initialize([
            'protocol' => 'smtp',
            'mailType' => 'html',
            'SMTPHost' => $mail_config['SMTPHost'],
            'SMTPUser' => $mail_config['SMTPUser'],
            'SMTPPass' => $mail_config['SMTPPass'],
            'SMTPPort' => (int)$mail_config['SMTPPort']
        ]);

        $html = '<html><p style="text-align: center;">Test Mail Configuration </p></html>';
        $email->setFrom($mail_config['sender_email'], '');
        $email->setTo($to_email);
        $email->setSubject("Testing Mail Configuration");
        $email->setMessage($html);

        if ($email->send()) {
            return json_encode(['status' => 200, 'message' => 'Email Sent Successfully...']);
        } else {
            log_message('error', 'Email sending failed: ' . $email->printDebugger(['headers']));
            return json_encode(['status' => 404, 'message' => 'Email Sent Failed...']);
        }
    }
}