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

class TW_SIMPLE_SLIDER_Metabox {
    
    private static $instance = null;
    
    public static function get_instance() {
        if (null === self::$instance) {
            self::$instance = new self();
        }
        return self::$instance;
    }
    
    private function __construct() {
        add_action('add_meta_boxes', array($this, 'twssc_add_metaboxes'));
        add_action('save_post_' . TW_SIMPLE_SLIDER_POST_TYPE, array($this, 'twssc_save_metabox_data'));
    }
    
    public function twssc_add_metaboxes() {
        add_meta_box('twssc_slider_images', __('Slider Images', 'tw-simple-slider'), 
                     array($this, 'twssc_render_images_metabox'), TW_SIMPLE_SLIDER_POST_TYPE, 'normal', 'high');
        
        add_meta_box('twssc_slider_settings', __('Slider Settings', 'tw-simple-slider'), 
                     array($this, 'twssc_render_settings_metabox'), TW_SIMPLE_SLIDER_POST_TYPE, 'side', 'high');
        
        add_meta_box('twssc_slider_styling', __('Slider Styling', 'tw-simple-slider'), 
                     array($this, 'twssc_render_styling_metabox'), TW_SIMPLE_SLIDER_POST_TYPE, 'normal', 'high');
    }
    
    public function twssc_render_images_metabox($post) {
        wp_nonce_field('twssc_slider_nonce', 'twssc_slider_nonce_field');
        
        $images = get_post_meta($post->ID, '_twssc_slider_images', true);
        $images = is_array($images) ? $images : array();
        ?>
        <div class="twssc-slider-images-container">
            <div class="twssc-slider-images-list" id="twssc-slider-images-list">
                <?php if (!empty($images)): ?>
                    <?php foreach ($images as $image_id): ?>
                        <?php if ($image_url = wp_get_attachment_image_url($image_id, 'medium')): ?>
                            <div class="twssc-slider-image-item" data-image-id="<?php echo esc_attr($image_id); ?>">
                                <div class="twssc-slider-image-preview">
                                    <img src="<?php echo esc_url($image_url); ?>" alt="">
                                    <input type="hidden" name="twssc_slider_images[]" value="<?php echo esc_attr($image_id); ?>">
                                </div>
                                <button type="button" class="button button-small twssc-slider-remove-image">
                                    <?php esc_html_e('Remove', 'tw-simple-slider'); ?>
                                </button>
                            </div>
                        <?php endif; ?>
                    <?php endforeach; ?>
                <?php else: ?>
                    <p class="twssc-no-images"><?php esc_html_e('No images added yet.', 'tw-simple-slider'); ?></p>
                <?php endif; ?>
            </div>
            
            <div class="twssc-slider-images-actions">
                <button type="button" class="button button-primary" id="twssc-slider-add-images">
                    <?php esc_html_e('Add Images', 'tw-simple-slider'); ?>
                </button>
                <p class="description">
                    <?php esc_html_e('Drag and drop to reorder images', 'tw-simple-slider'); ?>
                </p>
            </div>
        </div>
        <?php
    }
    
    public function twssc_render_settings_metabox($post) {
        $post_id = absint($post->ID);
        
        $slides_to_show = get_post_meta($post_id, '_twssc_slider_slides_to_show', true);
        $slides_to_show = $slides_to_show ?: '1';
        
        $fade_animation = get_post_meta($post_id, '_twssc_slider_fade_animation', true);
        $fade_animation = $fade_animation !== '' ? $fade_animation : 'no';
        
        $show_arrows = get_post_meta($post_id, '_twssc_slider_show_arrows', true);
        $show_arrows = $show_arrows !== '' ? $show_arrows : 'yes';
        
        $show_dots = get_post_meta($post_id, '_twssc_slider_show_dots', true);
        $show_dots = $show_dots !== '' ? $show_dots : 'yes';
        
        $autoplay = get_post_meta($post_id, '_twssc_slider_autoplay', true);
        $autoplay = $autoplay !== '' ? $autoplay : 'yes';
        
        $pause_on_hover = get_post_meta($post_id, '_twssc_slider_pause_on_hover', true);
        $pause_on_hover = $pause_on_hover !== '' ? $pause_on_hover : 'no';

        $fade_disabled = ($slides_to_show !== '1');
        if ($fade_disabled) {
            $fade_animation = 'no';
        }
        ?>
        <div class="twssc-slider-settings">
            <p>
                <label for="twssc_slider_slides_to_show">
                    <strong><?php esc_html_e('Slides to Show:', 'tw-simple-slider'); ?></strong>
                </label>
                <input type="number" name="twssc_slider_slides_to_show" id="twssc_slider_slides_to_show" 
                       value="<?php echo esc_attr($slides_to_show); ?>" 
                       min="1" step="1" class="widefat">
                <span class="description"><?php esc_html_e('Number of slides visible at once', 'tw-simple-slider'); ?></span>
            </p>
            
            <p>
                <label>
                    <input type="checkbox" name="twssc_slider_fade_animation" value="yes" 
                           id="twssc_slider_fade_animation" 
                           <?php checked($fade_animation, 'yes'); ?>
                           <?php echo $fade_disabled ? 'disabled' : ''; ?>>
                    <?php esc_html_e('Enable Fade Animation', 'tw-simple-slider'); ?>
                </label>
                <?php if ($fade_disabled): ?>
                    <span class="description" style="color: #d63638; display: block;">
                        <?php esc_html_e('Fade animation is only available when showing 1 slide', 'tw-simple-slider'); ?>
                    </span>
                <?php endif; ?>
            </p>
            
            <hr>
            
            <p>
                <label>
                    <input type="checkbox" name="twssc_slider_show_arrows" value="yes" <?php checked($show_arrows, 'yes'); ?>>
                    <?php esc_html_e('Show Navigation Arrows', 'tw-simple-slider'); ?>
                </label>
            </p>
            
            <p>
                <label>
                    <input type="checkbox" name="twssc_slider_show_dots" value="yes" <?php checked($show_dots, 'yes'); ?>>
                    <?php esc_html_e('Show Dots Navigation', 'tw-simple-slider'); ?>
                </label>
            </p>
            
            <p>
                <label>
                    <input type="checkbox" name="twssc_slider_autoplay" value="yes" <?php checked($autoplay, 'yes'); ?>>
                    <?php esc_html_e('Auto Play Slides', 'tw-simple-slider'); ?>
                </label>
            </p>
            
            <p id="pause_on_hover_container" style="<?php echo ($autoplay === 'yes') ? '' : 'display: none;'; ?>">
                <label>
                    <input type="checkbox" name="twssc_slider_pause_on_hover" value="yes" <?php checked($pause_on_hover, 'yes'); ?>>
                    <?php esc_html_e('Pause on Hover', 'tw-simple-slider'); ?>
                </label>
            </p>

            <hr>
            
            <p>
                <label for="twssc_slider_shortcode"><strong><?php esc_html_e('Shortcode:', 'tw-simple-slider'); ?></strong></label>
                <input type="text" readonly id="twssc_slider_shortcode" 
                       value='[twssc_slider id="<?php echo esc_attr($post_id); ?>"]' class="widefat" onclick="this.select();">
                <span class="description"><?php esc_html_e('Copy the shortcode and paste it to display the slider.', 'tw-simple-slider'); ?></span>
            </p>
        </div>
        <?php
    }
    
    public function twssc_render_styling_metabox($post) {
        $post_id = absint($post->ID);
        $custom_style = get_post_meta($post_id, '_twssc_slider_custom_style', true);
        $defaults = array(
            'image_fit' => 'cover',
            'image_height' => '400',
            'dots_color' => '#333333',
            'dots_active_color' => '#007cba',
            'dots_size' => '12',
            'arrows_type' => 'default',
            'custom_arrow_prev' => '',
            'custom_arrow_next' => '',
            'arrows_bg' => 'rgba(0,0,0,0.5)',
            'arrows_hover_bg' => 'rgba(0,0,0,0.8)',
            'arrows_color' => '#ffffff',
            'arrows_size' => '40',
            'arrows_icon_size' => '20',
            'arrows_position' => 'center',
        );
        
        $style = wp_parse_args($custom_style, $defaults);
        ?>
        <div class="twssc-slider-styling-options">
            <h3><?php esc_html_e('Image Settings', 'tw-simple-slider'); ?></h3>
            <table class="form-table">
                <tr>
                    <th><label for="image_fit"><?php esc_html_e('Image Fit', 'tw-simple-slider'); ?></label></th>
                    <td>
                        <select name="twssc_slider_custom_style[image_fit]" id="image_fit" class="regular-text">
                            <option value="cover" <?php selected($style['image_fit'], 'cover'); ?>><?php esc_html_e('Cover', 'tw-simple-slider'); ?></option>
                            <option value="contain" <?php selected($style['image_fit'], 'contain'); ?>><?php esc_html_e('Contain', 'tw-simple-slider'); ?></option>
                            <option value="fill" <?php selected($style['image_fit'], 'fill'); ?>><?php esc_html_e('Fill', 'tw-simple-slider'); ?></option>
                            <option value="scale-down" <?php selected($style['image_fit'], 'scale-down'); ?>><?php esc_html_e('Scale Down', 'tw-simple-slider'); ?></option>
                        </select>
                    </td>
                </tr>
                
                <tr>
                    <th><label for="image_height"><?php esc_html_e('Image Height (px)', 'tw-simple-slider'); ?></label></th>
                    <td>
                        <input type="number" name="twssc_slider_custom_style[image_height]" id="image_height" 
                               value="<?php echo esc_attr($style['image_height']); ?>" min="100" max="1000" step="10" class="small-text">
                    </td>
                </tr>
            </table>
            
            <h3><?php esc_html_e('Dots Navigation', 'tw-simple-slider'); ?></h3>
            <table class="form-table">
                <tr>
                    <th><label for="dots_color"><?php esc_html_e('Dots Color', 'tw-simple-slider'); ?></label></th>
                    <td>
                        <input type="text" name="twssc_slider_custom_style[dots_color]" id="dots_color" 
                               value="<?php echo esc_attr($style['dots_color']); ?>" class="color-picker" data-default-color="#333333">
                    </td>
                </tr>
                
                <tr>
                    <th><label for="dots_active_color"><?php esc_html_e('Active Dot Color', 'tw-simple-slider'); ?></label></th>
                    <td>
                        <input type="text" name="twssc_slider_custom_style[dots_active_color]" id="dots_active_color" 
                               value="<?php echo esc_attr($style['dots_active_color']); ?>" class="color-picker" data-default-color="#007cba">
                    </td>
                </tr>
                
                <tr>
                    <th><label for="dots_size"><?php esc_html_e('Dots Size (px)', 'tw-simple-slider'); ?></label></th>
                    <td>
                        <input type="number" name="twssc_slider_custom_style[dots_size]" id="dots_size" 
                               value="<?php echo esc_attr($style['dots_size']); ?>" min="6" max="20" class="small-text">
                    </td>
                </tr>
            </table>
            
            <h3><?php esc_html_e('Arrow Navigation', 'tw-simple-slider'); ?></h3>
            <table class="form-table">
                <tr>
                    <th><label><?php esc_html_e('Arrow Type', 'tw-simple-slider'); ?></label></th>
                    <td>
                        <label>
                            <input type="radio" name="twssc_slider_custom_style[arrows_type]" value="default" 
                                   <?php checked($style['arrows_type'], 'default'); ?> class="arrow-type-option">
                            <?php esc_html_e('Default Arrows', 'tw-simple-slider'); ?>
                        </label>
                        <br>
                        <label>
                            <input type="radio" name="twssc_slider_custom_style[arrows_type]" value="custom" 
                                   <?php checked($style['arrows_type'], 'custom'); ?> class="arrow-type-option">
                            <?php esc_html_e('Custom Uploaded Arrows', 'tw-simple-slider'); ?>
                        </label>
                    </td>
                </tr>
                
                <tr class="custom-arrow-fields" style="<?php echo $style['arrows_type'] === 'custom' ? '' : 'display: none;'; ?>">
                    <th><label for="custom_arrow_prev"><?php esc_html_e('Previous Arrow', 'tw-simple-slider'); ?></label></th>
                    <td>
                        <div class="custom-arrow-preview" style="margin-bottom: 10px;">
                            <?php if (!empty($style['custom_arrow_prev'])): ?>
                                <img src="<?php echo esc_url(wp_get_attachment_url($style['custom_arrow_prev'])); ?>" style="max-width: 100px; height: auto; display: block; margin-bottom: 5px;">
                            <?php endif; ?>
                        </div>
                        <input type="hidden" name="twssc_slider_custom_style[custom_arrow_prev]" id="custom_arrow_prev" 
                               value="<?php echo esc_attr($style['custom_arrow_prev']); ?>">
                        <button type="button" class="button twssc-upload-arrow" data-target="custom_arrow_prev">
                            <?php esc_html_e('Upload Previous Arrow', 'tw-simple-slider'); ?>
                        </button>
                        <button type="button" class="button twssc-remove-arrow" data-target="custom_arrow_prev" 
                                style="<?php echo empty($style['custom_arrow_prev']) ? 'display: none;' : ''; ?>">
                            <?php esc_html_e('Remove', 'tw-simple-slider'); ?>
                        </button>
                    </td>
                </tr>
                
                <tr class="custom-arrow-fields" style="<?php echo $style['arrows_type'] === 'custom' ? '' : 'display: none;'; ?>">
                    <th><label for="custom_arrow_next"><?php esc_html_e('Next Arrow', 'tw-simple-slider'); ?></label></th>
                    <td>
                        <div class="custom-arrow-preview" style="margin-bottom: 10px;">
                            <?php if (!empty($style['custom_arrow_next'])): ?>
                                <img src="<?php echo esc_url(wp_get_attachment_url($style['custom_arrow_next'])); ?>" style="max-width: 100px; height: auto; display: block; margin-bottom: 5px;">
                            <?php endif; ?>
                        </div>
                        <input type="hidden" name="twssc_slider_custom_style[custom_arrow_next]" id="custom_arrow_next" 
                               value="<?php echo esc_attr($style['custom_arrow_next']); ?>">
                        <button type="button" class="button twssc-upload-arrow" data-target="custom_arrow_next">
                            <?php esc_html_e('Upload Next Arrow', 'tw-simple-slider'); ?>
                        </button>
                        <button type="button" class="button twssc-remove-arrow" data-target="custom_arrow_next" 
                                style="<?php echo empty($style['custom_arrow_next']) ? 'display: none;' : ''; ?>">
                            <?php esc_html_e('Remove', 'tw-simple-slider'); ?>
                        </button>
                    </td>
                </tr>
                
                <tr>
                    <th><label for="arrows_bg"><?php esc_html_e('Arrow Background', 'tw-simple-slider'); ?></label></th>
                    <td>
                        <input type="text" name="twssc_slider_custom_style[arrows_bg]" id="arrows_bg" 
                               value="<?php echo esc_attr($style['arrows_bg']); ?>" class="color-picker" data-default-color="rgba(0,0,0,0.5)">
                    </td>
                </tr>
                
                <tr>
                    <th><label for="arrows_hover_bg"><?php esc_html_e('Arrow Hover Background', 'tw-simple-slider'); ?></label></th>
                    <td>
                        <input type="text" name="twssc_slider_custom_style[arrows_hover_bg]" id="arrows_hover_bg" 
                               value="<?php echo esc_attr($style['arrows_hover_bg']); ?>" class="color-picker" data-default-color="rgba(0,0,0,0.8)">
                    </td>
                </tr>
                
                <tr>
                    <th><label for="arrows_color"><?php esc_html_e('Arrow Color', 'tw-simple-slider'); ?></label></th>
                    <td>
                        <input type="text" name="twssc_slider_custom_style[arrows_color]" id="arrows_color" 
                               value="<?php echo esc_attr($style['arrows_color']); ?>" class="color-picker" data-default-color="#ffffff">
                    </td>
                </tr>
                
                <tr>
                    <th><label for="arrows_size"><?php esc_html_e('Arrow Size (px)', 'tw-simple-slider'); ?></label></th>
                    <td>
                        <input type="number" name="twssc_slider_custom_style[arrows_size]" id="arrows_size" 
                               value="<?php echo esc_attr($style['arrows_size']); ?>" min="20" max="100" class="small-text">
                    </td>
                </tr>
                
                <tr>
                    <th><label for="arrows_icon_size"><?php esc_html_e('Arrow Icon Size (px)', 'tw-simple-slider'); ?></label></th>
                    <td>
                        <input type="number" name="twssc_slider_custom_style[arrows_icon_size]" id="arrows_icon_size" 
                               value="<?php echo esc_attr($style['arrows_icon_size']); ?>" min="10" max="50" class="small-text">
                    </td>
                </tr>
                
                <tr>
                    <th><label><?php esc_html_e('Arrow Position', 'tw-simple-slider'); ?></label></th>
                    <td>
                        <select name="twssc_slider_custom_style[arrows_position]" id="arrows_position" class="regular-text">
                            <option value="center" <?php selected($style['arrows_position'], 'center'); ?>><?php esc_html_e('Center', 'tw-simple-slider'); ?></option>
                            <option value="top-left" <?php selected($style['arrows_position'], 'top-left'); ?>><?php esc_html_e('Top Left', 'tw-simple-slider'); ?></option>
                            <option value="top-center" <?php selected($style['arrows_position'], 'top-center'); ?>><?php esc_html_e('Top Center', 'tw-simple-slider'); ?></option>
                            <option value="top-right" <?php selected($style['arrows_position'], 'top-right'); ?>><?php esc_html_e('Top Right', 'tw-simple-slider'); ?></option>
                            <option value="middle-left" <?php selected($style['arrows_position'], 'middle-left'); ?>><?php esc_html_e('Middle Left', 'tw-simple-slider'); ?></option>
                            <option value="middle-right" <?php selected($style['arrows_position'], 'middle-right'); ?>><?php esc_html_e('Middle Right', 'tw-simple-slider'); ?></option>
                            <option value="bottom-left" <?php selected($style['arrows_position'], 'bottom-left'); ?>><?php esc_html_e('Bottom Left', 'tw-simple-slider'); ?></option>
                            <option value="bottom-center" <?php selected($style['arrows_position'], 'bottom-center'); ?>><?php esc_html_e('Bottom Center', 'tw-simple-slider'); ?></option>
                            <option value="bottom-right" <?php selected($style['arrows_position'], 'bottom-right'); ?>><?php esc_html_e('Bottom Right', 'tw-simple-slider'); ?></option>
                        </select>
                    </td>
                </tr>
            </table>
        </div>
        <?php
    }
    
    public function twssc_save_metabox_data($post_id) {
        if (!isset($_POST['twssc_slider_nonce_field'])) {
            return;
        }
        
        $nonce = sanitize_text_field(wp_unslash($_POST['twssc_slider_nonce_field']));
        if (!wp_verify_nonce($nonce, 'twssc_slider_nonce')) {
            return;
        }
        
        if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) {
            return;
        }
        
        if (!current_user_can('edit_post', $post_id)) {
            return;
        }
        
        if (isset($_POST['twssc_slider_images'])) {
            $images = array_map('intval', $_POST['twssc_slider_images']);
            $images = array_filter($images);
            update_post_meta($post_id, '_twssc_slider_images', $images);
        } else {
            delete_post_meta($post_id, '_twssc_slider_images');
        }
        
        if (isset($_POST['twssc_slider_slides_to_show'])) {
            $slides_to_show = sanitize_text_field(wp_unslash($_POST['twssc_slider_slides_to_show']));
            update_post_meta($post_id, '_twssc_slider_slides_to_show', $slides_to_show);
        }
        
        $fade_animation = isset($_POST['twssc_slider_fade_animation']) ? 'yes' : 'no';
        update_post_meta($post_id, '_twssc_slider_fade_animation', $fade_animation);
        
        $show_arrows = isset($_POST['twssc_slider_show_arrows']) ? 'yes' : 'no';
        update_post_meta($post_id, '_twssc_slider_show_arrows', $show_arrows);
        
        $show_dots = isset($_POST['twssc_slider_show_dots']) ? 'yes' : 'no';
        update_post_meta($post_id, '_twssc_slider_show_dots', $show_dots);
        
        $autoplay = isset($_POST['twssc_slider_autoplay']) ? 'yes' : 'no';
        update_post_meta($post_id, '_twssc_slider_autoplay', $autoplay);
        
        $pause_on_hover = isset($_POST['twssc_slider_pause_on_hover']) ? 'yes' : 'no';
        update_post_meta($post_id, '_twssc_slider_pause_on_hover', $pause_on_hover);

        if (isset($_POST['twssc_slider_custom_style'])) {
            $custom_style_input = array_map('sanitize_text_field', wp_unslash($_POST['twssc_slider_custom_style']));
            
            $allowed_fits = array('cover', 'contain', 'fill', 'scale-down');
            if (isset($custom_style_input['image_fit']) && !in_array($custom_style_input['image_fit'], $allowed_fits, true)) {
                $custom_style_input['image_fit'] = 'cover';
            }
            
            if (isset($custom_style_input['image_height'])) {
                $custom_style_input['image_height'] = absint($custom_style_input['image_height']);
                $custom_style_input['image_height'] = max(100, min(1000, $custom_style_input['image_height']));
            }
            
            if (isset($custom_style_input['dots_size'])) {
                $custom_style_input['dots_size'] = absint($custom_style_input['dots_size']);
                $custom_style_input['dots_size'] = max(6, min(20, $custom_style_input['dots_size']));
            }
            
            if (isset($custom_style_input['arrows_size'])) {
                $custom_style_input['arrows_size'] = absint($custom_style_input['arrows_size']);
                $custom_style_input['arrows_size'] = max(20, min(100, $custom_style_input['arrows_size']));
            }
            
            if (isset($custom_style_input['arrows_icon_size'])) {
                $custom_style_input['arrows_icon_size'] = absint($custom_style_input['arrows_icon_size']);
                $custom_style_input['arrows_icon_size'] = max(10, min(50, $custom_style_input['arrows_icon_size']));
            }
            
            if (isset($custom_style_input['custom_arrow_prev'])) {
                $custom_style_input['custom_arrow_prev'] = absint($custom_style_input['custom_arrow_prev']);
            }
            
            if (isset($custom_style_input['custom_arrow_next'])) {
                $custom_style_input['custom_arrow_next'] = absint($custom_style_input['custom_arrow_next']);
            }
            
            $allowed_types = array('default', 'custom');
            if (isset($custom_style_input['arrows_type']) && !in_array($custom_style_input['arrows_type'], $allowed_types, true)) {
                $custom_style_input['arrows_type'] = 'default';
            }
            
            $position_options = array('center', 'top-left', 'top-center', 'top-right', 'middle-left', 'middle-right', 'bottom-left', 'bottom-center', 'bottom-right');
            if (isset($custom_style_input['arrows_position']) && !in_array($custom_style_input['arrows_position'], $position_options, true)) {
                $custom_style_input['arrows_position'] = 'center';
            }
            
            update_post_meta($post_id, '_twssc_slider_custom_style', $custom_style_input);
        }
    }
}