<?php
/**
 * Plugin Name: JamAuth WordPress Integration
 * Description: Passwordless authentication for WordPress using JamAuth. Protect content with shortcodes.
 * Version: 1.0.0
 * Author: JamAuth
 * License: MIT
 */

// Prevent direct access
if (!defined('ABSPATH')) {
    exit;
}

/**
 * Add settings page
 */
add_action('admin_menu', 'jamauth_add_admin_menu');
add_action('admin_init', 'jamauth_settings_init');

function jamauth_add_admin_menu() {
    add_options_page(
        'JamAuth Settings',
        'JamAuth',
        'manage_options',
        'jamauth',
        'jamauth_options_page'
    );
}

function jamauth_settings_init() {
    register_setting('jamauth', 'jamauth_settings');
    
    add_settings_section(
        'jamauth_section',
        __('JamAuth Configuration', 'jamauth'),
        'jamauth_settings_section_callback',
        'jamauth'
    );
    
    add_settings_field(
        'jamauth_client_id',
        __('Client ID', 'jamauth'),
        'jamauth_client_id_render',
        'jamauth',
        'jamauth_section'
    );
    
    add_settings_field(
        'jamauth_host',
        __('JamAuth Host', 'jamauth'),
        'jamauth_host_render',
        'jamauth',
        'jamauth_section'
    );
    
    add_settings_field(
        'jamauth_session_endpoint',
        __('Session Endpoint', 'jamauth'),
        'jamauth_session_endpoint_render',
        'jamauth',
        'jamauth_section'
    );
}

function jamauth_client_id_render() {
    $options = get_option('jamauth_settings');
    ?>
    <input type='text' name='jamauth_settings[client_id]' 
           value='<?php echo esc_attr($options['client_id'] ?? ''); ?>' 
           size='50' placeholder='client_abc123'>
    <p class="description">Your JamAuth tenant client ID from <a href="https://app.jamauth.com" target="_blank">app.jamauth.com</a></p>
    <?php
}

function jamauth_host_render() {
    $options = get_option('jamauth_settings');
    ?>
    <input type='text' name='jamauth_settings[host]' 
           value='<?php echo esc_attr($options['host'] ?? 'https://app.jamauth.com'); ?>' 
           size='50'>
    <p class="description">Default: https://app.jamauth.com</p>
    <?php
}

function jamauth_session_endpoint_render() {
    $options = get_option('jamauth_settings');
    ?>
    <input type='text' name='jamauth_settings[session_endpoint]' 
           value='<?php echo esc_attr($options['session_endpoint'] ?? '/wp-json/jamauth/v1/session'); ?>' 
           size='50'>
    <p class="description">WordPress REST API endpoint for session validation (default: /wp-json/jamauth/v1/session)</p>
    <?php
}

function jamauth_settings_section_callback() {
    echo __('Configure your JamAuth credentials. Get your Client ID from <a href="https://app.jamauth.com" target="_blank">app.jamauth.com</a>', 'jamauth');
}

function jamauth_options_page() {
    ?>
    <div class="wrap">
        <h2>JamAuth Settings</h2>
        <form action='options.php' method='post'>
            <?php
            settings_fields('jamauth');
            do_settings_sections('jamauth');
            submit_button();
            ?>
        </form>
        
        <div class="card" style="max-width: 600px; margin-top: 20px;">
            <h3>Usage Instructions</h3>
            <p>Use these shortcodes in your posts or pages:</p>
            <pre style="background: #f5f5f5; padding: 10px; border-radius: 4px;">
[jamauth_gate]

[jamauth_protected]
Your premium content here
[/jamauth_protected]</pre>
            <p><strong>Note:</strong> The gate must appear before protected content on the page.</p>
        </div>
    </div>
    <?php
}

/**
 * Enqueue widget script in footer
 */
add_action('wp_footer', 'jamauth_enqueue_widget');

function jamauth_enqueue_widget() {
    $options = get_option('jamauth_settings');
    
    if (empty($options['client_id'])) {
        return; // Don't load if not configured
    }
    
    ?>
    <script>
        window.JAMAUTH_WP_CONFIG = {
            clientId: '<?php echo esc_js($options['client_id']); ?>',
            host: '<?php echo esc_js($options['host'] ?? 'https://app.jamauth.com'); ?>',
            sessionEndpoint: '<?php echo esc_js($options['session_endpoint'] ?? '/wp-json/jamauth/v1/session'); ?>'
        };
    </script>
    <script src="https://app.jamauth.com/jamauth-wordpress.js"></script>
    <?php
}

/**
 * Shortcode: [jamauth_gate]
 */
add_shortcode('jamauth_gate', 'jamauth_gate_shortcode');

function jamauth_gate_shortcode($atts) {
    return '<div class="jamauth-wp-gate"></div>';
}

/**
 * Shortcode: [jamauth_protected]content[/jamauth_protected]
 */
add_shortcode('jamauth_protected', 'jamauth_protected_shortcode');

function jamauth_protected_shortcode($atts, $content = null) {
    if (!$content) {
        return '';
    }
    
    return '<div class="jamauth-wp-protected" style="display:none;">' . 
           do_shortcode($content) . 
           '</div>';
}

/**
 * REST API endpoint for session validation
 */
add_action('rest_api_init', function() {
    register_rest_route('jamauth/v1', '/session', array(
        'methods' => 'GET',
        'callback' => 'jamauth_validate_session',
        'permission_callback' => '__return_true'
    ));
});

function jamauth_validate_session() {
    $options = get_option('jamauth_settings');
    $host = $options['host'] ?? 'https://app.jamauth.com';
    
    // Forward cookies to JamAuth (server-to-server)
    $cookie_header = $_SERVER['HTTP_COOKIE'] ?? '';
    
    if (empty($cookie_header)) {
        return new WP_REST_Response(
            array('authenticated' => false),
            401
        );
    }
    
    // Call JamAuth refresh-session for validation
    $response = wp_remote_post($host . '/.netlify/functions/refresh-session', array(
        'headers' => array(
            'Cookie' => $cookie_header,
            'Content-Type' => 'application/json'
        ),
        'timeout' => 10
    ));
    
    if (is_wp_error($response)) {
        // Fail closed on errors
        return new WP_REST_Response(
            array('authenticated' => false, 'error' => 'validation_failed'),
            503
        );
    }
    
    $status = wp_remote_retrieve_response_code($response);
    
    if ($status === 200) {
        $body = json_decode(wp_remote_retrieve_body($response), true);
        return new WP_REST_Response(
            array(
                'authenticated' => true,
                'email' => $body['email'] ?? null,
                'client_id' => $body['client_id'] ?? null
            ),
            200
        );
    }
    
    return new WP_REST_Response(
        array('authenticated' => false),
        401
    );
}
