<?php
if (!rad_is_wc_active()) {
    return;
}

//Add new attribute types to WC
add_filter("product_attributes_type_selector", "rad_add_woocommerce_attribute_types");

//Add image attribute UI to product metabox
add_action("woocommerce_product_option_terms", "rad_add_woocommerce_attribute_new_ui", 10, 3);

//save extra data for new attribute types
add_action("woocommerce_process_product_meta", "rad_save_woocommerce_attribute_metadata", 30, 2);

//change handler of saving attributes ajax request to Save extra data for new attributes
remove_action("wp_ajax_woocommerce_save_attributes", array("WC_AJAX", "save_attributes"));
add_action("wp_ajax_woocommerce_save_attributes", "rad_ajax_save_woocommerce_attribute_metadata");

function rad_add_woocommerce_attribute_new_ui($attribute_taxonomy, $i, $attribute)
{
    if ("color" === $attribute_taxonomy->attribute_type || "size" === $attribute_taxonomy->attribute_type) {
        ?>
        <select multiple="multiple" data-placeholder="<?php esc_attr_e("Select terms", "aventa");?>" class="multiselect attribute_values wc-enhanced-select" name="attribute_values[<?php echo esc_attr($i); ?>][]">
        <?php
        $args = array(
            "orderby"    => !empty($attribute_taxonomy->attribute_orderby) ? $attribute_taxonomy->attribute_orderby : "name",
            "hide_empty" => 0,
        );
        $all_terms = get_terms($attribute->get_taxonomy(), apply_filters("woocommerce_product_attribute_terms", $args));
        if ($all_terms) {
            foreach ($all_terms as $term) {
                $options = $attribute->get_options();
                $options = !empty($options) ? $options : array();
                echo "<option value=\"" . esc_attr($term->term_id) . "\" " . wc_selected($term->term_id, $options) . ">" . esc_html(apply_filters("woocommerce_product_attribute_term_name", $term->name, $term)) . "</option>";
            }
        }
        ?>
        </select>
        <button class="button plus select_all_attributes"><?php esc_html_e("Select all", "aventa");?></button>
        <button class="button minus select_no_attributes"><?php esc_html_e("Select none", "aventa");?></button>
        <button class="button fr plus add_new_attribute"><?php esc_html_e("Add new", "aventa");?></button>
        <?php

        return;

    } elseif ("image" === $attribute_taxonomy->attribute_type) {
        global $thepostid;

        if (!$thepostid) {
            $thepostid = $_POST["post_id"];
        }

        $attr_values = array();

        if ($thepostid) {
            $attr_values = get_post_meta($thepostid, esc_attr($attribute->get_taxonomy()) . "_extravalue", true);
        }

        $args = array(
            "orderby"    => !empty($attribute_taxonomy->attribute_orderby) ? $attribute_taxonomy->attribute_orderby : "name",
            "hide_empty" => 0,
        );
        $all_terms = get_terms($attribute->get_taxonomy(), apply_filters("woocommerce_product_attribute_terms", $args));

        if ($all_terms) {
            ?>
            <div class="fields-container">
            <?php

            foreach ($all_terms as $term) {
                $key = "" . $term->slug;

                $container_class        = "field-container image-attr-field-container";
                $input_value_name       = "attribute_values";
                $input_extra_value_name = "attribute_extra_values";

                $options = $attribute->get_options();
                $options = !empty($options) ? $options : array();

                //Hide deleted terms
                //Add X before names to prevent from saving it's values
                if (selected(in_array($term->term_id, $options), true, false) == "" && !empty($options)) {
                    $container_class        = "field-container image-attr-field-container hide-field";
                    $input_value_name       = "x_attribute_values";
                    $input_extra_value_name = "x_attribute_extra_values";
                }

                $val = $original_val = "";
                if (isset($attr_values[$term->slug])) {

                    // get image for upload field
                    if ("image" == $attribute_taxonomy->attribute_type) {
                        $original_val = $attr_values[$term->slug]; //id of image
                        $val          = wp_get_attachment_url($attr_values[$term->slug]); //url of image
                    }

                }
                ?>
                <div class="<?php echo esc_attr($container_class); ?>" data-attr-number="<?php echo esc_attr($i); ?>">
                    <a class="attr_remove"></a>
                    <input type="hidden" name="<?php echo esc_attr($input_value_name); ?>[<?php echo esc_attr($i); ?>][]" value="<?php echo esc_attr($term->term_id); ?>">
                    <input type="hidden" name="<?php echo esc_attr($input_extra_value_name); ?>[<?php echo esc_attr($i); ?>][<?php echo esc_attr($term->slug); ?>]" value="<?php echo esc_attr($original_val); ?>">

                    <div class="field upload-field clear-after" data-title="<?php esc_attr_e("Upload Image of attribute", "aventa");?>" data-referer="rad-attr-image" >
                        <label for="field-<?php echo esc_attr($term->slug); ?>">
                            <?php echo esc_html($term->name); ?>
                        </label>
                        <input type="hidden" id="field-<?php echo esc_attr($term->slug); ?>" name="<?php echo esc_attr($term->slug); ?>" value="<?php echo esc_attr($val); ?>"/>
                        <a href="#" class="upload-button"><?php esc_html_e("Browse", "aventa");?></a>
                        <div class="upload-thumb <?php if ($val) {echo "show";}?>">
                            <div class="close"><span class="close-icon"></span></div>
                            <img class="" src="<?php echo esc_url($val); ?>" alt="<?php echo esc_attr($term->name); ?>">
                        </div>
                    </div>

                </div>
                <?php
            }
            ?>

            </div>
            <?php
        }

        ?>
        <a href="#" class="button plus add_all_attr"><?php esc_html_e("Add all terms", "aventa");?></a>
        <a href="#" class="button plus add_new_attr"><?php esc_html_e("Add new terms", "aventa");?></a>
        <?php
    }
}

//Add new type to woocommerce attribute types
function rad_add_woocommerce_attribute_types($types)
{
    $types["image"] = esc_html__("Image", "aventa");
    $types["size"]  = esc_html__("Size", "aventa");
    $types["color"] = esc_html__("Color", "aventa");
    return $types;
}

/**
 * Save attributes via ajax.
 */
function rad_ajax_save_woocommerce_attribute_metadata()
{
    //save extra post data
    rad_save_woocommerce_attribute_metadata($_POST["post_id"], null);
    //call original ajax handler
    return WC_AJAX::save_attributes();
}

/**
 * Save meta box data
 */
function rad_save_woocommerce_attribute_metadata($post_id, $post)
{
    global $wpdb;

    if (isset($_POST["attribute_names"]) && isset($_POST["attribute_values"]) || isset($_POST["data"])) {

        if (isset($_POST["data"])) {
            parse_str($_POST["data"], $data);

            $attribute_names        = $data["attribute_names"];
            $attribute_values       = $data["attribute_values"];
            $attribute_extra_values = array();
            if (isset($data["attribute_extra_values"])) {
                $attribute_extra_values = $data["attribute_extra_values"]; // extra metadata such as image id
            }
        } else {
            $attribute_names        = $_POST["attribute_names"];
            $attribute_values       = $_POST["attribute_values"];
            $attribute_extra_values = array();
            if (isset($_POST["attribute_extra_values"])) {
                $attribute_extra_values = $_POST["attribute_extra_values"]; // extra metadata such as image id
            }
        }

        $attribute_names_max_key = max(array_keys($attribute_names));

        for ($i = 0; $i <= $attribute_names_max_key; $i++) {
            if (empty($attribute_names[$i])) {
                continue;
            }

            if (taxonomy_exists($attribute_names[$i]) && isset($attribute_values[$i])) {
                if (isset($attribute_extra_values[$i])) {

                    $slug_extra_data = array();
                    //posted values are extra data & key is term slug
                    if (is_array($attribute_extra_values[$i])) {

                        $extravalues = $attribute_extra_values[$i];

                        foreach ($extravalues as $key => $value) {
                            $slug_extra_data[$key] = $value;
                        }
                    }

                    update_post_meta($post_id, wc_clean($attribute_names[$i]) . "_extravalue", $slug_extra_data);

                } else {
                    update_post_meta($post_id, wc_clean($attribute_names[$i]) . "_extravalue", "");

                }
            }
        }
    }

}

add_action("add_tag_form_fields", "rad_add_color_attribute_type");
$wc_attributes = wc_get_attribute_taxonomies();
foreach ($wc_attributes as $wc_attribute) {
    if ($wc_attribute->attribute_type == "color") {
        add_action("pa_" . $wc_attribute->attribute_name . "_edit_form_fields", "rad_edit_color_attribute_type");
    }
}

add_action("create_term", "rad_save_termmeta_tag_on_create", 10, 3);
add_action("edit_terms", "rad_save_termmeta_tag_on_edit", 10, 2);

function rad_add_color_attribute_type($taxonomy)
{
    $type = rad_wc_get_Attribute_type($taxonomy);
    if ($type == "color") {
        echo "<div class=\"form-field term-colorpicker-wrap rad-color-attr\">
        <label for=\"term-colorpicker\">" . esc_html_e("Color", "aventa") . "</label>
        <input type=\"text\" name=\"rad_attr_color\" value=\"#737373\" class=\"colorinput\" />
        </div>";
    }
}

function rad_edit_color_attribute_type($term)
{

    $color = get_term_meta($term->term_id, "attr_color", true);
    $color = (!empty($color)) ? "#{$color}" : "#fff";

    echo "<tr class=\"form-field rad-color-attr color-field-wrap clear-after has-label\">
        <th scope=\"row\"><label for=\"term-colorpicker\">" . esc_html__("Color", "aventa") . "</label></th>
        <td>
            <input type=\"text\" name=\"rad_attr_color\" value=\"" . esc_attr($color) . "\" class=\"colorinput\"/>
            <div class=\"color-view\"></div>
        </td>
    </tr>";

}

function rad_save_termmeta_tag_on_create($term_id, $tt_id, $taxonomy)
{
    if (isset($_POST["rad_attr_color"]) && !empty($_POST["rad_attr_color"])) {
        update_term_meta($term_id, "attr_color", sanitize_hex_color_no_hash($_POST["rad_attr_color"]));
    } else {
        delete_term_meta($term_id, "attr_color");
    }
}

function rad_save_termmeta_tag_on_edit($term_id, $taxonomy)
{
    if (isset($_POST["rad_attr_color"]) && !empty($_POST["rad_attr_color"])) {
        update_term_meta($term_id, "attr_color", sanitize_hex_color_no_hash($_POST["rad_attr_color"]));
    } else {
        delete_term_meta($term_id, "attr_color");
    }
}

/*-----------------------------------------------------------------*/
// Custom fields of WC categories
/*-----------------------------------------------------------------*/
add_action("product_cat_edit_form_fields", "rad_wc_cat_taxonomy_edit_meta_field", 15);
add_action("product_cat_add_form_fields", "rad_wc_cat_taxonomy_add_meta_field", 15);
add_action("edited_product_cat", "rad_save_wc_cat_taxonomy_custom_meta", 10, 3);
add_action("create_product_cat", "rad_save_wc_cat_taxonomy_custom_meta", 10, 3);

if (!function_exists("rad_wc_cat_taxonomy_edit_meta_field")) {
    function rad_wc_cat_taxonomy_edit_meta_field($term)
    {

        $image                 = "";
        $header_image_id       = absint(get_term_meta($term->term_id, "cat-header-bg-image", true));
        $cat_header_bg_color   = get_term_meta($term->term_id, "cat-header-bg-color", true);
        $cat_header_text_color = get_term_meta($term->term_id, "cat-header-text-color", true);
        $cat_collection        = get_term_meta($term->term_id, "cat-collection", true);

        if ($header_image_id):
            $image = wp_get_attachment_url($header_image_id);
        else:
            $image = wc_placeholder_img_src();
        endif;

        ?>

        <tr class="form-field">
            <th scope="row" valign="top"><label><?php esc_html_e("Used as collection?", "aventa");?></label></th>
            <td>
                <div class="form-field term-collection-wrap">
                    <input type="checkbox" id="cat-collection" name="cat-collection" value="1" <?php checked($cat_collection, 1);?> />
                    <p><?php esc_html_e("Notice: If you checked this, this category is hidden in categories and just displayed under collection aside in menu.", "aventa");?></p>
                </div>
            </td>
        </tr>


        <tr class="form-field">
            <th scope="row" valign="top"><label><?php esc_html_e("Header background image", "aventa");?></label></th>
            <td>
                <div id="product_cat_background_image" data-default-img="<?php echo wc_placeholder_img_src(); ?>"><img src="<?php echo esc_url($image); ?>" width="60%"/></div>
                    <input type="hidden" id="cat-header-bg-image" name="cat-header-bg-image" value="<?php echo esc_attr($header_image_id); ?>" />
                    <button type="button" class="upload_wc_cat_header_image_button button"><?php esc_html_e("Upload/Add image", "aventa");?></button>
                    <button type="button" class="remove_wc_cat_header_image_button button"><?php esc_html_e("Remove image", "aventa");?></button>
            </td>
        </tr>
        <tr class="form-field">
            <th scope="row" valign="top"><label><?php esc_html_e("Header overlay color", "aventa");?></label></th>
            <td>
                <div class="field color-field clear-after">
                    <div class="color-field-wrap clear-after">
                        <input name="cat-header-bg-color" data-alpha="true" type="text" value="<?php echo esc_attr($cat_header_bg_color); ?>" class="colorinput"/>
                        <div class="color-view"></div>
                    </div>
                    <p><?php esc_html_e("Leave it empty to use theme setting values", "aventa");?></p>
                </div>
            </td>
        </tr>
        <tr class="form-field">
            <th scope="row" valign="top"><label><?php esc_html_e("Header text color", "aventa");?></label></th>
            <td>
                <div class="field color-field clear-after">
                    <div class="color-field-wrap clear-after">
                        <input name="cat-header-text-color" data-alpha="true" type="text" value="<?php echo esc_attr($cat_header_text_color); ?>" class="colorinput"/>
                        <div class="color-view"></div>
                    </div>
                    <p><?php esc_html_e("Leave it empty to use theme setting values", "aventa");?></p>
                </div>
            </td>
        </tr>
    <?php
    }
}

if (!function_exists("rad_wc_cat_taxonomy_add_meta_field")) {
    function rad_wc_cat_taxonomy_add_meta_field()
    {
        ?>
        <div class="form-field term-collection-wrap">
            <label><?php esc_html_e("Used as collection?", "aventa");?><label>
            <input type="checkbox" id="cat-collection" name="cat-collection" value="1"/>
            <p><?php esc_html_e("Notice: If you checked this, this category is hidden in categories and just displayed under collection aside in menu.", "aventa");?></p>
        </div>
        <div class="form-field term-header-image-wrap">
            <label><?php esc_html_e("Header background image", "aventa");?><label>
            <div id="product_cat_background_image" data-default-img="<?php echo wc_placeholder_img_src(); ?>"><img src="<?php echo esc_url(wc_placeholder_img_src()); ?>" width="60%"/></div>
            <input type="hidden" id="cat-header-bg-image" name="cat-header-bg-image" />
            <button type="button" class="upload_wc_cat_header_image_button button"><?php esc_html_e("Upload/Add image", "aventa");?></button>
            <button type="button" class="remove_wc_cat_header_image_button button"><?php esc_html_e("Remove image", "aventa");?></button>
        </div>
        <div class="form-field term-header-color-wrap">
            <label><?php esc_html_e("Header bg color", "aventa");?></label>
            <div class="color-field-wrap clear-after">
                <input name="cat-header-bg-color" data-alpha="true" type="text" value="" class="colorinput"/>
                <div class="color-view"></div>
            </div>
            <p><?php esc_html_e("Leave it empty to use theme setting values", "aventa");?></p>
        </div>
        <div class="form-field term-header-color-wrap">
            <label><?php esc_html_e("Header text color", "aventa");?></label>
            <div class="color-field-wrap clear-after">
                <input name="cat-header-text-color" data-alpha="true" type="text" value="" class="colorinput"/>
                <div class="color-view"></div>
            </div>
            <p><?php esc_html_e("Leave it empty to use theme setting values", "aventa");?></p>
        </div>
    <?php
    }
}

if (!function_exists("rad_save_wc_cat_taxonomy_custom_meta")) {
    function rad_save_wc_cat_taxonomy_custom_meta($term_id, $tt_id = "", $taxonomy = "")
    {
        if (isset($_POST["cat-header-bg-image"])) {
            update_term_meta($term_id, "cat-header-bg-image", absint($_POST["cat-header-bg-image"]));
        }

        if (isset($_POST["cat-header-bg-color"])) {
            update_term_meta($term_id, "cat-header-bg-color", $_POST["cat-header-bg-color"]);
        }

        if (isset($_POST["cat-header-text-color"])) {
            update_term_meta($term_id, "cat-header-text-color", $_POST["cat-header-text-color"]);
        }

        if (isset($_POST["cat-collection"]) && $_POST["cat-collection"] == "1") {
            update_term_meta($term_id, "cat-collection", "1");
        }

        delete_transient("wc_term_counts");
    }
}

/******************************************************
 * Add image of products in shop loop
 *******************************************************/
add_filter("wpb_vc_js_status_filter", "rad_disable_vc_on_tabs_in_summary");
if (!function_exists("rad_disable_vc_on_tabs_in_summary")) {
    function rad_disable_vc_on_tabs_in_summary($status)
    {
        global $post;
        $product_tab_position = rad_get_option("product-tab-position");
        if ($post->post_type == "product" && $product_tab_position != "default") {
            return false;
        }
        return $status;
    }
}
