<?php
/**
 * Admin page functionality
 */

// Prevent direct access
if (!defined('ABSPATH')) {
    exit;
}

class Seazonify_Admin
{

    public function __construct()
    {
        add_action('admin_menu', array($this, 'add_admin_menu'));
        add_action('admin_init', array($this, 'register_settings'));
        add_action('admin_init', array($this, 'handle_auth_callback'));
        add_action('admin_init', array($this, 'handle_disconnect'));
        add_action('admin_enqueue_scripts', array($this, 'enqueue_admin_assets'));
        add_action('wp_ajax_seazonify_refresh_effects', array($this, 'ajax_refresh_effects'));
        add_action('wp_ajax_seazonify_load_page', array($this, 'ajax_load_page'));
        add_action('wp_ajax_seazonify_search_effects', array($this, 'ajax_search_effects'));

        // Isolated OTP-based onboarding handlers
        add_action('wp_ajax_seazonify_init_connect', array($this, 'ajax_init_connect'));
        add_action('wp_ajax_seazonify_verify_connect', array($this, 'ajax_verify_connect'));
        add_action('wp_ajax_seazonify_complete_registration', array($this, 'ajax_complete_registration'));



        // Isolate Seazonify dashboard from 3rd party notices
        add_action('admin_head', array($this, 'remove_global_notices'), 1);
        
        // Add global styling for the admin sidebar menu icon (Compliant method)
        add_action('admin_enqueue_scripts', array($this, 'enqueue_global_admin_styles'));

        // Add settings link to plugins page
        add_filter('plugin_action_links_' . plugin_basename(SEAZONIFY_PLUGIN_DIR . 'seazonify.php'), array($this, 'add_plugin_action_links'));
    }

    /**
     * Ensure the Seazonify menu icon maintains proper size across all WordPress admin pages
     * Uses wp_add_inline_style for 100% compliance
     */
    public function enqueue_global_admin_styles()
    {
        wp_register_style('seazonify-admin-global', false, array(), SEAZONIFY_VERSION);
        wp_enqueue_style('seazonify-admin-global');
        wp_add_inline_style('seazonify-admin-global', '#toplevel_page_seazonify .wp-menu-image img { width: 20px !important; height: auto !important; padding-top: 7px !important; }');
    }

    /**
     * Remove global admin notices from Seazonify pages to ensure clean UI
     */
    public function remove_global_notices()
    {
        $screen = get_current_screen();
        if (!$screen || (strpos($screen->id, 'seazonify') === false)) {
            return;
        }

        // Global notices often clutter premium dashboard experiences
        remove_all_actions('admin_notices');
        remove_all_actions('all_admin_notices');
        remove_all_actions('network_admin_notices');
        remove_all_actions('user_admin_notices');
    }

    /**
     * Add settings link to the plugin action links
     */
    public function add_plugin_action_links($links)
    {
        $settings_link = '<a href="' . admin_url('admin.php?page=seazonify-settings') . '">' . __('Settings', 'seazonify') . '</a>';
        array_unshift($links, $settings_link);
        return $links;
    }

    /**
     * Enqueue Admin Assets - CSS and JS
     */
    public function enqueue_admin_assets($hook)
    {
        // Only load on Seazonify admin pages
        if (strpos($hook, 'seazonify') === false) {
            return;
        }

        wp_enqueue_style(
            'seazonify-admin-css',
            SEAZONIFY_PLUGIN_URL . 'admin/css/admin.css',
            array(),
            filemtime(SEAZONIFY_PLUGIN_DIR . 'admin/css/admin.css')
        );

        wp_enqueue_script(
            'seazonify-admin-js',
            SEAZONIFY_PLUGIN_URL . 'admin/js/admin.js',
            array('jquery'),
            SEAZONIFY_VERSION,
            true
        );

        wp_localize_script('seazonify-admin-js', 'seazonifyAdmin', array(
            'ajax_url'      => admin_url('admin-ajax.php'),
            'nonce'         => wp_create_nonce('seazonify_admin'),
            'dashboard_url' => admin_url('admin.php?page=seazonify&connected=1')
        ));
    }

    /**
     * Get connection URL for Seazonify App
     */
    public static function get_connect_url()
    {
        $params = array(
            'platform' => 'wordpress',
            'url' => get_site_url(),
            'callback' => admin_url('admin.php?page=seazonify&_wpnonce=' . wp_create_nonce('seazonify_auth_callback')),
        );
        return add_query_arg($params, SEAZONIFY_APP_URL . '/connect');
    }

    /**
     * Handle the auth callback from Seazonify
     */
    public function handle_auth_callback()
    {
        if (!current_user_can('manage_options')) {
            return;
        }

        if (isset($_GET['seazonify_token']) && isset($_GET['page']) && $_GET['page'] === 'seazonify') {
            // Verify Nonce
            if (!isset($_GET['_wpnonce']) || !wp_verify_nonce(sanitize_text_field(wp_unslash($_GET['_wpnonce'])), 'seazonify_auth_callback')) {
                wp_die(esc_html__('Security check failed', 'seazonify'));
            }

            $token = sanitize_text_field(wp_unslash($_GET['seazonify_token']));
            $settings = get_option('seazonify_settings', array());
            $settings['app_token'] = $token;

            update_option('seazonify_settings', $settings);
            delete_transient('seazonify_connection_status');

            // Redirect to clean the URL
            wp_safe_redirect(admin_url('admin.php?page=seazonify&connected=1'));
            exit;
        }
    }

    /**
     * Handle disconnect action
     */
    public function handle_disconnect()
    {
        if (!current_user_can('manage_options')) {
            return;
        }

        if (isset($_POST['seazonify_disconnect']) && check_admin_referer('seazonify_disconnect_action', 'seazonify_disconnect_nonce')) {
            $settings = get_option('seazonify_settings', array());
            $token = isset($settings['app_token']) ? $settings['app_token'] : '';

            // Optional: Tell backend to deactivate
            if (!empty($token)) {
                wp_remote_post(SEAZONIFY_APP_URL . '/api/plugin/v1/disconnect', array(
                    'headers' => array(
                        'Authorization' => 'Bearer ' . $token,
                    ),
                ));
            }

            // Remove token from settings
            unset($settings['app_token']);
            update_option('seazonify_settings', $settings);

            // CRITICAL: Clear connection status cache immediately
            delete_transient('seazonify_connection_status');

            wp_safe_redirect(admin_url('admin.php?page=seazonify&disconnected=1'));
            exit;
        }
    }

    /**
     * Get connection status from Seazonify API
     */
    public function get_connection_status()
    {
        $settings = get_option('seazonify_settings', array());
        $token = isset($settings['app_token']) ? $settings['app_token'] : '';

        if (empty($token)) {
            return false;
        }

        // Use transient to cache the status for 10 minutes
        $cache_key = 'seazonify_connection_status';
        $status = get_transient($cache_key);

        if (false !== $status) {
            return $status;
        }

        $response = wp_remote_get(SEAZONIFY_APP_URL . '/api/plugin/v1/status', array(
            'headers' => array(
                'Authorization' => 'Bearer ' . $token,
            ),
            'timeout' => 15,
        ));

        if (is_wp_error($response)) {
            return false;
        }

        $body = wp_remote_retrieve_body($response);
        $data = json_decode($body, true);

        if (isset($data['success']) && $data['success']) {
            set_transient($cache_key, $data, 600); // 10 minutes cache
            return $data;
        }

        return false;
    }

    /**
     * Add admin menu
     */
    public function add_admin_menu()
    {
        // Main Menu
        add_menu_page(
            __('Seazonify', 'seazonify'),
            __('Seazonify', 'seazonify'),
            'manage_options',
            'seazonify',
            array($this, 'render_dashboard'),
            SEAZONIFY_LOGO_URL, // Official Seazonify Logo
            80 // Moved down from 25 to respect WordPress hierarchy
        );

        // Dashboard (matches main)
        add_submenu_page(
            'seazonify',
            __('Dashboard', 'seazonify'),
            __('Dashboard', 'seazonify'),
            'manage_options',
            'seazonify',
            array($this, 'render_dashboard')
        );

        // Explore Effects
        add_submenu_page(
            'seazonify',
            __('Explore Effects', 'seazonify'),
            __('Explore Effects', 'seazonify'),
            'manage_options',
            'seazonify-explore',
            array($this, 'render_explore')
        );

        // Auto Seazonify
        add_submenu_page(
            'seazonify',
            __('Auto Seazonify', 'seazonify'),
            __('Auto Seazonify', 'seazonify'),
            'manage_options',
            'seazonify-auto',
            array($this, 'render_auto_seazonify')
        );

        // Settings
        add_submenu_page(
            'seazonify',
            __('General Settings', 'seazonify'),
            __('Settings', 'seazonify'),
            'manage_options',
            'seazonify-settings',
            array($this, 'render_settings_page')
        );
    }

    /**
     * Register settings
     */
    public function register_settings()
    {
        register_setting('seazonify_settings_group', 'seazonify_settings', array(
            'sanitize_callback' => array($this, 'sanitize_settings'),
            'show_in_rest' => false,
        ));
    }

    /**
     * Sanitize settings
     */
    public function sanitize_settings($input)
    {
        $old = get_option('seazonify_settings', array());
        $sanitized = is_array($old) ? $old : array();

        // Detect if this is a form submission for our settings group
        // phpcs:ignore WordPress.Security.NonceVerification.Missing
        $is_seazonify_submit = (isset($_POST['option_page']) && sanitize_key(wp_unslash($_POST['option_page'])) === 'seazonify_settings_group');

        // General Section
        if (isset($input['enabled'])) {
            $sanitized['enabled'] = !empty($input['enabled']);
        } elseif ($is_seazonify_submit) {
            $sanitized['enabled'] = false;
        }

        if (isset($input['show_controller'])) {
            $sanitized['show_controller'] = !empty($input['show_controller']);
        } elseif ($is_seazonify_submit) {
            $sanitized['show_controller'] = false;
        }

        if (isset($input['cache_duration'])) {
            $sanitized['cache_duration'] = absint($input['cache_duration']);
        }

        // Visuals
        if (isset($input['visual_effect'])) {
            $sanitized['visual_effect'] = sanitize_text_field($input['visual_effect']);
        }
        if (isset($input['audio_effect'])) {
            $sanitized['audio_effect'] = sanitize_text_field($input['audio_effect']);
        }
        if (isset($input['combo_effect'])) {
            $sanitized['combo_effect'] = sanitize_text_field($input['combo_effect']);
        }

        // Visibility
        if (isset($input['display_on'])) {
            $sanitized['display_on'] = sanitize_text_field($input['display_on']);
        }

        if (isset($input['include_pages'])) {
            $sanitized['include_pages'] = is_array($input['include_pages']) ? array_map('absint', $input['include_pages']) : array();
        } elseif ($is_seazonify_submit) {
            $sanitized['include_pages'] = array();
        }

        // CRITICAL: Preserve app_token. 
        // Only update if a non-empty token is explicitly provided in $input.
        if (!empty($input['app_token'])) {
            $sanitized['app_token'] = sanitize_text_field($input['app_token']);
        }

        return $sanitized;
    }

    /**
     * AJAX: Refresh effects
     */
    public function ajax_refresh_effects()
    {
        check_ajax_referer('seazonify_admin', 'nonce');
        Seazonify_Rate_Limiter::limit_or_continue('refresh_effects', 10, 60);

        if (!current_user_can('manage_options')) {
            wp_send_json_error(array('message' => __('Permission denied', 'seazonify')));
        }

        Seazonify_Effects::clear_cache();
        $effects = Seazonify_Effects::get_initial_effects();

        if (is_wp_error($effects)) {
            wp_send_json_error(array('message' => $effects->get_error_message()));
        }

        wp_send_json_success(array(
            'message' => __('Effects refreshed successfully', 'seazonify'),
            'effects' => $effects,
        ));
    }

    /**
     * AJAX: Load more effects (pagination)
     */
    public function ajax_load_page()
    {
        check_ajax_referer('seazonify_admin', 'nonce');

        if (!current_user_can('manage_options')) {
            wp_send_json_error(array('message' => __('Permission denied', 'seazonify')));
        }

        if (!isset($_POST['type']) || !isset($_POST['page'])) {
            wp_send_json_error(array('message' => __('Missing parameters', 'seazonify')));
        }

        $type = sanitize_text_field(wp_unslash($_POST['type']));
        $page = intval(wp_unslash($_POST['page']));

        $page_data = Seazonify_Effects::load_effects_page($type, $page);

        if (is_wp_error($page_data)) {
            wp_send_json_error(array('message' => $page_data->get_error_message()));
        }

        wp_send_json_success(array(
            'effects' => $page_data['effects'],
            'page' => $page_data['page'],
            'total_pages' => $page_data['total_pages'],
            'has_more' => $page < $page_data['total_pages'],
        ));
    }

    /**
     * AJAX: Search effects (100% Local-first filtering)
     */
    public function ajax_search_effects()
    {
        check_ajax_referer('seazonify_admin', 'nonce');

        if (!current_user_can('manage_options')) {
            wp_send_json_error(array('message' => __('Permission denied', 'seazonify')));
        }

        if (!isset($_POST['type']) || !isset($_POST['page']) || !isset($_POST['query'])) {
            wp_send_json_error(array('message' => __('Missing parameters', 'seazonify')));
        }

        $type = sanitize_text_field(wp_unslash($_POST['type']));
        if ($type === 'combos') {
            $type = 'combo';
        }

        $page = intval(wp_unslash($_POST['page']));
        $query = sanitize_text_field(wp_unslash($_POST['query']));

        // All searches are now performed locally to ensure absolute speed and compliance
        $page_data = Seazonify_Effects::load_effects_page($type, $page);

        if (is_wp_error($page_data)) {
            wp_send_json_error(array('message' => $page_data->get_error_message()));
        }

        $results = array();
        foreach ($page_data['effects'] as $effect) {
            $searchable = strtolower($effect['name'] . ' ' . $effect['description'] . ' ' . implode(' ', $effect['tags']));
            if (stripos($searchable, strtolower($query)) !== false) {
                $results[] = $effect;
            }
        }

        wp_send_json_success(array(
            'effects' => $results,
            'page' => $page,
            'total_pages' => $page_data['total_pages'],
            'has_more' => $page < $page_data['total_pages'],
        ));
    }

    /**
     * AJAX: Initialize connection - Step 1
     */
    public function ajax_init_connect()
    {
        check_ajax_referer('seazonify_admin', 'nonce');
        Seazonify_Rate_Limiter::limit_or_continue('init_connect', 5, 60);
        if (!current_user_can('manage_options')) {
            wp_send_json_error(array('message' => __('Permission denied', 'seazonify')));
        }

        $email = isset($_POST['email']) ? sanitize_email(wp_unslash($_POST['email'])) : '';
        if (empty($email)) {
            wp_send_json_error(array('message' => __('Email is required', 'seazonify')));
        }

        $response = wp_remote_post(SEAZONIFY_APP_URL . '/api/plugin/v1/init-connect', array(
            'headers' => array('Content-Type' => 'application/json'),
            'body' => wp_json_encode(array('email' => $email)),
            'timeout' => 15,
        ));

        if (is_wp_error($response)) {
            wp_send_json_error(array('message' => esc_html__('Network Error:', 'seazonify') . ' ' . $response->get_error_message()));
        }

        $code = wp_remote_retrieve_response_code($response);
        $body = wp_remote_retrieve_body($response);
        $data = json_decode($body, true);

        if ($code !== 200) {
            /* translators: %d: Server response code */
            $msg = isset($data['error']) ? $data['error'] : (isset($data['message']) ? $data['message'] : sprintf(esc_html__('Server returned code %d', 'seazonify'), $code));
            wp_send_json_error(array('message' => esc_html__('API Error:', 'seazonify') . ' ' . $msg));
        }

        if (isset($data['success']) && $data['success']) {
            wp_send_json_success($data);
        }
        else {
            wp_send_json_error(array('message' => isset($data['error']) ? $data['error'] : (isset($data['message']) ? $data['message'] : __('Failed to send verification code', 'seazonify'))));
        }
    }

    /**
     * AJAX: Verify OTP - Step 2
     */
    public function ajax_verify_connect()
    {
        check_ajax_referer('seazonify_admin', 'nonce');
        Seazonify_Rate_Limiter::limit_or_continue('verify_connect', 5, 60);
        if (!current_user_can('manage_options')) {
            wp_send_json_error(array('message' => __('Permission denied', 'seazonify')));
        }

        $email = isset($_POST['email']) ? sanitize_email(wp_unslash($_POST['email'])) : '';
        $otp = isset($_POST['otp']) ? sanitize_text_field(wp_unslash($_POST['otp'])) : '';

        if (empty($email) || empty($otp)) {
            wp_send_json_error(array('message' => __('Email and code are required', 'seazonify')));
        }

        $response = wp_remote_post(SEAZONIFY_APP_URL . '/api/plugin/v1/verify-connect', array(
            'headers' => array('Content-Type' => 'application/json'),
            'body' => wp_json_encode(array(
                'email' => $email,
                'otp' => $otp,
                'platform' => 'wordpress',
                'siteUrl' => get_site_url()
            )),
            'timeout' => 15,
        ));

        if (is_wp_error($response)) {
            wp_send_json_error(array('message' => esc_html__('Network Error:', 'seazonify') . ' ' . $response->get_error_message()));
        }

        $code = wp_remote_retrieve_response_code($response);
        $body = wp_remote_retrieve_body($response);
        $data = json_decode($body, true);

        if ($code !== 200) {
            /* translators: %d: Server response code */
            $msg = isset($data['error']) ? $data['error'] : (isset($data['message']) ? $data['message'] : sprintf(esc_html__('Server returned code %d', 'seazonify'), $code));
            wp_send_json_error(array('message' => esc_html__('API Error:', 'seazonify') . ' ' . $msg));
        }

        if (isset($data['success']) && $data['success']) {
            if (isset($data['appToken'])) {
                $this->save_app_token($data['appToken']);
            }
            wp_send_json_success($data);
        }
        else {
            wp_send_json_error(array('message' => isset($data['error']) ? $data['error'] : (isset($data['message']) ? $data['message'] : __('Verification failed', 'seazonify'))));
        }
    }

    /**
     * AJAX: Complete Registration - Step 3
     */
    public function ajax_complete_registration()
    {
        check_ajax_referer('seazonify_admin', 'nonce');
        Seazonify_Rate_Limiter::limit_or_continue('complete_registration', 5, 60);
        if (!current_user_can('manage_options')) {
            wp_send_json_error(array('message' => __('Permission denied', 'seazonify')));
        }

        $email = isset($_POST['email']) ? sanitize_email(wp_unslash($_POST['email'])) : '';
        $name = isset($_POST['name']) ? sanitize_text_field(wp_unslash($_POST['name'])) : '';
        $password = isset($_POST['password']) ? sanitize_text_field(wp_unslash($_POST['password'])) : '';

        if (empty($email) || empty($name) || empty($password)) {
            wp_send_json_error(array('message' => __('All fields are required', 'seazonify')));
        }

        $response = wp_remote_post(SEAZONIFY_APP_URL . '/api/plugin/v1/complete-registration', array(
            'headers' => array('Content-Type' => 'application/json'),
            'body' => wp_json_encode(array(
                'email' => $email,
                'name' => $name,
                'password' => $password,
                'platform' => 'wordpress',
                'siteUrl' => get_site_url()
            )),
            'timeout' => 15,
        ));

        if (is_wp_error($response)) {
            wp_send_json_error(array('message' => $response->get_error_message()));
        }

        $body = wp_remote_retrieve_body($response);
        $data = json_decode($body, true);

        if (isset($data['success']) && $data['success']) {
            if (isset($data['appToken'])) {
                $this->save_app_token($data['appToken']);
            }
            wp_send_json_success($data);
        }
        else {
            wp_send_json_error(array('message' => isset($data['error']) ? $data['error'] : __('Registration failed', 'seazonify')));
        }
    }

    /**
     * Helper to save app token and clear cache
     */
    private function save_app_token($token)
    {
        $settings = get_option('seazonify_settings', array());
        $settings['app_token'] = $token;
        update_option('seazonify_settings', $settings);
        delete_transient('seazonify_connection_status');
    }

    /**
     * Render Dashboard (Main Page)
     */
    public function render_dashboard()
    {
        if (!current_user_can('manage_options')) {
            return;
        }

        $settings = get_option('seazonify_settings', array());
        $is_connected = !empty($this->get_connection_status());

        if (!$is_connected) {
            include SEAZONIFY_PLUGIN_DIR . 'admin/welcome-page.php';
        }
        else {
            include SEAZONIFY_PLUGIN_DIR . 'admin/dashboard-page.php';
        }
    }

    /**
     * Render Explore Effects Page
     */
    public function render_explore()
    {
        if (!current_user_can('manage_options'))
            return;

        $settings = get_option('seazonify_settings', array());
        $is_connected = !empty($this->get_connection_status());

        if (!$is_connected) {
            include SEAZONIFY_PLUGIN_DIR . 'admin/welcome-page.php';
            return;
        }

        include SEAZONIFY_PLUGIN_DIR . 'admin/explore-effects-page.php';
    }

    /**
     * Render Auto Seazonify
     */
    public function render_auto_seazonify()
    {
        if (!current_user_can('manage_options'))
            return;

        $settings = get_option('seazonify_settings', array());
        $is_connected = !empty($this->get_connection_status());

        if (!$is_connected) {
            include SEAZONIFY_PLUGIN_DIR . 'admin/welcome-page.php';
            return;
        }

        include SEAZONIFY_PLUGIN_DIR . 'admin/auto-seazonify-page.php';
    }

    /**
     * Render General Settings
     */
    public function render_settings_page()
    {
        if (!current_user_can('manage_options'))
            return;

        $settings = get_option('seazonify_settings', array());
        $is_connected = !empty($this->get_connection_status());

        if (!$is_connected) {
            include SEAZONIFY_PLUGIN_DIR . 'admin/welcome-page.php';
            return;
        }

        include SEAZONIFY_PLUGIN_DIR . 'admin/settings-page.php';
    }

    /**
     * Maintain compatibility for old calls if any
     */
    public function render_page()
    {
        $this->render_dashboard();
    }
}
