<?php

ini_set('display_errors', 1);

require_once '../../../../resources/base_path_include.php';

require_once $base_path_to_resources . "includes/config.php"; // use require for mandatory files
require_once $base_path_to_resources . 'lib/function.php';
require_once $base_path_to_resources . "lib/currency_functions.php";
require_once $base_path_to_resources . 'lib/validate_api_signature.php';
require_once $base_path_to_resources . 'lib/validate_function.php';

//valdation file

require_once $base_path . 'user_management/authenticate.php';
//creating dynamic db
require_once $base_path_to_resources . 'includes/specific_db_config.php';


$postdata = json_decode(file_get_contents("php://input"), true);
checkIfNoPhpContentsReceive();
validateApiSignature($postdata['api_signature']);

//authenticate jwt token
$jwttoken = $postdata['jwt_token'];
$jwt_validate = authenticate_jwt($jwttoken);
//then workspace_id is decoded in data of jwt use from there
$userid = $jwt_validate->data->id;
$workspace_id = $jwt_validate->data->workspace_id;
$role = $jwt_validate->data->role;
$created_by = $jwt_validate->data->username;

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

   $confirmed_role_user = validatePrimaryAccess($conn, $workspace_id, $role, $userid, ['superadmin', 'admin', null]);
    if (!$confirmed_role_user){ 
            errorreturn('Access denied.');
    }else{
        $specific_db_conn = dynamicDbConnection($confirmed_role_user);
    }


    $res = $conn->prepare("SELECT count(*) as total FROM users WHERE  workspace_id = ? and status = ? and can_activate = ? ");
    $res->execute(array($workspace_id, 1, 1));
    $total_active_users = $res->fetchAll()[0]['total'];

    $res = $conn->prepare("SELECT count(*) as total FROM users WHERE workspace_id = ? and status = ? and can_activate = ?  ");
    $res->execute(array($workspace_id, 0, 1));
    $total_blocked_users = $res->fetchAll()[0]['total'];

    $res = $conn->prepare("SELECT count(*) as total FROM users WHERE  workspace_id = ? and can_activate = ? ");
    $res->execute(array($workspace_id, 0));
    $total_cannot_activated_users = $res->fetchAll()[0]['total'];

    $res = $specific_db_conn->prepare("SELECT count(*) as total FROM companies_info WHERE  workspace_id = ? and status =? ");
    $res->execute(array($workspace_id, 1));
    $total_companies = $res->fetchAll()[0]['total'];

    $res = $specific_db_conn->prepare("SELECT count(*) as total FROM  branch_info WHERE workspace_id = ? and status =? ");
    $res->execute(array($workspace_id, 1));
    $total_branches = $res->fetchAll()[0]['total'];

    successreturn(array('active_users' => $total_active_users, 'blocked_users' => $total_blocked_users, 'cannot_activate_users' => $total_cannot_activated_users, 'total_companies' => $total_companies, 'total_branches' => $total_branches));
}
