# Licensing Page - Usage Guide

## Quick Start

The Licensing Page component is automatically bundled and available globally after enqueueing the admin scripts.

## PHP Integration

### 1. Register Admin Menu Page

```php
<?php
/**
 * Register the licensing admin page
 */
function multilingual_press_zone_register_licensing_page() {
    add_submenu_page(
        'multilingual-press-zone',           // Parent slug
        __('Licensing', 'multilingual-press-zone'),  // Page title
        __('Licensing', 'multilingual-press-zone'),  // Menu title
        'manage_options',                     // Capability
        'multilingual-press-zone-licensing',  // Menu slug
        'multilingual_press_zone_render_licensing_page' // Callback
    );
}
add_action('admin_menu', 'multilingual_press_zone_register_licensing_page');

/**
 * Render the licensing page
 */
function multilingual_press_zone_render_licensing_page() {
    ?>
    <div class="wrap">
        <div id="multilingual-press-zone-licensing-root"></div>
    </div>
    <?php
}
```

### 2. Enqueue Scripts

```php
<?php
/**
 * Enqueue admin scripts
 */
function multilingual_press_zone_enqueue_admin_scripts($hook) {
    // Only load on our admin pages
    if (strpos($hook, 'multilingual-press-zone') === false) {
        return;
    }

    // Enqueue the compiled bundle
    wp_enqueue_script(
        'multilingual-press-zone-admin',
        plugins_url('dist/js/main.js', __FILE__),
        ['wp-i18n'], // WordPress i18n dependency
        '1.0.0',
        true
    );

    // Localize script with API configuration
    wp_localize_script('multilingual-press-zone-admin', 'multilingualPressZone', [
        'apiUrl' => rest_url('multilingual-press-zone/v1'),
        'nonce' => wp_create_nonce('wp_rest'),
        'apiKey' => get_option('multilingual_press_zone_api_key', '')
    ]);

    // Initialize licensing page if on that page
    if ($hook === 'multilingual-press-zone_page_multilingual-press-zone-licensing') {
        wp_add_inline_script(
            'multilingual-press-zone-admin',
            "
            document.addEventListener('DOMContentLoaded', function() {
                const container = document.getElementById('multilingual-press-zone-licensing-root');
                if (container && window.MultilingualPressZone) {
                    const licensingPage = new window.MultilingualPressZone.LicensingPage(container);
                    licensingPage.render();
                }
            });
            "
        );
    }
}
add_action('admin_enqueue_scripts', 'multilingual_press_zone_enqueue_admin_scripts');
```

## JavaScript Usage

### Global Access

After the scripts are loaded, the LicensingPage is available globally:

```javascript
// Access via global object
const licensingPage = new window.MultilingualPressZone.LicensingPage(container);
licensingPage.render();
```

### Module Import

For custom JavaScript modules:

```javascript
import { LicensingPage } from './main.js';

const container = document.getElementById('licensing-page-root');
const licensingPage = new LicensingPage(container);

// Render the page
await licensingPage.render();

// Later, clean up
licensingPage.destroy();
```

## API Methods

### Constructor

```javascript
const licensingPage = new LicensingPage(container);
```

**Parameters:**
- `container` (HTMLElement) - DOM element to render into

### render()

Renders the licensing page interface.

```javascript
await licensingPage.render();
```

**Returns:** Promise (resolves when rendering complete)

### destroy()

Cleans up the page and removes all event listeners.

```javascript
licensingPage.destroy();
```

## REST API Implementation

The licensing page expects these WordPress REST API endpoints:

### GET /license

Returns current license information.

```php
<?php
register_rest_route('multilingual-press-zone/v1', '/license', [
    'methods' => 'GET',
    'callback' => 'multilingual_press_zone_get_license',
    'permission_callback' => function() {
        return current_user_can('manage_options');
    }
]);

function multilingual_press_zone_get_license() {
    $license_key = get_option('multilingual_press_zone_license_key');

    if (!$license_key) {
        return new WP_REST_Response([
            'license' => null
        ], 200);
    }

    // Fetch license data from api.press.zone
    $response = wp_remote_get("https://api.press.zone/v1/licenses/{$license_key}/validate", [
        'headers' => [
            'X-API-Key' => get_option('multilingual_press_zone_api_key')
        ]
    ]);

    if (is_wp_error($response)) {
        return new WP_Error('api_error', $response->get_error_message(), ['status' => 500]);
    }

    $body = json_decode(wp_remote_retrieve_body($response), true);

    return new WP_REST_Response([
        'license' => [
            'key' => $license_key,
            'plan' => $body['plan'] ?? 'personal',
            'status' => $body['status'] ?? 'inactive',
            'sites_used' => $body['sites_used'] ?? 0,
            'expires_at' => $body['expires_at'] ?? null
        ]
    ], 200);
}
```

### POST /license/activate

Activates a license key for the current site.

```php
<?php
register_rest_route('multilingual-press-zone/v1', '/license/activate', [
    'methods' => 'POST',
    'callback' => 'multilingual_press_zone_activate_license',
    'permission_callback' => function() {
        return current_user_can('manage_options');
    }
]);

function multilingual_press_zone_activate_license($request) {
    $license_key = sanitize_text_field($request->get_param('license_key'));

    // Validate with api.press.zone
    $response = wp_remote_post('https://api.press.zone/v1/licenses/activate', [
        'headers' => [
            'Content-Type' => 'application/json',
            'X-API-Key' => get_option('multilingual_press_zone_api_key')
        ],
        'body' => json_encode([
            'license_key' => $license_key,
            'site_url' => get_site_url()
        ])
    ]);

    if (is_wp_error($response)) {
        return new WP_Error('activation_failed', $response->get_error_message(), ['status' => 500]);
    }

    $body = json_decode(wp_remote_retrieve_body($response), true);

    if (!$body['success']) {
        return new WP_Error('activation_failed', $body['message'] ?? 'Activation failed', ['status' => 400]);
    }

    // Store license key
    update_option('multilingual_press_zone_license_key', $license_key);

    return new WP_REST_Response([
        'success' => true,
        'message' => __('License activated successfully', 'multilingual-press-zone'),
        'license' => $body['license']
    ], 200);
}
```

### POST /license/deactivate

Deactivates the license for the current site.

```php
<?php
register_rest_route('multilingual-press-zone/v1', '/license/deactivate', [
    'methods' => 'POST',
    'callback' => 'multilingual_press_zone_deactivate_license',
    'permission_callback' => function() {
        return current_user_can('manage_options');
    }
]);

function multilingual_press_zone_deactivate_license() {
    $license_key = get_option('multilingual_press_zone_license_key');

    if (!$license_key) {
        return new WP_Error('no_license', 'No license to deactivate', ['status' => 400]);
    }

    // Deactivate with api.press.zone
    $response = wp_remote_post('https://api.press.zone/v1/licenses/deactivate', [
        'headers' => [
            'Content-Type' => 'application/json',
            'X-API-Key' => get_option('multilingual_press_zone_api_key')
        ],
        'body' => json_encode([
            'license_key' => $license_key,
            'site_url' => get_site_url()
        ])
    ]);

    if (is_wp_error($response)) {
        return new WP_Error('deactivation_failed', $response->get_error_message(), ['status' => 500]);
    }

    // Remove license key
    delete_option('multilingual_press_zone_license_key');

    return new WP_REST_Response([
        'success' => true,
        'message' => __('License deactivated successfully', 'multilingual-press-zone')
    ], 200);
}
```

### GET /license/usage

Returns usage statistics for the current license.

```php
<?php
register_rest_route('multilingual-press-zone/v1', '/license/usage', [
    'methods' => 'GET',
    'callback' => 'multilingual_press_zone_get_usage',
    'permission_callback' => function() {
        return current_user_can('manage_options');
    }
]);

function multilingual_press_zone_get_usage() {
    $license_key = get_option('multilingual_press_zone_license_key');

    if (!$license_key) {
        return new WP_Error('no_license', 'No active license', ['status' => 400]);
    }

    // Fetch usage from api.press.zone
    $response = wp_remote_get("https://api.press.zone/v1/licenses/{$license_key}/usage", [
        'headers' => [
            'X-API-Key' => get_option('multilingual_press_zone_api_key')
        ]
    ]);

    if (is_wp_error($response)) {
        return new WP_Error('api_error', $response->get_error_message(), ['status' => 500]);
    }

    $body = json_decode(wp_remote_retrieve_body($response), true);

    return new WP_REST_Response([
        'usage' => [
            'current_month' => $body['current_month'] ?? 0,
            'historical' => $body['historical'] ?? []
        ]
    ], 200);
}
```

## Customization

### Custom Styling

Override styles by adding custom CSS:

```css
/* Custom licensing page styles */
.mpz-licensing-page {
    /* Your custom styles */
}

.mpz-plan-option--popular {
    /* Highlight popular plan differently */
    border-color: #ff6b6b;
}
```

### Custom Success/Error Messages

Extend the class and override message methods:

```javascript
class CustomLicensingPage extends window.MultilingualPressZone.LicensingPage {
    showSuccess(message) {
        // Custom success notification
        // Use your toast/notification system
        MyNotificationSystem.success(message);
    }

    showError(message) {
        // Custom error notification
        MyNotificationSystem.error(message);
    }
}

const licensingPage = new CustomLicensingPage(container);
licensingPage.render();
```

## Troubleshooting

### Page Not Rendering

1. Check that the container element exists:
```javascript
const container = document.getElementById('multilingual-press-zone-licensing-root');
console.log('Container:', container); // Should not be null
```

2. Verify scripts are loaded:
```javascript
console.log('MultilingualPressZone:', window.MultilingualPressZone);
// Should show { adminPanel, LicensingPage }
```

3. Check for JavaScript errors in browser console

### API Errors

1. Verify REST API is accessible:
```bash
curl https://yoursite.com/wp-json/multilingual-press-zone/v1/license \
  -H "X-WP-Nonce: YOUR_NONCE"
```

2. Check nonce is valid (not expired)

3. Verify user has `manage_options` capability

### Styling Issues

1. Check that main.scss is being imported:
```javascript
// Should be in main.js
import './styles/main.scss';
```

2. Rebuild if styles not showing:
```bash
cd admin && npm run build
```

3. Clear browser cache

## Support

For issues or questions:
- Documentation: https://press.zone/docs
- Support: https://press.zone/support
- API Reference: https://api.press.zone/docs
