<?php

namespace _121Digital\Connect\Admin\Pages;

use _121Digital\Connect\Core\Environment;
use _121Digital\Connect\Core\Plugin;

class Pages
{
    public function register(): void
    {
        // Use post-type-specific hooks to avoid duplicate calls from generic hooks.
        add_filter('manage_edit-page_columns', [ $this, 'modify_columns' ]);

        add_action('load-edit.php', [ $this, 'on_page_load' ]);

        // Render for the 'page' post type only (prevents double-calls).
        add_action('manage_page_posts_custom_column', [ $this, 'render_custom_column' ], 10, 2);
        add_action('admin_enqueue_scripts', [$this, 'enque_page_scripts']);

        // Rename the default "Edit" link and clean up duplicate edit links from other plugins
        // (run early so we can remove competing actions before other filters are applied).
        add_filter('page_row_actions', [ $this, 'filter_row_actions' ], 5, 2);
        add_filter('page_row_actions', [ $this, 'rename_edit_link' ], 10, 2);
        add_filter('page_row_actions', [ $this, 'remove_quick_edit_link' ], 10, 2);
        add_filter('page_row_actions', [ $this, 'rename_trash_link' ], 10, 2);
        add_filter(' page_row_actions', [$this, 'rename_edit_link'], 10, 2);
        add_filter('get_edit_post_link', [$this, 'alter_edit_post_link'], 10, 3);
    }

    public function modify_columns(array $columns): array
    {
        $new = [];
        foreach ($columns as $key => $label) {
            // Copy existing column
            $new[ $key ] = $label;

            // Insert our edit button column immediately after the title column so the
            // page title remains the left-most column and the button sits directly
            // to the right of the title (aligned per row).
            if ('title' === $key) {
                $new['sc_edit'] = __('Edit', '121-connect');
            }
        }
        return $new;
    }

    public function on_page_load(): void
    {
        if (
            isset($_GET['post_type']) &&
            $_GET['post_type'] === 'page' &&
            isset($_POST['action']) &&
                      $_POST['action'] === 'create_custom_page'
        ) {
            if (!current_user_can('edit_pages') || !isset($_POST['_wpnonce']) || !wp_verify_nonce($_POST['_wpnonce'], 'create_custom_page')) {
                Plugin::die('Unauthorized request. Action has been blocked.');
            }

            // check for create page form submission from frontend...
            $page_title = sanitize_text_field($_POST['page-title'] ?? '');
            if (empty($page_title)) {
                Plugin::die('Page title is required to create a new page.');
            }

            // check if we have a page layout provided...
            $template_type = sanitize_text_field($_POST['template-type'] ?? '');
            $new_page = [
                'post_title'   => wp_strip_all_tags($page_title),
                'post_content' => '',
                'post_status'  => 'publish',
                'post_type'    => 'page',
            ];

            // create the new page and redirect to the elementor editor...
            $new_page_id = wp_insert_post($new_page);
            if (is_wp_error($new_page_id)) {
                Plugin::die('Error creating new page');
            }

            // redirect to elementor editor if active...
            $edit_url = get_edit_post_link($new_page_id, '');
            if (Environment::isElementorActive()) {
                $edit_url = \Elementor\Plugin::$instance->documents->get($new_page_id)->get_edit_url();
            }
            wp_redirect($edit_url);
            exit;
        }
    }

    public function enque_page_scripts($hook): void
    {
        if ($hook === 'edit.php' && isset($_GET['post_type']) && $_GET['post_type'] === 'page') {
            $handle = 'sc-pages-js';
            wp_enqueue_script($handle, plugin_dir_url(__FILE__) . 'js/Pages.js', [ 'jquery' ], defined('SC_PLUGIN_VERSION') ? SC_PLUGIN_VERSION : false, true);

            // Pass the nonce (and optionally the AJAX URL) to your JS
            wp_localize_script($handle, 'createPageForm', [
                    'ajax_url' => admin_url('admin-ajax.php'),
                    'nonce'    => wp_create_nonce('create_custom_page'),
            ]);
        }
    }

    public function render_custom_column(string $column, int $post_id): void
    {
        switch ($column) {
            case 'sc_edit':
                $elementor_url = get_edit_post_link($post_id, ''); // default edit link
                $pageEditor_url = $elementor_url .= '&edit_settings=1';

                if (Environment::isElementorActive()) {
                    $elementor_url = \Elementor\Plugin::$instance->documents->get($post_id)->get_edit_url();
                }
                echo '<a class="button button-primary" href="' . esc_url($elementor_url) . '" target="_blank">'
                    . esc_html__('Edit Page', '121-connect')
                    . '</a>';
                echo '<a style="margin-left: 5px;" class="button" href="' . esc_url($pageEditor_url) . '">'
                    . esc_html__('Page Settings', '121-connect')
                    . '</a>';

                break;
        }
    }

    public function rename_edit_link(array $actions, \WP_Post $post): array
    {
        if (isset($actions['edit'])) {
            // Change anchor text and href to include edit_settings=1
            $actions['edit'] = preg_replace_callback(
                '/<a\s+(.*?)href=["\']([^"\']*)["\'](.*?)>(.*?)<\/a>/i',
                function ($matches) use ($post) {
                    $url = add_query_arg('edit_settings', '1', $matches[2]);
                    return '<a ' . $matches[1] . 'href="' . esc_url($url) . '"' . $matches[3] . '>Page Options</a>';
                },
                $actions['edit']
            );
        }
        return $actions;
    }

    public function alter_edit_post_link($url, $post_id, $context)
    {
        $post = get_post($post_id);
        if ($post && $post->post_type === 'page' && $context === 'display') {
            $url = add_query_arg('edit_settings', '1', $url);
        }
        return $url;
    }

    public function remove_quick_edit_link(array $actions, \WP_Post $post): array
    {
        if (isset($actions['inline hide-if-no-js'])) {
            unset($actions['inline hide-if-no-js']);
        }
        return $actions;
    }

    public function remove_edit_with_elementor_link(array $actions, \WP_Post $post): array
    {
        if (isset($actions['edit_with_elementor'])) {
            unset($actions['edit_with_elementor']);
        }
        return $actions;
    }

    public function remove_edit_with_builder_link(array $actions, \WP_Post $post): array
    {
        if (isset($actions['edit_with_builder'])) {
            unset($actions['edit_with_builder']);
        }
        return $actions;
    }

    public function rename_trash_link(array $actions, \WP_Post $post): array
    {
        if (isset($actions['trash'])) {
            $actions['trash'] = str_replace('Trash', 'Delete Page', $actions['trash']);
        }
        return $actions;
    }

    /**
     * Remove duplicate/competing row action edit links from other plugins.
     *
     * This unsets keys known to produce an extra "Edit" button in the row actions
     * so our custom column button doesn't appear to be duplicated.
     *
     * @param array $actions Current row actions
     * @param \WP_Post $post The post being rendered
     * @return array Filtered actions
     */
    public function filter_row_actions(array $actions, \WP_Post $post): array
    {
        // Compute our editor URL (the same URL used in the custom column button).
        $our_url = get_edit_post_link($post->ID, '');
        if ($our_url && Environment::isElementorActive()) {
            try {
                $doc = \Elementor\Plugin::$instance->documents->get($post->ID);
                if ($doc) {
                    $our_url = $doc->get_edit_url();
                }
            } catch (\Throwable $e) {
                // If Elementor isn't available or document retrieval fails, fall back to WP edit link.
            }
        }

        if ($our_url) {
            $our_norm = esc_url_raw($our_url);
            $our_parts = parse_url($our_norm);
            $our_comp = '';
            if (isset($our_parts['host'])) {
                $our_comp .= $our_parts['host'];
            }
            if (isset($our_parts['path'])) {
                $our_comp .= untrailingslashit($our_parts['path']);
            }

            // Remove any action whose href points to the same host+path (ignore query params).
            foreach ($actions as $key => $html) {
                if (preg_match('/href=["\']([^"\']+)["\']/', $html, $m)) {
                    $href_raw = esc_url_raw($m[1]);
                    $href_parts = parse_url($href_raw);
                    $href_comp = '';
                    if (isset($href_parts['host'])) {
                        $href_comp .= $href_parts['host'];
                    }
                    if (isset($href_parts['path'])) {
                        $href_comp .= untrailingslashit($href_parts['path']);
                    }

                    if ($href_comp && $href_comp === $our_comp) {
                        unset($actions[ $key ]);
                        continue;
                    }
                }
            }
        }

        // As a fallback, also remove known vendor keys which can duplicate the edit action.
        $known_keys = [ 'edit_with_elementor', 'elementor_edit', 'edit_with_builder' ];
        foreach ($known_keys as $k) {
            if (isset($actions[ $k ])) {
                unset($actions[ $k ]);
            }
        }

        return $actions;
    }
}
