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

require_once '../../resources/base_path_include.php';
require_once $base_path_to_learning_resources  . "includes/connect.php"; // use require for mandatory files
require_once $base_path_to_learning_resources . 'lib/function.php';
require_once $base_path_to_learning_resources . 'lib/validate_api_signature.php';

//valdation file
require_once $base_path_to_learning_resources . 'lib/validate_function.php';
require_once $base_path_to_learning . '/user_management/check_username_availability.php';
require_once $base_path_to_learning . 'user_management/authenticate.php';
require_once $base_path_to_learning . 'admin_api/academic_session/functions/registration_functions.php';

require_once $base_path_to_learning . 'functions/common_functions.php';

//db access function
require_once $base_path_to_learning_resources . 'includes/specific_db_config.php';
require_once $base_path_to_learning . 'user_management/faculty/functions.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';

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

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

if (
    !isset($postdata['api_signature']) or !checkIfIssetAndNotEmpty($postdata['api_signature']) or
    !isset($postdata['function_type']) or !checkIfIssetAndNotEmpty($postdata['function_type'])  or
    !isset($postdata['jwt_token']) or  !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;

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

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

if ($role == 'principal' or $role == 'teacher') {
    $institution_id = $jwt_validate->data->institution_id;
    $branch_id = $jwt_validate->data->branch_id;


    $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);
}

if ($role == 'admin' or $role == 'superadmin') {
    if (!isset($postdata['institution_id']) or !checkIfIssetAndNotEmpty($postdata['institution_id'])) {
        errorreturn("institution field is required.");
    } else {
        $institution_id = $postdata['institution_id'];
        if (isset($postdata['branch_id']) and !empty($postdata['branch_id'])) {
            $branch_id = trim($postdata['branch_id']);
        } else {
            $branch_id = "all";
        }
    }
}

if ($postdata['function_type']  == "fetch_faculty") {

    $check_academic_confirmation = CheckAcademicSession($conn_rjllearning_specific, $institution_id);

    if ($check_academic_confirmation != true) {
        errorreturn("Access denied. Academic session not active.");
    }

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

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

    if (array_key_exists('faculty_status', $postdata)) {
        $faculty_status = trim($postdata['faculty_status']);
        // Only set to null if it's an empty string, but keep 0 as valid
        if ($faculty_status === '') {
            $faculty_status = null;
        }
    } else {
        $faculty_status = null;
    }
    
    if (array_key_exists('registered_bool_epf_esi', $postdata)) {
        $registered_bool_epf_esi = trim($postdata['registered_bool_epf_esi']);
        // Only set to null if it's an empty string, but keep 0 as valid
        if ($registered_bool_epf_esi === '') {
            $registered_bool_epf_esi = null;
        }
    } else {
        $registered_bool_epf_esi = null;
    }

    // $registered_bool_epf_esi = $postdata['registered_bool_epf_esi'] && !empty($postdata['registered_bool_epf_esi'])
    //     ? ($postdata['registered_bool_epf_esi'])
    //     : null;

    $date_filter = isset($postdata['date_filter']) && !empty($postdata['date_filter'])
        ? date('Y-m-d', strtotime($postdata['date_filter']))
        : null;

    $date_comparison = isset($postdata['date_comparison']) && !empty($postdata['date_comparison'])
        ? ($postdata['date_comparison'])
        : null;

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

    $additionaldata = ['name', 'gender', 'email', 'mobile', 'designation', 'role', 'dob', 'father_name', 'userid', 'id', 'registered_bool_epf_esi', 'date_of_joining_as_per_registration'];

    if (isset($postdata['additional_data']) && is_array($postdata['additional_data'])) {
        if ($role == 'admin' or $role == 'superadmin') {
            if (!in_array('branch_id', $postdata['additional_data'])) {
                $postdata['additional_data'][] = 'branch_id';
            }
        }
        $additionaldata = array_merge($additionaldata, $postdata['additional_data']);
    }

    $limit = $postdata['limit'];

    if ($limit != 'all') {
        $offset = ($page - 1) * $limit;
    } else {
        $offset = null;
    }

    $export_type = (isset($postdata['export_type']) and !empty($postdata['export_type'])) ? trim($postdata['export_type']) : null;
    if (isset($export_type)) {
        if ($export_type == 'spreadsheet') {
            require_once $base_path_to_learning_resources . 'lib/common_modules/export/faculty_data/excel/export_manage_faculty_excel.php';
        }
        // else  if ($export_type == 'pdf') {
        //     require_once $base_path_to_learning . 'admin_api/modules/students/export/pdf/export_manage_students_pdf.php';
        // } else  if ($export_type == 'print') {
        //     require_once $base_path_to_learning . 'admin_api/modules/students/export/print/export_manage_students_print.php';
        // }
    } else {
        $success['data'] = GetBasicfacultyDetail($conn_rjllearning, $conn_rjllearning_specific, $institution_id, $branch_id, $search_string, $limit, $offset, $additionaldata, $role_option, $faculty_status, $registered_bool_epf_esi, $date_filter, $date_comparison);
        successreturn($success);
    }
}
