<?php
declare(strict_types=1);
// ==================================================
// Nuclear Fancy Pants Edition™ -- NUCLEAR+++
// File: /home/ploi/automarketer-ai.com/public/wp-content/plugins/automarketer-ai/includes/class-install-handler.php
// Description: Handles the one-click plugin install redirect from Core - NUCLEAR+++
// Last Edited: 2026-05-11
// ==================================================
namespace AutoMarketerAI;

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

final class InstallHandler
{
    private const DOWNLOAD_BASE = 'https://core.automarketer-ai.com/api/plugin/download';
    private const PLUGIN_FILE   = 'automarketer-ai/automarketer-ai.php';

    public static function register(): void
    {
        add_action('init', [self::class, 'handle']);
    }

    public static function handle(): void
    {
        if (!isset($_SERVER['REQUEST_URI'])) {
            return;
        }

        $path = (string) parse_url((string) $_SERVER['REQUEST_URI'], PHP_URL_PATH);
        if ($path !== '/amai-install') {
            return;
        }

        // Must be a logged-in WP admin with plugin install capability.
        if (!is_user_logged_in() || !current_user_can('install_plugins')) {
            wp_die(
                esc_html__('You must be logged in as a WordPress administrator to install AutoMarketer AI.', 'automarketer-ai'),
                esc_html__('Permission Denied', 'automarketer-ai'),
                ['response' => 403]
            );
        }

        $licenseKey = isset($_GET['license_key'])
            ? sanitize_text_field(wp_unslash((string) $_GET['license_key']))
            : '';
        $sig = isset($_GET['sig'])
            ? sanitize_text_field(wp_unslash((string) $_GET['sig']))
            : '';

        if ($licenseKey === '' || $sig === '') {
            wp_die(
                esc_html__('Invalid install link -- missing parameters.', 'automarketer-ai'),
                esc_html__('Install Error', 'automarketer-ai'),
                ['response' => 400]
            );
        }

        // Verify the signature -- Core signs with hash_hmac(sha256, license_key, hex2bin(amai_tenant_hmac_secret)).
        $tenantSecret = (string) get_option('amai_tenant_hmac_secret', '');
        if ($tenantSecret === '') {
            wp_die(
                esc_html__('Install configuration error. Please contact support.', 'automarketer-ai'),
                esc_html__('Install Error', 'automarketer-ai'),
                ['response' => 500]
            );
        }

        $expected = hash_hmac('sha256', $licenseKey, hex2bin($tenantSecret));
        if (!hash_equals($expected, $sig)) {
            wp_die(
                esc_html__('Invalid install link -- signature mismatch.', 'automarketer-ai'),
                esc_html__('Install Error', 'automarketer-ai'),
                ['response' => 403]
            );
        }

        // Already installed -- just activate and redirect to dashboard.
        if (self::isInstalled()) {
            if (!is_plugin_active(self::PLUGIN_FILE)) {
                activate_plugin(self::PLUGIN_FILE);
            }
            update_option('amai_install_completed', true);
            wp_safe_redirect(admin_url('admin.php?page=automarketer-ai&installed=1'));
            exit;
        }

        // Trigger WP_Upgrader install from the Core download URL.
        require_once ABSPATH . 'wp-admin/includes/class-wp-upgrader.php';
        require_once ABSPATH . 'wp-admin/includes/plugin-install.php';
        require_once ABSPATH . 'wp-admin/includes/file.php';

        $downloadUrl = self::DOWNLOAD_BASE . '?license_key=' . rawurlencode($licenseKey);

        $skin     = new \WP_Ajax_Upgrader_Skin();
        $upgrader = new \Plugin_Upgrader($skin);
        $result   = $upgrader->install($downloadUrl);

        if (is_wp_error($result) || $result === false || $result === null) {
            $errorMsg = is_wp_error($result) ? $result->get_error_message() : 'Unknown install error.';
            wp_die(
                esc_html('AutoMarketer AI could not be installed: ' . $errorMsg),
                esc_html__('Install Failed', 'automarketer-ai'),
                ['response' => 500]
            );
        }

        $activated = activate_plugin(self::PLUGIN_FILE);
        if (is_wp_error($activated)) {
            wp_die(
                esc_html('Plugin installed but could not be activated: ' . $activated->get_error_message()),
                esc_html__('Activation Failed', 'automarketer-ai'),
                ['response' => 500]
            );
        }

        update_option('amai_install_completed', true);
        wp_safe_redirect(admin_url('admin.php?page=automarketer-ai&installed=1'));
        exit;
    }

    private static function isInstalled(): bool
    {
        if (!function_exists('get_plugins')) {
            require_once ABSPATH . 'wp-admin/includes/plugin.php';
        }
        $plugins = get_plugins();
        return isset($plugins[self::PLUGIN_FILE]);
    }
}