<?php
ini_set('display_errors', 1);

require_once '../../../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/validate_api_signature.php';
require_once $base_path_to_learning_resources . 'lib/validate_function.php';
require_once $base_path_to_learning . 'user_management/authenticate.php';
require_once $base_path_to_learning . 'admin_api/academic_session/functions/validate_faculty.php';
require_once $base_path_to_learning . 'admin_api/academic_session/functions/functions.php';
require_once $base_path_to_learning . 'functions/common_functions.php';
require_once $base_path_to_learning_resources . 'includes/specific_db_config.php';
require_once $base_path_to_learning_resources . 'lib/bucket_functions/bucket_functions.php';
require_once $base_path_to_learning . "vendor/autoload.php";
require_once $base_path_to_learning_resources . 'includes/aws_bucket_config.php';
require_once $base_path_to_learning . "faculty_api/faculty_function/common_faculty_function.php";
require_once $base_path_to_learning . "principal_api/principal_function/principal_function.php";

use Aws\S3\S3Client;
use Aws\S3\Exception\S3Exception;

$postdata = json_decode(file_get_contents("php://input"), true);
checkIfNoPhpContentsReceive();

if (
    !isset($postdata['api_signature']) || !checkIfIssetAndNotEmpty($postdata['api_signature']) ||
    !isset($postdata['function_type']) || !checkIfIssetAndNotEmpty($postdata['function_type']) ||
    !isset($postdata['jwt_token']) || !checkIfIssetAndNotEmpty($postdata['jwt_token'])
) {
    errorreturn("All * fields are required.");
}

validateApiSignature($postdata['api_signature']);

$jwttoken = $postdata['jwt_token'];
$jwt_validate = authenticate_jwt($jwttoken);
$userid = $jwt_validate->data->id;
$workspace_id = $jwt_validate->data->workspace_id;
$username = $jwt_validate->data->username;
$role = $jwt_validate->data->role;
$institution_id = $jwt_validate->data->institution_id;
$branch_id = $jwt_validate->data->branch_id;

$specific_db_name = validateUserAccess($conn_rjllearning, $userid, $role, $workspace_id,["teacher"], null);
if (!$specific_db_name) {
    errorreturn('Access denied.');
} else {
    $conn_rjllearning_specific = dynamicDbConnection($specific_db_name);
}

require_once $base_path_to_learning . 'user_management/user_versioning.php';

$version = isset($_POST['version']) ? $_POST['version'] : (isset($postdata['version']) ? $postdata['version'] : null);
$updated_time = isset($_POST['updated_time']) ? $_POST['updated_time'] : (isset($postdata['updated_time']) ? $postdata['updated_time'] : null);

$response = user_data_refresh($conn_rjllearning,$conn_rjllearning_specific, $version, $updated_time, $userid, $institution_id);

$Faculty_Codes = $conn_rjllearning_specific->prepare("SELECT id FROM faculty_info WHERE userid = ? AND institution_id = ? AND branch_id = ?");
$Faculty_Codes->execute(array($userid, $institution_id, $branch_id));

// Fetch a single row instead of all
$result_faculty = $Faculty_Codes->fetch(PDO::FETCH_ASSOC);

// Check if the faculty exists
if ($result_faculty === false) {
    errorreturn("Faculty Not Found.");
}

// Retrieve the faculty_id from the result
$faculty_id = $result_faculty['id'];
$function_type=$postdata['function_type'];

function getAlumni($conn_rjllearning_specific, $institution_id, $search_string, $branch_id, $class_id, $section_id, $limit, $faculty_id, $function_type, $conn_rjllearning, $userid, $offset)
{
    // Validate that either search string or branch/class is provided
    // if (empty($search_string) && (empty($branch_id) || $branch_id == 'all') && (empty($class_id) || $class_id == 'all')) {
    //     errorreturn("Either search term or branch/class filters are required");
    // }
    
    if (empty($search_string) && (empty($class_id)) && (empty($section_id))) {
        errorreturn("Either search or class-section filters are required");
    }
    
    $teacher_data = getClassSectionSubjectsAndInChargeRoles($conn_rjllearning, $conn_rjllearning_specific, $institution_id, $userid);
    $class_section_subjects  = $teacher_data['class_section_subjects'];

    $class_incharge_roles = $teacher_data['class_incharge_roles'];
    $staff_access_modules = $teacher_data['staff_access_modules'];

    $check_faculty_status = checkFacultyModuleGranted($function_type, $class_section_subjects, $class_incharge_roles, $staff_access_modules, $class_id, $section_id, null, $conn_rjllearning);
    if($check_faculty_status == false){
            errorreturn("Access denied: You do not have the required permissions.");
    }

    $sql_count = "SELECT count(*) as total_rows FROM left_students ls 
    JOIN students s ON ls.student_id = s.id AND ls.institution_id = s.institution_id
    LEFT JOIN class_info ci ON ls.class_id = ci.id AND ls.institution_id = ci.institution_id
    LEFT JOIN section_info si ON ls.section_id = si.id AND ls.institution_id = si.institution_id
    WHERE ls.institution_id = ?";

    $sql_session = "SELECT ls.* FROM left_students ls
                  JOIN students s ON ls.student_id = s.id AND ls.institution_id = s.institution_id
                  LEFT JOIN class_info ci ON ls.class_id = ci.id AND ls.institution_id = ci.institution_id
                  LEFT JOIN section_info si ON ls.section_id = si.id AND ls.institution_id = si.institution_id
                  WHERE ls.institution_id = ?";

    $array_params = [$institution_id];

    // if ($search_string != null) {
   if (!empty($search_string)) {    
        $search_condition = " AND (
            ls.caste LIKE ? 
            OR s.name LIKE ? 
            OR ci.classname LIKE ? 
            OR si.section_name LIKE ? 
            OR s.admission_number LIKE ?
        )";
        $sql_count .= $search_condition;
        $sql_session .= $search_condition;
    
        $array_params[] = '%' . $search_string . '%'; // caste
        $array_params[] = '%' . $search_string . '%'; // student name
        $array_params[] = '%' . $search_string . '%'; // class name
        $array_params[] = '%' . $search_string . '%'; // section name
        $array_params[] = '%' . $search_string . '%'; // admission number
    }

    if (!empty($branch_id) && $branch_id != 'all') {
        $branch_condition = " AND ls.branch_id = ?";
        $sql_count .= $branch_condition;
        $sql_session .= $branch_condition;
        $array_params[] = $branch_id;
    }

    // if (!empty($class_id) && $class_id != 'all') {
    //     $class_condition = " AND ls.class_id = ?";
    //     $sql_count .= $class_condition;
    //     $sql_session .= $class_condition;
    //     $array_params[] = $class_id;
    // }
    
    $sql_append_data = facultyFilterQueryAppend($sql_count, $array_params, $function_type, $class_section_subjects, $class_incharge_roles, $staff_access_modules, $class_id, $section_id, null, $conn_rjllearning, 1, 1, 1, 1);
    $sql_count = $sql_append_data['sql']; // Get the modified SQL
    $array_params =  $sql_append_data['array_params'];

    $stmt = $conn_rjllearning_specific->prepare($sql_count);
    $stmt->execute($array_params);
    $result_total = $stmt->fetchAll();
    $totalrows = $result_total[0]['total_rows'];
    
    $sql_append_data = facultyFilterQueryAppend($sql_session, $array_params, $function_type, $class_section_subjects, $class_incharge_roles, $staff_access_modules, $class_id, $section_id, null, $conn_rjllearning, 1, 1, 1, 1);
    $sql_session = $sql_append_data['sql']; // Get the modified SQL
    $array_params =  $sql_append_data['array_params'];

    if ($limit != 'all') {
        $sql_session .= " LIMIT " . $offset . ", " . $limit;
    }

    $stmt = $conn_rjllearning_specific->prepare($sql_session);
    $stmt->execute($array_params);
    $session_rows = $stmt->fetchAll();

    $array_return = [];

    foreach ($session_rows as $row) {
        $student_sql = "SELECT * FROM students WHERE institution_id = ? and can_activate = 0 and status = 0 and id = ?";
        $student_stmt = $conn_rjllearning_specific->prepare($student_sql);
        $student_stmt->execute([$institution_id, $row['student_id']]);
        $student_result = $student_stmt->fetchAll(PDO::FETCH_ASSOC);

        if (!empty($student_result)) {
            $student_id = $student_result[0]['id'];
            $student_name = $student_result[0]['name'];
            $student_father_name = $student_result[0]['fathername'];
            $admission_id = $student_result[0]['admission_id'];
            $admission_number = $student_result[0]['admission_number'];
            $status = $student_result[0]['status'];
        } else {
            $student_id = null;
            $student_name = null;
            $student_father_name = null;
            $admission_id = null;
            $admission_number = null;
            $status = null;
        }

        $branch_info = getBranchInfo($conn_rjllearning_specific, $institution_id, $row['branch_id']);
        $class_info = getClass($conn_rjllearning_specific, $institution_id, $row['class_id']);

        $section_info = [];
        $section_id = $row['section_id'];
        if ($section_id == 'all') {
            $section_info[] = ['section_id' => $section_id, 'section_name' => ucwords($section_id)];
        } else {
            $sql = "SELECT * FROM section_info WHERE institution_id = ? AND id = ?";
            $stmt = $conn_rjllearning_specific->prepare($sql);
            $stmt->execute([$institution_id, $section_id]);
            $section_data = $stmt->fetch(PDO::FETCH_ASSOC);
            if ($section_data) {
                $section_info[] = ['section_id' => $section_data['id'], 'section_name' => $section_data['section_name']];
            }
        }

        $array_return[] = [
            'alumni_id' => $row['id'],
            'student_id' => $student_id,
            'name' => $student_name,
            'fathername' => $student_father_name,
            'branch_info' => $branch_info,
            'class_info' => $class_info,
            'class_in_words' => $row['class_in_words'],
            'section_info' => $section_info,
            'admission_id' => $admission_id,
            'admission_number' => $admission_number,
            'nationality' => $row['nationality'],
            'caste' => $row['caste'],
            'date_admission' => $row['date_admission'],
            'dob' => $row['dob'],
            'school_last_examination' => $row['school_last_examination'],
            'failed_same_class' => $row['failed_same_class'],
            'subject_studied' => $row['subject_studied'],
            'promotion_higher_class' => $row['promotion_higher_class'],
            'paid' => $row['paid'],
            'fee_concession' => $row['fee_concession'],
            'working_days' => $row['working_days'],
            'conduct' => $row['conduct'],
            'ncc' => $row['ncc'],
            'present_days' => $row['present_days'],
            'class_in_figure' => $row['class_in_figure'],
            'extra_curricular_activities' => $row['extra_curricular_activities'],
            'date_application_certificate' => $row['date_application_certificate'],
            'date_issue_certificate' => $row['date_issue_certificate'],
            'reasons_leaving_school' => $row['reasons_leaving_school'],
            'remarks' => $row['remarks'],
            'status' => $status,
        ];
    }

    if (count($array_return) < 50) {
        return ['total_rows' => $totalrows, 'alumni_info' => $array_return, 'maxreach' => 1];
    } else {
        return ['total_rows' => $totalrows, 'alumni_info' => $array_return, 'maxreach' => 0];
    }
}

if ($postdata['function_type'] == "fetch_left_alumni") {
    
    $check_academic_confirmation = CheckAcademicSession($conn_rjllearning_specific, $institution_id);
    if ($check_academic_confirmation != true) {
        errorreturn("Access denied. Academic session not active.");
    }

    // $branch_id = isset($postdata['branch_id']) && !empty($postdata['branch_id']) ? trim($postdata['branch_id']) : null;
    $class_id = isset($postdata['class_id']) && !empty($postdata['class_id']) ? trim($postdata['class_id']) : null;
    $section_id = isset($postdata['section_id']) && !empty($postdata['section_id']) ? trim($postdata['section_id']) : null;
    $search_string = isset($postdata['search_string']) && !empty($postdata['search_string']) ? trim($postdata['search_string']) : null;
    $nationality = isset($postdata['nationality']) && !empty($postdata['nationality']) ? trim($postdata['nationality']) : null;
    $caste = isset($postdata['caste']) && !empty($postdata['caste']) ? trim($postdata['caste']) : null;
    $admission_number = isset($postdata['admission_number']) && !empty($postdata['admission_number']) ? trim($postdata['admission_number']) : null;
    $dob = isset($postdata['dob']) && !empty($postdata['dob']) ? trim($postdata['dob']) : null;

    if (isset($postdata['name']) and !empty($postdata['name'])) {
        $name = trim($postdata['name']);
    } else {
        $name = null;
    }


    $limit = $postdata['limit'];
    $page = isset($postdata['page']) && isNumeric($postdata['page']) ? (int)$postdata['page'] : 1;

    $offset = $limit != 'all' ? ($page - 1) * $limit : null;
    $success['data'] = getAlumni($conn_rjllearning_specific, $institution_id, $search_string, $branch_id, $class_id,$section_id, $limit, $faculty_id, $function_type, $conn_rjllearning, $userid, $offset);
    successreturn($success);
}
?>
