<?php

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

class FlowDino_WC_VideoGameRatings_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_vgratings_nonce'] ) &&
            wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['flowdino_vgratings_nonce'] ) ), 'flowdino_vgratings' )
        ) {
            try {
                // Save selected attribute taxonomy
                if ( isset( $_POST['vgrating_attribute'] ) ) {
                    update_option( 'flowdino_vgrating_attribute', sanitize_text_field( wp_unslash( $_POST['vgrating_attribute'] ) ) );
                }

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

                echo '<div class="notice notice-success"><p>' . esc_html__( 'Video game rating 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 video game rating mappings: %s', 'flowdino' ), $e->getMessage() ) ) . '</p></div>';
                // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log -- Logging for debugging purposes
                error_log( 'FlowDino: Video game rating mapping save error - ' . $e->getMessage() );
            }
        }

        // Get all WooCommerce product attributes
        $all_attributes     = $this->get_all_wc_attributes();
        $selected_attribute = get_option( 'flowdino_vgrating_attribute', '' );

        // Get FlowDino video game ratings
        $flowdino_ratings = $this->get_flowdino_video_game_ratings();
        $token_missing    = empty( get_option( 'flowdino_token', '' ) );

        // Get terms for selected attribute
        $wc_terms = array();
        if ( ! empty( $selected_attribute ) && taxonomy_exists( $selected_attribute ) ) {
            $wc_terms = $this->get_terms_for_attribute( $selected_attribute );
        }

        ?>
        <div class="flowdino-tab-content">
            <h2><?php esc_html_e( 'Video Game Ratings Mapping', 'flowdino' ); ?></h2>
            <p><?php esc_html_e( 'Select the WooCommerce attribute that contains your video game ratings, then map each value to a FlowDino rating.', '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_ratings ) ): ?>
                <div class="notice notice-error">
                    <p>
                        <strong><?php esc_html_e( 'Unable to load FlowDino video game ratings.', '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_vgratings', 'flowdino_vgratings_nonce' ); ?>

                <!-- Attribute Selection -->
                <div class="card" style="margin-bottom: 20px;">
                    <h3 style="margin: 15px;"><?php esc_html_e( 'WooCommerce Attribute Selection', 'flowdino' ); ?></h3>
                    <div style="padding: 15px;">
                        <table class="form-table">
                            <tr>
                                <th scope="row"><?php esc_html_e( 'Video Game Rating 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="vgrating_attribute" id="vgrating_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 represent video game age ratings (e.g. PEGI, USK…).', 'flowdino' ); ?></p>
                                    <?php endif; ?>
                                </td>
                            </tr>
                        </table>
                    </div>
                </div>

                <!-- Mapping Table (shown only when an attribute is selected and has terms) -->
                <?php if ( ! empty( $selected_attribute ) && ! empty( $wc_terms ) ): ?>
                    <div class="card">
                        <h3 style="margin: 15px;"><?php esc_html_e( 'Ratings 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 Rating', 'flowdino' ); ?></th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <?php foreach ( $wc_terms as $term ): ?>
                                            <?php $current_mapping = get_option( 'flowdino_vgrating_mapping_' . $term['id'], '' ); ?>
                                            <tr>
                                                <td>
                                                    <strong><?php echo esc_html( $term['name'] ); ?></strong>
                                                    <?php if ( $term['count'] > 0 ): ?>
                                                        <span style="color: #666; font-size: 0.9em;">
                                                            (<?php echo esc_html( $term['count'] ); ?> <?php esc_html_e( 'products', 'flowdino' ); ?>)
                                                        </span>
                                                    <?php endif; ?>
                                                </td>
                                                <td>
                                                    <?php if ( empty( $flowdino_ratings ) ): ?>
                                                        <p style="color: #d63638; font-style: italic; font-size: 0.9em;">
                                                            <?php esc_html_e( 'Unable to retrieve FlowDino ratings. Please check your API connection.', 'flowdino' ); ?>
                                                        </p>
                                                    <?php else: ?>
                                                        <select name="flowdino_vgrating_<?php echo esc_attr( $term['id'] ); ?>" class="flowdino-vgrating-select2">
                                                            <option value=""><?php esc_html_e( '-- Select a FlowDino rating --', 'flowdino' ); ?></option>
                                                            <?php foreach ( $flowdino_ratings as $rating ): ?>
                                                                <option value="<?php echo esc_attr( $rating['id'] ); ?>"
                                                                    <?php selected( $current_mapping, $rating['id'] ); ?>>
                                                                    <?php echo esc_html( $rating['name'] ); ?>
                                                                </option>
                                                            <?php endforeach; ?>
                                                        </select>
                                                    <?php endif; ?>
                                                </td>
                                            </tr>
                                        <?php endforeach; ?>
                                    </tbody>
                                </table>
                            </div>
                        </div>
                    </div>
                <?php elseif ( ! empty( $selected_attribute ) && empty( $wc_terms ) ): ?>
                    <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 endif; ?>

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

        <?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 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 FlowDino video game ratings from API
     */
    private function get_flowdino_video_game_ratings() {
        try {
            $api_response = $this->api->get_video_game_ratings();

            if ( $api_response && isset( $api_response['member'] ) && is_array( $api_response['member'] ) ) {
                $ratings = array();

                foreach ( $api_response['member'] as $rating ) {
                    if ( isset( $rating['id'] ) && isset( $rating['libelle'] ) ) {
                        $ratings[] = array(
                            'id'   => $rating['id'],
                            'name' => $rating['libelle'],
                            'code' => isset( $rating['code'] ) ? $rating['code'] : '',
                        );
                    }
                }

                // Sort by ordervd if available, otherwise by name
                usort( $ratings, function( $a, $b ) use ( $api_response ) {
                    $ra = null;
                    $rb = null;
                    foreach ( $api_response['member'] as $r ) {
                        if ( $r['id'] == $a['id'] ) $ra = $r;
                        if ( $r['id'] == $b['id'] ) $rb = $r;
                    }
                    if ( $ra && $rb && isset( $ra['ordervd'] ) && isset( $rb['ordervd'] ) ) {
                        return $ra['ordervd'] - $rb['ordervd'];
                    }
                    return strcasecmp( $a['name'], $b['name'] );
                } );

                return $ratings;
            }

            return array();

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