<?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['institution_id']) or !checkIfIssetAndNotEmpty($postdata['institution_id']) or
    !isset($postdata['student_id']) or !checkIfIssetAndNotEmpty($postdata['student_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;
$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);

function fetchSpecificStudent($conn_rjllearning_specific, $student_id, $institution_id)
{
    $res = $conn_rjllearning_specific->prepare("SELECT * FROM  students WHERE id  = ? AND institution_id = ?  ");
    $res->execute(array($student_id, $institution_id));
    $result = $res->fetchAll();
    if (count($result) != 1) {
        errorreturn("Student not found. Contact admin.");
    }

    // if (count($result) == 1) {

    $student_class_info = getClass($conn_rjllearning_specific, $institution_id, $result[0]['class_id']);
    $section = getSection($conn_rjllearning_specific, $institution_id, $result[0]['section_id']);
    $branch_info =  getBranchInfo($conn_rjllearning_specific, $institution_id, $result[0]['branch_id']);

    $res = $conn_rjllearning_specific->prepare("SELECT bus_id, route_id, stop_id FROM student_stops WHERE student_id = ? AND institution_id = ? ");
    $res->execute(array($student_id, $institution_id));
    $resultStops = $res->fetch();  // This returns false if no rows are found

    // Check if resultStops is valid
    if ($resultStops !== false) {
        $bus_id = $resultStops['bus_id'];
        $route_id = $resultStops['route_id'];
        $stop_id = $resultStops['stop_id'];
    } else {
        $bus_id = null;
        $route_id = null;
        $stop_id = null;
    }

    if ($result[0]['birth_certificate'] !=  null) {
        $birth_certificate_data = json_decode($result[0]['birth_certificate'], true);
        $filePath = $birth_certificate_data['filepath'];
        $originalName = $birth_certificate_data['original_name'];
        $aws_birth_certificate = displayFileFromS3($GLOBALS['s3_learning_bucket'], $GLOBALS['learning_bucketName'], $filePath);
        $birth_certificate   = array("filepath" => $aws_birth_certificate, "original_name" => $originalName);
    } else {
        $birth_certificate =  null;
    }

    if ($result[0]['nationality_proof'] !=  null) {
        $proof_data = json_decode($result[0]['nationality_proof'], true);
        $filePath = $proof_data['filepath'];
        $originalName = $proof_data['original_name'];
        $aws_nationality_proof = displayFileFromS3($GLOBALS['s3_learning_bucket'], $GLOBALS['learning_bucketName'], $filePath);
        $nationality_proof    = array("filepath" => $aws_nationality_proof, "original_name" => $originalName);
    } else {
        $nationality_proof =  null;
    }

    if ($result[0]['student_profile_image'] !=  null) {
        $profile_image_data = json_decode($result[0]['student_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, 1, $GLOBALS['cloudFrontDomain']);
        $student_profile_image   = array("filepath" => $aws_profile_image, "original_name" => $originalName);
    } else {
        $student_profile_image =  null;
    }

    $admission_id = $result[0]['admission_id'];

    $sqlAdmission = $conn_rjllearning_specific->prepare("SELECT date_admission,reg_no,class_admitted,section_admitted,last_tc,last_school,sibling_bool,sibling FROM  student_admission WHERE id  = ? AND institution_id = ?  ");
    $sqlAdmission->execute(array($admission_id, $institution_id));
    $resultAdmission = $sqlAdmission->fetchAll();
    //  print_R($resultAdmission);die();
    if ($resultAdmission >= 1) {
        $date_admission = $resultAdmission[0]['date_admission'];
        $reg_no = $resultAdmission[0]['reg_no'];
        // $class_info = getClass($conn_rjllearning_specific, $institution_id, $resultAdmission[0]['class_admitted']);
        // $section_info = getSection($conn_rjllearning_specific, $institution_id, $resultAdmission[0]['section_admitted']);
        // $last_tc = $resultAdmission[0]['last_tc'];
        // $last_school = $resultAdmission[0]['last_school'];
        
        // if ($resultAdmission[0]['sibling_bool'] == 1) {
        //     $sibling_bool = $resultAdmission[0]['sibling_bool'];
        //     $sibling_ids = $resultAdmission[0]['sibling'];
        //     $sqlStudents = "SELECT id, admission_number, name FROM students WHERE institution_id = ? AND admission_number IN ($sibling_ids)";
        //     $array_params = [$institution_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']
        //         );
        //     }
        // } 
        $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;
        }

        // if ($resultAdmission[0]['last_tc'] != null and !is_array($resultAdmission[0]['last_tc'])) {
        //     $last_tc_row = json_decode($resultAdmission[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;
        // }
    }

    return  array(
        'student_id' => $result[0]['id'],
        'branch_id' => $branch_info,
        'admission_id' => $result[0]['admission_id'],
        'nationality' => $result[0]['nationality'],
        'caste' => $result[0]['caste'],
        'admission_number' => $result[0]['admission_number'],
        'class' => $student_class_info,
        'section' => $section,
        'roll_no' => $result[0]['roll_no'],
        'username' => $result[0]['username'],
        'student_profile_image' => $student_profile_image,
        'birth_certificate' => $birth_certificate,
        'nationality_proof' => $nationality_proof,
        'nationality_proof_number' => $result[0]['nationality_proof_number'],
        'name' => $result[0]['name'],
        'fathername' => $result[0]['fathername'],
        'mothername' => $result[0]['mothername'],
        'father_occupation' => $result[0]['father_occupation'],
        'mother_occupation' => $result[0]['mother_occupation'],
        'mobile' => $result[0]['mobile'],
        'email' => $result[0]['email'],
        'address_line_1' => $result[0]['address_line_1'],
        'city' => $result[0]['city'],
        'pincode' => $result[0]['pincode'],
        'dob' => $result[0]['dob'],
        'gender' => $result[0]['gender'],
        'father_occupation' => $result[0]['father_occupation'],
        'mother_occupation' => $result[0]['mother_occupation'],
        'blood_group' => $result[0]['blood_group'],
        'date_admission' => $date_admission,
        'reg_no' => $reg_no,
        // 'class_admitted' => $class_info,
        // 'section_admitted' => $section_info,
        'sibling_bool' => $sibling_bool,
        'sibling' => $sibling,
        // 'last_tc' => $last_tc_data,
        // 'last_school' => $last_school,
        'bus_id' => $bus_id,
        'route_id' => $route_id,
        'stop_id' => $stop_id
    );
    // } else {

    //     errorreturn("Student not found. Contact admin.");
    // }
}
if ($postdata['function_type'] == "fetch_specific_student") {
    
    // $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_students', $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.");
    // }

    // $institution_id = trim($postdata['institution_id']);
    // $branch_id = trim($postdata['branch_id']);
    $student_id = trim($postdata['student_id']);
    $success['data'] = fetchSpecificStudent($conn_rjllearning_specific, $student_id, $institution_id);
    successreturn($success);
}
