<?php
// Exit if accessed directly
if (!defined('ABSPATH')) exit;

// Add the Command Center admin page
add_action('admin_menu', function () {
    add_submenu_page(
        'diyseo_settings_page',
        'Command Center',
        'Command Center',
        'manage_options',
        'diyseo-command-center',
        'diyseo_render_command_center'
    );
});

// Render the Command Center page
function diyseo_render_command_center() {
    ?>
    <style>
        /* [Keep your existing CSS styles here - omitted for brevity, paste them back in] */
        html, body { background: #0b0c2a !important; }
        .wrap h1, h2, h3, label, span, p, div, input, textarea { color: #f2f2f2 !important; }
        #diyseo-command-center-root { padding: 30px; }
        .diyseo-header-bar { text-align: center; margin-bottom: 40px; }
        .diyseo-logo { width: 160px; margin: 0 auto 10px; display: block; }
        .diyseo-nav { font-size: 18px; font-weight: 600; background: rgba(255, 255, 255, 0.08); padding: 10px 24px; border-radius: 12px; display: inline-block; color: white; }
        .glass-card { background: rgba(255, 255, 255, 0.05); backdrop-filter: blur(18px); border-radius: 16px; border: 1px solid rgba(255, 255, 255, 0.1); padding: 20px; margin-bottom: 30px; }
        .card-row { display: flex; gap: 30px; flex-wrap: wrap; }
        input[type="text"], input[type="file"], textarea { background: rgba(255, 255, 255, 0.06); border: 1px solid rgba(255, 255, 255, 0.15); border-radius: 8px; color: white; padding: 8px 12px; width: 100%; margin-bottom: 12px; font-size: 14px; }
        button { background: linear-gradient(135deg, #d127ff, #9740ff); color: white; border: none; padding: 8px 16px; font-weight: 600; border-radius: 8px; cursor: pointer; }
        #cc-item-list { list-style: none; padding: 0; margin: 0; }
        #cc-item-list li { background: rgba(255, 255, 255, 0.05); padding: 10px 14px; border-radius: 10px; margin-bottom: 10px; display: flex; justify-content: space-between; align-items: center; font-size: 14px; color: #fff; }
        #cc-item-list button { background: transparent; color: #ff5e5e; border: none; font-size: 14px; cursor: pointer; }
    </style>

    <div id="diyseo-command-center-root">
        <div class="diyseo-header-bar">
             <img class="diyseo-logo" src="<?php echo esc_url(plugins_url('logo.png', __FILE__)); ?>" alt="DIYSEO Logo">
            <div class="diyseo-nav">Command Center (Local Mode)</div>
        </div>

        <div class="glass-card">
            <h2>📁 Your Command Center</h2>
            <ul id="cc-item-list"><li>Loading...</li></ul>
        </div>

        <div class="card-row">
            <div class="glass-card" style="flex: 1">
               <h3>📎 Upload Reference File</h3>
               <p style="color: #ccc; font-size: 13px; margin: -10px 0 10px;">Supported: .csv, .txt, .json (Text extracted locally)</p>
               <form id="cc-upload-form">
                    <input type="file" name="file" accept=".csv,.txt,.json" required />
                    <input type="text" name="title" placeholder="Title for file..." required />
                    <button type="submit">Save File Data</button>
                </form>
            </div>

            <div class="glass-card" style="flex: 1">
                <h3>🧠 Add Note</h3>
                <form id="cc-note-form">
                    <input type="text" name="title" placeholder="Note title..." required />
                    <textarea name="content" placeholder="Write your instruction..." rows="6" required></textarea>
                    <button type="submit">Save Note</button>
                </form>
            </div>
        </div>
    </div>
    <?php
}

// ------------------------------------------
// LOCAL AJAX HANDLERS (Replacing External API)
// ------------------------------------------

// 1. Get Items
add_action('wp_ajax_diyseo_cc_get_items', 'diyseo_cc_get_items');
function diyseo_cc_get_items() {
    check_ajax_referer('diyseo_cc_nonce', 'nonce');
    $items = get_option('diyseo_cc_items', array());
    // Return array reversed so newest is first
    wp_send_json_success(array_reverse($items));
}

// 2. Save Item (Note or File Content)
add_action('wp_ajax_diyseo_cc_save_item', 'diyseo_cc_save_item');
function diyseo_cc_save_item() {
    check_ajax_referer('diyseo_cc_nonce', 'nonce');

    $title = sanitize_text_field($_POST['title']);
    // We allow some HTML/Lines in content, but generally sanitize
    $content = sanitize_textarea_field($_POST['content']);
    $type = sanitize_text_field($_POST['type']); // 'note' or 'file'
    $file_type = isset($_POST['file_type']) ? sanitize_text_field($_POST['file_type']) : '';

    if (empty($title) || empty($content)) {
        wp_send_json_error('Missing fields');
    }

    $new_item = array(
        'id' => uniqid('cc_'), // Generate a unique ID
        'title' => $title,
        'content' => $content, // For files, this is the extracted text sent from JS
        'type' => $type,
        'file_type' => $file_type,
        'date' => current_time('mysql')
    );

    $items = get_option('diyseo_cc_items', array());
    $items[] = $new_item;
    
    update_option('diyseo_cc_items', $items);
    wp_send_json_success();
}

// 3. Delete Item
add_action('wp_ajax_diyseo_cc_delete_item', 'diyseo_cc_delete_item');
function diyseo_cc_delete_item() {
    check_ajax_referer('diyseo_cc_nonce', 'nonce');
    $id_to_delete = sanitize_text_field($_POST['id']);

    $items = get_option('diyseo_cc_items', array());
    
    // Filter out the item with the matching ID
    $updated_items = array_filter($items, function($item) use ($id_to_delete) {
        return $item['id'] !== $id_to_delete;
    });

    // Reset array keys
    $updated_items = array_values($updated_items);

    update_option('diyseo_cc_items', $updated_items);
    wp_send_json_success();
}

// Enqueue Scripts
add_action('admin_enqueue_scripts', function ($hook) {
    if (strpos($hook, 'diyseo-command-center') === false) return;
    $version = defined('DIYSEO_PLUGIN_VERSION') ? DIYSEO_PLUGIN_VERSION : '1.0.0';
    
    // Using your existing JS file location
    wp_enqueue_script('diyseo-command-center-js', plugin_dir_url(__FILE__) . 'js/diyseo-command-center.js', ['jquery'], $version, true);

    wp_localize_script('diyseo-command-center-js', 'DIYSEO_CC', [
        'ajaxurl' => admin_url('admin-ajax.php'),
        'nonce'   => wp_create_nonce('diyseo_cc_nonce')
    ]);
});