<?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';
//db access function
require_once $base_path_to_learning_resources . 'includes/specific_db_config.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);
//print_r($postdata);
checkIfNoPhpContentsReceive();
if (
    !isset($postdata['faculty_id']) or !checkIfIssetAndNotEmpty($postdata['faculty_id']) or
    // !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);
$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 = null;
            }
      }
}

function getSpecificFaculty($conn_rjllearning_specific, $institution_id, $faculty_id, $conn_rjllearning)
{
    // reeturns all data from the specific row of the profile
    $sql_faculty = $conn_rjllearning_specific->prepare("SELECT * FROM   faculty_info where id = ? and institution_id =? ");
    $sql_faculty->execute(array($faculty_id, $institution_id));
    $rows = $sql_faculty->fetchAll();

    if (count($rows) == 1) {
        
        $left_teacher_info = null;
        $sql_left_teacher = $conn_rjllearning_specific->prepare("SELECT * FROM left_teachers WHERE teacher_id = ? AND institution_id = ?");
        $sql_left_teacher->execute(array($faculty_id, $institution_id));
        $left_teacher_data = $sql_left_teacher->fetchAll();

        if (count($left_teacher_data) > 0) {
            $left_teacher_info = array(
                'id' => $left_teacher_data[0]['id'],
                'date_of_leaving' => $left_teacher_data[0]['date_of_leaving'],
                'reason' => $left_teacher_data[0]['reason']
            );
        }
        
        $sql_staff = $conn_rjllearning_specific->prepare("SELECT * FROM other_staff_details where faculty_id = ? and institution_id =? ");
        $sql_staff->execute(array($faculty_id, $institution_id));
        $result_staff = $sql_staff->fetchAll();
         $other_staff_details = null;
        if(count($result_staff) == 1){
            
            if ($result_staff[0]['adhar_card'] != null) {
                $data_attachment = json_decode($result_staff[0]['adhar_card'], true);
                $filePath = $data_attachment['filepath'];
                $originalName = $data_attachment['original_name'];
                $aws_image = displayFileFromS3($GLOBALS['s3_learning_bucket'], $GLOBALS['learning_bucketName'], $filePath);
                $final_adhar_card  = array("filepath" => $aws_image, "original_name" => $originalName);
             } else {
                $final_adhar_card =  null;
            }
            
            if ($result_staff[0]['pan_card'] != null) {
                $data_attachment = json_decode($result_staff[0]['pan_card'], true);
                $filePath = $data_attachment['filepath'];
                $originalName = $data_attachment['original_name'];
                $aws_image = displayFileFromS3($GLOBALS['s3_learning_bucket'], $GLOBALS['learning_bucketName'], $filePath);
                $final_pan_card  = array("filepath" => $aws_image, "original_name" => $originalName);
             } else {
                $final_pan_card =  null;
            }
            
             if ($result_staff[0]['driving_licence'] != null) {
                $data_attachment = json_decode($result_staff[0]['driving_licence'], true);
                $filePath = $data_attachment['filepath'];
                $originalName = $data_attachment['original_name'];
                $aws_image = displayFileFromS3($GLOBALS['s3_learning_bucket'], $GLOBALS['learning_bucketName'], $filePath);
                $final_driving_licence  = array("filepath" => $aws_image, "original_name" => $originalName);
             } else {
                $final_driving_licence =  null;
            }
            
            $other_staff_details =  array('print_bank_details'=>$result_staff[0]['print_bank_details'],
            'account_holder_name'=>$result_staff[0]['account_holder_name'],
            'account_name'=>$result_staff[0]['account_name'],
            'account_no'=>$result_staff[0]['account_no'],
            'ifsc_code'=>$result_staff[0]['ifsc_code'],
            'branch_address'=>$result_staff[0]['branch_address'],
            'account_type'=>$result_staff[0]['account_type'],
            'adhar_card'=>$final_adhar_card,
            'pan_card'=>$final_pan_card,
            'driving_licence'=>$final_driving_licence,
            'driving_expiry_date'=>$result_staff[0]['driving_expiry_date']);
        }
        
        // $sql_staff_group = $conn_rjllearning_specific->prepare("SELECT * FROM other_staff_groups where id = ? and institution_id =? ");
        // $sql_staff_group->execute(array($rows[0]['other_staff_group_id'], $institution_id));
        // $result_staff_group = $sql_staff_group->fetchAll();
        // $other_staff_groups =  null;
        // if(count($result_staff_group) == 1){
            
        //     $other_staff_groups = array('id'=>$result_staff_group[0]['id'],'group_name'=>$result_staff_group[0]['group_name']);
        // }
        $username = null;
        $status = null;
        $can_activate = null;
        
        if (!empty($rows[0]['userid'])) {
            $stmt_fetch_user = $conn_rjllearning->prepare("
                SELECT username, status, can_activate 
                FROM users 
                WHERE id = ?
            ");
            $stmt_fetch_user->execute([$rows[0]['userid']]);
            $user_info = $stmt_fetch_user->fetch(PDO::FETCH_ASSOC);
        
            // Assign values or null if not found
            $username = $user_info['username'] ?? null;
            $status = $user_info['status'] ?? null;
            $can_activate = $user_info['can_activate'] ?? null;
        }

        // $fieldarray['status'] = $user_info['status'] ?? null;
        // $fieldarray['can_activate'] = $user_info['can_activate'] ?? null;
        
        // print_r($result_staff);die();
        if ($rows[0]['profile_image'] != null) {

            $data_attachment = json_decode($rows[0]['profile_image'], true);
            $filePath = $data_attachment['filepath'];
            $originalName = $data_attachment['original_name'];
            $aws_image = displayFileFromS3($GLOBALS['s3_learning_bucket'], $GLOBALS['learning_bucketName'], $filePath,1,$GLOBALS['cloudFrontDomain']);
            $final_array_image   = array("filepath" => $aws_image, "original_name" => $originalName);
        } else {
            $final_array_image =  null;
        }

        $country = $rows[0]['country'];
        $sql = $conn_rjllearning->prepare("SELECT * FROM  country_info  where id = ?");
        $sql->execute(array($country));
        $rows_country = $sql->fetchAll();
        if (count($rows_country) == 1) {
            $country_id = array('id' => $rows_country[0]['id'], 'name' => $rows_country[0]['name']);
        }

        $state = $rows[0]['state'];
        $sql = $conn_rjllearning->prepare("SELECT * FROM state_info WHERE id = ?");
        $sql->execute([$state]);
        $rows_state = $sql->fetchAll(PDO::FETCH_ASSOC);
        $state_id = null;
        if (isset($rows_state[0])) {
            $state_id = ['id' => $rows_state[0]['id'], 'name' => $rows_state[0]['state']];
        }
        // $state_data = array(
        //         'id' => $rows_state[0]['id'],
        //         'name' => $rows_state[0]['state']
        //     );

        $branch_info  = getBranchInfo($conn_rjllearning_specific, $institution_id, $rows[0]['branch_id']);
        return array(
            'faculty_id' => $rows[0]['id'],
            'institution_id' => $rows[0]['institution_id'],
            'branch_id' => $branch_info,
            'userid' => $rows[0]['userid'],
            'name' => $rows[0]['name'],
            'gender' => $rows[0]['gender'],
            'email' => $rows[0]['email'],
            'mobile' => $rows[0]['mobile'],
            'designation' => $rows[0]['designation'],
            'father_name' => $rows[0]['father_name'],
            'mother_name' => $rows[0]['mother_name'],
            'role' => $rows[0]['role'],
            'spouse_name' => $rows[0]['spouse_name'],
            'nationality' => $rows[0]['nationality'],
            'dob' => $rows[0]['dob'],
            'address' => $rows[0]['address'],
            'username' => $username ,
            'city' => $rows[0]['city'],
            'state' => $state_id,
            'pincode' => $rows[0]['pincode'],
            'country' => $country_id,
            'status' => $rows[0]['status'],
            "profile_image" => $final_array_image,
            'other_staff_group_id' => $rows[0]['other_staff_group_id'],
            'date_of_joining' => $rows[0]['date_of_joining'],
            'registered_bool_epf_esi' => $rows[0]['registered_bool_epf_esi'],
            'date_of_joining_as_per_registration' => $rows[0]['date_of_joining_as_per_registration'],
            'date_of_termination' => $rows[0]['date_of_termination'],
            'other_staff_details'=>$other_staff_details,
            'left_teacher_info' => $left_teacher_info 
        );
    } else {
        errorreturn("Enter Invalid Faculty Info.");
    }
}

if ($postdata['function_type']  == "fetch_specific_faculty") {
    $faculty_id = trim($postdata['faculty_id']);
    // $institution_id = $postdata['institution_id'];

    $check_academic_confirmation = CheckAcademicSession($conn_rjllearning_specific, $institution_id);
    if ($check_academic_confirmation != true) {
        errorreturn("Access denied. Academic session not active.");
    }
    $success['data'] = getSpecificFaculty($conn_rjllearning_specific, $institution_id, $faculty_id, $conn_rjllearning);
    successreturn($success);
}
