<?php

/**
 * Admin Interface
 *
 * @package Spin_Wheel
 */

// Exit if accessed directly
if (!defined('ABSPATH')) {
    exit;
}

/**
 * SWP_Admin Class
 */
// The "swp" hook prefix below is the plugin's established, documented extension
// API (shared with the Spin Wheel Pro add-on) and is kept for compatibility.
// phpcs:disable WordPress.NamingConventions.PrefixAllGlobals
class SWP_Admin
{

    /**
     * Instance
     *
     * @var SWP_Admin
     */
    private static $instance = null;

    /**
     * Get instance
     *
     * @return SWP_Admin
     */
    public static function instance()
    {
        if (is_null(self::$instance)) {
            self::$instance = new self();
        }
        return self::$instance;
    }

    /**
     * Constructor
     */
    private function __construct()
    {
        add_action('admin_menu', [$this, 'add_submenu_pages'], 25);
        add_action('admin_enqueue_scripts', [$this, 'enqueue_assets']);
        add_filter('manage_swp_wheel_posts_columns', [$this, 'add_columns']);
        add_action('manage_swp_wheel_posts_custom_column', [$this, 'render_columns'], 10, 2);
        
        // Disable metabox drag and drop
        add_action('admin_head', [$this, 'disable_metabox_drag_drop']);
        
        // AJAX handlers
        add_action('wp_ajax_swp_save_settings', [$this, 'ajax_save_settings']);
        // Note: the swp_run_cleanup_now action (manual database cleanup) is
        // provided by the Spin Wheel Pro add-on.
    }
    
    /**
     * Disable metabox drag and drop
     */
    public function disable_metabox_drag_drop()
    {
        global $post_type;
        
        if ($post_type === 'swp_wheel') {
            ?>
            <style>
                /* Disable metabox drag and drop */
                #normal-sortables .postbox,
                #side-sortables .postbox,
                #acf_after_title-sortables .postbox {
                    cursor: default !important;
                }
                
                #normal-sortables .postbox .hndle,
                #side-sortables .postbox .hndle,
                #acf_after_title-sortables .postbox .hndle {
                    cursor: default !important;
                }
                
                /* Hide drag handle if visible */
                #normal-sortables .postbox .handle-order-higher,
                #normal-sortables .postbox .handle-order-lower,
                #side-sortables .postbox .handle-order-higher,
                #side-sortables .postbox .handle-order-lower,
                #acf_after_title-sortables .postbox .handle-order-higher,
                #acf_after_title-sortables .postbox .handle-order-lower {
                    display: none !important;
                }
                
                /* Prevent any sortable styling */
                .ui-sortable-helper {
                    display: none !important;
                }
                
                .ui-sortable-placeholder {
                    display: none !important;
                }
            </style>
            <script>
                jQuery(document).ready(function($) {
                    // Completely disable WordPress metabox sorting
                    
                    // Method 1: Destroy sortable immediately
                    function disableSortables() {
                        $('.meta-box-sortables').each(function() {
                            if ($(this).hasClass('ui-sortable')) {
                                $(this).sortable('destroy');
                            }
                            // Prevent pointer events
                            $(this).css('pointer-events', 'auto');
                            $(this).find('.postbox').css('cursor', 'default');
                            $(this).find('.hndle').css('cursor', 'default');
                        });
                    }
                    
                    // Disable immediately
                    disableSortables();
                    
                    // Method 2: Override postboxes.init if it exists
                    if (typeof postboxes !== 'undefined' && typeof postboxes.init === 'function') {
                        var originalInit = postboxes.init;
                        postboxes.init = function() {
                            // Call original but then destroy sortables
                            originalInit.apply(this, arguments);
                            setTimeout(disableSortables, 0);
                        };
                    }
                    
                    // Method 3: Disable after any postbox operations
                    $(document).on('postbox-toggled postboxes-columnchange', function() {
                        disableSortables();
                    });
                    
                    // Method 4: Prevent sortable from working at all
                    $('.meta-box-sortables').on('sortstart', function(event, ui) {
                        event.stopImmediatePropagation();
                        return false;
                    });
                    
                    // Method 5: Disable after a short delay (catches late initialization)
                    setTimeout(disableSortables, 100);
                    setTimeout(disableSortables, 500);
                    setTimeout(disableSortables, 1000);
                });
            </script>
            <?php
        }
    }

    /**
     * Add submenu pages
     */
    public function add_submenu_pages()
    {
        add_submenu_page(
            'edit.php?post_type=swp_wheel',
            __('Settings', 'spin-wheel'),
            __('Settings', 'spin-wheel'),
            'manage_options',
            'swp-settings',
            [$this, 'render_settings_page']
        );

        /**
         * Register CRM Webhook immediately after Settings (Spin Wheel Pro or free teaser).
         */
        do_action('swp_register_crm_webhook_submenu');
    }

    /**
     * Enqueue admin assets
     *
     * @param string $hook Current page hook
     */
    public function enqueue_assets($hook)
    {
        global $post_type;

        if ($post_type === 'swp_wheel' || strpos($hook, 'swp-') !== false) {
            wp_enqueue_style('wp-color-picker');
            wp_enqueue_media();

            wp_enqueue_style('swp-admin-style', SPIN_WHEEL_URL . 'admin/css/admin.css', [], SPIN_WHEEL_VERSION);

            // Use modern admin JS for wheel editor
            if ($post_type === 'swp_wheel' && in_array($hook, ['post.php', 'post-new.php'])) {
                // Enqueue lucky-canvas for preview
                wp_enqueue_script('lucky-canvas', SPIN_WHEEL_URL . 'public/js/lucky-canvas.umd.min.js', [], '1.7.27', true);

                wp_enqueue_script('swp-admin-modern', SPIN_WHEEL_URL . 'admin/js/admin-modern.js', ['jquery', 'wp-color-picker', 'lucky-canvas'], SPIN_WHEEL_VERSION, true);

                wp_localize_script('swp-admin-modern', 'swpAdminData', [
                    'ajaxUrl'                 => admin_url('admin-ajax.php'),
                    'nonce'                   => wp_create_nonce('swp_admin_nonce'),
                    'pluginUrl'               => SPIN_WHEEL_URL,
                    'confirmDelete'           => __('Are you sure you want to delete this prize?', 'spin-wheel'),
                    'selectWinner'            => __('Select as Winner', 'spin-wheel'),
                    'confirmWinner'           => __('Are you sure you want to select this entry as winner?', 'spin-wheel'),
                    'copied'                  => __('Copied!', 'spin-wheel'),
                    'processing'              => __('Processing...', 'spin-wheel'),
                    'winner'                  => __('Winner', 'spin-wheel'),
                    'winnerSelectedNotified'  => __('Winner selected and notified successfully!', 'spin-wheel'),
                    'errorSelectingWinner'    => __('Error selecting winner', 'spin-wheel'),
                    'errorOccurred'           => __('An error occurred', 'spin-wheel'),
                    'luckyCanvasNotLoaded'    => __('Lucky Canvas library not loaded.', 'spin-wheel'),
                    'addPrizesToPreview'      => __('Add prizes to see preview', 'spin-wheel'),
                    'previewError'             => __('Preview error. Check console.', 'spin-wheel'),
                    'prizeLabelFallback'      => __('Prize', 'spin-wheel'),
                    /* translators: %s: prize number */
                    'prizeNumber'             => __('Prize #%s', 'spin-wheel'),
                    /* translators: %s: current total percentage */
                    'prizeProbabilityWarning'  => __('Warning: Prize probabilities should total 100%%. Current total: %s%%', 'spin-wheel'),
                    'confirmContinueAnyway'   => __('Do you want to continue anyway?', 'spin-wheel'),
                ]);
            } else {
                // Use legacy admin JS for other pages
                wp_enqueue_script('swp-admin-script', SPIN_WHEEL_URL . 'admin/js/admin.js', ['jquery', 'wp-color-picker'], SPIN_WHEEL_VERSION, true);

                wp_localize_script('swp-admin-script', 'swpAdminData', [
                    'ajaxUrl'                 => admin_url('admin-ajax.php'),
                    'nonce'                   => wp_create_nonce('swp_admin_nonce'),
                    'confirmDelete'           => __('Are you sure you want to delete this item?', 'spin-wheel'),
                    'selectWinner'            => __('Select as Winner', 'spin-wheel'),
                    'confirmWinner'           => __('Are you sure you want to select this entry as winner?', 'spin-wheel'),
                    'copied'                  => __('Copied!', 'spin-wheel'),
                    'processing'              => __('Processing...', 'spin-wheel'),
                    'winner'                  => __('Winner', 'spin-wheel'),
                    'winnerSelectedNotified'  => __('Winner selected and notified successfully!', 'spin-wheel'),
                    'errorSelectingWinner'    => __('Error selecting winner', 'spin-wheel'),
                    /* translators: %s: prize number */
                    'prizeNumber'             => __('Prize #%s', 'spin-wheel'),
                ]);
            }
        }
    }

    /**
     * Add custom columns
     *
     * @param array $columns Existing columns
     * @return array Modified columns
     */
    public function add_columns($columns)
    {
        $new_columns = [];

        foreach ($columns as $key => $value) {
            $new_columns[$key] = $value;

            if ($key === 'title') {
                $new_columns['wheel_type'] = __('Wheel Type', 'spin-wheel');
                $new_columns['entries']    = __('Entries', 'spin-wheel');
                $new_columns['shortcode']  = __('Shortcode', 'spin-wheel');
            }
        }

        return $new_columns;
    }

    /**
     * Render custom columns
     *
     * @param string $column Column name
     * @param int $post_id Post ID
     */
    public function render_columns($column, $post_id)
    {
        switch ($column) {
            case 'wheel_type':
                $wheel_type = get_post_meta($post_id, '_swp_wheel_type', true);
                $types = [
                    'big_wheel'    => __('Big Wheel', 'spin-wheel'),
                    'nine_squares' => __('N Squares', 'spin-wheel'),
                    'slot_machine' => __('Slot Machine', 'spin-wheel'),
                ];
                echo isset($types[$wheel_type]) ? esc_html($types[$wheel_type]) : '—';
                break;

            case 'entries':
                $db = SWP_Database::instance();
                $count = $db->count_entries($post_id);
                $url = add_query_arg([
                    'page'     => 'swp-entries',
                    'wheel_id' => $post_id,
                ], admin_url('edit.php?post_type=swp_wheel'));
                printf('<a href="%s">%d</a>', esc_url($url), (int) $count);
                break;

            case 'shortcode':
                $shortcode = '[spin_wheel id="' . $post_id . '"]';
                echo '<div class="swp-shortcode-column">';
                echo '<code class="swp-shortcode-text">' . esc_html($shortcode) . '</code>';
                echo '<button type="button" class="button button-small swp-copy-btn" data-clipboard-text="' . esc_attr($shortcode) . '" title="' . esc_attr__('Copy shortcode', 'spin-wheel') . '">';
                echo '<span class="dashicons dashicons-admin-page"></span>';
                echo '</button>';
                echo '</div>';
                break;
        }
    }

    /**
     * Render settings page
     */
    public function render_settings_page()
    {
        if (!current_user_can('manage_options')) {
            return;
        }

        $settings = get_option('swp_settings', []);

        // Set defaults
        $defaults = [
            // General
            'default_wheel_mode'            => 'instant',
            'enable_animations'             => 1,
            // Email
            'enable_winner_notifications'   => 1,
            'enable_admin_notifications'    => 0,
            'admin_email'                   => get_option('admin_email'),
            'from_name'                     => get_bloginfo('name'),
            'from_email'                    => get_option('admin_email'),
            'default_email_subject'         => 'Congratulations! You Won!',
            'default_email_message'         => '<p>Hi {user_name},</p>
<p>Congratulations! You have won <strong>{prize_label}</strong> from our {wheel_name} spin wheel!</p>
<p>Your prize code is: <strong>{prize_code}</strong></p>
<p>Thank you for participating!</p>
<p>Best regards,<br>' . get_bloginfo('name') . '</p>',
            // Display
            'default_button_text'           => 'SPIN',
            'default_submit_button_text'    => 'Spin Now!',
            'default_width'                 => 460,
            'default_height'                => 460,
            'enable_confetti'               => 1,
            // Database
            // Performance
            'enable_caching'                => 0,
            'cache_duration'                => 3600,
            'lazy_load_assets'              => 0,
            'minify_output'                 => 0,
        ];

        $settings = wp_parse_args($settings, $defaults);

        include SPIN_WHEEL_PATH . 'admin/templates/settings.php';
    }

    /**
     * AJAX handler for saving settings
     */
    public function ajax_save_settings()
    {
        // Check nonce
        check_ajax_referer('swp_settings_nonce', 'nonce');

        // Check permissions
        if (!current_user_can('manage_options')) {
            wp_send_json_error([
                'message' => __('You do not have permission to save settings.', 'spin-wheel')
            ]);
        }

        // Sanitize and save settings
        $settings = [
            // General Settings
            'default_wheel_mode'        => sanitize_text_field( wp_unslash( $_POST['default_wheel_mode'] ?? 'instant' ) ),
            'enable_animations'         => isset($_POST['enable_animations']) ? 1 : 0,

            // Email Settings
            'enable_winner_notifications' => isset($_POST['enable_winner_notifications']) ? 1 : 0,
            'enable_admin_notifications' => isset($_POST['enable_admin_notifications']) ? 1 : 0,
            'admin_email'               => sanitize_email( wp_unslash( $_POST['admin_email'] ?? get_option('admin_email') ) ),
            'from_name'                 => sanitize_text_field( wp_unslash( $_POST['from_name'] ?? get_bloginfo('name') ) ),
            'from_email'                => sanitize_email( wp_unslash( $_POST['from_email'] ?? get_option('admin_email') ) ),
            'default_email_subject'     => sanitize_text_field( wp_unslash( $_POST['default_email_subject'] ?? 'Congratulations! You Won!' ) ),
            'default_email_message'     => wp_kses_post( wp_unslash( $_POST['default_email_message'] ?? '' ) ),


            // Display Settings
            'default_button_text'       => sanitize_text_field( wp_unslash( $_POST['default_button_text'] ?? 'SPIN' ) ),
            'default_submit_button_text' => sanitize_text_field( wp_unslash( $_POST['default_submit_button_text'] ?? 'Spin Now!' ) ),
            'default_width'             => intval($_POST['default_width'] ?? 460),
            'default_height'            => intval($_POST['default_height'] ?? 460),
            'enable_confetti'           => isset($_POST['enable_confetti']) ? 1 : 0,

            // Database Settings

            // Performance Settings
            'enable_caching'            => isset($_POST['enable_caching']) ? 1 : 0,
            'cache_duration'            => intval($_POST['cache_duration'] ?? 3600),
            'lazy_load_assets'          => isset($_POST['lazy_load_assets']) ? 1 : 0,
            'minify_output'             => isset($_POST['minify_output']) ? 1 : 0,
        ];

        /**
         * Let add-ons (e.g. Spin Wheel Pro) sanitize and persist their own settings
         * fields alongside the core ones.
         *
         * @param array $settings Sanitized core settings about to be saved.
         * @param array $raw      Raw, slashed $_POST payload.
         */
        $settings = apply_filters('swp_save_settings', $settings, wp_unslash($_POST));
        if (!is_array($settings)) {
            $settings = [];
        }

        // Update settings
        $updated = update_option('swp_settings', $settings);

        if ($updated || get_option('swp_settings') === $settings) {
            wp_send_json_success([
                'message' => __('Settings saved successfully!', 'spin-wheel')
            ]);
        } else {
            wp_send_json_error([
                'message' => __('Failed to save settings. Please try again.', 'spin-wheel')
            ]);
        }
    }
    
}


// phpcs:enable WordPress.NamingConventions.PrefixAllGlobals
