<?php

require_once RAD_THEME_ADMIN . "/settings/fieldtemplate.php";
require_once RAD_THEME_ADMIN . "/settings/post-options-provider.php";
require_once RAD_THEME_INC . "/admin/menu/nav-menu-walker.php";

class Rad_Menu
{
    private $postType;

    public function __construct()
    {

        $this->postType = "nav_menu_item";

        add_filter("nav_menu_item_additional_fields", array(&$this, "rad_ShowMetaBox"), 10, 5);

        add_filter("wp_edit_nav_menu_walker", array(&$this, "rad_NavMenuHanler"));

        /* Save post meta on the "save_post" hook. */
        add_action("save_post", array(&$this, "rad_SaveData"), 10, 2);

        add_action("admin_enqueue_scripts", array(&$this, "rad_InitScripts"));

    }

    public function rad_SaveData($post_id = false, $post = false)
    {

        /* Verify the nonce before proceeding. */
        $nonce = "aventa_post_nonce";

        if (!isset($_POST[$nonce]) || !wp_verify_nonce($_POST[$nonce], "theme-post-meta-form")) {
            return $post_id;
        }

        // check auto-save
        if (defined("DOING_AUTOSAVE") && DOING_AUTOSAVE) {
            return $post_id;
        }

        if ($post->post_type != $this->postType || !current_user_can("edit_post", $post_id)) {
            return $post_id;
        }

        //CRUD Operation
        foreach ($this->rad_GetOptionsForStore() as $key => $settings) {
            $uniqueKey = $key . "-" . $post_id; //Unique key used for access fields of each menu item
            $postedVal = isset($_POST[$uniqueKey]) ? $_POST[$uniqueKey] : "";
            $val       = get_post_meta($post_id, $key, false);

            if (is_array($postedVal)) {
                //Insert
                if (!empty($postedVal) && empty($val)) {
                    add_post_meta($post_id, $key, $postedVal);

                }
                //Delete
                elseif (!empty($val) && empty($postedVal)) {
                    delete_post_meta($post_id, $key);

                    //Delete the attachment as well
                    if ($settings["type"] == "upload") {
                        rad_delete_attachment($val);
                    }
                }
                //Update
                elseif (!empty($val) && !empty($postedVal) && $postedVal != $val) {
                    update_post_meta($post_id, $key, $postedVal);
                }

            } else {
                //Insert
                if ($postedVal != "" && empty($val)) {
                    add_post_meta($post_id, $key, $postedVal);

                }
                //Delete
                elseif (!empty($val) && $postedVal == "") {
                    delete_post_meta($post_id, $key);

                    //Delete the attachment as well
                    if ($settings["type"] == "upload") {
                        rad_delete_attachment($val);
                    }
                }
                //Update
                elseif ($postedVal != "" && !empty($val) && $postedVal != $val) {
                    update_post_meta($post_id, $key, $postedVal);
                }

            }
        }

        return $post_id;
    }

    private function rad_GetOptionsForStore()
    {
        $options = $this->rad_GetOptions();
        $values  = array();

        foreach ($options as $key => $field) {
            $ignore = rad_array_value("dontsave", rad_array_value("meta", $field, array()), false);

            if ($ignore) {
                continue;
            }

            $values[$key] = $field;
        }

        return $values;
    }

    private function rad_GetOptions()
    {
        $fields = array(
            "notice_column"            => array(
                "title" => esc_html__("Notice!", "aventa"),
                "desc"  => esc_html__("Column must be used at second level.", "aventa"),
                "type"  => "label",
                "class" => "rad-menu-notice-column rad-menu-message",
            ),
            "notice_column_megamenu"   => array(
                "title" => esc_html__("Notice!", "aventa"),
                "desc"  => esc_html__("Its parent must be a megamenu.", "aventa"),
                "type"  => "label",
                "class" => "rad-menu-notice-column-megamenu rad-menu-message",
            ),
            "notice_headline"          => array(
                "title" => esc_html__("Notice!", "aventa"),
                "desc"  => esc_html__("Headline/Banner must be used at 3rd level.", "aventa"),
                "type"  => "label",
                "class" => "rad-menu-notice-headline-banner rad-menu-message",
            ),
            "notice_headline_megamenu" => array(
                "title" => esc_html__("Notice!", "aventa"),
                "desc"  => esc_html__("Its parent must be a megamenu.", "aventa"),
                "type"  => "label",
                "class" => "rad-menu-notice-headline-banner-megamenu rad-menu-message",
            ),
            "badge-label"              => array(
                "type"        => "text",
                "class"       => "badge-label",
                "label"       => esc_html__("Badge label", "aventa"),
                "placeholder" => esc_html__("eg: new", "aventa"),
                "value"       => "",
            ),
            "badge-bg-color"           => array(
                "type"  => "color",
                "class" => "badge-bg-color",
                "label" => esc_html__("Badge background color", "aventa"),
                "value" => "#ccc",
            ),
            "is-mega-menu"             => array(
                "type"        => "checkbox",
                "class"       => "is-mega-menu",
                "label"       => esc_html__("Mega Menu", "aventa"),
                "description" => esc_html__("Is it a Mega menu?", "aventa"),
                "value"       => "1",
            ),
            "column-title"             => array(
                "label" => esc_html__("Column title in mobile/tablet devices", "aventa"),
                "type"  => "text",
                "class" => "column-title",
                "value" => "",
            ),
            "bg-image"                 => array(
                "label"       => esc_html__("Background Image", "aventa"),
                "description" => esc_html__("Set an image for the mega menu", "aventa"),
                "type"        => "upload",
                "referer"     => "rad-insert-image",
                "meta"        => array("array" => false),
            ),
        );

        return $fields;

    }

    //this option add id of menu to each options because we need unique field names in menu page for each menu item
    private function rad_MakeUniqueOptions($id)
    {
        $options = $this->rad_GetOptions();

        $new_options;

        foreach ($options as $key => $field) {
            $new_options[$key . "-" . $id] = $field;
        }

        return $new_options;
    }

    public function rad_ShowMetaBox($new_fields, $item_output, $item, $depth, $args)
    {
        global $post;
        $post    = $item;
        $options = $this->rad_MakeUniqueOptions($item->ID);

        $form = new rad_FieldTemplate(new rad_PostOptionsProvider(), dirname(__FILE__));
        return $form->rad_GetTemplate("meta-form", $options);
    }

    public function rad_NavMenuHanler()
    {
        //return the name of class that handles nav-menu output in wp-admin
        return "rad_Walker_Nav_Menu_Edit";

    }

    public function rad_InitScripts()
    {
        global $post;
        if (!$post || $post->post_type != $this->postType) {
            return;
        }

        $this->rad_RegisterScripts();
        $this->rad_EnqueueScripts();
    }

    private function rad_RegisterScripts()
    {
        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");

        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");
    }

    private function rad_EnqueueScripts()
    {
        wp_enqueue_media();
        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("media-upload");
        wp_enqueue_script("thickbox");
        wp_enqueue_style("thickbox");
    }
}

new rad_Menu();
