<?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/authenticate.php';

//dynemic db
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);
// $postdata = $_POST;
checkIfNoPhpContentsReceive();
// print_r($postdata);die();
if (
    !isset($postdata['institution_id']) or !checkIfIssetAndNotEmpty($postdata['institution_id']) or
    !isset($postdata['group_name']) or !checkIfIssetAndNotEmpty($postdata['group_name'])  
    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;

$specific_db_name = validateUserAccess($conn_rjllearning, $userid, $role, $workspace_id,['superadmin','admin'],null);
if (!$specific_db_name) {
    errorreturn('Access denied.');
} else {
    $conn_rjllearning_specific = dynamicDbConnection($specific_db_name);
}
require_once $base_path_to_learning . 'functions/common_functions.php';
require_once $base_path_to_learning . 'functions/get_branch_functions.php';

$institution_id = ($postdata['institution_id']);
$branch_id = ($postdata['branch_id']);
$group_name = ucwords(strtolower(trim($postdata['group_name'])));
$date_now = date('Y-m-d');

if ($branch_id != 'all') {

    if (!is_array($branch_id) or count($branch_id) <= 0) {
        errorreturn("Select atleast one branch.");
    }

    $imploded_branch_ids = "('" . implode("','", $branch_id) . "')";
    $count_ids = count($branch_id);

    $sql_codes = $conn_rjllearning_specific->prepare("Select count(*) as total from  branch WHERE id IN $imploded_branch_ids and status =? ");
    $sql_codes->execute(array('1'));
    $result_branch = $sql_codes->fetchAll()[0]['total'];
    if ($result_branch != $count_ids) {
        errorreturn("Branch Not Found.");
    }
    $imploded_branchids = "'" . implode("','", $branch_id) . "'";
} else {

    $imploded_branchids = $branch_id;
}

if ($postdata['function_type'] == 'create_staff_groups') {

        //check ledger categries exists or not
        $sql = "Select group_name from   other_staff_groups where institution_id = ? AND group_name = ? ";
        $fetch_category = $conn_rjllearning_specific->prepare($sql);
        $fetch_category->execute(array($institution_id,$group_name));
        if (count($fetch_category->fetchAll()) > 0) {
            
            errorreturn('Staff groups already exists');
        }
        
    
        $sql = "Insert into  other_staff_groups(institution_id, branch_id,group_name,added_by,time_created, date_created,status) values (?, ?, ?, ? ,? ,?,?)";
        $insert_ledger = $conn_rjllearning_specific->prepare($sql);
        $insert_ledger->execute(array($institution_id, $imploded_branchids, $group_name,$username,time(),$date_now,1));
        $group_id = $conn_rjllearning_specific->lastInsertId();
        successreturn(array('id' => $group_id, 'successmsg' => "Staff group added successfully."));
      
} if (!isset($postdata['staff_group_id']) or !checkIfIssetAndNotEmpty($postdata['staff_group_id']) and !checkIfIssetAndNotEmpty($postdata['staff_group_id']) ) {
            errorreturn('Error in updating the group id.');
        } else {
            $group_id = $postdata['staff_group_id'];
        }

        if ($postdata['function_type'] == 'alter_staff_groups') {
            $placeholders = implode(',', array_fill(0, count($branch_id), '?'));
            $sql = "SELECT group_name FROM other_staff_groups WHERE id != ? AND institution_id = ? AND group_name = ? AND branch_id IN ($placeholders)";
            $params = array_merge([$group_id, $institution_id, $group_name], $branch_id);
            $fetch_staff = $conn_rjllearning_specific->prepare($sql);
            $fetch_staff->execute($params);
            $result_staff = $fetch_staff->fetchAll();
    
            if (count($result_staff) > 0) {
                errorreturn('Staff group already exists.');
            }
       
            $sql = "Update other_staff_groups set branch_id = ? ,group_name = ?, time_created = ? where id = ? and institution_id = ?";
            $insert_ledger = $conn_rjllearning_specific->prepare($sql);
            $insert_ledger->execute(array($imploded_branchids,$group_name, time(),$group_id, $institution_id));
        
            successreturn('Staff group updated successfully.');
        }
        errorreturn('Invalid request.');
