<?php
/**
 * Plugin Name: Mark Bogner's Story Prompts
 * Description: Generate AI-powered writing prompts based on selected story genres using the Anthropic Claude API.
 * Version: 1.2.0
 * Author: Mark Bogner
 * License: GPL-2.0+
 */

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

define( 'ASPG_VERSION', '1.0.0' );
define( 'ASPG_PLUGIN_DIR', plugin_dir_path( __FILE__ ) );
define( 'ASPG_PLUGIN_URL', plugin_dir_url( __FILE__ ) );

// ── Admin settings page ────────────────────────────────────────────────────

add_action( 'admin_menu', 'aspg_add_settings_page' );
function aspg_add_settings_page() {
    add_options_page(
        'Mark Bogner\'s Story Prompts Settings',
        'Story Prompt AI',
        'manage_options',
        'aspg-settings',
        'aspg_render_settings_page'
    );
}

add_action( 'admin_init', 'aspg_register_settings' );
function aspg_register_settings() {
    register_setting( 'aspg_settings_group', 'aspg_anthropic_api_key', [
        'sanitize_callback' => 'sanitize_text_field',
    ]);

    add_settings_section( 'aspg_main_section', 'API Configuration', null, 'aspg-settings' );

    add_settings_field(
        'aspg_anthropic_api_key',
        'Anthropic API Key',
        'aspg_api_key_field_cb',
        'aspg-settings',
        'aspg_main_section'
    );
}

function aspg_api_key_field_cb() {
    $key = get_option( 'aspg_anthropic_api_key', '' );
    echo '<input type="password" name="aspg_anthropic_api_key" value="' . esc_attr( $key ) . '" class="regular-text" placeholder="sk-ant-..." />';
    echo '<p class="description">Enter your <a href="https://console.anthropic.com/" target="_blank">Anthropic API key</a>. It is stored securely in the database.</p>';
}

function aspg_render_settings_page() {
    ?>
    <div class="wrap">
        <h1>Mark Bogner's Story Prompts — Settings</h1>
        <form method="post" action="options.php">
            <?php
            settings_fields( 'aspg_settings_group' );
            do_settings_sections( 'aspg-settings' );
            submit_button( 'Save Settings' );
            ?>
        </form>
        <hr>
        <h2>Shortcode Usage</h2>
        <p>Paste the shortcode below anywhere on a page or post:</p>
        <code>[story_prompt_generator]</code>
        <p>You can also pass optional attributes:</p>
        <ul style="list-style:disc;margin-left:1.5em;">
            <li><code>title="Your Title"</code> — Override the widget heading.</li>
            <li><code>button_text="Generate"</code> — Override the button label.</li>
        </ul>
        <p>Example: <code>[story_prompt_generator title="Spark Your Story" button_text="Inspire Me"]</code></p>
    </div>
    <?php
}

// ── Shortcode ──────────────────────────────────────────────────────────────

add_shortcode( 'story_prompt_generator', 'aspg_render_shortcode' );
function aspg_render_shortcode( $atts ) {
    $atts = shortcode_atts([
        'title'       => 'Story Prompt Generator',
        'button_text' => 'Generate Prompt',
    ], $atts, 'story_prompt_generator' );

    wp_enqueue_style(  'aspg-style',  ASPG_PLUGIN_URL . 'assets/style.css',  [], ASPG_VERSION );
    wp_enqueue_script( 'aspg-script', ASPG_PLUGIN_URL . 'assets/script.js', [], ASPG_VERSION, true );

    wp_localize_script( 'aspg-script', 'ASPG', [
        'ajax_url' => admin_url( 'admin-ajax.php' ),
        'nonce'    => wp_create_nonce( 'aspg_generate_nonce' ),
    ]);

    $genres = aspg_get_genres();

    ob_start();
    ?>
    <div class="aspg-widget" role="region" aria-label="Story Prompt Generator">
        <div class="aspg-inner">
            <div class="aspg-header">
                <div class="aspg-quill-icon" aria-hidden="true">
                    <svg viewBox="0 0 48 48" fill="none" xmlns="http://www.w3.org/2000/svg">
                        <path d="M38 6C28 10 18 22 14 38" stroke="currentColor" stroke-width="2.5" stroke-linecap="round"/>
                        <path d="M38 6C34 16 26 24 14 38" stroke="currentColor" stroke-width="1.2" stroke-linecap="round" stroke-dasharray="2 3"/>
                        <path d="M14 38 L11 43 L17 40 Z" fill="currentColor"/>
                        <path d="M38 6 C42 2 46 4 44 8 C40 8 38 10 38 6Z" fill="currentColor" opacity="0.5"/>
                    </svg>
                </div>
                <h2 class="aspg-title"><?php echo esc_html( $atts['title'] ); ?></h2>
                <p class="aspg-subtitle">Pick a genre and let my brain craft your next story spark.</p>
            </div>

            <div class="aspg-form">
                <div class="aspg-select-wrapper">
                    <label for="aspg-genre" class="aspg-label">Story Genre</label>
                    <div class="aspg-select-box">
                        <select id="aspg-genre" name="genre" aria-label="Select a story genre">
                            <option value="">— Choose a genre —</option>
                            <?php foreach ( $genres as $value => $label ) : ?>
                                <option value="<?php echo esc_attr( $value ); ?>"><?php echo esc_html( $label ); ?></option>
                            <?php endforeach; ?>
                        </select>
                        <span class="aspg-chevron" aria-hidden="true">
                            <svg viewBox="0 0 20 20" fill="none"><path d="M5 7.5L10 12.5L15 7.5" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/></svg>
                        </span>
                    </div>
                </div>

                <button id="aspg-generate-btn" class="aspg-btn" type="button" disabled>
                    <span class="aspg-btn-text"><?php echo esc_html( $atts['button_text'] ); ?></span>
                    <span class="aspg-btn-icon" aria-hidden="true">
                        <svg viewBox="0 0 20 20" fill="none"><path d="M4 10h12M11 5l5 5-5 5" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/></svg>
                    </span>
                </button>
            </div>

            <div class="aspg-result-area" aria-live="polite" aria-atomic="true">
                <div class="aspg-result-idle">
                    <span class="aspg-dot"></span><span class="aspg-dot"></span><span class="aspg-dot"></span>
                    <p>Your prompt will appear here.</p>
                </div>
                <div class="aspg-result-loading" hidden>
                    <div class="aspg-spinner" role="status" aria-label="Generating prompt…">
                        <svg viewBox="0 0 50 50"><circle cx="25" cy="25" r="20" fill="none" stroke="currentColor" stroke-width="4" stroke-dasharray="90 60"/></svg>
                    </div>
                    <p>Crafting your prompt…</p>
                </div>
                <div class="aspg-result-output" hidden>
                    <div class="aspg-genre-badge" id="aspg-genre-badge"></div>
                    <blockquote class="aspg-prompt-text" id="aspg-prompt-text"></blockquote>
                    <button class="aspg-copy-btn" id="aspg-copy-btn" type="button" aria-label="Copy prompt to clipboard">
                        <svg viewBox="0 0 20 20" fill="none"><rect x="7" y="7" width="10" height="12" rx="2" stroke="currentColor" stroke-width="1.8"/><path d="M13 7V5a2 2 0 00-2-2H5a2 2 0 00-2 2v10a2 2 0 002 2h2" stroke="currentColor" stroke-width="1.8" stroke-linecap="round"/></svg>
                        Copy
                    </button>
                </div>
                <div class="aspg-result-error" hidden>
                    <span class="aspg-error-icon" aria-hidden="true">⚠</span>
                    <p id="aspg-error-msg"></p>
                </div>
            </div>
        </div>

        <p class="aspg-attribution">Writing prompts generated by the mind of Mark Bogner.</p>
    </div>
    <?php
    return ob_get_clean();
}

// ── Genre list ─────────────────────────────────────────────────────────────

function aspg_get_genres() {
    return [
        'literary-fiction'  => 'Literary Fiction',
        'fantasy'           => 'Fantasy',
        'science-fiction'   => 'Science Fiction',
        'horror'            => 'Horror',
        'mystery'           => 'Mystery & Thriller',
        'romance'           => 'Romance',
        'historical-fiction'=> 'Historical Fiction',
        'adventure'         => 'Adventure',
        'crime'             => 'Crime & Noir',
        'magical-realism'   => 'Magical Realism',
        'dystopian'         => 'Dystopian',
        'comedy'            => 'Comedy & Satire',
        'western'           => 'Western',
        'young-adult'       => 'Young Adult',
        'childrens'         => 'Children\'s Story',
    ];
}

// ── AJAX handler ───────────────────────────────────────────────────────────

add_action( 'wp_ajax_aspg_generate',        'aspg_ajax_generate' );
add_action( 'wp_ajax_nopriv_aspg_generate', 'aspg_ajax_generate' );

function aspg_ajax_generate() {
    check_ajax_referer( 'aspg_generate_nonce', 'nonce' );

    $genre = isset( $_POST['genre'] ) ? sanitize_text_field( wp_unslash( $_POST['genre'] ) ) : '';

    if ( empty( $genre ) ) {
        wp_send_json_error( [ 'message' => 'Please select a genre.' ] );
    }

    $genres      = aspg_get_genres();
    $genre_label = isset( $genres[ $genre ] ) ? $genres[ $genre ] : $genre;

    $api_key = get_option( 'aspg_anthropic_api_key', '' );
    if ( empty( $api_key ) ) {
        wp_send_json_error( [ 'message' => 'API key not configured. Please contact the site administrator.' ] );
    }

    $prompt = sprintf(
        'You are a creative writing coach. Generate a single compelling writing prompt (1–2 sentences) for the "%s" genre. ' .
        'The prompt should be vivid, specific, and immediately inspire a writer. ' .
        'Return ONLY the prompt text — no labels, no quotes, no preamble.',
        $genre_label
    );

    $response = wp_remote_post( 'https://api.anthropic.com/v1/messages', [
        'timeout' => 30,
        'headers' => [
            'Content-Type'      => 'application/json',
            'x-api-key'         => $api_key,
            'anthropic-version' => '2023-06-01',
        ],
        'body' => wp_json_encode([
            'model'      => 'claude-sonnet-4-20250514',
            'max_tokens' => 200,
            'messages'   => [
                [ 'role' => 'user', 'content' => $prompt ],
            ],
        ]),
    ]);

    if ( is_wp_error( $response ) ) {
        wp_send_json_error( [ 'message' => 'Network error: ' . $response->get_error_message() ] );
    }

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

    if ( 200 !== (int) $code ) {
        $err = isset( $body['error']['message'] ) ? $body['error']['message'] : 'Unknown API error.';
        wp_send_json_error( [ 'message' => $err ] );
    }

    $text = isset( $body['content'][0]['text'] ) ? trim( $body['content'][0]['text'] ) : '';

    if ( empty( $text ) ) {
        wp_send_json_error( [ 'message' => 'The AI returned an empty response. Please try again.' ] );
    }

    wp_send_json_success([
        'prompt' => $text,
        'genre'  => $genre_label,
    ]);
}
