<?php

// Exit if accessed directly.
if (!defined('ABSPATH')) {
    exit;
}

class Wiaas_Template_Admin_Ajax {

    /**
     * Hook in.
     */
    public static function init() {

        // Ajax template category
        add_action('wp_ajax_wiaas_add_template_product', array(__CLASS__, 'ajax_add_wiaas_template_product'));
        add_action('wp_ajax_wiaas_template_category_search', array(__CLASS__, 'ajax_wiaas_template_category_search'));

        add_action('wp_ajax_wiaas_select_template', array(__CLASS__, 'ajax_handle_template_selection'));
        add_action('wp_ajax_wiaas_product_type_change', array(__CLASS__, 'toggle_template_selection_on_type_change'));
    }


    /**
     * An ajax callback action for handling template selection
     */

    public static function ajax_handle_template_selection() {

        $selected_template_id = intval($_POST['selected_template']);
        $response = array(
            'markup' => '',
            'message' => ''
        );

        $template_products = Wiaas_Admin_Template_Selection::show_template_products($selected_template_id);

        if (!empty($template_products)) {
            ob_start();
            Wiaas_Admin_Template_Selection::render_template_products($template_products['hardware']);
            Wiaas_Admin_Template_Selection::render_template_products($template_products['services']);
            Wiaas_Admin_Template_Selection::render_template_products($template_products['installation']);
            Wiaas_Admin_Template_Selection::render_template_products($template_products['software']);

            $response['markup'] = ob_get_clean();
        }

        wp_send_json($response);
    }


    /**
     * Handles adding template categories to template via ajax.
     */
    public static function ajax_add_wiaas_template_product() {

        check_ajax_referer('wc_bundles_add_bundled_product', 'security');

        $loop = intval($_POST['id']);
        $template_category_id = intval($_POST['template_category_id']);
        $title = $_POST['title'];
        $options = $_POST['options'];

        $response = array(
            'markup' => '',
            'message' => ''
        );

        ob_start();
        include('views/html-wiaas-template-product.php');
        $response['markup'] = ob_get_clean();

        wp_send_json($response);
    }

    /**
     * Handles adding template categories search.
     */
    public static function ajax_wiaas_template_category_search() {

        $term = wp_unslash($_GET['term']);
        $response = array();
        
        $terms = get_terms(array(
            'taxonomy' => 'template_category',
            'name__like' => $term
        ));

        foreach ($terms as $t) {
            $response[$t->term_id] = $t->name;
        }

        wp_send_json($response);
    }
}

Wiaas_Template_Admin_Ajax::init();
