<?php


namespace WpBookingPro\Utilities;

use WpBookingPro\Factory;
use WpBookingPro\Crypt\Crypt;
use WpBookingPro\Filesystem\File;
use WpBookingPro\Language\Text;
use WpBookingPro\Mvc\Model\Model;
use WpBookingProAdmin\app\helpers\AdminHelper;

/**
 * Class Utility
 * @package WpBookingPro\Utilities
 */
class Utility
{

    /**
     * @param $path
     */
    public static function getListViewFromXml($path)
    {

    }
    public static function call_ajax_by_task($task,$data=array(),$clientId=0)
    {
        $body=array(
            'action'=> "action_ajax_by_task",
            'task'=>$task,
            "submit_clientid"=>$clientId,

        );
        $body=array_merge($data,$body);

        wp_remote_post(admin_url('admin-ajax.php'), array(
            'body'  => $body
        ));
    }
    public static function printDebugBacktrace($title = 'Debug Backtrace:')
    {

        $stacks = debug_backtrace();
        ob_start();
        ?>
        <hr/>
        <h3><?php echo ($title) ?></h3>
        <table class="table table-bordered">
        <thead>
        <tr>
            <th><?php esc_attr_e('File','wpbookingpro');?></th>
            <th><?php esc_attr_e('Line','wpbookingpro');?></th>
            <th><?php esc_attr_e('Class','wpbookingpro');?></th>
            <th><?php esc_attr_e('Type','wpbookingpro');?></th>
            <th><?php esc_attr_e('Function','wpbookingpro');?></th>
            <th><?php esc_attr_e('Line content','wpbookingpro');?></th>
            <th><?php esc_attr_e('args','wpbookingpro');?></th>
        </tr>
        </thead>
        <tbody>
        <?php foreach ($stacks as $_stack) { ?>
            <?php
            $line_content="";
            $args=$_stack['args'];
            $line=$_stack['line'];
            if (!isset($_stack['file']))
                $file_path_short = '[PHP Kernel]';
            else
            {
                $file_full_path=$_stack["file"];
                $file_path_short=self::get_short_file_by_path($file_full_path);
                $line_content=File::readLine($file_full_path,$line);


            }

            if (!isset($_stack['line']))
                $_stack['line'] = '';
            ?>
            <tr>
                <td><?php echo ($file_path_short) ?></td>
                <td><?php echo ($_stack['line']) ?></td>
                <td><?php echo ($_stack['class']) ?></td>
                <td><?php echo ($_stack['type']) ?></td>
                <td><?php echo ($_stack['function']) ?></td>
                <td><?php echo  ($line_content); ?></td>
                <td><pre><?php  print_r($args,false); ?></pre></td>
            </tr>
        <?php } ?>
        </tbody>
        <?php
        $content=ob_get_clean();
        return $content;
    }

    public static function redirect($url){
        $root_url= Factory::getRootUrl();
        $html = '<html><head>';
        $html .= '<meta http-equiv="content-type" content="text/html; charset=utf-8" />';
        $html .= '<script>document.location.href=' . json_encode(str_replace("'", '&apos;',$url)) . ';</script>';
        $html .= '</head><body></body></html>';
        echo ($html);
    }

    /**
     * @param $file_path
     * @return mixed
     */
    public static function  get_path_file($file_path){
        return str_replace(WPBOOKINGPRO_PATH_ROOT,"",$file_path);
    }

    /**
     * @param $view_layout
     * @param array $items_var
     * @return string
     */
    public static function getFrontendGoToLink($view_layout, $items_var = array())
    {

        list($view, $layout) = explode(".", $view_layout);
        $http_list_var = array();
        if (is_array($items_var)) {
            foreach ($items_var as $key => $value) {
                $http_list_var[] = "$key=$value";
            }
        } else {
            $http_list_var[] = $items_var;
        }
        $http_string_var = implode("&", $http_list_var);
        $link = Factory::getRootUrl() . "/wpbookingpro/?view=$view-$layout" . ($http_string_var != "" ? "&$http_string_var" : '');
        return $link;
    }


    /**
     * @param $view_layout
     * @param array $items_var
     * @return string
     */
    public static function getBackendGoToLink($view_layout, $items_var = array())
    {
        $wordpress = Factory::getWordpress(1);
        list($view, $layout) = explode(".", $view_layout);
        $http_list_var = array();
        if (is_array($items_var)) {
            foreach ($items_var as $key => $value) {
                $http_list_var[] = "$key=$value";
            }
        } else {
            $http_list_var[] = $items_var;
        }
        $page = $wordpress->get_format_page($view);
        $http_string_var = implode("&", $http_list_var);
        $link = Factory::getRootUrlBackend() . "/admin.php?page=$page&layout=$layout" . ($http_string_var != "" ? "&$http_string_var" : '');
        return $link;
    }

    /**
     * @param $view_layout
     * @param array $items_var
     * @return string
     */
    public static function getBackendWooPanelGoToLink($view_layout, $items_var = array())
    {
        list($view, $layout) = explode(".", $view_layout);
        $http_list_var = array();
        if (is_array($items_var)) {
            foreach ($items_var as $key => $value) {
                $http_list_var[] = "$key=$value";
            }
        } else {
            $http_list_var[] = $items_var;
        }
        $page="wb_$view";
        $http_string_var = implode("&", $http_list_var);
        $link = Factory::getRootUrlBackendWooPanel() . "/$page?layout=$layout" . ($http_string_var != "" ? "&$http_string_var" : '');
        return $link;
    }

    /**
     * @param string $table
     * @return string
     */
    public static function getTableName($table = "")
    {
        if(!function_exists('wp_get_current_user')) {
            include(ABSPATH . "wp-includes/pluggable.php");
        }
        $config = Factory::getConfig();
        $environment = $config->get('environment', 'production');
        $user_id_login = isset($_SESSION['user_id'])?$_SESSION['user_id']:'';
        if(is_admin()) {
            $user = wp_get_current_user();
        } else {
            $user = get_userdata($user_id_login);
        }

        $is_exist_wp_mp_demo_sandboxes = self::checkTableExist('wp_mp_demo_sandboxes');
        $is_exist_wp_mp_demo_users = self::checkTableExist('wp_mp_demo_users');
        $db = Factory::getDBO();
        $query = $db->getQuery(true);
        $blog_id = '';
        if($is_exist_wp_mp_demo_sandboxes && $is_exist_wp_mp_demo_users) {
            $query->clear()
                ->select('wp_mp_demo_sandboxes.blog_id')
                ->from('wp_mp_demo_sandboxes AS wp_mp_demo_sandboxes')
                ->leftJoin('wp_mp_demo_users AS wp_mp_demo_users ON wp_mp_demo_users.user_id = wp_mp_demo_sandboxes.user_id')
                ->where('wp_mp_demo_users.wp_user_id='.(int)(is_admin()?$user->ID:$user_id_login))
            ;
            $blog_id = $db->setQuery($query)->loadResult();
        }

        if($environment == 'demo' && $user && trim($blog_id) != '') {
            $user_email = $user->data->user_email;
            $user_email = str_replace('.','_',$user_email);
            $user_email = strstr($user_email, '@', true);
            $underscore= '_';
            return 'wp_'.$blog_id.$underscore.$user_email.$underscore.WPBOOKINGPRO_PREFIX_TABLE.$table;
        }

        return WPBOOKINGPRO_PREFIX_TABLE . "$table";
    }

    public static function checkTableExist($table_name) {
        global $wpdb;
        $query = $wpdb->prepare( 'SHOW TABLES LIKE %s', $wpdb->esc_like( $table_name ) );

        if ( count($wpdb->get_results( $query )) ) {
            return true;
        }
        return false;
    }

    /**
     * @param $view
     * @param $task
     * @param array $items_var
     * @return string
     */
    public static function goToTaskByView($view, $task, $items_var = array())
    {
        $wordpress = Factory::getWordpress(1);
        $http_list_var = array();
        if (is_array($items_var)) {
            foreach ($items_var as $key => $value) {
                $http_list_var[] = "$key=$value";
            }
        } else {
            $http_list_var[] = $items_var;
        }
        $page = $wordpress->get_format_page($view);
        $http_string_var = implode("&", $http_list_var);
        $link = Factory::getRootUrlBackend() . "/admin.php?page=$page&task=$task" . ($http_string_var != "" ? "&$http_string_var" : '');
        return $link;
    }
    /**
     * @param $view
     * @param $task
     * @param array $items_var
     * @return string
     */
    public static function goToTaskByViewWooPanel($view, $task, $items_var = array())
    {
        $wordpress = Factory::getWordpress(2);
        $http_list_var = array();
        if (is_array($items_var)) {
            foreach ($items_var as $key => $value) {
                $http_list_var[] = "$key=$value";
            }
        } else {
            $http_list_var[] = $items_var;
        }
        $page = $wordpress->get_format_page($view);
        $http_string_var = implode("&", $http_list_var);
        $link = Factory::getRootUrlBackendWooPanel() . "/$page?task=$task" . ($http_string_var != "" ? "&$http_string_var" : '');
        return $link;
    }

    /**
     * @param int $length
     * @return string
     */
    public static function gen_random_string($length = 8)
    {
        $salt = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
        $base = strlen($salt);
        $makepass = '';

        $random = Crypt::genRandomBytes($length + 1);
        $shift = ord($random[0]);
        for ($i = 1; $i <= $length; ++$i) {
            $makepass .= $salt[($shift + ord($random[$i])) % $base];
            $shift += ord($random[$i]);
        }
        return $makepass;
    }

    /**
     * @param int $length
     * @return string
     */
    public static function gen_random_integer($length = 8)
    {
        $salt = "0123456789";
        $base = strlen($salt);
        $makepass = '';

        $random = Crypt::genRandomBytes($length + 1);
        $shift = ord($random[0]);
        for ($i = 1; $i <= $length; ++$i) {
            $makepass .= $salt[($shift + ord($random[$i])) % $base];
            $shift += ord($random[$i]);
        }
        return $makepass;
    }

    /**
     * @param $file_path
     * @return mixed
     */
    public static function get_short_file_by_path($file_path)
    {

        return str_replace(WPBOOKINGPRO_PATH_ROOT . '/', '', $file_path);
    }

    /**
     * @param $str
     * @return mixed
     */
    public static function remove_string_javascript($str)
    {
        preg_match_all('/<script type=\"text\/javascript">(.*?)<\/script>/s', $str, $estimates);
        return $estimates[1][0];
    }

    /**
     * @param $string
     * @return string|string[]|null
     */
    public static function clean($string)
    {
        return preg_replace('/[^a-zA-Z0-9_ -]/s', '', $string);
    }

    /**
     * @param $string
     * @return string|string[]|null
     */
    public static function clean_all_space_to_single_space($string)
    {
        return preg_replace('/\s+/', ' ', $string);
    }

    /**
     *
     */
    public static function render_message()
    {
        $client = is_admin() ? 1 : 0;
        $app = Factory::getApplication($client);
        $message = $app->getEnqueueMessage();
        echo "<pre>";
        print_r($message, false);
        echo "</pre>";
    }

    /**
     * @return false|string
     */
    public static function random_string_by_time(){
        //Generate a timestamp using mt_rand.
        $timestamp = mt_rand(1, time());

        //Format that timestamp into a readable date string.
        $randomDate = date("d M Y", $timestamp);

        //Print it out.
        return $randomDate;
    }

    /**
     * @param $fist_name
     * @param $last_name
     * @return string
     */
    public static function get_full_name($fist_name, $last_name)
    {
        return "$fist_name $last_name";
    }

}