<?php

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

class Cregis_Admin {
    public function __construct() {
        add_action('admin_menu', array($this, 'add_admin_menu'));
        add_action('admin_init', array($this, 'register_settings'));
    }
    
    /**
     * Add admin menu
     */
    public function add_admin_menu() {
        add_menu_page(
            esc_html__('Cregis Payment', 'cregis-payment-for-woocommerce'),
            esc_html__('Cregis Payment', 'cregis-payment-for-woocommerce'),
            'manage_options',
            'cregis-payment-for-woocommerce',
            array($this, 'admin_page'),
            'dashicons-money',
            50
        );
    }
    
    /**
     * Register settings
     */
    public function register_settings() {
        register_setting('cregis_payment_settings', 'cregis_payment_settings', array($this, 'validate_settings'));

        add_settings_section(
            'cregis_api_settings',
            esc_html__('API Settings', 'cregis-payment-for-woocommerce'),
            array($this, 'api_settings_section'),
            'cregis-payment-for-woocommerce'
        );

        add_settings_field(
            'api_url',
            esc_html__('Base URL', 'cregis-payment-for-woocommerce'),
            array($this, 'api_url_field'),
            'cregis-payment-for-woocommerce',
            'cregis_api_settings'
        );

        add_settings_field(
            'project_id',
            esc_html__('Project ID', 'cregis-payment-for-woocommerce'),
            array($this, 'project_id_field'),
            'cregis-payment-for-woocommerce',
            'cregis_api_settings'
        );

        add_settings_field(
            'secret_key',
            esc_html__('API Key', 'cregis-payment-for-woocommerce'),
            array($this, 'secret_key_field'),
            'cregis-payment-for-woocommerce',
            'cregis_api_settings'
        );

        add_settings_field(
            'server_ip',
            esc_html__('Server IP Address', 'cregis-payment-for-woocommerce'),
            array($this, 'server_ip_field'),
            'cregis-payment-for-woocommerce',
            'cregis_api_settings'
        );

        add_settings_section(
            'cregis_payment_settings',
            esc_html__('Payment Settings', 'cregis-payment-for-woocommerce'),
            array($this, 'payment_settings_section'),
            'cregis-payment-for-woocommerce'
        );

        add_settings_field(
            'accept_all_underpaid',
            esc_html__('Accept All Underpaid', 'cregis-payment-for-woocommerce'),
            array($this, 'accept_all_underpaid_field'),
            'cregis-payment-for-woocommerce',
            'cregis_payment_settings'
        );

        add_settings_field(
            'underpaid_tolerance',
            esc_html__('Underpaid Tolerance (%)', 'cregis-payment-for-woocommerce'),
            array($this, 'underpaid_tolerance_field'),
            'cregis-payment-for-woocommerce',
            'cregis_payment_settings'
        );

        add_settings_field(
            'accept_all_overpaid',
            esc_html__('Accept All Overpaid', 'cregis-payment-for-woocommerce'),
            array($this, 'accept_all_overpaid_field'),
            'cregis-payment-for-woocommerce',
            'cregis_payment_settings'
        );

        add_settings_field(
            'overpaid_tolerance',
            esc_html__('Overpaid Tolerance (%)', 'cregis-payment-for-woocommerce'),
            array($this, 'overpaid_tolerance_field'),
            'cregis-payment-for-woocommerce',
            'cregis_payment_settings'
        );

        add_settings_field(
            'payment_valid_time',
            esc_html__('Payment Valid Time (minutes)', 'cregis-payment-for-woocommerce'),
            array($this, 'payment_valid_time_field'),
            'cregis-payment-for-woocommerce',
            'cregis_payment_settings'
        );
    }
    
    /**
     * Validate settings
     */
    public function validate_settings($settings) {
        if (isset($settings['api_url'])) {
            $settings['api_url'] = esc_url_raw($settings['api_url']);
        }
        
        if (isset($settings['project_id'])) {
            $settings['project_id'] = sanitize_text_field($settings['project_id']);
        }
        
        if (isset($settings['secret_key'])) {
            $settings['secret_key'] = sanitize_text_field($settings['secret_key']);
        }
        
        if (isset($settings['payment_valid_time'])) {
            $settings['payment_valid_time'] = intval($settings['payment_valid_time']);
            if ($settings['payment_valid_time'] < 1) {
                $settings['payment_valid_time'] = 60;
            }
        }
        
        if (isset($settings['underpaid_tolerance'])) {
            $settings['underpaid_tolerance'] = floatval($settings['underpaid_tolerance']);
            if ($settings['underpaid_tolerance'] < 0 || $settings['underpaid_tolerance'] > 100) {
                $settings['underpaid_tolerance'] = 0;
            }
        }
        
        if (isset($settings['overpaid_tolerance'])) {
            $settings['overpaid_tolerance'] = floatval($settings['overpaid_tolerance']);
            if ($settings['overpaid_tolerance'] < 0 || $settings['overpaid_tolerance'] > 100) {
                $settings['overpaid_tolerance'] = 0;
            }
        }

        if (isset($settings['accept_all_underpaid']) && 'yes' === $settings['accept_all_underpaid']) {
            $settings['accept_all_underpaid'] = 'yes';
        } else {
            $settings['accept_all_underpaid'] = 'no';
        }

        if (isset($settings['accept_all_overpaid']) && 'yes' === $settings['accept_all_overpaid']) {
            $settings['accept_all_overpaid'] = 'yes';
        } else {
            $settings['accept_all_overpaid'] = 'no';
        }

        return $settings;
    }
    
    /**
     * API settings section
     */
    public function api_settings_section() {
        echo '<p>' . esc_html__('Enter your Cregis API credentials below', 'cregis-payment-for-woocommerce') . '</p>';
    }
    
    /**
     * Project ID field
     */
    public function project_id_field() {
        $settings = get_option('cregis_payment_settings', array());
        $project_id = isset($settings['project_id']) ? $settings['project_id'] : '';
        echo '<input type="text" name="cregis_payment_settings[project_id]" value="' . esc_attr($project_id) . '" class="regular-text" />';
    }
    
    /**
     * Secret Key field
     */
    public function secret_key_field() {
        $settings = get_option('cregis_payment_settings', array());
        $secret_key = isset($settings['secret_key']) ? $settings['secret_key'] : '';
        echo '<input type="text" name="cregis_payment_settings[secret_key]" value="' . esc_attr($secret_key) . '" class="regular-text" />';
    }

    /**
     * API URL field
     */
    public function api_url_field() {
        $settings = get_option('cregis_payment_settings', array());
        $api_url = isset($settings['api_url']) ? $settings['api_url'] : 'https://api.cregis.com';
        echo '<input type="text" name="cregis_payment_settings[api_url]" value="' . esc_attr($api_url) . '" class="regular-text" />';
    }

    /**
     * Server IP field
     */
    public function server_ip_field() {
        $ip_info = $this->get_server_ip();
        $ipv4 = $ip_info['ipv4'];
        $ipv6 = $ip_info['ipv6'];
        ?>
        <div style="margin-bottom: 15px;">
            <label style="display: block; margin-bottom: 5px; font-weight: 600;">
                <?php esc_html_e('IPv4 Address:', 'cregis-payment-for-woocommerce'); ?>
            </label>
            <div style="display: flex; align-items: center; gap: 10px;">
                <input type="text" id="cregis_server_ipv4" value="<?php echo esc_attr($ipv4); ?>" class="regular-text" readonly style="background-color: #f0f0f1;" />
                <button type="button" class="button" onclick="cregisCopyIP('cregis_server_ipv4')"><?php esc_html_e('Copy', 'cregis-payment-for-woocommerce'); ?></button>
            </div>
        </div>
        
        <div style="margin-bottom: 15px;">
            <label style="display: block; margin-bottom: 5px; font-weight: 600;">
                <?php esc_html_e('IPv6 Address:', 'cregis-payment-for-woocommerce'); ?>
            </label>
            <div style="display: flex; align-items: center; gap: 10px;">
                <input type="text" id="cregis_server_ipv6" value="<?php echo esc_attr($ipv6); ?>" class="regular-text" readonly style="background-color: #f0f0f1;" />
                <button type="button" class="button" onclick="cregisCopyIP('cregis_server_ipv6')"><?php esc_html_e('Copy', 'cregis-payment-for-woocommerce'); ?></button>
            </div>
        </div>
        
        <div style="background-color: #fff3cd; border: 1px solid #ffc107; border-radius: 4px; padding: 12px; margin-top: 15px; max-width: 600px;">
            <p style="margin: 0; color: #856404; font-size: 13px;">
                <strong><?php esc_html_e('Important:', 'cregis-payment-for-woocommerce'); ?></strong>
                <?php esc_html_e('Add these IP addresses to your Cregis portal IP whitelist. If you\'re unsure which IP to add or how to configure the whitelist, please contact the Cregis support team for assistance.', 'cregis-payment-for-woocommerce'); ?>
            </p>
        </div>
        
        <script>
        function cregisCopyIP(fieldId) {
            var ipField = document.getElementById(fieldId);
            ipField.select();
            ipField.setSelectionRange(0, 99999);
            
            try {
                document.execCommand('copy');
                var copyBtn = event.target;
                var originalText = copyBtn.textContent;
                copyBtn.textContent = '<?php echo esc_js(__('Copied!', 'cregis-payment-for-woocommerce')); ?>';
                copyBtn.style.backgroundColor = '#46b450';
                copyBtn.style.color = '#fff';
                
                setTimeout(function() {
                    copyBtn.textContent = originalText;
                    copyBtn.style.backgroundColor = '';
                    copyBtn.style.color = '';
                }, 2000);
            } catch (err) {
                alert('<?php echo esc_js(__('Failed to copy. Please copy manually.', 'cregis-payment-for-woocommerce')); ?>');
            }
        }
        </script>
        <?php
    }

    /**
     * Get server IP addresses (both IPv4 and IPv6)
     */
    private function get_server_ip() {
        $result = array(
            'ipv4' => '',
            'ipv6' => ''
        );
        
        // Get IPv4 address
        $response = wp_remote_get('https://api.ipify.org?format=json', array('timeout' => 5));
        if (!is_wp_error($response)) {
            $body = wp_remote_retrieve_body($response);
            $data = json_decode($body, true);
            if (isset($data['ip']) && filter_var($data['ip'], FILTER_VALIDATE_IP, FILTER_FLAG_IPV4)) {
                $result['ipv4'] = $data['ip'];
            }
        }
        
        // Get IPv6 address
        $response = wp_remote_get('https://api64.ipify.org?format=json', array('timeout' => 5));
        if (!is_wp_error($response)) {
            $body = wp_remote_retrieve_body($response);
            $data = json_decode($body, true);
            if (isset($data['ip']) && filter_var($data['ip'], FILTER_VALIDATE_IP, FILTER_FLAG_IPV6)) {
                $result['ipv6'] = $data['ip'];
            }
        }
        
        // Fallback for IPv4
        if (empty($result['ipv4']) && isset($_SERVER['SERVER_ADDR'])) {
            $server_addr = $_SERVER['SERVER_ADDR'];
            if (filter_var($server_addr, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4)) {
                $result['ipv4'] = $server_addr;
            }
        }
        
        // Set default messages if not detected
        if (empty($result['ipv4'])) {
            $result['ipv4'] = __('Unable to detect', 'cregis-payment-for-woocommerce');
        }
        if (empty($result['ipv6'])) {
            $result['ipv6'] = __('Not available or not detected', 'cregis-payment-for-woocommerce');
        }
        
        return $result;
    }

    /**
     * Payment settings section
     */
    public function payment_settings_section() {
        echo '<p>' . esc_html__('Configure payment settings', 'cregis-payment-for-woocommerce') . '</p>';
    }
    
    /**
     * Accept all underpaid field
     */
    public function accept_all_underpaid_field() {
        $settings = get_option('cregis_payment_settings', array());
        $accept_all_underpaid = isset($settings['accept_all_underpaid']) ? $settings['accept_all_underpaid'] : 'no';
        echo '<input type="checkbox" name="cregis_payment_settings[accept_all_underpaid]" id="cregis_accept_all_underpaid" value="yes" ' . checked('yes', $accept_all_underpaid, false) . ' />';
        echo '<label for="cregis_accept_all_underpaid"> ' . esc_html__('Accept all underpayments regardless of amount', 'cregis-payment-for-woocommerce') . '</label>';
    }

    /**
     * Underpaid tolerance field
     */
    public function underpaid_tolerance_field() {
        $settings = get_option('cregis_payment_settings', array());
        $underpaid_tolerance = isset($settings['underpaid_tolerance']) ? $settings['underpaid_tolerance'] : 0;
        $accept_all_underpaid = isset($settings['accept_all_underpaid']) ? $settings['accept_all_underpaid'] : 'no';
        $disabled = ($accept_all_underpaid === 'yes') ? 'disabled' : '';
        echo '<input type="number" name="cregis_payment_settings[underpaid_tolerance]" id="cregis_underpaid_tolerance" value="' . esc_attr($underpaid_tolerance) . '" class="small-text" min="0" max="100" step="0.1" ' . $disabled . ' />';
        echo '<p class="description">' . esc_html__('Maximum percentage of underpayment allowed', 'cregis-payment-for-woocommerce') . '</p>';
    }

    /**
     * Accept all overpaid field
     */
    public function accept_all_overpaid_field() {
        $settings = get_option('cregis_payment_settings', array());
        $accept_all_overpaid = isset($settings['accept_all_overpaid']) ? $settings['accept_all_overpaid'] : 'no';
        echo '<input type="checkbox" name="cregis_payment_settings[accept_all_overpaid]" id="cregis_accept_all_overpaid" value="yes" ' . checked('yes', $accept_all_overpaid, false) . ' />';
        echo '<label for="cregis_accept_all_overpaid"> ' . esc_html__('Accept all overpayments regardless of amount', 'cregis-payment-for-woocommerce') . '</label>';
    }

    /**
     * Overpaid tolerance field
     */
    public function overpaid_tolerance_field() {
        $settings = get_option('cregis_payment_settings', array());
        $overpaid_tolerance = isset($settings['overpaid_tolerance']) ? $settings['overpaid_tolerance'] : 0;
        $accept_all_overpaid = isset($settings['accept_all_overpaid']) ? $settings['accept_all_overpaid'] : 'no';
        $disabled = ($accept_all_overpaid === 'yes') ? 'disabled' : '';
        echo '<input type="number" name="cregis_payment_settings[overpaid_tolerance]" id="cregis_overpaid_tolerance" value="' . esc_attr($overpaid_tolerance) . '" class="small-text" min="0" max="100" step="0.1" ' . $disabled . ' />';
        echo '<p class="description">' . esc_html__('Maximum percentage of overpayment allowed', 'cregis-payment-for-woocommerce') . '</p>';
    }
    
    /**
     * Payment valid time field
     */
    public function payment_valid_time_field() {
        $settings = get_option('cregis_payment_settings', array());
        $payment_valid_time = isset($settings['payment_valid_time']) ? $settings['payment_valid_time'] : 60;
        
        echo '<input type="number" name="cregis_payment_settings[payment_valid_time]" value="' . esc_attr($payment_valid_time) . '" class="small-text" min="1" max="1440" />';
        echo '<p class="description">' . esc_html__('Payment valid time in minutes. Default is 60 minutes (1 hour). Maximum is 1440 minutes (24 hours).', 'cregis-payment-for-woocommerce') . '</p>';
    }

    /**
     * Admin page
     */
    public function admin_page() {
        if (!current_user_can('manage_options')) {
            return;
        }
        
        if (isset($_GET['settings-updated'])) {
            add_settings_error('cregis_payment_messages', 'cregis_payment_message', esc_html__('Settings saved', 'cregis-payment-for-woocommerce'), 'updated');
        }
        
        settings_errors('cregis_payment_messages');
        
        echo '<div class="wrap">';
        echo '<h1>' . esc_html__('Cregis Payment Settings', 'cregis-payment-for-woocommerce') . '</h1>';
        echo '<form action="options.php" method="post">';
        settings_fields('cregis_payment_settings');
        do_settings_sections('cregis-payment-for-woocommerce');
        submit_button();
        echo '</form>';
        echo '</div>';
        
        // Add JavaScript for checkbox/tolerance field interaction
        ?>
        <script type="text/javascript">
        jQuery(document).ready(function($) {
            // Handle Accept All Underpaid checkbox
            $('#cregis_accept_all_underpaid').on('change', function() {
                if ($(this).is(':checked')) {
                    $('#cregis_underpaid_tolerance').prop('disabled', true);
                } else {
                    $('#cregis_underpaid_tolerance').prop('disabled', false);
                }
            });
            
            // Handle Accept All Overpaid checkbox
            $('#cregis_accept_all_overpaid').on('change', function() {
                if ($(this).is(':checked')) {
                    $('#cregis_overpaid_tolerance').prop('disabled', true);
                } else {
                    $('#cregis_overpaid_tolerance').prop('disabled', false);
                }
            });
            
            // Initialize on page load
            if ($('#cregis_accept_all_underpaid').is(':checked')) {
                $('#cregis_underpaid_tolerance').prop('disabled', true);
            }
            if ($('#cregis_accept_all_overpaid').is(':checked')) {
                $('#cregis_overpaid_tolerance').prop('disabled', true);
            }
        });
        </script>
        <?php
    }
}
