<?php

// 1️⃣ Register the Custom Post Type
function register_travel_package_cpt() {
    $labels = array(
        'name'               => 'Travel Packages',
        'singular_name'      => 'Travel Package',
        'menu_name'          => 'Travel Packages',
        'name_admin_bar'     => 'Travel Package',
        'add_new'            => 'Add New',
        'add_new_item'       => 'Add New Travel Package',
        'new_item'           => 'New Travel Package',
        'edit_item'          => 'Edit Travel Package',
        'view_item'          => 'View Travel Package',
        'all_items'          => 'All Travel Packages',
        'search_items'       => 'Search Travel Packages',
        'not_found'          => 'No packages found',
        'not_found_in_trash' => 'No packages found in trash',
        'featured_image'     => 'Package Image',
        'set_featured_image' => 'Set package image',
        'remove_featured_image' => 'Remove package image',
        'use_featured_image' => 'Use as package image'
    );

    $args = array(
        'labels'             => $labels,
        'public'             => true,
        'publicly_queryable' => true,
        'show_ui'            => true,
        'show_in_menu'       => true,
        'query_var'          => true,
        'rewrite'            => array('slug' => 'travel-packages', 'with_front' => false),
        'has_archive'        => true,
        'hierarchical'       => false,
        'menu_position'      => 20,
        'supports'           => array('title', 'editor', 'thumbnail', 'excerpt', 'custom-fields'),
        'menu_icon'          => 'dashicons-airplane',
        'show_in_rest'       => true,
        'taxonomies'         => array('category', 'post_tag'),
    );

    register_post_type('travel_package', $args);
}
add_action('init', 'register_travel_package_cpt');

// 2️⃣ Add custom meta boxes for all package details
function travel_package_add_meta_boxes() {
    add_meta_box('travel_package_details', 'Package Details', 'travel_package_meta_box_callback', 'travel_package', 'normal', 'high');
    add_meta_box('travel_package_card_details', 'Package Card Details', 'travel_package_card_details_callback', 'travel_package', 'normal', 'high');
    add_meta_box('travel_package_itinerary', 'Itinerary Details', 'travel_package_itinerary_callback', 'travel_package', 'normal', 'high');
    add_meta_box('travel_package_includes_excludes', 'Price Includes/Excludes', 'travel_package_includes_excludes_callback', 'travel_package', 'normal', 'high');
    add_meta_box('travel_package_gallery', 'Gallery Images', 'travel_package_gallery_callback', 'travel_package', 'side', 'default');
}
add_action('add_meta_boxes', 'travel_package_add_meta_boxes');

function travel_package_meta_box_callback($post) {
    wp_nonce_field('save_travel_package_details', 'travel_package_nonce');

    $price_usd = get_post_meta($post->ID, '_price_usd', true);
    $price_ugx = get_post_meta($post->ID, '_price_ugx', true);
    $category = get_post_meta($post->ID, '_category', true);
    $destination = get_post_meta($post->ID, '_destination', true);
    $reviews = get_post_meta($post->ID, '_reviews', true);
    $badge = get_post_meta($post->ID, '_badge', true);
    $country = get_post_meta($post->ID, '_country', true);
    $city = get_post_meta($post->ID, '_city', true);
    $group_size = get_post_meta($post->ID, '_group_size', true);

    $categories = [
        "1 Adult",
        "2 Adults",
        "2 Adults & 1 Child",
        "2 Adults & 2 Children",
        "2 Adults & 3 Children",
        "3 Adults & 2 Children"
    ];

    $badges = [
        "Popular",
        "Best Value", 
        "Limited Time",
        "New",
        "Featured",
        "Hot Deal"
    ];

    ?>
    <table style="width: 100%;">
        <tr>
            <td style="width: 50%; padding-right: 15px;">
                <p><label><strong>Price (USD):</strong></label><br>
                    <input type="text" name="price_usd" value="<?php echo esc_attr($price_usd); ?>" placeholder="e.g., $299" style="width:100%;">
                </p>
            </td>
            <td style="width: 50%; padding-left: 15px;">
                <p><label><strong>Price (UGX):</strong></label><br>
                    <input type="text" name="price_ugx" value="<?php echo esc_attr($price_ugx); ?>" placeholder="e.g., UGX 1,100,000" style="width:100%;">
                </p>
            </td>
        </tr>
    </table>
    
    <p><label><strong>Category:</strong></label><br>
        <select name="category" style="width:100%;">
            <option value="">Select Category</option>
            <?php foreach ($categories as $cat) : ?>
                <option value="<?php echo esc_attr($cat); ?>" <?php selected($category, $cat); ?>><?php echo esc_html($cat); ?></option>
            <?php endforeach; ?>
        </select>
    </p>
    
    <table style="width: 100%;">
        <tr>
            <td style="width: 33%; padding-right: 10px;">
                <p><label><strong>Country:</strong></label><br>
                    <input type="text" name="country" value="<?php echo esc_attr($country); ?>" placeholder="e.g., France" style="width:100%;">
                </p>
            </td>
            <td style="width: 33%; padding: 0 5px;">
                <p><label><strong>City:</strong></label><br>
                    <input type="text" name="city" value="<?php echo esc_attr($city); ?>" placeholder="e.g., Paris" style="width:100%;">
                </p>
            </td>
            <td style="width: 33%; padding-left: 10px;">
                <p><label><strong>Destination (Legacy):</strong></label><br>
                    <input type="text" name="destination" value="<?php echo esc_attr($destination); ?>" placeholder="e.g., Maldives" style="width:100%;">
                </p>
            </td>
        </tr>
    </table>
    
    <p><label><strong>Group Size:</strong></label><br>
        <input type="text" name="group_size" value="<?php echo esc_attr($group_size); ?>" placeholder="e.g., 2-10 people" style="width:100%;">
    </p>
    
    <table style="width: 100%;">
        <tr>
            <td style="width: 50%; padding-right: 15px;">
                <p><label><strong>Reviews Count:</strong></label><br>
                    <input type="number" name="reviews" value="<?php echo esc_attr($reviews); ?>" min="0" style="width:100%;">
                </p>
            </td>
            <td style="width: 50%; padding-left: 15px;">
                <p><label><strong>Badge (Optional):</strong></label><br>
                    <select name="badge" style="width:100%;">
                        <option value="">No Badge</option>
                        <?php foreach ($badges as $badge_option) : ?>
                            <option value="<?php echo esc_attr($badge_option); ?>" <?php selected($badge, $badge_option); ?>><?php echo esc_html($badge_option); ?></option>
                        <?php endforeach; ?>
                    </select>
                </p>
            </td>
        </tr>
    </table>
    <?php
}

// Package Card Details Metabox
function travel_package_card_details_callback($post) {
    wp_nonce_field('save_travel_package_details', 'travel_package_nonce');
    
    $brief_description = get_post_meta($post->ID, '_brief_description', true);
    $trip_duration = get_post_meta($post->ID, '_trip_duration', true);
    $best_season = get_post_meta($post->ID, '_best_season', true);
    $accommodation = get_post_meta($post->ID, '_accommodation', true);
    ?>
    
    <p><label><strong>Brief Description (2-3 lines for package cards):</strong></label><br>
        <textarea name="brief_description" style="width:100%; height:80px;" placeholder="Short description that appears on package cards"><?php echo esc_textarea($brief_description); ?></textarea>
        <small>This description will appear on the package cards. Keep it concise and engaging.</small>
    </p>
    
    <table style="width: 100%;">
        <tr>
            <td style="width: 33%; padding-right: 10px;">
                <p><label><strong>Trip Duration:</strong></label><br>
                    <input type="text" name="trip_duration" value="<?php echo esc_attr($trip_duration); ?>" placeholder="e.g., 5 Days / 4 Nights" style="width:100%;">
                </p>
            </td>
            <td style="width: 33%; padding: 0 10px;">
                <p><label><strong>Best Season:</strong></label><br>
                    <input type="text" name="best_season" value="<?php echo esc_attr($best_season); ?>" placeholder="e.g., April to October" style="width:100%;">
                </p>
            </td>
            <td style="width: 33%; padding-left: 10px;">
                <p><label><strong>Accommodation:</strong></label><br>
                    <input type="text" name="accommodation" value="<?php echo esc_attr($accommodation); ?>" placeholder="e.g., Luxury Hotels" style="width:100%;">
                </p>
            </td>
        </tr>
    </table>
    <?php
}



// Itinerary Metabox
function travel_package_itinerary_callback($post) {
    wp_nonce_field('save_travel_package_details', 'travel_package_nonce');
    
    $itinerary_days = get_post_meta($post->ID, '_itinerary_days', true);
    if (empty($itinerary_days) || !is_array($itinerary_days)) {
        $itinerary_days = array(array('day_title' => '', 'day_description' => '', 'day_media' => array()));
    }
    ?>
    
    <div id="itinerary-days">
        <?php foreach ($itinerary_days as $index => $day): ?>
            <div class="itinerary-day" style="border: 1px solid #ddd; padding: 15px; margin-bottom: 15px; border-radius: 5px;">
                <h4 style="margin-top: 0;">Day <?php echo $index + 1; ?></h4>
                
                <p><label><strong>Day Title:</strong></label><br>
                    <input type="text" name="itinerary_days[<?php echo $index; ?>][day_title]" value="<?php echo esc_attr($day['day_title']); ?>" placeholder="e.g., Arrival in Paris" style="width:100%;">
                </p>
                
                <p><label><strong>Day Description:</strong></label><br>
                    <textarea name="itinerary_days[<?php echo $index; ?>][day_description]" style="width:100%; height:100px;" placeholder="Detailed description of the day's activities"><?php echo esc_textarea($day['day_description']); ?></textarea>
                </p>
                
                <!-- Day Media Section (Images & Videos) -->
                <div class="day-media-container">
                    <label><strong>Day Images & Videos:</strong></label>
                    <div class="day-media-grid" id="day-media-<?php echo $index; ?>" style="display: flex; flex-wrap: wrap; gap: 10px; margin: 10px 0;">
                        <?php 
                        $day_media = isset($day['day_media']) ? $day['day_media'] : array();
                        if (!empty($day_media)) :
                            foreach ($day_media as $media_index => $media_id) :
                                $media_url = wp_get_attachment_url($media_id);
                                $media_type = get_post_mime_type($media_id);
                                $is_video = strpos($media_type, 'video') !== false;
                                
                                if ($media_url) :
                        ?>
                            <div class="day-media-item" style="position: relative; display: inline-block;">
                                <?php if ($is_video): ?>
                                    <video src="<?php echo esc_url($media_url); ?>" style="width: 80px; height: 80px; object-fit: cover; border-radius: 4px;"></video>
                                    <span style="position: absolute; top: 2px; left: 2px; background: rgba(0,0,0,0.7); color: white; padding: 2px 4px; font-size: 9px; border-radius: 2px;">VIDEO</span>
                                <?php else: ?>
                                    <img src="<?php echo esc_url(wp_get_attachment_image_url($media_id, 'thumbnail')); ?>" style="width: 80px; height: 80px; object-fit: cover; border-radius: 4px;">
                                <?php endif; ?>
                                <input type="hidden" name="itinerary_days[<?php echo $index; ?>][day_media][]" value="<?php echo esc_attr($media_id); ?>">
                                <button type="button" class="remove-day-media" style="position: absolute; top: -8px; right: -8px; background: #dc3545; color: white; border: none; border-radius: 50%; width: 20px; height: 20px; cursor: pointer; font-size: 12px;">×</button>
                            </div>
                        <?php 
                                endif;
                            endforeach;
                        endif; 
                        ?>
                    </div>
                    <button type="button" class="add-day-media" data-day="<?php echo $index; ?>" style="background: #007cba; color: white; border: none; padding: 5px 10px; border-radius: 3px; margin-top: 5px;">Add Images/Videos</button>
                </div>
                
                <button type="button" class="remove-day" style="background: #dc3545; color: #fff; border: none; padding: 5px 10px; border-radius: 3px;">Remove Day</button>
            </div>
        <?php endforeach; ?>
    </div>
    
    <button type="button" id="add-itinerary-day" class="button button-primary" style="margin-top: 10px;">Add Another Day</button>
    
    <script>
    jQuery(document).ready(function($) {
        let dayIndex = <?php echo count($itinerary_days); ?>;
        
        // Add new itinerary day
        $('#add-itinerary-day').on('click', function() {
            var html = '<div class="itinerary-day" style="border: 1px solid #ddd; padding: 15px; margin-bottom: 15px; border-radius: 5px;">' +
                '<h4 style="margin-top: 0;">Day ' + (dayIndex + 1) + '</h4>' +
                '<p><label><strong>Day Title:</strong></label><br>' +
                '<input type="text" name="itinerary_days[' + dayIndex + '][day_title]" value="" placeholder="e.g., Arrival in Paris" style="width:100%;"></p>' +
                '<p><label><strong>Day Description:</strong></label><br>' +
                '<textarea name="itinerary_days[' + dayIndex + '][day_description]" style="width:100%; height:100px;" placeholder="Detailed description of the day\'s activities"></textarea></p>' +
                '<div class="day-media-container">' +
                '<label><strong>Day Images & Videos:</strong></label>' +
                '<div class="day-media-grid" id="day-media-' + dayIndex + '" style="display: flex; flex-wrap: wrap; gap: 10px; margin: 10px 0;"></div>' +
                '<button type="button" class="add-day-media" data-day="' + dayIndex + '" style="background: #007cba; color: white; border: none; padding: 5px 10px; border-radius: 3px; margin-top: 5px;">Add Images/Videos</button>' +
                '</div>' +
                '<button type="button" class="remove-day" style="background: #dc3545; color: #fff; border: none; padding: 5px 10px; border-radius: 3px;">Remove Day</button>' +
                '</div>';
            
            $('#itinerary-days').append(html);
            dayIndex++;
        });
        
        // Remove itinerary day
        $(document).on('click', '.remove-day', function() {
            if ($('.itinerary-day').length > 1) {
                $(this).closest('.itinerary-day').remove();
            } else {
                alert('You need at least one itinerary day.');
            }
        });
        
        // Add day media (images and videos)
        $(document).on('click', '.add-day-media', function(e) {
            e.preventDefault();
            
            var dayNum = $(this).data('day');
            var $container = $('#day-media-' + dayNum);
            
            var frame = wp.media({
                title: 'Select Images/Videos for Day ' + (dayNum + 1),
                multiple: true,
                library: { type: ['image', 'video'] },
                button: { text: 'Add Media' }
            });
            
            frame.on('select', function() {
                var attachments = frame.state().get('selection').toJSON();
                $.each(attachments, function() {
                    var isVideo = this.type === 'video';
                    var html = '<div class="day-media-item" style="position: relative; display: inline-block;">';
                    
                    if (isVideo) {
                        html += '<video src="' + this.url + '" style="width: 80px; height: 80px; object-fit: cover; border-radius: 4px;"></video>';
                        html += '<span style="position: absolute; top: 2px; left: 2px; background: rgba(0,0,0,0.7); color: white; padding: 2px 4px; font-size: 9px; border-radius: 2px;">VIDEO</span>';
                    } else {
                        html += '<img src="' + this.sizes.thumbnail.url + '" style="width: 80px; height: 80px; object-fit: cover; border-radius: 4px;">';
                    }
                    
                    html += '<input type="hidden" name="itinerary_days[' + dayNum + '][day_media][]" value="' + this.id + '">';
                    html += '<button type="button" class="remove-day-media" style="position: absolute; top: -8px; right: -8px; background: #dc3545; color: white; border: none; border-radius: 50%; width: 20px; height: 20px; cursor: pointer; font-size: 12px;">×</button>';
                    html += '</div>';
                    
                    $container.append(html);
                });
            });
            
            frame.open();
        });
        
        // Remove day media
        $(document).on('click', '.remove-day-media', function() {
            $(this).parent().remove();
        });
    });
    </script>
    <?php
}
    

// Includes/Excludes Metabox
function travel_package_includes_excludes_callback($post) {
    wp_nonce_field('save_travel_package_details', 'travel_package_nonce');
    
    $price_includes = get_post_meta($post->ID, '_price_includes', true);
    $price_excludes = get_post_meta($post->ID, '_price_excludes', true);
    
    if (empty($price_includes) || !is_array($price_includes)) {
        $price_includes = array('');
    }
    
    if (empty($price_excludes) || !is_array($price_excludes)) {
        $price_excludes = array('');
    }
    ?>
    
    <div style="display: flex; gap: 20px;">
        <div style="flex: 1;">
            <h3>Price Includes</h3>
            <div id="price-includes">
                <?php foreach ($price_includes as $index => $include): ?>
                    <p>
                        <input type="text" name="price_includes[]" value="<?php echo esc_attr($include); ?>" placeholder="e.g., 4 nights accommodation" style="width:100%;">
                        <?php if ($index > 0): ?>
                            <button type="button" class="button remove-include" style="background: #dc3545; color:#fff; border: none; margin-top: 5px;">Remove</button>
                        <?php endif; ?>
                    </p>
                <?php endforeach; ?>
            </div>
            <button type="button" id="add-include" class="button" style="margin-top: 10px;">Add Include Item</button>
        </div>
        
        <div style="flex: 1;">
            <h3>Price Excludes</h3>
            <div id="price-excludes">
                <?php foreach ($price_excludes as $index => $exclude): ?>
                    <p>
                        <input type="text" name="price_excludes[]" value="<?php echo esc_attr($exclude); ?>" placeholder="e.g., International airfare" style="width:100%;">
                        <?php if ($index > 0): ?>
                            <button type="button" class="button remove-exclude" style="background: #dc3545; color: #fff; border: none; margin-top: 5px;">Remove</button>
                        <?php endif; ?>
                    </p>
                <?php endforeach; ?>
            </div>
            <button type="button" id="add-exclude" class="button" style="margin-top: 10px;">Add Exclude Item</button>
        </div>
    </div>
    
    <script>
    jQuery(document).ready(function($) {
        $('#add-include').on('click', function() {
            $('#price-includes').append('<p><input type="text" name="price_includes[]" value="" placeholder="e.g., 4 nights accommodation" style="width:100%;"><button type="button" class="button remove-include" style="background: #dc3545; color: #fff; border: none; margin-top: 5px;">Remove</button></p>');
        });
        
        $('#add-exclude').on('click', function() {
            $('#price-excludes').append('<p><input type="text" name="price_excludes[]" value="" placeholder="e.g., International airfare" style="width:100%;"><button type="button" class="button remove-exclude" style="background: #dc3545; color: #fff; border: none; margin-top: 5px;">Remove</button></p>');
        });
        
        $(document).on('click', '.remove-include', function() {
            $(this).parent().remove();
        });
        
        $(document).on('click', '.remove-exclude', function() {
            $(this).parent().remove();
        });
    });
    </script>
    <?php
}

// Gallery Metabox
function travel_package_gallery_callback($post) {
    wp_nonce_field('save_travel_package_details', 'travel_package_nonce');
    
    $gallery_images = get_post_meta($post->ID, '_gallery_images', true);
    if (!is_array($gallery_images)) {
        $gallery_images = array();
    }
    ?>
    
    <div id="gallery-images-container">
        <?php foreach ($gallery_images as $image_id): ?>
            <?php if ($image_url = wp_get_attachment_image_url($image_id, 'thumbnail')): ?>
                <div class="gallery-image" style="display: inline-block; margin: 0 10px 10px 0; position: relative;">
                    <img src="<?php echo esc_url($image_url); ?>" style="width: 80px; height: 80px; object-fit: cover;">
                    <input type="hidden" name="gallery_images[]" value="<?php echo esc_attr($image_id); ?>">
                    <button type="button" class="button remove-image" style="position: absolute; top: -10px; right: -10px; background: #dc3545; color: #fff; border: none; border-radius: 50%; width: 20px; height: 20px; line-height: 1; padding: 0;">×</button>
                </div>
            <?php endif; ?>
        <?php endforeach; ?>
    </div>
    
    <button type="button" id="upload-gallery-image" class="button" style="margin-top: 10px;">Add Gallery Image</button>
    
    <script>
    jQuery(document).ready(function($) {
        $('#upload-gallery-image').on('click', function(e) {
            e.preventDefault();
            
            var frame = wp.media({
                title: 'Select Gallery Images',
                multiple: true,
                library: { type: 'image' },
                button: { text: 'Add to Gallery' }
            });
            
            frame.on('select', function() {
                var attachments = frame.state().get('selection').toJSON();
                $.each(attachments, function() {
                    var html = '<div class="gallery-image" style="display: inline-block; margin: 0 10px 10px 0; position: relative;">' +
                        '<img src="' + this.sizes.thumbnail.url + '" style="width: 80px; height: 80px; object-fit: cover;">' +
                        '<input type="hidden" name="gallery_images[]" value="' + this.id + '">' +
                        '<button type="button" class="button remove-image" style="position: absolute; top: -10px; right: -10px; background: #dc3545; color: #fff; border: none; border-radius: 50%; width: 20px; height: 20px; line-height: 1; padding: 0;">×</button>' +
                        '</div>';
                    
                    $('#gallery-images-container').append(html);
                });
            });
            
            frame.open();
        });
        
        $(document).on('click', '.remove-image', function() {
            $(this).parent().remove();
        });
    });
    </script>
    <?php
}

// Add Package Overview Metabox
function travel_package_overview_metabox() {
    add_meta_box(
        'travel_package_overview',
        'Package Overview (appears after breadcrumbs)',
        'travel_package_overview_callback',
        'travel_package',
        'normal',
        'high'
    );
}
add_action('add_meta_boxes', 'travel_package_overview_metabox');

function travel_package_overview_callback($post) {
    wp_nonce_field('save_travel_package_details', 'travel_package_nonce');
    
    $package_overview = get_post_meta($post->ID, '_package_overview', true);
    
    $settings = array(
        'textarea_name' => 'package_overview',
        'textarea_rows' => 15,
        'media_buttons' => true,
        'teeny' => false,
        'tinymce' => true,
        'quicktags' => true
    );
    
    wp_editor($package_overview, 'package_overview_editor', $settings);
    
    echo '<p class="description"><strong>This text will appear:</strong><br>1. On the package detail page (after breadcrumbs)<br>2. First 15 words will appear on package cards in the sidebar layout</p>';
}

function save_travel_package_details($post_id) {
    if (!isset($_POST['travel_package_nonce']) || !wp_verify_nonce($_POST['travel_package_nonce'], 'save_travel_package_details')) {
        return;
    }
    if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) return;
    if (!current_user_can('edit_post', $post_id)) return;

    if (isset($_POST['price_usd'])) update_post_meta($post_id, '_price_usd', sanitize_text_field($_POST['price_usd']));
    if (isset($_POST['price_ugx'])) update_post_meta($post_id, '_price_ugx', sanitize_text_field($_POST['price_ugx']));
    if (isset($_POST['category'])) update_post_meta($post_id, '_category', sanitize_text_field($_POST['category']));
    if (isset($_POST['destination'])) update_post_meta($post_id, '_destination', sanitize_text_field($_POST['destination']));
    if (isset($_POST['country'])) update_post_meta($post_id, '_country', sanitize_text_field($_POST['country']));
    if (isset($_POST['city'])) update_post_meta($post_id, '_city', sanitize_text_field($_POST['city']));
    if (isset($_POST['group_size'])) update_post_meta($post_id, '_group_size', sanitize_text_field($_POST['group_size']));
    if (isset($_POST['reviews'])) update_post_meta($post_id, '_reviews', intval($_POST['reviews']));
    if (isset($_POST['badge'])) update_post_meta($post_id, '_badge', sanitize_text_field($_POST['badge']));
    
    // Save overview details
    if (isset($_POST['brief_description'])) update_post_meta($post_id, '_brief_description', sanitize_textarea_field($_POST['brief_description']));
    if (isset($_POST['trip_duration'])) update_post_meta($post_id, '_trip_duration', sanitize_text_field($_POST['trip_duration']));
    if (isset($_POST['best_season'])) update_post_meta($post_id, '_best_season', sanitize_text_field($_POST['best_season']));
    if (isset($_POST['accommodation'])) update_post_meta($post_id, '_accommodation', sanitize_text_field($_POST['accommodation']));
    
    
    // Save itinerary
    if (isset($_POST['itinerary_days']) && is_array($_POST['itinerary_days'])) {
        $itinerary_days = array();
        foreach ($_POST['itinerary_days'] as $day) {
            if (!empty($day['day_title']) || !empty($day['day_description'])) {
                $itinerary_days[] = array(
                    'day_title' => sanitize_text_field($day['day_title']),
                    'day_description' => wp_kses_post($day['day_description']),
                    'day_media' => isset($day['day_media']) ? array_map('intval', $day['day_media']) : array()
                );
            }
        }
        update_post_meta($post_id, '_itinerary_days', $itinerary_days);
    }
    
    // Save includes/excludes
    if (isset($_POST['price_includes']) && is_array($_POST['price_includes'])) {
        $price_includes = array();
        foreach ($_POST['price_includes'] as $include) {
            if (!empty(trim($include))) {
                $price_includes[] = sanitize_text_field($include);
            }
        }
        update_post_meta($post_id, '_price_includes', $price_includes);
    }
    
    if (isset($_POST['price_excludes']) && is_array($_POST['price_excludes'])) {
        $price_excludes = array();
        foreach ($_POST['price_excludes'] as $exclude) {
            if (!empty(trim($exclude))) {
                $price_excludes[] = sanitize_text_field($exclude);
            }
        }
        update_post_meta($post_id, '_price_excludes', $price_excludes);
    }
    
    // Save gallery images
    if (isset($_POST['gallery_images']) && is_array($_POST['gallery_images'])) {
        $gallery_images = array();
        foreach ($_POST['gallery_images'] as $image_id) {
            if (!empty($image_id)) {
                $gallery_images[] = intval($image_id);
            }
        }
        update_post_meta($post_id, '_gallery_images', $gallery_images);
    }
    
    
if (isset($_POST['package_overview'])) {
    update_post_meta($post_id, '_package_overview', wp_kses_post($_POST['package_overview']));
}
}
add_action('save_post', 'save_travel_package_details');


// 3️⃣ Shortcode for dynamic packages - 2 COLUMNS MAX
function travel_packages_shortcode() {
    $categories = [
        "All Packages",
        "1 Adult",
        "2 Adults",
        "2 Adults & 1 Child",
        "2 Adults & 2 Children",
        "2 Adults & 3 Children",
        "3 Adults & 2 Children"
    ];

    ob_start(); ?>
    
    <div class="travel-services-panel" style="display:flex;gap:20px;">
        <!-- Sidebar -->
        <div class="services-sidebar" style="width:250px;flex-shrink:0;background:linear-gradient(135deg,#c94b4b 0%,#4b134f 100%);color:white;padding:15px;border-radius:8px;">
            <?php foreach ($categories as $index => $cat) : ?>
                <div class="sidebar-item <?php echo $index === 0 ? 'active' : ''; ?>" data-tab="cat-<?php echo $index; ?>" style="padding:10px 15px;cursor:pointer;border-left:3px solid transparent;transition:all 0.3s ease;margin-bottom:5px;color:white;border-radius:4px;">
                    <i class="fas fa-suitcase" style="margin-right:8px;"></i>
                    <span><?php echo esc_html($cat); ?></span>
                </div>
            <?php endforeach; ?>
        </div>

        <!-- Content -->
<div class="services-content" style="flex-grow:1;">
    <div class="child-definition" style="margin-bottom:20px;padding:10px;background:#f8f9fa;border-radius:5px;">
        <strong>Child Definition:</strong> Any individual who has not yet made their 12th birthday.
    </div>

    <?php foreach ($categories as $index => $cat) : ?>
        <div id="cat-<?php echo $index; ?>" class="content-item <?php echo $index === 0 ? 'active' : ''; ?>" style="display:<?php echo $index === 0 ? 'block' : 'none'; ?>;">
            <div class="packages-grid" style="display:grid;grid-template-columns:repeat(2, 1fr);gap:20px;padding:10px;max-width:1200px;">
                <?php
                $args = array(
                    'post_type' => 'travel_package',
                    'posts_per_page' => -1,
                    'post_status' => 'publish'
                );

                if ($cat !== "All Packages") {
                    $args['meta_query'] = array(
                        array(
                            'key' => '_category',
                            'value' => $cat,
                            'compare' => '='
                        )
                    );
                }

                $query = new WP_Query($args);

                if ($query->have_posts()) :
                    while ($query->have_posts()) : $query->the_post();
                        $price_usd = get_post_meta(get_the_ID(), '_price_usd', true);
                        $price_ugx = get_post_meta(get_the_ID(), '_price_ugx', true);
                        $country = get_post_meta(get_the_ID(), '_country', true);
                        $city = get_post_meta(get_the_ID(), '_city', true);
                        $group_size = get_post_meta(get_the_ID(), '_group_size', true);
                        $trip_duration = get_post_meta(get_the_ID(), '_trip_duration', true);
                        $reviews = get_post_meta(get_the_ID(), '_reviews', true);
                        $badge = get_post_meta(get_the_ID(), '_badge', true);
                        $package_overview = get_post_meta(get_the_ID(), '_package_overview', true);
                        $brief_description = get_post_meta(get_the_ID(), '_brief_description', true);
                        
                        // Determine card description text with priority order
                        $card_text = '';
                        if ($package_overview) {
                            // Strip HTML tags and get first 15 words from overview
                            $card_text = wp_trim_words(wp_strip_all_tags($package_overview), 15, '...');
                        } elseif ($brief_description) {
                            $card_text = wp_trim_words($brief_description, 15, '...');
                        } elseif (has_excerpt()) {
                            $card_text = wp_trim_words(get_the_excerpt(), 15, '...');
                        } else {
                            $card_text = wp_trim_words(get_the_content(), 15, '...');
                        }
                        
                        $image_id = get_post_thumbnail_id(get_the_ID());
                        if ($image_id) {
                            $image = wp_get_attachment_image_url($image_id, 'medium_large');
                        } else {
                            $image = 'https://via.placeholder.com/400x200/cccccc/666666?text=No+Image';
                        }
                        ?>
                        <div class="package-card" style="border:1px solid #eee;border-radius:8px;overflow:hidden;box-shadow:0 3px 10px rgba(0,0,0,0.1);background:#fff;transition:transform 0.3s ease;max-width:500px;">
                            <div class="package-image" style="background-image:url('<?php echo esc_url($image); ?>');background-size:cover;background-position:center;height:180px;position:relative;">
                                <?php if ($badge) : ?>
                                    <div class="package-badge" style="position:absolute;top:8px;left:8px;background:#dc3545;color:#fff;padding:4px 8px;border-radius:12px;font-size:10px;font-weight:bold;text-transform:uppercase;">
                                        <?php echo esc_html($badge); ?>
                                    </div>
                                <?php endif; ?>
                                
                                <div class="package-prices" style="position:absolute;top:8px;right:8px;">
                                    <?php if ($price_usd) : ?>
                                        <div style="background:#dc3545;color:#fff;padding:4px 8px;border-radius:4px;font-weight:bold;margin-bottom:2px;font-size:11px;">
                                            <?php echo esc_html($price_usd); ?>
                                        </div>
                                    <?php endif; ?>
                                    <?php if ($price_ugx) : ?>
                                        <div style="background:rgba(0,0,0,0.7);color:#fff;padding:2px 6px;border-radius:3px;font-size:9px;">
                                            <?php echo esc_html($price_ugx); ?>
                                        </div>
                                    <?php endif; ?>
                                </div>
                            </div>
                            
                            <div class="package-info" style="padding:15px;">
                                <h3 style="margin:0 0 8px;font-size:1.1rem;line-height:1.3;">
                                    <a href="<?php the_permalink(); ?>" style="color:#333;text-decoration:none;">
                                        <?php the_title(); ?>
                                    </a>
                                </h3>
                                
                                <div class="package-description" style="font-size:0.9rem;color:#555;margin-bottom:12px;line-height:1.5;min-height:42px;">
                                    <?php echo esc_html($card_text); ?>
                                </div>
                                
                                <div class="package-details" style="margin-bottom:12px;">
                                    <?php if ($country || $city) : ?>
                                        <div style="font-size:0.85rem;color:#666;margin-bottom:5px;">
                                            <i class="fas fa-map-marker-alt" style="color:#dc3545;margin-right:4px;width:14px;"></i>
                                            <?php 
                                            if ($country && $city) {
                                                echo esc_html($city . ', ' . $country);
                                            } elseif ($country) {
                                                echo esc_html($country);
                                            } elseif ($city) {
                                                echo esc_html($city);
                                            }
                                            ?>
                                        </div>
                                    <?php endif; ?>
                                    
                                    <?php if ($trip_duration) : ?>
                                        <div style="font-size:0.85rem;color:#666;margin-bottom:5px;">
                                            <i class="fas fa-clock" style="color:#007bff;margin-right:4px;width:14px;"></i>
                                            <?php echo esc_html($trip_duration); ?>
                                        </div>
                                    <?php endif; ?>
                                    
                                    <?php if ($group_size) : ?>
                                        <div style="font-size:0.85rem;color:#666;margin-bottom:5px;">
                                            <i class="fas fa-users" style="color:#28a745;margin-right:4px;width:14px;"></i>
                                            <?php echo esc_html($group_size); ?>
                                        </div>
                                    <?php endif; ?>
                                </div>
                                
                                <div class="package-meta" style="display:flex;justify-content:space-between;align-items:center;border-top:1px solid #eee;padding-top:10px;">
                                    <?php if ($reviews && $reviews > 0) : ?>
                                        <div class="package-rating" style="font-size:0.85rem;color:#888;">
                                            <span style="color:#ffa500;">★★★★★</span> 
                                            <span class="review-count">(<?php echo intval($reviews); ?>)</span>
                                        </div>
                                    <?php else : ?>
                                        <div></div>
                                    <?php endif; ?>
                                    
                                    <a href="<?php the_permalink(); ?>" class="view-details-btn" style="display:inline-block;padding:8px 16px;background:#1e3a8a;color:#fff;border-radius:4px;text-decoration:none;font-size:0.85rem;font-weight:500;transition:background 0.3s ease;">
                                        View Details
                                    </a>
                                </div>
                            </div>
                        </div>
                    <?php endwhile;
                    wp_reset_postdata();
                else :
                    echo '<div style="grid-column:1/-1;text-align:center;padding:60px 20px;color:#666;font-size:1.1rem;">';
                    echo '<i class="fas fa-suitcase" style="font-size:3rem;margin-bottom:1rem;opacity:0.3;"></i><br>';
                    echo 'No packages found in this category.<br>';
                    echo '<small style="color:#999;margin-top:10px;display:block;">Add travel packages to see them here.</small>';
                    echo '</div>';
                endif;
                ?>
            </div>
        </div>
    <?php endforeach; ?>
</div>

    <script>
        jQuery(document).ready(function($) {
            $('.sidebar-item').on('click', function() {
                $('.sidebar-item').removeClass('active');
                $(this).addClass('active');
                $('.content-item').hide().removeClass('active');
                var tabId = $(this).data('tab');
                $('#' + tabId).show().addClass('active');
                $('.services-content').scrollTop(0);
            });
            
            $('.sidebar-item').hover(
                function() {
                    if (!$(this).hasClass('active')) {
                        $(this).css('background-color', 'rgba(255, 255, 255, 0.1)');
                    }
                },
                function() {
                    if (!$(this).hasClass('active')) {
                        $(this).css('background-color', 'transparent');
                    }
                }
            );
            
            $('.content-item').hide();
            $('#cat-0').show().addClass('active');
            
            $('.view-details-btn').hover(
                function() { $(this).css('background', '#162d6b'); },
                function() { $(this).css('background', '#1e3a8a'); }
            );
        });
    </script>
    
    <style>
        .sidebar-item.active{background-color:rgba(255,255,255,0.2)!important;border-left-color:#ffb3d9!important;font-weight:bold;}
        .package-card:hover{transform:translateY(-5px);box-shadow:0 5px 20px rgba(0,0,0,0.15);}
        @media (max-width:768px){.packages-grid{grid-template-columns:1fr!important;}.travel-services-panel{flex-direction:column;}.services-sidebar{width:100%!important;}}
    </style>
    <?php
    return ob_get_clean();
}
add_shortcode('travel_packages', 'travel_packages_shortcode');

// Enqueue assets
function travel_packages_enqueue_assets() {
    wp_enqueue_style('font-awesome', 'https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.4/css/all.min.css', array(), '5.15.4');
    
    if (!wp_script_is('jquery', 'enqueued')) {
        wp_enqueue_script('jquery');
    }
    
    if (is_admin()) {
        wp_enqueue_media();
    }
}
add_action('wp_enqueue_scripts', 'travel_packages_enqueue_assets');

// Add featured image support
function travel_packages_add_thumbnail_support() {
    add_theme_support('post-thumbnails');
    add_image_size('travel-package-thumb', 600, 400, true);
}
add_action('after_setup_theme', 'travel_packages_add_thumbnail_support');

?>