<?php

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

/**
 * Settings Tab for FlowDino
 */
class FlowDino_WC_Settings_Tab {
    
    /**
     * Constructor
     */
    public function __construct() {
        // Constructor can be used for any initialization if needed
    }
    
    /**
     * Render the settings tab
     */
    public function render() {
        // Handle form submission
        if (isset($_POST['save_settings']) && isset($_POST['flowdino_settings_nonce']) && wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['flowdino_settings_nonce'])), 'flowdino_settings')) {
            $this->save_settings();
        }
        
        // Handle disconnect action
        if (isset($_POST['disconnect_flowdino']) && isset($_POST['flowdino_settings_nonce']) && wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['flowdino_settings_nonce'])), 'flowdino_settings')) {
            $this->handle_disconnect();
        }
        
        // Check connection status
        $connection_status = $this->check_connection_status();
        
        ?>
        <div class="flowdino-tab-content">
            <h2><?php esc_html_e('FlowDino Settings & Connection', 'flowdino'); ?></h2>
            <p><?php esc_html_e('Configure your FlowDino API credentials and connection settings to enable product synchronization.', 'flowdino'); ?></p>
            
            <div class="notice notice-info" style="margin-bottom: 20px;">
                <p>
                    <?php esc_html_e('Vous n\'avez pas encore de compte FlowDino ?', 'flowdino'); ?>
                    <a href="https://www.flowdino.com/register" target="_blank" class="button button-primary" style="margin-left: 10px;">
                        <?php esc_html_e('S\'inscrire sur FlowDino', 'flowdino'); ?>
                    </a>
                </p>
            </div>
            
            <?php $this->render_connection_status($connection_status); ?>
            
            <form method="post" action="">
            <?php wp_nonce_field('flowdino_settings', 'flowdino_settings_nonce'); ?>
            
            <table class="form-table">
                <tr>
                    <th scope="row"><?php esc_html_e('Email', 'flowdino'); ?></th>
                    <td>
                        <input type="email" name="flowdino_email" value="<?php echo esc_attr(get_option('flowdino_email')); ?>" class="regular-text" />
                        <p class="description"><?php esc_html_e('Your FlowDino account email', 'flowdino'); ?></p>
                    </td>
                </tr>
                <tr>
                    <th scope="row"><?php esc_html_e('Password', 'flowdino'); ?></th>
                    <td>
                        <input type="password" name="flowdino_password" value="<?php echo esc_attr(get_option('flowdino_password')); ?>" class="regular-text" />
                        <p class="description"><?php esc_html_e('Your FlowDino account password', 'flowdino'); ?></p>
                    </td>
                </tr>
            </table>
            
            <p class="submit">
                <input type="submit" name="save_settings" class="button-primary" value="<?php esc_html_e('Save Settings', 'flowdino'); ?>" />
                <button type="button" id="test-connection" class="button"><?php esc_html_e('Connexion', 'flowdino'); ?></button>
                <?php if (!$connection_status['connected']): ?>
                    <button type="button" id="force-reconnect" class="button" style="background: #27ae60; color: white; border-color: #229954;">🔄 Forcer Reconnexion</button>
                <?php endif; ?>
                <?php if ($connection_status['connected']): ?>
                    <input type="submit" name="disconnect_flowdino" class="button button-secondary" value="<?php esc_html_e('Déconnexion', 'flowdino'); ?>" 
                           onclick="confirmDisconnect(event)" />
                    <a href="https://www.flowdino.com/register" target="_blank" class="button button-primary" style="margin-left: 10px;">
                        <?php esc_html_e('S\'inscrire sur FlowDino', 'flowdino'); ?>
                    </a>
                <?php endif; ?>
            </p>
        </form>
        
        <div id="connection-test-result" style="margin-top: 20px;"></div>
        </div>
        <?php
    }
    
    /**
     * Check connection status to FlowDino
     */
    private function check_connection_status() {
        $status = array(
            'connected' => false,
            'message' => '',
            'last_check' => '',
            'api_url' => get_option('flowdino_api_url', 'https://www.flowdino.com'),
            'email' => get_option('flowdino_email', '')
        );
        
        // Check if we have credentials
        if (empty($status['email']) || empty(get_option('flowdino_password'))) {
            $status['message'] = esc_html(__('No credentials configured', 'flowdino'));
            return $status;
        }
        
        // Try to test connection
        try {
            if (class_exists('FlowDino_WC_API')) {
                $api = new FlowDino_WC_API();
                $token = $api->get_token();
                
                if (!empty($token)) {
                    $status['connected'] = true;
                    $status['message'] = esc_html(__('Connected to FlowDino', 'flowdino'));
                    $status['last_check'] = current_time('mysql');
                } else {
                    $status['message'] = esc_html(__('Unable to authenticate', 'flowdino'));
                }
            } else {
                // translators: This message is shown when the API class is not found
                $status['message'] = esc_html(__('FlowDino API class not found', 'flowdino'));
            }
        } catch (Exception $e) {
            // translators: %s is the error message
            $status['message'] = sprintf(esc_html(__('Connection error: %s', 'flowdino')), $e->getMessage());
        }
        
        return $status;
    }
    
    /**
     * Render connection status display
     */
    private function render_connection_status($status) {
        // Ajout du débogage détaillé
        $debug_info = $this->get_debug_info();
        
        ?>
        <div class="flowdino-connection-status" style="margin-bottom: 20px;">
            <h3><?php esc_html_e('Connection Status', 'flowdino'); ?></h3>
            
            <?php if ($status['connected']): ?>
                <div class="notice notice-success">
                    <p>
                        <span class="dashicons dashicons-yes" style="color: #46b450;"></span>
                        <strong><?php esc_html_e('Connected to FlowDino', 'flowdino'); ?></strong>
                    </p>
                    <p>
                        <strong><?php esc_html_e('API URL:', 'flowdino'); ?></strong> <?php echo esc_html($status['api_url']); ?><br>
                        <strong><?php esc_html_e('Account:', 'flowdino'); ?></strong> <?php echo esc_html($status['email']); ?><br>
                        <?php if ($status['last_check']): ?>
                            <strong><?php esc_html_e('Last check:', 'flowdino'); ?></strong> 
                            <?php echo esc_html(date_i18n(get_option('date_format') . ' ' . get_option('time_format'), strtotime($status['last_check']))); ?>
                        <?php endif; ?>
                    </p>
                </div>
            <?php else: ?>
                <div class="notice notice-warning">
                    <p>
                        <span class="dashicons dashicons-warning" style="color: #ffb900;"></span>
                        <strong><?php esc_html_e('Not connected to FlowDino', 'flowdino'); ?></strong>
                    </p>
                    <p><?php echo esc_html($status['message']); ?></p>
                    <?php if (!empty($status['api_url']) || !empty($status['email'])): ?>
                        <p>
                            <?php if (!empty($status['api_url'])): ?>
                                <strong><?php esc_html_e('API URL:', 'flowdino'); ?></strong> <?php echo esc_html($status['api_url']); ?><br>
                            <?php endif; ?>
                            <?php if (!empty($status['email'])): ?>
                                <strong><?php esc_html_e('Account:', 'flowdino'); ?></strong> <?php echo esc_html($status['email']); ?>
                            <?php endif; ?>
                        </p>
                    <?php endif; ?>
                </div>
            <?php endif; ?>
        </div>
        <?php
    }
    
    /**
     * Handle disconnect action
     */
    private function handle_disconnect() {
        // Clear stored tokens or connection data if any
        delete_option('flowdino_api_token');
        delete_transient('flowdino_api_token');
        
        // Show success message
        add_action('admin_notices', function() {
            echo '<div class="notice notice-success is-dismissible">';
            echo '<p>' . esc_html(__('Successfully disconnected from FlowDino.', 'flowdino')) . '</p>';
            echo '</div>';
        });
    }
    
    /**
     * Save settings
     */
    private function save_settings() {
        // Validate and sanitize input data
        // phpcs:ignore WordPress.Security.NonceVerification.Missing -- Nonce verification handled in calling method
        $email = isset($_POST['flowdino_email']) ? sanitize_email(wp_unslash($_POST['flowdino_email'])) : '';
        // phpcs:ignore WordPress.Security.NonceVerification.Missing -- Nonce verification handled in calling method
        $password = isset($_POST['flowdino_password']) ? sanitize_text_field(wp_unslash($_POST['flowdino_password'])) : '';
        
        // Save options
        update_option('flowdino_email', $email);
        update_option('flowdino_password', $password);
        
        // Show success message
        add_action('admin_notices', function() {
            echo '<div class="notice notice-success is-dismissible">';
            echo '<p>' . esc_html(__('Settings saved successfully!', 'flowdino')) . '</p>';
            echo '</div>';
        });
    }
    
    /**
     * Collecte des informations de débogage détaillées
     */
    private function get_debug_info() {
        $debug = array();
        
        // Informations système
        $debug['system'] = array(
            'php_version' => PHP_VERSION,
            'wp_version' => get_bloginfo('version'),
            'woocommerce_active' => class_exists('WooCommerce'),
            'curl_available' => function_exists('curl_init'),
            'ssl_support' => extension_loaded('openssl'),
            'json_support' => function_exists('json_encode'),
            'server_time' => current_time('mysql'),
            'timezone' => wp_timezone_string()
        );
        
        // Configuration FlowDino
        $debug['config'] = array(
            'api_url' => get_option('flowdino_api_url', 'https://www.flowdino.com'),
            'email' => get_option('flowdino_email', ''),
            'has_password' => !empty(get_option('flowdino_password', '')),
            'password_length' => strlen(get_option('flowdino_password', '')),
            'has_token' => !empty(get_option('flowdino_token', '')),
            'token_preview' => substr(get_option('flowdino_token', ''), 0, 20),
            'token_last_refresh' => get_option('flowdino_token_last_refresh', 0)
        );
        
        // Test de connectivité
        $api_url = get_option('flowdino_api_url', 'https://www.flowdino.com');
        $debug['connectivity'] = $this->test_connectivity($api_url);
        
        // Test API si on a les identifiants
        $email = get_option('flowdino_email', '');
        $password = get_option('flowdino_password', '');
        if (!empty($email) && !empty($password)) {
            $debug['api_test'] = $this->test_api_connection($api_url, $email, $password);
        }
        
        return $debug;
    }
    
    /**
     * Affiche les informations de débogage
     */
    private function render_debug_info($debug) {
        echo "<strong>🖥️ SYSTÈME:</strong><br>";
        echo "PHP: " . esc_html($debug['system']['php_version']) . " | ";
        echo "WP: " . esc_html($debug['system']['wp_version']) . " | ";
        echo "WooCommerce: " . ($debug['system']['woocommerce_active'] ? '✅' : '❌') . " | ";
        echo "CURL: " . ($debug['system']['curl_available'] ? '✅' : '❌') . " | ";
        echo "SSL: " . ($debug['system']['ssl_support'] ? '✅' : '❌') . "<br><br>";
        
        echo "<strong>⚙️ CONFIGURATION:</strong><br>";
        echo "API URL: " . esc_html($debug['config']['api_url']) . "<br>";
        echo "Email: " . (!empty($debug['config']['email']) ? '✅ ' . esc_html($debug['config']['email']) : '❌ Non configuré') . "<br>";
        echo "Password: " . ($debug['config']['has_password'] ? '✅ Configuré (' . esc_html($debug['config']['password_length']) . ' chars)' : '❌ Non configuré') . "<br>";
        echo "Token: " . ($debug['config']['has_token'] ? '✅ ' . esc_html($debug['config']['token_preview']) . '...' : '❌ Aucun') . "<br>";
        if ($debug['config']['token_last_refresh']) {
            echo "Dernier refresh: " . esc_html(gmdate('Y-m-d H:i:s', $debug['config']['token_last_refresh'])) . "<br>";
        }
        echo "<br>";
        
        echo "<strong>🌐 CONNECTIVITÉ:</strong><br>";
        if (isset($debug['connectivity'])) {
            echo "DNS: " . ($debug['connectivity']['dns_resolved'] ? '✅ ' . esc_html($debug['connectivity']['ip']) : '❌ Échec') . "<br>";
            echo "HTTP: " . ($debug['connectivity']['http_accessible'] ? '✅ Accessible' : '❌ Inaccessible') . "<br>";
            if (isset($debug['connectivity']['http_status'])) {
                echo "Status: " . esc_html($debug['connectivity']['http_status']) . "<br>";
            }
        }
        echo "<br>";
        
        if (isset($debug['api_test'])) {
            echo "<strong>🔐 TEST API:</strong><br>";
            echo "Login: " . ($debug['api_test']['login_success'] ? '✅ Réussi' : '❌ Échec') . "<br>";
            echo "Code: " . esc_html($debug['api_test']['login_code']) . "<br>";
            if (!$debug['api_test']['login_success']) {
                echo "Erreur: " . esc_html($debug['api_test']['login_message']) . "<br>";
            }
            if (isset($debug['api_test']['categories_test'])) {
                echo "Categories: " . ($debug['api_test']['categories_test']['success'] ? '✅ OK' : '❌ Échec') . "<br>";
                echo "Code: " . esc_html($debug['api_test']['categories_test']['code']) . "<br>";
            }
        }
    }
    
    /**
     * Test la connectivité réseau vers FlowDino
     */
    private function test_connectivity($api_url) {
        $result = array();
        
        // Test DNS
        $host = wp_parse_url($api_url, PHP_URL_HOST);
        $ip = gethostbyname($host);
        $result['dns_resolved'] = ($ip !== $host);
        if ($result['dns_resolved']) {
            $result['ip'] = $ip;
        }
        
        // Test HTTP basique
        $response = wp_remote_get($api_url, array('timeout' => 10, 'sslverify' => false));
        if (!is_wp_error($response)) {
            $result['http_accessible'] = true;
            $result['http_status'] = wp_remote_retrieve_response_code($response);
        } else {
            $result['http_accessible'] = false;
            $result['http_error'] = $response->get_error_message();
        }
        
        return $result;
    }
    
    /**
     * Test la connexion API FlowDino
     */
    private function test_api_connection($api_url, $email, $password) {
        $result = array();
        
        // Test de login
        $response = wp_remote_post($api_url . '/api/login_check', array(
            'headers' => array('Content-Type' => 'application/json'),
            'body' => json_encode(array('email' => $email, 'password' => $password)),
            'timeout' => 30,
            'sslverify' => false
        ));
        
        if (is_wp_error($response)) {
            $result['login_success'] = false;
            $result['login_code'] = 0;
            $result['login_message'] = $response->get_error_message();
        } else {
            $code = wp_remote_retrieve_response_code($response);
            $body = wp_remote_retrieve_body($response);
            $data = json_decode($body, true);
            
            $result['login_code'] = $code;
            $result['login_success'] = ($code === 200 && isset($data['token']));
            
            if ($result['login_success']) {
                $token = $data['token'];
                $result['token_received'] = substr($token, 0, 20) . '...';
                
                // Test endpoint categories
                $cat_response = wp_remote_get($api_url . '/api/categories/tree', array(
                    'headers' => array(
                        'Authorization' => 'Bearer ' . $token,
                        'Content-Type' => 'application/json'
                    ),
                    'timeout' => 30,
                    'sslverify' => false
                ));
                
                if (!is_wp_error($cat_response)) {
                    $cat_code = wp_remote_retrieve_response_code($cat_response);
                    $result['categories_test'] = array(
                        'success' => ($cat_code === 200),
                        'code' => $cat_code
                    );
                }
            } else {
                $result['login_message'] = isset($data['message']) ? $data['message'] : 'Unknown error';
            }
        }
        
        return $result;
    }
}
