<?php
if (!defined('ABSPATH')) exit;

// Add main settings menu page
if (!defined('AFB_AUTOMATOR_EMBEDDED')) {
    add_action('admin_menu', function () {
        add_menu_page('Asana Automator', 'Asana Automator', 'manage_options', 'asana-automator', 'asana_automator_main_settings_page', 'dashicons-hammer', 90);

        add_submenu_page('asana-automator', 'API Settings', 'API Settings', 'manage_options', 'asana-automator', 'asana_automator_main_settings_page');

        add_submenu_page(
            'asana-automator',
            'Asana Automator Diagnostics',
            'Diagnostics',
            'manage_options',
            'asana-automator-diagnostics',
            'asana_automator_diagnostic_report'
        );
    });
}

// Register workspace settings
add_action('admin_init', function () {
    register_setting('asana_automator_main', 'asana_workspace_gid');
    register_setting('asana_automator_main', 'asana_workspace_name');
});

// Main settings page UI
function asana_automator_main_settings_page() {
    $tokens = asana_automator_get_pat_accounts();
    $workspace_gid = asana_automator_get_workspace_gid();
    $workspace_name = asana_automator_get_workspace_name();
    ?>
    <div class="wrap">
        <h1>🔐 Asana API Settings</h1>
        <?php if (defined('AFB_AUTOMATOR_EMBEDDED')) : ?>
            <p>Asana Automator is now embedded in Asana Form Builder.</p>
            <p>Manage PAT accounts from <a href="<?php echo esc_url(admin_url('admin.php?page=asana-accounts')); ?>">Asana Accounts</a>. Existing legacy PAT options are still read for compatibility.</p>
        <?php endif; ?>
        <h2>Saved PAT Accounts</h2>
        <?php if (!empty($tokens)) : ?>
            <table class="widefat striped" style="max-width:600px;">
                <thead>
                    <tr><th>Label</th><th>Token Prefix</th><th>Actions</th></tr>
                </thead>
                <tbody>
                <?php foreach ($tokens as $label => $token): ?>
                    <tr>
                        <td><?php echo esc_html($label); ?></td>
                        <td><?php echo esc_html(substr($token, 0, 12)) . '...'; ?></td>
                        <td><?php echo defined('AFB_AUTOMATOR_EMBEDDED') ? 'Managed in Asana Accounts' : 'Legacy'; ?></td>
                    </tr>
                <?php endforeach; ?>
                </tbody>
            </table>
        <?php else: ?>
            <p>No PATs saved yet.</p>
        <?php endif; ?>

        <?php if (!defined('AFB_AUTOMATOR_EMBEDDED')) : ?>
            <hr style="margin: 30px 0;">

            <h2>Add New PAT</h2>
            <form method="post">
                <table class="form-table">
                    <tr><th><label>Label</label></th><td><input type="text" name="asana_new_pat_label" class="regular-text" required /></td></tr>
                    <tr><th><label>Token</label></th><td><input type="text" name="asana_new_pat_token" class="regular-text" required /></td></tr>
                </table>
                <?php submit_button('➕ Save New PAT'); ?>
            </form>
        <?php endif; ?>

        <hr style="margin: 40px 0;">

        <h2>🌐 Workspace Selection</h2>
        <p><button type="button" class="button button-secondary" id="fetch-workspaces">🔄 Fetch Workspaces</button></p>
        <?php if ($workspace_gid && $workspace_name): ?>
            <p><strong>Selected Workspace:</strong> <?php echo esc_html($workspace_name); ?> (GID: <?php echo esc_html($workspace_gid); ?>)</p>
        <?php elseif ($workspace_gid): ?>
            <p><strong>Selected Workspace:</strong> <?php echo esc_html($workspace_gid); ?></p>
        <?php else: ?>
            <p>No workspace selected.</p>
        <?php endif; ?>

        <div id="workspace-selector" style="margin-top:10px;"></div>
        <script>
        (function($){
            $('#fetch-workspaces').on('click', function(e){
                e.preventDefault();
                $.get(ajaxurl, { action: 'get_asana_workspaces' }, function(response){
                    const $selector = $('#workspace-selector').empty();
                    if (!response.success || response.data.length === 0) {
                        $selector.html('<p style="color:red;">No workspaces found. Ensure your PATs are valid.</p>');
                        return;
                    }
                    if (response.data.length === 1) {
                        $.post(ajaxurl, {
                            action: 'save_asana_workspace',
                            workspace_gid: response.data[0].gid,
                            workspace_name: response.data[0].name
                        }, () => location.reload());
                    } else {
                        $selector.append('<select id="workspace-pick" class="regular-text"></select>');
                        $.each(response.data, (i, ws) => {
                            $('#workspace-pick').append(`<option value="${ws.gid}">${ws.name}</option>`);
                        });
                        $selector.append('<br><br><button id="save-workspace" class="button button-primary">Save Workspace</button>');
                        $('#save-workspace').on('click', () => {
                            const gid = $('#workspace-pick').val();
                            const name = $('#workspace-pick option:selected').text();
                            $.post(ajaxurl, {
                                action: 'save_asana_workspace',
                                workspace_gid: gid,
                                workspace_name: name
                            }, () => location.reload());
                        });
                    }
                });
            });
        })(jQuery);
        </script>
    </div>
    <?php
}
