<?php

/**
 * Product Types Manager
 * 
 * @package cwpt
 * @since 1.0.0
 */

defined('ABSPATH') or die;

class CWPT_Product_Types
{
    /**
     * Add custom product types to WooCommerce
     * 
     * @param array $types
     * @return array
     */
    public static function add_type($types)
    {
        if (!empty(CWPT_Settings::get('name_ids')) && is_array(CWPT_Settings::get('name_ids'))) {
            foreach (CWPT_Settings::get('name_ids') as $key => $name) {
                $types[$name] = ucfirst(CWPT_Settings::get('single')[$key]) . ' product';
            }
        }
        return $types;
    }

    /**
     * Set WooCommerce product class
     * 
     * @param string $classname
     * @param string $product_type
     * @return string
     */
    public static function set_product_class($classname, $product_type)
    {
        if (class_exists('WC_CWPT_Product_Type_' . $product_type) && in_array($product_type, CWPT_Settings::get('name_ids'))) {
            $classname = 'WC_CWPT_Product_Type_' . $product_type;
        } else {
            $classname = $classname;
        }

        return $classname;
    }

    /**
     * Register custom product types dynamically
     * 
     * @return void
     */
    public static function register_types()
    {
        $cwpt_types = CWPT_Settings::get('single');
        $cwpt_types_ids = CWPT_Settings::get('name_ids');

        if (!empty($cwpt_types) && is_array($cwpt_types)) {
            foreach ($cwpt_types as $key => $type) {
                $class_name = 'WC_CWPT_Product_Type_' . $cwpt_types_ids[$key];
                if (!class_exists($class_name)) {
                    $code = '
                class ' . $class_name . ' extends WC_Product_Simple {
                    /**
                     * Return the product type
                     * @return string
                     */
                    public function get_type() {
                        return \'' . $cwpt_types_ids[$key] . '\';
                    }
                }';
                    eval($code);
                }
            }
        }
    }

    /**
     * Generate product type classes
     * 
     * @return void
     */
    public static function generate_classes()
    {
        if (isset($_POST['CWPT_Generate'])) {
            $cwpt_types = CWPT_Settings::get('single');
            $cwpt_types_ids = CWPT_Settings::get('name_ids');
            $cwpt_types_classes = CWPT_Settings::get('class');
            
            $classes_files_checker = [];
            $current_exists_classes = array_diff(scandir(dirname(__FILE__) . '/classes'), array('..', '.'));

            if (!empty($cwpt_types) && is_array($cwpt_types)) {
                foreach ($cwpt_types as $key => $type) {
                    $classes_files_checker[] = 'class-' . $cwpt_types_classes[$key] . '.php';
                    $classes_creator = fopen(plugin_dir_path(dirname(__FILE__)) . '/includes/classes/class-' . $cwpt_types_classes[$key] . '.php', 'w') or die('Unable to Create cwpt file!');
                    $code = '<?php

                    defined( \'ABSPATH\' ) || exit;

                    class WC_CWPT_Product_Type_' . $cwpt_types_ids[$key] . ' extends WC_Product_Simple {
                        /**
                         * Return the product type
                         * @return string
                         */
                        public function get_type() {
                            return \'' . $cwpt_types_ids[$key] . '\';
                        }
                    
                         
                    }';
                    fwrite($classes_creator, $code);
                    fclose($classes_creator);
                }

                foreach ($current_exists_classes as $file) {
                    if (!in_array($file, $classes_files_checker) && $file !== 'cwpt_class_creator.php') {
                        unlink(plugin_dir_path(dirname(__FILE__)) . '/includes/classes/' . $file);
                    }
                }
                $_POST['CWPT_Generate'] = 'success';
            } elseif (empty($cwpt_types)) {
                $_POST['CWPT_Generate'] = 'empty';
            } else {
                $_POST['CWPT_Generate'] = 'failed';
            }
        }
    }

    /**
     * Register custom taxonomies for product types
     * 
     * @return void
     */
    public static function register_taxonomies()
    {
        $types_plural = CWPT_Settings::get('plural');
        $types_tax_status = CWPT_Settings::get('status');
        
        if (is_array(CWPT_Settings::get('single'))) {
            foreach (CWPT_Settings::get('single') as $key => $name_single) {

                if ($types_tax_status[$key] == 'Enabled') {
                    $args = [
                        'label'                => esc_html__(ucfirst($name_single) . ' category', 'cwpt'),
                        'labels'               => [
                            'menu_name'                  => esc_html__(ucfirst($types_plural[$key]) . ' categories', 'cwpt'),
                            'all_items'                  => esc_html__('All ' . ucfirst($types_plural[$key]) . ' categories', 'cwpt'),
                            'edit_item'                  => esc_html__('Edit ' . ucfirst($name_single) . ' category', 'cwpt'),
                            'view_item'                  => esc_html__('View ' . ucfirst($name_single) . ' category', 'cwpt'),
                            'update_item'                => esc_html__('Update ' . ucfirst($name_single) . ' category', 'cwpt'),
                            'add_new_item'               => esc_html__('Add new ' . ucfirst($name_single) . ' category', 'cwpt'),
                            'new_item'                   => esc_html__('New ' . ucfirst($name_single) . ' category', 'cwpt'),
                            'parent_item'                => esc_html__('Parent ' . ucfirst($name_single) . ' category', 'cwpt'),
                            'parent_item_colon'          => esc_html__('Parent ' . ucfirst($name_single) . ' category', 'cwpt'),
                            'search_items'               => esc_html__('Search ' . ucfirst($types_plural[$key]) . ' categories', 'cwpt'),
                            'popular_items'              => esc_html__('Popular ' . ucfirst($types_plural[$key]) . ' categories', 'cwpt'),
                            'separate_items_with_commas' => esc_html__('Separate ' . ucfirst($types_plural[$key]) . ' categories' . ' with commas', 'cwpt'),
                            'add_or_remove_items'        => esc_html__('Add or remove ' . ucfirst($types_plural[$key]) . ' categories', 'cwpt'),
                            'choose_from_most_used'      => esc_html__('Choose most used ' . ucfirst($types_plural[$key]) . ' categories', 'cwpt'),
                            'not_found'                  => esc_html__('No ' . ucfirst($types_plural[$key]) . ' categories' . ' found', 'cwpt'),
                            'name'                       => esc_html__(ucfirst($types_plural[$key]) . ' categories', 'cwpt'),
                            'singular_name'              => esc_html__(ucfirst($name_single) . ' category', 'cwpt'),
                        ],
                        'public'               => true,
                        'show_ui'              => true,
                        'show_in_menu'         => true,
                        'show_in_nav_menus'    => true,
                        'show_tagcloud'        => true,
                        'show_in_quick_edit'   => true,
                        'show_admin_column'    => false,
                        'show_in_rest'         => true,
                        'hierarchical'         => true,
                        'query_var'            => true,
                        'sort'                 => true,
                        'rewrite_no_front'     => false,
                        'rewrite_hierarchical' => false,
                        'rewrite'              => true,
                    ];
                    register_taxonomy(ucfirst($types_plural[$key]) . ' categories', ['product'], $args);
                }
            }
        }
    }

    /**
     * Filter shop products to hide disabled types
     * 
     * @param object $q
     * @return void
     */
    public static function hide_in_shop($q)
    {
        $product_types_hidden = get_posts(array(
            'fields'         => 'ids',
            'posts_per_page' => -1,
            'post_type'      => 'custom-product-type',
            'meta_key'       => 'cwpt_show_in_shop',
            'meta_value'     => 'Hide',
        ));
        $disabled_types = [];
        foreach ($product_types_hidden as $type_id) {
            $disabled_types[] = preg_replace('/\\s+/', '_', sanitize_text_field(get_post_meta($type_id, 'cwpt_product_type_name_singular', true)));
        }
        $tax_query = $q->get('tax_query');
        $tax_query[] = array(
            'taxonomy' => 'product_type',
            'field'    => 'slug',
            'terms'    => $disabled_types,
            'operator' => 'NOT IN',
        );
        $q->set('tax_query', $tax_query);
    }
}
