<?php

if ( ! defined( 'ABSPATH' ) ) {
    exit;
}

class FlowDino_WC_Tags_Tab {

    private $api;
    private $database;

    public function __construct() {
        $this->api      = new FlowDino_WC_API();
        $this->database = new FlowDino_WC_Database();
    }

    public function render() {
        // Handle form submission
        if (
            isset( $_POST['submit'] ) &&
            isset( $_POST['flowdino_tags_nonce'] ) &&
            wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['flowdino_tags_nonce'] ) ), 'flowdino_tags' )
        ) {
            try {
                // Save source type: 'attribute' or 'shipping_class'
                if ( isset( $_POST['tag_source_type'] ) ) {
                    update_option( 'flowdino_tag_source_type', sanitize_text_field( wp_unslash( $_POST['tag_source_type'] ) ) );
                }

                // Save selected attribute taxonomy (if source = attribute)
                if ( isset( $_POST['tag_attribute'] ) ) {
                    update_option( 'flowdino_tag_attribute', sanitize_text_field( wp_unslash( $_POST['tag_attribute'] ) ) );
                }

                // Save each term/class mapping
                foreach ( $_POST as $key => $value ) {
                    $key = sanitize_key( $key );
                    if ( strpos( $key, 'flowdino_tag_' ) === 0 ) {
                        $option_name = 'flowdino_tag_mapping_' . str_replace( 'flowdino_tag_', '', $key );
                        update_option( $option_name, sanitize_text_field( wp_unslash( $value ) ) );
                    }
                }

                echo '<div class="notice notice-success"><p>' . esc_html__( 'Tag mappings saved successfully.', 'flowdino' ) . '</p></div>';
            } catch ( Exception $e ) {
                // translators: %s is the error message
                echo '<div class="notice notice-error"><p>' . esc_html( sprintf( __( 'Error saving tag mappings: %s', 'flowdino' ), $e->getMessage() ) ) . '</p></div>';
                // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log -- Logging for debugging purposes
                error_log( 'FlowDino: Tag mapping save error - ' . $e->getMessage() );
            }
        }

        $source_type        = get_option( 'flowdino_tag_source_type', 'attribute' );
        $all_attributes     = $this->get_all_wc_attributes();
        $selected_attribute = get_option( 'flowdino_tag_attribute', '' );
        $flowdino_tags      = $this->get_flowdino_tags();
        $token_missing      = empty( get_option( 'flowdino_token', '' ) );

        // Build source items based on selected source type
        $source_items = array();
        if ( 'shipping_class' === $source_type ) {
            $source_items = $this->get_shipping_classes();
        } elseif ( ! empty( $selected_attribute ) && taxonomy_exists( $selected_attribute ) ) {
            $source_items = $this->get_terms_for_attribute( $selected_attribute );
        }

        ?>
        <div class="flowdino-tab-content">
            <h2><?php esc_html_e( 'Tags Mapping', 'flowdino' ); ?></h2>
            <p><?php esc_html_e( 'Select a WooCommerce attribute or shipping classes to map each value to a FlowDino tag.', 'flowdino' ); ?></p>

            <?php if ( $token_missing ) : ?>
                <div class="notice notice-warning">
                    <p>
                        <strong><?php esc_html_e( 'FlowDino API not connected.', 'flowdino' ); ?></strong>
                        <?php esc_html_e( 'Please configure your credentials in the Settings tab before using this page.', 'flowdino' ); ?>
                        <a href="?page=flowdino-sync&tab=settings" class="button button-small" style="margin-left:10px;"><?php esc_html_e( 'Go to Settings', 'flowdino' ); ?></a>
                    </p>
                </div>
            <?php elseif ( empty( $flowdino_tags ) ) : ?>
                <div class="notice notice-error">
                    <p>
                        <strong><?php esc_html_e( 'Unable to load FlowDino tags.', 'flowdino' ); ?></strong>
                        <?php esc_html_e( 'Please check your API connection and credentials in the Settings tab.', 'flowdino' ); ?>
                        <a href="?page=flowdino-sync&tab=settings" class="button button-small" style="margin-left:10px;"><?php esc_html_e( 'Test Connection', 'flowdino' ); ?></a>
                    </p>
                </div>
            <?php endif; ?>

            <form method="post" action="">
                <?php wp_nonce_field( 'flowdino_tags', 'flowdino_tags_nonce' ); ?>

                <!-- Source Type Selection -->
                <div class="card" style="margin-bottom: 20px;">
                    <h3 style="margin: 15px;"><?php esc_html_e( 'Source Selection', 'flowdino' ); ?></h3>
                    <div style="padding: 15px;">
                        <table class="form-table">
                            <tr>
                                <th scope="row"><?php esc_html_e( 'Source Type', 'flowdino' ); ?></th>
                                <td>
                                    <label style="margin-right: 20px;">
                                        <input type="radio" name="tag_source_type" value="attribute"
                                            <?php checked( $source_type, 'attribute' ); ?> id="tag_source_attribute" />
                                        <?php esc_html_e( 'Product Attribute', 'flowdino' ); ?>
                                    </label>
                                    <label>
                                        <input type="radio" name="tag_source_type" value="shipping_class"
                                            <?php checked( $source_type, 'shipping_class' ); ?> id="tag_source_shipping" />
                                        <?php esc_html_e( 'Shipping Classes', 'flowdino' ); ?>
                                    </label>
                                    <p class="description"><?php esc_html_e( 'Choose whether to map from a product attribute or from WooCommerce shipping classes.', 'flowdino' ); ?></p>
                                </td>
                            </tr>

                            <!-- Attribute selector row -->
                            <tr id="tag_attribute_row" <?php echo ( 'attribute' !== $source_type ) ? 'style="display:none;"' : ''; ?>>
                                <th scope="row"><?php esc_html_e( 'Product Attribute', 'flowdino' ); ?></th>
                                <td>
                                    <?php if ( empty( $all_attributes ) ) : ?>
                                        <div style="background: #ffeaa7; border: 1px solid #fdcb6e; padding: 10px; border-radius: 4px;">
                                            <p style="margin: 0; color: #2d3436;">
                                                <?php esc_html_e( 'No product attributes found in WooCommerce. Create one in WooCommerce > Products > Attributes.', 'flowdino' ); ?>
                                            </p>
                                        </div>
                                    <?php else : ?>
                                        <select name="tag_attribute" id="tag_attribute" class="regular-text">
                                            <option value=""><?php esc_html_e( '-- Select a WooCommerce attribute --', 'flowdino' ); ?></option>
                                            <?php foreach ( $all_attributes as $attr ) : ?>
                                                <option value="<?php echo esc_attr( $attr['taxonomy'] ); ?>"
                                                    <?php selected( $selected_attribute, $attr['taxonomy'] ); ?>>
                                                    <?php echo esc_html( $attr['label'] ); ?> (<?php echo esc_html( $attr['taxonomy'] ); ?>)
                                                </option>
                                            <?php endforeach; ?>
                                        </select>
                                        <p class="description"><?php esc_html_e( 'Choose the attribute whose terms will be mapped to FlowDino tags.', 'flowdino' ); ?></p>
                                    <?php endif; ?>
                                </td>
                            </tr>
                        </table>
                    </div>
                </div>

                <!-- Mapping Table -->
                <?php if ( ! empty( $source_items ) ) : ?>
                    <div class="card">
                        <h3 style="margin: 15px;"><?php esc_html_e( 'Tags Mapping', 'flowdino' ); ?></h3>
                        <div style="padding: 15px;">
                            <div class="table-responsive">
                                <table class="wp-list-table widefat fixed striped">
                                    <thead>
                                        <tr>
                                            <th style="width: 40%;"><?php esc_html_e( 'WooCommerce Value', 'flowdino' ); ?></th>
                                            <th style="width: 60%;"><?php esc_html_e( 'FlowDino Tag', 'flowdino' ); ?></th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <?php foreach ( $source_items as $item ) : ?>
                                            <?php $current_mapping = get_option( 'flowdino_tag_mapping_' . $item['id'], '' ); ?>
                                            <tr>
                                                <td>
                                                    <strong><?php echo esc_html( $item['name'] ); ?></strong>
                                                    <?php if ( isset( $item['count'] ) && $item['count'] > 0 ) : ?>
                                                        <span style="color: #666; font-size: 0.9em;">
                                                            (<?php echo esc_html( $item['count'] ); ?> <?php esc_html_e( 'products', 'flowdino' ); ?>)
                                                        </span>
                                                    <?php endif; ?>
                                                </td>
                                                <td>
                                                    <?php if ( empty( $flowdino_tags ) ) : ?>
                                                        <p style="color: #d63638; font-style: italic; font-size: 0.9em;">
                                                            <?php esc_html_e( 'Unable to retrieve FlowDino tags. Please check your API connection.', 'flowdino' ); ?>
                                                        </p>
                                                    <?php else : ?>
                                                        <select name="flowdino_tag_<?php echo esc_attr( $item['id'] ); ?>" class="flowdino-tag-select2">
                                                            <option value=""><?php esc_html_e( '-- Select a FlowDino tag --', 'flowdino' ); ?></option>
                                                            <?php foreach ( $flowdino_tags as $tag ) : ?>
                                                                <option value="<?php echo esc_attr( $tag['id'] ); ?>"
                                                                    data-color="<?php echo esc_attr( isset( $tag['color'] ) ? $tag['color'] : '' ); ?>"
                                                                    <?php selected( (string) $current_mapping, (string) $tag['id'] ); ?>>
                                                                    <?php echo esc_html( $tag['name'] ); ?>
                                                                    <?php if ( ! empty( $tag['color'] ) ) : ?>
                                                                        (<?php echo esc_html( $tag['color'] ); ?>)
                                                                    <?php endif; ?>
                                                                </option>
                                                            <?php endforeach; ?>
                                                        </select>
                                                    <?php endif; ?>
                                                </td>
                                            </tr>
                                        <?php endforeach; ?>
                                    </tbody>
                                </table>
                            </div>
                        </div>
                    </div>
                <?php elseif ( 'attribute' === $source_type && ! empty( $selected_attribute ) ) : ?>
                    <div class="notice notice-info">
                        <p><?php esc_html_e( 'The selected attribute has no terms yet. Add terms in WooCommerce > Products > Attributes.', 'flowdino' ); ?></p>
                    </div>
                <?php elseif ( 'shipping_class' === $source_type ) : ?>
                    <div class="notice notice-info">
                        <p><?php esc_html_e( 'No shipping classes found. Create shipping classes in WooCommerce > Settings > Shipping > Shipping classes.', 'flowdino' ); ?></p>
                    </div>
                <?php endif; ?>

                <p class="submit">
                    <input type="submit" name="submit" class="button button-primary" value="<?php esc_html_e( 'Save Mappings', 'flowdino' ); ?>" />
                </p>
            </form>
        </div>

        <script>
        jQuery(document).ready(function($) {
            $('input[name="tag_source_type"]').on('change', function() {
                if ($(this).val() === 'attribute') {
                    $('#tag_attribute_row').show();
                } else {
                    $('#tag_attribute_row').hide();
                }
            });
        });
        </script>
        <?php
    }

    /**
     * Get all WooCommerce product attributes
     */
    private function get_all_wc_attributes() {
        $attributes    = array();
        $wc_attributes = wc_get_attribute_taxonomies();

        if ( empty( $wc_attributes ) ) {
            return $attributes;
        }

        foreach ( $wc_attributes as $attr ) {
            $taxonomy = 'pa_' . $attr->attribute_name;
            if ( taxonomy_exists( $taxonomy ) ) {
                $attributes[] = array(
                    'taxonomy' => $taxonomy,
                    'label'    => $attr->attribute_label,
                );
            }
        }

        return $attributes;
    }

    /**
     * Get terms for a given attribute taxonomy
     */
    private function get_terms_for_attribute( $taxonomy ) {
        $terms = get_terms( array(
            'taxonomy'   => $taxonomy,
            'hide_empty' => false,
            'orderby'    => 'name',
            'order'      => 'ASC',
        ) );

        if ( is_wp_error( $terms ) || empty( $terms ) ) {
            return array();
        }

        $result = array();
        foreach ( $terms as $term ) {
            $result[] = array(
                'id'    => $term->term_id,
                'name'  => $term->name,
                'count' => $term->count,
            );
        }

        return $result;
    }

    /**
     * Get WooCommerce shipping classes
     */
    private function get_shipping_classes() {
        $terms = get_terms( array(
            'taxonomy'   => 'product_shipping_class',
            'hide_empty' => false,
            'orderby'    => 'name',
            'order'      => 'ASC',
        ) );

        if ( is_wp_error( $terms ) || empty( $terms ) ) {
            return array();
        }

        $result = array();
        foreach ( $terms as $term ) {
            $result[] = array(
                'id'    => $term->term_id,
                'name'  => $term->name,
                'count' => $term->count,
            );
        }

        return $result;
    }

    /**
     * Get FlowDino tags from API
     */
    private function get_flowdino_tags() {
        try {
            $tags = $this->api->get_tags();

            if ( ! is_array( $tags ) || empty( $tags ) ) {
                return array();
            }

            $result = array();
            foreach ( $tags as $tag ) {
                if ( isset( $tag['id'] ) && isset( $tag['name'] ) ) {
                    $result[] = array(
                        'id'    => $tag['id'],
                        'name'  => $tag['name'],
                        'color' => isset( $tag['color'] ) ? $tag['color'] : '',
                    );
                }
            }

            usort( $result, function( $a, $b ) {
                return strcasecmp( $a['name'], $b['name'] );
            } );

            return $result;

        } catch ( Exception $e ) {
            // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log -- Logging for debugging purposes
            error_log( 'FlowDino: Error retrieving tags - ' . $e->getMessage() );
            return array();
        }
    }
}
