<?php

function sendMarksheetNotification($conn_rjllearning, $conn_rjllearning_specific, $institution_id, $marksheet_id, $workspace_id, $web_app_title) {
    // Debug: Start Function Execution
   
    // Step 1: Fetch marksheet info from `marksheet_info`
    $queryMarksheetInfo = "
        SELECT 
            marksheet_id, 
            class_id
        FROM 
            marksheet_info 
        WHERE 
            institution_id = ? 
            AND id = ? 
            AND status = 1
    ";
    $stmtMarksheetInfo = $conn_rjllearning_specific->prepare($queryMarksheetInfo);
    $stmtMarksheetInfo->execute([$institution_id, $marksheet_id]);

    $marksheetInfo = $stmtMarksheetInfo->fetch(PDO::FETCH_ASSOC);

    if (!$marksheetInfo) {
       
        return false; // Stop execution if no marksheet info
    }

    // Debug: Log marksheet info
    

    $class_id = $marksheetInfo['class_id'];

    // Step 2: Fetch marksheet details from `marksheet`
    $queryMarksheetDetails = "
        SELECT 
            examination_name 
        FROM 
            marksheet 
        WHERE 
            id = ?
    ";
    $stmtMarksheetDetails = $conn_rjllearning_specific->prepare($queryMarksheetDetails);
    $stmtMarksheetDetails->execute([$marksheet_id]);

    $marksheetDetails = $stmtMarksheetDetails->fetch(PDO::FETCH_ASSOC);

    if (!$marksheetDetails) {
        
        return false; // Stop execution if no marksheet details
    }

    // Debug: Log marksheet details
   

    $examination_name = $marksheetDetails['examination_name'];

    // Step 3: Fetch students with complete marks
    $queryStudentMarksheet = "
        SELECT 
            smd.student_id, 
            s.name, 
            s.user_id, 
            s.mobile, 
            s.email 
        FROM 
            student_marksheet_data smd
        INNER JOIN 
            students s 
        ON 
            smd.student_id = s.id
        WHERE 
            smd.marksheet_id = ? 
            AND smd.data IS NOT NULL 
            AND s.class_id = ?
    ";
    $stmtStudentMarksheet = $conn_rjllearning_specific->prepare($queryStudentMarksheet);
    $stmtStudentMarksheet->execute([$marksheet_id, $class_id]);
    $students = $stmtStudentMarksheet->fetchAll(PDO::FETCH_ASSOC);
   
       // Debug: Log fetched students
   

    if (empty($students)) {
        
        return false; // Stop execution if no students found
    }

    // Step 4: Prepare and send notifications
    $subject = 'Marksheet Published - ' . $examination_name . ' ' . $web_app_title . ' - ' . date('d M Y');

    $studentsWithMarksheet = [];
    
    foreach ($students as $student) {
        $studentsWithMarksheet[] = [
            'user_id' => $student['user_id'],
            'name' => $student['name'],
            'mobile' => $student['mobile'],
            'email' => $student['email'],
            'examination_name' => $examination_name
        ];
    }
    
    // Debug: Log students to notify
    require_once $GLOBALS['base_path_to_learning_resources'] . 'lib/cron_jobs/firebase_notification/fcm_notifications_function.php';
    
    // Create the message template only once
    $messageTemplate = "Dear {student_name}, your marksheet for {examination_name} has been published. Please log in to your account to view it.";
    
    foreach ($studentsWithMarksheet as $student) {
        // Replace placeholders with actual student data
        $message = str_replace(
            ['{student_name}', '{examination_name}'],
            [$student['name'], $examination_name],
            $messageTemplate
        );
    
        // Send notification
        $notificationSent = sendNotification($conn_rjllearning, [$student['user_id']], $subject, $message, 'marksheet_published');
    
        if (!$notificationSent) {
            return false; // Stop execution if a notification fails
        }
    }

    // Step 5: Update notification count
    $student_count = count($studentsWithMarksheet);

    

    require_once $GLOBALS['base_path_to_learning_resources'] . 'lib/cron_jobs/function/function.php';

    $countUpdated = updateMailSmsCount($workspace_id, $institution_id, null, null, null, $student_count, 'notification', $conn_rjllearning);

    if (!$countUpdated) {
       
        return false; // Stop execution if count update fails
    }

   
    return true; // Execution completed successfully
}
