<?php
ini_set('display_errors', 1);
date_default_timezone_set('Asia/Kolkata');
require_once '/home/rejoicebilldesk/public_html/rjllearning_development/resources/base_path_include.php';

require_once $base_path_to_learning_resources  . "includes/connect.php";
require_once $base_path_to_learning_resources . 'lib/function.php';
require_once $base_path_to_learning_resources . 'lib/mail_system/aws_mail_send.php';
require_once $base_path_to_learning_resources . 'lib/task_schedule/task_scheduler_functions.php';
require_once $base_path_to_learning_resources . 'includes/specific_db_config.php';
require_once $base_path_to_learning . 'admin_api/modules/students/student_functions.php';
require_once $base_path_to_learning . 'functions/common_functions.php';
require_once $base_path_to_learning_resources . 'lib/cron_jobs/function/function.php';
require_once $base_path_to_learning . "vendor/autoload.php";
require_once $base_path_to_learning_resources . 'lib/bucket_functions/bucket_functions.php';
require_once $base_path_to_learning_resources . 'includes/aws_bucket_config.php';
// require_once $base_path_to_learning_resources . 'lib/cron_jobs/firebase_notification/fcm_notifications_function.php';
use Aws\S3\S3Client;
use Aws\S3\Exception\S3Exception;



// Get current date and time
$currentDatetime = date('Y-m-d');
$time = time();
$currentTime = date('H:i');
// Get notifications that need to be sent
$stmt = $conn_rjllearning->prepare("SELECT id, type, type_id, status_to_change, institution_id, workspace_id FROM scheduler_tasks WHERE status = 0  AND date = ?  order by workspace_id  ");

$stmt->execute([$currentDatetime]);
$notifications = $stmt->fetchAll(PDO::FETCH_ASSOC);

$send_mail_bool = 0;
$send_notification_bool = 0;
foreach ($notifications as $notification) {
    $statusToChange = $notification['status_to_change'];
    $type = $notification['type'];
    $type_in_captital = ucwords($type);
    $type_id = $notification['type_id'];
    $institution_id = $notification['institution_id'];
    $workspace_id = $notification['workspace_id'];
    $schedule_task_id = $notification['id'];
    $subject = $type_in_captital . ' Notification - ';
    $institutions = getInstitution($conn_rjllearning, $institution_id);
    $institutions_logo = $institutions['logo'];

    // Fetch workspace information
    // Declare a static variable to store the last fetched db_name
    static $last_db_name = null;

    // Check if the current workspace's db_name matches the last fetched one
    if ($last_db_name !== null && $last_db_name === $db_name) {
        // If the db_name matches, no need to fetch again
        $conn_rjllearning_specific = dynamicDbConnection($last_db_name);
    } else {
        // Fetch the db_name again if it doesn't match or if it is null
        $sql = "SELECT db_name FROM workspace_database_info WHERE workspace_id = ? AND status = ?";
        $fetch_workspace = $conn_rjllearning->prepare($sql);
        $fetch_workspace->execute([$workspace_id, 1]);
        $result_workspace = $fetch_workspace->fetchAll();

        if (count($result_workspace) < 1) {
            return false;
        }

        $db_name = $result_workspace[0]['db_name'];
        $conn_rjllearning_specific = dynamicDbConnection($db_name);

        // Update the static variable with the fetched db_name
        $last_db_name = $db_name;
    }

    $institution_info = getInstitution($conn_rjllearning, $institution_id);
    $white_label_url = $institution_info['white_label_url'] ?? '';
    $white_label_email = $institution_info['white_label_email'] ?? '';
    $white_label_message_header = $institution_info['white_label_message_header'] ?? '';
    $white_label_app_name = $institution_info['white_label_app_name'] ?? '';
    // Set default domain
    //$default_domain = 'rejoicelearning.in';

    // Build faculty subdomain-based URL dynamically
    // if (!empty($white_label_url)) {
    //     $domain = str_replace(['http://', 'https://', 'www.'], '', $white_label_url);
    //     $domain_parts = explode('/', $domain); // remove any path
    //     $base_domain = $domain_parts[0];
    //     $url = 'https://faculty.' . $base_domain;
    // } else {
    //     $url = 'https://faculty.' . $default_domain;
    // }
    // Use white label values if provided, otherwise fallback to default
    $app_name = !empty($white_label_app_name) ? $white_label_app_name : $$web_app_title;
    $app_url = $url;
    $from_email = !empty($white_label_email) ? $white_label_email : 'no-reply@rejoicelearning.in';
    switch ($type) {
        case 'assignment':
            $result_question = fetchRecordById($conn_rjllearning_specific, 'assignments', $type_id, $institution_id);
            if ($result_question) {
                $branch_id = $result_question['branch_id'];
                $class_id = $result_question['class_id'];
                $section_id = $result_question['section_id'];
                $subject_id = $result_question['subject_id'];
                $publish_date = $result_question['publish_date'];
                $last_date = $result_question['last_date'];
                $termination_time = $result_question['last_submission_time'];
                $can_submit_after_last_date = $result_question['can_submit_after_last_date'];

                $subject_info = getSubject($conn_rjllearning_specific, $institution_id, $subject_id);
                $subject_name = isset($subject_info['subject_name']) ? $subject_info['subject_name'] : 'Unknown Subject';

                $additionaldata = ['id', 'institution_id', 'branch_id', 'admission_number', 'name', 'mobile', 'email', 'fathername', 'user_id'];
                $students = getStudentsForNotification($conn_rjllearning_specific, $institution_id, $branch_id, $class_id, $section_id, null, $additionaldata);

                if ($statusToChange == 1 && $currentTime >= '07:00') {
                    publishBlockTasks($conn_rjllearning, $workspace_id, $institution_id, $type, $type_id, 1, $schedule_task_id);
                    updateSchedulerTaskStatus($conn_rjllearning, $workspace_id, $institution_id, $type, $schedule_task_id, $statusToChange);

                    $mailData = "
                    <h1>$type_in_captital - <span class='web_app_title'>$app_name</span></h1>
                    <p>You have been assigned a new $type_in_captital for the subject <strong>$subject_name</strong>.</p>
                    <p>Please ensure that you complete and submit the $type_in_captital by the due date. Late submissions may not be accepted.</p>
                    <p>If you have any questions, feel free to contact your teacher.</p>";
                    $notificationSubject = "Assignment " . ucwords($subject_name);
                    $notificationMessage = "Your assignment has been published and is now available. Please check the details and start working on it.";
                    $send_mail_bool = 1;
                    $send_notification_bool = 1;
                } elseif ($statusToChange == 0 && $currentTime >= '17:00') {
                    publishBlockTasks($conn_rjllearning, $workspace_id, $institution_id, $type, $type_id, 0, $schedule_task_id);
                    updateSchedulerTaskStatus($conn_rjllearning, $workspace_id, $institution_id, $type, $schedule_task_id, $statusToChange);
                } elseif ($statusToChange == 2) {
                    publishBlockTasks($conn_rjllearning, $workspace_id, $institution_id, $type, $type_id, 2, $schedule_task_id);
                    updateSchedulerTaskStatus($conn_rjllearning, $workspace_id, $institution_id, $type, $schedule_task_id, $statusToChange);

                    $mailData = "
                    <h1>$type_in_captital Reminder - <span class='web_app_title'>$app_name</span></h1>
                    <p>This is a reminder that your $type_in_captital for the subject <strong>$subject_name</strong> is approaching its due date.</p>
                    <p>Kindly ensure that you complete and submit the $type_in_captital before the deadline to avoid any penalties or missed opportunities.</p>
                    <p>If you have any questions or need any assistance, please feel free to contact your teacher.</p>
                    <p>Don't wait until the last minute!</p>";
                    $notificationSubject = "Assignment " . ucwords($subject_name);
                    $notificationMessage = "Reminder: Your assignment deadline is approaching. Please make sure to submit it on time.";
                    $send_mail_bool = 1;
                    $send_notification_bool = 1;
                }
            } else {
                // errorreturn("Assignment not found with ID: $type_id");
                return false;
            }
            break;

        case 'lesson':
            $result_question = fetchRecordById($conn_rjllearning_specific, 'lessons', $type_id, $institution_id);
            if ($result_question) {
                $branch_id = $result_question['branch_id'];
                $class_id = $result_question['class_id'];
                $section_id = $result_question['section_id'];
                $subject_id = $result_question['subject_id'];
                $publish_date = $result_question['publish_date'];
                $publish_time = $result_question['publish_time'];
                $terminate_date = $result_question['terminate_date'];
                $termination_time = $result_question['termination_time'];

                // Fetch 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';
                $additionaldata = ['id', 'institution_id', 'branch_id', 'admission_number', 'name', 'mobile', 'email', 'fathername', 'user_id'];
                $students = getStudentsForNotification($conn_rjllearning_specific, $institution_id, $branch_id, $class_id, $section_id, null, $additionaldata);

                if ($statusToChange == 1 && date('H') == 11 && date('i') == 23) {

                    publishBlockTasks($conn_rjllearning, $workspace_id, $institution_id, $type, $type_id, 1, $schedule_task_id);
                    updateSchedulerTaskStatus($conn_rjllearning, $workspace_id, $institution_id, $type, $schedule_task_id, $statusToChange);
                    $notificationSubject = "Lesson " . ucwords($subject_name);
                    $notificationMessage = "A new lesson titled '{$result_question['lesson_name']}' for the subject '{$subject_name}' has been published. Please check your dashboard for details.";
                    $send_mail_bool = 0;
                    $send_notification_bool = 1;
                } elseif ($statusToChange == 0 && date('H') == 0 && date('i') >= 1) {
                    publishBlockTasks($conn_rjllearning, $workspace_id, $institution_id, $type, $type_id, 0, $schedule_task_id);
                    updateSchedulerTaskStatus($conn_rjllearning, $workspace_id, $institution_id, $type, $schedule_task_id, $statusToChange);
                    $send_mail_bool = 0;
                    $send_notification_bool = 0;
                }
            } else {
                return false;
            }
            break;


        case 'live_meeting':
            // Fetch the live meeting details by ID
            $result_meeting = fetchRecordById($conn_rjllearning_specific, 'live_meetings', $type_id, $institution_id);

            if ($result_meeting) {
                // Extract live meeting details
                $branch_id = $result_meeting['branch_id'];
                $class_id = $result_meeting['class_id'];
                $section_id = $result_meeting['section_id'];
                $subject_id = $result_meeting['subject_id'];
                $meeting_link = $result_meeting['meeting_link'];
                $start_time = $result_meeting['start_time']; // Format: "HH:MM"

                // Convert start_time to a timestamp
                $meeting_timestamp = strtotime($start_time);
                $reminder_timestamp = strtotime('-2 hours', $meeting_timestamp);

                // Format reminder time
                $reminder_time = date('H:i', $reminder_timestamp);

                // If it's not 2 hours before the meeting, exit early
                if (date('H:i') != $reminder_time) {
                    return false;
                }

                // Get subject details
                $subject_info = getSubject($conn_rjllearning_specific, $institution_id, $subject_id);
                $subject_name = isset($subject_info['subject_name']) ? $subject_info['subject_name'] : 'Unknown Subject';

                // Fetch the list of students for notification
                $additionaldata = ['id', 'institution_id', 'branch_id', 'admission_number', 'name', 'mobile', 'email', 'fathername', 'user_id'];
                $students = getStudentsForNotification($conn_rjllearning_specific, $institution_id, $branch_id, $class_id, $section_id, null, $additionaldata);

                if ($statusToChange == 1) {
                    // Live Meeting Scheduled - Notification will be sent automatically
                    $notificationSubject = ucwords($subject_name);
                    $notificationMessage = "A live meeting '$subject_name' has been scheduled. Join using the link: $meeting_link at $start_time.";

                    $send_mail_bool = 0;  // No email for live meetings
                    $send_notification_bool = 1; // Only notification should be sent

                    updateSchedulerTaskStatus($conn_rjllearning, $workspace_id, $institution_id, $type, $schedule_task_id, $statusToChange);
                }
            } else {
                return false;
            }

            break;


        case 'book_issues':
            $result_question = fetchRecordById($conn_rjllearning_specific, 'book_issues', $type_id, $institution_id);
            if ($result_question) {
                $branch_id = $result_question['branch_id'];
                $date_of_issue = $result_question['date_of_issue'];
                $issue_time = $result_question['issue_time'];
                $due_date = $result_question['due_date'];
                $date_of_return = $result_question['date_of_return'] ?? null;
                $student_id = $result_question['student_id'];
                $book_id = $result_question['book_id'];
                $additionaldata = ['id', 'institution_id', 'branch_id', 'admission_number', 'name', 'mobile', 'email', 'fathername', 'user_id'];
                $students = getStudentsForNotification($conn_rjllearning_specific, $institution_id, $branch_id, null, null, $student_id, $additionaldata);


                $sql = "SELECT book_name FROM library_management WHERE id = ? AND institution_id = ?";
                $stmt = $conn_rjllearning_specific->prepare($sql);
                $stmt->execute([$book_id, $institution_id]);
                $library_data = $stmt->fetch(PDO::FETCH_ASSOC);

                $book_name = $library_data['book_name'] ?? 'Unknown Book';
            } else {
                return false;
            }

            // 1. Send message confirming book issue
            if ($date_of_return === null) { // Ensure it's not already returned
                $mailData = "
                        <h1>$type_in_captital - <span class='web_app_title'>$app_name</span></h1>
                        <p>You have successfully issued the book <strong>$book_name</strong>.</p>
                        <p>Please ensure that you return the book by the due date: <strong>$due_date</strong>.</p>
                        <p>If you have any questions, feel free to contact your teacher.</p>
                        <p>Thank you for using our library services!</p>";
                $notificationSubject = "Library Book status";
                $notificationMessage = "You have successfully issued the book: $book_name. Please return it by $due_date.";
                $send_mail_bool = 1;
                $send_notification_bool = 1;
                updateSchedulerTaskStatus($conn_rjllearning, $workspace_id, $institution_id, $type, $schedule_task_id, $statusToChange);
            }

            // Send the confirmation email and notification

            // 2. Send reminder message the day before due date, before 6 PM
            if ($date_of_return == null) {
                $due_date_time = strtotime($due_date);
                $current_datetime = new DateTime();
                $one_day_before_due_date = (new DateTime())->setTimestamp($due_date_time)->modify('-1 day');

                // Check if current time is before 6 PM and one day before due date
                if ($current_datetime >= $one_day_before_due_date && $current_datetime->format('H') < 18) {
                    publishBlockTasks($conn_rjllearning, $workspace_id, $institution_id, $type, $type_id, 0, $schedule_task_id);
                    updateSchedulerTaskStatus($conn_rjllearning, $workspace_id, $institution_id, $type, $schedule_task_id, $statusToChange);

                    // Prepare the message for sending reminder
                    $mailData = "
                        <h1>Reminder: $type_in_captital - <span class='web_app_title'>$app_name</span></h1>
                        
                        <p>This is a reminder that the due date for your $type_in_captital for the book <strong>$book_name</strong> is tomorrow, <strong>$due_date</strong>.</p>
                        <p>Please ensure that you return the book by the due date to avoid any late fees or penalties.</p>
                        <p>If you have any questions or need assistance, please feel free to contact your teacher.</p>
                        <p>Thank you for your attention.</p>";
                    $notificationSubject = "Library Book status";
                    $notificationMessage = "Reminder: Your book $book_name is due tomorrow. Please return it by $due_date to avoid any late fees.";
                    $send_mail_bool = 1;
                    $send_notification_bool = 1;

                    // Send the reminder email and notification

                }
            }

            break;

        case 'apply_leaves':
            // Case: Leave Status Update
            $result_question = fetchRecordById($conn_rjllearning_specific, 'apply_leaves', $type_id, $institution_id);

            if ($result_question) {
                $branch_id = $result_question['branch_id'];
                $class_id = $result_question['class_id'];
                $section_id = $result_question['section_id'];
                $user_id = $result_question['student_id'];
                $start_date = $result_question['start_date'];
                $end_date = $result_question['end_date'];
                $status = $result_question['status'];  // 1 = Approved, -1 = Rejected, 0 = Pending
                $student_id = getStudentInfoForCronJob($conn_rjllearning_specific, $institution_id, $user_id);

                $additionaldata = ['id', 'institution_id', 'branch_id', 'admission_number', 'name', 'mobile', 'email', 'fathername', 'user_id'];
                $students = getStudentsForNotification($conn_rjllearning_specific, $institution_id, $branch_id, null, null, $student_id, $additionaldata);

                // Prepare data for mail and notification based on leave status

                switch ($status) {
                    case 1:

                        // Approved Leave
                        $mailData = "
                                        <h1>Leave Approved</h1>
                                        <p>Dear Student,</p>
                                        <p>Your leave request from <strong>$start_date</strong> to <strong>$end_date</strong> has been approved.</p>
                                        <p>Please ensure that you catch up on any missed classes or assignments during this period.</p>
                                        <p>Thank you.</p>
                                    ";
                        $notificationSubject = "Leave status";
                        $notificationMessage = "Your leave request from $start_date to $end_date has been approved.";
                        $send_mail_bool = 1;
                        $send_notification_bool = 1;
                        break;

                    case -1:
                        // Rejected Leave
                        $mailData = "
                                        <h1>Leave Rejected</h1>
                                        <p>Dear Student,</p>
                                        <p>We regret to inform you that your leave request from <strong>$start_date</strong> to <strong>$end_date</strong> has been rejected.</p>
                                        <p>Please contact your class teacher or administration if you need further assistance.</p>
                                        <p>Thank you.</p>
                                    ";
                        $notificationSubject = "Leave status";
                        $notificationMessage = "Your leave request from $start_date to $end_date has been rejected.";
                        $send_mail_bool = 1;
                        $send_notification_bool = 1;
                        break;

                    case 0:
                        // Pending Leave (No action required)
                        $send_mail_bool = 0;
                        $send_notification_bool = 0;
                        break;

                    default:
                        return false;
                }

                // If mail and notification are enabled, proceed with sending them


                // Update scheduler task status if necessary
                updateSchedulerTaskStatus($conn_rjllearning, $workspace_id, $institution_id, $type, $schedule_task_id, $statusToChange);
            } else {
                // Handle leave request not found
                return false;
            }
            break;


        case 'announcement':
            // Fetch the announcement details by ID
            $result_question = fetchRecordById($conn_rjllearning_specific, 'announcement', $type_id, $institution_id);

            if ($result_question) {
                // Extract announcement details
                $branch_id = $result_question['branch_id'];
                $class_id = $result_question['class_id'];
                $section_id = $result_question['section_id'];
                $title = $result_question['title'];
                $message = $result_question['message'];
                // $publish_date = $result_question['publish_date'];

                // Fetch the list of students for notification
                $additionaldata = ['id', 'institution_id', 'branch_id', 'admission_number', 'name', 'mobile', 'email', 'fathername', 'user_id'];
                $students = getStudentsForNotification($conn_rjllearning_specific, $institution_id, $branch_id, $class_id, $section_id, null, $additionaldata);


                if ($statusToChange == 1) {
                    // Announcement published
                    $mailData = "
                                    <h1>New Announcement - <span class='web_app_title'>$app_name</span></h1>
                                    <p>A new announcement titled '<strong>$title</strong>' has been made for the class. Please check the details below:</p>
                                    <p>$message</p>
                                    <p>Stay informed and follow the instructions accordingly.</p>";
                    $notificationSubject = ucwords($title);
                    $notificationMessage = "A new announcement titled '$title' has been made. Please check the details.";
                    $send_mail_bool = 1;
                    $send_notification_bool = 1;
                    updateSchedulerTaskStatus($conn_rjllearning, $workspace_id, $institution_id, $type, $schedule_task_id, $statusToChange);
                }
            } else {
                return false;
            }
            break;

        default:
            return false;
            break;
    }
}
if (empty($students)) {
    return;
}

$emailAddresses = array_map(function ($student) {
    return $student['email'];
}, $students);


// $emailAddresses = [];

// // Loop through the students array and collect all email addresses
// for ($i = 0; $i < count($students); $i++) {
//     $student = $students[$i];  // Access the student at index $i
//     $emailAddresses[] = $student['email'];  // Add the email to the array
// }


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

// Handle mail and notification sending
if ($send_mail_bool == 1) {
    sendMailTemplate1(
        $conn_rjllearning,
        $from_email,
        $emailAddresses,
        $subject,
        $mailData,
        $workspace_id,
        $institution_id,
        $branch_id,
        null,
        null,
        'real_time'
    );
    // updateMailSmsCount($workspace_id, $institution_id, $branch_id, count($emailAddresses), null, null, 'mail', $conn_rjllearning);
}

if ($send_notification_bool == 1) {
    require_once $GLOBALS['base_path_to_learning_resources'] . 'lib/cron_jobs/firebase_notification/fcm_notifications_function.php';
    $user_id = array_map(function ($student) {
        return $student['user_id'];
    }, $students);
    $mail_count = sendNotification($conn_rjllearning, $user_id, $notificationSubject, $notificationMessage);
    updateMailSmsCount($workspace_id, $institution_id, $branch_id, null, null, $mail_count, 'notification', $conn_rjllearning);
}
