<?php
namespace WpBookingProAdmin\app\controllers;
defined('_WPBOOKINGPRO_EXEC') or die;


use WpBookingPro\Factory;
use WpBookingPro\Filesystem\File;
use WpBookingPro\Mvc\Controller\ControllerFrontend;
use WpBookingPro\Utilities\Utility;

class InstallController extends ControllerFrontend
{
    /**
     * @return mixed
     * @throws Exception
     */
    public function next()
    {
        $input = Factory::getInput();
        $tool = $input->get('tool', array(), 'array');
        return $this->view("install.form");
    }

    /**
     * @return false|string
     */
    public function check_required()
    {
        $response = new \stdClass();
        $check_ok = true;
        $response->result = "success";

        if ($check_ok == false) {
            return json_encode($response);
        }
        return json_encode($response);
    }

    /**
     * @return false|string
     */
    public function install_construct()
    {
        $response = new \stdClass();
        $response->result = "success";
        $db = Factory::getDBO();
        $query = $db->getQuery(true);
        $list_table_in_database = $db->setQuery("SHOW TABLES LIKE " . $db->quote("woobooking\\_%"))->loadColumn();
        $json_table_need_install = File::read(WPBOOKINGPRO_PATH_ROOT . "/install/tables.json");
        $json_table_need_install = json_decode($json_table_need_install);
        $db->setQuery("SET FOREIGN_KEY_CHECKS=0")->execute();
        foreach ($json_table_need_install as $table) {
            $db->setQuery("CREATE TABLE IF NOT EXISTS `$table` ( `id` int(11) NOT NULL ) ")->execute();
            $db->setQuery("TRUNCATE TABLE `$table`")->execute();
        }
        foreach ($json_table_need_install as $table) {
            $db->setQuery('DROP TABLE IF EXISTS ' . $table)->execute();
        }
        $install_file = "create_table.txt";
        if (file_exists(WPBOOKINGPRO_PATH_ROOT . DS . "install/$install_file")) {
            $query = File::read(WPBOOKINGPRO_PATH_ROOT . DS . "install/$install_file");
        }else {
            return json_encode($response);
        }
        $connection = $db->getConnection();
        set_time_limit(300);
        if (mysqli_multi_query($connection, $query)) {
            do {
                if ($result = mysqli_store_result($connection)) {
                    while ($row = mysqli_fetch_row($result)) {
                    }
                    mysqli_free_result($result);
                }
                if (mysqli_more_results($connection)) {
                }
            } while (mysqli_next_result($connection));
        }

        return json_encode($response);
    }

    /**
     * @return false|string
     */
    public function finish_install()
    {
        $input = Factory::getInput();
        $data = $input->getData();
        $all_tool_check = $data['all_tool_check'];
        // if (!in_array("import_media_sample", $all_tool_check)) {
        //     self::change_media_table_path();
        // }
        $wordpress = Factory::getWordpress(1);
        $wordpress::pluginprefix_activation();
        $response = new \stdClass();
        $response->result = "success";
        $user = isset($data['user'])?$data['user']:array();
        $user_email = $user['data']['user_email'];
        $user_id = $user['ID'];

        $db= Factory::getDBO();
        $query = $db->getQuery(true);
        $list_key_value=array(
            "group_user_id"=>3,
            "email"=>$user_email,
            "first_name"=>"admin",
            "last_name"=>" ",
            "gender"=>"male",
            "phonecode"=>"+84",
            "countrycode"=>"VN",
            "mobile"=>"0912123123",
            "image"=> WPBOOKINGPRO_PLUGIN_DIR_URL ."/admin/app/assets/images/no-image.jpg",
            "description"=>" ",
            "address"=>" ",
            "state"=>" ",
            "country"=>"vietnam",
            "city"=>"hanoi",
            "postcode"=>"100000",
            "address_bill"=>" ",
            "open_source_user_id"=>$user_id,
            "created"=>date('Y-m-d H:i:s'),
            "published"=>1,
            "ordering"=>"1",
            "params"=>"",
        );
        $sql='INSERT INTO `woobooking_user` SET ';
        $list_insert=[];
        foreach ($list_key_value as $key=>$value){
            $list_insert[]="`$key`=\"$value\"";
        }
        $sql.=implode(',',$list_insert);
        $db->setQuery($sql)->execute();
        return json_encode($response);
    }

    /**
     * @return false|string
     */
    public function setup_sample_database()
    {
        $response = new \stdClass();
        $response->result = "success";
        $install_file = "example_data.txt";
        if (file_exists(WPBOOKINGPRO_PATH_ROOT . DS . "install/$install_file")) {
            $query = File::read(WPBOOKINGPRO_PATH_ROOT . DS . "install/$install_file");
        } else {
            return json_encode($response);
        }
        $db = Factory::getDBO();
        $connection = $db->getConnection();
        if (mysqli_multi_query($connection, $query)) {
            do {
                if ($result = mysqli_store_result($connection)) {
                    while ($row = mysqli_fetch_row($result)) {
                    }
                    mysqli_free_result($result);
                }
                if (mysqli_more_results($connection)) {
                }
            } while (mysqli_next_result($connection));
        }

        return json_encode($response);
    }

    /**
     * @return false|string
     */
    public function download_current_media()
    {
        global $wp_filesystem;
        $input = Factory::getInput();
        $current_media = $input->getString('current_media', "");
        $root_media = "https://demo.retreat.club/wp-content/plugins/wpbookingpro/";
        if ($current_media != "" && !File::exists(WPBOOKINGPRO_PATH_ROOT . DS . $current_media)) {


            if (empty($wp_filesystem)) {
                require_once (ABSPATH . '/wp-admin/includes/file.php');
                WP_Filesystem();
            }
            $data=  $wp_filesystem->get_contents($root_media . $current_media);

            File::write(WPBOOKINGPRO_PATH_ROOT . DS . $current_media, $data);
        }
        $response = new \stdClass();
        $response->result = "success";
        return json_encode($response);
    }

    /**
     * @return false|string
     */
    public function get_total_media_download()
    {
        $json_table_need_download_media = File::read(WPBOOKINGPRO_PATH_ROOT . "/install/tables_media.json");
        $json_table_need_download_media = json_decode($json_table_need_download_media);

        $db = Factory::getDBO();
        $res_list_media = array();
        $query = $db->getQuery(true);
        foreach ($json_table_need_download_media as $item_table) {

            $query->clear();
            $query->select("*")
                ->from($item_table->table);
            $list_media = $db->setQuery($query)->loadObjectList();

            $fields = $item_table->fields;
            foreach ($list_media as $row) {
                foreach ($fields as $field) {
                    $media_path = $row->$field;
                    if ($media_path != "" && !File::exists(WPBOOKINGPRO_PATH_ROOT . DS . $media_path)) {
                        $res_list_media[] = $media_path;
                    }
                }
            }
        }

        $response = new \stdClass();
        $response->result = "success";
        $response->list_media = $res_list_media;
        return json_encode($response);
    }

    /**
     *
     */
    public function change_media_table_path()
    {
        $json_table_need_download_media = File::read(WPBOOKINGPRO_PATH_ROOT . "/install/tables_media.json");
        $json_table_need_download_media = json_decode($json_table_need_download_media);
        $db = Factory::getDBO();
        $query = $db->getQuery(true);
        foreach ($json_table_need_download_media as $item_table) {
            $query->clear();
            $query->select("*")
                ->from($item_table->table);
            $list_media = $db->setQuery($query)->loadObjectList();

            $fields = $item_table->fields;
            foreach ($list_media as $row) {
                foreach ($fields as $field) {
                    $media_path = $row->$field;
                    $id = $row->id;
                    $query->clear();
                    $query->update($item_table->table);
                    if (strpos($media_path, 'http') !== false) {
                        $query->set("$field=" . $query->quote(Factory::getRootUrlPlugin() . "frontend/app/assets/images/no-image.jpg"));
                    } else {
                        $query->set("$field=" . $query->quote("frontend/app/assets/images/no-image.jpg"));
                    }
                    $query->where('id=' . (int)$id);

                    $db->setQuery($query)->execute();
                }
            }
        }
    }
}
