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

$postdata = json_decode(file_get_contents("php://input"), true);
//print_r($postdata);
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  !isset($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,["principal"], 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 fetchStudentRegistration($conn_rjllearning_specific,$institution_id,$branch_id,$reg_id){
    
     $res = $conn_rjllearning_specific->prepare("SELECT * FROM  student_registration WHERE id  = ? AND institution_id = ? ");
     $res->execute(array($reg_id,$institution_id));
    
     $result = $res->fetchAll();
        // print_r($result);die();
     if(count($result) == 1)
         {
           $class_info = getClass($conn_rjllearning_specific,$institution_id,$result[0]['for_class']);
           $branch_info = getBranchInfo($conn_rjllearning_specific, $institution_id, $result[0]['branch_id']);
           $current_info = getClass($conn_rjllearning_specific,$institution_id,$result[0]['current_class']);
           $sibling = array();  // Initialize the sibling array

        if ($result[0]['sibling_bool'] == 1 && !empty($result[0]['sibling'])) {
            $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, $branch_id];
            
            // if($result[0]['sibling'] != null){
            //     $sqlStudents .= "";
            // }
            $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;
        }

           
          return array('reg_id'=> $result[0]['id'],'branch_id'=> $branch_info,'name'=> $result[0]['name'],'reg_no'=> $result[0]['reg_no'],'fathername'=> $result[0]['fathername'],'mothername'=> $result[0]['mothername'],'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'],'reg_fees'=> $result[0]['reg_fees'],'paid_through'=> $result[0]['paid_through'],'refrence_number'=> $result[0]['refrence_number'],'for_class'=> $class_info,'last_school'=> $result[0]['last_school']
          ,'current_class'=>$current_info,'sibling_bool'=>$sibling_bool,'sibling'=>$sibling);
         
     }else{
         
         errorreturn("Student registration not found. Contact admin.");
     }
     
}

if($postdata['function_type'] == "fetch_specific_student_registration") {
    
  
    // $branch_id = trim($postdata['branch_id']);
    $reg_id = trim($postdata['reg_id']);
    $success['data'] = fetchStudentRegistration($conn_rjllearning_specific,$institution_id,$branch_id,$reg_id);
    successreturn($success);

}