<?php
/**
 * Edit-link redirect for SailWP Co-pilot designed pages.
 *
 * AI-designed pages (post_meta `_swcp_designed = 1`) live as one big HTML
 * blob in a single Gutenberg HTML block. Opening them in the standard
 * Gutenberg editor shows the user a wall of raw markup instead of the
 * actual page design, which is confusing — they expect to see what they
 * just designed, not its source.
 *
 * This class redirects the "Edit" link surface area for those pages to
 * the front-end design-view URL (`?s24-edit=1`) where the Co-pilot rail
 * is already attached and the user can talk to / select / drag elements
 * on the rendered page itself.
 *
 * Gutenberg stays one click away via a new "Code editor" row action, so
 * users who want to inspect or hand-edit the markup are not blocked.
 */
if (!defined('ABSPATH')) exit;

class SailWP_Copilot_Edit_Redirect {

    public function __construct() {
        // Pages list (and any custom post type list using the same hooks).
        add_filter('page_row_actions', [$this, 'rewrite_row_actions'], 10, 2);
        add_filter('post_row_actions', [$this, 'rewrite_row_actions'], 10, 2);

        // Admin-bar "Edit Page" button (visible on the front-end when
        // logged in as editor/admin). Keeps the in-context edit flow
        // consistent with what the row actions do.
        add_action('admin_bar_menu', [$this, 'rewrite_admin_bar_edit'], 90);
    }

    /**
     * Replace the URL inside the existing "Edit" row action and add a
     * sibling "Code editor" action pointing at Gutenberg.
     */
    public function rewrite_row_actions($actions, $post) {
        if (!$post instanceof WP_Post) return $actions;
        if (!get_post_meta($post->ID, '_swcp_designed', true)) return $actions;

        $design_url = $this->design_view_url($post);
        if (!$design_url) return $actions;

        if (isset($actions['edit'])) {
            $actions['edit'] = preg_replace(
                '/href="[^"]*"/',
                'href="' . esc_url($design_url) . '"',
                $actions['edit'],
                1
            );
        }

        // Inject a "Code editor" action right after the (now-rewritten)
        // Edit action so the Gutenberg flow stays one click away.
        $gutenberg_url = admin_url('post.php?post=' . $post->ID . '&action=edit');
        $code_label    = esc_html__('Code editor', 'sailwp-ai-copilot');
        $new = [];
        foreach ($actions as $key => $val) {
            $new[$key] = $val;
            if ($key === 'edit' && !isset($actions['code-editor'])) {
                $new['code-editor'] = '<a href="' . esc_url($gutenberg_url) . '" aria-label="' . esc_attr($code_label) . '">' . $code_label . '</a>';
            }
        }
        return $new;
    }

    /**
     * Front-end admin-bar "Edit Page" — point it at design-view too.
     */
    public function rewrite_admin_bar_edit($wp_admin_bar) {
        if (is_admin()) return; // only on the front-end
        $node = $wp_admin_bar->get_node('edit');
        if (!$node) return;

        $post_id = (int) get_queried_object_id();
        if (!$post_id) return;
        if (!get_post_meta($post_id, '_swcp_designed', true)) return;

        // When viewing the page (no swcp_edit=1) → "Edit Page" takes the
        // user to the editable overlay. When already in edit mode →
        // change the label + URL to "View as visitor" (drops the param).
        $is_editing = isset($_GET['swcp_edit']) && (string) $_GET['swcp_edit'] === '1';
        if ($is_editing) {
            $view_url = get_permalink($post_id);
            if ($view_url) {
                $wp_admin_bar->add_node([
                    'id'    => 'edit',
                    'title' => __('View as visitor', 'sailwp-ai-copilot'),
                    'href'  => $view_url,
                ]);
            }
        } else {
            $design_url = $this->design_view_url(get_post($post_id));
            if ($design_url) {
                $wp_admin_bar->add_node([
                    'id'   => 'edit',
                    'href' => $design_url,
                ]);
            }
        }
    }

    private function design_view_url($post) {
        if (!$post instanceof WP_Post) return '';
        $permalink = get_permalink($post);
        if (!$permalink) return '';
        // swcp_edit=1 → fullpage.php enqueues the inline-edit overlay.
        // Without the param the page renders read-only (view-as-visitor).
        // Joost 2026-05-17 v0.24.2 — was s24-edit, renamed for consistency.
        return add_query_arg('swcp_edit', '1', $permalink);
    }
}
