<?php
function getActivity_details($conn_rjllearning_specific, $institution_id, $branch_id, $search_string, $class_id, $section_id, $student_id,$date, $limit, $offset)
{
    $sql = "SELECT  count(*) as total_rows FROM  activity_mentor  where institution_id =?";
    $array_params = [$institution_id];
    if ($branch_id != null && $branch_id != 'all') {
        $sql .= " AND (branch_id LIKE ? OR branch_id = 'all')";
        $array_params[] = '%"' . $branch_id . '"%';
    }

    if ($class_id != null && $class_id != 'all') {
        $sql .= " AND (class_id LIKE ? OR class_id = 'all')";
        $array_params[] = '%"' . $class_id . '"%';
    }

    if ($section_id != null && $section_id != 'all') {
        $sql .= " AND (section_id LIKE ? OR section_id = 'all')";
        $array_params[] = '%"' . $section_id . '"%';
    }

    if ($student_id != null && $student_id != 'all') {
        $sql .= " AND (student_id LIKE ? OR student_id = 'all')";
        $array_params[] = '%"' . $student_id . '"%';
    }

    if ($search_string != null) {
        $sql .= " AND (type LIKE ? OR title LIKE ? OR description LIKE ?)";
        $search_term = '%' . $search_string . '%';
        $array_params[] = $search_term;
        $array_params[] = $search_term;
        $array_params[] = $search_term;
    }
    $stmt = $conn_rjllearning_specific->prepare($sql);
    $stmt->execute($array_params);
    $result_total = $stmt->fetchAll();
    $totalrows = $result_total[0]['total_rows'];

    if ($limit == 'all') {
        $sql_query = "SELECT * FROM activity_mentor WHERE institution_id = ? AND type LIKE ?";
        $array_params = [$institution_id, '%' . $search_string . '%'];
      if ($branch_id != null && $branch_id != 'all') {
        $sql_query .= " AND (branch_id LIKE ? OR branch_id = 'all')";
        $array_params[] = '%"' . $branch_id . '"%';
    }

    if ($class_id != null && $class_id != 'all') {
        $sql_query .= " AND (class_id LIKE ? OR class_id = 'all')";
        $array_params[] = '%"' . $class_id . '"%';
    }

    if ($section_id != null && $section_id != 'all') {
        $sql_query .= " AND (section_id LIKE ? OR section_id = 'all')";
        $array_params[] = '%"' . $section_id . '"%';
    }

    if ($student_id != null && $student_id != 'all') {
        $sql_query .= " AND (student_id LIKE ? OR student_id = 'all')";
        $array_params[] = '%"' . $student_id . '"%';
    }

    if ($search_string != null) {
        $sql_query .= " AND (type LIKE ? OR title LIKE ? OR description LIKE ?)";
        $search_term = '%' . $search_string . '%';
        $array_params[] = $search_term;
        $array_params[] = $search_term;
        $array_params[] = $search_term;
    }
        $sql_query .= "order by publish_date desc, publish_time desc";
    } else {

        $sql_query = "SELECT * FROM activity_mentor WHERE institution_id = ?";
        $array_params = [$institution_id];
  if ($branch_id != null && $branch_id != 'all') {
        $sql_query .= " AND (branch_id LIKE ? OR branch_id = 'all')";
        $array_params[] = '%"' . $branch_id . '"%';
    }

    if ($class_id != null && $class_id != 'all') {
        $sql_query .= " AND (class_id LIKE ? OR class_id = 'all')";
        $array_params[] = '%"' . $class_id . '"%';
    }

    if ($section_id != null && $section_id != 'all') {
        $sql_query .= " AND (section_id LIKE ? OR section_id = 'all')";
        $array_params[] = '%"' . $section_id . '"%';
    }

    if ($student_id != null && $student_id != 'all') {
        $sql_query .= " AND (student_id LIKE ? OR student_id = 'all')";
        $array_params[] = '%"' . $student_id . '"%';
    }

    if ($search_string != null) {
        $sql_query .= " AND (type LIKE ? OR title LIKE ? OR description LIKE ?)";
        $search_term = '%' . $search_string . '%';
        $array_params[] = $search_term;
        $array_params[] = $search_term;
        $array_params[] = $search_term;
    }
        $sql_query .= " order by date_created desc, time_created desc ";
        $sql_query .= "LIMIT " . $offset . " ," . $limit . "";
    }
    $stmt = $conn_rjllearning_specific->prepare($sql_query);
    $stmt->execute($array_params);
    $session_rows = $stmt->fetchAll();


    $array_return = [];

    foreach ($session_rows as $rows) {
      $data_to_send = array();

        // Check if the attachment exists and is valid
        if (!empty($rows['attachment'])) {
            // Decode the attachment
            $data_attachment = json_decode($rows['attachment'], true);
            
            // Check if the decoded result is an array (for multiple attachments)
            if (is_array($data_attachment)) {
                // Loop through each attachment if it's an array
                foreach ($data_attachment as $attachment) {
                    // Check if required keys exist
                    if (isset($attachment['filepath']) && isset($attachment['original_name'])) {
                        $filepath = $attachment['filepath'];
                        $originalname = $attachment['original_name'];
        
                        // Fetch the AWS attachment URL
                        $aws_attachment = displayFileFromS3($GLOBALS['s3_learning_bucket'], $GLOBALS['learning_bucketName'], $filepath);
        
                        // Prepare the attachment array
                        $final_array_attachment = array(
                            "filepath" => $aws_attachment,
                            "original_name" => $originalname
                        );
        
                        // Add the attachment array to the main data array
                        $data_to_send[] = $final_array_attachment;
                    }
                }
            } else {
                // If it's a single attachment (not an array)
                if (isset($data_attachment['filepath']) && isset($data_attachment['original_name'])) {
                    $filepath = $data_attachment['filepath'];
                    $originalname = $data_attachment['original_name'];
        
                    // Fetch the AWS attachment URL
                    $aws_attachment = displayFileFromS3($GLOBALS['s3_learning_bucket'], $GLOBALS['learning_bucketName'], $filepath);
        
                    // Prepare the attachment array
                    $final_array_attachment = array(
                        "filepath" => $aws_attachment,
                        "original_name" => $originalname
                    );
        
                    // Add the attachment array to the main data array
                    $data_to_send[] = $final_array_attachment;
                }
            }
        }
        
        // Check if no attachments were found and set to an empty array
        if (empty($data_to_send)) {
            $data_to_send[] = array(); // or you could skip adding anything
        }
        
                // Initialize branches array
              $branch = [];
        // $section_info = [];
        $class_info = [];
        $student_info = [];
        
        
        
        // Handle branch_id
        $branch_id = $rows['branch_id'];
        
        $branch = []; // Initialize branch array
        
        // Decode branch_id if it's a JSON-encoded string
        $branch_ids_array = json_decode($branch_id, true);
        
        // Check if branch_id is 'all'
        if ($branch_id == 'all' || (is_array($branch_ids_array) && in_array('all', $branch_ids_array))) {
            // If branch_id is 'all', return an entry for 'All branches'
            $branch[] = array('branch_id' => 'all', 'branch_name' => 'All branches');
        
        } else {
            // If branch_id is not 'all', ensure it's an array
            if (!empty($branch_ids_array) && is_array($branch_ids_array)) {
                // Implode the array into a comma-separated string
                $imploded_branch_ids = implode(',', array_map('intval', $branch_ids_array)); // Convert to integers for safety
        
                $sql = "SELECT * FROM branch WHERE institution_id = ? AND id IN ($imploded_branch_ids)";
                $stmt = $conn_rjllearning_specific->prepare($sql);
                $stmt->execute([$institution_id]); // Execute query with institution_id
                $branch_rows = $stmt->fetchAll();
        
                foreach ($branch_rows as $branch_data) {
                    $branch[] = array('branch_id' => $branch_data['id'], 'branch_name' => $branch_data['name']);
                }
            }
        }
        
        
        // Handle section_id
        $section_id = $rows['section_id'];
        
        $section = []; // Initialize section array
        
        // Decode section_id in case it's a JSON-encoded string
        $section_ids_array = json_decode($section_id, true);
        
        // Check if section_id is 'all'
        if ($section_id == 'all' || (is_array($section_ids_array) && in_array('all', $section_ids_array))) {
            // If section_id is 'all', return it as the section
            $section[] = array('section_id' => 'all', 'section_name' => 'All Sections');
        } else {
            // If section_id is not 'all', ensure it's an array
            if (!empty($section_ids_array) && is_array($section_ids_array)) {
                // Implode the array into a comma-separated string
                $imploded_section_ids = implode(',', array_map('intval', $section_ids_array)); // Convert to integers for safety
        
                $sql = "SELECT * FROM section_info WHERE institution_id = ? AND id IN ($imploded_section_ids)";
                $array_params = [$institution_id]; // Add institution_id to parameters
                $stmt = $conn_rjllearning_specific->prepare($sql);
                $stmt->execute($array_params);
                $section_rows = $stmt->fetchAll();
        
                foreach ($section_rows as $section_data) {
                    $section[] = array('section_id' => $section_data['id'], 'section_name' => $section_data['section_name']);
                }
            }
        }
        
        
        
        // Handle class_id
        $class_id = $rows['class_id'];
        
        $class_info = []; // Initialize class array
        
        // Decode class_id in case it's a JSON-encoded string
        $class_ids_array = json_decode($class_id, true);
        
        // Check if class_id is 'all'
        if ($class_id == 'all' || (is_array($class_ids_array) && in_array('all', $class_ids_array))) {
           
        
            // Add an entry for 'all' classes
            $class_info[] = array('class_id' => 'all', 'class_name' => 'All Classes');
        } else {
            // If class_id is not 'all', ensure it's an array
            if (!empty($class_ids_array) && is_array($class_ids_array)) {
                // Implode the array into a comma-separated string
                $imploded_class_ids = implode(',', array_map('intval', $class_ids_array)); // Convert to integers for safety
        
                $sql = "SELECT * FROM class_info WHERE institution_id = ? AND id IN ($imploded_class_ids)";
                $array_params = [$institution_id]; // Add institution_id to parameters
                $stmt = $conn_rjllearning_specific->prepare($sql);
                $stmt->execute($array_params);
                $class_rows = $stmt->fetchAll();
        
                foreach ($class_rows as $class_data) {
                    $class_info[] = array('class_id' => $class_data['id'], 'class_name' => $class_data['classname']);
                }
            }
        }
        
        
        
        
        
        
        $student_id = $rows['student_id'];
        // Check if student_id is a string and decode if it's a JSON string
        if (is_string($student_id)) {
            $student_id = json_decode($student_id, true);
        }
        
        // Check if the student_id is 'all'
        if ($student_id === null) {
            // If null, return info for all students
            $student_info = [['student_id' => 'all', 'student_name' => 'All Students']];
        } else  {
            // Ensure student_id is an array
            if (!is_array($student_id)) {
                $student_id = [$student_id];
            }
        
            // Prepare placeholders for the SQL query
            $placeholders = implode(',', array_fill(0, count($student_id), '?'));
            $sql = "SELECT * FROM students WHERE institution_id = ? AND user_id IN ($placeholders)";
        
            // Prepare and execute the SQL statement
            $stmt = $conn_rjllearning_specific->prepare($sql);
            $stmt->execute(array_merge([$institution_id], $student_id));
        
            // Fetch the student rows
            $student_rows = $stmt->fetchAll();
        
            // Prepare student info array
            $student_info = [];
            foreach ($student_rows as $student_data) {
                $student_info[] = array('student_id' => $student_data['user_id'], 'student_name' => $student_data['name']);
            }
        }
        





        $array_return[] = array(
            'activity_id' => $rows['id'],
            'branch_id' => $branch,
            'class_info' => $class_info,
            'section_info' => $section,
            'student_info' => $student_info,
            'type' => $rows['type'],
            'tags' => json_decode($rows['tags'],true),
            'title' => $rows['title'],
            'description' => $rows['description'],
            'activity_attachment' => $data_to_send,
            'publish_date' => $rows['publish_date'],
            'publish_time' => $rows['publish_time'],
            'termination_date' => $rows['termination_date'],
            'termination_time' => $rows['termination_time'],
            'created_by' => $rows['created_by'],
            'date_created' => $rows['date_created'],
            'time_created' => $rows['time_created'],
            'status' => $rows['status']
        );
    }
    if (count($session_rows) < 50) {

        return array('total_rows' => $totalrows, 'activity_info' => $array_return, 'maxreach' => 1);
    } else {
        return array('total_rows' => $totalrows, 'activity_info' => $array_return, 'maxreach' => 0);
    }
}


// function getActivity_details($conn_rjllearning_specific, $institution_id, $branch_id, $search_string, $class_id, $section_id, $student_id,$date, $limit, $offset) {


  

//     $fetched_academic_session = compareDatesAcademicSession($conn_rjllearning_specific, $institution_id, $date, null);

//         if ($date == date("Y-m-d")) {
//             // Query students table when the academic session is active
//             $sql = "SELECT id, name, user_id FROM students 
//                     WHERE institution_id = ? 
//                       AND date_admission <= ? 
//                       AND (date_left > ? OR date_left IS NULL)";
//             $array_params = [$institution_id, $date, $date];
            
//             if ($branch_id != null && $branch_id != 'all') {
//                 $sql .= " AND (branch_id LIKE ? OR branch_id = 'all')";
//                 $array_params[] = '%"' . $branch_id . '"%';
//             }
        
//             if ($class_id != null && $class_id != 'all') {
//                 $sql .= " AND (class_id LIKE ? OR class_id = 'all')";
//                 $array_params[] = '%"' . $class_id . '"%';
//             }
        
//             if ($section_id != null && $section_id != 'all') {
//                 $sql .= " AND (section_id LIKE ? OR section_id = 'all')";
//                 $array_params[] = '%"' . $section_id . '"%';
//             }
        
//             $stmt = $conn_rjllearning_specific->prepare($sql);
//             $stmt->execute($array_params);
//             $students = $stmt->fetchAll(PDO::FETCH_ASSOC);
        
//         } else {
//             // Query cache_academic_students_data table if the session is not active
//             $sql = "SELECT id, name 
//                     FROM students 
//                     WHERE institution_id = ? 
//                       AND branch_id = ? 
//                       AND date_admission <= ? 
//                       AND (date_left > ? OR date_left IS NULL) 
//                       AND id IN (
//                           SELECT student_id 
//                           FROM cache_academic_students_data 
//                           WHERE class_id = ? 
//                             AND section_id = ? 
//                             AND (date, student_id) IN (
//                                 SELECT MAX(date), student_id 
//                                 FROM cache_academic_students_data 
//                                 WHERE institution_id = ? 
//                                   AND branch_id = ? 
//                                   AND date <= ? 
//                                 GROUP BY student_id
//                             )
//                       )";
            
//             $array_params = [$institution_id, $branch_id, $date, $date, $class_id, $section_id, $institution_id, $branch_id, $date];
            
//             $fetch_students = $conn_rjllearning_specific->prepare($sql);
//             $fetch_students->execute($array_params);
//             $students = $fetch_students->fetchAll(PDO::FETCH_ASSOC);
//         }
        
          
//         //     // Print the students data (id and name)
//          $cleaned_students = [];
//         foreach ($students as $student) {
//             $cleaned_students[] = [
//                 'id' => $student['id'],
//                 'name' => $student['name'],
//                 'user_id' => $student['user_id']
//             ];
//         }

 
//     // Step 3: Query activities based on filters
//     $sql = "SELECT COUNT(*) as total_rows FROM activity_mentor WHERE institution_id = ?";
//     $array_params = [$institution_id];

//     if ($branch_id != null && $branch_id != 'all') {
//         $sql .= " AND (branch_id LIKE ? OR branch_id = 'all')";
//         $array_params[] = '%"' . $branch_id . '"%';
//     }

//     if ($class_id != null && $class_id != 'all') {
//         $sql .= " AND (class_id LIKE ? OR class_id = 'all')";
//         $array_params[] = '%"' . $class_id . '"%';
//     }

//     if ($section_id != null && $section_id != 'all') {
//         $sql .= " AND (section_id LIKE ? OR section_id = 'all')";
//         $array_params[] = '%"' . $section_id . '"%';
//     }

//     if ($student_id != null && $student_id != 'all') {
//         $sql .= " AND (student_id LIKE ? OR student_id = 'all')";
//         $array_params[] = '%"' . $student_id . '"%';
//     }

//     if ($search_string != null) {
//         $sql .= " AND (type LIKE ? OR title LIKE ? OR description LIKE ?)";
//         $search_term = '%' . $search_string . '%';
//         $array_params[] = $search_term;
//         $array_params[] = $search_term;
//         $array_params[] = $search_term;
//     }

//     $stmt = $conn_rjllearning_specific->prepare($sql);
//     $stmt->execute($array_params);
//     $result_total = $stmt->fetchAll();
//     $totalrows = $result_total[0]['total_rows'];

//     // Step 4: Query actual activities based on limit and offset
//     $sql_query = "SELECT * FROM activity_mentor WHERE institution_id = ?";
//     $array_params = [$institution_id];

//     if ($branch_id != null && $branch_id != 'all') {
//         $sql_query .= " AND (branch_id LIKE ? OR branch_id = 'all')";
//         $array_params[] = '%"' . $branch_id . '"%';
//     }

//     if ($class_id != null && $class_id != 'all') {
//         $sql_query .= " AND (class_id LIKE ? OR class_id = 'all')";
//         $array_params[] = '%"' . $class_id . '"%';
//     }

//     if ($section_id != null && $section_id != 'all') {
//         $sql_query .= " AND (section_id LIKE ? OR section_id = 'all')";
//         $array_params[] = '%"' . $section_id . '"%';
//     }

//     if ($student_id != null && $student_id != 'all') {
//         $sql_query .= " AND (student_id LIKE ? OR student_id = 'all')";
//         $array_params[] = '%"' . $student_id . '"%';
//     }

//     if ($search_string != null) {
//         $sql_query .= " AND (type LIKE ? OR title LIKE ? OR description LIKE ?)";
//         $search_term = '%' . $search_string . '%';
//         $array_params[] = $search_term;
//         $array_params[] = $search_term;
//         $array_params[] = $search_term;
//     }

//     $sql_query .= " order by date_created desc, time_created desc ";
//     $sql_query .= "LIMIT " . $offset . " ," . $limit . "";

//     $stmt = $conn_rjllearning_specific->prepare($sql_query);
//     $stmt->execute($array_params);
//     $activities = $stmt->fetchAll();

//     // Prepare the data to return
//     $array_return = [];
//     foreach ($activities as $rows) {
        
    
   

// $correct_students = []; // Initialize an empty array for correct students

// // Check if $rows['student_id'] is not 'all'
// if ($rows['student_id'] != 'all') {
//     // Clean $rows['student_id'] to get rid of unwanted characters
//     // Remove the surrounding quotes, brackets and then decode the JSON string into an array
//     $cleaned_student_ids = json_decode($rows['student_id'], true); // Decode JSON into an array

//     // Ensure it's an array, and iterate through it
//     if (is_array($cleaned_student_ids)) {
//         // Iterate through the cleaned_students array
//         foreach ($cleaned_students as $student) {
            
//             // Check if the student's user_id is in the cleaned student IDs
//             if (in_array($student['user_id'], $cleaned_student_ids)) {
//                 $correct_students[] = [
//                     'student_id' => $student['user_id'], // Correctly access the user_id
//                     'student_name' => $student['name']
//                 ];
//             }
//         }
//     }
// } else {
//     // If 'all', include the "all students" entry
//     $correct_students[] = [
//         'student_id' => 'all',
//         'student_name' => 'All Students'
//     ];
// }








// // Debugging: print the correct_students array to check the output


//               $data_to_send = array();

// // Check if the attachment exists and is valid
// if (!empty($rows['attachment'])) {
//     // Decode the attachment
//     $data_attachment = json_decode($rows['attachment'], true);
    
//     // Check if the decoded result is an array (for multiple attachments)
//     if (is_array($data_attachment)) {
//         // Loop through each attachment if it's an array
//         foreach ($data_attachment as $attachment) {
//             // Check if required keys exist
//             if (isset($attachment['filepath']) && isset($attachment['original_name'])) {
//                 $filepath = $attachment['filepath'];
//                 $originalname = $attachment['original_name'];

//                 // Fetch the AWS attachment URL
//                 $aws_attachment = displayFileFromS3($GLOBALS['s3_learning_bucket'], $GLOBALS['learning_bucketName'], $filepath);

//                 // Prepare the attachment array
//                 $final_array_attachment = array(
//                     "filepath" => $aws_attachment,
//                     "original_name" => $originalname
//                 );

//                 // Add the attachment array to the main data array
//                 $data_to_send[] = $final_array_attachment;
//             }
//         }
//     } else {
//         // If it's a single attachment (not an array)
//         if (isset($data_attachment['filepath']) && isset($data_attachment['original_name'])) {
//             $filepath = $data_attachment['filepath'];
//             $originalname = $data_attachment['original_name'];

//             // Fetch the AWS attachment URL
//             $aws_attachment = displayFileFromS3($GLOBALS['s3_learning_bucket'], $GLOBALS['learning_bucketName'], $filepath);

//             // Prepare the attachment array
//             $final_array_attachment = array(
//                 "filepath" => $aws_attachment,
//                 "original_name" => $originalname
//             );

//             // Add the attachment array to the main data array
//             $data_to_send[] = $final_array_attachment;
//         }
//     }
// }

// // Check if no attachments were found and set to an empty array
// if (empty($data_to_send)) {
//     $data_to_send[] = array(); // or you could skip adding anything
// }


//         // Process branches, sections, and classes
//                 // Initialize branches array
//       $branch = [];
// // $section_info = [];
// $class_info = [];
// $student_info = [];



// // Handle branch_id
// $branch_id = $rows['branch_id'];

// $branch = []; // Initialize branch array

// // Decode branch_id if it's a JSON-encoded string
// $branch_ids_array = json_decode($branch_id, true);

// // Check if branch_id is 'all'
// if ($branch_id == 'all' || (is_array($branch_ids_array) && in_array('all', $branch_ids_array))) {
//     // If branch_id is 'all', return an entry for 'All branches'
//     $branch[] = array('branch_id' => 'all', 'branch_name' => 'All branches');

// } else {
//     // If branch_id is not 'all', ensure it's an array
//     if (!empty($branch_ids_array) && is_array($branch_ids_array)) {
//         // Implode the array into a comma-separated string
//         $imploded_branch_ids = implode(',', array_map('intval', $branch_ids_array)); // Convert to integers for safety

//         $sql = "SELECT * FROM branch WHERE institution_id = ? AND id IN ($imploded_branch_ids)";
//         $stmt = $conn_rjllearning_specific->prepare($sql);
//         $stmt->execute([$institution_id]); // Execute query with institution_id
//         $branch_rows = $stmt->fetchAll();

//         foreach ($branch_rows as $branch_data) {
//             $branch[] = array('branch_id' => $branch_data['id'], 'branch_name' => $branch_data['name']);
//         }
//     }
// }


// // Handle section_id
// $section_id = $rows['section_id'];

// $section = []; // Initialize section array

// // Decode section_id in case it's a JSON-encoded string
// $section_ids_array = json_decode($section_id, true);

// // Check if section_id is 'all'
// if ($section_id == 'all' || (is_array($section_ids_array) && in_array('all', $section_ids_array))) {
//     // If section_id is 'all', return it as the section
//     $section[] = array('section_id' => 'all', 'section_name' => 'All Sections');
// } else {
//     // If section_id is not 'all', ensure it's an array
//     if (!empty($section_ids_array) && is_array($section_ids_array)) {
//         // Implode the array into a comma-separated string
//         $imploded_section_ids = implode(',', array_map('intval', $section_ids_array)); // Convert to integers for safety

//         $sql = "SELECT * FROM section_info WHERE institution_id = ? AND id IN ($imploded_section_ids)";
//         $array_params = [$institution_id]; // Add institution_id to parameters
//         $stmt = $conn_rjllearning_specific->prepare($sql);
//         $stmt->execute($array_params);
//         $section_rows = $stmt->fetchAll();

//         foreach ($section_rows as $section_data) {
//             $section[] = array('section_id' => $section_data['id'], 'section_name' => $section_data['section_name']);
//         }
//     }
// }



// // Handle class_id
// $class_id = $rows['class_id'];

// $class_info = []; // Initialize class array

// // Decode class_id in case it's a JSON-encoded string
// $class_ids_array = json_decode($class_id, true);

// // Check if class_id is 'all'
// if ($class_id == 'all' || (is_array($class_ids_array) && in_array('all', $class_ids_array))) {
//     // If class_id is 'all', fetch all classes
//     // $sql = "SELECT * FROM class_info WHERE institution_id = ?";
//     // $stmt = $conn_rjllearning_specific->prepare($sql);
//     // $stmt->execute([$institution_id]);
//     // $class_rows = $stmt->fetchAll();

//     // foreach ($class_rows as $class_data) {
//     //     $class_info[] = array('class_id' => $class_data['id'], 'class_name' => $class_data['classname']);
//     // }

//     // Add an entry for 'all' classes
//     $class_info[] = array('class_id' => 'all', 'class_name' => 'All Classes');
// } else {
//     // If class_id is not 'all', ensure it's an array
//     if (!empty($class_ids_array) && is_array($class_ids_array)) {
//         // Implode the array into a comma-separated string
//         $imploded_class_ids = implode(',', array_map('intval', $class_ids_array)); // Convert to integers for safety

//         $sql = "SELECT * FROM class_info WHERE institution_id = ? AND id IN ($imploded_class_ids)";
//         $array_params = [$institution_id]; // Add institution_id to parameters
//         $stmt = $conn_rjllearning_specific->prepare($sql);
//         $stmt->execute($array_params);
//         $class_rows = $stmt->fetchAll();

//         foreach ($class_rows as $class_data) {
//             $class_info[] = array('class_id' => $class_data['id'], 'class_name' => $class_data['classname']);
//         }
//     }
// }

//         // Add the collected data to the final array
//         $array_return[] = array(
//             'activity_id' => $rows['id'],
//             'branch_id' => $branch,
//             'class_info' => $class_info,
//             'section_info' => $section,
//             'student_info' => $correct_students,  // This will contain the student information
//             'type' => $rows['type'],
//             'tags' => json_decode($rows['tags'], true),
//             'title' => $rows['title'],
//             'description' => $rows['description'],
//             'activity_attachment' => $data_to_send,
//             'publish_date' => $rows['publish_date'],
//             'publish_time' => $rows['publish_time'],
//             'termination_date' => $rows['termination_date'],
//             'termination_time' => $rows['termination_time'],
//             'created_by' => $rows['created_by'],
//             'date_created' => $rows['date_created'],
//             'time_created' => $rows['time_created'],
//             'status' => $rows['status']
//         );
//     }

//     if (count($activities) < 50) {

//         return array('total_rows' => $totalrows, 'activity_info' => $array_return, 'maxreach' => 1);
//     } else {
//         return array('total_rows' => $totalrows, 'activity_info' => $array_return, 'maxreach' => 0);
//     }
// }

function sendActivityMentorNotification($conn_rjllearning, $conn_rjllearning_specific, $institution_id, $student_id, $message, $workspace_id, $web_app_title) {
    // If student_id is 'all', do not send any notification
    if ($student_id === 'all') {
        return true;
    }

    // Additional student data to fetch
    $additionaldata = ['id', 'institution_id', 'branch_id', 'admission_number', 'name', 'mobile', 'email', 'fathername', 'user_id'];

    // Decode student IDs if it's a JSON string
    if (is_string($student_id)) {
        $decoded_student_ids = json_decode($student_id, true);
        if (json_last_error() === JSON_ERROR_NONE && is_array($decoded_student_ids)) {
            $student_id = $decoded_student_ids;
        } else {
            $student_id = [$student_id];
        }
    }

    // Fetch students
    $students = getStudentsForActivityMentorNotification($conn_rjllearning_specific, $institution_id, $student_id, $additionaldata);
   
    if (empty($students)) {
        return; // No students found
    }

    // Get subject or activity details
    $subject = 'Activity Mentor Notification - ' . $web_app_title;
    $notificationBody = "You have a new activity assigned by your mentor.\nMessage: " . ucwords($message);

    // Collect student user IDs for notification
    $student_userids = array_column($students, 'user_id');

    // Send the notification
    require_once $GLOBALS['base_path_to_learning_resources'] . 'lib/cron_jobs/function/function.php'; 
    require_once $GLOBALS['base_path_to_learning_resources'] . 'lib/cron_jobs/firebase_notification/fcm_notifications_function.php';

    $mail_count = sendNotification($conn_rjllearning, $student_userids, $subject, $notificationBody);

    // Update notification count per branch (extracted from students)
    $branch_ids = array_unique(array_column($students, 'branch_id'));
    foreach ($branch_ids as $branch) {
        updateMailSmsCount($workspace_id, $institution_id, $branch, null, null, $mail_count, 'notification', $conn_rjllearning);
    }
}


function getStudentsForActivityMentorNotification($conn_rjllearning_specific, $institution_id, $student_id, $additionaldata = null) {
    try {
        // Build SQL
        $sql = "SELECT ";
        $sql .= ($additionaldata && is_array($additionaldata)) ? implode(", ", $additionaldata) : "*";
        $sql .= " FROM students WHERE institution_id = ? AND can_activate = 1 AND status = 1";

        $params = [$institution_id];

        if (!empty($student_id)) {
            if (!is_array($student_id)) {
                $student_id = [$student_id];
            }
            $imploded_ids = implode(",", array_map('intval', $student_id));
            $sql .= " AND user_id IN ($imploded_ids)";
        }

        $sql .= " ORDER BY name ASC";
        
        $stmt = $conn_rjllearning_specific->prepare($sql);
        $stmt->execute($params);

        return $stmt->fetchAll(PDO::FETCH_ASSOC);
    } catch (PDOException $e) {
        return [];
    }
}


