<?php
/**
 * Admin Class
 *
 * @package Tech_Repair_Service
 */

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

/**
 * Admin Class
 */
class Tech_Repair_Admin {
    /**
     * Constructor
     */
    public function __construct() {
        // Add admin menu
        add_action('admin_menu', array($this, 'add_admin_menu'));
        
        // Add admin scripts and styles
        add_action('admin_enqueue_scripts', array($this, 'enqueue_admin_assets'));
        
        // Add settings
        add_action('admin_init', array($this, 'register_settings'));
    }
    
    /**
     * Add admin menu
     */
    public function add_admin_menu() {
        add_menu_page(
            __('TR Settings', 'tech-repair-service'),
            __('TR Settings', 'tech-repair-service'),
            'manage_options',
            'tech-repair-service',
            array($this, 'render_settings_page'),
            'dashicons-admin-generic',
            26
        );
        
        add_submenu_page(
            'tech-repair-service',
            __('Settings', 'tech-repair-service'),
            __('Settings', 'tech-repair-service'),
            'manage_options',
            'tech-repair-service',
            array($this, 'render_settings_page')
        );
        
        add_submenu_page(
            'tech-repair-service',
            __('Shortcodes', 'tech-repair-service'),
            __('Shortcodes', 'tech-repair-service'),
            'manage_options',
            'tech-repair-shortcodes',
            array($this, 'render_shortcodes_page')
        );
    }
    
    /**
     * Enqueue admin assets
     */
    public function enqueue_admin_assets($hook) {
        // Only enqueue on our plugin pages
        if (strpos($hook, 'tech-repair') === false) {
            return;
        }
        
        // Подключаем WordPress Color Picker
        wp_enqueue_style('wp-color-picker');
        wp_enqueue_script('wp-color-picker');
        
        // Enqueue admin styles
        wp_enqueue_style(
            'tech-repair-admin-styles',
            TECH_REPAIR_PLUGIN_URL . 'assets/css/admin.css',
            array('wp-color-picker'),
            TECH_REPAIR_VERSION
        );
        
        // Enqueue admin scripts
        wp_enqueue_script(
            'tech-repair-admin-scripts',
            TECH_REPAIR_PLUGIN_URL . 'assets/js/admin.js',
            array('jquery', 'wp-color-picker'),
            TECH_REPAIR_VERSION,
            true
        );
    }
    
    /**
     * Register settings
     */
    public function register_settings() {
        register_setting(
            'tech_repair_settings',
            'tech_repair_settings',
            array($this, 'sanitize_settings')
        );
        
        add_settings_section(
            'tech_repair_general_settings',
            __('General Settings', 'tech-repair-service'),
            array($this, 'render_general_settings_section'),
            'tech_repair_settings'
        );
        
        add_settings_field(
            'tech_repair_currency_symbol',
            __('Currency Symbol', 'tech-repair-service'),
            array($this, 'render_currency_symbol_field'),
            'tech_repair_settings',
            'tech_repair_general_settings'
        );
        
        add_settings_field(
            'tech_repair_checkout_page',
            __('Checkout Page', 'tech-repair-service'),
            array($this, 'render_checkout_page_field'),
            'tech_repair_settings',
            'tech_repair_general_settings'
        );
        
        add_settings_field(
            'tech_repair_primary_color',
            __('Primary Color', 'tech-repair-service'),
            array($this, 'render_primary_color_field'),
            'tech_repair_settings',
            'tech_repair_general_settings'
        );
        
        add_settings_field(
            'tech_repair_enable_comments',
            __('Enable Comments', 'tech-repair-service'),
            array($this, 'render_enable_comments_field'),
            'tech_repair_settings',
            'tech_repair_general_settings'
        );
        
        // Добавляем поле для API ключа OpenAI
        add_settings_field(
            'tech_repair_openai_api_key',
            __('OpenAI API Key', 'tech-repair-service'),
            array($this, 'render_openai_api_key_field'),
            'tech_repair_settings',
            'tech_repair_general_settings'
        );
        
        add_settings_section(
            'tech_repair_category_settings',
            __('Category Settings', 'tech-repair-service'),
            array($this, 'render_category_settings_section'),
            'tech_repair_settings'
        );
        
        add_settings_field(
            'tech_repair_default_category_text',
            __('Default Device Category Text', 'tech-repair-service'),
            array($this, 'render_default_category_text_field'),
            'tech_repair_settings',
            'tech_repair_category_settings'
        );
        
        add_settings_field(
            'tech_repair_default_issue_type_text',
            __('Default Issue Type Text', 'tech-repair-service'),
            array($this, 'render_default_issue_type_text_field'),
            'tech_repair_settings',
            'tech_repair_category_settings'
        );
    }
    
    /**
     * Sanitize settings
     */
    public function sanitize_settings($input) {
        $sanitized_input = array();
        
        if (isset($input['currency_symbol'])) {
            $sanitized_input['currency_symbol'] = sanitize_text_field($input['currency_symbol']);
        }
        
        if (isset($input['checkout_page'])) {
            $sanitized_input['checkout_page'] = absint($input['checkout_page']);
        }
        
        if (isset($input['primary_color'])) {
            $sanitized_input['primary_color'] = sanitize_hex_color($input['primary_color']);
        }
        
        if (isset($input['enable_comments'])) {
            $sanitized_input['enable_comments'] = (bool) $input['enable_comments'];
        }
        
        if (isset($input['openai_api_key'])) {
            $sanitized_input['openai_api_key'] = sanitize_text_field($input['openai_api_key']);
        }
        
        if (isset($input['default_category_text'])) {
            $sanitized_input['default_category_text'] = sanitize_text_field($input['default_category_text']);
        }
        
        if (isset($input['default_issue_type_text'])) {
            $sanitized_input['default_issue_type_text'] = sanitize_text_field($input['default_issue_type_text']);
        }
        
        return $sanitized_input;
    }
    
    /**
     * Render general settings section
     */
    public function render_general_settings_section() {
        echo '<p>' . __('Configure general settings for the Tech Repair Service plugin.', 'tech-repair-service') . '</p>';
    }
    
    /**
     * Render category settings section
     */
    public function render_category_settings_section() {
        echo '<p>' . __('Configure settings for device categories and issue types display.', 'tech-repair-service') . '</p>';
    }
    
    /**
     * Render currency symbol field
     */
    public function render_currency_symbol_field() {
        $options = get_option('tech_repair_settings', array());
        $currency_symbol = isset($options['currency_symbol']) ? $options['currency_symbol'] : '$';
        
        echo '<input type="text" id="tech_repair_currency_symbol" name="tech_repair_settings[currency_symbol]" value="' . esc_attr($currency_symbol) . '" class="regular-text">';
        echo '<p class="description">' . __('The currency symbol to display before prices.', 'tech-repair-service') . '</p>';
    }
    
    /**
     * Render checkout page field
     */
    public function render_checkout_page_field() {
        $options = get_option('tech_repair_settings', array());
        $checkout_page = isset($options['checkout_page']) ? $options['checkout_page'] : 0;
        
        wp_dropdown_pages(array(
            'name' => 'tech_repair_settings[checkout_page]',
            'echo' => 1,
            'show_option_none' => __('&mdash; Select &mdash;', 'tech-repair-service'),
            'option_none_value' => '0',
            'selected' => $checkout_page
        ));
        
        echo '<p class="description">' . __('The page where customers will be directed to checkout.', 'tech-repair-service') . '</p>';
    }
    
    /**
     * Render primary color field
     */
    public function render_primary_color_field() {
        $options = get_option('tech_repair_settings', array());
        $primary_color = isset($options['primary_color']) ? $options['primary_color'] : '#007bff';
        
        echo '<input type="text" id="tech_repair_primary_color" name="tech_repair_settings[primary_color]" value="' . esc_attr($primary_color) . '" class="color-picker">';
        echo '<p class="description">' . __('The primary color for the plugin.', 'tech-repair-service') . '</p>';
    }
    
    /**
     * Render enable comments field
     */
    public function render_enable_comments_field() {
        $options = get_option('tech_repair_settings', array());
        $enable_comments = isset($options['enable_comments']) ? $options['enable_comments'] : 1;
        
        echo '<label for="tech_repair_enable_comments">';
        echo '<input type="checkbox" id="tech_repair_enable_comments" name="tech_repair_settings[enable_comments]" value="1" ' . checked(1, $enable_comments, false) . '>';
        echo ' ' . __('Enable "Leave a Reply" comments section on device and issue pages', 'tech-repair-service');
        echo '</label>';
        echo '<p class="description">' . __('When disabled, the comments section will be hidden on all plugin pages.', 'tech-repair-service') . '</p>';
    }
    
    /**
     * Render OpenAI API key field
     */
    public function render_openai_api_key_field() {
        $settings = get_option('tech_repair_settings', array());
        $api_key = isset($settings['openai_api_key']) ? $settings['openai_api_key'] : '';
        ?>
        <input type="text" name="tech_repair_settings[openai_api_key]" value="<?php echo esc_attr($api_key); ?>" class="regular-text" />
        <p class="description">
            <?php esc_html_e('Enter your OpenAI API key to enable automatic generation of repair issue descriptions.', 'tech-repair-service'); ?>
            <a href="https://platform.openai.com/api-keys" target="_blank"><?php esc_html_e('Get your API key here', 'tech-repair-service'); ?></a>
        </p>
        <?php
    }
    
    /**
     * Render default category text field
     */
    public function render_default_category_text_field() {
        $options = get_option('tech_repair_settings', array());
        $default_text = isset($options['default_category_text']) ? $options['default_category_text'] : 'FIXAR';
        
        echo '<input type="text" id="tech_repair_default_category_text" name="tech_repair_settings[default_category_text]" value="' . esc_attr($default_text) . '" class="regular-text">';
        echo '<p class="description">' . __('Default text to display when a device category does not have an image.', 'tech-repair-service') . '</p>';
    }
    
    /**
     * Render default issue type text field
     */
    public function render_default_issue_type_text_field() {
        $options = get_option('tech_repair_settings', array());
        $default_text = isset($options['default_issue_type_text']) ? $options['default_issue_type_text'] : 'FIXAR';
        
        echo '<input type="text" id="tech_repair_default_issue_type_text" name="tech_repair_settings[default_issue_type_text]" value="' . esc_attr($default_text) . '" class="regular-text">';
        echo '<p class="description">' . __('Default text to display when an issue type does not have an image.', 'tech-repair-service') . '</p>';
    }
    
    /**
     * Render settings page
     */
    public function render_settings_page() {
        if (!current_user_can('manage_options')) {
            return;
        }
        
        ?>
        <div class="wrap">
            <h1><?php echo esc_html(get_admin_page_title()); ?></h1>
            
            <form action="options.php" method="post">
                <?php
                settings_fields('tech_repair_settings');
                do_settings_sections('tech_repair_settings');
                submit_button();
                ?>
            </form>
        </div>
        <?php
    }
    
    /**
     * Render shortcodes page
     */
    public function render_shortcodes_page() {
        if (!current_user_can('manage_options')) {
            return;
        }
        
        ?>
        <div class="wrap">
            <h1><?php echo esc_html(get_admin_page_title()); ?></h1>
            
            <div class="tech-repair-shortcode-info">
                <h2><?php _e('Available Shortcodes', 'tech-repair-service'); ?></h2>
                
                <div class="tech-repair-shortcode-card">
                    <h3><?php _e('Quick Order Form', 'tech-repair-service'); ?></h3>
                    <code>[tech_repair_form text="Order Repair Now" class="primary-button"]</code>
                    
                    <h4><?php _e('Parameters', 'tech-repair-service'); ?></h4>
                    <table class="widefat">
                        <thead>
                            <tr>
                                <th><?php _e('Parameter', 'tech-repair-service'); ?></th>
                                <th><?php _e('Description', 'tech-repair-service'); ?></th>
                                <th><?php _e('Default', 'tech-repair-service'); ?></th>
                            </tr>
                        </thead>
                        <tbody>
                            <tr>
                                <td><code>text</code></td>
                                <td><?php _e('Button text', 'tech-repair-service'); ?></td>
                                <td><code>"Quick Repair Order"</code></td>
                            </tr>
                            <tr>
                                <td><code>class</code></td>
                                <td><?php _e('Additional CSS classes for the button', 'tech-repair-service'); ?></td>
                                <td><code>""</code></td>
                            </tr>
                        </tbody>
                    </table>
                    
                    <h4><?php _e('Description', 'tech-repair-service'); ?></h4>
                    <p><?php _e('The <code>tech_repair_form</code> shortcode displays a button that, when clicked, opens a modal popup with a quick order form. This form allows customers to quickly submit repair requests without navigating to a separate page.', 'tech-repair-service'); ?></p>
                    
                    <p><?php _e('The form includes fields for customer name, email address, phone number, device selection, issue selection, and additional notes.', 'tech-repair-service'); ?></p>
                    
                    <p><?php _e('When submitted, the form creates a new WooCommerce order with a special repair product and marks it as a repair order in the system.', 'tech-repair-service'); ?></p>
                    
                    <h4><?php _e('Alternative Usage', 'tech-repair-service'); ?></h4>
                    <p><?php _e('In addition to using the shortcode, you can also trigger the quick order form from any HTML element by adding specific CSS classes:', 'tech-repair-service'); ?></p>
                    <pre><code>&lt;button class="open-repair-form"&gt;Order Repair&lt;/button&gt;</code></pre>
                    
                    <p><?php _e('You can customize the form behavior using data attributes:', 'tech-repair-service'); ?></p>
                    <pre><code>&lt;a href="#" 
   class="open-repair-form" 
   data-form-title="iPhone Repair" 
   data-form-subtitle="Fill out the form to request a repair" 
   data-submit-text="Submit Request" 
   data-device-id="123"&gt;
   Fix My iPhone
&lt;/a&gt;</code></pre>
                </div>
                
                <div class="tech-repair-shortcode-card">
                    <h3><?php _e('Repair Tabs', 'tech-repair-service'); ?></h3>
                    <code>[tech_repair_tabs]</code>
                    
                    <h4><?php _e('Parameters', 'tech-repair-service'); ?></h4>
                    <table class="widefat">
                        <thead>
                            <tr>
                                <th><?php _e('Parameter', 'tech-repair-service'); ?></th>
                                <th><?php _e('Description', 'tech-repair-service'); ?></th>
                                <th><?php _e('Default', 'tech-repair-service'); ?></th>
                            </tr>
                        </thead>
                        <tbody>
                            <tr>
                                <td><code>device_category</code></td>
                                <td><?php _e('Filter devices by category slug. Separate multiple categories with commas.', 'tech-repair-service'); ?></td>
                                <td><em><?php _e('empty (all categories)', 'tech-repair-service'); ?></em></td>
                            </tr>
                            <tr>
                                <td><code>issue_type</code></td>
                                <td><?php _e('Filter issues by type slug. Separate multiple types with commas.', 'tech-repair-service'); ?></td>
                                <td><em><?php _e('empty (all types)', 'tech-repair-service'); ?></em></td>
                            </tr>
                            <tr>
                                <td><code>columns</code></td>
                                <td><?php _e('Number of columns for the layout.', 'tech-repair-service'); ?></td>
                                <td><code>3</code></td>
                            </tr>
                            <tr>
                                <td><code>device_title</code></td>
                                <td><?php _e('Title for the devices column.', 'tech-repair-service'); ?></td>
                                <td><?php _e('Select your device', 'tech-repair-service'); ?></td>
                            </tr>
                            <tr>
                                <td><code>issue_title</code></td>
                                <td><?php _e('Title for the issues column.', 'tech-repair-service'); ?></td>
                                <td><?php _e('Select issue', 'tech-repair-service'); ?></td>
                            </tr>
                            <tr>
                                <td><code>details_title</code></td>
                                <td><?php _e('Title for the details column.', 'tech-repair-service'); ?></td>
                                <td><?php _e('Repair details', 'tech-repair-service'); ?></td>
                            </tr>
                        </tbody>
                    </table>
                    
                    <h4><?php _e('Example', 'tech-repair-service'); ?></h4>
                    <code>[tech_repair_tabs device_category="smartphones,tablets" columns="3" device_title="Choose Device" issue_title="Select Problem"]</code>
                </div>
            </div>
        </div>
        <?php
    }
    
    /**
     * Render demo data page (proxy function)
     */
    public function render_demo_data_page() {
        // Эта функция просто перенаправляет на метод render_import_page класса Tech_Repair_Demo_Data
        if (class_exists('Tech_Repair_Demo_Data')) {
            $demo_data = new Tech_Repair_Demo_Data();
            $demo_data->render_import_page();
        } else {
            echo '<div class="wrap"><h1>' . esc_html__('Import Demo Data', 'tech-repair-service') . '</h1>';
            echo '<div class="notice notice-error"><p>' . esc_html__('Demo data importer is not available.', 'tech-repair-service') . '</p></div>';
            echo '</div>';
        }
    }
}
