<?php
defined('BASEPATH') or exit('No direct script access allowed');
class Cron extends CI_Controller
{

    public function __construct()
    {
        parent::__construct();
        header('Access-Control-Allow-Origin: *');
        header('Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept, Access-Control-Request-Method');
        header('Access-Control-Allow-Methods: GET, POST, OPTIONS, PUT, DELETE');
        // // avoiding preflight requests
        $method = $_SERVER['REQUEST_METHOD'];
        if ($method == "OPTIONS") {
            die();
        }

        $this->load->helper('form');
        $this->load->library('upload');
        $this->db->query("SET time_zone = '+03:00'");
    }
    
    
    
 
 public function send_due_date_reminders()
{
    // Current date for comparison
    $current_date = date('Y-m-d');
    $reminder_days = [1, 3, 7]; // Days before due date to send reminders

    // Initialize email library
    $this->load->library('phpmailer_lib');
    $mail = $this->phpmailer_lib->load();
    $mail->isSMTP();
    $mail->Host = 'smarthub.ovalspace.co';
    $mail->SMTPAuth = true;
    $mail->Username = 'notifications@smarthub.ovalspace.co';
    $mail->Password = 'wgw6.)O7sCTy';
    $mail->SMTPSecure = 'ssl';
    $mail->Port = 465;
    $mail->setFrom('notifications@smarthub.ovalspace.co', 'SmartHub Notification');
    $mail->isHTML(true);

    // Admin emails (as per previous functions)
    $admin_emails = ['sam.ejibua@vng.nl', 'racheal.atukwase@vngi.org'];

    // Email template components
    $header = '<div style="background-color: #00A1E5; height: 15px; width: 100%;"></div>'
        . '<div style="background-color: #FDB913; height: 5px; width: 100%;"></div>'
        . '<div style="background-color: #ffffff; text-align: center; padding: 10px 0;">'
        . '<img src="https://api.smarthub.ovalspace.co/files/smart-hub.png" style="height: 150px; width: auto;" alt="SmartHub Logo" />'
        . '</div>';
    $footer = '<div style="font-size: 10px; color: #666; text-align: center; padding: 10px; background-color: #ffffff;">'
        . '© 2025 VNG International | SmartHub<br>'
        . '<a href="https://smarthub.ovalspace.co" style="color: #00A1E5; text-decoration: underline;">Visit SmartHub</a>'
        . '</div>';

    // Process follow_up_activities
    foreach ($reminder_days as $days) {
        $due_date = date('Y-m-d', strtotime($current_date . " +$days days"));
        
        // Query follow_up_activities
        $this->db->select('f.id, f.name, f.due_date, f.parent_activity_id, a.inCharges, p.code as programme_code, q.quarter, y.year');
        $this->db->from('follow_up_activities f');
        $this->db->join('activities a', 'f.parent_activity_id = a.id', 'left');
        $this->db->join('outcomes o', 'a.outcome_id = o.id', 'left');
        $this->db->join('quarters q', 'o.quarter_id = q.id', 'left');
        $this->db->join('years y', 'q.year_id = y.id', 'left');
        $this->db->join('programmes p', 'y.programme_id = p.id', 'left');
        $this->db->where('f.is_active', 1);
        $this->db->where('f.due_date', $due_date);
        $follow_up_activities = $this->db->get()->result_array();

        foreach ($follow_up_activities as $activity) {
            $in_charge_ids = json_decode($activity['inCharges'], true) ?: [];
            $entity_name = $activity['name'] ?? 'Unknown Follow Up Activity';
            $entity_display_type = 'Follow Up Activity';
            $due_date_formatted = date('F j, Y', strtotime($activity['due_date']));
            $app_link = "https://www.smarthub.ovalspace.co/ug/programmes";
            $entity_link = "$app_link/{$activity['programme_code']}/activities/{$activity['quarter']}/{$activity['year']}/{$activity['parent_activity_id']}";

            // Fetch in-charge emails and IDs
            $in_charge_emails = [];
            $in_charge_ids_filtered = [];
            if (!empty($in_charge_ids)) {
                $this->db->select('id, email');
                $this->db->where_in('id', $in_charge_ids);
                $this->db->where('is_active', 1);
                $in_charge_users = $this->db->get('users')->result_array();
                $in_charge_emails = array_column($in_charge_users, 'email');
                $in_charge_ids_filtered = array_column($in_charge_users, 'id');
            }

            // Combine recipients
            $this->db->select('id, email');
            $this->db->where_in('email', $admin_emails);
            $admin_users = $this->db->get('users')->result_array();
            $admin_emails_filtered = array_column($admin_users, 'email');
            $admin_user_ids = array_column($admin_users, 'id');
            $all_emails = array_unique(array_merge($in_charge_emails, $admin_emails_filtered));
            $all_user_ids = array_unique(array_merge($in_charge_ids_filtered, $admin_user_ids));

            if (!empty($all_emails)) {
                // Notification content
                $notification_title = 'Due Date Reminder';
                $notification_message = "Reminder: The {$entity_display_type}: \"{$entity_name}\" is due in {$days} day(s) on {$due_date_formatted}.";
                $email_subject = 'Due Date Reminder Notification';
                $email_body = "<!DOCTYPE html><html><body style='margin: 0; padding: 0; font-family: Arial, sans-serif; background-color: #f4f4f4;'>"
                    . "<table cellpadding='0' cellspacing='0' border='0' width='100%' style='max-width: 600px; margin: 20px auto; background-color: #ffffff; border-radius: 8px; box-shadow: 0 2px 5px rgba(0,0,0,0.1);'>"
                    . "<tr><td>$header</td></tr>"
                    . "<tr><td style='padding: 30px; color: #333; line-height: 1.6;'>"
                    . "<h2 style='color: #333; margin: 0 0 20px;'>Due Date Reminder Notification</h2>"
                    . "<p style='margin: 0 0 15px;'>Dear Team,</p>"
                    . "<p style='margin: 0 0 15px;'>This is a reminder that the <strong>" . htmlspecialchars($entity_display_type) . "</strong>: "
                    . "<a href='$entity_link' style='color: #00A1E5; text-decoration: underline;'>" . htmlspecialchars($entity_name) . "</a> "
                    . "is due in <strong>{$days} day(s)</strong> on <strong>{$due_date_formatted}</strong>.</p>"
                    . "<p style='margin: 0;'>Please ensure all necessary actions are completed by the due date.</p>"
                    . "<p style='margin: 0;'>Regards,<br>SmartHub Team</p>"
                    . "</td></tr>"
                    . "<tr><td align='center'>$footer</td></tr>"
                    . "</table></body></html>";
                $email_alt_body = "Dear Team,\n\nReminder: The {$entity_display_type}: {$entity_name} ($entity_link) is due in {$days} day(s) on {$due_date_formatted}.\n\nPlease ensure all necessary actions are completed.\n\nRegards,\nSmartHub";

                // Send email
                foreach ($all_emails as $email) {
                    // $mail->addAddress($email);
                    $mail->addAddress("kimbowaandrew@gmail.com");
                }
                $mail->Subject = $email_subject;
                $mail->Body = $email_body;
                $mail->AltBody = $email_alt_body;
                if (!$mail->send()) {
                    log_message('error', 'Failed to send due date reminder email for follow_up_activity ID ' . $activity['id'] . ': ' . $mail->ErrorInfo);
                }
                $mail->clearAddresses();

                // Store in-app notifications
                $this->db->trans_start();
                foreach ($all_user_ids as $user_id_to_notify) {
                    $this->db->insert('notifications', [
                        'user_id' => $user_id_to_notify,
                        'type' => 'DUE_DATE_REMINDER',
                        'title' => $notification_title,
                        'message' => $notification_message,
                        'link' => $entity_link,
                        'is_read' => 0,
                        'created_by' => null // System-generated, no specific user
                    ]);
                }
                $this->db->trans_complete();
            }
        }

        // Query sub_activity_follow_up_activities
        $this->db->select('sf.id, sf.name, sf.due_date, sf.parent_sub_activity_id, s.parent_activity_id, a.inCharges, p.code as programme_code, q.quarter, y.year');
        $this->db->from('sub_activity_follow_up_activities sf');
        $this->db->join('sub_activities s', 'sf.parent_sub_activity_id = s.id', 'left');
        $this->db->join('activities a', 's.parent_activity_id = a.id', 'left');
        $this->db->join('outcomes o', 'a.outcome_id = o.id', 'left');
        $this->db->join('quarters q', 'o.quarter_id = q.id', 'left');
        $this->db->join('years y', 'q.year_id = y.id', 'left');
        $this->db->join('programmes p', 'y.programme_id = p.id', 'left');
        $this->db->where('sf.is_active', 1);
        $this->db->where('sf.due_date', $due_date);
        $sub_activity_follow_up_activities = $this->db->get()->result_array();

        foreach ($sub_activity_follow_up_activities as $activity) {
            $in_charge_ids = json_decode($activity['inCharges'], true) ?: [];
            $entity_name = $activity['name'] ?? 'Unknown Sub Activity Follow Up Activity';
            $entity_display_type = 'Sub Activity Follow Up Activity';
            $due_date_formatted = date('F j, Y', strtotime($activity['due_date']));
            $app_link = "https://www.smarthub.ovalspace.co/ug/programmes";
            $entity_link = "$app_link/{$activity['programme_code']}/activities/{$activity['quarter']}/{$activity['year']}/{$activity['parent_activity_id']}";

            // Fetch in-charge emails and IDs
            $in_charge_emails = [];
            $in_charge_ids_filtered = [];
            if (!empty($in_charge_ids)) {
                $this->db->select('id, email');
                $this->db->where_in('id', $in_charge_ids);
                $this->db->where('is_active', 1);
                $in_charge_users = $this->db->get('users')->result_array();
                $in_charge_emails = array_column($in_charge_users, 'email');
                $in_charge_ids_filtered = array_column($in_charge_users, 'id');
            }

            // Combine recipients
            $this->db->select('id, email');
            $this->db->where_in('email', $admin_emails);
            $admin_users = $this->db->get('users')->result_array();
            $admin_emails_filtered = array_column($admin_users, 'email');
            $admin_user_ids = array_column($admin_users, 'id');
            $all_emails = array_unique(array_merge($in_charge_emails, $admin_emails_filtered));
            $all_user_ids = array_unique(array_merge($in_charge_ids_filtered, $admin_user_ids));

            if (!empty($all_emails)) {
                // Notification content
                $notification_title = 'Due Date Reminder';
                $notification_message = "Reminder: The {$entity_display_type}: \"{$entity_name}\" is due in {$days} day(s) on {$due_date_formatted}.";
                $email_subject = 'Due Date Reminder Notification';
                $email_body = "<!DOCTYPE html><html><body style='margin: 0; padding: 0; font-family: Arial, sans-serif; background-color: #f4f4f4;'>"
                    . "<table cellpadding='0' cellspacing='0' border='0' width='100%' style='max-width: 600px; margin: 20px auto; background-color: #ffffff; border-radius: 8px; box-shadow: 0 2px 5px rgba(0,0,0,0.1);'>"
                    . "<tr><td>$header</td></tr>"
                    . "<tr><td style='padding: 30px; color: #333; line-height: 1.6;'>"
                    . "<h2 style='color: #333; margin: 0 0 20px;'>Due Date Reminder Notification</h2>"
                    . "<p style='margin: 0 0 15px;'>Dear Team,</p>"
                    . "<p style='margin: 0 0 15px;'>This is a reminder that the <strong>" . htmlspecialchars($entity_display_type) . "</strong>: "
                    . "<a href='$entity_link' style='color: #00A1E5; text-decoration: underline;'>" . htmlspecialchars($entity_name) . "</a> "
                    . "is due in <strong>{$days} day(s)</strong> on <strong>{$due_date_formatted}</strong>.</p>"
                    . "<p style='margin: 0;'>Please ensure all necessary actions are completed by the due date.</p>"
                    . "<p style='margin: 0;'>Regards,<br>SmartHub Team</p>"
                    . "</td></tr>"
                    . "<tr><td align='center'>$footer</td></tr>"
                    . "</table></body></html>";
                $email_alt_body = "Dear Team,\n\nReminder: The {$entity_display_type}: {$entity_name} ($entity_link) is due in {$days} day(s) on {$due_date_formatted}.\n\nPlease ensure all necessary actions are completed.\n\nRegards,\nSmartHub";

                // Send email
                foreach ($all_emails as $email) {
                    // $mail->addAddress($email);
                    $mail->addAddress("kimbowaandrew@gmail.com");
                }
                $mail->Subject = $email_subject;
                $mail->Body = $email_body;
                $mail->AltBody = $email_alt_body;
                if (!$mail->send()) {
                    log_message('error', 'Failed to send due date reminder email for sub_activity_followup_activity ID ' . $activity['id'] . ': ' . $mail->ErrorInfo);
                }
                $mail->clearAddresses();

                // Store in-app notifications
                $this->db->trans_start();
                foreach ($all_user_ids as $user_id_to_notify) {
                    $this->db->insert('notifications', [
                        'user_id' => $user_id_to_notify,
                        'type' => 'DUE_DATE_REMINDER',
                        'title' => $notification_title,
                        'message' => $notification_message,
                        'link' => $entity_link,
                        'is_read' => 0,
                        'created_by' => null // System-generated, no specific user
                    ]);
                }
                $this->db->trans_complete();
            }
        }
    }

    return $this->output
        ->set_content_type('application/json')
        ->set_status_header(200)
        ->set_output(json_encode(['success' => true, 'message' => 'DUE_DATE_REMINDERS_SENT']));
}

// function to send overdue notifications
// public function send_overdue_activity_notifications()
// {
//     // Current date for comparison
//     $current_date = date('Y-m-d');
//     $current_date_formatted = date('F j, Y');

//     // Initialize email library
//     $this->load->library('phpmailer_lib');
//     $mail = $this->phpmailer_lib->load();
//     $mail->isSMTP();
//     $mail->Host = 'smarthub.ovalspace.co';
//     $mail->SMTPAuth = true;
//     $mail->Username = 'notifications@smarthub.ovalspace.co';
//     $mail->Password = 'wgw6.)O7sCTy';
//     $mail->SMTPSecure = 'ssl';
//     $mail->Port = 465;
//     $mail->setFrom('notifications@smarthub.ovalspace.co', 'SmartHub Notification');
//     $mail->isHTML(true);

//     // Admin emails (consistent with previous functions)
//     $admin_emails = ['sam.ejibua@vng.nl', 'racheal.atukwase@vngi.org'];

//     // Email template components
//     $header = '<div style="background-color: #00A1E5; height: 15px; width: 100%;"></div>'
//         . '<div style="background-color: #FDB913; height: 5px; width: 100%;"></div>'
//         . '<div style="background-color: #ffffff; text-align: center; padding: 10px 0;">'
//         . '<img src="https://api.smarthub.ovalspace.co/files/smart-hub.png" style="height: 150px; width: auto;" alt="SmartHub Logo" />'
//         . '</div>';
//     $footer = '<div style="font-size: 10px; color: #666; text-align: center; padding: 10px; background-color: #ffffff;">'
//         . '© 2025 VNG International | SmartHub<br>'
//         . '<a href="https://smarthub.ovalspace.co" style="color: #00A1E5; text-decoration: underline;">Visit SmartHub</a>'
//         . '</div>';

//     // Process follow_up_activities
//     $this->db->select('f.id, f.name, f.due_date, DATEDIFF(CURRENT_DATE, f.due_date) as days_overdue, f.parent_activity_id, a.inCharges, p.code as programme_code, q.quarter, y.year');
//     $this->db->from('follow_up_activities f');
//     $this->db->join('activities a', 'f.parent_activity_id = a.id', 'left');
//     $this->db->join('outcomes o', 'a.outcome_id = o.id', 'left');
//     $this->db->join('quarters q', 'o.quarter_id = q.id', 'left');
//     $this->db->join('years y', 'q.year_id = y.id', 'left');
//     $this->db->join('programmes p', 'y.programme_id = p.id', 'left');
//     $this->db->where('f.is_active', 1);
//     $this->db->where('f.due_date <', $current_date);
//     $follow_up_activities = $this->db->get()->result_array();

//     foreach ($follow_up_activities as $activity) {
//         $in_charge_ids = json_decode($activity['inCharges'], true) ?: [];
//         $entity_name = $activity['name'] ?? 'Unknown Follow Up Activity';
//         $entity_display_type = 'Follow Up Activity';
//         $days_overdue = $activity['days_overdue'];
//         $app_link = "https://www.smarthub.ovalspace.co/ug/programmes";
//         $entity_link = "$app_link/{$activity['programme_code']}/activities/{$activity['quarter']}/{$activity['year']}/{$activity['parent_activity_id']}";

//         // Fetch in-charge emails and IDs
//         $in_charge_emails = [];
//         $in_charge_ids_filtered = [];
//         if (!empty($in_charge_ids)) {
//             $this->db->select('id, email');
//             $this->db->where_in('id', $in_charge_ids);
//             $this->db->where('is_active', 1);
//             $in_charge_users = $this->db->get('users')->result_array();
//             $in_charge_emails = array_column($in_charge_users, 'email');
//             $in_charge_ids_filtered = array_column($in_charge_users, 'id');
//         }

//         // Combine recipients
//         $this->db->select('id, email');
//         $this->db->where_in('email', $admin_emails);
//         $admin_users = $this->db->get('users')->result_array();
//         $admin_emails_filtered = array_column($admin_users, 'email');
//         $admin_user_ids = array_column($admin_users, 'id');
//         $all_emails = array_unique(array_merge($in_charge_emails, $admin_emails_filtered));
//         $all_user_ids = array_unique(array_merge($in_charge_ids_filtered, $admin_user_ids));

//         if (!empty($all_emails)) {
//             // Notification content
//             $notification_title = 'Overdue Activity Notification';
//             $notification_message = "The {$entity_display_type}: \"{$entity_name}\" is overdue by {$days_overdue} day(s) as of {$current_date_formatted}.";
//             $email_subject = 'Overdue Activity Notification';
//             $email_body = "<!DOCTYPE html><html><body style='margin: 0; padding: 0; font-family: Arial, sans-serif; background-color: #f4f4f4;'>"
//                 . "<table cellpadding='0' cellspacing='0' border='0' width='100%' style='max-width: 600px; margin: 20px auto; background-color: #ffffff; border-radius: 8px; box-shadow: 0 2px 5px rgba(0,0,0,0.1);'>"
//                 . "<tr><td>$header</td></tr>"
//                 . "<tr><td style='padding: 30px; color: #333; line-height: 1.6;'>"
//                 . "<h2 style='color: #333; margin: 0 0 20px;'>Overdue Activity Notification</h2>"
//                 . "<p style='margin: 0 0 15px;'>Dear Team,</p>"
//                 . "<p style='margin: 0 0 15px;'>The <strong>" . htmlspecialchars($entity_display_type) . "</strong>: "
//                 . "<a href='$entity_link' style='color: #00A1E5; text-decoration: underline;'>" . htmlspecialchars($entity_name) . "</a> "
//                 . "is overdue by <strong>{$days_overdue} day(s)</strong> as of <strong>{$current_date_formatted}</strong>.</p>"
//                 . "<p style='margin: 0;'>Please take immediate action to address this overdue activity.</p>"
//                 . "<p style='margin: 0;'>Regards,<br>SmartHub Team</p>"
//                 . "</td></tr>"
//                 . "<tr><td align='center'>$footer</td></tr>"
//                 . "</table></body></html>";
//             $email_alt_body = "Dear Team,\n\nThe {$entity_display_type}: {$entity_name} ($entity_link) is overdue by {$days_overdue} day(s) as of {$current_date_formatted}.\n\nPlease take immediate action.\n\nRegards,\nSmartHub";

//             // Send email
//             foreach ($all_emails as $email) {
//                 // $mail->addAddress($email);
//                 $mail->addAddress('kimbowaandrew@gmail.com');
//             }
//             $mail->Subject = $email_subject;
//             $mail->Body = $email_body;
//             $mail->AltBody = $email_alt_body;
//             if (!$mail->send()) {
//                 log_message('error', 'Failed to send overdue notification email for follow_up_activity ID ' . $activity['id'] . ': ' . $mail->ErrorInfo);
//             }
//             $mail->clearAddresses();

//             // Store in-app notifications
//             $this->db->trans_start();
//             foreach ($all_user_ids as $user_id_to_notify) {
//                 $this->db->insert('notifications', [
//                     'user_id' => $user_id_to_notify,
//                     'type' => 'OVERDUE_ACTIVITY',
//                     'title' => $notification_title,
//                     'message' => $notification_message,
//                     'link' => $entity_link,
//                     'is_read' => 0,
//                     'created_by' => null // System-generated, no specific user
//                 ]);
//             }
//             $this->db->trans_complete();
//         }
//     }

//     // Process sub_activity_follow_up_activities
//     $this->db->select('sf.id, sf.name, sf.due_date, DATEDIFF(CURRENT_DATE, sf.due_date) as days_overdue, sf.parent_sub_activity_id, s.parent_activity_id, a.inCharges, p.code as programme_code, q.quarter, y.year');
//     $this->db->from('sub_activity_follow_up_activities sf');
//     $this->db->join('sub_activities s', 'sf.parent_sub_activity_id = s.id', 'left');
//     $this->db->join('activities a', 's.parent_activity_id = a.id', 'left');
//     $this->db->join('outcomes o', 'a.outcome_id = o.id', 'left');
//     $this->db->join('quarters q', 'o.quarter_id = q.id', 'left');
//     $this->db->join('years y', 'q.year_id = y.id', 'left');
//     $this->db->join('programmes p', 'y.programme_id = p.id', 'left');
//     $this->db->where('sf.is_active', 1);
//     $this->db->where('sf.due_date <', $current_date);
//     $sub_activity_follow_up_activities = $this->db->get()->result_array();

//     foreach ($sub_activity_follow_up_activities as $activity) {
//         $in_charge_ids = json_decode($activity['inCharges'], true) ?: [];
//         $entity_name = $activity['name'] ?? 'Unknown Sub Activity Follow Up Activity';
//         $entity_display_type = 'Sub Activity Follow Up Activity';
//         $days_overdue = $activity['days_overdue'];
//         $app_link = "https://www.smarthub.ovalspace.co/ug/programmes";
//         $entity_link = "$app_link/{$activity['programme_code']}/activities/{$activity['quarter']}/{$activity['year']}/{$activity['parent_activity_id']}";

//         // Fetch in-charge emails and IDs
//         $in_charge_emails = [];
//         $in_charge_ids_filtered = [];
//         if (!empty($in_charge_ids)) {
//             $this->db->select('id, email');
//             $this->db->where_in('id', $in_charge_ids);
//             $this->db->where('is_active', 1);
//             $in_charge_users = $this->db->get('users')->result_array();
//             $in_charge_emails = array_column($in_charge_users, 'email');
//             $in_charge_ids_filtered = array_column($in_charge_users, 'id');
//         }

//         // Combine recipients
//         $this->db->select('id, email');
//         $this->db->where_in('email', $admin_emails);
//         $admin_users = $this->db->get('users')->result_array();
//         $admin_emails_filtered = array_column($admin_users, 'email');
//         $admin_user_ids = array_column($admin_users, 'id');
//         $all_emails = array_unique(array_merge($in_charge_emails, $admin_emails_filtered));
//         $all_user_ids = array_unique(array_merge($in_charge_ids_filtered, $admin_user_ids));

//         if (!empty($all_emails)) {
//             // Notification content
//             $notification_title = 'Overdue Activity Notification';
//             $notification_message = "The {$entity_display_type}: \"{$entity_name}\" is overdue by {$days_overdue} day(s) as of {$current_date_formatted}.";
//             $email_subject = 'Overdue Activity Notification';
//             $email_body = "<!DOCTYPE html><html><body style='margin: 0; padding: 0; font-family: Arial, sans-serif; background-color: #f4f4f4;'>"
//                 . "<table cellpadding='0' cellspacing='0' border='0' width='100%' style='max-width: 600px; margin: 20px auto; background-color: #ffffff; border-radius: 8px; box-shadow: 0 2px 5px rgba(0,0,0,0.1);'>"
//                 . "<tr><td>$header</td></tr>"
//                 . "<tr><td style='padding: 30px; color: #333; line-height: 1.6;'>"
//                 . "<h2 style='color: #333; margin: 0 0 20px;'>Overdue Activity Notification</h2>"
//                 . "<p style='margin: 0 0 15px;'>Dear Team,</p>"
//                 . "<p style='margin: 0 0 15px;'>The <strong>" . htmlspecialchars($entity_display_type) . "</strong>: "
//                 . "<a href='$entity_link' style='color: #00A1E5; text-decoration: underline;'>" . htmlspecialchars($entity_name) . "</a> "
//                 . "is overdue by <strong>{$days_overdue} day(s)</strong> as of <strong>{$current_date_formatted}</strong>.</p>"
//                 . "<p style='margin: 0;'>Please take immediate action to address this overdue activity.</p>"
//                 . "<p style='margin: 0;'>Regards,<br>SmartHub Team</p>"
//                 . "</td></tr>"
//                 . "<tr><td align='center'>$footer</td></tr>"
//                 . "</table></body></html>";
//             $email_alt_body = "Dear Team,\n\nThe {$entity_display_type}: {$entity_name} ($entity_link) is overdue by {$days_overdue} day(s) as of {$current_date_formatted}.\n\nPlease take immediate action.\n\nRegards,\nSmartHub";

//             // Send email
//             foreach ($all_emails as $email) {
//                 // $mail->addAddress($email);
//                 $mail->addAddress('kimbowaandrew@gmail.com');
//             }
//             $mail->Subject = $email_subject;
//             $mail->Body = $email_body;
//             $mail->AltBody = $email_alt_body;
//             if (!$mail->send()) {
//                 log_message('error', 'Failed to send overdue notification email for sub_activity_followup_activity ID ' . $activity['id'] . ': ' . $mail->ErrorInfo);
//             }
//             $mail->clearAddresses();

//             // Store in-app notifications
//             $this->db->trans_start();
//             foreach ($all_user_ids as $user_id_to_notify) {
//                 $this->db->insert('notifications', [
//                     'user_id' => $user_id_to_notify,
//                     'type' => 'OVERDUE_ACTIVITY',
//                     'title' => $notification_title,
//                     'message' => $notification_message,
//                     'link' => $entity_link,
//                     'is_read' => 0,
//                     'created_by' => null // System-generated, no specific user
//                 ]);
//             }
//             $this->db->trans_complete();
//         }
//     }

//     return $this->output
//         ->set_content_type('application/json')
//         ->set_status_header(200)
//         ->set_output(json_encode(['success' => true, 'message' => 'OVERDUE_NOTIFICATIONS_SENT']));
// }
 
 
//  public function send_overdue_activity_notifications()
// {
//     // Current date for comparison
//     $current_date = date('Y-m-d');
//     $current_date_formatted = date('F j, Y');

//     // Initialize email library
//     $this->load->library('phpmailer_lib');
//     $mail = $this->phpmailer_lib->load();
//     $mail->isSMTP();
//     $mail->Host = 'smarthub.ovalspace.co';
//     $mail->SMTPAuth = true;
//     $mail->Username = 'notifications@smarthub.ovalspace.co';
//     $mail->Password = 'wgw6.)O7sCTy';
//     $mail->SMTPSecure = 'ssl';
//     $mail->Port = 465;
//     $mail->setFrom('notifications@smarthub.ovalspace.co', 'SmartHub Notification');
//     $mail->isHTML(true);

//     // Admin emails (consistent with previous functions)
//     $admin_emails = ['sam.ejibua@vng.nl', 'racheal.atukwase@vngi.org'];

//     // Email template components
//     $header = '<div style="background-color: #00A1E5; height: 15px; width: 100%;"></div>'
//         . '<div style="background-color: #FDB913; height: 5px; width: 100%;"></div>'
//         . '<div style="background-color: #ffffff; text-align: center; padding: 10px 0;">'
//         . '<img src="https://api.smarthub.ovalspace.co/files/smart-hub.png" style="height: 150px; width: auto;" alt="SmartHub Logo" />'
//         . '</div>';
//     $footer = '<div style="font-size: 10px; color: #666; text-align: center; padding: 10px; background-color: #ffffff;">'
//         . '© 2025 VNG International | SmartHub<br>'
//         . '<a href="https://smarthub.ovalspace.co" style="color: #00A1E5; text-decoration: underline;">Visit SmartHub</a>'
//         . '</div>';

//     // Process follow_up_activities
//     $this->db->select('f.id, f.name, f.due_date, DATEDIFF(CURRENT_DATE, f.due_date) as days_overdue, f.parent_activity_id, a.inCharges, p.code as programme_code, q.quarter, y.year');
//     $this->db->from('follow_up_activities f');
//     $this->db->join('activities a', 'f.parent_activity_id = a.id', 'left');
//     $this->db->join('outcomes o', 'a.outcome_id = o.id', 'left');
//     $this->db->join('quarters q', 'o.quarter_id = q.id', 'left');
//     $this->db->join('years y', 'q.year_id = y.id', 'left');
//     $this->db->join('programmes p', 'y.programme_id = p.id', 'left');
//     $this->db->where('f.is_active', 1);
//     $this->db->where('f.due_date <', $current_date);
//     $this->db->where('f.status', 'Not Started');
//     $follow_up_activities = $this->db->get()->result_array();

//     foreach ($follow_up_activities as $activity) {
//         $in_charge_ids = json_decode($activity['inCharges'], true) ?: [];
//         $entity_name = $activity['name'] ?? 'Unknown Follow Up Activity';
//         $entity_display_type = 'Follow Up Activity';
//         $days_overdue = $activity['days_overdue'];
//         $app_link = "https://www.smarthub.ovalspace.co/ug/programmes";
//         $entity_link = "$app_link/{$activity['programme_code']}/activities/{$activity['quarter']}/{$activity['year']}/{$activity['parent_activity_id']}";

//         // Fetch in-charge emails and IDs
//         $in_charge_emails = [];
//         $in_charge_ids_filtered = [];
//         if (!empty($in_charge_ids)) {
//             $this->db->select('id, email');
//             $this->db->where_in('id', $in_charge_ids);
//             $this->db->where('is_active', 1);
//             $in_charge_users = $this->db->get('users')->result_array();
//             $in_charge_emails = array_column($in_charge_users, 'email');
//             $in_charge_ids_filtered = array_column($in_charge_users, 'id');
//         }

//         // Combine recipients
//         $this->db->select('id, email');
//         $this->db->where_in('email', $admin_emails);
//         $admin_users = $this->db->get('users')->result_array();
//         $admin_emails_filtered = array_column($admin_users, 'email');
//         $admin_user_ids = array_column($admin_users, 'id');
//         $all_emails = array_unique(array_merge($in_charge_emails, $admin_emails_filtered));
//         $all_user_ids = array_unique(array_merge($in_charge_ids_filtered, $admin_user_ids));

//         if (!empty($all_emails)) {
//             // Notification content
//             $notification_title = 'Overdue Activity Notification';
//             $notification_message = "The {$entity_display_type}: \"{$entity_name}\" is overdue by {$days_overdue} day(s) as of {$current_date_formatted}.";
//             $email_subject = 'Overdue Activity Notification';
//             $email_body = "<!DOCTYPE html><html><body style='margin: 0; padding: 0; font-family: Arial, sans-serif; background-color: #f4f4f4;'>"
//                 . "<table cellpadding='0' cellspacing='0' border='0' width='100%' style='max-width: 600px; margin: 20px auto; background-color: #ffffff; border-radius: 8px; box-shadow: 0 2px 5px rgba(0,0,0,0.1);'>"
//                 . "<tr><td>$header</td></tr>"
//                 . "<tr><td style='padding: 30px; color: #333; line-height: 1.6;'>"
//                 . "<h2 style='color: #333; margin: 0 0 20px;'>Overdue Activity Notification</h2>"
//                 . "<p style='margin: 0 0 15px;'>Dear Team,</p>"
//                 . "<p style='margin: 0 0 15px;'>The <strong>" . htmlspecialchars($entity_display_type) . "</strong>: "
//                 . "<a href='$entity_link' style='color: #00A1E5; text-decoration: underline;'>" . htmlspecialchars($entity_name) . "</a> "
//                 . "is overdue by <strong>{$days_overdue} day(s)</strong> as of <strong>{$current_date_formatted}</strong>.</p>"
//                 . "<p style='margin: 0;'>Please take immediate action to address this overdue activity.</p>"
//                 . "<p style='margin: 0;'>Regards,<br>SmartHub Team</p>"
//                 . "</td></tr>"
//                 . "<tr><td align='center'>$footer</td></tr>"
//                 . "</table></body></html>";
//             $email_alt_body = "Dear Team,\n\nThe {$entity_display_type}: {$entity_name} ($entity_link) is overdue by {$days_overdue} day(s) as of {$current_date_formatted}.\n\nPlease take immediate action.\n\nRegards,\nSmartHub";

//             // Send email
//             foreach ($all_emails as $email) {
//                 $mail->addAddress($email);
//             }
//             $mail->Subject = $email_subject;
//             $mail->Body = $email_body;
//             $mail->AltBody = $email_alt_body;
//             if (!$mail->send()) {
//                 log_message('error', 'Failed to send overdue notification email for follow_up_activity ID ' . $activity['id'] . ': ' . $mail->ErrorInfo);
//             }
//             $mail->clearAddresses();

//             // Store in-app notifications
//             $this->db->trans_start();
//             foreach ($all_user_ids as $user_id_to_notify) {
//                 $this->db->insert('notifications', [
//                     'user_id' => $user_id_to_notify,
//                     'type' => 'OVERDUE_ACTIVITY',
//                     'title' => $notification_title,
//                     'message' => $notification_message,
//                     'link' => $entity_link,
//                     'is_read' => 0,
//                     'created_by' => null // System-generated, no specific user
//                 ]);
//             }
//             $this->db->trans_complete();
//         }
//     }

//     // Process sub_activity_follow_up_activities
//     $this->db->select('sf.id, sf.name, sf.due_date, DATEDIFF(CURRENT_DATE, sf.due_date) as days_overdue, sf.parent_sub_activity_id, s.parent_activity_id, a.inCharges, p.code as programme_code, q.quarter, y.year');
//     $this->db->from('sub_activity_follow_up_activities sf');
//     $this->db->join('sub_activities s', 'sf.parent_sub_activity_id = s.id', 'left');
//     $this->db->join('activities a', 's.parent_activity_id = a.id', 'left');
//     $this->db->join('outcomes o', 'a.outcome_id = o.id', 'left');
//     $this->db->join('quarters q', 'o.quarter_id = q.id', 'left');
//     $this->db->join('years y', 'q.year_id = y.id', 'left');
//     $this->db->join('programmes p', 'y.programme_id = p.id', 'left');
//     $this->db->where('sf.is_active', 1);
//     $this->db->where('sf.due_date <', $current_date);
//     $this->db->where('sf.status', 'Not Started');
//     $sub_activity_follow_up_activities = $this->db->get()->result_array();

//     foreach ($sub_activity_follow_up_activities as $activity) {
//         $in_charge_ids = json_decode($activity['inCharges'], true) ?: [];
//         $entity_name = $activity['name'] ?? 'Unknown Sub Activity Follow Up Activity';
//         $entity_display_type = 'Sub Activity Follow Up Activity';
//         $days_overdue = $activity['days_overdue'];
//         $app_link = "https://www.smarthub.ovalspace.co/ug/programmes";
//         $entity_link = "$app_link/{$activity['programme_code']}/activities/{$activity['quarter']}/{$activity['year']}/{$activity['parent_activity_id']}";

//         // Fetch in-charge emails and IDs
//         $in_charge_emails = [];
//         $in_charge_ids_filtered = [];
//         if (!empty($in_charge_ids)) {
//             $this->db->select('id, email');
//             $this->db->where_in('id', $in_charge_ids);
//             $this->db->where('is_active', 1);
//             $in_charge_users = $this->db->get('users')->result_array();
//             $in_charge_emails = array_column($in_charge_users, 'email');
//             $in_charge_ids_filtered = array_column($in_charge_users, 'id');
//         }

//         // Combine recipients
//         $this->db->select('id, email');
//         $this->db->where_in('email', $admin_emails);
//         $admin_users = $this->db->get('users')->result_array();
//         $admin_emails_filtered = array_column($admin_users, 'email');
//         $admin_user_ids = array_column($admin_users, 'id');
//         $all_emails = array_unique(array_merge($in_charge_emails, $admin_emails_filtered));
//         $all_user_ids = array_unique(array_merge($in_charge_ids_filtered, $admin_user_ids));

//         if (!empty($all_emails)) {
//             // Notification content
//             $notification_title = 'Overdue Activity Notification';
//             $notification_message = "The {$entity_display_type}: \"{$entity_name}\" is overdue by {$days_overdue} day(s) as of {$current_date_formatted}.";
//             $email_subject = 'Overdue Activity Notification';
//             $email_body = "<!DOCTYPE html><html><body style='margin: 0; padding: 0; font-family: Arial, sans-serif; background-color: #f4f4f4;'>"
//                 . "<table cellpadding='0' cellspacing='0' border='0' width='100%' style='max-width: 600px; margin: 20px auto; background-color: #ffffff; border-radius: 8px; box-shadow: 0 2px 5px rgba(0,0,0,0.1);'>"
//                 . "<tr><td>$header</td></tr>"
//                 . "<tr><td style='padding: 30px; color: #333; line-height: 1.6;'>"
//                 . "<h2 style='color: #333; margin: 0 0 20px;'>Overdue Activity Notification</h2>"
//                 . "<p style='margin: 0 0 15px;'>Dear Team,</p>"
//                 . "<p style='margin: 0 0 15px;'>The <strong>" . htmlspecialchars($entity_display_type) . "</strong>: "
//                 . "<a href='$entity_link' style='color: #00A1E5; text-decoration: underline;'>" . htmlspecialchars($entity_name) . "</a> "
//                 . "is overdue by <strong>{$days_overdue} day(s)</strong> as of <strong>{$current_date_formatted}</strong>.</p>"
//                 . "<p style='margin: 0;'>Please take immediate action to address this overdue activity.</p>"
//                 . "<p style='margin: 0;'>Regards,<br>SmartHub Team</p>"
//                 . "</td></tr>"
//                 . "<tr><td align='center'>$footer</td></tr>"
//                 . "</table></body></html>";
//             $email_alt_body = "Dear Team,\n\nThe {$entity_display_type}: {$entity_name} ($entity_link) is overdue by {$days_overdue} day(s) as of {$current_date_formatted}.\n\nPlease take immediate action.\n\nRegards,\nSmartHub";

//             // Send email
//             foreach ($all_emails as $email) {
//                 $mail->addAddress($email);
//             }
//             $mail->Subject = $email_subject;
//             $mail->Body = $email_body;
//             $mail->AltBody = $email_alt_body;
//             if (!$mail->send()) {
//                 log_message('error', 'Failed to send overdue notification email for sub_activity_followup_activity ID ' . $activity['id'] . ': ' . $mail->ErrorInfo);
//             }
//             $mail->clearAddresses();

//             // Store in-app notifications
//             $this->db->trans_start();
//             foreach ($all_user_ids as $user_id_to_notify) {
//                 $this->db->insert('notifications', [
//                     'user_id' => $user_id_to_notify,
//                     'type' => 'OVERDUE_ACTIVITY',
//                     'title' => $notification_title,
//                     'message' => $notification_message,
//                     'link' => $entity_link,
//                     'is_read' => 0,
//                     'created_by' => null // System-generated, no specific user
//                 ]);
//             }
//             $this->db->trans_complete();
//         }
//     }

//     return $this->output
//         ->set_content_type('application/json')
//         ->set_status_header(200)
//         ->set_output(json_encode(['success' => true, 'message' => 'OVERDUE_NOTIFICATIONS_SENT']));
// }


public function send_overdue_activity_notifications()
{
    // Current date for comparison
    $current_date = date('Y-m-d');
    $current_date_formatted = date('F j, Y');

    // Initialize email library
    $this->load->library('phpmailer_lib');
    $mail = $this->phpmailer_lib->load();
    $mail->isSMTP();
    $mail->Host = 'smarthub.ovalspace.co';
    $mail->SMTPAuth = true;
    $mail->Username = 'notifications@smarthub.ovalspace.co';
    $mail->Password = 'wgw6.)O7sCTy';
    $mail->SMTPSecure = 'ssl';
    $mail->Port = 465;
    $mail->setFrom('notifications@smarthub.ovalspace.co', 'SmartHub Notification');
    $mail->isHTML(true);

    // Admin emails (consistent with previous functions)
    $admin_emails = ['sam.ejibua@vng.nl', 'racheal.atukwase@vngi.org'];

    // Email template components
    $header = '<div style="background-color: #00A1E5; height: 15px; width: 100%;"></div>'
        . '<div style="background-color: #FDB913; height: 5px; width: 100%;"></div>'
        . '<div style="background-color: #ffffff; text-align: center; padding: 10px 0;">'
        . '<img src="https://api.smarthub.ovalspace.co/files/smart-hub.png" style="height: 150px; width: auto;" alt="SmartHub Logo" />'
        . '</div>';
    $footer = '<div style="font-size: 10px; color: #666; text-align: center; padding: 10px; background-color: #ffffff;">'
        . '© 2025 VNG International | SmartHub<br>'
        . '<a href="https://smarthub.ovalspace.co" style="color: #00A1E5; text-decoration: underline;">Visit SmartHub</a>'
        . '</div>';

    // Process follow_up_activities
    $this->db->select('f.id, f.name, f.due_date, DATEDIFF(CURRENT_DATE, f.due_date) as days_overdue, f.parent_activity_id, a.inCharges, p.code as programme_code, q.quarter, y.year');
    $this->db->from('follow_up_activities f');
    $this->db->join('activities a', 'f.parent_activity_id = a.id', 'left');
    $this->db->join('outcomes o', 'a.outcome_id = o.id', 'left');
    $this->db->join('quarters q', 'o.quarter_id = q.id', 'left');
    $this->db->join('years y', 'q.year_id = y.id', 'left');
    $this->db->join('programmes p', 'y.programme_id = p.id', 'left');
    $this->db->where('f.is_active', 1);
    $this->db->where('f.due_date <', $current_date);
    $this->db->where('f.status', 'Not Started');
    $follow_up_activities = $this->db->get()->result_array();

    foreach ($follow_up_activities as $activity) {
        $in_charge_ids = json_decode($activity['inCharges'], true) ?: [];
        $entity_name = $activity['name'] ?? 'Unknown Follow Up Activity';
        $entity_display_type = 'Follow Up Activity';
        $days_overdue = $activity['days_overdue'];
        $app_link = "https://www.smarthub.ovalspace.co/ug/programmes";
        $entity_link = "$app_link/{$activity['programme_code']}/activities/{$activity['quarter']}/{$activity['year']}/{$activity['parent_activity_id']}";

        // Fetch in-charge emails and IDs
        $in_charge_emails = [];
        $in_charge_ids_filtered = [];
        if (!empty($in_charge_ids)) {
            $this->db->select('id, email');
            $this->db->where_in('id', $in_charge_ids);
            $this->db->where('is_active', 1);
            $in_charge_users = $this->db->get('users')->result_array();
            $in_charge_emails = array_column($in_charge_users, 'email');
            $in_charge_ids_filtered = array_column($in_charge_users, 'id');
        }

        // Combine recipients
        $this->db->select('id, email');
        $this->db->where_in('email', $admin_emails);
        $admin_users = $this->db->get('users')->result_array();
        $admin_emails_filtered = array_column($admin_users, 'email');
        $admin_user_ids = array_column($admin_users, 'id');
        $all_emails = array_unique(array_merge($in_charge_emails, $admin_emails_filtered));
        $all_user_ids = array_unique(array_merge($in_charge_ids_filtered, $admin_user_ids));

        if (!empty($all_emails)) {
            // Notification content
            $notification_title = 'Overdue Activity Notification';
            $notification_message = "The {$entity_display_type}: \"{$entity_name}\" is overdue by {$days_overdue} day(s) as of {$current_date_formatted}.";
            $email_subject = 'Overdue Activity Notification';
            $email_body = "<!DOCTYPE html><html><body style='margin: 0; padding: 0; font-family: Arial, sans-serif; background-color: #f4f4f4;'>"
                . "<table cellpadding='0' cellspacing='0' border='0' width='100%' style='max-width: 600px; margin: 20px auto; background-color: #ffffff; border-radius: 8px; box-shadow: 0 2px 5px rgba(0,0,0,0.1);'>"
                . "<tr><td>$header</td></tr>"
                . "<tr><td style='padding: 30px; color: #333; line-height: 1.6;'>"
                . "<h2 style='color: #333; margin: 0 0 20px;'>Overdue Activity Notification</h2>"
                . "<p style='margin: 0 0 15px;'>Dear Team,</p>"
                . "<p style='margin: 0 0 15px;'>The <strong>" . htmlspecialchars($entity_display_type) . "</strong>: "
                . "<a href='$entity_link' style='color: #00A1E5; text-decoration: underline;'>" . htmlspecialchars($entity_name) . "</a> "
                . "is overdue by <strong>{$days_overdue} day(s)</strong> as of <strong>{$current_date_formatted}</strong>.</p>"
                . "<p style='margin: 0;'>Please take immediate action to address this overdue activity.</p>"
                . "<p style='margin: 0;'>Regards,<br>SmartHub Team</p>"
                . "</td></tr>"
                . "<tr><td align='center'>$footer</td></tr>"
                . "</table></body></html>";
            $email_alt_body = "Dear Team,\n\nThe {$entity_display_type}: {$entity_name} ($entity_link) is overdue by {$days_overdue} day(s) as of {$current_date_formatted}.\n\nPlease take immediate action.\n\nRegards,\nSmartHub";

            // Send email
            foreach ($all_emails as $email) {
                // $mail->addAddress($email);
                $mail->addAddress('kimbowaandrew@gmail.com');
            }
            $mail->Subject = $email_subject;
            $mail->Body = $email_body;
            $mail->AltBody = $email_alt_body;
            if (!$mail->send()) {
                log_message('error', 'Failed to send overdue notification email for follow_up_activity ID ' . $activity['id'] . ': ' . $mail->ErrorInfo);
            }
            $mail->clearAddresses();

            // Store in-app notifications
            $this->db->trans_start();
            foreach ($all_user_ids as $user_id_to_notify) {
                $this->db->insert('notifications', [
                    'user_id' => $user_id_to_notify,
                    'type' => 'OVERDUE_ACTIVITY',
                    'title' => $notification_title,
                    'message' => $notification_message,
                    'link' => $entity_link,
                    'is_read' => 0,
                    'created_by' => null // System-generated, no specific user
                ]);
            }
            $this->db->trans_complete();
        }
    }

    // Process sub_activity_follow_up_activities
    $this->db->select('sf.id, sf.name, sf.due_date, DATEDIFF(CURRENT_DATE, sf.due_date) as days_overdue, sf.parent_sub_activity_id, s.parent_activity_id, s.name as sub_activity_name, a.inCharges, p.code as programme_code, q.quarter, y.year');
    $this->db->from('sub_activity_follow_up_activities sf');
    $this->db->join('sub_activities s', 'sf.parent_sub_activity_id = s.id', 'left');
    $this->db->join('activities a', 's.parent_activity_id = a.id', 'left');
    $this->db->join('outcomes o', 'a.outcome_id = o.id', 'left');
    $this->db->join('quarters q', 'o.quarter_id = q.id', 'left');
    $this->db->join('years y', 'q.year_id = y.id', 'left');
    $this->db->join('programmes p', 'y.programme_id = p.id', 'left');
    $this->db->where('sf.is_active', 1);
    $this->db->where('sf.due_date <', $current_date);
    $this->db->where('sf.status', 'Not Started');
    $sub_activity_follow_up_activities = $this->db->get()->result_array();

    foreach ($sub_activity_follow_up_activities as $activity) {
        $in_charge_ids = json_decode($activity['inCharges'], true) ?: [];
        $entity_name = $activity['name'] ?? 'Unknown Follow Up Activity';
        $sub_activity_name = $activity['sub_activity_name'] ?? 'Unknown Sub Activity';
        $entity_display_type = "Sub Activity '$sub_activity_name' Follow Up Activity";
        $days_overdue = $activity['days_overdue'];
        $app_link = "https://www.smarthub.ovalspace.co/ug/programmes";
        $entity_link = "$app_link/{$activity['programme_code']}/activities/{$activity['quarter']}/{$activity['year']}/{$activity['parent_activity_id']}";

        // Fetch in-charge emails and IDs
        $in_charge_emails = [];
        $in_charge_ids_filtered = [];
        if (!empty($in_charge_ids)) {
            $this->db->select('id, email');
            $this->db->where_in('id', $in_charge_ids);
            $this->db->where('is_active', 1);
            $in_charge_users = $this->db->get('users')->result_array();
            $in_charge_emails = array_column($in_charge_users, 'email');
            $in_charge_ids_filtered = array_column($in_charge_users, 'id');
        }

        // Combine recipients
        $this->db->select('id, email');
        $this->db->where_in('email', $admin_emails);
        $admin_users = $this->db->get('users')->result_array();
        $admin_emails_filtered = array_column($admin_users, 'email');
        $admin_user_ids = array_column($admin_users, 'id');
        $all_emails = array_unique(array_merge($in_charge_emails, $admin_emails_filtered));
        $all_user_ids = array_unique(array_merge($in_charge_ids_filtered, $admin_user_ids));

        if (!empty($all_emails)) {
            // Notification content
            $notification_title = 'Overdue Activity Notification';
            $notification_message = "The {$entity_display_type}: \"{$entity_name}\" is overdue by {$days_overdue} day(s) as of {$current_date_formatted}.";
            $email_subject = 'Overdue Activity Notification';
            $email_body = "<!DOCTYPE html><html><body style='margin: 0; padding: 0; font-family: Arial, sans-serif; background-color: #f4f4f4;'>"
                . "<table cellpadding='0' cellspacing='0' border='0' width='100%' style='max-width: 600px; margin: 20px auto; background-color: #ffffff; border-radius: 8px; box-shadow: 0 2px 5px rgba(0,0,0,0.1);'>"
                . "<tr><td>$header</td></tr>"
                . "<tr><td style='padding: 30px; color: #333; line-height: 1.6;'>"
                . "<h2 style='color: #333; margin: 0 0 20px;'>Overdue Activity Notification</h2>"
                . "<p style='margin: 0 0 15px;'>Dear Team,</p>"
                . "<p style='margin: 0 0 15px;'>The <strong>" . htmlspecialchars($entity_display_type) . "</strong>: "
                . "<a href='$entity_link' style='color: #00A1E5; text-decoration: underline;'>" . htmlspecialchars($entity_name) . "</a> "
                . "is overdue by <strong>{$days_overdue} day(s)</strong> as of <strong>{$current_date_formatted}</strong>.</p>"
                . "<p style='margin: 0;'>Please take immediate action to address this overdue activity.</p>"
                . "<p style='margin: 0;'>Regards,<br>SmartHub Team</p>"
                . "</td></tr>"
                . "<tr><td align='center'>$footer</td></tr>"
                . "</table></body></html>";
            $email_alt_body = "Dear Team,\n\nThe {$entity_display_type}: {$entity_name} ($entity_link) is overdue by {$days_overdue} day(s) as of {$current_date_formatted}.\n\nPlease take immediate action.\n\nRegards,\nSmartHub";

            // Send email
            foreach ($all_emails as $email) {
                // $mail->addAddress($email);
                 $mail->addAddress('kimbowaandrew@gmail.com');
            }
            $mail->Subject = $email_subject;
            $mail->Body = $email_body;
            $mail->AltBody = $email_alt_body;
            if (!$mail->send()) {
                log_message('error', 'Failed to send overdue notification email for sub_activity_followup_activity ID ' . $activity['id'] . ': ' . $mail->ErrorInfo);
            }
            $mail->clearAddresses();

            // Store in-app notifications
            $this->db->trans_start();
            foreach ($all_user_ids as $user_id_to_notify) {
                $this->db->insert('notifications', [
                    'user_id' => $user_id_to_notify,
                    'type' => 'OVERDUE_ACTIVITY',
                    'title' => $notification_title,
                    'message' => $notification_message,
                    'link' => $entity_link,
                    'is_read' => 0,
                    'created_by' => null // System-generated, no specific user
                ]);
            }
            $this->db->trans_complete();
        }
    }

    return $this->output
        ->set_content_type('application/json')
        ->set_status_header(200)
        ->set_output(json_encode(['success' => true, 'message' => 'OVERDUE_NOTIFICATIONS_SENT']));
}



// public function send_overdue_activity_list_to_admins()
// {
//     // Current date for comparison
//     $current_date = date('Y-m-d');
//     $current_date_formatted = date('F j, Y');

//     // Initialize email library
//     $this->load->library('phpmailer_lib');
//     $mail = $this->phpmailer_lib->load();
//     $mail->isSMTP();
//     $mail->Host = 'smarthub.ovalspace.co';
//     $mail->SMTPAuth = true;
//     $mail->Username = 'notifications@smarthub.ovalspace.co';
//     $mail->Password = 'wgw6.)O7sCTy';
//     $mail->SMTPSecure = 'ssl';
//     $mail->Port = 465;
//     $mail->setFrom('notifications@smarthub.ovalspace.co', 'SmartHub Notification');
//     $mail->isHTML(true);

//     // Admin emails
//     // $admin_emails = ['sam.ejibua@vng.nl', 'racheal.atukwase@vngi.org'];
//     $admin_emails = ['kimbowaandrew@gmail.com'];

//     // Email template components
//     $header = '<div style="background-color: #00A1E5; height: 15px; width: 100%;"></div>'
//         . '<div style="background-color: #FDB913; height: 5px; width: 100%;"></div>'
//         . '<div style="background-color: #ffffff; text-align: center; padding: 10px 0;">'
//         . '<img src="https://api.smarthub.ovalspace.co/files/smart-hub.png" style="height: 150px; width: auto;" alt="SmartHub Logo" />'
//         . '</div>';
//     $footer = '<div style="font-size: 10px; color: #666; text-align: center; padding: 10px; background-color: #ffffff;">'
//         . '© 2025 VNG International | SmartHub<br>'
//         . '<a href="https://smarthub.ovalspace.co" style="color: #00A1E5; text-decoration: underline;">Visit SmartHub</a>'
//         . '</div>';

//     // Fetch overdue follow_up_activities
//     $this->db->select('f.id, f.name, f.due_date, DATEDIFF(CURRENT_DATE, f.due_date) as days_overdue, f.parent_activity_id, a.name as parent_activity_name, p.code as programme_code, q.quarter, y.year');
//     $this->db->from('follow_up_activities f');
//     $this->db->join('activities a', 'f.parent_activity_id = a.id', 'left');
//     $this->db->join('outcomes o', 'a.outcome_id = o.id', 'left');
//     $this->db->join('quarters q', 'o.quarter_id = q.id', 'left');
//     $this->db->join('years y', 'q.year_id = y.id', 'left');
//     $this->db->join('programmes p', 'y.programme_id = p.id', 'left');
//     $this->db->where('f.is_active', 1);
//     $this->db->where('f.due_date <', $current_date);
//     $this->db->where('f.status', 'Not Started');
//     $follow_up_activities = $this->db->get()->result_array();

//     // Fetch overdue sub_activity_follow_up_activities
//     $this->db->select('sf.id, sf.name, sf.due_date, DATEDIFF(CURRENT_DATE, sf.due_date) as days_overdue, sf.parent_sub_activity_id, s.name as sub_activity_name, s.parent_activity_id, a.name as parent_activity_name, p.code as programme_code, q.quarter, y.year');
//     $this->db->from('sub_activity_follow_up_activities sf');
//     $this->db->join('sub_activities s', 'sf.parent_sub_activity_id = s.id', 'left');
//     $this->db->join('activities a', 's.parent_activity_id = a.id', 'left');
//     $this->db->join('outcomes o', 'a.outcome_id = o.id', 'left');
//     $this->db->join('quarters q', 'o.quarter_id = q.id', 'left');
//     $this->db->join('years y', 'q.year_id = y.id', 'left');
//     $this->db->join('programmes p', 'y.programme_id = p.id', 'left');
//     $this->db->where('sf.is_active', 1);
//     $this->db->where('sf.due_date <', $current_date);
//     $this->db->where('sf.status', 'Not Started');
//     $sub_activity_follow_up_activities = $this->db->get()->result_array();

//     // Combine and format the list of overdue activities
//     $activity_list_html = '';
//     $activity_list_text = '';
//     $app_link = "https://www.smarthub.ovalspace.co/ug/programmes";

//     foreach ($follow_up_activities as $activity) {
//         $entity_name = $activity['name'] ?? 'Unknown Follow Up Activity';
//         $parent_activity_name = $activity['parent_activity_name'] ?? 'Unknown Activity';
//         $days_overdue = $activity['days_overdue'];
//         $entity_link = "$app_link/{$activity['programme_code']}/activities/{$activity['quarter']}/{$activity['year']}/{$activity['parent_activity_id']}";

//         $activity_list_html .= "<li>Follow Up Activity '<strong>" . htmlspecialchars($entity_name) . "</strong>' (Parent Activity: '<strong>" . htmlspecialchars($parent_activity_name) . "</strong>') - Overdue by {$days_overdue} day(s) "
//             . "<a href='$entity_link' style='color: #00A1E5; text-decoration: underline;'>View Activity</a></li>";
//         $activity_list_text .= "- Follow Up Activity '$entity_name' (Parent Activity: '$parent_activity_name') - Overdue by $days_overdue day(s) ($entity_link)\n";
//     }

//     foreach ($sub_activity_follow_up_activities as $activity) {
//         $entity_name = $activity['name'] ?? 'Unknown Follow Up Activity';
//         $sub_activity_name = $activity['sub_activity_name'] ?? 'Unknown Sub Activity';
//         $parent_activity_name = $activity['parent_activity_name'] ?? 'Unknown Activity';
//         $days_overdue = $activity['days_overdue'];
//         $entity_link = "$app_link/{$activity['programme_code']}/activities/{$activity['quarter']}/{$activity['year']}/{$activity['parent_activity_id']}";

//         $activity_list_html .= "<li>Sub Activity '<strong>" . htmlspecialchars($sub_activity_name) . "</strong>' Follow Up Activity '<strong>" . htmlspecialchars($entity_name) . "</strong>' (Parent Activity: '<strong>" . htmlspecialchars($parent_activity_name) . "</strong>') - Overdue by {$days_overdue} day(s) "
//             . "<a href='$entity_link' style='color: #00A1E5; text-decoration: underline;'>View Activity</a></li>";
//         $activity_list_text .= "- Sub Activity '$sub_activity_name' Follow Up Activity '$entity_name' (Parent Activity: '$parent_activity_name') - Overdue by $days_overdue day(s) ($entity_link)\n";
//     }

//     // Proceed only if there are overdue activities
//     if (!empty($follow_up_activities) || !empty($sub_activity_follow_up_activities)) {
//         // Fetch admin recipients
//         $this->db->select('id, email');
//         $this->db->where_in('email', $admin_emails);
//         $this->db->where('is_active', 1);
//         $admin_users = $this->db->get('users')->result_array();
//         $admin_emails_filtered = array_column($admin_users, 'email');
//         $admin_user_ids = array_column($admin_users, 'id');

//         if (!empty($admin_emails_filtered)) {
//             // Notification content
//             $notification_title = 'Overdue Activities Summary';
//             $notification_message = "The following activities are overdue and not started as of {$current_date_formatted}:\n" . $activity_list_text;
//             $email_subject = 'Overdue Activities Summary';
//             $email_body = "<!DOCTYPE html><html><body style='margin: 0; padding: 0; font-family: Arial, sans-serif; background-color: #f4f4f4;'>"
//                 . "<table cellpadding='0' cellspacing='0' border='0' width='100%' style='max-width: 600px; margin: 20px auto; background-color: #ffffff; border-radius: 8px; box-shadow: 0 2px 5px rgba(0,0,0,0.1);'>"
//                 . "<tr><td>$header</td></tr>"
//                 . "<tr><td style='padding: 30px; color: #333; line-height: 1.6;'>"
//                 . "<h2 style='color: #333; margin: 0 0 20px;'>Overdue Activities Summary</h2>"
//                 . "<p style='margin: 0 0 15px;'>Dear Admins,</p>"
//                 . "<p style='margin: 0 0 15px;'>The following activities are overdue and have not been started as of <strong>{$current_date_formatted}</strong>:</p>"
//                 . "<ul style='list-style-type: disc; padding-left: 20px; margin: 0 0 15px;'>{$activity_list_html}</ul>"
//                 . "<p style='margin: 0;'>Please review and ensure these activities are addressed promptly.</p>"
//                 . "<p style='margin: 0;'>Regards,<br>SmartHub Team</p>"
//                 . "</td></tr>"
//                 . "<tr><td align='center'>$footer</td></tr>"
//                 . "</table></body></html>";
//             $email_alt_body = "Dear Admins,\n\nThe following activities are overdue and not started as of {$current_date_formatted}:\n\n{$activity_list_text}\nPlease review and ensure these activities are addressed promptly.\n\nRegards,\nSmartHub";

//             // Send email
//             foreach ($admin_emails_filtered as $email) {
//                 $mail->addAddress($email);
//             }
//             $mail->Subject = $email_subject;
//             $mail->Body = $email_body;
//             $mail->AltBody = $email_alt_body;
//             if (!$mail->send()) {
//                 log_message('error', 'Failed to send overdue activities summary email: ' . $mail->ErrorInfo);
//             }
//             $mail->clearAddresses();

//             // Store in-app notifications
//             $this->db->trans_start();
//             foreach ($admin_user_ids as $user_id) {
//                 $this->db->insert('notifications', [
//                     'user_id' => $user_id,
//                     'type' => 'OVERDUE_ACTIVITY_LIST',
//                     'title' => $notification_title,
//                     'message' => $notification_message,
//                     'link' => 'https://www.smarthub.ovalspace.co/ug/programmes', // General link to programmes
//                     'is_read' => 0,
//                     'created_by' => null // System-generated
//                 ]);
//             }
//             $this->db->trans_complete();
//         }
//     }

//     return $this->output
//         ->set_content_type('application/json')
//         ->set_status_header(200)
//         ->set_output(json_encode(['success' => true, 'message' => 'OVERDUE_ACTIVITY_LIST_SENT']));
// }

// public function send_overdue_activity_list_to_admins()
// {
//     // Current date for comparison
//     $current_date = date('Y-m-d');
//     $current_date_formatted = date('F j, Y');

//     // Initialize email library
//     $this->load->library('phpmailer_lib');
//     $mail = $this->phpmailer_lib->load();
//     $mail->isSMTP();
//     $mail->Host = 'smarthub.ovalspace.co';
//     $mail->SMTPAuth = true;
//     $mail->Username = 'notifications@smarthub.ovalspace.co';
//     $mail->Password = 'wgw6.)O7sCTy';
//     $mail->SMTPSecure = 'ssl';
//     $mail->Port = 465;
//     $mail->setFrom('notifications@smarthub.ovalspace.co', 'SmartHub Notification');
//     $mail->isHTML(true);

//     // Admin emails
//     // $admin_emails = ['sam.ejibua@vng.nl', 'racheal.atukwase@vngi.org'];
//     $admin_emails = ['andrew@ovalspace.co','kimbowaandrew@gmail.com'];

//     // Email template components
//     $header = '<div style="background-color: #00A1E5; height: 15px; width: 100%;"></div>'
//         . '<div style="background-color: #FDB913; height: 5px; width: 100%;"></div>'
//         . '<div style="background-color: #ffffff; text-align: center; padding: 10px 0;">'
//         . '<img src="https://api.smarthub.ovalspace.co/files/smart-hub.png" style="height: 150px; width: auto;" alt="SmartHub Logo" />'
//         . '</div>';
//     $footer = '<div style="font-size: 10px; color: #666; text-align: center; padding: 10px; background-color: #ffffff;">'
//         . '© 2025 VNG International | SmartHub<br>'
//         . '<a href="https://smarthub.ovalspace.co" style="color: #00A1E5; text-decoration: underline;">Visit SmartHub</a>'
//         . '</div>';

//     // Fetch overdue follow_up_activities
//     $this->db->select('f.id, f.name, f.due_date, DATEDIFF(CURRENT_DATE, f.due_date) as days_overdue, f.parent_activity_id, a.name as parent_activity_name, p.code as programme_code, q.quarter, y.year');
//     $this->db->from('follow_up_activities f');
//     $this->db->join('activities a', 'f.parent_activity_id = a.id', 'left');
//     $this->db->join('outcomes o', 'a.outcome_id = o.id', 'left');
//     $this->db->join('quarters q', 'o.quarter_id = q.id', 'left');
//     $this->db->join('years y', 'q.year_id = y.id', 'left');
//     $this->db->join('programmes p', 'y.programme_id = p.id', 'left');
//     $this->db->where('f.is_active', 1);
//     $this->db->where('f.due_date <', $current_date);
//     $this->db->where('f.status', 'Not Started');
//     $follow_up_activities = $this->db->get()->result_array();

//     // Fetch overdue sub_activity_follow_up_activities
//     $this->db->select('sf.id, sf.name, sf.due_date, DATEDIFF(CURRENT_DATE, sf.due_date) as days_overdue, sf.parent_sub_activity_id, s.name as sub_activity_name, s.parent_activity_id, a.name as parent_activity_name, p.code as programme_code, q.quarter, y.year');
//     $this->db->from('sub_activity_follow_up_activities sf');
//     $this->db->join('sub_activities s', 'sf.parent_sub_activity_id = s.id', 'left');
//     $this->db->join('activities a', 's.parent_activity_id = a.id', 'left');
//     $this->db->join('outcomes o', 'a.outcome_id = o.id', 'left');
//     $this->db->join('quarters q', 'o.quarter_id = q.id', 'left');
//     $this->db->join('years y', 'q.year_id = y.id', 'left');
//     $this->db->join('programmes p', 'y.programme_id = p.id', 'left');
//     $this->db->where('sf.is_active', 1);
//     $this->db->where('sf.due_date <', $current_date);
//     $this->db->where('sf.status', 'Not Started');
//     $sub_activity_follow_up_activities = $this->db->get()->result_array();

//     // Combine and format the list of overdue activities
//     $activity_list_html = '<table style="width: 100%; border-collapse: collapse; font-family: Arial, sans-serif; margin: 15px 0;">'
//         . '<thead><tr style="background-color: #00A1E5; color: #ffffff;">'
//         . '<th style="padding: 10px; border: 1px solid #ddd; text-align: left;">Activity Type</th>'
//         . '<th style="padding: 10px; border: 1px solid #ddd; text-align: left;">Activity Name</th>'
//         . '<th style="padding: 10px; border: 1px solid #ddd; text-align: left;">Parent Activity</th>'
//         . '<th style="padding: 10px; border: 1px solid #ddd; text-align: center;">Days Overdue</th>'
//         . '<th style="padding: 10px; border: 1px solid #ddd; text-align: center;">View</th>'
//         . '</tr></thead><tbody>';

//     $activity_list_text = "Activity Type | Activity Name | Parent Activity | Days Overdue | View Link\n";
//     $activity_list_text .= str_repeat("-", 100) . "\n";
//     $app_link = "https://www.smarthub.ovalspace.co/ug/programmes";

//     foreach ($follow_up_activities as $index => $activity) {
//         $entity_name = $activity['name'] ?? 'Unknown Follow Up Activity';
//         $parent_activity_name = $activity['parent_activity_name'] ?? 'Unknown Activity';
//         $days_overdue = $activity['days_overdue'];
//         $entity_link = "$app_link/{$activity['programme_code']}/activities/{$activity['quarter']}/{$activity['year']}/{$activity['parent_activity_id']}";
//         $entity_type = 'Follow Up Activity';
//         $row_bg = $index % 2 == 0 ? '#f8f8f8' : '#ffffff';

//         $activity_list_html .= "<tr style='background-color: $row_bg;'>"
//             . "<td style='padding: 10px; border: 1px solid #ddd;'>" . htmlspecialchars($entity_type) . "</td>"
//             . "<td style='padding: 10px; border: 1px solid #ddd;'>" . htmlspecialchars($entity_name) . "</td>"
//             . "<td style='padding: 10px; border: 1px solid #ddd;'>" . htmlspecialchars($parent_activity_name) . "</td>"
//             . "<td style='padding: 10px; border: 1px solid #ddd; text-align: center;'>{$days_overdue}</td>"
//             . "<td style='padding: 10px; border: 1px solid #ddd; text-align: center;'><a href='$entity_link' style='color: #00A1E5; text-decoration: underline;'>View</a></td>"
//             . "</tr>";
//         $activity_list_text .= "$entity_type | $entity_name | $parent_activity_name | $days_overdue | $entity_link\n";
//     }

//     foreach ($sub_activity_follow_up_activities as $index => $activity) {
//         $entity_name = $activity['name'] ?? 'Unknown Follow Up Activity';
//         $sub_activity_name = $activity['sub_activity_name'] ?? 'Unknown Sub Activity';
//         $parent_activity_name = $activity['parent_activity_name'] ?? 'Unknown Activity';
//         $days_overdue = $activity['days_overdue'];
//         $entity_link = "$app_link/{$activity['programme_code']}/activities/{$activity['quarter']}/{$activity['year']}/{$activity['parent_activity_id']}";
//         $entity_type = "Sub Activity '$sub_activity_name' Follow Up Activity";
//         $row_bg = ($index + count($follow_up_activities)) % 2 == 0 ? '#f8f8f8' : '#ffffff';

//         $activity_list_html .= "<tr style='background-color: $row_bg;'>"
//             . "<td style='padding: 10px; border: 1px solid #ddd;'>" . htmlspecialchars($entity_type) . "</td>"
//             . "<td style='padding: 10px; border: 1px solid #ddd;'>" . htmlspecialchars($entity_name) . "</td>"
//             . "<td style='padding: 10px; border: 1px solid #ddd;'>" . htmlspecialchars($parent_activity_name) . "</td>"
//             . "<td style='padding: 10px; border: 1px solid #ddd; text-align: center;'>{$days_overdue}</td>"
//             . "<td style='padding: 10px; border: 1px solid #ddd; text-align: center;'><a href='$entity_link' style='color: #00A1E5; text-decoration: underline;'>View</a></td>"
//             . "</tr>";
//         $activity_list_text .= "$entity_type | $entity_name | $parent_activity_name | $days_overdue | $entity_link\n";
//     }

//     $activity_list_html .= '</tbody></table>';

//     // Proceed only if there are overdue activities
//     if (!empty($follow_up_activities) || !empty($sub_activity_follow_up_activities)) {
//         // Fetch admin recipients
//         $this->db->select('id, email');
//         $this->db->where_in('email', $admin_emails);
//         $this->db->where('is_active', 1);
//         $admin_users = $this->db->get('users')->result_array();
//         $admin_emails_filtered = array_column($admin_users, 'email');
//         $admin_user_ids = array_column($admin_users, 'id');

//         if (!empty($admin_emails_filtered)) {
//             // Notification content
//             $notification_title = 'Overdue Activities Summary';
//             $notification_message = "The following activities are overdue and not started as of {$current_date_formatted}:\n\n{$activity_list_text}";
//             $email_subject = 'Overdue Activities Summary';
//             $email_body = "<!DOCTYPE html><html><body style='margin: 0; padding: 0; font-family: Arial, sans-serif; background-color: #f4f4f4;'>"
//                 . "<table cellpadding='0' cellspacing='0' border='0' width='100%' style='max-width: 600px; margin: 20px auto; background-color: #ffffff; border-radius: 8px; box-shadow: 0 2px 5px rgba(0,0,0,0.1);'>"
//                 . "<tr><td>$header</td></tr>"
//                 . "<tr><td style='padding: 30px; color: #333; line-height: 1.6;'>"
//                 . "<h2 style='color: #333; margin: 0 0 20px;'>Overdue Activities Summary</h2>"
//                 . "<p style='margin: 0 0 15px;'>Dear Admins,</p>"
//                 . "<p style='margin: 0 0 15px;'>The following activities are overdue and have not been started as of <strong>{$current_date_formatted}</strong>:</p>"
//                 . "<div style='overflow-x: auto;'>{$activity_list_html}</div>"
//                 . "<p style='margin: 15px 0 0;'>Please review and ensure these activities are addressed promptly.</p>"
//                 . "<p style='margin: 0;'>Regards,<br>SmartHub Team</p>"
//                 . "</td></tr>"
//                 . "<tr><td align='center'>$footer</td></tr>"
//                 . "</table></body></html>";
//             $email_alt_body = "Dear Admins,\n\nThe following activities are overdue and not started as of {$current_date_formatted}:\n\n{$activity_list_text}\nPlease review and ensure these activities are addressed promptly.\n\nRegards,\nSmartHub";

//             // Send email
//             foreach ($admin_emails_filtered as $email) {
//                 $mail->addAddress($email);
//             }
//             $mail->Subject = $email_subject;
//             $mail->Body = $email_body;
//             $mail->AltBody = $email_alt_body;
//             if (!$mail->send()) {
//                 log_message('error', 'Failed to send overdue activities summary email: ' . $mail->ErrorInfo);
//             }
//             $mail->clearAddresses();

//             // Store in-app notifications
//             $this->db->trans_start();
//             foreach ($admin_user_ids as $user_id) {
//                 $this->db->insert('notifications', [
//                     'user_id' => $user_id,
//                     'type' => 'OVERDUE_ACTIVITY_LIST',
//                     'title' => $notification_title,
//                     'message' => $notification_message,
//                     'link' => 'https://www.smarthub.ovalspace.co/ug/programmes', // General link to programmes
//                     'is_read' => 0,
//                     'created_by' => null // System-generated
//                 ]);
//             }
//             $this->db->trans_complete();
//         }
//     }

//     return $this->output
//          ->set_content_type('application/json')
//          ->set_status_header(200)
//         ->set_output(json_encode(['success' => true, 'message' => 'OVERDUE_ACTIVITY_LIST_SENT']));
// }


public function send_overdue_activity_list_to_admins()
{
    // Current date for comparison
    $current_date = date('Y-m-d');
    $current_date_formatted = date('F j, Y');

    // Initialize email library
    $this->load->library('phpmailer_lib');
    $mail = $this->phpmailer_lib->load();
    $mail->isSMTP();
    $mail->Host = 'smarthub.ovalspace.co';
    $mail->SMTPAuth = true;
    $mail->Username = 'notifications@smarthub.ovalspace.co';
    $mail->Password = 'wgw6.)O7sCTy';
    $mail->SMTPSecure = 'ssl';
    $mail->Port = 465;
    $mail->setFrom('notifications@smarthub.ovalspace.co', 'SmartHub Notification');
    $mail->isHTML(true);

    // Admin emails
    // $admin_emails = ['sam.ejibua@vng.nl', 'racheal.atukwase@vngi.org'];
    
    $admin_emails = ['kimbowaandrew@gmail.com'];

    // Email template components
    $header = '<div style="background-color: #00A1E5; height: 15px; width: 100%;"></div>'
        . '<div style="background-color: #FDB913; height: 5px; width: 100%;"></div>'
        . '<div style="background-color: #ffffff; text-align: center; padding: 10px 0;">'
        . '<img src="https://api.smarthub.ovalspace.co/files/smart-hub.png" style="height: 150px; width: auto;" alt="SmartHub Logo" />'
        . '</div>';
    $footer = '<div style="font-size: 10px; color: #666; text-align: center; padding: 10px; background-color: #ffffff;">'
        . '© 2025 VNG International | SmartHub<br>'
        . '<a href="https://smarthub.ovalspace.co" style="color: #00A1E5; text-decoration: underline;">Visit SmartHub</a>'
        . '</div>';

    // Fetch overdue follow_up_activities
    $this->db->select('f.id, f.name, f.due_date, DATEDIFF(CURRENT_DATE, f.due_date) as days_overdue, f.parent_activity_id, a.name as parent_activity_name, p.code as programme_code, q.quarter, y.year');
    $this->db->from('follow_up_activities f');
    $this->db->join('activities a', 'f.parent_activity_id = a.id', 'left');
    $this->db->join('outcomes o', 'a.outcome_id = o.id', 'left');
    $this->db->join('quarters q', 'o.quarter_id = q.id', 'left');
    $this->db->join('years y', 'q.year_id = y.id', 'left');
    $this->db->join('programmes p', 'y.programme_id = p.id', 'left');
    $this->db->where('f.is_active', 1);
    $this->db->where('f.due_date <', $current_date);
    $this->db->where('f.status', 'Not Started');
    $follow_up_activities = $this->db->get()->result_array();

    // Fetch overdue sub_activity_follow_up_activities
    $this->db->select('sf.id, sf.name, sf.due_date, DATEDIFF(CURRENT_DATE, sf.due_date) as days_overdue, sf.parent_sub_activity_id, s.name as parent_sub_activity_name, s.parent_activity_id, p.code as programme_code, q.quarter, y.year');
    $this->db->from('sub_activity_follow_up_activities sf');
    $this->db->join('sub_activities s', 'sf.parent_sub_activity_id = s.id', 'left');
    $this->db->join('activities a', 's.parent_activity_id = a.id', 'left');
    $this->db->join('outcomes o', 'a.outcome_id = o.id', 'left');
    $this->db->join('quarters q', 'o.quarter_id = q.id', 'left');
    $this->db->join('years y', 'q.year_id = y.id', 'left');
    $this->db->join('programmes p', 'y.programme_id = p.id', 'left');
    $this->db->where('sf.is_active', 1);
    $this->db->where('sf.due_date <', $current_date);
    $this->db->where('sf.status', 'Not Started');
    $sub_activity_follow_up_activities = $this->db->get()->result_array();

    // Combine and format the list of overdue activities
    $activity_list_html = '<table style="width: 100%; border-collapse: collapse; font-family: Arial, sans-serif; margin: 15px 0;">'
        . '<thead><tr style="background-color: #00A1E5; color: #ffffff;">'
        . '<th style="padding: 10px; border: 1px solid #ddd; text-align: left;">Follow-up Activity</th>'
        . '<th style="padding: 10px; border: 1px solid #ddd; text-align: left;">Parent Type</th>'
        . '<th style="padding: 10px; border: 1px solid #ddd; text-align: left;">Parent Activity</th>'
        . '<th style="padding: 10px; border: 1px solid #ddd; text-align: center;">Days Overdue</th>'
        . '<th style="padding: 10px; border: 1px solid #ddd; text-align: center;">View</th>'
        . '</tr></thead><tbody>';

    $activity_list_text = "Activity Name | Activity Type | Parent Activity | Days Overdue | View Link\n";
    $activity_list_text .= str_repeat("-", 100) . "\n";
    $app_link = "https://www.smarthub.ovalspace.co/ug/programmes";

    foreach ($follow_up_activities as $index => $activity) {
        $entity_name = $activity['name'] ?? 'Unknown Follow Up Activity';
        $parent_activity_name = $activity['parent_activity_name'] ?? 'Unknown Activity';
        $days_overdue = $activity['days_overdue'];
        $entity_link = "$app_link/{$activity['programme_code']}/activities/{$activity['quarter']}/{$activity['year']}/{$activity['parent_activity_id']}";
        $entity_type = 'Main Activity Follow Up';
        $row_bg = $index % 2 == 0 ? '#f8f8f8' : '#ffffff';

        $activity_list_html .= "<tr style='background-color: $row_bg;'>"
            . "<td style='padding: 10px; border: 1px solid #ddd;'>" . htmlspecialchars($entity_name) . "</td>"
            . "<td style='padding: 10px; border: 1px solid #ddd;'>" . htmlspecialchars($entity_type) . "</td>"
            . "<td style='padding: 10px; border: 1px solid #ddd;'>" . htmlspecialchars($parent_activity_name) . "</td>"
            . "<td style='padding: 10px; border: 1px solid #ddd; text-align: center;'>{$days_overdue}</td>"
            . "<td style='padding: 10px; border: 1px solid #ddd; text-align: center;'><a href='$entity_link' style='color: #00A1E5; text-decoration: underline;'>View</a></td>"
            . "</tr>";
        $activity_list_text .= "$entity_name | $entity_type | $parent_activity_name | $days_overdue | $entity_link\n";
    }

    foreach ($sub_activity_follow_up_activities as $index => $activity) {
        $entity_name = $activity['name'] ?? 'Unknown Follow Up Activity';
        $parent_sub_activity_name = $activity['parent_sub_activity_name'] ?? 'Unknown Sub Activity';
        $days_overdue = $activity['days_overdue'];
        $entity_link = "$app_link/{$activity['programme_code']}/activities/{$activity['quarter']}/{$activity['year']}/{$activity['parent_activity_id']}";
        $entity_type = 'Sub Activity Follow Up';
        $row_bg = ($index + count($follow_up_activities)) % 2 == 0 ? '#f8f8f8' : '#ffffff';

        $activity_list_html .= "<tr style='background-color: $row_bg;'>"
            . "<td style='padding: 10px; border: 1px solid #ddd;'>" . htmlspecialchars($entity_name) . "</td>"
            . "<td style='padding: 10px; border: 1px solid #ddd;'>" . htmlspecialchars($entity_type) . "</td>"
            . "<td style='padding: 10px; border: 1px solid #ddd;'>" . htmlspecialchars($parent_sub_activity_name) . "</td>"
            . "<td style='padding: 10px; border: 1px solid #ddd; text-align: center;'>{$days_overdue}</td>"
            . "<td style='padding: 10px; border: 1px solid #ddd; text-align: center;'><a href='$entity_link' style='color: #00A1E5; text-decoration: underline;'>View</a></td>"
            . "</tr>";
        $activity_list_text .= "$entity_name | $entity_type | $parent_sub_activity_name | $days_overdue | $entity_link\n";
    }

    $activity_list_html .= '</tbody></table>';

    // Proceed only if there are overdue activities
    if (!empty($follow_up_activities) || !empty($sub_activity_follow_up_activities)) {
        // Fetch admin recipients
        $this->db->select('id, email');
        $this->db->where_in('email', $admin_emails);
        $this->db->where('is_active', 1);
        $admin_users = $this->db->get('users')->result_array();
        $admin_emails_filtered = array_column($admin_users, 'email');
        $admin_user_ids = array_column($admin_users, 'id');

        if (!empty($admin_emails_filtered)) {
            // Notification content
            $notification_title = 'Overdue Activities Summary';
            $notification_message = "The following Follow up activities are overdue and not started as of {$current_date_formatted}:\n\n{$activity_list_text}";
            $email_subject = 'Overdue Activities Summary';
            $email_body = "<!DOCTYPE html><html><body style='margin: 0; padding: 0; font-family: Arial, sans-serif; background-color: #f4f4f4;'>"
                . "<table cellpadding='0' cellspacing='0' border='0' width='100%' style='max-width: 600px; margin: 20px auto; background-color: #ffffff; border-radius: 8px; box-shadow: 0 2px 5px rgba(0,0,0,0.1);'>"
                . "<tr><td>$header</td></tr>"
                . "<tr><td style='padding: 30px; color: #333; line-height: 1.6;'>"
                . "<h2 style='color: #333; margin: 0 0 20px;'>Overdue Activities Summary</h2>"
                . "<p style='margin: 0 0 15px;'>Dear Admins,</p>"
                . "<p style='margin: 0 0 15px;'>The following activities are overdue and have not been started as of <strong>{$current_date_formatted}</strong>:</p>"
                . "<div style='overflow-x: auto;'>{$activity_list_html}</div>"
                . "<p style='margin: 15px 0 0;'>Please review and ensure these activities are addressed promptly.</p>"
                . "<p style='margin: 0;'>Regards,<br>SmartHub Team</p>"
                . "</td></tr>"
                . "<tr><td align='center'>$footer</td></tr>"
                . "</table></body></html>";
            $email_alt_body = "Dear Admins,\n\nThe following activities are overdue and not started as of {$current_date_formatted}:\n\n{$activity_list_text}\nPlease review and ensure these activities are addressed promptly.\n\nRegards,\nSmartHub";

            // Send email
            foreach ($admin_emails_filtered as $email) {
                $mail->addAddress($email);
            }
            $mail->Subject = $email_subject;
            $mail->Body = $email_body;
            $mail->AltBody = $email_alt_body;
            if (!$mail->send()) {
                log_message('error', 'Failed to send overdue activities summary email: ' . $mail->ErrorInfo);
            }
            $mail->clearAddresses();

            // Store in-app notifications
            $this->db->trans_start();
            foreach ($admin_user_ids as $user_id) {
                $this->db->insert('notifications', [
                    'user_id' => $user_id,
                    'type' => 'OVERDUE_ACTIVITY_LIST',
                    'title' => $notification_title,
                    'message' => $notification_message,
                    'link' => 'https://www.smarthub.ovalspace.co/ug/programmes', // General link to programmes
                    'is_read' => 0,
                    'created_by' => null // System-generated
                ]);
            }
            $this->db->trans_complete();
        }
    }

    return $this->output
        ->set_content_type('application/json')
        ->set_status_header(200)
        ->set_output(json_encode(['success' => true, 'message' => 'OVERDUE_ACTIVITY_LIST_SENT']));
}
    
}