<?php
/**
 * Device Category Taxonomy
 *
 * @package Tech_Repair_Service
 */

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

/**
 * Device Category Taxonomy Class
 */
class Tech_Repair_Device_Category {
    /**
     * Constructor
     */
    public function __construct() {
        // Register taxonomy
        add_action('init', array($this, 'register_taxonomy'));
        
        // Add form fields for the taxonomy
        add_action('tech_repair_device_cat_add_form_fields', array($this, 'add_category_image_field'));
        add_action('tech_repair_device_cat_edit_form_fields', array($this, 'edit_category_image_field'), 10, 2);
        
        // Save the taxonomy fields
        add_action('created_tech_repair_device_cat', array($this, 'save_category_image'));
        add_action('edited_tech_repair_device_cat', array($this, 'save_category_image'));
        
        // Add scripts and styles for media uploader
        add_action('admin_enqueue_scripts', array($this, 'load_media_scripts'));
        
        // Add image column to the taxonomy table
        add_filter('manage_edit-tech_repair_device_cat_columns', array($this, 'add_image_column'));
        add_filter('manage_tech_repair_device_cat_custom_column', array($this, 'add_image_column_content'), 10, 3);
    }
    
    /**
     * Register taxonomy
     */
    public function register_taxonomy() {
        $labels = array(
            'name'                       => _x('Device Categories', 'taxonomy general name', 'tech-repair-service'),
            'singular_name'              => _x('Device Category', 'taxonomy singular name', 'tech-repair-service'),
            'search_items'               => __('Search Device Categories', 'tech-repair-service'),
            'popular_items'              => __('Popular Device Categories', 'tech-repair-service'),
            'all_items'                  => __('All Device Categories', 'tech-repair-service'),
            'parent_item'                => __('Parent Device Category', 'tech-repair-service'),
            'parent_item_colon'          => __('Parent Device Category:', 'tech-repair-service'),
            'edit_item'                  => __('Edit Device Category', 'tech-repair-service'),
            'update_item'                => __('Update Device Category', 'tech-repair-service'),
            'add_new_item'               => __('Add New Device Category', 'tech-repair-service'),
            'new_item_name'              => __('New Device Category Name', 'tech-repair-service'),
            'separate_items_with_commas' => __('Separate device categories with commas', 'tech-repair-service'),
            'add_or_remove_items'        => __('Add or remove device categories', 'tech-repair-service'),
            'choose_from_most_used'      => __('Choose from the most used device categories', 'tech-repair-service'),
            'not_found'                  => __('No device categories found.', 'tech-repair-service'),
            'menu_name'                  => __('Device Categories', 'tech-repair-service'),
        );
        
        $args = array(
            'hierarchical'          => true,
            'labels'                => $labels,
            'show_ui'               => true,
            'show_admin_column'     => true,
            'query_var'             => true,
            'rewrite'               => array('slug' => 'device-category'),
            'show_in_rest'          => true,
        );
        
        register_taxonomy('tech_repair_device_cat', 'tech_repair_device', $args);
    }
    
    /**
     * Load media scripts and styles
     */
    public function load_media_scripts() {
        $screen = get_current_screen();
        
        // Only load on taxonomy screens
        if (!$screen || !in_array($screen->id, array('edit-tech_repair_device_cat'))) {
            return;
        }
        
        wp_enqueue_media();
        
        // Register and enqueue our custom script
        wp_register_script(
            'trs_taxonomy_image_js',
            plugin_dir_url(dirname(dirname(__FILE__))) . 'assets/js/taxonomy-image.js',
            array('jquery'),
            '1.0.0',
            true
        );
        
        // Localize the script with translation strings
        wp_localize_script('trs_taxonomy_image_js', 'trs_l10n', array(
            'upload_image_title' => esc_html__('Select or Upload Category Image', 'tech-repair-service'),
            'use_this_image'     => esc_html__('Use this image', 'tech-repair-service'),
        ));
        
        wp_enqueue_script('trs_taxonomy_image_js');
        
        // Enqueue CSS
        wp_enqueue_style(
            'trs_taxonomy_image_css',
            plugin_dir_url(dirname(dirname(__FILE__))) . 'assets/css/taxonomy-image.css',
            array(),
            '1.0.0'
        );
    }
    
    /**
     * Add image field to "Add new category" form
     */
    public function add_category_image_field() {
        ?>
        <div class="form-field term-image-wrap">
            <label for="trs_category_image"><?php esc_html_e('Category Image', 'tech-repair-service'); ?></label>
            <div class="trs-category-image-container">
                <div class="trs-category-image-preview"></div>
                <input type="hidden" id="trs_category_image" name="trs_category_image" class="trs-category-image-id" value="">
                <button type="button" class="button trs-upload-image"><?php esc_html_e('Upload Image', 'tech-repair-service'); ?></button>
                <button type="button" class="button trs-remove-image" style="display:none"><?php esc_html_e('Remove Image', 'tech-repair-service'); ?></button>
            </div>
            <p class="description"><?php esc_html_e('Upload an image for this device category.', 'tech-repair-service'); ?></p>
        </div>
        <?php
    }
    
    /**
     * Add image field to "Edit category" form
     */
    public function edit_category_image_field($term, $taxonomy) {
        $image_id = get_term_meta($term->term_id, 'trs_category_image_id', true);
        $image_url = '';
        
        if ($image_id) {
            $image_url = wp_get_attachment_image_url($image_id, 'thumbnail');
        }
        ?>
        <tr class="form-field term-image-wrap">
            <th scope="row"><label for="trs_category_image"><?php esc_html_e('Category Image', 'tech-repair-service'); ?></label></th>
            <td>
                <div class="trs-category-image-container">
                    <div class="trs-category-image-preview">
                        <?php if ($image_url) : ?>
                            <img src="<?php echo esc_url($image_url); ?>" alt="<?php esc_attr_e('Category Image', 'tech-repair-service'); ?>" style="max-width:100px;height:auto;">
                        <?php endif; ?>
                    </div>
                    <input type="hidden" id="trs_category_image" name="trs_category_image" class="trs-category-image-id" value="<?php echo esc_attr($image_id); ?>">
                    <button type="button" class="button trs-upload-image"><?php esc_html_e('Upload Image', 'tech-repair-service'); ?></button>
                    <button type="button" class="button trs-remove-image" <?php echo empty($image_id) ? 'style="display:none"' : ''; ?>><?php esc_html_e('Remove Image', 'tech-repair-service'); ?></button>
                </div>
                <p class="description"><?php esc_html_e('Upload an image for this device category.', 'tech-repair-service'); ?></p>
            </td>
        </tr>
        <?php
    }
    
    /**
     * Save category image
     */
    public function save_category_image($term_id) {
        if (isset($_POST['trs_category_image']) && '' !== $_POST['trs_category_image']) {
            $image_id = (int) $_POST['trs_category_image'];
            update_term_meta($term_id, 'trs_category_image_id', $image_id);
        } else {
            delete_term_meta($term_id, 'trs_category_image_id');
        }
    }
    
    /**
     * Add image column to the taxonomy table
     */
    public function add_image_column($columns) {
        $new_columns = array();
        
        // Add image column after checkbox but before name
        foreach ($columns as $key => $value) {
            if ($key === 'cb') {
                $new_columns['cb'] = $value;
                $new_columns['trs_category_image'] = esc_html__('Image', 'tech-repair-service');
            } else {
                $new_columns[$key] = $value;
            }
        }
        
        return $new_columns;
    }
    
    /**
     * Add image column content
     */
    public function add_image_column_content($content, $column_name, $term_id) {
        if ('trs_category_image' === $column_name) {
            $image_id = self::get_category_image_id($term_id);
            
            if ($image_id) {
                $image_url = wp_get_attachment_image_url($image_id, 'thumbnail');
                $image_alt = get_term($term_id)->name;
                
                $content = '<img src="' . esc_url($image_url) . '" alt="' . esc_attr($image_alt) . '" class="trs-category-thumbnail" />';
            }
        }
        
        return $content;
    }
    
    /**
     * Get category image ID
     *
     * @param int $term_id Term ID
     * @return int|false Image ID or false if not set
     */
    public static function get_category_image_id($term_id) {
        return get_term_meta($term_id, 'trs_category_image_id', true);
    }
    
    /**
     * Get category image URL
     *
     * @param int $term_id Term ID
     * @param string $size Image size
     * @return string|false Image URL or false if not set
     */
    public static function get_category_image_url($term_id, $size = 'thumbnail') {
        $image_id = self::get_category_image_id($term_id);
        
        if (!$image_id) {
            return false;
        }
        
        return wp_get_attachment_image_url($image_id, $size);
    }
}
