<?php

include_once "settings/form-settings.php";
include_once "settings/admin-form.php";

class Rad_Admin_Dashboard
{
    public function __construct()
    {

        $this->rad_activation();

        add_action("admin_menu", array(&$this, "rad_setup_menus"), 5, 0);
        add_action("admin_menu", array(&$this, "rad_setup_submenus"), 15, 0);
        add_action("admin_enqueue_scripts", array(&$this, "rad_admin_scripts"));
        add_action("admin_init", array(&$this, "rad_admin_init"));
        add_action("after_setup_theme", array(&$this, "rad_after_setup"));
        add_action("switch_theme", array(&$this, "rad_after_deactivate"));
        add_action("wp_ajax_theme_save_options", array(&$this, "rad_save_options"));
        add_filter("wp_generate_attachment_metadata", array(&$this, "rad_retina_upload_filter"));
        add_filter("mce_buttons_2", array(&$this, "rad_mce_buttons"));
        add_filter("tiny_mce_before_init", array(&$this, "rad_mce_text_sizes"));

        add_action("enqueue_block_editor_assets", array(&$this, "prefix_block_styles"));

        //Add new buttons to tinyMCE editor
        add_filter("mce_external_plugins", array(&$this, "tiny_mce_add_buttons"));
        add_filter("mce_buttons", array(&$this, "tiny_mce_register_buttons"));
    }

    public function rad_save_options()
    {
        $options = get_option(RAD_OPTIONS_KEY);

        foreach ($options as $key => $value) {
            $newVal        = isset($_POST[$key]) ? $_POST[$key] : "";
            $options[$key] = $newVal;
        }

        update_option(RAD_OPTIONS_KEY, $options);

        echo "OK";

        die(); // this is required to return a proper result
    }

    public function rad_after_deactivate()
    {
        update_option("theme_initialised", false);

    }

    public function rad_after_setup()
    {
        // we can not use directly after_switch_theme hook because we need activated plguins before that
        if (!is_admin()) {
            return;
        }

        $theme_initialised = get_option("theme_initialised");

        if ($theme_initialised != true) {
            if (class_exists("WPBakeryVisualComposerAbstract") || class_exists("YITH_WCWL")) {
                update_option("theme_initialised", true);
            }

            if (class_exists("WPBakeryVisualComposerAbstract")) {

                //Enable Visual composer in page,post and product
                $pt_array = vc_editor_post_types();

                if (is_array($pt_array)) {

                    if (!in_array("post", $pt_array)) {
                        $pt_array[] = "post";
                    }

                    if (!in_array("page", $pt_array)) {
                        $pt_array[] = "page";
                    }

                    if (!in_array("product", $pt_array)) {
                        $pt_array[] = "product";
                    }

                    vc_editor_set_post_types($pt_array);
                }
            }

            //Set wishlist position after add to cart button
            if (class_exists("YITH_WCWL")) {

                $wishlist_position = get_option("yith_wcwl_button_position");

                if ($wishlist_position != "add-to-cart") {
                    update_option("yith_wcwl_button_position", "add-to-cart");
                }
            }
        }

        //Initialize default options
        $options  = get_option(RAD_OPTIONS_KEY);
        $defaults = rad_admin_get_defaults();

        // Are our options saved in the DB?
        if (false !== $options) {
            $changed = false;
            //Add new keys if any
            foreach ($defaults as $key => $value) {
                if (!array_key_exists($key, $options)) {
                    //Add default value
                    $options[$key] = $value;
                    $changed       = true;
                }
            }

            //Check if any key removed from defaults
            foreach ($options as $key => $value) {
                if (!array_key_exists($key, $defaults)) {
                    //Remove the option
                    unset($options[$key]);
                    $changed = true;
                }
            }

            if ($changed) {
                update_option(RAD_OPTIONS_KEY, $options);
            }

            return;
        }

        // If not, we'll save our default options
        add_option(RAD_OPTIONS_KEY, $defaults);
    }

    public function rad_activation()
    {
        // Redirect To Theme Options Page on Activation
        if (isset($_GET["activated"])) {
            wp_redirect(admin_url("admin.php?page=aventa_theme_settings"));
        }
    }

    public function rad_setup_menus()
    {

        add_menu_page(esc_html__("Aventa Settings", "aventa"), esc_html__("Aventa Settings", "aventa"), "manage_options", "aventa_theme_settings", array(&$this, "theme_settings"), RAD_THEME_INC_URI . "/admin/assets/img/logo.png", 60);
    }

    public function rad_setup_submenus()
    {

        add_submenu_page("aventa_theme_settings", esc_html__("Demo Importer", "aventa"), esc_html__("Demo Importer", "aventa"), "manage_options", "aventa_demo_importer", array($GLOBALS["rad_Importer"], "dispatch"), 20);
    }

    public function rad_admin_init()
    {
        if (in_array($GLOBALS["pagenow"], array("media-upload.php", "async-upload.php"))) {
            // Now we'll replace the 'Insert into Post Button' inside Thickbox
            add_filter("gettext", array(&$this, "rad_replace_thickbox_text"), 1, 3);
        }

        //Custom stylesheet file to the TinyMCE visual editor{
        add_editor_style("inc/admin/assets/css/editor-style.css");

    }

    public function prefix_block_styles()
    {

        /*************************************************************/
        /*  Fonts
        /*************************************************************/
        $body_font_spec     = rad_get_option("font-body");
        $body_font_variants = "";
        if ($body_font_spec == "theme_default") {
            $body_font = "theme_default";
        } elseif ($body_font_spec != "") {
            $body_font_spec = explode(":", $body_font_spec);
            if (isset($body_font_spec[1]) && isset($body_font_spec[2])) {
                $body_font          = trim($body_font_spec[1]);
                $body_font_variants = trim($body_font_spec[2]);
            } else {
                $body_font          = "theme_default";
                $body_font_variants = "";
            }
        }

        $heading_font_spec     = rad_get_option("font-headings");
        $heading_font_variants = "";
        if ($heading_font_spec == "theme_default") {
            $heading_font = "theme_default";
        } elseif ($body_font_spec != "") {
            $heading_font_spec = explode(":", $heading_font_spec);
            if (isset($heading_font_spec[1]) && isset($heading_font_spec[2])) {
                $heading_font          = trim($heading_font_spec[1]);
                $heading_font_variants = trim($heading_font_spec[2]);
            } else {
                $heading_font          = "theme_default";
                $heading_font_variants = "";
            }

        }

        wp_enqueue_style("rad-inline-editor-styles", RAD_THEME_INC_URI . "assets/css/inline-editor-styles.css");

        rad_theme_fonts();

        $prefix_custom_css = "
        .edit-post-visual-editor.editor-styles-wrapper { font-family:" . esc_html($body_font) . ";" .
        rad_get_font_variant_attribute($body_font_variants) . " }

        .editor-post-title__block .editor-post-title__input,
        .editor-styles-wrapper h1,
        .editor-styles-wrapper h2,
        .editor-styles-wrapper h3,
        .editor-styles-wrapper h4,
        .editor-styles-wrapper h5,
        .editor-styles-wrapper h6 { font-family:" . esc_html($heading_font) . ";" .
        rad_get_font_variant_attribute($heading_font_variants) . " } ";

        wp_add_inline_style("rad-inline-editor-styles", $prefix_custom_css);
    }

    public function rad_replace_thickbox_text($translated_text, $text, $domain)
    {
        if ("Insert into Post" == $text) {

            $texts = $this->rad_get_mediabox_strings();

            foreach ($texts as $key => $value) {
                $referer = strpos(wp_get_referer(), $key);

                if ($referer !== false) {
                    return $value;
                }

            }

        }

        return $translated_text;
    }

    public function rad_get_mediabox_strings()
    {
        return array(
            "rad-insert-image"         => esc_html__("Insert Image", "aventa"),
            "rad-slide-image"          => esc_html__("Insert slide image", "aventa"),
            "rad-video-cover-image"    => esc_html__("Insert video cover image", "aventa"),
            "rad-settings-preloader"   => esc_html__("Insert preloader image", "aventa"),
            "rad-settings-logo"        => esc_html__("Insert Logo", "aventa"),
            "rad-hamburger-menu-image" => esc_html__("Insert image of hamburger menu", "aventa"),
            "rad-settings-favicon"     => esc_html__("Insert Favicon", "aventa"),
            "rad-attr-image"           => esc_html__("Insert image for attributes", "aventa"),
        );
    }

    public function theme_settings()
    {
        $form = new rad_AdminForm();
        $form->displayForm();
    }

    public function rad_admin_scripts()
    {
        if (!isset($_GET["page"]) || $_GET["page"] != "aventa_theme_settings") {
            return;
        }

        $this->rad_Register_Scripts();
        $this->rad_Enqueue_Scripts();
    }

    public function rad_Register_Scripts()
    {

        wp_register_script("rad-jquery-easing", RAD_THEME_INC_URI . "/admin/assets/js/jquery.easing.1.3.js", array("jquery"), "1.3.0");

        wp_register_style("rad-nouislider-style", RAD_THEME_INC_URI . "/admin/assets/css/jquery.nouislider.min.css", false, "7.0.10", "screen");
        wp_register_script("rad-nouislider-script", RAD_THEME_INC_URI . "/admin/assets/js/jquery.nouislider.min.js", array("jquery"), "7.0.10");

        //Include wpcolorpicker + its patch to support alpha chanel
        wp_register_script("rad-colorpicker-alpha", RAD_THEME_INC_URI . "/admin/assets/js/wp-color-picker-alpha.js", array("wp-color-picker"), "1.2.2");
        $color_picker_strings = array(
            "clear"            => esc_html__("Clear", "aventa"),
            "clearAriaLabel"   => esc_html__("Clear color", "aventa"),
            "defaultString"    => esc_html__("Default", "aventa"),
            "defaultAriaLabel" => esc_html__("Select default color", "aventa"),
            "pick"             => esc_html__("Select Color", "aventa"),
            "defaultLabel"     => esc_html__("Color value", "aventa"),
        );
        wp_localize_script("rad-colorpicker-alpha", "wpColorPickerL10n", $color_picker_strings);

        wp_register_style("rad-admin-style", RAD_THEME_INC_URI . "/admin/assets/css/style.css", false, "1.0.0", "screen");
        wp_register_script("rad-admin-script", RAD_THEME_INC_URI . "/admin/assets/js/admin.js", array("jquery"), "1.0.0");
        wp_register_script("rad-admin-options", RAD_THEME_INC_URI . "/admin/assets/js/options-panel.js", array("jquery"), "1.0.0");
    }

    public function rad_Enqueue_Scripts()
    {
        wp_enqueue_media();
        wp_enqueue_script("jquery");
        wp_enqueue_script("thickbox");
        wp_enqueue_style("thickbox");
        wp_enqueue_script("media-upload");
        wp_enqueue_script("hoverIntent");
        wp_enqueue_script("rad-jquery-easing");
        wp_enqueue_style("rad-nouislider-style");
        wp_enqueue_script("rad-nouislider-script");
        wp_enqueue_style("wp-color-picker");
        wp_enqueue_script("wp-color-picker");
        wp_enqueue_script("rad-colorpicker-alpha");
        wp_enqueue_style("rad-admin-style");
        wp_enqueue_script("rad-admin-script");
        wp_enqueue_script("rad-admin-options");
    }

    public function rad_retina_upload_filter($metadata)
    {

        //Check for errors
        if (!count($metadata) ||
            !array_key_exists("file", $metadata) ||
            !array_key_exists("sizes", $metadata)) {
            return $metadata;
        }

        $upload  = wp_upload_dir();
        $relPath = dirname($metadata["file"]);
        $path    = rad_path_combine($upload["basedir"], $relPath);
        $sizes   = $metadata["sizes"];

        // remove duplicate values from a $sizes array ( cause Error when Upload Images )
        $sizes = array_map("unserialize", array_unique(array_map("serialize", $sizes)));

        //Check for @2x extension
        foreach ($sizes as $key => $size) {
            if (!rad_ends_with($key, "@2x")) {
                continue;
            }

            //key without @2x
            $id = substr($key, 0, strlen($key) - 3);

            //Check for normal resolution key
            if (!array_key_exists($id, $sizes)) {
                continue;
            }

            //Change the file name to match the LoDPI one
            //Except we add @2x to the filename
            $file     = $sizes[$id]["file"];
            $ext      = pathinfo($file, PATHINFO_EXTENSION);
            $fileName = basename($file, ".$ext");
            $newName  = "$fileName@2x.$ext";
            //Rename the file
            rename(rad_path_combine($path, $sizes[$key]["file"]), rad_path_combine($path, $newName));

            //Save the new name
            $metadata["sizes"][$key]["file"] = $newName;
        }

        return $metadata;
    }

    public function rad_mce_buttons($buttons)
    {
        array_unshift($buttons, "fontsizeselect"); // Add Font Size Select

        return $buttons;
    }

    // Customize mce editor font sizes
    public function rad_mce_text_sizes($initArray)
    {
        $initArray["fontsize_formats"] = "12px 13px 14px 15px 16px 17px 18px 19px 20px 21px 22px 24px 26px 28px 36px 40px 48px 60px 72px 80px";
        return $initArray;
    }

    public function tiny_mce_add_buttons($plugins)
    {
        $plugins["RadoTypographExtenssion"] = RAD_THEME_INC_URI . "/admin/assets/js/not_existed_js.js";

        return $plugins;
    }

    public function tiny_mce_register_buttons($buttons)
    {
        $newBtns = array(
            "rad_font",
            "rad_lineheight",
            "rad_letterspacing",
            "rad_background",
            "rad_underline1",
            "rad_underline2",
            "rad_underline3",
            "rad_interactive_underline",
        );

        $buttons = array_merge($buttons, $newBtns);
        return $buttons;
    }

}

new Rad_Admin_Dashboard();
