<?php



// function sendHomeworkNotification($conn_rjllearning,$conn_rjllearning_specific, $institution_id, $branch_id, $class_id, $section_id,$subject_id,$message, $workspace_id, $web_app_title) {

//     if ($attachment != null and !is_array($attachment)) {
//             $data_attachment = json_decode($attachment, true);
//             $filePath = $data_attachment['filepath'];
//             $originalName = $data_attachment['original_name'];
//             $aws_attachment = displayFileFromS3($GLOBALS['s3_learning_bucket'], $GLOBALS['learning_bucketName'], $filePath);
//             $final_array_attachment   = array("filepath" => $aws_attachment, "original_name" => $originalName);
//         } else {
//             $final_array_attachment =  null;
//         }
//     // Step 1: Get all students in the specified class and section
//     $students = getAllStudentsClassSection($conn_rjllearning_specific, $institution_id, $branch_id, $class_id, $section_id);
//      $subject_info = getSubject($conn_rjllearning_specific, $institution_id, $subject_id);
//       $subject_name = isset($subject_info['subject_name']) ? $subject_info['subject_name'] : 'Unknown Subject';
//     // Step 2: Loop through each student and send the homework notification
//     foreach ($students as $student) {
//         // Get the student's name and email (or mobile, depending on your data structure)
//         $student_name = $student['name'];
//         $student_email = $student['email'];  // Assuming the student array has an 'email' field
//       $student_userid = $student['user_id'];


//         // Prepare the email subject and message
//         // Prepare the email subject and message
//         $subject = 'Homework Notification - ' . $web_app_title;

//         $format = "
//         <h1>Homework Assignment - <span class='web_app_title'>$web_app_title</span></h1>
//         <p>Dear $student_name,</p>
//         <p>You have been assigned new homework for the subject <strong>$subject_name</strong>.</p>
//         <p><strong>Details of the Assignment:</strong></p>
//         <ul>
//             <li><strong>Topic:</strong> $message</li>
//             <li><strong>attachment:</strong> $final_array_attachment</li>


//         </ul>
//         <p>Please ensure that you complete and submit the assignment by the due date. Late submissions may not be accepted.</p>
//         <p>If you have any questions, feel free to contact your teacher.</p>
//         <p>Best regards,<br>
//         The $web_app_title Team</p>";

//         // Step 3: Send the email using the existing function
//         // Assuming `sendMailTemplate1` is a function that sends the email
//         require_once $GLOBALS['base_path_to_learning_resources'] . 'lib/mail_system/mail_Template1.php';
//         sendMailTemplate1($conn_rjllearning, 'no-reply@rejoicelearning.in', $student_email, $subject, $format,$workspace_id,$institution_id,$branch_id,$student_userid);
//     }
// }


function sendHomeworkNotification($conn_rjllearning, $conn_rjllearning_specific, $institution_id, $branch_id, $class_id, $section_id, $subject_id, $message, $workspace_id, $web_app_title)
{
    // Additional student data to fetch

    require_once $GLOBALS['base_path_to_learning'] . 'admin_api/modules/students/student_functions.php';
    $additionaldata = ['id', 'institution_id', 'branch_id', 'admission_number', 'name', 'mobile', 'email', 'fathername', 'user_id'];

    // Step 1: Get all students in the specified class and section
    $students = getStudentsForNotification($conn_rjllearning_specific, $institution_id, $branch_id, $class_id, $section_id, $student_id = null, $additionaldata);
    
    if (empty($students)) {
        return;  // No students found, stop execution
    }
    // Get subject information
    $subject_info = getSubject($conn_rjllearning_specific, $institution_id, $subject_id);
    $subject_name = isset($subject_info['subject_name']) ? $subject_info['subject_name'] : 'Unknown Subject';

    // Step 2: Loop through each student and send the homework notification
    $student_count = count($students);

    // Prepare the email subject and content
    $subject = 'Homework Notification - ' . $web_app_title;

    $notificationTitle = "New Homework Assigned!";
    $notificationBody = "Dear Student,  
    You have a new homework for $subject_name.  
    
    Homework Details: $message  
    
    Please make sure to complete it as per the instructions.  
    
    Best regards,  
    Your School Team.";




    // Collect student user IDs for notification
    $student_userids = array_map(function ($student) {
        return $student['user_id'];
    }, $students);

    // Step 3: Fetch all FCM tokens for the collected user_ids
    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';

    // $tokens = getUserFCMToken($conn_rjllearning, $student_userids);

    // Send the notification
    $mail_count=sendNotification($conn_rjllearning, $student_userids, "Homework Notification", $notificationBody ,'homework',$GLOBALS['id']);
    
    // Update Mail and SMS count after sending notifications to all students
    updateMailSmsCount($workspace_id, $institution_id, $branch_id, null, null, $mail_count, 'notification', $conn_rjllearning);
}

// function getUserFCMToken($conn_rjllearning, $userIds) {
//     try {
//         // Ensure userIds is an array
//         if (!is_array($userIds)) {
//             $userIds = [$userIds];
//         }
     
//         // Prepare placeholders for the query
//         $placeholders = implode(',', array_fill(0, count($userIds), '?'));

//         $sql = "SELECT fcm_token FROM user_fcm_tokens WHERE userid IN ($placeholders)";
//         $stmt = $conn_rjllearning->prepare($sql);
//         $stmt->execute($userIds);

//         $tokens = [];
//         while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
//             if (!empty($row['fcm_token'])) {
//                 $decodedTokens = json_decode($row['fcm_token'], true);
//                 if (is_array($decodedTokens)) {
//                     $tokens = array_merge($tokens, $decodedTokens);
//                 }
//             }
//         }

//         return $tokens;
//     } catch (PDOException $e) {
//         errorreturn('Database error: ' . $e->getMessage());
//     }
// }
