<?php

declare(strict_types=1);
if (!defined('WPINC')) {
    die();
}
/**
 * Class CPEPAI_Admin_Service
 * Handles the admin page registration and rendering.
 */
class CPEPAI_Admin_Service
{
    /**
     * Action name for deactivate and delete all data.
     */
    private const ACTION_DEACTIVATE_DELETE_DATA = 'cpepai_deactivate_delete_data';

    /**
     * Register the service.
     *
     * @return void
     */
    public function register(): void
    {
        add_action('admin_menu', [$this, 'register_admin_menu']);
        add_action('admin_init', [$this, 'handle_deactivate_delete_data']);
        add_action('admin_enqueue_scripts', [$this, 'enqueue_plugins_page_assets']);
        add_action('admin_footer-plugins.php', [$this, 'render_deactivate_confirm_modal']);
        add_action('network_admin_footer-plugins.php', [$this, 'render_deactivate_confirm_modal']);
    }

    /**
     * Register the admin menu item.
     *
     * @return void
     */
    public function register_admin_menu(): void
    {
        add_menu_page(
            __('Editorial Planner', 'cplanteam-ai-content-planner'),
            __('Editorial Planner', 'cplanteam-ai-content-planner'),
            'edit_posts',
            'cplanteam-ai-content-planner',
            [$this, 'render_admin_page'],
            'dashicons-calendar-alt',
            30
        );
    }

    /**
     * Render the admin page.
     *
     * @return void
     */
    public function render_admin_page(): void
    {
        echo '<div id="cpepai-app"></div>';
    }

    /**
     * Enqueue assets for the Plugins page.
     *
     * @return void
     */
    public function enqueue_plugins_page_assets(): void
    {
        $screen = get_current_screen();
        if (!$screen || !in_array($screen->id, ['plugins', 'plugins-network'], true)) {
            return;
        }
        $plugin_basename = plugin_basename(CPEPAI_PLUGIN_DIR . 'cplanteam-ai-content-planner.php');
        $url = wp_nonce_url(
            add_query_arg(
                [
                    'action' => self::ACTION_DEACTIVATE_DELETE_DATA,
                    'plugin' => $plugin_basename
                ],
                admin_url('plugins.php')
            ),
            'cpepai_deactivate_delete_data_' . $plugin_basename
        );
        wp_enqueue_script('jquery');
        wp_localize_script('jquery', 'cpepaiDeactivateDelete', [
            'pluginBasename' => $plugin_basename,
            'url' => $url,
            'label' => __('Deactivate and delete all data', 'cplanteam-ai-content-planner'),
            'confirmMessage' => __(
                'This will permanently delete all content plans, tasks, logs, and plugin settings. This action cannot be undone. Are you sure?',
                'cplanteam-ai-content-planner'
            )
        ]);
        wp_add_inline_script('jquery', $this->get_deactivate_confirm_script());
    }

    /**
     * Render the deactivate and delete confirmation modal.
     *
     * @return void
     */
    public function render_deactivate_confirm_modal(): void
    {
        ?>
        <div id="cpepai-deactivate-modal" style="display:none;position:fixed;inset:0;background:rgba(0,0,0,0.5);z-index:100000;align-items:center;justify-content:center;">
            <div style="background:#fff;padding:20px;max-width:400px;border-radius:4px;box-shadow:0 4px 20px rgba(0,0,0,0.15);">
                <p id="cpepai-deactivate-modal-message" style="margin:0 0 20px;"></p>
                <div style="display:flex;gap:10px;justify-content:flex-end;">
                    <button type="button" class="button" id="cpepai-deactivate-modal-cancel"><?php esc_html_e(
                        'Cancel',
                        'cplanteam-ai-content-planner'
                    ); ?></button>
                    <button type="button" class="button button-primary" id="cpepai-deactivate-modal-confirm" style="background:#000;border-color:#000;"><?php esc_html_e(
                        'Deactivate and delete all data',
                        'cplanteam-ai-content-planner'
                    ); ?></button>
                </div>
            </div>
        </div>
        <?php
    }

    /**
     * Get the inline script for the deactivate confirmation modal.
     *
     * @return string
     */
    private function get_deactivate_confirm_script(): string
    {
        return <<<'JS'
        (function() {
            var config = typeof cpepaiDeactivateDelete !== 'undefined' ? cpepaiDeactivateDelete : {};
            var pluginBasename = config.pluginBasename || '';
            var url = config.url || '';
            var label = config.label || 'Deactivate and delete all data';
            var message = config.confirmMessage || 'This will permanently delete all content plans, tasks, logs, and plugin settings. This action cannot be undone. Are you sure?';

            function injectLink() {
                if (!pluginBasename || !url) return;
                var row = document.querySelector('#the-list tr[data-plugin="' + pluginBasename + '"]');
                if (!row) return;
                var deactivateSpan = row.querySelector('.deactivate');
                if (!deactivateSpan || row.querySelector('.cpepai-deactivate-delete-wrap')) return;
                var wrap = document.createElement('span');
                wrap.className = 'cpepai-deactivate-delete-wrap';
                var link = document.createElement('a');
                link.href = url;
                link.className = 'cpepai-deactivate-delete-trigger';
                link.setAttribute('data-url', url);
                link.setAttribute('aria-label', label);
                link.textContent = label;
                wrap.appendChild(link);
                wrap.appendChild(document.createTextNode(' | '));
                var next = deactivateSpan.nextSibling && deactivateSpan.nextSibling.nextSibling;
                deactivateSpan.parentNode.insertBefore(wrap, next || deactivateSpan.nextSibling);
            }

            if (document.readyState === 'loading') {
                document.addEventListener('DOMContentLoaded', injectLink);
            } else {
                injectLink();
            }

            document.addEventListener('click', function(e) {
                var el = e.target.closest('.cpepai-deactivate-delete-trigger');
                if (!el) return;
                e.preventDefault();
                e.stopPropagation();
                e.stopImmediatePropagation();
                var modal = document.getElementById('cpepai-deactivate-modal');
                var msg = document.getElementById('cpepai-deactivate-modal-message');
                var cancelBtn = document.getElementById('cpepai-deactivate-modal-cancel');
                var confirmBtn = document.getElementById('cpepai-deactivate-modal-confirm');
                if (!modal || !msg || !cancelBtn || !confirmBtn) return;
                msg.textContent = message;
                modal.style.display = 'flex';
                var linkUrl = el.getAttribute('data-url');
                var onClose = function() { modal.style.display = 'none'; };
                cancelBtn.onclick = onClose;
                confirmBtn.onclick = function() { window.location.href = linkUrl; };
                modal.onclick = function(ev) { if (ev.target === modal) onClose(); };
            }, true);
        })();
        JS;
    }

    /**
     * Handle the "Deactivate and delete all data" action.
     *
     * @return void
     */
    public function handle_deactivate_delete_data(): void
    {
        if (!isset($_GET['action']) || $_GET['action'] !== self::ACTION_DEACTIVATE_DELETE_DATA) {
            return;
        }

        if (!isset($_GET['plugin']) || !isset($_GET['_wpnonce'])) {
            return;
        }

        $plugin_basename = sanitize_text_field(wp_unslash($_GET['plugin']));

        if (
            !wp_verify_nonce(
                sanitize_text_field(wp_unslash($_GET['_wpnonce'])),
                'cpepai_deactivate_delete_data_' . $plugin_basename
            )
        ) {
            wp_die(esc_html__('Security check failed.', 'cplanteam-ai-content-planner'));
        }

        if (!current_user_can('activate_plugins')) {
            wp_die(esc_html__('You do not have permission to perform this action.', 'cplanteam-ai-content-planner'));
        }

        if (plugin_basename(CPEPAI_PLUGIN_DIR . 'cplanteam-ai-content-planner.php') !== $plugin_basename) {
            wp_die(esc_html__('Invalid plugin.', 'cplanteam-ai-content-planner'));
        }

        $database_service = new CPEPAI_Database_Service();
        $database_service->delete_all_plugin_data();

        $options_service = new CPEPAI_Options_Service();
        $options_service->delete_all_options();

        require_once ABSPATH . 'wp-admin/includes/plugin.php';
        deactivate_plugins($plugin_basename, true);

        wp_safe_redirect(
            add_query_arg(
                [
                    'deactivate' => 'true',
                    'plugin' => $plugin_basename
                ],
                self_admin_url('plugins.php')
            )
        );
        exit();
    }
}
