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

use BenMajor\ExchangeRatesAPI\ExchangeRatesAPI;
use WpBookingPro\Factory;
use WpBookingPro\Filesystem\File as FileAlias;
use WpBookingPro\Language\Text;
use WpBookingPro\Mvc\Model\ModelForm;
use WpBookingPro\Form\Form;
use WpBookingPro\Registry\Registry;
use WpBookingPro\Utilities\Utility;

class ConfigModel extends ModelForm
{
    /**
     * @var string
     */
    public $context = "config";
    /**
     * @var string
     */
    public $table_name = "config";
    /**
     * @var array
     */
    public static $list_menu_by_xml = array();

    /**
     * @param array $data
     * @return array|bool|object|void
     * @throws Exception
     */
    public function save($data = array())
    {
        $appConfig = Factory::getAppConfig();
        $file_client_secret_exist = $appConfig->get('client_secret_file','');
        $table = $this->getTable('config');
        $table->load(1);
        global $wp_filesystem;
        if (empty($wp_filesystem)) {
            require_once (ABSPATH . '/wp-admin/includes/file.php');
            WP_Filesystem();
        }

        $file_client_secret=$data['params']['client_secret_file'];
        if(file_exists(WPBOOKINGPRO_PATH_ROOT.DS.$file_client_secret_exist) && $file_client_secret!==$file_client_secret_exist) {
            FileAlias::delete(WPBOOKINGPRO_PATH_ROOT.DS.$file_client_secret_exist);
        }
        if(isset($file_client_secret) && trim($file_client_secret) !== '' && $file_client_secret_exist !== $file_client_secret) {
            $name = str_replace(' ', '_','file_system_wpbooking_') . $file_client_secret;
            $short_path_file_client_secret = "upload_system/client_secret/$name";
            $new_file_client_secret_path = WPBOOKINGPRO_PATH_ROOT . DS . $short_path_file_client_secret;
            if (!FileAlias::write($new_file_client_secret_path, FileAlias::read($file_client_secret))) {
                throw new \Exception(Text::_("can not upload file"));
            }
            $old_file=  $wp_filesystem->get_contents($_FILES['file_upload']['tmp_name']);

            FileAlias::write($new_file_client_secret_path,$old_file);
            $data['params']['client_secret_file']=$short_path_file_client_secret;
        }
        $param = $data['params'];
        $reg = new Registry();
        $reg->loadArray($param);
        $table->params = $reg->toString();
        $table->store();
    }

    /**
     * @param int $id
     * @return mixed
     */
    public function getItem($id = 0)
    {
        $item = parent::getItem(1); // TODO: Change the autogenerated stub
        $param = $item->params;
        $reg = new Registry();
        $reg->loadString($param);
        $item->params = $reg;
        return $item;
    }

    /**
     * @return array|mixed
     */
    public function get_list_view_publish()
    {
        $db = Factory::getDBO();
        $query_check_table = $db->getQuery(true);
        $query_check_table->setQuery("SHOW TABLES LIKE '" . $this->getTableName('view') . "'");
        $tables = $db->setQuery($query_check_table)->loadColumn();
        if (count($tables)) {
            $query = $db->getQuery(true);
            $query->select('view.name')
                ->from($this->getTableName('view') . ' AS view')
                ->where('view.published=1');
            $listview = $db->setQuery($query)->loadColumn();
        } else {
            $listview = self::get_list_view_xml();
        }
        return $listview;
    }

    /**
     * @return array
     */
    public static function get_list_view_xml()
    {
        if (empty(self::$list_menu_by_xml)) {
            $file_xml_path_app = WPBOOKINGPRO_APP_BACKEND_PATH . "/views.xml";
            $xml = simplexml_load_file($file_xml_path_app);
            $list_menu_by_xml = [];
            foreach ($xml->view as $view) {
                $is_system = (string)$view->attributes()['is_system'];
                if ($is_system == 1) {
                    $list_menu_by_xml[] = (object)[
                        'id' => (string)$view->attributes()['id'],
                        'menu_slug' => (string)$view->attributes()['menu_slug'],
                        'label' => (string)$view->attributes()['label'],
                        'page_title' => (string)$view->attributes()['page_title'],
                        'capability' => (string)$view->attributes()['capability'],
                        'icon' => (string)$view->attributes()['icon'],
                        'is_system' => (string)$view->attributes()['is_system'],
                    ];
                }
            }
            self::$list_menu_by_xml = $list_menu_by_xml;
        }
        return self::$list_menu_by_xml;
    }

    /**
     * @return bool|Form
     */
    public function getFormCreateView()
    {
        Form::addFieldPath(WPBOOKINGPRO_PLUGIN_DIR_URL . '/lib/Form/Field');
        Form::addFieldPath(WPBOOKINGPRO_PLUGIN_DIR_URL . '/lib/fieldss');
        Form::addFormPath(WPBOOKINGPRO_APP_PATH . '/models/forms');
        try {
            $data = [
                "views" => $this->get_list_view_publish()
            ];
            $form = Form::getInstance("create_view");
            $form->bind($data);
        } catch (\Exception $e) {
            $this->setError($e->getMessage());
            return false;
        }
        return $form;
    }
}
