<?php
/**
 * Admin Panel Functionality
 *
 * @package ReplyIt_Chat_Widget
 */

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

class ReplyIt_Admin {

    /**
     * Single instance
     */
    private static $instance = null;

    /**
     * Get instance
     */
    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_admin_menu']);
        add_action('admin_init', [$this, 'register_settings']);
        add_action('admin_enqueue_scripts', [$this, 'enqueue_admin_assets']);
    }

    /**
     * Add admin menu
     */
    public function add_admin_menu() {
        // Main settings page
        add_options_page(
            __('ReplyIt Chat Widget Settings', 'replyit-chat-widget'),
            __('ReplyIt Chat', 'replyit-chat-widget'),
            'manage_options',
            'replyit-chat-settings',
            [$this, 'settings_page']
        );

        // Analytics submenu
        add_submenu_page(
            'options-general.php',
            __('ReplyIt Analytics', 'replyit-chat-widget'),
            __('ReplyIt Analytics', 'replyit-chat-widget'),
            'manage_options',
            'replyit-chat-analytics',
            [$this, 'analytics_page']
        );

        // WooCommerce settings submenu (only if WooCommerce is active)
        if (class_exists('WooCommerce')) {
            add_submenu_page(
                'options-general.php',
                __('ReplyIt WooCommerce', 'replyit-chat-widget'),
                __('ReplyIt WooCommerce', 'replyit-chat-widget'),
                'manage_options',
                'replyit-chat-woocommerce',
                [$this, 'woocommerce_settings_page']
            );
        }
    }

    /**
     * Register settings
     */
    public function register_settings() {
        // General settings
        register_setting('replyit_chat_settings', 'replyit_widget_id', [
            'sanitize_callback' => 'sanitize_text_field'
        ]);

        register_setting('replyit_chat_settings', 'replyit_api_secret', [
            'sanitize_callback' => 'sanitize_text_field'
        ]);

        register_setting('replyit_chat_settings', 'replyit_api_url', [
            'sanitize_callback' => 'esc_url_raw',
            'default' => 'https://replyit.ai'
        ]);

        register_setting('replyit_chat_settings', 'replyit_enabled', [
            'sanitize_callback' => 'rest_sanitize_boolean',
            'default' => true
        ]);

        // Blog settings
        register_setting('replyit_chat_settings', 'replyit_blog_search_enabled', [
            'sanitize_callback' => 'rest_sanitize_boolean',
            'default' => true
        ]);

        register_setting('replyit_chat_settings', 'replyit_blog_content_enabled', [
            'sanitize_callback' => 'rest_sanitize_boolean',
            'default' => true
        ]);

        // WooCommerce settings
        if (class_exists('WooCommerce')) {
            register_setting('replyit_chat_settings', 'replyit_woocommerce_enabled', [
                'sanitize_callback' => 'rest_sanitize_boolean',
                'default' => true
            ]);

            register_setting('replyit_chat_settings', 'replyit_cart_abandon_time', [
                'sanitize_callback' => 'absint',
                'default' => 3
            ]);

            register_setting('replyit_chat_settings', 'replyit_product_page_delay', [
                'sanitize_callback' => 'absint',
                'default' => 20
            ]);

            register_setting('replyit_chat_settings', 'replyit_checkout_help_enabled', [
                'sanitize_callback' => 'rest_sanitize_boolean',
                'default' => true
            ]);

            register_setting('replyit_chat_settings', 'replyit_order_tracking_enabled', [
                'sanitize_callback' => 'rest_sanitize_boolean',
                'default' => true
            ]);
        }
    }

    /**
     * Enqueue admin assets
     */
    public function enqueue_admin_assets($hook) {
        // Settings page assets
        if ($hook === 'settings_page_replyit-chat-settings') {
            wp_enqueue_style(
                'replyit-admin-style',
                REPLYIT_CHAT_PLUGIN_URL . 'admin/css/admin-style.css',
                [],
                REPLYIT_CHAT_VERSION
            );

            wp_enqueue_script(
                'replyit-admin-script',
                REPLYIT_CHAT_PLUGIN_URL . 'admin/js/admin-script.js',
                ['jquery'],
                REPLYIT_CHAT_VERSION,
                true
            );

            // Add inline styles for settings page
            wp_register_style('replyit-settings-inline', false);
            wp_enqueue_style('replyit-settings-inline');
            $settings_css = '
.replyit-settings-container {
    display: flex;
    gap: 20px;
    margin-top: 20px;
}
.replyit-settings-main {
    flex: 1;
    max-width: 800px;
}
.replyit-settings-sidebar {
    width: 300px;
}
.replyit-settings-sidebar .card {
    margin-bottom: 15px;
}
.replyit-settings-sidebar h3 {
    margin-top: 0;
}
.replyit-settings-sidebar ol,
.replyit-settings-sidebar ul {
    padding-left: 20px;
}
';
            wp_add_inline_style('replyit-settings-inline', $settings_css);
        }

        // WooCommerce settings page assets
        if ($hook === 'settings_page_replyit-chat-woocommerce') {
            wp_register_style('replyit-woo-settings-inline', false);
            wp_enqueue_style('replyit-woo-settings-inline');
            $woo_settings_css = '
.replyit-woocommerce-settings .card {
    margin-bottom: 20px;
}

.replyit-woocommerce-settings .card h2 {
    margin-top: 0;
    padding-bottom: 10px;
    border-bottom: 1px solid #ddd;
}

.replyit-woocommerce-settings .description {
    font-style: italic;
    color: #666;
}
';
            wp_add_inline_style('replyit-woo-settings-inline', $woo_settings_css);
        }

        // Analytics page assets
        if ($hook === 'settings_page_replyit-chat-analytics') {
            // Enqueue Chart.js locally
            wp_enqueue_script(
                'chartjs',
                REPLYIT_CHAT_PLUGIN_URL . 'admin/js/vendor/chart.min.js',
                [],
                '4.5.1',
                true
            );

            // Enqueue analytics script
            wp_enqueue_script(
                'replyit-analytics-script',
                REPLYIT_CHAT_PLUGIN_URL . 'admin/js/analytics.js',
                ['jquery', 'chartjs'],
                REPLYIT_CHAT_VERSION,
                true
            );

            // Pass config to analytics script
            $widget_id = get_option('replyit_widget_id', '');
            $api_secret = get_option('replyit_api_secret', '');
            $api_url = get_option('replyit_api_url', 'https://replyit.ai');
            $period = isset($_GET['period']) ? intval($_GET['period']) : 7;

            wp_localize_script('replyit-analytics-script', 'replyitAnalyticsConfig', [
                'widgetId' => $widget_id,
                'apiSecret' => $api_secret,
                'apiUrl' => $api_url,
                'period' => $period
            ]);

            // Enqueue analytics styles
            wp_register_style('replyit-analytics-style', false);
            wp_enqueue_style('replyit-analytics-style');
            $analytics_css = '
.replyit-analytics-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin: 20px 0;
}

.replyit-period-selector select {
    margin-left: 10px;
}

.replyit-analytics-loading {
    text-align: center;
    padding: 40px;
}

.replyit-stats-grid {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
    gap: 20px;
    margin-bottom: 30px;
}

.replyit-stat-card {
    background: white;
    border: 1px solid #ddd;
    border-radius: 8px;
    padding: 20px;
    display: flex;
    align-items: center;
    gap: 15px;
}

.replyit-stat-icon {
    width: 50px;
    height: 50px;
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 24px;
}

.replyit-stat-content h3 {
    margin: 0;
    font-size: 14px;
    color: #666;
}

.replyit-stat-content p {
    margin: 5px 0 0 0;
    font-size: 28px;
    font-weight: bold;
}

.replyit-chart-container {
    background: white;
    border: 1px solid #ddd;
    border-radius: 8px;
    padding: 20px;
    margin-bottom: 20px;
}

.replyit-conversations-list {
    background: white;
    border: 1px solid #ddd;
    border-radius: 8px;
    padding: 20px;
}

.replyit-conversation-item {
    padding: 15px;
    border-bottom: 1px solid #eee;
}

.replyit-conversation-item:last-child {
    border-bottom: none;
}

.replyit-conversation-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 10px;
}

.replyit-conversation-customer {
    font-weight: bold;
}

.replyit-conversation-time {
    color: #666;
    font-size: 12px;
}

.replyit-conversation-stats {
    display: flex;
    gap: 20px;
    margin-top: 10px;
    font-size: 12px;
    color: #666;
}
';
            wp_add_inline_style('replyit-analytics-style', $analytics_css);
        }
    }

    /**
     * Settings page template
     */
    public function settings_page() {
        if (!current_user_can('manage_options')) {
            return;
        }

        // Handle domain registration
        if (isset($_POST['replyit_register_domain']) && check_admin_referer('replyit_register_domain')) {
            $this->register_domain();
        }

        require_once REPLYIT_CHAT_PLUGIN_DIR . 'admin/views/settings-general.php';
    }

    /**
     * Analytics page template
     */
    public function analytics_page() {
        if (!current_user_can('manage_options')) {
            return;
        }

        require_once REPLYIT_CHAT_PLUGIN_DIR . 'admin/views/analytics.php';
    }

    /**
     * WooCommerce settings page template
     */
    public function woocommerce_settings_page() {
        if (!current_user_can('manage_options')) {
            return;
        }

        require_once REPLYIT_CHAT_PLUGIN_DIR . 'admin/views/settings-woocommerce.php';
    }

    /**
     * Register current domain with ReplyIt API
     */
    private function register_domain() {
        $widget_id = get_option('replyit_widget_id');
        $api_secret = get_option('replyit_api_secret');
        $api_url = get_option('replyit_api_url');

        if (empty($widget_id) || empty($api_secret)) {
            add_settings_error(
                'replyit_messages',
                'replyit_domain_register_error',
                __('Please configure Widget ID and API Secret first.', 'replyit-chat-widget'),
                'error'
            );
            return;
        }

        $site_url = parse_url(get_site_url(), PHP_URL_HOST);

        $response = ReplyIt_API::add_domain($widget_id, $api_secret, $site_url);

        if (isset($response['result'])) {
            add_settings_error(
                'replyit_messages',
                'replyit_domain_register_success',
                __('Domain registered successfully!', 'replyit-chat-widget'),
                'updated'
            );
        } else {
            add_settings_error(
                'replyit_messages',
                'replyit_domain_register_error',
                sprintf(__('Failed to register domain: %s', 'replyit-chat-widget'), $response['message']),
                'error'
            );
        }
    }
}
