<?php
/**
 * Issue Post Type
 *
 * @package Tech_Repair_Service
 */

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

/**
 * Issue Post Type Class
 */
class Tech_Repair_Issue {
    /**
     * Constructor
     */
    public function __construct() {
        // Register post type
        add_action('init', array($this, 'register_post_type'));
        
        // Add meta boxes
        add_action('add_meta_boxes', array($this, 'add_meta_boxes'));
        
        // Save meta box data
        add_action('save_post', array($this, 'save_meta_box_data'));
        
        // Подключаем скрипты и стили для OpenAI в админке
        add_action('admin_enqueue_scripts', array($this, 'enqueue_admin_assets'));
    }
    
    /**
     * Register post type
     */
    public function register_post_type() {
        $labels = array(
            'name'               => _x('Repair Issues', 'post type general name', 'tech-repair-service'),
            'singular_name'      => _x('Repair Issue', 'post type singular name', 'tech-repair-service'),
            'menu_name'          => _x('Repair Issues', 'admin menu', 'tech-repair-service'),
            'name_admin_bar'     => _x('Repair Issue', 'add new on admin bar', 'tech-repair-service'),
            'add_new'            => _x('Add New', 'issue', 'tech-repair-service'),
            'add_new_item'       => __('Add New Repair Issue', 'tech-repair-service'),
            'new_item'           => __('New Repair Issue', 'tech-repair-service'),
            'edit_item'          => __('Edit Repair Issue', 'tech-repair-service'),
            'view_item'          => __('View Repair Issue', 'tech-repair-service'),
            'all_items'          => __('All Repair Issues', 'tech-repair-service'),
            'search_items'       => __('Search Repair Issues', 'tech-repair-service'),
            'parent_item_colon'  => __('Parent Repair Issues:', 'tech-repair-service'),
            'not_found'          => __('No repair issues found.', 'tech-repair-service'),
            'not_found_in_trash' => __('No repair issues found in Trash.', 'tech-repair-service')
        );
        
        $args = array(
            'labels'             => $labels,
            'description'        => __('Repair Issue post type for Tech Repair Service.', 'tech-repair-service'),
            'public'             => true,
            'publicly_queryable' => true,
            'show_ui'            => true,
            'show_in_menu'       => true,
            'query_var'          => true,
            'rewrite'            => array('slug' => 'repair-issue', 'with_front' => false),
            'capability_type'    => 'post',
            'has_archive'        => true,
            'hierarchical'       => false,
            'menu_position'      => null,
            'supports'           => array('title', 'editor', 'thumbnail', 'excerpt', 'comments'),
            'menu_icon'          => 'dashicons-admin-tools'
        );
        
        register_post_type('tech_repair_issue', $args);
    }
    
    /**
     * Add meta boxes
     */
    public function add_meta_boxes() {
        add_meta_box(
            'tech_repair_issue_details',
            __('Repair Issue Details', 'tech-repair-service'),
            array($this, 'render_issue_details_meta_box'),
            'tech_repair_issue',
            'normal',
            'high'
        );
        
        add_meta_box(
            'tech_repair_issue_pricing',
            __('Repair Pricing', 'tech-repair-service'),
            array($this, 'render_issue_pricing_meta_box'),
            'tech_repair_issue',
            'normal',
            'high'
        );
        
        add_meta_box(
            'tech_repair_issue_devices',
            __('Compatible Devices', 'tech-repair-service'),
            array($this, 'render_issue_devices_meta_box'),
            'tech_repair_issue',
            'side',
            'default'
        );
    }
    
    /**
     * Render issue details meta box
     */
    public function render_issue_details_meta_box($post) {
        // Add a nonce field so we can check for it later
        wp_nonce_field('tech_repair_issue_details_meta_box', 'tech_repair_issue_details_meta_box_nonce');
        
        // Get current values
        $difficulty = get_post_meta($post->ID, '_tech_repair_difficulty', true);
        $repair_time = get_post_meta($post->ID, '_tech_repair_time', true);
        
        // Output fields
        ?>
        <table class="form-table">
            <tr>
                <th scope="row">
                    <label for="tech_repair_difficulty"><?php _e('Repair Difficulty', 'tech-repair-service'); ?></label>
                </th>
                <td>
                    <select id="tech_repair_difficulty" name="tech_repair_difficulty">
                        <option value="easy" <?php selected($difficulty, 'easy'); ?>><?php _e('Easy', 'tech-repair-service'); ?></option>
                        <option value="medium" <?php selected($difficulty, 'medium'); ?>><?php _e('Medium', 'tech-repair-service'); ?></option>
                        <option value="hard" <?php selected($difficulty, 'hard'); ?>><?php _e('Hard', 'tech-repair-service'); ?></option>
                        <option value="expert" <?php selected($difficulty, 'expert'); ?>><?php _e('Expert Only', 'tech-repair-service'); ?></option>
                    </select>
                </td>
            </tr>
            <tr>
                <th scope="row">
                    <label for="tech_repair_time"><?php _e('Repair Time (hours)', 'tech-repair-service'); ?></label>
                </th>
                <td>
                    <input type="number" id="tech_repair_time" name="tech_repair_time" value="<?php echo esc_attr($repair_time); ?>" class="small-text" step="0.5" min="0.5">
                </td>
            </tr>
        </table>
        <?php
    }
    
    /**
     * Render issue pricing meta box
     */
    public function render_issue_pricing_meta_box($post) {
        // Add a nonce field so we can check for it later
        wp_nonce_field('tech_repair_issue_pricing_meta_box', 'tech_repair_issue_pricing_meta_box_nonce');
        
        // Get current values
        $pricing_options = get_post_meta($post->ID, '_tech_repair_pricing_options', true);
        
        if (!is_array($pricing_options)) {
            $pricing_options = array(
                array(
                    'name' => '',
                    'price' => '',
                    'description' => ''
                )
            );
        }
        
        // Output fields
        ?>
        <div id="tech_repair_pricing_options">
            <?php foreach ($pricing_options as $index => $option) : ?>
                <div class="tech-repair-pricing-option" data-index="<?php echo $index; ?>">
                    <h4><?php _e('Pricing Option', 'tech-repair-service'); ?> <span class="option-number"><?php echo $index + 1; ?></span></h4>
                    <table class="form-table">
                        <tr>
                            <th scope="row">
                                <label for="tech_repair_pricing_options_<?php echo $index; ?>_name"><?php _e('Option Name', 'tech-repair-service'); ?></label>
                            </th>
                            <td>
                                <input type="text" id="tech_repair_pricing_options_<?php echo $index; ?>_name" name="tech_repair_pricing_options[<?php echo $index; ?>][name]" value="<?php echo esc_attr($option['name']); ?>" class="regular-text">
                            </td>
                        </tr>
                        <tr>
                            <th scope="row">
                                <label for="tech_repair_pricing_options_<?php echo $index; ?>_price"><?php _e('Price', 'tech-repair-service'); ?></label>
                            </th>
                            <td>
                                <input type="text" id="tech_repair_pricing_options_<?php echo $index; ?>_price" name="tech_repair_pricing_options[<?php echo $index; ?>][price]" value="<?php echo esc_attr($option['price']); ?>" class="regular-text">
                            </td>
                        </tr>
                        <tr>
                            <th scope="row">
                                <label for="tech_repair_pricing_options_<?php echo $index; ?>_description"><?php _e('Description', 'tech-repair-service'); ?></label>
                            </th>
                            <td>
                                <textarea id="tech_repair_pricing_options_<?php echo $index; ?>_description" name="tech_repair_pricing_options[<?php echo $index; ?>][description]" class="large-text" rows="3"><?php echo esc_textarea($option['description']); ?></textarea>
                            </td>
                        </tr>
                    </table>
                    <?php if ($index > 0) : ?>
                        <button type="button" class="button remove-pricing-option"><?php _e('Remove Option', 'tech-repair-service'); ?></button>
                    <?php endif; ?>
                    <hr>
                </div>
            <?php endforeach; ?>
        </div>
        <button type="button" class="button add-pricing-option"><?php _e('Add Pricing Option', 'tech-repair-service'); ?></button>
        
        <script type="text/javascript">
            jQuery(document).ready(function($) {
                var optionIndex = <?php echo count($pricing_options); ?>;
                
                $('.add-pricing-option').on('click', function() {
                    var template = `
                        <div class="tech-repair-pricing-option" data-index="${optionIndex}">
                            <h4><?php _e('Pricing Option', 'tech-repair-service'); ?> <span class="option-number">${optionIndex + 1}</span></h4>
                            <table class="form-table">
                                <tr>
                                    <th scope="row">
                                        <label for="tech_repair_pricing_options_${optionIndex}_name"><?php _e('Option Name', 'tech-repair-service'); ?></label>
                                    </th>
                                    <td>
                                        <input type="text" id="tech_repair_pricing_options_${optionIndex}_name" name="tech_repair_pricing_options[${optionIndex}][name]" value="" class="regular-text">
                                    </td>
                                </tr>
                                <tr>
                                    <th scope="row">
                                        <label for="tech_repair_pricing_options_${optionIndex}_price"><?php _e('Price', 'tech-repair-service'); ?></label>
                                    </th>
                                    <td>
                                        <input type="text" id="tech_repair_pricing_options_${optionIndex}_price" name="tech_repair_pricing_options[${optionIndex}][price]" value="" class="regular-text">
                                    </td>
                                </tr>
                                <tr>
                                    <th scope="row">
                                        <label for="tech_repair_pricing_options_${optionIndex}_description"><?php _e('Description', 'tech-repair-service'); ?></label>
                                    </th>
                                    <td>
                                        <textarea id="tech_repair_pricing_options_${optionIndex}_description" name="tech_repair_pricing_options[${optionIndex}][description]" class="large-text" rows="3"></textarea>
                                    </td>
                                </tr>
                            </table>
                            <button type="button" class="button remove-pricing-option"><?php _e('Remove Option', 'tech-repair-service'); ?></button>
                            <hr>
                        </div>
                    `;
                    
                    $('#tech_repair_pricing_options').append(template);
                    optionIndex++;
                });
                
                $(document).on('click', '.remove-pricing-option', function() {
                    $(this).closest('.tech-repair-pricing-option').remove();
                    
                    // Update option numbers
                    $('.tech-repair-pricing-option').each(function(index) {
                        $(this).find('.option-number').text(index + 1);
                    });
                });
            });
        </script>
        <?php
    }
    
    /**
     * Render issue devices meta box
     */
    public function render_issue_devices_meta_box($post) {
        // Add a nonce field so we can check for it later
        wp_nonce_field('tech_repair_issue_devices_meta_box', 'tech_repair_issue_devices_meta_box_nonce');
        
        // Get current values
        $compatible_devices = get_post_meta($post->ID, '_tech_repair_compatible_devices', true);
        
        if (!is_array($compatible_devices)) {
            $compatible_devices = array();
        }
        
        // Get all devices
        $devices = get_posts(array(
            'post_type' => 'tech_repair_device',
            'posts_per_page' => -1,
            'orderby' => 'title',
            'order' => 'ASC'
        ));
        
        // Output fields
        ?>
        <p><?php _e('Select devices that this repair issue applies to:', 'tech-repair-service'); ?></p>
        
        <?php if (!empty($devices)) : ?>
            <div style="max-height: 200px; overflow-y: auto;">
                <?php foreach ($devices as $device) : ?>
                    <label>
                        <input type="checkbox" name="tech_repair_compatible_devices[]" value="<?php echo $device->ID; ?>" <?php checked(in_array($device->ID, $compatible_devices)); ?>>
                        <?php echo $device->post_title; ?>
                    </label><br>
                <?php endforeach; ?>
            </div>
        <?php else : ?>
            <p><?php _e('No devices found. Please create some devices first.', 'tech-repair-service'); ?></p>
        <?php endif; ?>
        <?php
    }
    
    /**
     * Enqueue admin assets for OpenAI integration
     *
     * @param string $hook Current admin page
     */
    public function enqueue_admin_assets($hook) {
        global $post;
        
        // Only enqueue on issue edit page
        if (!($hook === 'post.php' || $hook === 'post-new.php') || 
            !is_object($post) || $post->post_type !== 'tech_repair_issue') {
            return;
        }
        
        // Enqueue OpenAI styles
        wp_enqueue_style(
            'tech-repair-openai-styles',
            TECH_REPAIR_PLUGIN_URL . 'assets/css/tech-repair-openai.css',
            array(),
            TECH_REPAIR_VERSION
        );
        
        // Enqueue OpenAI scripts
        wp_enqueue_script(
            'tech-repair-openai-scripts',
            TECH_REPAIR_PLUGIN_URL . 'assets/js/tech-repair-openai.js',
            array('jquery'),
            TECH_REPAIR_VERSION,
            true
        );
        
        // Localize script
        wp_localize_script(
            'tech-repair-openai-scripts',
            'techRepairOpenAI',
            array(
                'nonce' => wp_create_nonce('tech_repair_openai_nonce'),
                'generateButtonText' => esc_html__('Generate Description with AI', 'tech-repair-service'),
                'generatingText' => esc_html__('Generating description...', 'tech-repair-service'),
                'successText' => esc_html__('Description generated successfully!', 'tech-repair-service'),
                'errorText' => esc_html__('Error generating description. Please try again.', 'tech-repair-service'),
                'errorTitleRequired' => esc_html__('Please enter a title for the issue.', 'tech-repair-service'),
                'errorTypeRequired' => esc_html__('Please select an issue type.', 'tech-repair-service')
            )
        );
    }
    
    /**
     * Save meta box data
     */
    public function save_meta_box_data($post_id) {
        // Check if our nonce is set
        if (!isset($_POST['tech_repair_issue_details_meta_box_nonce']) || 
            !isset($_POST['tech_repair_issue_pricing_meta_box_nonce']) || 
            !isset($_POST['tech_repair_issue_devices_meta_box_nonce'])) {
            return;
        }
        
        // Verify that the nonces are valid
        if (!wp_verify_nonce($_POST['tech_repair_issue_details_meta_box_nonce'], 'tech_repair_issue_details_meta_box') || 
            !wp_verify_nonce($_POST['tech_repair_issue_pricing_meta_box_nonce'], 'tech_repair_issue_pricing_meta_box') || 
            !wp_verify_nonce($_POST['tech_repair_issue_devices_meta_box_nonce'], 'tech_repair_issue_devices_meta_box')) {
            return;
        }
        
        // If this is an autosave, our form has not been submitted, so we don't want to do anything
        if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) {
            return;
        }
        
        // Check the user's permissions
        if (isset($_POST['post_type']) && 'tech_repair_issue' == $_POST['post_type']) {
            if (!current_user_can('edit_post', $post_id)) {
                return;
            }
        }
        
        // OK, it's safe for us to save the data now
        
        // Save difficulty
        if (isset($_POST['tech_repair_difficulty'])) {
            $difficulty = sanitize_text_field($_POST['tech_repair_difficulty']);
            update_post_meta($post_id, '_tech_repair_difficulty', $difficulty);
        }
        
        // Save repair time
        if (isset($_POST['tech_repair_time'])) {
            $repair_time = floatval($_POST['tech_repair_time']);
            update_post_meta($post_id, '_tech_repair_time', $repair_time);
        }
        
        // Save pricing options
        if (isset($_POST['tech_repair_pricing_options']) && is_array($_POST['tech_repair_pricing_options'])) {
            $pricing_options = array();
            
            foreach ($_POST['tech_repair_pricing_options'] as $option) {
                $pricing_options[] = array(
                    'name' => sanitize_text_field($option['name']),
                    'price' => sanitize_text_field($option['price']),
                    'description' => sanitize_textarea_field($option['description'])
                );
            }
            
            update_post_meta($post_id, '_tech_repair_pricing_options', $pricing_options);
        }
        
        // Save compatible devices
        if (isset($_POST['tech_repair_compatible_devices']) && is_array($_POST['tech_repair_compatible_devices'])) {
            $compatible_devices = array_map('intval', $_POST['tech_repair_compatible_devices']);
            update_post_meta($post_id, '_tech_repair_compatible_devices', $compatible_devices);
        } else {
            update_post_meta($post_id, '_tech_repair_compatible_devices', array());
        }
    }
}
