<?php

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

class AIEO_DMM_Social_Login extends AIEO_DMM_Module_Base {

    public function get_id()       { return 'social_login'; }
    public function get_label()    { return __('Social Login', 'ai-eshop-optimizer'); }
    public function get_priority() { return 60; }
    public function get_group()    { return 'checkout_handling'; }

    public function __construct() {
        $this->load_services();
    }

    private function load_services() {
        $base = AIEO_DIR . 'includes/social-login/';

        foreach (array(
            'class-aieo-sso-buttons-data.php',
            'class-aieo-sso-state.php',
            'class-aieo-sso-provider-base.php',
            'class-aieo-sso-account-linker.php',
            'class-aieo-sso-rest.php',
            'class-aieo-sso-migrator.php',
        ) as $f) {
            $path = $base . $f;
            if (file_exists($path)) { require_once $path; }
        }

        
        $providers_dir = $base . 'providers/';
        if (is_dir($providers_dir)) {
            foreach (glob($providers_dir . 'class-aieo-sso-provider-*.php') as $provider_path) {
                require_once $provider_path;
            }
        }

        if (class_exists('AIEO_SSO_Rest')) { AIEO_SSO_Rest::register(); }
    }

    public function register_hooks() {
        add_action('wp_ajax_aieo_sso_save_settings',   array($this, 'ajax_save_settings'));
        add_action('wp_ajax_aieo_sso_migrate_audit',   array($this, 'ajax_migrate_audit'));
        add_action('wp_ajax_aieo_sso_migrate_settings',array($this, 'ajax_migrate_settings'));
        add_action('wp_ajax_aieo_sso_migrate_users',   array($this, 'ajax_migrate_users'));
    }

    public function render_subtab() {
        $section  = isset($_GET['sso_section']) ? sanitize_key((string) $_GET['sso_section']) : 'settings';
        if (!in_array($section, array('settings', 'migrator'), true)) { $section = 'settings'; }
        $base_url = admin_url('admin.php?page=' . AIEO_DMM::MENU_SLUG . '&dmm_tab=social_login');

        echo '<div class="aieo-dmm-section">';
        echo '<h2>' . esc_html__('Social Login', 'ai-eshop-optimizer') . '</h2>';
        echo '<p class="description">' . esc_html__('Sign in with Google, Facebook, LinkedIn, X.com, Apple, GitHub or Microsoft. Surfaces buttons on the login form, register form, classic + block checkout, my-account, and the footer newsletter pattern. Replaces the SkyVerge `woocommerce-social-login` plugin.', 'ai-eshop-optimizer') . '</p>';

        echo '<div class="nav-tab-wrapper" style="margin-bottom:14px;">';
        foreach (array(
            'settings' => __('Settings', 'ai-eshop-optimizer'),
            'migrator' => __('Migrator', 'ai-eshop-optimizer'),
        ) as $slug => $label) {
            $active = $section === $slug ? ' nav-tab-active' : '';
            echo '<a href="' . esc_url($base_url . '&sso_section=' . $slug) . '" class="nav-tab' . $active . '">' . esc_html($label) . '</a>'; 
        }
        echo '</div>';

        switch ($section) {
            case 'settings': $this->render_settings(); break;
            case 'migrator': $this->render_migrator(); break;
        }

        echo '</div>';
    }

    private function render_settings() {
        $settings = AIEO_SSO_Buttons_Data::get_settings();
        $providers_meta = array(
            'google'    => __('Google',    'ai-eshop-optimizer'),
            'facebook'  => __('Facebook',  'ai-eshop-optimizer'),
            'linkedin'  => __('LinkedIn',  'ai-eshop-optimizer'),
            'twitter'   => __('X.com',     'ai-eshop-optimizer'),
            'apple'     => __('Apple',     'ai-eshop-optimizer'),
            'github'    => __('GitHub',    'ai-eshop-optimizer'),
            'microsoft' => __('Microsoft', 'ai-eshop-optimizer'),
        );
        $intents_meta = array(
            'login'      => __('Login form',           'ai-eshop-optimizer'),
            'register'   => __('Register form',        'ai-eshop-optimizer'),
            'checkout'   => __('Checkout (classic + block)', 'ai-eshop-optimizer'),
            'my_account' => __('My Account → Connected accounts', 'ai-eshop-optimizer'),
            'newsletter' => __('Newsletter pattern (footer)', 'ai-eshop-optimizer'),
        );
        $nonce = wp_create_nonce('aieo_sso_admin');

        echo '<form id="aieo-sso-settings-form" data-nonce="' . esc_attr($nonce) . '" onsubmit="return false;">';

        echo '<div class="aieo-dmm-card"><h3>' . esc_html__('Providers', 'ai-eshop-optimizer') . '</h3>';
        echo '<p class="description">' . esc_html__('Paste the OAuth Client ID + Secret from each provider\'s developer console. Enable only the providers you have configured.', 'ai-eshop-optimizer') . '</p>';
        echo '<table class="wp-list-table widefat"><thead><tr>';
        echo '<th>' . esc_html__('Provider', 'ai-eshop-optimizer') . '</th>';
        echo '<th>' . esc_html__('Enabled', 'ai-eshop-optimizer') . '</th>';
        echo '<th>' . esc_html__('Client ID', 'ai-eshop-optimizer') . '</th>';
        echo '<th>' . esc_html__('Client Secret', 'ai-eshop-optimizer') . '</th>';
        echo '<th>' . esc_html__('Button text', 'ai-eshop-optimizer') . '</th>';
        echo '<th>' . esc_html__('Callback URL', 'ai-eshop-optimizer') . '</th>';
        echo '</tr></thead><tbody>';
        foreach ($providers_meta as $code => $label) {
            $row = isset($settings['providers'][$code]) ? $settings['providers'][$code] : array();
            $callback = AIEO_SSO_Buttons_Data::callback_url($code);
            echo '<tr>';
            echo '<td><strong>' . esc_html($label) . '</strong><br><code>' . esc_html($code) . '</code></td>';
            echo '<td><input type="checkbox" name="providers[' . esc_attr($code) . '][enabled]" value="1"' . checked(!empty($row['enabled']), true, false) . '></td>';
            echo '<td><input type="text" class="regular-text" name="providers[' . esc_attr($code) . '][client_id]" value="' . esc_attr((string) ($row['client_id'] ?? '')) . '"></td>';
            echo '<td><input type="password" class="regular-text" name="providers[' . esc_attr($code) . '][client_secret]" value="' . esc_attr((string) ($row['client_secret'] ?? '')) . '"></td>';
            echo '<td><input type="text" class="regular-text" name="providers[' . esc_attr($code) . '][button_text]" placeholder="' . esc_attr(AIEO_SSO_Buttons_Data::default_button_text($code)) . '" value="' . esc_attr((string) ($row['button_text'] ?? '')) . '"></td>';
            echo '<td><code style="font-size:10px;">' . esc_html($callback) . '</code></td>';
            echo '</tr>';
        }
        echo '</tbody></table></div>';

        echo '<div class="aieo-dmm-card" style="margin-top:14px;"><h3>' . esc_html__('Where to render', 'ai-eshop-optimizer') . '</h3>';
        echo '<p class="description">' . esc_html__('Pick the surfaces where the SSO buttons appear.', 'ai-eshop-optimizer') . '</p>';
        echo '<table class="form-table">';
        foreach ($intents_meta as $code => $label) {
            $checked = !empty($settings['intents'][$code]);
            echo '<tr><th><label>' . esc_html($label) . '</label></th>';
            echo '<td><label><input type="checkbox" name="intents[' . esc_attr($code) . ']" value="1"' . checked($checked, true, false) . '> ' . esc_html__('Enabled', 'ai-eshop-optimizer') . '</label></td></tr>';
        }
        echo '</table></div>';

        echo '<div class="aieo-dmm-card" style="margin-top:14px;"><h3>' . esc_html__('Security', 'ai-eshop-optimizer') . '</h3>';
        echo '<table class="form-table">';
        echo '<tr><th>' . esc_html__('Force HTTPS callback URLs', 'ai-eshop-optimizer') . '</th>';
        echo '<td><label><input type="checkbox" name="force_ssl_callback" value="1"' . checked(!empty($settings['force_ssl_callback']), true, false) . '> ' . esc_html__('Required by Apple, recommended for all providers.', 'ai-eshop-optimizer') . '</label></td></tr>';
        echo '<tr><th>' . esc_html__('Intro text', 'ai-eshop-optimizer') . '</th>';
        echo '<td><textarea name="intro_text" class="large-text" rows="3" placeholder="' . esc_attr__('Optional Greek text rendered above the buttons (e.g. on the checkout).', 'ai-eshop-optimizer') . '">' . esc_textarea((string) ($settings['intro_text'] ?? '')) . '</textarea></td></tr>';
        echo '</table></div>';

        echo '<p style="margin-top:14px;"><button type="button" class="button button-primary" id="aieo-sso-save-settings">' . esc_html__('Save settings', 'ai-eshop-optimizer') . '</button>';
        echo ' <span id="aieo-sso-save-status" style="margin-left:10px;font-size:13px;color:#646970;"></span></p>';
        echo '</form>';

        $this->print_settings_js($nonce);
    }

    private function render_migrator() {
        $audit = AIEO_SSO_Migrator::audit();
        $nonce = wp_create_nonce('aieo_sso_admin');

        echo '<div class="aieo-dmm-card" data-aieo-sso-migrate data-nonce="' . esc_attr($nonce) . '">';
        echo '<h3>' . esc_html__('Migrate from `woocommerce-social-login`', 'ai-eshop-optimizer') . '</h3>';
        echo '<p class="description">' . esc_html__('Permanent, idempotent, re-runnable. Lifts the legacy SkyVerge plugin\'s settings + per-user link meta into our keys. Safe to run multiple times.', 'ai-eshop-optimizer') . '</p>';

        echo '<h4>' . esc_html__('Audit', 'ai-eshop-optimizer') . '</h4>';
        echo '<ul>';
        foreach ($audit['providers'] as $legacy => $info) {
            $maps_to = $info['maps_to'] ?: __('(skipped — not in our 7)', 'ai-eshop-optimizer');
            
            echo '<li><strong>' . esc_html($legacy) . '</strong> — ' . esc_html(sprintf(__('enabled=%1$s, has_id=%2$s, has_secret=%3$s, maps_to=%4$s', 'ai-eshop-optimizer'),
                $info['enabled'] ? 'yes' : 'no',
                $info['has_id'] ? 'yes' : 'no',
                $info['has_secret'] ? 'yes' : 'no',
                $maps_to
            )) . '</li>';
        }
        
        echo '<li>' . esc_html(sprintf(__('Linked users in legacy plugin: %d', 'ai-eshop-optimizer'), $audit['linked_users'])) . '</li>';
        
        echo '<li>' . esc_html(sprintf(__('Display option present: %1$s · Intro text present: %2$s', 'ai-eshop-optimizer'),
            $audit['has_display'] ? 'yes' : 'no',
            $audit['has_text'] ? 'yes' : 'no'
        )) . '</li>';
        echo '</ul>';

        echo '<p>';
        echo '<button type="button" class="button" id="aieo-sso-migrate-audit">' . esc_html__('Re-audit', 'ai-eshop-optimizer') . '</button> ';
        echo '<button type="button" class="button button-primary" id="aieo-sso-migrate-settings">' . esc_html__('Migrate settings', 'ai-eshop-optimizer') . '</button> ';
        echo '<button type="button" class="button button-primary" id="aieo-sso-migrate-users">' . esc_html__('Migrate user links (batched)', 'ai-eshop-optimizer') . '</button> ';
        echo '<span id="aieo-sso-migrate-status" style="margin-left:10px;font-size:13px;color:#646970;"></span>';
        echo '</p>';
        echo '</div>';

        $this->print_migrator_js($nonce);
    }

    private function print_settings_js($nonce) {
        $ajax = admin_url('admin-ajax.php');
        ?>
        <script>
        (function(){
            var form = document.getElementById('aieo-sso-settings-form'); if (!form) return;
            var btn  = document.getElementById('aieo-sso-save-settings'); if (!btn) return;
            btn.addEventListener('click', function(){
                btn.disabled = true;
                var status = document.getElementById('aieo-sso-save-status');
                status.textContent = '<?php echo esc_js(__('Saving…', 'ai-eshop-optimizer')); ?>';
                var fd = new FormData(form);
                fd.set('action', 'aieo_sso_save_settings');
                fd.set('nonce',  '<?php echo esc_js($nonce); ?>');
                fetch('<?php echo esc_js($ajax); ?>', {method:'POST', credentials:'same-origin', body: fd})
                    .then(function(r){ return r.json(); })
                    .then(function(j){
                        btn.disabled = false;
                        if (j && j.success) {
                            status.style.color = '#15803d';
                            status.textContent = '<?php echo esc_js(__('Saved.', 'ai-eshop-optimizer')); ?>';
                        } else {
                            status.style.color = '#b91c1c';
                            status.textContent = (j && j.data && j.data.message) || '<?php echo esc_js(__('Save failed.', 'ai-eshop-optimizer')); ?>';
                        }
                    });
            });
        })();
        </script>
        <?php
    }

    private function print_migrator_js($nonce) {
        $ajax = admin_url('admin-ajax.php');
        ?>
        <script>
        (function(){
            var box = document.querySelector('[data-aieo-sso-migrate]'); if (!box) return;
            var nonce = '<?php echo esc_js($nonce); ?>';
            function setStatus(text, color){ var el = document.getElementById('aieo-sso-migrate-status'); if (!el) return; el.style.color = color || '#646970'; el.textContent = text; }
            function post(action, data){
                var fd = new FormData();
                fd.set('action', action); fd.set('nonce', nonce);
                Object.keys(data || {}).forEach(function(k){ fd.set(k, data[k]); });
                return fetch('<?php echo esc_js($ajax); ?>', {method:'POST', credentials:'same-origin', body: fd}).then(function(r){return r.json();});
            }
            document.getElementById('aieo-sso-migrate-audit').addEventListener('click', function(){
                setStatus('<?php echo esc_js(__('Auditing…', 'ai-eshop-optimizer')); ?>');
                post('aieo_sso_migrate_audit', {}).then(function(j){
                    if (j && j.success) { setTimeout(function(){ location.reload(); }, 300); }
                    else { setStatus('<?php echo esc_js(__('Audit failed.', 'ai-eshop-optimizer')); ?>', '#b91c1c'); }
                });
            });
            document.getElementById('aieo-sso-migrate-settings').addEventListener('click', function(){
                setStatus('<?php echo esc_js(__('Migrating settings…', 'ai-eshop-optimizer')); ?>');
                post('aieo_sso_migrate_settings', {}).then(function(j){
                    if (j && j.success) { setStatus('<?php echo esc_js(__('Settings migrated.', 'ai-eshop-optimizer')); ?>', '#15803d'); }
                    else { setStatus('<?php echo esc_js(__('Settings migration failed.', 'ai-eshop-optimizer')); ?>', '#b91c1c'); }
                });
            });
            document.getElementById('aieo-sso-migrate-users').addEventListener('click', function(){
                var cursor = 0, total = 0, done = false;
                function tick(){
                    if (done) return;
                    setStatus('<?php echo esc_js(__('Migrating user links… processed', 'ai-eshop-optimizer')); ?> ' + total);
                    post('aieo_sso_migrate_users', {cursor: cursor, batch_size: 500}).then(function(j){
                        if (!j || !j.success) { setStatus('<?php echo esc_js(__('User migration failed.', 'ai-eshop-optimizer')); ?>', '#b91c1c'); done = true; return; }
                        var d = j.data || {};
                        total += (d.processed | 0);
                        if (d.done) {
                            setStatus('<?php echo esc_js(__('Done. Linked rows:', 'ai-eshop-optimizer')); ?> ' + (d.linked | 0) + ' / ' + total, '#15803d');
                            done = true;
                        } else {
                            cursor = (d.next_cursor | 0);
                            setTimeout(tick, 30);
                        }
                    });
                }
                tick();
            });
        })();
        </script>
        <?php
    }

    

    private function verify_admin_ajax() {
        if (!current_user_can('manage_woocommerce')) { wp_send_json_error(array('message' => 'permission_denied'), 403); }
        check_ajax_referer('aieo_sso_admin', 'nonce');
    }

    public function ajax_save_settings() {
        $this->verify_admin_ajax();
        $providers_in = isset($_POST['providers']) && is_array( wp_unslash( $_POST['providers'] ) ) ? wp_unslash($_POST['providers']) : array();
        $intents_in   = isset($_POST['intents'])   && is_array( wp_unslash( $_POST['intents'] ) )   ? wp_unslash($_POST['intents'])   : array();
        $intro_text   = isset($_POST['intro_text']) ? sanitize_textarea_field((string) wp_unslash($_POST['intro_text'])) : '';
        $force_ssl    = !empty($_POST['force_ssl_callback']);

        $clean_providers = array();
        foreach ((array) $providers_in as $code => $row) {
            $code = sanitize_key((string) $code);
            if ($code === '') { continue; }
            $clean_providers[$code] = array(
                'enabled'       => !empty($row['enabled']),
                'client_id'     => isset($row['client_id'])     ? sanitize_text_field((string) $row['client_id'])     : '',
                'client_secret' => isset($row['client_secret']) ? sanitize_text_field((string) $row['client_secret']) : '',
                'button_text'   => isset($row['button_text'])   ? sanitize_text_field((string) $row['button_text'])   : '',
            );
        }
        $clean_intents = array();
        foreach (array('login', 'register', 'checkout', 'my_account', 'newsletter') as $i) {
            $clean_intents[$i] = !empty($intents_in[$i]);
        }
        AIEO_SSO_Buttons_Data::save_settings(array(
            'providers'          => $clean_providers,
            'intents'            => $clean_intents,
            'force_ssl_callback' => $force_ssl,
            'intro_text'         => $intro_text,
        ));
        wp_send_json_success();
    }

    public function ajax_migrate_audit() {
        $this->verify_admin_ajax();
        wp_send_json_success(AIEO_SSO_Migrator::audit());
    }

    public function ajax_migrate_settings() {
        $this->verify_admin_ajax();
        wp_send_json_success(AIEO_SSO_Migrator::run_settings());
    }

    public function ajax_migrate_users() {
        $this->verify_admin_ajax();
        $cursor     = isset($_POST['cursor'])     ? (int) $_POST['cursor']     : 0;
        $batch_size = isset($_POST['batch_size']) ? (int) $_POST['batch_size'] : 500;
        wp_send_json_success(AIEO_SSO_Migrator::run_users($batch_size, $cursor));
    }
}
