<?php

ini_set('display_errors', 1);
// this file is used to create all other users except superadmin
require_once '../../../../resources/base_path_include.php';
require_once $base_path_to_learning_resources  . "includes/connect.php";
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/authenticate.php';
require_once $base_path_to_learning .'functions/common_functions.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;
//db access function
require_once $base_path_to_learning_resources . 'includes/specific_db_config.php';

$postdata = json_decode(file_get_contents("php://input"), true);

validateCurlSignature($postdata['api_signature']);

$data = $postdata['data'];
// echo json_encode($data);die();
$workspace_id = $data['workspace_id'];
$learning_branch_id = $data['learning_branch_id'];
$sql = "Select db_name from workspace_database_info where workspace_id = ? and  status = ?";
$fetch_workspace = $conn_rjllearning->prepare($sql);
$fetch_workspace->execute(array($workspace_id, 1));
$result_workspace = $fetch_workspace->fetchAll();
// echo json_encode($result_workspace);die();
if (count($result_workspace) < 1) {
    errorreturn('Fatal error (1). Access denied.');
}

$specific_db_name = $result_workspace[0]['db_name'];

$conn_rjllearning_specific = dynamicDbConnection($specific_db_name);


$sql = $conn_rjllearning_specific->prepare("SELECT institution_id,rejoice_solutions_company_id,rejoice_solutions_branch_id,rejoice_finware_book_id FROM branch WHERE id = ?");
$sql->execute(array($learning_branch_id));
$result = $sql->fetchAll();
if (count($result) < 1 || (is_null($result[0]['rejoice_solutions_company_id']) && is_null($result[0]['rejoice_solutions_branch_id']) && is_null($result[0]['rejoice_finware_book_id']))) {
//   header('Content-Type: application/json');
//   echo json_encode([
//     'error' => true,
//     'message' => 'This branch not connected.Kindly contact admin.'
//   ]);
//   die();
return false;
}

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

$institution_data =  getInstitution($conn_rjllearning, $institution_id);
$additional_data = array();
$additional_data = ['id', 'name','address','contact_number','email','affiliation_code'];
$branch = getBranchInfo($conn_rjllearning_specific, $institution_id, $learning_branch_id, $additional_data);

echo json_encode(array('institution_data'=>$institution_data,'branch'=>$branch));
die();


