<?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';

//dynemic db
require_once $base_path_to_learning_resources.'includes/specific_db_config.php';
require_once $base_path_to_learning . 'functions/common_functions.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;
$postdata = json_decode(file_get_contents("php://input"), true);
//print_r($postdata);
checkIfNoPhpContentsReceive();
if (
!isset($postdata['admission_id']) or !checkIfIssetAndNotEmpty($postdata['admission_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);

function fetchSpecificStudentAdmission($conn_rjllearning_specific,$admission_id,$institution_id){
    
     $res = $conn_rjllearning_specific->prepare("SELECT * FROM  student_admission WHERE id  = ? AND institution_id = ?  ");
     $res->execute(array($admission_id,$institution_id));
     $result = $res->fetchAll();
    
     if (count($result) == 1) {

        $class_info = getClass($conn_rjllearning_specific, $institution_id, $result[0]['class_admitted']);
        $section = getSection($conn_rjllearning_specific, $institution_id, $result[0]['section_admitted']);
        $branch_info =  getBranchInfo($conn_rjllearning_specific, $institution_id, $result[0]['branch_id']);

        if ($result[0]['last_tc'] != null and !is_array($result[0]['last_tc'])) {
            $last_tc_row = json_decode($result[0]['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 ($result[0]['profile_image'] != null and !is_array($result[0]['profile_image'])) {
            $profile_image_data = json_decode($result[0]['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 ($result[0]['birth_certificate'] != null and !is_array($result[0]['birth_certificate'])) {
            $birth_certificate_data = json_decode($result[0]['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 ($result[0]['nationality_proof'] != null and !is_array($result[0]['nationality_proof'])) {
            $nationality_proof_data = json_decode($result[0]['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;
        }

        $sibling = array();  // Initialize the sibling array

        if ($result[0]['sibling_bool'] == 1) {
            $sibling_bool = $result[0]['sibling_bool'];

            // Retrieve sibling admission numbers from the result
            $sibling_ids = $result[0]['sibling'];

            // Prepare the SQL query to fetch sibling details
            $sqlStudents = "SELECT id, admission_number, name FROM students WHERE institution_id = ? AND branch_id = ? AND admission_number IN ($sibling_ids)";
            $array_params = [$institution_id, $result[0]['branch_id']];
            $stmtStudents = $conn_rjllearning_specific->prepare($sqlStudents);
            $stmtStudents->execute($array_params);
            $result_students = $stmtStudents->fetchAll();
            foreach ($result_students as $rows) {
                $sibling[] = array(
                    'id' => $rows['id'],
                    'admission_number' => $rows['admission_number'],
                    'name' => $rows['name']
                );
            }
        } else {
            // Reset sibling_bool and sibling to null if no siblings are found
            $sibling_bool = 0;
            $sibling = null;
        }
        
        $student = "SELECT name, email, mobile FROM students WHERE institution_id = ? AND branch_id = ? AND id = ?";
            $array_params = [$institution_id, $result[0]['branch_id'], $result[0]['student_id']];
            $stmtstudent = $conn_rjllearning_specific->prepare($student);
            $stmtstudent->execute($array_params);
            $result_student = $stmtstudent->fetchAll();
            
            $student_name = $result_student[0]['name'];
            $student_email = $result_student[0]['email'];
            $student_mobile = $result_student[0]['mobile'];

        return  array(
            'admission_id' => $result[0]['id'],
            'branch_id' => $branch_info,
            'reg_no' => $result[0]['reg_no'],
            'date_admission' => $result[0]['date_admission'],
            'admission_number' => $result[0]['admission_number'],
            'class_admitted' => $class_info,
            'section_admitted' => $section,
            'last_tc' => $last_tc_data,
            'last_school' => $result[0]['last_school'],
            'nationality' => $result[0]['nationality'],
            'nationality_proof_number' => $result[0]['nationality_proof_number'],
            'caste' => $result[0]['caste'],
            'birth_certificate' => $final_array_birth_certificate,
            'nationality_proof' => $final_array_nationality_proof,
            'dob' => $result[0]['dob'],
            'gender' => $result[0]['gender'],
            'blood_group' => $result[0]['blood_group'],
            'address_line_1' => $result[0]['address_line_1'],
            'city' => $result[0]['city'],
            'pincode' => $result[0]['pincode'],
            'date_added' => $result[0]['date_added'],
            'added_by' => $result[0]['added_by'],
            'profile_image' => $final_array_profile,
            'sibling_bool' => $sibling_bool,
            'sibling' => $sibling,
            'name' => $student_name,
            'email' => $student_email,
            'mobile' => $student_mobile
        );

    } else {

        errorreturn("Student admission not found. Contact admin.");
    }
}
if($postdata['function_type'] == "fetch_specific_student_admission") {
    
    // $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('fetch_student_admission', $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.");
    // }
    $admission_id = trim($postdata['admission_id']);
    
    $export_type = (isset($postdata['export_type']) and !empty($postdata['export_type'])) ? trim($postdata['export_type']) : null;
      $student_id = (isset($postdata['student_id']) and !empty($postdata['student_id'])) ? trim($postdata['student_id']) : null;
    if (isset($export_type)) {
        if ($export_type == 'print') {
            require_once $base_path_to_learning . 'faculty_api/modules/student_admission/export/export_manage_student_admisson.php';
           }
    }else{

        $success['data'] = fetchSpecificStudentAdmission($conn_rjllearning_specific,$admission_id,$institution_id);
        successreturn($success);
    }
}