<?php

namespace auctionforge\inc\controllers;

if (!defined('ABSPATH')) {
    die('You shouldnt be here');
}

class ManualAuctions
{
    const POST_TYPE = 'manual_auction';
    const META_PREFIX = '_manual_auction_';

    public function init()
    {
        add_action('init', array($this, 'register_post_type'), 0);
        add_action('add_meta_boxes', array($this, 'add_meta_boxes'));
        add_action('save_post_' . self::POST_TYPE, array($this, 'save_meta_boxes'), 10, 2);
        add_action('admin_enqueue_scripts', array($this, 'enqueue_admin_scripts'));
        add_filter('manage_' . self::POST_TYPE . '_posts_columns', array($this, 'set_custom_columns'));
        add_action('manage_' . self::POST_TYPE . '_posts_custom_column', array($this, 'render_custom_columns'), 10, 2);
        add_filter('manage_edit-' . self::POST_TYPE . '_sortable_columns', array($this, 'sortable_columns'));
        add_action('pre_get_posts', array($this, 'custom_orderby'));
        add_filter('template_include', array($this, 'load_single_template'), 99);
    }

    public function register_post_type()
    {
        $labels = array(
            'name'               => __('Manual Auctions', 'auctionforge'),
            'singular_name'      => __('Manual Auction', 'auctionforge'),
            'menu_name'          => __('Add Auction', 'auctionforge'),
            'all_items'          => __('Add Auction', 'auctionforge'),
            'add_new'            => __('Add New', 'auctionforge'),
            'add_new_item'       => __('Add New Manual Auction', 'auctionforge'),
            'edit_item'          => __('Edit Manual Auction', 'auctionforge'),
            'new_item'           => __('New Manual Auction', 'auctionforge'),
            'view_item'          => __('View Manual Auction', 'auctionforge'),
            'search_items'       => __('Search Manual Auctions', 'auctionforge'),
            'not_found'          => __('No manual auctions found', 'auctionforge'),
            'not_found_in_trash' => __('No manual auctions found in trash', 'auctionforge'),
        );

        $args = array(
            'labels'             => $labels,
            'public'             => true,
            'show_ui'            => true,
            'show_in_menu'       => 'edit.php?post_type=lot',
            'supports'           => array('title', 'editor', 'thumbnail'),
            'has_archive'        => false,
            'publicly_queryable' => true,
            'exclude_from_search'=> true,
            'capability_type'    => 'post',
            'menu_position'      => 5,
            'rewrite'            => array('slug' => 'auction-listing', 'with_front' => false),
        );

        register_post_type(self::POST_TYPE, $args);
    }

    public function load_single_template($template)
    {
        if (is_singular(self::POST_TYPE)) {
            $plugin_template = plugin_dir_path(dirname(__DIR__)) . 'templates/single-manual_auction.php';
            $theme_template = get_stylesheet_directory() . '/auctionforge/single-manual_auction.php';

            if (file_exists($theme_template)) {
                return $theme_template;
            } elseif (file_exists($plugin_template)) {
                return $plugin_template;
            }
        }
        return $template;
    }

    public function add_meta_boxes()
    {
        add_meta_box(
            'manual_auction_details',
            __('Auction Details', 'auctionforge'),
            array($this, 'render_details_meta_box'),
            self::POST_TYPE,
            'normal',
            'high'
        );

        add_meta_box(
            'manual_auction_gallery',
            __('Auction Gallery', 'auctionforge'),
            array($this, 'render_gallery_meta_box'),
            self::POST_TYPE,
            'normal',
            'default'
        );
    }

    public function render_details_meta_box($post)
    {
        wp_nonce_field('manual_auction_save', 'manual_auction_nonce');

        $date = get_post_meta($post->ID, self::META_PREFIX . 'date', true);
        $time = get_post_meta($post->ID, self::META_PREFIX . 'time', true);
        $auction_type = get_post_meta($post->ID, self::META_PREFIX . 'auction_type', true);
        $auction_link = get_post_meta($post->ID, self::META_PREFIX . 'auction_link', true);
        $auction_status = get_post_meta($post->ID, self::META_PREFIX . 'status', true);
        $auction_category = get_post_meta($post->ID, self::META_PREFIX . 'category', true);

        if (empty($auction_type)) {
            $auction_type = 'in_person';
        }
        if (empty($auction_status)) {
            $auction_status = 'upcoming';
        }
        ?>
        <style>
            .manual-auction-meta-box { padding: 10px 0; }
            .manual-auction-meta-box .form-row { margin-bottom: 15px; display: flex; align-items: flex-start; }
            .manual-auction-meta-box .form-row label { display: block; font-weight: 600; width: 150px; min-width: 150px; padding-top: 5px; }
            .manual-auction-meta-box .form-row .field-input { flex: 1; }
            .manual-auction-meta-box .form-row input[type="text"],
            .manual-auction-meta-box .form-row input[type="url"],
            .manual-auction-meta-box .form-row input[type="date"],
            .manual-auction-meta-box .form-row input[type="time"],
            .manual-auction-meta-box .form-row select { width: 100%; max-width: 400px; }
            .manual-auction-meta-box .form-row .description { color: #666; font-style: italic; margin-top: 4px; font-size: 12px; }
            .manual-auction-meta-box .form-row .field-inline { display: flex; gap: 10px; }
            .manual-auction-meta-box .form-row .field-inline input { max-width: 195px; }
        </style>
        <div class="manual-auction-meta-box">
            <div class="form-row">
                <label for="manual_auction_date"><?php _e('Date & Time', 'auctionforge'); ?> *</label>
                <div class="field-input">
                    <div class="field-inline">
                        <input type="date" id="manual_auction_date" name="manual_auction_date" value="<?php echo esc_attr($date); ?>" required />
                        <input type="time" id="manual_auction_time" name="manual_auction_time" value="<?php echo esc_attr($time); ?>" required />
                    </div>
                    <p class="description"><?php _e('The date and time of the auction. Used for sorting in the auction list.', 'auctionforge'); ?></p>
                </div>
            </div>

            <div class="form-row">
                <label for="manual_auction_type"><?php _e('Auction Type', 'auctionforge'); ?> *</label>
                <div class="field-input">
                    <select id="manual_auction_type" name="manual_auction_type">
                        <option value="in_person" <?php selected($auction_type, 'in_person'); ?>><?php _e('In Person', 'auctionforge'); ?></option>
                        <option value="online" <?php selected($auction_type, 'online'); ?>><?php _e('Online', 'auctionforge'); ?></option>
                    </select>
                    <p class="description"><?php _e('Whether this is an in-person or online auction.', 'auctionforge'); ?></p>
                </div>
            </div>

            <div class="form-row">
                <label for="manual_auction_link"><?php _e('External Auction Link', 'auctionforge'); ?></label>
                <div class="field-input">
                    <input type="url" id="manual_auction_link" name="manual_auction_link" value="<?php echo esc_url($auction_link); ?>" placeholder="https://" />
                    <p class="description"><?php _e('Optional. If provided, the "View Auction" button links to this external URL. If left empty, the button links to this auction\'s own page on your site.', 'auctionforge'); ?></p>
                </div>
            </div>

            <div class="form-row">
                <label for="manual_auction_status"><?php _e('Auction Status', 'auctionforge'); ?></label>
                <div class="field-input">
                    <select id="manual_auction_status" name="manual_auction_status">
                        <option value="upcoming" <?php selected($auction_status, 'upcoming'); ?>><?php _e('Upcoming', 'auctionforge'); ?></option>
                        <option value="ended" <?php selected($auction_status, 'ended'); ?>><?php _e('Ended', 'auctionforge'); ?></option>
                    </select>
                    <p class="description"><?php _e('Set to "Ended" once the auction has concluded.', 'auctionforge'); ?></p>
                </div>
            </div>


            <div class="form-row">
                <label for="manual_auction_category"><?php _e('Auction Category', 'auctionforge'); ?></label>
                <div class="field-input">
                    <?php $categories = Settings::getAuctionCategories(); ?>
                    <select id="manual_auction_category" name="manual_auction_category">
                        <option value=""><?php _e('— None —', 'auctionforge'); ?></option>
                        <?php foreach ($categories as $cat) : ?>
                            <option value="<?php echo esc_attr($cat['letter']); ?>" <?php selected($auction_category, $cat['letter']); ?>><?php echo esc_html($cat['name'] . ' (' . $cat['letter'] . ')'); ?></option>
                        <?php endforeach; ?>
                    </select>
                    <p class="description"><?php _e('Assign this auction to a category for filtering with the [bp_auction_list] shortcode.', 'auctionforge'); ?></p>
                </div>
            </div>

            <div class="form-row">
                <label><?php _e('Cover Image', 'auctionforge'); ?></label>
                <div class="field-input">
                    <p class="description"><?php _e('Use the "Set featured image" option in the right sidebar to set the auction cover image.', 'auctionforge'); ?></p>
                </div>
            </div>
        </div>
        <?php
    }

    public function render_gallery_meta_box($post)
    {
        $gallery_ids = get_post_meta($post->ID, self::META_PREFIX . 'gallery', true);
        if (!is_array($gallery_ids)) {
            $gallery_ids = !empty($gallery_ids) ? array_filter(array_map('intval', explode(',', $gallery_ids))) : array();
        }
        ?>
        <style>
            .manual-auction-gallery-wrap { padding: 10px 0; }
            .manual-auction-gallery-wrap .gallery-images { display: flex; flex-wrap: wrap; gap: 10px; margin-bottom: 15px; min-height: 30px; }
            .manual-auction-gallery-wrap .gallery-images .gallery-item { position: relative; width: 120px; height: 120px; border: 1px solid #ddd; border-radius: 4px; overflow: hidden; cursor: grab; }
            .manual-auction-gallery-wrap .gallery-images .gallery-item.ui-sortable-helper { cursor: grabbing; box-shadow: 0 2px 8px rgba(0,0,0,0.3); }
            .manual-auction-gallery-wrap .gallery-images .gallery-item.ui-sortable-placeholder { visibility: visible !important; background: #f0f0f0; border: 2px dashed #aaa; }
            .manual-auction-gallery-wrap .gallery-images .gallery-item img { width: 100%; height: 100%; object-fit: cover; }
            .manual-auction-gallery-wrap .gallery-images .gallery-item .remove-image { position: absolute; top: 2px; right: 2px; background: rgba(200,0,0,0.8); color: #fff; border: none; border-radius: 50%; width: 22px; height: 22px; font-size: 14px; line-height: 20px; text-align: center; cursor: pointer; padding: 0; }
            .manual-auction-gallery-wrap .gallery-images .gallery-item .remove-image:hover { background: rgba(200,0,0,1); }
            .manual-auction-gallery-wrap .gallery-debug { margin-top: 8px; padding: 4px 8px; background: #f0f0f0; font-size: 11px; color: #666; font-family: monospace; }
        </style>
        <div class="manual-auction-gallery-wrap">
            <p class="description" style="margin-bottom:10px;"><?php _e('Add images to the auction gallery. These will be displayed on the auction detail page.', 'auctionforge'); ?></p>
            <div id="manual-auction-gallery-images" class="gallery-images">
                <?php foreach ($gallery_ids as $img_id) {
                    $img_id = intval($img_id);
                    if ($img_id <= 0) continue;
                    $img_url = wp_get_attachment_image_url($img_id, 'thumbnail');
                    if (!$img_url) continue;
                    ?>
                    <div class="gallery-item" data-id="<?php echo $img_id; ?>">
                        <img src="<?php echo esc_url($img_url); ?>" />
                        <button type="button" class="remove-image" title="<?php _e('Remove', 'auctionforge'); ?>">&times;</button>
                    </div>
                <?php } ?>
            </div>
            <input type="hidden" id="manual_auction_gallery_input" name="manual_auction_gallery" value="<?php echo esc_attr(implode(',', $gallery_ids)); ?>" />
            <button type="button" id="manual-auction-add-gallery" class="button"><?php _e('Add Gallery Images', 'auctionforge'); ?></button>
            <button type="button" id="manual-auction-inverse-gallery" class="button" style="margin-left:5px;"><?php _e('Inverse Order', 'auctionforge'); ?></button>
            <p class="description" style="margin-top:6px;"><?php _e('Drag and drop images to reorder them.', 'auctionforge'); ?></p>
            <div id="manual-auction-gallery-debug" class="gallery-debug"></div>
        </div>
        <script>
        jQuery(document).ready(function($) {
            var galleryFrame;
            var container = document.getElementById('manual-auction-gallery-images');
            var hiddenInput = document.getElementById('manual_auction_gallery_input');
            var debugEl = document.getElementById('manual-auction-gallery-debug');

            function updateGalleryInput() {
                var items = container.querySelectorAll('.gallery-item');
                var ids = [];
                for (var i = 0; i < items.length; i++) {
                    var id = items[i].getAttribute('data-id');
                    if (id) ids.push(id);
                }
                var val = ids.join(',');
                hiddenInput.value = val;
                hiddenInput.setAttribute('value', val);
                debugEl.textContent = 'Gallery IDs: ' + (val || '(empty)') + ' | Input name: ' + hiddenInput.name + ' | Items: ' + items.length;
            }

            // Drag-and-drop reordering via jQuery UI Sortable
            $(container).sortable({
                items: '.gallery-item',
                cursor: 'grabbing',
                placeholder: 'gallery-item ui-sortable-placeholder',
                tolerance: 'pointer',
                update: function() {
                    updateGalleryInput();
                }
            });

            // Inverse Order button
            document.getElementById('manual-auction-inverse-gallery').addEventListener('click', function(e) {
                e.preventDefault();
                var items = Array.prototype.slice.call(container.querySelectorAll('.gallery-item'));
                items.reverse();
                for (var i = 0; i < items.length; i++) {
                    container.appendChild(items[i]);
                }
                updateGalleryInput();
            });

            document.getElementById('manual-auction-add-gallery').addEventListener('click', function(e) {
                e.preventDefault();
                if (galleryFrame) {
                    galleryFrame.open();
                    return;
                }
                galleryFrame = wp.media({
                    title: '<?php echo esc_js(__("Select Gallery Images", "auctionforge")); ?>',
                    button: { text: '<?php echo esc_js(__("Add to Gallery", "auctionforge")); ?>' },
                    multiple: true,
                    library: { type: 'image' }
                });
                galleryFrame.on('select', function() {
                    var selection = galleryFrame.state().get('selection');
                    selection.each(function(attachment) {
                        var id = attachment.id;
                        var url = (attachment.attributes.sizes && attachment.attributes.sizes.thumbnail)
                            ? attachment.attributes.sizes.thumbnail.url
                            : attachment.attributes.url;
                        if (!container.querySelector('.gallery-item[data-id="' + id + '"]')) {
                            var div = document.createElement('div');
                            div.className = 'gallery-item';
                            div.setAttribute('data-id', id);
                            div.innerHTML = '<img src="' + url + '" /><button type="button" class="remove-image" title="Remove">&times;</button>';
                            container.appendChild(div);
                        }
                    });
                    updateGalleryInput();
                });
                galleryFrame.open();
            });

            container.addEventListener('click', function(e) {
                if (e.target.classList.contains('remove-image') || e.target.closest('.remove-image')) {
                    var item = e.target.closest('.gallery-item');
                    if (item) {
                        item.parentNode.removeChild(item);
                        updateGalleryInput();
                    }
                }
            });

            // Safety net: update hidden input right before form submit
            var postForm = document.getElementById('post');
            if (postForm) {
                postForm.addEventListener('submit', function() {
                    updateGalleryInput();
                });
            }

            // Init debug display
            updateGalleryInput();
        });
        </script>
        <?php
    }

    public function save_meta_boxes($post_id, $post)
    {
        // Debug log
        error_log('ManualAuctions save: post_id=' . $post_id . ' has_nonce=' . (isset($_POST['manual_auction_nonce']) ? '1' : '0') . ' has_gallery=' . (isset($_POST['manual_auction_gallery']) ? $_POST['manual_auction_gallery'] : 'NOT SET'));

        if (!isset($_POST['manual_auction_nonce']) || !wp_verify_nonce($_POST['manual_auction_nonce'], 'manual_auction_save')) {
            return;
        }

        if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) {
            return;
        }

        if (!current_user_can('edit_post', $post_id)) {
            return;
        }

        $fields = array(
            'manual_auction_date'   => 'date',
            'manual_auction_time'   => 'time',
            'manual_auction_type'   => 'auction_type',
            'manual_auction_link'   => 'auction_link',
            'manual_auction_status'   => 'status',
            'manual_auction_category' => 'category',
        );

        foreach ($fields as $post_field => $meta_key) {
            if (isset($_POST[$post_field])) {
                $value = sanitize_text_field($_POST[$post_field]);
                if ($meta_key === 'auction_link') {
                    $value = esc_url_raw($_POST[$post_field]);
                }
                update_post_meta($post_id, self::META_PREFIX . $meta_key, $value);
            }
        }

        // Save gallery
        if (isset($_POST['manual_auction_gallery'])) {
            $gallery = sanitize_text_field($_POST['manual_auction_gallery']);
            $gallery_ids = array_filter(array_map('intval', explode(',', $gallery)));
            error_log('ManualAuctions gallery: raw="' . $gallery . '" count=' . count($gallery_ids));
            update_post_meta($post_id, self::META_PREFIX . 'gallery', $gallery_ids);
        }
    }

    public function enqueue_admin_scripts($hook)
    {
        global $post_type;
        if ($post_type === self::POST_TYPE) {
            wp_enqueue_media();
            wp_enqueue_script('jquery-ui-sortable');
        }
    }

    public function set_custom_columns($columns)
    {
        $new_columns = array();
        $new_columns['cb'] = $columns['cb'];
        $new_columns['title'] = $columns['title'];
        $new_columns['auction_type'] = __('Type', 'auctionforge');
        $new_columns['auction_date'] = __('Auction Date', 'auctionforge');
        $new_columns['auction_status'] = __('Status', 'auctionforge');
        $new_columns['auction_category'] = __('Category', 'auctionforge');
        $new_columns['auction_link'] = __('Link', 'auctionforge');
        $new_columns['date'] = $columns['date'];
        return $new_columns;
    }

    public function render_custom_columns($column, $post_id)
    {
        switch ($column) {
            case 'auction_type':
                $type = get_post_meta($post_id, self::META_PREFIX . 'auction_type', true);
                echo $type === 'online' ? __('Online', 'auctionforge') : __('In Person', 'auctionforge');
                break;
            case 'auction_date':
                $date = get_post_meta($post_id, self::META_PREFIX . 'date', true);
                $time = get_post_meta($post_id, self::META_PREFIX . 'time', true);
                if ($date) {
                    echo esc_html(date_i18n('F d, Y', strtotime($date)));
                    if ($time) {
                        echo ' ' . esc_html($time);
                    }
                } else {
                    echo '&#8212;';
                }
                break;
            case 'auction_status':
                $status = get_post_meta($post_id, self::META_PREFIX . 'status', true);
                if ($status === 'ended') {
                    echo '<span style="color:#a00;">' . __('Ended', 'auctionforge') . '</span>';
                } else {
                    echo '<span style="color:#0a0;">' . __('Upcoming', 'auctionforge') . '</span>';
                }
                break;
            case 'auction_category':
                $cat = get_post_meta($post_id, self::META_PREFIX . 'category', true);
                if ($cat) {
                    $categories = Settings::getAuctionCategories();
                    $catName = $cat;
                    foreach ($categories as $c) {
                        if (strtoupper($c['letter']) === strtoupper($cat)) {
                            $catName = $c['name'] . ' (' . $c['letter'] . ')';
                            break;
                        }
                    }
                    echo esc_html($catName);
                } else {
                    echo '&#8212;';
                }
                break;
            case 'auction_link':
                $link = get_post_meta($post_id, self::META_PREFIX . 'auction_link', true);
                if ($link) {
                    echo '<a href="' . esc_url($link) . '" target="_blank">' . __('External', 'auctionforge') . '</a>';
                } else {
                    echo '<a href="' . get_permalink($post_id) . '">' . __('Internal', 'auctionforge') . '</a>';
                }
                break;
        }
    }

    public function sortable_columns($columns)
    {
        $columns['auction_date'] = 'auction_date';
        $columns['auction_status'] = 'auction_status';
        return $columns;
    }

    public function custom_orderby($query)
    {
        if (!is_admin() || !$query->is_main_query()) {
            return;
        }

        if ($query->get('post_type') !== self::POST_TYPE) {
            return;
        }

        $orderby = $query->get('orderby');

        if ($orderby === 'auction_date') {
            $query->set('meta_key', self::META_PREFIX . 'date');
            $query->set('orderby', 'meta_value');
        } elseif ($orderby === 'auction_status') {
            $query->set('meta_key', self::META_PREFIX . 'status');
            $query->set('orderby', 'meta_value');
        }
    }

    private static function buildAuctionObject($post, $status)
    {
        $date = get_post_meta($post->ID, self::META_PREFIX . 'date', true);
        $time = get_post_meta($post->ID, self::META_PREFIX . 'time', true);
        $auction_type = get_post_meta($post->ID, self::META_PREFIX . 'auction_type', true);
        $auction_link = get_post_meta($post->ID, self::META_PREFIX . 'auction_link', true);
        $feature_image = get_the_post_thumbnail_url($post->ID, 'full');
        $gallery_ids = get_post_meta($post->ID, self::META_PREFIX . 'gallery', true);
        if (!is_array($gallery_ids)) {
            $gallery_ids = !empty($gallery_ids) ? array_filter(array_map('intval', explode(',', $gallery_ids))) : array();
        }

        $has_external_link = !empty($auction_link);
        $view_link = $has_external_link ? $auction_link : get_permalink($post->ID);

        return (object) array(
            'is_manual'         => true,
            'post_id'           => $post->ID,
            'title'             => $post->post_title,
            'description'       => $post->post_content,
            'date'              => $date,
            'time'              => $time ? $time : '00:00',
            'datetime'          => $date . ' ' . ($time ? $time : '00:00'),
            'auction_type'      => $auction_type ? $auction_type : 'in_person',
            'auction_link'      => $view_link,
            'has_external_link' => $has_external_link,
            'feature_image'     => $feature_image,
            'gallery_ids'       => $gallery_ids,
            'permalink'         => get_permalink($post->ID),
            'status'            => $status,
        );
    }

    public static function getUpcomingManualAuctions()
    {
        $args = array(
            'post_type'      => self::POST_TYPE,
            'post_status'    => 'publish',
            'posts_per_page' => -1,
            'meta_query'     => array(
                array(
                    'key'     => self::META_PREFIX . 'status',
                    'value'   => 'upcoming',
                    'compare' => '='
                ),
            ),
        );

        $posts = get_posts($args);
        $manualAuctions = array();

        foreach ($posts as $post) {
            $manualAuctions[] = self::buildAuctionObject($post, 'upcoming');
        }

        return $manualAuctions;
    }

    public static function getEndedManualAuctions()
    {
        $args = array(
            'post_type'      => self::POST_TYPE,
            'post_status'    => 'publish',
            'posts_per_page' => -1,
            'meta_query'     => array(
                array(
                    'key'     => self::META_PREFIX . 'status',
                    'value'   => 'ended',
                    'compare' => '='
                ),
            ),
        );

        $posts = get_posts($args);
        $manualAuctions = array();

        foreach ($posts as $post) {
            $manualAuctions[] = self::buildAuctionObject($post, 'ended');
        }

        return $manualAuctions;
    }
}

$manualAuctions = new ManualAuctions();
$manualAuctions->init();
