<?php
function createDatabaseAndSetPrivileges($cpanelUsername, $generatedToken, $workspace_id,$database_user,$database_password) {
       
        $prefix = $GLOBALS['db_prefix'];
        // Construct the string
        $database_name =  $prefix .'education_specific_' . $workspace_id;
        // echo $database_name;
       
        //$query = "https://hostname.example.com:2083/cpsess##########/execute/Mysql/get_server_information";
        $query = "https://rejoicebilldesk.in:2083/execute/Mysql/create_database?name=".$database_name;
        
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST,0);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER,0);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER,1);
        
        $header[0] = "Authorization: cpanel $cpanelUsername:" . preg_replace("'(\r|\n)'","",$generatedToken);
        curl_setopt($curl,CURLOPT_HTTPHEADER,$header);
        curl_setopt($curl, CURLOPT_URL, $query);
         
        $result = curl_exec($curl);
        
        $result = json_decode($result);
        
        
      
        if(intval($result->status) == 1)
        {

            curl_close($curl);
            $privilege_database_access = "ALL%20PRIVILEGES";
            
            //proceed to setting user privilege to database
            $query = "https://rejoicebilldesk.in:2083/execute/Mysql/set_privileges_on_database?user=".$database_user."&database=".$database_name."&privileges=".$privilege_database_access;
            $curl = curl_init();
            curl_setopt($curl, CURLOPT_SSL_VERIFYHOST,0);
            curl_setopt($curl, CURLOPT_SSL_VERIFYPEER,0);
            curl_setopt($curl, CURLOPT_RETURNTRANSFER,1);
            $header[0] = "Authorization: cpanel $cpanelUsername:" . preg_replace("'(\r|\n)'","",$generatedToken);
            curl_setopt($curl,CURLOPT_HTTPHEADER,$header);
            curl_setopt($curl, CURLOPT_URL, $query);
            $result = curl_exec($curl);

            
            //return $database_name;
            try {
             $conn_rjllearning_specific = dynamicDbConnection($database_name);
             $sql = "ALTER DATABASE $database_name CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci";
             $alter = $conn_rjllearning_specific->prepare($sql);
             $alter->execute();
            } catch(Exception $e) {
                errorreturn($e->getMessage());
            }

            createTableStructure($conn_rjllearning_specific);

            return $database_name;
            
        } else
        {
            //unable to create database
            return $result;
        }
}

