<?php

declare(strict_types=1);

namespace SecurWP\Includes\CLI;

use SecurWP\Modules\Cloud\Service\CloudSettings;

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

/**
 * WP-CLI commands for SecurWP license management.
 *
 * ## EXAMPLES
 *
 *     wp securwp activate --license-key=XXXX-XXXX-XXXX
 *     wp securwp status
 *     wp securwp deactivate
 */
class ActivateCommand {

    /**
     * Activate the site via license key.
     *
     * ## OPTIONS
     *
     * [--license-key=<key>]
     * : The license key. Falls back to SECURWP_LICENSE_KEY constant if not provided.
     *
     * [--email=<email>]
     * : License owner email used for OTP verification.
     *
     * [--otp=<code>]
     * : One-time verification code sent to the owner email.
     *
     * ## EXAMPLES
     *
     *     wp securwp activate --license-key=XXXX-XXXX-XXXX
     *     wp securwp activate
     *
     * @param array $args       Positional arguments.
     * @param array $assoc_args Associative arguments.
     */
    public function activate( $args, $assoc_args ): void {
        $key = $assoc_args['license-key'] ?? '';
        $email = isset( $assoc_args['email'] ) ? sanitize_email( (string) $assoc_args['email'] ) : '';
        $otp = isset( $assoc_args['otp'] ) ? sanitize_text_field( (string) $assoc_args['otp'] ) : '';

        if ( empty( $key ) && defined( 'SECURWP_LICENSE_KEY' ) ) {
            $key = constant( 'SECURWP_LICENSE_KEY' );
            \WP_CLI::log( 'Using SECURWP_LICENSE_KEY constant.' );
        }

        if ( empty( $key ) || ! is_string( $key ) || trim( $key ) === '' ) {
            \WP_CLI::error( 'No license key provided. Use --license-key=XXX or define SECURWP_LICENSE_KEY in wp-config.php.' );
            return;
        }
        if ( $email === '' || $otp === '' ) {
            \WP_CLI::error( 'Email + OTP are required. Use --email=<owner-email> --otp=<code>.' );
            return;
        }

        $settings = CloudSettings::get_all();
        $manager  = new \SecurWP\Modules\Cloud\License\LicenseManager( $settings );

        if ( $manager->is_active() ) {
            \WP_CLI::warning( 'Site is already activated.' );
            $this->print_status();
            return;
        }

        \WP_CLI::log( 'Activating license...' );
        $result = $manager->verify_license( trim( $key ), $email, $otp );

        if ( is_wp_error( $result ) ) {
            \WP_CLI::error( 'Activation failed: ' . $result->get_error_message() );
            return;
        }

        \WP_CLI::success( 'Site activated successfully.' );
        $this->print_status();
    }

    /**
     * Show current license/connection status.
     *
     * ## EXAMPLES
     *
     *     wp securwp status
     *
     * @param array $args       Positional arguments.
     * @param array $assoc_args Associative arguments.
     */
    public function status( $args, $assoc_args ): void {
        $this->print_status();
    }

    /**
     * Deactivate the current license.
     *
     * ## EXAMPLES
     *
     *     wp securwp deactivate
     *
     * @param array $args       Positional arguments.
     * @param array $assoc_args Associative arguments.
     */
    public function deactivate( $args, $assoc_args ): void {
        $settings = CloudSettings::get_all();
        $manager  = new \SecurWP\Modules\Cloud\License\LicenseManager( $settings );

        if ( ! $manager->is_active() ) {
            \WP_CLI::warning( 'Site is not currently activated.' );
            return;
        }

        $result = $manager->deactivate();

        if ( is_wp_error( $result ) ) {
            \WP_CLI::error( 'Deactivation failed: ' . $result->get_error_message() );
            return;
        }

        \WP_CLI::success( 'License deactivated.' );
    }

    /**
     * Print license status as a table.
     */
    private function print_status(): void {
        $settings  = CloudSettings::get_all();
        $has_creds = ! empty( $settings['site_token'] ) && ! empty( $settings['site_secret'] );
        $status    = (string) ( $settings['license_status'] ?? '' );
        // Don't show 'active' when credentials are missing - keeps CLI output accurate.
        if ( $status === 'active' && ! $has_creds ) {
            $status = '';
        }
        $plan    = (string) ( $settings['license_plan'] ?? 'free' );
        $expires = $settings['license_expires_at'] ?? 0;

        $rows = [
            [ 'Field' => 'Status',  'Value' => $status ?: '(not connected)' ],
            [ 'Field' => 'Plan',    'Value' => $plan ],
        ];

        if ( $expires && is_numeric( $expires ) ) {
            $rows[] = [ 'Field' => 'Expires', 'Value' => gmdate( 'Y-m-d H:i:s', (int) $expires ) . ' UTC' ];
        }

        $site_uuid = (string) ( $settings['site_uuid'] ?? '' );
        if ( $site_uuid ) {
            $rows[] = [ 'Field' => 'Site UUID', 'Value' => $site_uuid ];
        }

        \WP_CLI\Utils\format_items( 'table', $rows, [ 'Field', 'Value' ] );
    }
}
