<?php
namespace TourOperatorProAdmin\app\controllers;
defined('_TOUROPERATOR_EXEC') or die;


use TourOperatorPro\Factory;
use TourOperatorPro\Filesystem\File;
use TourOperatorPro\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("tbpro\\_%"))->loadColumn();
        $json_table_need_install = File::read(TOUROPERATORPRO_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(TOUROPERATORPRO_PATH_ROOT . DS . "install/$install_file")) {
            $query = File::read(TOUROPERATORPRO_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 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.txt";
        if (file_exists(TOUROPERATORPRO_PATH_ROOT . DS . "install/$install_file")) {
            $query = File::read(TOUROPERATORPRO_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 = "http://demo12.cmsmart.net/torhub_tf/wp-content/plugins/touroperatorpro/";
        if ($current_media != "" && !File::exists(TOUROPERATORPRO_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(TOUROPERATORPRO_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(TOUROPERATORPRO_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(TOUROPERATORPRO_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(TOUROPERATORPRO_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();
                }
            }
        }
    }
}
