<?php
/**
 * ZutaLW Admin License Module
 * Handles the UI and form submission for activating the plugin license.
 */

if ( ! defined( 'ABSPATH' ) ) {
    exit; // Exit if accessed directly
}

class ZUTALW_Admin_License {

    private $message = '';
    private $message_type = '';

    /**
     * Main render function called from the admin menu router.
     */
    public function render() {
        // Handle form submission before rendering the UI
        $this->process_form();
        $this->display_form();
    }

    /**
     * Process the license activation/deactivation request.
     */
    private function process_form() {
        if ( isset( $_POST['zutalw_license_action'] ) && isset( $_POST['zutalw_license_nonce'] ) ) {
            
            // Security check: Verify nonce
            if ( ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['zutalw_license_nonce'] ) ), 'zutalw_license_action' ) ) {
                $this->message = esc_html__( 'Security check failed. Please try again.', 'zuta-lucky-wheel' );
                $this->message_type = 'error';
                return;
            }

            // Security check: Verify user capability
            if ( ! current_user_can( 'manage_options' ) ) {
                $this->message = esc_html__( 'You do not have permission to do this.', 'zuta-lucky-wheel' );
                $this->message_type = 'error';
                return;
            }

            $action = sanitize_text_field( wp_unslash( $_POST['zutalw_license_action'] ) );

            // Handle Activation
            if ( 'activate' === $action ) {
                $license_key = sanitize_text_field( wp_unslash( $_POST['zutalw_license_key'] ) );

                if ( empty( $license_key ) ) {
                    $this->message = esc_html__( 'Please enter a license key.', 'zuta-lucky-wheel' );
                    $this->message_type = 'error';
                    return;
                }

                // Call the License Manager to process via Django API
                if ( class_exists( 'ZUTALW_License_Manager' ) ) {
                    $manager = new ZUTALW_License_Manager();
                    $result  = $manager->activate_license( $license_key );

                    if ( is_wp_error( $result ) ) {
                        $this->message = $result->get_error_message();
                        $this->message_type = 'error';
                    } else {
                        $this->message = $result['message'];
                        $this->message_type = 'success';
                    }
                } else {
                    $this->message = esc_html__( 'License manager core is missing.', 'zuta-lucky-wheel' );
                    $this->message_type = 'error';
                }

            // Handle Deactivation
            } elseif ( 'deactivate' === $action ) {
                // Clear the local license data
                delete_option( 'zutalw_license_info' );

                // Clear the background cron job to save server resources
                if ( class_exists( 'ZUTALW_License_Manager' ) ) {
                    ZUTALW_License_Manager::clear_cron();
                }

                $this->message = esc_html__( 'License deactivated successfully.', 'zuta-lucky-wheel' );
                $this->message_type = 'success';
            }
        }
    }

    /**
     * Render the HTML UI.
     */
    private function display_form() {
        $license_info = get_option( 'zutalw_license_info' );
        $is_active    = ( isset( $license_info['license_status'] ) && $license_info['license_status'] === 'active' );
        $current_key  = isset( $license_info['license_key'] ) ? $license_info['license_key'] : '';
        $expiry_date  = ! empty( $license_info['expiry_date'] ) ? date_i18n( get_option( 'date_format' ), strtotime( $license_info['expiry_date'] ) ) : esc_html__( 'Lifetime', 'zuta-lucky-wheel' );

        // Print status messages
        if ( ! empty( $this->message ) ) {
            $notice_class = ( $this->message_type === 'success' ) ? 'notice-success' : 'notice-error';
            echo '<div class="notice ' . esc_attr( $notice_class ) . ' is-dismissible"><p>' . esc_html( $this->message ) . '</p></div>';
        }
        ?>
        <div class="zutalw-license-wrapper" style="max-width: 600px; margin-top: 30px;">
            
            <div class="postbox" style="padding: 30px; border-radius: 8px; box-shadow: 0 4px 12px rgba(0,0,0,0.05); border: 1px solid #e2e4e7;">
                <div style="text-align: center; margin-bottom: 30px;">
                    <span class="dashicons dashicons-admin-network" style="font-size: 48px; width: 48px; height: 48px; color: #2271b1;"></span>
                    <h2 style="font-size: 24px; font-weight: 600; margin-top: 15px; margin-bottom: 5px;">
                        <?php esc_html_e( 'Pro License Activation', 'zuta-lucky-wheel' ); ?>
                    </h2>
                    <p style="color: #646970; font-size: 14px; margin: 0;">
                        <?php esc_html_e( 'Enter your license key to unlock premium features and automatic updates.', 'zuta-lucky-wheel' ); ?>
                    </p>
                </div>

                <hr style="border: 0; border-top: 1px solid #f0f0f1; margin-bottom: 25px;">

                <?php if ( $is_active ) : ?>
                    
                    <div style="background: #f0f6fc; border-left: 4px solid #72aee6; padding: 20px; border-radius: 4px; margin-bottom: 25px;">
                        <div style="display: flex; align-items: center; margin-bottom: 15px;">
                            <span class="dashicons dashicons-yes-alt" style="color: #00a32a; font-size: 24px; width: 24px; height: 24px; margin-right: 10px;"></span>
                            <h3 style="margin: 0; font-size: 16px; color: #0a4b78;"><?php esc_html_e( 'License is Active', 'zuta-lucky-wheel' ); ?></h3>
                        </div>
                        <p style="margin: 0 0 10px 0;"><strong><?php esc_html_e( 'License Key:', 'zuta-lucky-wheel' ); ?></strong> 
                            <code style="font-size: 14px; background: #fff; padding: 4px 8px; border: 1px solid #ccd0d4; border-radius: 3px;">
                                <?php echo esc_html( $this->mask_key( $current_key ) ); ?>
                            </code>
                        </p>
                        <p style="margin: 0;"><strong><?php esc_html_e( 'Valid Until:', 'zuta-lucky-wheel' ); ?></strong> <?php echo esc_html( $expiry_date ); ?></p>
                    </div>

                    <form method="post" action="">
                        <?php wp_nonce_field( 'zutalw_license_action', 'zutalw_license_nonce' ); ?>
                        <input type="hidden" name="zutalw_license_action" value="deactivate">
                        <button type="submit" class="button button-secondary" onclick="return confirm('<?php esc_attr_e( 'Are you sure you want to deactivate this license? Pro features will be locked.', 'zuta-lucky-wheel' ); ?>');">
                            <?php esc_html_e( 'Deactivate License', 'zuta-lucky-wheel' ); ?>
                        </button>
                    </form>

                <?php else : ?>

                    <form method="post" action="">
                        <?php wp_nonce_field( 'zutalw_license_action', 'zutalw_license_nonce' ); ?>
                        <input type="hidden" name="zutalw_license_action" value="activate">
                        
                        <table class="form-table" role="presentation" style="margin-top: 0;">
                            <tbody>
                                <tr>
                                    <th scope="row" style="padding-top: 10px; width: 100px;">
                                        <label for="zutalw_license_key" style="font-weight: 600;"><?php esc_html_e( 'License Key', 'zuta-lucky-wheel' ); ?></label>
                                    </th>
                                    <td style="padding-top: 10px;">
                                        <input type="password" id="zutalw_license_key" name="zutalw_license_key" value="" class="regular-text" placeholder="ZUTA-XXXX-XXXX-XXXX" style="width: 100%; padding: 8px; font-size: 14px;" required autocomplete="off">
                                        <p class="description" style="margin-top: 8px;">
                                            <?php esc_html_e( 'You can find your license key in your Zuta Themes account dashboard.', 'zuta-lucky-wheel' ); ?>
                                        </p>
                                    </td>
                                </tr>
                            </tbody>
                        </table>
                        
                        <div style="margin-top: 25px; text-align: right;">
                            <button type="submit" class="button button-primary button-large" style="padding: 0 30px; height: 40px; line-height: 38px; font-size: 14px;">
                                <?php esc_html_e( 'Activate Now', 'zuta-lucky-wheel' ); ?>
                            </button>
                        </div>
                    </form>

                <?php endif; ?>

            </div>
            
            <div style="text-align: center; margin-top: 15px;">
                <a href="https://zutathemes.com" target="_blank" style="color: #2271b1; text-decoration: none; font-size: 13px;">
                    <?php esc_html_e( 'Need help finding your key?', 'zuta-lucky-wheel' ); ?> <span class="dashicons dashicons-external" style="font-size: 14px; margin-top: 2px;"></span>
                </a>
            </div>
        </div>
        <?php
    }

    /**
     * Helper function to partially mask the license key for display.
     * e.g., ZUTA-1234-5678-ABCD becomes ZUTA-****-****-ABCD
     */
    private function mask_key( $key ) {
        if ( strlen( $key ) < 10 ) {
            return '****' . substr( $key, -4 );
        }
        
        $parts = explode( '-', $key );
        if ( count( $parts ) >= 3 ) {
            // Mask middle parts if separated by dashes
            for ( $i = 1; $i < count( $parts ) - 1; $i++ ) {
                $parts[$i] = str_repeat( '*', strlen( $parts[$i] ) );
            }
            return implode( '-', $parts );
        }
        
        // Fallback mask: show first 4 and last 4 characters
        return substr( $key, 0, 4 ) . str_repeat( '*', strlen( $key ) - 8 ) . substr( $key, -4 );
    }
}