<?php

class Wiaas_Admin_Template_Selection {

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

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

    }

    public static function create_custom_meta_box() {
        add_meta_box(
            'template_product_meta_box',
            __('Choose  package template <em>(optional)</em>', 'cmb'),
            'Wiaas_Admin_Template_Selection::add_custom_content_meta_box',
            'product',
            'normal',
            'high'
        );
    }


    public static function add_custom_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['service']);
        self::render_template_products($template_products_data['installation']);
        self::render_template_products($template_products_data['software']);
        ?></div><?php

    }

    public static function get_categories_from_templates($products_form_template) {

        $all_template_categories = array();

        $all_template_categories = array_merge($all_template_categories, self::get_product_categories($products_form_template['hardware']));
        $all_template_categories = array_merge($all_template_categories, self::get_product_categories($products_form_template['service']));
        $all_template_categories = array_merge($all_template_categories, self::get_product_categories($products_form_template['installation']));
        $all_template_categories = array_merge($all_template_categories, self::get_product_categories($products_form_template['software']));

        return $all_template_categories;

    }

    public static function show_template_products($selected_template) {


        if (empty($selected_template)) {
            return;

        } else {
            $template_products_hardware = (get_post_meta($selected_template, '_template_items_hardware', true));
            $template_products_service = (get_post_meta($selected_template, '_template_items_service', true));
            $template_products_installation = (get_post_meta($selected_template, '_template_items_installation', true));
            $template_products_software = (get_post_meta($selected_template, '_template_items_software', true));
        }


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

    }

    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');

            }
        }
    }

    public static function get_product_categories($category_meta) {
        $category_objects = array();


        if (empty($category_meta)) {
            return array();
        }

        foreach ($category_meta as $meta) {

            if (!empty($meta)) {


                $category_template_id = $meta['template_category_id'];

                $template_category_object = new Wiaas_Template_Category_Object(
                    $category_template_id,
                    $meta['template_category_title'],
                    $meta['quantity']);

                $category_objects[$category_template_id] = $template_category_object;
            }

        }
        return empty($category_objects) ? null : $category_objects;
    }

    public static function get_bundled_product_categories($bundled_items) {

        $template_category_objects = array();
        foreach ($bundled_items as $item_id => $item) {
            $item_data = $item->get_data();
            $post_terms = wp_get_object_terms($item->get_product_id(), 'template_category', array('fields' => 'id=>name'));

            if (!empty($post_terms) && !is_wp_error($post_terms)) {

                $cat = '';
                $category_template_id = '';

                foreach ($post_terms as $id => $term) {
                    $cat = $term;
                    $category_template_id = $id;
                }

                $template_category_object = new Wiaas_Template_Category_Object(
                    $category_template_id,
                    $cat,
                    $item_data['quantity_max']);
                $template_category_objects[$category_template_id] = $template_category_object;

            }
        }

        return $template_category_objects;
    }


    function save_custom_content_meta_box($post_id) {
        $selected_template = $_POST['_select_template'];
        if (!empty($selected_template))
            update_post_meta($post_id, '_select_template', esc_attr($selected_template));
        else {
            update_post_meta($post_id, '_select_template', '');
        }

    }

    public static function validate_bundle($product) {


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

            $missing_categories = array();
            $insufficient_product_quantities = array();


            $categories_form_template = self::get_categories_from_templates($products_form_template);
            $categories_form_bundle = self::get_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_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_product_quantities, $category->name);
                        }
                    }
                }
            }

            $categories_message = implode(',', $missing_categories);
            $quantity_message = implode(',', $insufficient_product_quantities);

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

            if (!empty($insufficient_product_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'));
            }
        }

    }

    public static function get_category_ids_form_bundle($product) {
        $products_form_budnle = $product->get_bundled_data_items();
        $product_ids = array();

        foreach ($products_form_budnle as $product) {
            array_push($product_ids, $product->get_id());
        }

        return self::get_product_categories($product_ids);

    }
}

Wiaas_Admin_Template_Selection::init();
