<?php
/**
 * navigate_to — open the URL the user just asked for in plain language.
 *
 * Returns a `target_url` the rail interprets as a same-tab navigation. This
 * is the escape valve for the page-target safety rules: when the user says
 * "bring me to my home page" from the Dashboard, the co-pilot used to refuse
 * with "open the page you want to work on first". That gate exists for
 * page-modification tools, not for navigation intent.
 *
 * Auto-confirmed in the rail (see AUTO_CONFIRM_TOOLS in assets/js/rail.js).
 */
if (!defined('ABSPATH')) exit;

function swcp_tool_navigate_to($input, $ctx) {
    $target = isset($input['target']) ? trim((string) $input['target']) : '';
    $mode   = isset($input['mode']) ? strtolower(trim((string) $input['mode'])) : 'view';
    // Default: only auto-create on edit-intent navigation. View-intent never
    // creates pages (the user expected something to be there, not to mint one).
    $create_if_missing = array_key_exists('create_if_missing', $input)
        ? (bool) $input['create_if_missing']
        : ($mode === 'edit' || $mode === 'editor');
    if ($target === '') {
        return ['ok' => false, 'message' => 'I need a destination. Try "home", "dashboard", "media", or a page title.'];
    }

    $key = strtolower($target);
    $aliases = [
        'home'           => 'site_home',
        'homepage'       => 'site_home',
        'home page'      => 'site_home',
        'front page'     => 'site_home',
        'front'          => 'site_home',
        'website'        => 'site_home',
        'site'           => 'site_home',
        'my site'        => 'site_home',
        'my website'     => 'site_home',
        'dashboard'      => 'admin_dashboard',
        'wp-admin'       => 'admin_dashboard',
        'admin'          => 'admin_dashboard',
        'pages'          => 'admin_pages',
        'all pages'      => 'admin_pages',
        'posts'          => 'admin_posts',
        'all posts'      => 'admin_posts',
        'media'          => 'admin_media',
        'media library'  => 'admin_media',
        'settings'       => 'admin_settings',
        'plugins'        => 'admin_plugins',
        'themes'         => 'admin_themes',
        'appearance'     => 'admin_themes',
    ];
    if (isset($aliases[$key])) $key = $aliases[$key];

    switch ($key) {
        case 'site_home':
            return swcp_navigate_result(home_url('/'), get_bloginfo('name') . ' — homepage', 'Opening your homepage.');
        case 'admin_dashboard':
            return swcp_navigate_result(admin_url(), 'WordPress Dashboard', 'Back to the dashboard.');
        case 'admin_pages':
            return swcp_navigate_result(admin_url('edit.php?post_type=page'), 'All Pages', 'Opening Pages.');
        case 'admin_posts':
            return swcp_navigate_result(admin_url('edit.php'), 'All Posts', 'Opening Posts.');
        case 'admin_media':
            return swcp_navigate_result(admin_url('upload.php'), 'Media Library', 'Opening Media.');
        case 'admin_settings':
            return swcp_navigate_result(admin_url('options-general.php'), 'Settings', 'Opening Settings.');
        case 'admin_plugins':
            return swcp_navigate_result(admin_url('plugins.php'), 'Plugins', 'Opening Plugins.');
        case 'admin_themes':
            return swcp_navigate_result(admin_url('themes.php'), 'Themes', 'Opening Themes.');
    }

    // Treat as a page/post title and try the same fuzzy resolver as the
    // edit tools. Match → navigate. Ambiguous → return candidates so the
    // chat can disambiguate.
    $current_post_id = isset($ctx['post_id']) ? (int) $ctx['post_id'] : 0;
    $resolved = swcp_resolve_or_error($target, $current_post_id);
    if (is_array($resolved) && !empty($resolved['ambiguous'])) {
        return $resolved;
    }
    if ($resolved instanceof WP_Post) {
        $title = get_the_title($resolved);
        if ($mode === 'edit' || $mode === 'editor') {
            $edit = get_edit_post_link($resolved->ID, '');
            return swcp_navigate_result($edit, 'Editor: ' . $title, 'Opening the editor for "' . $title . '".');
        }
        return swcp_navigate_result(get_permalink($resolved->ID), $title, 'Opening "' . $title . '".');
    }

    // No existing page matched. For edit-intent we can mint a fresh draft so
    // the conversation can continue ON the page the user wanted to design.
    if ($create_if_missing && ($mode === 'edit' || $mode === 'editor')) {
        $clean_title = sanitize_text_field($target);
        $new_id = wp_insert_post([
            'post_type'    => 'page',
            'post_status'  => 'draft',
            'post_title'   => $clean_title,
            'post_content' => '',
        ]);
        if (!is_wp_error($new_id) && $new_id) {
            update_post_meta($new_id, '_swcp_auto_created_via_navigate', 1);
            $edit_url = get_edit_post_link((int) $new_id, '');
            $result = swcp_navigate_result($edit_url, 'New draft: ' . $clean_title, 'Starting a fresh "' . $clean_title . '" page for you.');
            $result['created']    = true;
            $result['post_id']    = (int) $new_id;
            $result['page_title'] = $clean_title;
            return $result;
        }
    }

    return [
        'ok'      => false,
        'message' => 'I could not find anything called "' . $target . '". Try a page title, or "home", "dashboard", "pages", "media", "settings".',
    ];
}

function swcp_navigate_result($url, $label, $message) {
    return [
        'ok'           => true,
        'action'       => 'navigate',
        'target_url'   => (string) $url,
        'target_label' => (string) $label,
        'message'      => (string) $message,
    ];
}
