<?php

class Wiaas_Admin_Template_Selection {

    public static function init() {
        add_action('add_meta_boxes', array(__CLASS__, 'create_template_meta_box'), 100);
        add_action('woocommerce_process_product_meta_bundle', array(__CLASS__, 'save_template_content_meta_box'), 10, 1);

        // Processes and saves type-specific data.
        add_action('woocommerce_admin_process_product_object', array(__CLASS__, 'validate_bundle'), 11);

    }

    /**
     * Renders template selection meta box
     */
    public static function create_template_meta_box() {
        add_meta_box(
            'template_product_meta_box',
            __('Choose  package template <em>(optional)</em>', 'cmb'),
            'Wiaas_Admin_Template_Selection::add_template_content_meta_box',
            'product',
            'normal',
            'high'
        );
    }

    /**
     * Fill in the value of template selection dropdown,
     * and render template categories of the selected template
     *
     * @param $post WP_Post object
     */
    public static function add_template_content_meta_box($post) {

        $value = get_post_meta($post->ID, '_select_template', true);

        if (empty($value)) {
            $value = '';
        }

        $products = wc_get_products(array(
            'type' => 'wiaastemplate'
        ));
        $product_ids[''] = __('Select a template', 'wiaas');
        foreach ($products as $prod) {
            $product_ids[$prod->id] = $prod->name;
        }
        woocommerce_wp_select(array(
            'id' => '_select_template',
            'options' => $product_ids,
            'value' => $value
        ));

        ?>
        <div id="wiaas_selected_template_items_container"><?php
        $template_products_data = self::show_template_products($value);

        self::render_template_products($template_products_data['hardware']);
        self::render_template_products($template_products_data['services']);
        self::render_template_products($template_products_data['installation']);
        self::render_template_products($template_products_data['software']);
        ?></div><?php

    }

    /**
     * Extract template categories for all of the main product categories
     * (software , hardware, services, installation)  and combine them in one array
     *
     * @param $categories_form_template
     * @return array of Wiaas_Template_Category_Object
     */
    public static function get_categories_from_templates($categories_form_template) {

        $all_template_categories = array();

        $all_template_categories = array_merge($all_template_categories,
            WC_Product_Template::extract_template_product_categories($categories_form_template['hardware']));

        $all_template_categories = array_merge($all_template_categories,
            WC_Product_Template::extract_template_product_categories($categories_form_template['services']));

        $all_template_categories = array_merge($all_template_categories,
            WC_Product_Template::extract_template_product_categories($categories_form_template['installation']));

        $all_template_categories = array_merge($all_template_categories,
            WC_Product_Template::extract_template_product_categories($categories_form_template['software']));

        return $all_template_categories;

    }

    /**
     * Return all of the template product meta_data from selected template
     *
     * @param $selected_template integer an id of selected template
     * @return array of template categories
     */
    public static function show_template_products($selected_template) {


        if (empty($selected_template)) {
            return array();

        } else {

            $template_products_hardware = WC_Product_Template::get_template_categories_from_meta(
                $selected_template, '_template_items_hardware');

            $template_products_services = WC_Product_Template::get_template_categories_from_meta(
                $selected_template, '_template_items_services');

            $template_products_installation = WC_Product_Template::get_template_categories_from_meta(
                $selected_template, '_template_items_installation');

            $template_products_software = WC_Product_Template::get_template_categories_from_meta(
                $selected_template, '_template_items_software');
        }


        return array(
            'hardware' => $template_products_hardware,
            'services' => $template_products_services,
            'installation' => $template_products_installation,
            'software' => $template_products_software
        );

    }

    /**
     * Render html of template categories
     *
     * @param $template_products array containing template category information
     */
    public static function render_template_products($template_products) {
        if (!empty($template_products)) {


            foreach ($template_products as $item) {

                $product_id = $item['template_category_id'];
                $title = $item['template_category_title'];
                $quantity = $item['quantity'];

                include('views/html-wiaas-template-selection.php');

            }
        }
    }


    /**
     * Save selected template
     *
     * @param $post_id WP_Post
     */

    function save_template_content_meta_box($post_id) {
        $selected_template = $_POST['_select_template'];

        WC_Product_Template::bind_selected_template_to_product($selected_template, $post_id);

    }

    /**
     * Get the template categories from bundle products and selected template
     * Compare template categories and quantities that are required by the template with those in bundle products
     *
     * Admin error is added if validation is not satisfied
     *
     * @param $product WC_Product_Bundle
     */
    public static function validate_bundle($product) {


        if ($product->get_type() == 'bundle') {
            $selected_template = $_POST['_select_template'];
            $bundled_items = $product->get_bundled_items('view');
            $template_categories_form_template = self::show_template_products($selected_template);

            $missing_template_categories = array();
            $insufficient_template_category_quantities = array();

            $categories_form_template = self::get_categories_from_templates($template_categories_form_template);
            $categories_form_bundle = WC_Product_Template::extract_bundled_product_categories($bundled_items);
            $bundle_category_keys = array_keys($categories_form_bundle);

            if (!empty($categories_form_template)) {

                foreach ($categories_form_template as $category) {
                    $template_cat_id = $category->template_category_id;


                    if (!in_array($template_cat_id, $bundle_category_keys)) {

                        array_push($missing_template_categories, $category->name);

                    } else {

                        $product_from_bundle_quantity = $categories_form_bundle[$template_cat_id]->quantity;
                        $quantity_from_template = $category->quantity;

                        if ((int)($quantity_from_template) !== $product_from_bundle_quantity) {
                            array_push($insufficient_template_category_quantities, $category->name);
                        }
                    }
                }
            }

            $template_categories_message = implode(',', $missing_template_categories);
            $quantity_message = implode(',', $insufficient_template_category_quantities);

            if (!empty($missing_template_categories)) {
                WC_PB_Meta_Box_Product_Data::add_admin_error(__(' <strong> WIAAS This product bundle does not correspond to selected template</strong>  Categories missing: ' . $template_categories_message, 'woocommerce-product-bundles'));
            }

            if (!empty($insufficient_template_category_quantities)) {
                WC_PB_Meta_Box_Product_Data::add_admin_error(__(' <strong> WIAAS This product bundle does not correspond to selected template</strong>  Categories with different quantities:  ' . $quantity_message, 'woocommerce-product-bundles'));
            }
        }

    }
}

Wiaas_Admin_Template_Selection::init();
