<?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 . 'functions/common_functions.php';
//dynemic db
require_once $base_path_to_learning_resources . 'includes/specific_db_config.php';

//aws image store
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);
//print_r($postdata);
checkIfNoPhpContentsReceive();
if (
    // !isset($postdata['institution_id']) or !checkIfIssetAndNotEmpty($postdata['institution_id'])  or
    !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);
//then workspace_id is iin decodede data of jwt use from there
$userid = $jwt_validate->data->id;
$workspace_id = $jwt_validate->data->workspace_id;
$username = $jwt_validate->data->username;
$role = $jwt_validate->data->role;
$branch_id = $jwt_validate->data->branch_id;
$institution_id = $jwt_validate->data->institution_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);

$class_id = trim($postdata['class_id']);
$section_id = ($postdata['section_id']);


$function_type = trim($postdata['function_type']);
$sql_codes = $conn_rjllearning_specific->prepare("SELECT id FROM faculty_info WHERE userid = ? AND institution_id = ? AND branch_id = ?");
$sql_codes->execute(array($userid, $institution_id, $branch_id));
$result_faculty = $sql_codes->fetch(PDO::FETCH_ASSOC);

if ($result_faculty === false) {
    errorreturn("Faculty Not Found.");
}
$faculty_id = $result_faculty['id'];

$faculty_data = getClassSectionSubjectsAndInChargeRoles($conn_rjllearning, $conn_rjllearning_specific, $institution_id, $userid);
    
$class_section_subjects  = $faculty_data['class_section_subjects'];
$class_incharge_roles = $faculty_data['class_incharge_roles'];
$staff_access_modules = $faculty_data['staff_access_modules'];

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

function fetchStudentAdmission($conn_rjllearning_specific, $userid, $institution_id,$branch_id, $conn_rjllearning,$function_type, $class_id, $section_id, $search_string, $limit, $offset)
{
    
    
    $sql = "SELECT  count(*) as total_rows FROM student_admission  where institution_id =? and branch_id=?";
    $array_params = array($institution_id,$branch_id);
    
   
    $stmt = $conn_rjllearning_specific->prepare($sql);
    $stmt->execute($array_params);
    $result_total = $stmt->fetchAll();
    
    $totalrows = $result_total[0]['total_rows'];
    if ($limit == 'all') {
        $sql = "SELECT * FROM  student_admission WHERE institution_id = ? and branch_id=?";
        $array_params = [$institution_id,$branch_id];
        if ($branch_id == 'all') {
            $sql .= "";
        } else if ($branch_id !=  null  && $branch_id != 'all') {
            $sql .= " AND branch_id = ? ";
            $array_params[] = $branch_id;
        }
        if ($search_string != null) {
            // $sql .= " AND (reg_no LIKE ? OR admission_number LIKE ? OR name LIKE ? OR mobile LIKE ? OR email LIKE ?)  ";
            $sql .= " AND (reg_no LIKE ? OR admission_number LIKE ? OR nationality LIKE ? OR city LIKE ?)  ";
            $array_params[] = '%' . $search_string . '%';
            $array_params[] = '%' . $search_string . '%';
            $array_params[] = '%' . $search_string . '%';
            $array_params[] = '%' . $search_string . '%';
            // $array_params[] = '%' . $search_string . '%';
        }
    } else {
        $sql = "SELECT * FROM  student_admission WHERE institution_id = ? and branch_id=?";
        $array_params = [$institution_id,$branch_id];
         if ($branch_id == 'all') {
            $sql .= "";
        } else if ($branch_id !=  null  && $branch_id != 'all') {
            $sql .= " AND branch_id = ? ";
            $array_params[] = $branch_id;
        }
        $sql .= " order by id desc, date_added desc ";
        $sql .= "LIMIT " . $offset . " ," . $limit . "";
    }
    $stmt = $conn_rjllearning_specific->prepare($sql);
    $stmt->execute($array_params);
    $result = $stmt->fetchAll();
    $data = array();
    foreach ($result as $rows) {
        $class_info = getClass($conn_rjllearning_specific, $institution_id, $rows['class_admitted']);
        $section = getSection($conn_rjllearning_specific, $institution_id, $rows['section_admitted']);
        $branch_info =  getBranchInfo($conn_rjllearning_specific, $institution_id, $rows['branch_id']);

        if ($rows['last_tc'] != null and !is_array($rows['last_tc'])) {
            $last_tc_row = json_decode($rows['last_tc'], true);
            $filePath = $last_tc_row['filepath'];
            $originalName = $last_tc_row['original_name'];
            $aws_last_tc = displayFileFromS3($GLOBALS['s3_learning_bucket'], $GLOBALS['learning_bucketName'], $filePath);
            $last_tc_data   = array("filepath" => $aws_last_tc, "original_name" => $originalName);
        } else {
            $last_tc_data =  null;
        }

        if ($rows['profile_image'] != null and !is_array($rows['profile_image'])) {
            $profile_image_data = json_decode($rows['profile_image'], true);
            $filePath = $profile_image_data['filepath'];
            $originalName = $profile_image_data['original_name'];
            $aws_profile_image = displayFileFromS3($GLOBALS['s3_learning_bucket'], $GLOBALS['learning_bucketName'], $filePath);
            $final_array_profile   = array("filepath" => $aws_profile_image, "original_name" => $originalName);
        } else {
            $final_array_profile =  null;
        }

        if ($rows['birth_certificate'] != null and !is_array($rows['birth_certificate'])) {
            $birth_certificate_data = json_decode($rows['birth_certificate'], true);
            $filePath = $birth_certificate_data['filepath'];
            $originalName = $birth_certificate_data['original_name'];
            $aws_birth_certificate_image = displayFileFromS3($GLOBALS['s3_learning_bucket'], $GLOBALS['learning_bucketName'], $filePath);
            $final_array_birth_certificate  = array("filepath" => $aws_birth_certificate_image, "original_name" => $originalName);
        } else {
            $final_array_birth_certificate =  null;
        }

        if ($rows['nationality_proof'] != null and !is_array($rows['nationality_proof'])) {
            $nationality_proof_data = json_decode($rows['nationality_proof'], true);
            $filePath = $nationality_proof_data['filepath'];
            $originalName = $nationality_proof_data['original_name'];
            $aws_nationality_proof_image = displayFileFromS3($GLOBALS['s3_learning_bucket'], $GLOBALS['learning_bucketName'], $filePath);
            $final_array_nationality_proof  = array("filepath" => $aws_nationality_proof_image, "original_name" => $originalName);
        } else {
            $final_array_nationality_proof =  null;
        }

        // if ($rows['admission_profile_image'] != null and !is_array($rows['admission_profile_image'])) {
        //     $admission_profile_image_data = json_decode($rows['admission_profile_image'], true);
        //     $filePath = $admission_profile_image_data['filepath'];
        //     $originalName = $admission_profile_image_data['original_name'];
        //     $aws_admission_profile_image = displayFileFromS3($GLOBALS['s3_learning_bucket'], $GLOBALS['learning_bucketName'], $filePath);
        //     $final_array_admission_profile   = array("filepath" => $aws_admission_profile_image, "original_name" => $originalName);
        // } else {
        //     $final_array_admission_profile =  null;
        // }

        $data[] = array(
            'admission_id' => $rows['id'],
            'branch_id' => $branch_info,
            'reg_no' => $rows['reg_no'],
            'date_admission' => $rows['date_admission'],
            'admission_number' => $rows['admission_number'],
            'class_admitted' => $class_info,
            'section_admitted' => $section,
            'last_tc' => $last_tc_data,
            'last_school' => $rows['last_school'],
            'nationality' => $rows['nationality'],
            'nationality_proof_number' => $rows['nationality_proof_number'],
            'caste' => $rows['caste'],
            'birth_certificate' => $final_array_birth_certificate,
            'nationality_proof' => $final_array_nationality_proof,
            'dob' => $rows['dob'],
            'gender' => $rows['gender'],
            'blood_group' => $rows['blood_group'],
            'address_line_1' => $rows['address_line_1'],
            'city' => $rows['city'],
            'pincode' => $rows['pincode'],
            'date_added' => $rows['date_added'],
            'added_by' => $rows['added_by'],
            'profile_image' => $final_array_profile,
            'sibling_bool' => $rows['sibling_bool'],
            'sibling' => $rows['sibling'],
            'student_id' => $rows['student_id'],
        );
    }

    if (count($result) < 50) {
        return array('total_rows' => $totalrows, 'student_admission' => $data, 'maxreach' => 1);
    } else {
        return array('total_rows' => $totalrows, 'student_admission' => $data, 'maxreach' => 0);
    }
}


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

    // $institution_id = trim($postdata['institution_id']);
    // $branch_id = trim($postdata['branch_id']);
    $limit = $postdata['limit'];
    $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($postdata['function_type'], $class_section_subjects, $class_incharge_roles, $staff_access_modules, null, null, null, $conn_rjllearning);
    if ($check_faculty_status == false) {
        errorreturn("Access denied: You do not have the required permissions.");
    }

    $page = (isset($postdata['page']) and isNumeric($postdata['page'])) ? (int)$postdata['page'] : 1;
    $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['branch_id']) and !empty($postdata['branch_id'])) {
    //     $branch_id = trim($postdata['branch_id']);
    // } else {
    //     $branch_id = null;
    // }
    if ($limit != 'all') {
        $offset = ($page - 1) * $limit;
        $success['data'] = fetchStudentAdmission($conn_rjllearning_specific, $userid, $institution_id,$branch_id, $conn_rjllearning,$function_type, $class_id, $section_id, $search_string, $limit, $offset);
        successreturn($success);
    } else {
        $success['data'] = fetchStudentAdmission($conn_rjllearning_specific, $userid, $institution_id,$branch_id, $conn_rjllearning,$function_type, $class_id, $section_id, $search_string, $limit, null);
        successreturn($success);
    }
}
