<?php

require ('vendor/autoload.php');
define("CPANEL_API_1", 1);
define("CPANEL_API_2", 2);
define("UAPI", 3);

    class P2P_class {

        private static $host     = 'https://clone.onlinetestingserver.com:2083';
        private static $user     = 'cloneonlinetesti';
        private static $password = 'X?0O{zC55NV,QDj';
        // X?0O{zC55NV,QDj
        public function __construct() {
            
            if($_POST['action'] == 'projectUnzip'){
                P2P_class::projectUnzip();
            }
            
            if($_POST['action'] == 'createDtatbace'){
                P2P_class::createDtatbace();
            }
            
            if($_POST['action'] == 'importDb'){
                P2P_class::importDb();
            }
             if($_POST['action'] == 'updateUrl'){
                P2P_class::updateUrl();
            }
            
            // if($_POST['action'] == 'add_project'){
            //     P2P_class::add_project();
            // }
        }
    
    
        public static function projectUnzip() {
            
             $project_name = $_POST['project_name'];
             $new_project_name = SELF::clean_string($_POST['new_project_name']);

             $zipPath = $project_name.".zip";
             $path = str_replace("ptp","",dirname(__DIR__));
             
             if(file_exists($path.$project_name)){
               $err = ['status' => true , 'error' => 'Project Unzip successfully.' ,'project_name' => $project_name ];
                return SELF::response_json( $err );
            }

            $zip = new ZipArchive;
            $res = $zip->open($path.$zipPath);
            if ($res === TRUE) {
                $zip->extractTo($path);
                $zip->close();
                
                if(!file_exists($path.$project_name)){
                    $err = ['status' => false , 'error' => 'Project failed to rename something went wrong.'];
                    return SELF::response_json( $err );
                }
                
                rename($path.$project_name,$path.$new_project_name);
                $project_name = $new_project_name;

                // unlink($path.$zipPath);
                
                $err = ['status' => true , 'error' => 'Project Unzip successfully.' ,'project_name' => $project_name ];
                return SELF::response_json( $err );
                
            } else {
                $err = ['status' => false , 'error' => 'Project Failed to Unzip.'];
                return SELF::response_json( $err );
            }
        }
        
        
        public static function createDtatbace() {
            $timestemp = date("yHs");
            $project_name = $_POST['project_name'];
            $dbname = substr($project_name, 0, 9).$timestemp;
            // $password = P2P_class::randomPassword(12);
            $password = '{['.$dbname.']}';
            
            
            $cpanel = new \Gufy\CpanelPhp\Cpanel([
                'host'        =>  SELF::$host,
                'username'    =>  SELF::$user,
                'auth_type'   =>  'password', // there is also an option to use "hash"
                'password'    =>  SELF::$password, // if you use hash, get the value from WHM's Remote Access Key if not use the root password here
            ]);
            
            //parameters: API Version, Action Class, Action name, cPanel account username, parameters to be passed to function
            //remember to pass the prefix
            
            $data = $cpanel->execute_action(UAPI, 'Mysql', 'create_database', 'cpanel_username', ['name'=>'cloneonlinetesti_'.$dbname]);
            
            if(!json_decode($data)->result->status){
                 $err = ['status' => false , 'error' => 'The database already exists.'];
                return SELF::response_json( $err );
            }
            
            //result should look similar to this: //{"func":"create_database","result":{"metadata":{},"data":null,"errors":null,"status":1,"messages":null},"apiversion":3,"module":"Mysql"}
            
            $usr = $cpanel->execute_action(
                UAPI, 
                'Mysql', 
                'create_user', 
                'cpanel_username', 
                [
                    'name'=>'cloneonlinetesti_'.$dbname, 
                    'password'=>$password
                ]
            );
            
             if(!json_decode($usr)->result->status){
                 $err = ['status' => false , 'error' => 'This User already exists.'];
                return SELF::response_json( $err );
            }
            
            //grant everything
            $grant = $cpanel->execute_action(
                UAPI, 
                'Mysql', 
                'set_privileges_on_database', 
                'cpanel_username', 
                [
                    'user'=>'cloneonlinetesti_'.$dbname, 
                    'database'=>'cloneonlinetesti_'.$dbname, 
                    'privileges'=>'ALL PRIVILEGES'
                ]
            );
            
                $err = ['status' => true , 'error' => 'Database created successfully', 'password' => $password ,'dbname' => 'cloneonlinetesti_'.$dbname ,'project_name' => $project_name];
                return SELF::response_json( $err );
        }
        
        
         public static function importDb() {
                
            $dbHost = 'localhost';
            $dbUname = $_POST['dbname'];
            $dbPass = $_POST['password'];
            $dbName = $_POST['dbname'];
            $prefix = $_POST['prefix'];

            $projectName = $_POST['project_name'];
            $new_project_name = $_POST['new_project_name'];

            $project_path = str_replace("ptp","",dirname(__DIR__)).$new_project_name;
            $filePath = $project_path."/".$projectName.".sql";
            
            if(!file_exists($filePath)){
                $err = ['status' => false , 'error' => 'Project database file is missing something went wrong.'];
                return SELF::response_json( $err );
            }
            try {
                
                 $db = new mysqli($dbHost, $dbUname, $dbPass, $dbName); 
        
                // Temporary variable, used to store current query
                $templine = '';
                
                // Read in entire file
                $lines = file($filePath);
                $error = '';
                
                // Loop through each line
                foreach ($lines as $line){
                    // Skip it if it's a comment
                    if(substr($line, 0, 2) == '--' || $line == ''){
                        continue;
                    }
                    
                    // Add this line to the current segment
                    $templine .= $line;
                    
                    // If it has a semicolon at the end, it's the end of the query
                    if (substr(trim($line), -1, 1) == ';'){
                        // Perform the query
                        if(!$db->query($templine)){
                            $error .= 'Error importing query '. $templine.' '.$db->error;
                        }
                        
                        // Reset temp variable to empty
                        $templine = '';
                    }
                }
                
                
                if (file_exists($project_path."/wp-config.php")) { 
                    rename($project_path."/wp-config.php",$project_path."/wp-config-old.php"); 
                    copy(getcwd()."/wp-config.php",$project_path."/wp-config.php");
                    SELF::SetUpConfigFile($project_path."/wp-config.php", $dbName, $dbUname, $dbPass, $prefix);
                }

                copy(getcwd()."/wp-config-sample.php",$project_path."/wp-config-sample.php");

                if (file_exists($project_path."/wp-content/plugins/point-to-point")) {  
                    rename($project_path."/wp-content/plugins/point-to-point",$project_path."/wp-content/plugins/point-to-point-old-".P2P_class::randomPassword(5)); 
                }
                
                if(file_exists($filePath)){
                    rename($filePath,$project_path."/".$new_project_name.".hsql"); 
                }
    
            } catch (Exception $e) {
                $err = ['status' => false , 'error' => $e->getMessage()];
                return SELF::response_json( $err );
            }
            
            // Connect & select the database
           
            
            if($error == ""){
                $err = ['status' => true , 'error' => 'Database import successfully'];
            }
            else
            {
                $err = ['status' => false , 'error' => $error];
            }
     
            return SELF::response_json( $err );
        }
        
        
        public static function updateUrl() {
                
            $servername = 'localhost';
            $username = $_POST['dbname'];
            $password = $_POST['password'];
            $dbname = $_POST['dbname'];
            $prefix = $_POST['prefix'];
            $project_name =  $_POST['project_name'];
            $old_url =  $_POST['old_url'];
            $new_url = "https://clone.onlinetestingserver.com/".$project_name;
            
            // Create connection
            $conn = mysqli_connect($servername, $username, $password, $dbname);
            // Check connection
            if (!$conn) {
               $err = ['status' => false , 'error' => "Connection failed: " . mysqli_connect_error()];
               return SELF::response_json( $err );
            }
            
            $sql_option = 'UPDATE '.$prefix.'options SET option_value = replace(option_value, "'.$old_url.'", "'.$new_url.'") WHERE option_name = "home" OR option_name = "siteurl"';
           
            $sql = 'UPDATE '.$prefix.'posts SET guid = replace(guid, "'.$old_url.'","'.$new_url.'")';
            mysqli_query($conn, $sql);
            $sql = 'UPDATE '.$prefix.'posts SET post_content = replace(post_content, "'.$old_url.'", "'.$new_url.'")';
            mysqli_query($conn, $sql);
            $sql = 'UPDATE '.$prefix.'postmeta SET meta_value = replace(meta_value,"'.$old_url.'","'.$new_url.'")';
             mysqli_query($conn, $sql);
             
            //$sql = 'UPDATE de_options SET option_value = "'.$new_url.'" WHERE option_name="home"';
            
            if (mysqli_query($conn, $sql_option)) {
              $err = ['status' => true , 'error' => "Table updated successfully" ,'new_url' => $new_url];
            } else {
              $err = ['status' => false , 'error' =>  "Error creating table: " . mysqli_error($conn)];
            }
            
            mysqli_close($conn);
            return SELF::response_json( $err );
        }
        
        // function add_project() {
            
        //         $url = "https://clone.onlinetestingserver.com/temlate_hub/wp-json/api/insert_post";
                
        //         $curl = curl_init($url);
        //         curl_setopt($curl, CURLOPT_URL, $url);
        //         curl_setopt($curl, CURLOPT_POST, true);
        //         curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
                
        //         $headers = array(
        //            "Accept: application/json",
        //            "Authorization: Bearer {token}",
        //            "Content-Type: application/json",
        //         );
        //         curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
                
        //         $data = [
        //                 "post_title"      => $_POST['post_title'],
        //                 "image"           => $_FILES['image'],
        //                 "post_categories" => $_POST['post_categories'],
        //                 "post_tags"       => $_POST['post_tags'],
        //                 "post_url"        => $_POST['post_url'],
        //                 "description"     => $_POST['description']
        //             ];
                
        //         curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($data));
                
        //         //for debug only!
        //         curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
        //         curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
                
        //         $resp = curl_exec($curl);
        //         curl_close($curl);
        //      $err = ['status' => true , 'error' => "" ];
        //       return SELF::response_json( $err );
        // }

        public static function clean_string($string) {

               $string = str_replace(' ', '-', $string); // Replaces all spaces with hyphens.
               $string = preg_replace('/[^A-Za-z0-9\-]/', '', $string); // Removes special chars.

               return preg_replace('/-+/', '-', $string); // Replaces multiple hyphens with single one.
        }

        public static function SetUpConfigFile($path,$db_name,$db_user,$db_password,$tb_prefix) {

            $file_contents = file_get_contents($path);

            $file_contents = str_replace("DB_TEM_NAME",     $db_name,     $file_contents);
            $file_contents = str_replace("DB_TEM_USER",     $db_user,     $file_contents);
            $file_contents = str_replace("DB_TEM_PASSWORD", $db_password, $file_contents);
            $file_contents = str_replace("TEM_PREFIX",      $tb_prefix,   $file_contents);
            $phptag = "<?php\n\n";
            return file_put_contents($path, $phptag.$file_contents);
        }
        
        public static function randomPassword($length = 8) {
            $alphabet = "abcdefghijklmnopqrstuwxyzABCDEFGHIJKLMNOPQRSTUWXYZ0123456789!@#$%";
            $pass = array(); //remember to declare $pass as an array
            $alphaLength = strlen($alphabet) - 1; //put the length -1 in cache
            for ($i = 0; $i < $length; $i++) {
                $n = rand(0, $alphaLength);
                $pass[] = $alphabet[$n];
            }
            return implode($pass); //turn the array into a string
        }

        public static function  response_json($request)
        {
          echo json_encode($request);
          exit();
        }
       
    }
     new P2P_class();

