<?php

// Include necessary files

// echo 'here';
// die();
// require_once '../../base_path_include.php'; // Adjusted to navigate to the correct directory
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/cron_jobs/firebase_notification/fcm_notifications_function.php';
require_once $base_path_to_learning_resources . 'lib/cron_jobs/function/function.php';
require $base_path_to_learning . 'vendor/autoload.php';
require_once $base_path_to_learning .'admin_api/modules/students/student_functions.php';

use \Kreait\Firebase\Factory;
use \Kreait\Firebase\Messaging\CloudMessage;
use \Kreait\Firebase\Messaging\Notification;
use \Kreait\Firebase\Exception\MessagingException;

// Initialize Firebase
$factory = (new Factory)->withServiceAccount(''); // Path to your service account key
$messaging = $factory->createMessaging();

try {
    // Get current date and time
    $currentDatetime = date('Y-m-d H:i');
    // Get notifications that need to be sent
    $stmt = $conn_rjllearning->prepare("SELECT id, institution_id, type,type_id FROM scheduler_tasks WHERE status=0 AND date = ?");
    $stmt->execute([$currentDatetime]);
    $notifications = $stmt->fetchAll(PDO::FETCH_ASSOC);
    foreach ($notifications as $notification) {

        $notification_data = getDataUsers($conn_rjllearning, $notification['institution_id'], $notification['type'], $notification['type_id'],$workspace_id['workspace_id']);
        $students = $notification_data['students'];
        $notificationTitle = $notification_data['notification_title'];
        $notificationBody = $notification_data['notification_body'];

        foreach ($students as $student) {
        $userid = $student['user_id'];

        // Fetch FCM token for the user
        $fcmStmt = $conn_rjllearning->prepare("SELECT fcm_token FROM user_fcm_tokens WHERE userid = ?");
        $fcmStmt->execute([$userid]);
        $fcmTokens = $fcmStmt->fetchAll();
        if ($fcmTokens) {
            if ($fcmTokens[0]['fcm_token'] != null and $fcmTokens[0]['fcm_token'] != '') {
                $fcmTokens =  json_decode($fcmTokens[0]['fcm_token']);
                try {
                    sendNotification($fcmTokens, $notificationTitle, $notificationBody, $messaging);
                } catch (Exception $e) {
                    // Handle errors in sendNotification function
                    // errorreturn("Notification error for user ID $userid: " . $e->getMessage());
                }
            }
            // Update notification as sent
            $notificationId = $notification['id'];
            $updateStmt = $conn_rjllearning->prepare("UPDATE scheduler_tasks SET status=1 WHERE id=?");
            $updateStmt->execute([$notificationId]);
        } else {
            // errorreturn ("FCM token not found for user ID: $userid\n");
        }
        
        }
    }

    // Delete notifications that have been sent
    // $deleteStmt = $conn_rjllearning->prepare("DELETE FROM notifications WHERE status=1");
    // $deleteStmt->execute();

} catch (PDOException $e) {
    errorreturn("Error: " . $e->getMessage());
}

function getDataUsers($conn_rjllearning, $institution_id, $type, $type_id, $workspace_id)
{
    try {
        // Fetch database name based on workspace ID and status
        $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) {
            errorreturn('Fatal error (1). Access denied.');
        }
        
        $db_name = $result_workspace[0]['db_name'];
        $conn_rjllearning_specific = dynamicDbConnection($db_name);

        // Initialize default values
        $students = [];
        $notificationTitle = '';
        $notificationBody = '';

        // Process the task based on type
        switch ($type) {
            case 'assignment':
                // Handle task related to assignments
                $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'];

                    // 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);
                    $notificationTitle = 'Assignment';
                    $notificationBody = $subject_name;
                } else {
                    errorreturn("Assignment not found with ID: $type_id");
                }
                break;

            case 'lesson':
                // Handle task related to lessons
                $result_question = fetchRecordById($conn_rjllearning_specific, 'lesson', $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);
                    $notificationTitle = 'Lesson';
                    $notificationBody = $subject_name;
                } else {
                    errorreturn("Lesson not found with ID: $type_id");
                }
                break;
                case 'book_issues':
                    // Handle task related to assignments
                       $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'];
                        $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);
                        $notificationBody = "Book due date: " . ($date_of_return ? $date_of_return : "Not returned yet");
                     
                    } else {
                        // Handle assignment not found
                        errorreturn("book_issues not found with ID: $type_id");
                    }
            default:
                // Handle invalid category case
                errorreturn("Invalid category provided: $type");
        }
        
             
    } catch (Exception $e) {
        errorreturn("An error occurred: " . $e->getMessage());
    }

    return array(
        "students" => $students,
        "notification_title" => $notificationTitle,
        "notification_body" => $notificationBody
    );
}
