<?php
require_once('/home/rejoicebilldesk/public_html/rjllearning_development/resources/base_path_include.php');

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';
require_once $GLOBALS['base_path_to_learning_resources'] . 'lib/cron_jobs/firebase_notification/faculty_and_principal_notification_function.php';

require_once $GLOBALS['base_path_to_learning_resources'] . 'lib/cron_jobs/sms_function/sms_function.php';
// 6. Notifications

  
function sendGatePassSmsAlertToPrincipal($conn_rjllearning,$conn_rjllearning_specific, $institution_id, $branch_id, $workspace_id, $sms_message)
{
    // Step 1: Get principal mobile
    $sql = "SELECT mobile 
            FROM faculty_info 
            WHERE institution_id = ? 
              AND branch_id = ? 
              AND role = 'principal' 
              AND status = 1";
    $stmt = $conn_rjllearning_specific->prepare($sql);
    $stmt->execute([$institution_id, $branch_id]);
    $principal = $stmt->fetchAll();
    

    if (!$principal) {
        errorreturn("No principal found for this branch/institution.");
    }

    // Step 2: Send SMS
    $mobile = [];
    foreach($principal as $temp) {
        $mobile[] = preg_replace('/^\+91/', '91', $temp['mobile']);
    }
    sendSmsAndUpdateCounter(
        $workspace_id,
        $institution_id,
        $branch_id,
        $mobile,
        $sms_message,
        $conn_rjllearning,
        null,
        "principal_gatepass_alert"
    );

    return true;
}


// this sends faculty gate pass notification to principal
function sendNotificationToPrincipal(
    $conn_rjllearning,
    $conn_rjllearning_specific,
    $institution_id,
    $branch_id,
    $notificationTitle,
    $notificationBody,
    $redirectType = null,
    $redirectId = null
) {
    
    // try {
        // 1. Fetch all principal user IDs from faculty_info
        $principal_sql = "SELECT userid 
                          FROM faculty_info 
                          WHERE institution_id = ? 
                            AND branch_id = ? 
                            AND role = 'principal'";
        $stmt = $conn_rjllearning_specific->prepare($principal_sql);
        $stmt->execute([$institution_id, $branch_id]);
        $principals = $stmt->fetchAll(PDO::FETCH_COLUMN);


        if (empty($principals)) {
            return 0; // No principal found
        }

        // 2. Use the existing generic sendNotification function
        return sendNotification(
            $conn_rjllearning,
            $principals,
            $notificationTitle,
            $notificationBody,
            $redirectType,
            $redirectId
        );

    // } catch (Exception $e) {
    //     return 0;
    // }
}


// this is called for student gate pass request notification to principals and class incharge
function sendGatePassStudentRequestNotification(
    $conn_rjllearning, 
    $conn_rjllearning_specific, 
    $institution_id, 
    $branch_id,
    $student_id,
    $message = null
) {
    // Notification title/body
    $title = "Gate Pass Request";
    $body  = $message ?: "A student has requested a gate pass. Approval needed.";

    // -------------------
    // Step 0: Fetch student's class/section
    // -------------------
    $sql_student = "SELECT class_id, section_id 
                    FROM students 
                    WHERE id = ? 
                      AND institution_id = ? 
                      AND branch_id = ?";
    $stmt_student = $conn_rjllearning_specific->prepare($sql_student);
    $stmt_student->execute([$student_id, $institution_id, $branch_id]);
    $studentData = $stmt_student->fetch(PDO::FETCH_ASSOC);

    if (!$studentData) {
        return 0; // Invalid student
    }

    $class_id   = $studentData['class_id'];
    $section_id = $studentData['section_id'];

    // -------------------
    // Step 1: Fetch principals
    // -------------------
    $sql_principal = "SELECT userid 
                      FROM faculty_info 
                      WHERE institution_id = ? 
                        AND branch_id = ? 
                        AND role = 'principal'";
    $stmt_principal = $conn_rjllearning_specific->prepare($sql_principal);
    $stmt_principal->execute([$institution_id, $branch_id]);
    $principal_ids = $stmt_principal->fetchAll(PDO::FETCH_COLUMN);

    if (!empty($principal_ids)) {
        // Found principals → stop here
        sendNotification(
            $conn_rjllearning,
            $principal_ids,
            $title,
            $body,
            "gate_pass_request",
            $student_id
        );
        return count($principal_ids);
    }

    // -------------------
    // Step 2: Get class incharge(s) directly
    // -------------------
    $sql_incharge = "SELECT DISTINCT faculty_id 
                     FROM timetable 
                     WHERE institution_id = ? 
                       AND branch_id = ? 
                       AND class_id = ? 
                       AND section_id = ? 
                       AND type = 'class_incharge'";
    $stmt_incharge = $conn_rjllearning_specific->prepare($sql_incharge);
    $stmt_incharge->execute([$institution_id, $branch_id, $class_id, $section_id]);
    $faculty_ids = $stmt_incharge->fetchAll(PDO::FETCH_COLUMN);

    if (!empty($faculty_ids)) {
        // Found class incharges → stop here
        sendNotification(
            $conn_rjllearning,
            $faculty_ids,
            $title,
            $body,
            "gate_pass_request",
            $student_id
        );
        return count($faculty_ids);
    }

    // -------------------
    // Step 3: Staff access fallback
    // -------------------
    $sql_func = "SELECT id 
                 FROM function_codes 
                 WHERE LOWER(code) = 'approve_gate_pass_request' 
                 LIMIT 1";
    $stmt_func = $conn_rjllearning->prepare($sql_func);
    $stmt_func->execute();
    $function_code_id = $stmt_func->fetchColumn();

    $staff_ids = [];
    if ($function_code_id) {
        $sql_staff = "SELECT faculty_id, function_code, access_classes 
                      FROM staff_access_support 
                      WHERE institution_id = ? 
                        AND branch_id = ?";
        $stmt_staff = $conn_rjllearning_specific->prepare($sql_staff);
        $stmt_staff->execute([$institution_id, $branch_id]);
        $all_staff = $stmt_staff->fetchAll(PDO::FETCH_ASSOC);

        foreach ($all_staff as $row) {
            // --- Step 3.1: check function codes ---
            $func_keys = $row['function_code'];
            if (!$func_keys) continue;

            $func_ids = is_string($func_keys) && strpos($func_keys, '[') !== false
                ? json_decode($func_keys, true)
                : explode(',', $func_keys);
            $func_ids = array_map('intval', $func_ids);

            if (!in_array($function_code_id, $func_ids)) {
                continue; // this faculty doesn’t have gate pass approve access
            }

            // --- Step 3.2: check class-section access ---
            $hasAccess = false;
            if (!empty($row['access_classes'])) {
                $accessData = json_decode($row['access_classes'], true);
                if (is_array($accessData)) {
                    foreach ($accessData as $access) {
                        $class_ok = ($access['class_id'] === "all" || intval($access['class_id']) === intval($class_id));
                        if ($class_ok) {
                            if (in_array("all", $access['section_id']) || in_array(intval($section_id), array_map('intval',$access['section_id']))) {
                                $hasAccess = true;
                                break;
                            }
                        }
                    }
                }
            }

            if ($hasAccess) {
                $staff_ids[] = $row['faculty_id'];
            }
        }
    }

    if (!empty($staff_ids)) {
        sendNotification(
            $conn_rjllearning,
            $staff_ids,
            $title,
            $body,
            "gate_pass_request",
            $student_id
        );
        return count($staff_ids);
    }

    return 0; // No recipients at all
}

// primary function
function sendGatePassStudentRequestNotificationToPrincipalAndFaculty(
    $conn_rjllearning,
    $conn_rjllearning_specific,
    $institution_id,
    $branch_id,
    $user_id
) {
    

    // 1. Get role and workspace_id
    $sql = "SELECT role, workspace_id
            FROM users
            WHERE id = ? AND status = 1";

    $res_type = $conn_rjllearning->prepare($sql);
    $res_type->execute([$user_id]);
    $result_users = $res_type->fetch(PDO::FETCH_ASSOC);

    if (!$result_users) {
        errorreturn("User not found or inactive.");
    }

    $type         = $result_users['role'];
    $workspace_id = $result_users['workspace_id'];

    // 2. Fetch user details by role
    if ($type == 'student') {
        $sql = "SELECT name, email, mobile, admission_number, id, class_id, section_id
                FROM students 
                WHERE id = ? AND institution_id = ? AND branch_id = ? AND can_activate = 1";
    } elseif ($type == 'faculty') {
        $sql = "SELECT name, email, mobile, dob
                FROM faculty_info 
                WHERE id = ? AND institution_id = ? AND branch_id = ?";
    } else {
        errorreturn("Invalid user type.");
    }

    $res_type = $conn_rjllearning_specific->prepare($sql);
    $res_type->execute([$user_id, $institution_id, $branch_id]);
    $result1 = $res_type->fetch(PDO::FETCH_ASSOC);

    if (!$result1) {
        errorreturn("User not available in the specified branch of the institution.");
    }

    // 3. Common fields
    $name   = $result1['name'];
    $email  = $result1['email'];
    $mobile = preg_replace('/^\+91/', '91', $result1['mobile']);

    // 4. Role-specific handling
    if ($type == 'student') {
        $username_sms  = $result1['admission_number'];
        $student_id    = $result1['id'];
        $class_id      = $result1['class_id'];
        $section_id    = $result1['section_id'];
        $sms_module    = 'gatepass';
        $gatepass_name = mb_strimwidth($name, 0, 20, "...");
        $student_name  = $name;
        $admission_no  = $result1['admission_number'];
        $var2          = 'Adm No. ' . $admission_no;
    } else { // faculty
        $username_sms  = $result1['email'];
        $sms_module    = 'facultygatepass';
        $gatepass_name = mb_strimwidth($name, 0, 20, "...");
        $student_name  = '';
        $admission_no  = '';
        $faculty_dob   = $result1['dob'];
        $var2          = $faculty_dob;
    }

    // 5. Principal alert message
    $gate_name = "Gate";
    $principal_sms_message = "{$gate_name} Pass Alert: {$gatepass_name} {$var2} has requested a gate pass. Kindly review in the app. Regards, Rejoice Learning.";

    // Send SMS alert
    sendGatePassSmsAlertToPrincipal(
        $conn_rjllearning,
        $conn_rjllearning_specific,
        $institution_id,
        $branch_id,
        $workspace_id,
        $principal_sms_message
    );


    // Student notification
    if ($type == 'student' && $student_id && $class_id && $section_id) {
        $notification_count = sendGatePassStudentRequestNotification(
            $conn_rjllearning,
            $conn_rjllearning_specific,
            $institution_id,
            $branch_id,
            $student_id,
            $class_id,
            $section_id
        );

        updateMailSmsCount(
            $workspace_id,
            $institution_id,
            $branch_id,
            null,
            null,
            $notification_count,
            'notification',
            $conn_rjllearning
        );
    }

    // Faculty notification
    if ($type == 'faculty') {
        $notifTitle   = "Faculty Gate Pass Request";
        $notifBody    = "Faculty member $name has requested a gate pass.";
        $redirectType = "gatepass";
        $redirectId   = $user_id;

        $notification_count = sendNotificationToPrincipal(
            $conn_rjllearning,
            $conn_rjllearning_specific,
            $institution_id,
            $branch_id,
            $notifTitle,
            $notifBody,
            $redirectType,
            $redirectId
        );

        updateMailSmsCount(
            $workspace_id,
            $institution_id,
            $branch_id,
            null,
            null,
            $notification_count,
            'notification',
            $conn_rjllearning
        );
    }

    return true;
}