<?php

/**
 * Front-end Fields Handler
 * 
 * @package cwpt
 * @since 1.0.0
 */
defined( 'ABSPATH' ) or die;
class CWPT_Front_Fields {
    /**
     * Display badge on shop loop
     * 
     * @return void
     */
    public static function display_badge() {
        if ( CWPT_Settings::get( 'badges' ) !== null && !empty( CWPT_Settings::get( 'badges' ) ) ) {
            global $product;
            $cwpt_badges = CWPT_Settings::get( 'badges' );
            if ( isset( $cwpt_badges[$product->get_type()] ) ) {
                $badge_text = $cwpt_badges[$product->get_type()]['text'];
                $badge_background = $cwpt_badges[$product->get_type()]['background'];
                $badge_color = $cwpt_badges[$product->get_type()]['color'];
                ?>
                <div class="cwpt_badge" style="position: absolute; top: 5%;  right: 5%; left: auto; z-index: 999; background-color: <?php 
                echo $badge_background;
                ?>; color: <?php 
                echo $badge_color;
                ?>;
                padding: 0 5px; border-radius: 5px;">
                    <?php 
                echo $badge_text;
                ?>
                </div>
                <?php 
            }
        }
    }

    /**
     * Display front-end fields and tabs
     * 
     * @return void
     */
    public static function render() {
        global $product;
        $product_id = $product->get_id();
        $current_hook = current_action();
        $cwpt_tabs = CWPT_Settings::get( 'custom_tab' );
        // Handle add-to-cart button for custom product types on woocommerce_single_product_summary
        if ( $current_hook === 'woocommerce_single_product_summary' && in_array( $product->get_type(), CWPT_Settings::get( 'name_ids' ) ) ) {
            wc_get_template( 'single-product/add-to-cart/simple.php' );
            // Do not return; allow fields/tabs assigned to this hook to render
        }
        $cwpt_addons = CWPT_Settings::get( 'front_addons' );
        $prefix = 'cwpt_';
        if ( $cwpt_tabs && !empty( $cwpt_tabs ) ) {
            if ( in_array( $product->get_type(), CWPT_Settings::get( 'name_ids' ) ) ) {
                if ( !empty( $cwpt_tabs[$product->get_type()]['fields'] ) ) {
                    foreach ( $cwpt_tabs as $key => $tab ) {
                        if ( isset( $tab['position'] ) && $tab['position'] == $current_hook && $key == $product->get_type() ) {
                            self::render_tabs_fields(
                                $product,
                                $cwpt_tabs,
                                $tab,
                                $key,
                                $product_id
                            );
                        }
                    }
                }
            }
        }
        if ( $cwpt_addons !== null && !empty( $cwpt_addons ) ) {
            foreach ( $cwpt_addons as $key => $addon ) {
                if ( isset( $addon['fields'] ) && !empty( $addon['fields'] ) && $key == $product->get_type() ) {
                    //Front Addons Functionality
                    if ( !empty( $cwpt_addons[$product->get_type()]['fields'] ) && $cwpt_addons[$product->get_type()]['enabled'] ) {
                        $has_buy_now = false;
                        foreach ( $cwpt_addons[$product->get_type()]['fields'] as $field ) {
                            if ( isset( $field['type'] ) && $field['type'] === 'buy_now' ) {
                                $has_buy_now = [true, ( !empty( $field['label'] ) ? $field['label'] : __( 'Buy Now', 'custom-product-type-for-woocommerce' ) )];
                                break;
                            }
                        }
                        if ( $current_hook == 'woocommerce_after_add_to_cart_button' && is_array( $has_buy_now ) && $has_buy_now[0] ) {
                            if ( $product && $product->is_purchasable() && $product->is_in_stock() ) {
                                $checkout_url = wc_get_checkout_url();
                                $direct_checkout_link = add_query_arg( array(
                                    'add-to-cart' => $product->get_id(),
                                ), $checkout_url );
                                ?>
                                <a href="<?php 
                                echo esc_url( $direct_checkout_link );
                                ?>" class="single_add_to_cart_button button alt cwpt-buy-now">
                                    <?php 
                                echo esc_html( $has_buy_now[1] );
                                ?>
                                </a>
<?php 
                            }
                        }
                        // Check Hook Placement
                        if ( $current_hook == 'woocommerce_before_add_to_cart_button' && !(is_array( $has_buy_now ) && $has_buy_now[0]) ) {
                            self::render_addons_fields(
                                $product,
                                $cwpt_addons,
                                $prefix,
                                $product_id
                            );
                        }
                    }
                }
            }
        }
    }

    /**
     * Render addons fields in front-end
     * 
     * @param object $product
     * @param array $cwpt_addons
     * @param string $prefix
     * @param int $product_id
     * @return void
     */
    private static function render_addons_fields(
        $product,
        $cwpt_addons,
        $prefix,
        $product_id
    ) {
        $fields = $cwpt_addons[$product->get_type()]['fields'];
        if ( !$cwpt_addons[$product->get_type()]['enabled'] ) {
            return;
        }
        $fields_title = $cwpt_addons[$product->get_type()]['text'];
        $cmb = new_cmb2_box( array(
            'id'           => "{$prefix}front_fields_addons",
            'title'        => ( !empty( $fields_title ) ? esc_html( $fields_title ) : __( 'Custom Fields', 'custom-product-type-for-woocommerce' ) ),
            'object_types' => array('product'),
            'classes'      => 'cwpt-field',
        ) );
        echo '<h4>' . esc_html( $fields_title ) . '</h4>';
        if ( in_array( $product->get_type(), CWPT_Settings::get( 'name_ids' ) ) ) {
            if ( !empty( $fields ) ) {
                foreach ( $fields as $field ) {
                    $type = ( isset( $field['type'] ) ? $field['type'] : 'text' );
                    $required = ( isset( $field['required'] ) && $field['required'] == 'on' ? true : false );
                    $label = ( isset( $field['label'] ) ? esc_html( $field['label'] ) : '' );
                    $description = ( isset( $field['description'] ) ? esc_html( $field['description'] ) : '' );
                    $field_id = str_replace( '-', '_', sanitize_title( $label ) );
                    $options = ( isset( $field['options'] ) ? explode( '|', $field['options'] ) : [] );
                    $options_types = [
                        'select',
                        'radio',
                        'checkbox',
                        'multicheck'
                    ];
                    $taxonomy_types = [
                        'taxonomy_radio',
                        'taxonomy_radio_inline',
                        'taxonomy_radio_hierarchical',
                        'taxonomy_select',
                        'taxonomy_multicheck',
                        'taxonomy_multicheck_inline',
                        'taxonomy_multicheck_hierarchical'
                    ];
                    if ( is_rtl() ) {
                        $space = 'margin-left';
                    } else {
                        $space = 'margin-right';
                    }
                    if ( !empty( $field['iconselect'] ) ) {
                        $icon = '<i class="' . esc_attr( $field['iconselect'] ) . '" style="' . $space . ': 10px;"></i>';
                        $label = $icon . $label;
                    }
                    $args = array(
                        'name'       => $label . (( $required ? ' <span class="required">*</span>' : '' )),
                        'desc'       => $description,
                        'id'         => ( empty( $field_id ) ? 'cwpt_field_' . rand( 1, 999 ) : $field_id ),
                        'type'       => $type,
                        'attributes' => array(
                            'required' => $required,
                        ),
                    );
                    // Handle specific field type options
                    if ( in_array( $type, $options_types ) ) {
                        $args['options'] = array_combine( $options, $options );
                        if ( $type === 'select' ) {
                            $args['show_option_none'] = false;
                        }
                    }
                    if ( $type === 'textarea' ) {
                        $args['attributes'] = array(
                            'rows' => 5,
                        );
                    }
                    if ( $type === 'number' ) {
                        $args['type'] = 'text';
                        $args['attributes']['type'] = 'number';
                        $args['attributes']['pattern'] = '\\d*';
                        // $args['attributes']['step'] = 'any';
                        // $args['attributes']['min'] = isset($field['min']) ? $field['min'] : '';
                        // $args['attributes']['max'] = isset($field['max']) ? $field['max'] : '';
                    }
                    if ( $type === 'checkbox' ) {
                        $args['default'] = 'off';
                    }
                    if ( $type === 'file' ) {
                        $args['options'] = array(
                            'url' => false,
                        );
                    }
                    $cmb->add_field( $args );
                }
            }
        }
        cmb2_metabox_form( 'cwpt_front_fields_addons', $product_id, array(
            'form_format' => '',
        ) );
    }

    /**
     * Render admin tab fields in front-end
     * 
     * @param object $product
     * @param array $cwpt_tabs
     * @param array $tab
     * @param string $key
     * @param int $product_id
     * @return void
     */
    private static function render_tabs_fields(
        $product,
        $cwpt_tabs,
        $tab,
        $key,
        $product_id
    ) {
        echo '<h2 style="font-size:1.2rem; font-weight: 700;" class="cwpt-tab-title">' . esc_html( $tab['text'] ) . '</h2>';
        foreach ( $tab['fields'] as $field_key => $field ) {
            $field_label = ( empty( $field['label'] ) ? '' : $field['label'] );
            $field_id = $product->get_type() . 'field_' . $field_key;
            $field_class = $product->get_type() . '-field-' . preg_replace( '/\\s+/', '-', trim( preg_replace( '/[^\\da-z ]/i', '', strtolower( $field_label ) ) ) );
            $field_global_class = $product->get_type() . '-field';
            $field_description = ( isset( $field['description'] ) ? $field['description'] : '' );
            $field_type = $field['type'];
            if ( !empty( $field['url'] ) ) {
                $field_url = $field['url'];
            }
            $data = get_post_meta( $product_id, $field_id );
            if ( !empty( $data[0] ) ) {
                echo '<div class="cwpt-field cwpt-product-data ' . $field_global_class . '">';
                if ( array_key_exists( 'show_front', $field ) && $field['show_front'] === 'on' ) {
                    // var_dump($field);
                    if ( is_rtl() ) {
                        $space = 'margin-left';
                    } else {
                        $space = 'margin-right';
                    }
                    if ( !empty( $field['iconselect'] ) ) {
                        $icon = '<i class="' . esc_attr( $field['iconselect'] ) . '" style="' . $space . ': 10px;"></i>';
                    } else {
                        $icon = '';
                    }
                    if ( $field_url == 'show' && $field_type == 'text' ) {
                        echo '<a class="' . $field_class . '-url' . '" href="' . esc_url( $data[0] ) . '" style=" clear: both; display: block; margin: 0.5rem 0; display: block; ">' . $icon . $field_label . '</a>';
                        echo '<span class="' . esc_attr( $field_global_class . ' ' . $field_class . '-value' ) . '" style="font-weight: 300;">' . esc_html( $data[0] ) . '</span>';
                    } else {
                        if ( $field_type !== 'buy_now' ) {
                            echo '<label class="' . $field_class . '-label' . '">' . $icon . $field_label . '</label>';
                            if ( $field_type !== 'checkbox' ) {
                                echo '<span class="' . esc_attr( $field_global_class . ' ' . $field_class . '-value' ) . '" style="font-weight: 300;">' . esc_html( $data[0] ) . '</span>';
                            }
                        }
                    }
                }
                echo "</div>";
                if ( !empty( $field_description ) ) {
                    echo '<p class="cwpt-field-description">' . $field_description . '</p>';
                }
            }
        }
    }

}
