<?php

ini_set('display_errors', 1);
//error_reporting(0);
require_once '../resources/base_path_include.php';
// should we not call header and ch
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 . 'includes/specific_db_config.php';
require_once $base_path_to_learning_resources . 'lib/validate_api_signature.php';
$postdata = json_decode(file_get_contents("php://input"), true);

if ( !isset($postdata['api_signature']) or !checkIfIssetAndNotEmpty($postdata['api_signature']) or 
!isset($postdata['function_type']) or !checkIfIssetAndNotEmpty($postdata['function_type']) or 
!isset($postdata['workspace_id']) or !checkIfIssetAndNotEmpty($postdata['workspace_id']) or 
!isset($postdata['institution_id']) or !checkIfIssetAndNotEmpty($postdata['institution_id'])) {
    errorreturn("All * fields are required.");
}

validateApiSignature($postdata['api_signature']);


$workspace_id = $postdata['workspace_id'];
$institution_id = $postdata['institution_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();
// print_r($result_workspace);
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);


if ($postdata['function_type'] == "fetch_institution_branch") {

$sql = "Select id,branch_code,name FROM  branch WHERE institution_id = ? ";
$stmt = $conn_rjllearning_specific->prepare($sql);
$stmt->execute(array($institution_id));
$result = $stmt->fetchAll();
$array_return = [];
foreach ($result as $res) {
    $array_return[] = array('branch_id'=> $res['id'],'branch_code'=>$res['branch_code'] ,'name' => $res['name']);
}
successreturn($array_return);

}
