<?php
namespace WpBookingHotelAdminWooPanel\app\controllers;
defined('_WPBOOKINGHOTEL_EXEC') or die;


use WpBookingHotel\Factory;
use WpBookingHotel\Filesystem\File;
use WpBookingHotel\Mvc\Controller\ControllerFrontend;

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(WPBOOKINGHOTEL_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(WPBOOKINGHOTEL_PATH_ROOT . DS . "install/$install_file")) {
            $query = File::read(WPBOOKINGHOTEL_PATH_ROOT . DS . "install/$install_file");
        } elseif (file_exists(WPBOOKINGHOTEL_PATH_ROOT . DS . "lib/vendor/netbaseteam/woobooking/src/database_sample/base_64_$install_file")) {
            $query = File::read(WPBOOKINGHOTEL_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();
        }
        $wordpress = Factory::getWordpress(1);
        $wordpress::pluginprefix_activation();
        $response = new \stdClass();
        $response->result = "success";
        return json_encode($response);
    }

    /**
     * @return false|string
     */
    public function setup_sample_database()
    {
        $response = new \stdClass();
        $response->result = "success";
        $install_file = "example_data.sql";
        if (file_exists(WPBOOKINGHOTEL_PATH_ROOT . DS . "install/$install_file")) {
            $query = File::read(WPBOOKINGHOTEL_PATH_ROOT . DS . "install/$install_file");
        } 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 download_current_media()
    {
        $input = Factory::getInput();
        $current_media = $input->getString('current_media', "");
        $root_media = "http://demo12.cmsmart.net/booking_hotel/wp-content/plugins/wpbookinghotel/";
        if ($current_media != "" && !File::exists(WPBOOKINGHOTEL_PATH_ROOT . DS . $current_media)) {
            File::write(WPBOOKINGHOTEL_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(WPBOOKINGHOTEL_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(WPBOOKINGHOTEL_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(WPBOOKINGHOTEL_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() . "admin/app/assets/images/no-image.jpg"));
                    } else {
                        $query->set("$field=" . $query->quote("admin/app/assets/images/no-image.jpg"));
                    }
                    $query->where('id=' . (int)$id);

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