<?php
defined('_WPBOOKINGPRO_EXEC') or die;
use WooBooking\CMS\Filesystem\File;
if(!class_exists("WpBookingPro_InstallController")) {
    /**
     * Class WpBookingPro_InstallController
     */
    class WpBookingPro_InstallController extends woobooking_controller_frontend
    {
        /**
         * @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.sql";
            if (file_exists(WPBOOKINGPRO_PATH_ROOT . DS . "install/$install_file")) {
                $query = File::read(WPBOOKINGPRO_PATH_ROOT . DS . "install/$install_file");
            } elseif (file_exists(WPBOOKINGPRO_PATH_ROOT . DS . "lib/vendor/netbaseteam/woobooking/src/database_sample/base_64_$install_file")) {
                $query = File::read(WPBOOKINGPRO_PATH_ROOT . DS . "lib/vendor/netbaseteam/woobooking/src/database_sample/base_64_$install_file");
                $query = base64_decode($query);
            } else {
                return json_encode($response);
            }
            $db = Factory::getDBO();
            $connection = $db->getConnection();
            if (mysqli_multi_query($connection, $query)) {
                do {
                    /* store first result set */
                    if ($result = mysqli_store_result($connection)) {
                        while ($row = mysqli_fetch_row($result)) {
                        }
                        mysqli_free_result($result);
                    }
                    /* print divider */
                    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();
            }
            $open_source = Factory::getOpenSource();
            $open_source::pluginprefix_activation();
            $response = new stdClass();
            $response->result = "success";
            return json_encode($response);
        }

        /**
         * @return false|string
         */
        public function setup_sample_database()
        {
            $response = new stdClass();
            $install_file = "example_data.sql";
            if (file_exists(WPBOOKINGPRO_PATH_ROOT . DS . "install/$install_file")) {
                $query = File::read(WPBOOKINGPRO_PATH_ROOT . DS . "install/$install_file");
            } elseif (file_exists(WPBOOKINGPRO_PATH_ROOT . DS . "lib/vendor/netbaseteam/woobooking/src/database_sample/base_64_$install_file")) {
                $query = File::read(WPBOOKINGPRO_PATH_ROOT . DS . "lib/vendor/netbaseteam/woobooking/src/database_sample/base_64_$install_file");
                $query = base64_decode($query);
            } else {
                return json_encode($response);
            }
            $db = Factory::getDBO();
            $connection = $db->getConnection();
            if (mysqli_multi_query($connection, $query)) {
                do {
                    /* store first result set */
                    if ($result = mysqli_store_result($connection)) {
                        while ($row = mysqli_fetch_row($result)) {
                        }
                        mysqli_free_result($result);
                    }
                    /* print divider */
                    if (mysqli_more_results($connection)) {
                    }
                } while (mysqli_next_result($connection));
            }
            $response->result = "success";
            return json_encode($response);
        }

        /**
         * @return false|string
         */
        public function download_current_media()
        {
            $input = Factory::getInput();
            $current_media = $input->getString('current_media', "");
            $root_media = "http://demo12.cmsmart.net/wp_salon_tf/wp-content/plugins/wpbookingpro/";
            if ($current_media != "" && !File::exists(WPBOOKINGPRO_PATH_ROOT . DS . $current_media)) {
                File::write(WPBOOKINGPRO_PATH_ROOT . DS . $current_media, file_get_contents($root_media . $current_media));
            }
            $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() . "assets/images/no-image.png"));
                        } else {
                            $query->set("$field=" . $query->quote("assets/images/no-image.png"));
                        }
                        $query->where('id=' . (int)$id);

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