<?php
/**
 * Safari Packages Custom Post Type with Costs
 * Add this code to your theme's functions.php file
 */

// Register Custom Post Type for Packages
function create_packages_post_type() {
    $labels = array(
        'name'                  => _x('Safari Packages', 'Post Type General Name', 'textdomain'),
        'singular_name'         => _x('Package', 'Post Type Singular Name', 'textdomain'),
        'menu_name'             => __('Safari Packages', 'textdomain'),
        'name_admin_bar'        => __('Package', 'textdomain'),
        'archives'              => __('Package Archives', 'textdomain'),
        'attributes'            => __('Package Attributes', 'textdomain'),
        'parent_item_colon'     => __('Parent Package:', 'textdomain'),
        'all_items'             => __('All Packages', 'textdomain'),
        'add_new_item'          => __('Add New Package', 'textdomain'),
        'add_new'               => __('Add New', 'textdomain'),
        'new_item'              => __('New Package', 'textdomain'),
        'edit_item'             => __('Edit Package', 'textdomain'),
        'update_item'           => __('Update Package', 'textdomain'),
        'view_item'             => __('View Package', 'textdomain'),
        'view_items'            => __('View Packages', 'textdomain'),
        'search_items'          => __('Search Package', 'textdomain'),
        'not_found'             => __('Not found', 'textdomain'),
        'not_found_in_trash'    => __('Not found in Trash', 'textdomain'),
    );

    $args = array(
        'label'                 => __('Package', 'textdomain'),
        'description'           => __('Safari tour packages', 'textdomain'),
        'labels'                => $labels,
        'supports'              => array('title', 'editor', 'thumbnail', 'excerpt'),
        'taxonomies'            => array('package_category'),
        'hierarchical'          => false,
        'public'                => true,
        'show_ui'               => true,
        'show_in_menu'          => true,
        'menu_position'         => 5,
        'menu_icon'             => 'dashicons-palmtree',
        'show_in_admin_bar'     => true,
        'show_in_nav_menus'     => true,
        'can_export'            => true,
        'has_archive'           => true,
        'exclude_from_search'   => false,
        'publicly_queryable'    => true,
        'capability_type'       => 'post',
        'show_in_rest'          => true,
    );

    register_post_type('packages', $args);
}
add_action('init', 'create_packages_post_type', 0);

// Register Custom Taxonomy for Package Categories
function create_package_categories_taxonomy() {
    $labels = array(
        'name'                       => _x('Package Categories', 'Taxonomy General Name', 'textdomain'),
        'singular_name'              => _x('Package Category', 'Taxonomy Singular Name', 'textdomain'),
        'menu_name'                  => __('Categories', 'textdomain'),
        'all_items'                  => __('All Categories', 'textdomain'),
        'parent_item'                => __('Parent Category', 'textdomain'),
        'parent_item_colon'          => __('Parent Category:', 'textdomain'),
        'new_item_name'              => __('New Category Name', 'textdomain'),
        'add_new_item'               => __('Add New Category', 'textdomain'),
        'edit_item'                  => __('Edit Category', 'textdomain'),
        'update_item'                => __('Update Category', 'textdomain'),
        'view_item'                  => __('View Category', 'textdomain'),
        'separate_items_with_commas' => __('Separate categories with commas', 'textdomain'),
        'add_or_remove_items'        => __('Add or remove categories', 'textdomain'),
        'choose_from_most_used'      => __('Choose from the most used', 'textdomain'),
        'popular_items'              => __('Popular Categories', 'textdomain'),
        'search_items'               => __('Search Categories', 'textdomain'),
        'not_found'                  => __('Not Found', 'textdomain'),
        'no_terms'                   => __('No categories', 'textdomain'),
        'items_list'                 => __('Categories list', 'textdomain'),
        'items_list_navigation'      => __('Categories list navigation', 'textdomain'),
    );

    $args = array(
        'labels'                     => $labels,
        'hierarchical'               => true,
        'public'                     => true,
        'show_ui'                    => true,
        'show_admin_column'          => true,
        'show_in_nav_menus'          => true,
        'show_tagcloud'              => true,
        'show_in_rest'               => true,
    );

    register_taxonomy('package_category', array('packages'), $args);
}
add_action('init', 'create_package_categories_taxonomy', 0);

// Add Custom Meta Boxes for Package Details
function add_package_meta_boxes() {
    add_meta_box(
        'package_details',
        'Package Details',
        'package_details_callback',
        'packages',
        'normal',
        'high'
    );
    
    add_meta_box(
        'package_itinerary',
        'Itinerary',
        'package_itinerary_callback',
        'packages',
        'normal',
        'high'
    );
    
    add_meta_box(
        'package_costs',
        'Package Costs',
        'package_costs_callback',
        'packages',
        'normal',
        'high'
    );
}
add_action('add_meta_boxes', 'add_package_meta_boxes');

// Package Details Meta Box Callback
function package_details_callback($post) {
    wp_nonce_field('save_package_details', 'package_details_nonce');
    
    $duration = get_post_meta($post->ID, '_package_duration', true);
    $location = get_post_meta($post->ID, '_package_location', true);
    
    echo '<table class="form-table">';
    echo '<tr>';
    echo '<th><label for="package_duration">Duration (Days)</label></th>';
    echo '<td><input type="number" id="package_duration" name="package_duration" value="' . esc_attr($duration) . '" min="1" style="width: 100px;" /></td>';
    echo '</tr>';
    echo '<tr>';
    echo '<th><label for="package_location">Location</label></th>';
    echo '<td><input type="text" id="package_location" name="package_location" value="' . esc_attr($location) . '" style="width: 100%;" /></td>';
    echo '</tr>';
    echo '</table>';
}

// Package Costs Meta Box Callback
function package_costs_callback($post) {
    wp_nonce_field('save_package_costs', 'package_costs_nonce');
    
    $inclusive_costs = get_post_meta($post->ID, '_package_inclusive_costs', true);
    $exclusive_costs = get_post_meta($post->ID, '_package_exclusive_costs', true);
    
    if (!is_array($inclusive_costs)) {
        $inclusive_costs = array();
    }
    if (!is_array($exclusive_costs)) {
        $exclusive_costs = array();
    }
    
    echo '<div class="costs-container">';
    
    // Inclusive Costs Section
    echo '<div class="costs-section">';
    echo '<h3>Inclusive Costs</h3>';
    echo '<div id="inclusive-costs-container">';
    
    if (!empty($inclusive_costs)) {
        foreach ($inclusive_costs as $index => $cost) {
            echo '<div class="cost-item" data-index="' . $index . '">';
            echo '<input type="text" name="inclusive_costs[]" value="' . esc_attr($cost) . '" placeholder="Enter inclusive cost item" style="width: 80%;" />';
            echo '<button type="button" class="button remove-cost-item">Remove</button>';
            echo '</div>';
        }
    }
    
    echo '</div>';
    echo '<button type="button" id="add-inclusive-cost" class="button">Add Inclusive Cost</button>';
    echo '</div>';
    
    // Exclusive Costs Section
    echo '<div class="costs-section" style="margin-top: 30px;">';
    echo '<h3>Exclusive Costs</h3>';
    echo '<div id="exclusive-costs-container">';
    
    if (!empty($exclusive_costs)) {
        foreach ($exclusive_costs as $index => $cost) {
            echo '<div class="cost-item" data-index="' . $index . '">';
            echo '<input type="text" name="exclusive_costs[]" value="' . esc_attr($cost) . '" placeholder="Enter exclusive cost item" style="width: 80%;" />';
            echo '<button type="button" class="button remove-cost-item">Remove</button>';
            echo '</div>';
        }
    }
    
    echo '</div>';
    echo '<button type="button" id="add-exclusive-cost" class="button">Add Exclusive Cost</button>';
    echo '</div>';
    
    echo '</div>';
    
    // Add JavaScript for dynamic fields
    ?>
    <script>
    jQuery(document).ready(function($) {
        // Add inclusive cost item
        $('#add-inclusive-cost').on('click', function() {
            var costHtml = '<div class="cost-item">' +
                '<input type="text" name="inclusive_costs[]" placeholder="Enter inclusive cost item" style="width: 80%;" />' +
                '<button type="button" class="button remove-cost-item">Remove</button>' +
                '</div>';
            $('#inclusive-costs-container').append(costHtml);
        });
        
        // Add exclusive cost item
        $('#add-exclusive-cost').on('click', function() {
            var costHtml = '<div class="cost-item">' +
                '<input type="text" name="exclusive_costs[]" placeholder="Enter exclusive cost item" style="width: 80%;" />' +
                '<button type="button" class="button remove-cost-item">Remove</button>' +
                '</div>';
            $('#exclusive-costs-container').append(costHtml);
        });
        
        // Remove cost item
        $(document).on('click', '.remove-cost-item', function() {
            $(this).closest('.cost-item').remove();
        });
    });
    </script>
    <?php
}

// Itinerary Meta Box Callback
function package_itinerary_callback($post) {
    wp_nonce_field('save_package_itinerary', 'package_itinerary_nonce');
    
    $itinerary = get_post_meta($post->ID, '_package_itinerary', true);
    if (!is_array($itinerary)) {
        $itinerary = array();
    }
    
    echo '<div id="itinerary-container">';
    
    if (!empty($itinerary)) {
        foreach ($itinerary as $day => $item) {
            echo '<div class="itinerary-day" data-day="' . $day . '">';
            echo '<h4>Day ' . $day . '</h4>';
            echo '<table class="form-table">';
            echo '<tr>';
            echo '<th><label>Title</label></th>';
            echo '<td><input type="text" name="itinerary[' . $day . '][title]" value="' . esc_attr($item['title']) . '" style="width: 100%;" /></td>';
            echo '</tr>';
            echo '<tr>';
            echo '<th><label>Description</label></th>';
            echo '<td><textarea name="itinerary[' . $day . '][description]" rows="4" style="width: 100%;">' . esc_textarea($item['description']) . '</textarea></td>';
            echo '</tr>';
            echo '</table>';
            echo '<button type="button" class="button remove-day">Remove Day</button>';
            echo '</div>';
        }
    }
    
    echo '</div>';
    echo '<button type="button" id="add-itinerary-day" class="button">Add Day</button>';
    
    // Add JavaScript for dynamic fields
    ?>
    <script>
    jQuery(document).ready(function($) {
        var dayCounter = <?php echo !empty($itinerary) ? max(array_keys($itinerary)) : 0; ?>;
        
        $('#add-itinerary-day').on('click', function() {
            dayCounter++;
            var dayHtml = '<div class="itinerary-day" data-day="' + dayCounter + '">' +
                '<h4>Day ' + dayCounter + '</h4>' +
                '<table class="form-table">' +
                '<tr>' +
                '<th><label>Title</label></th>' +
                '<td><input type="text" name="itinerary[' + dayCounter + '][title]" style="width: 100%;" /></td>' +
                '</tr>' +
                '<tr>' +
                '<th><label>Description</label></th>' +
                '<td><textarea name="itinerary[' + dayCounter + '][description]" rows="4" style="width: 100%;"></textarea></td>' +
                '</tr>' +
                '</table>' +
                '<button type="button" class="button remove-day">Remove Day</button>' +
                '</div>';
            
            $('#itinerary-container').append(dayHtml);
        });
        
        $(document).on('click', '.remove-day', function() {
            $(this).closest('.itinerary-day').remove();
        });
    });
    </script>
    <?php
}

// Save Custom Meta Box Data
function save_package_meta($post_id) {
    // Check nonce and permissions
    if (!isset($_POST['package_details_nonce']) || !wp_verify_nonce($_POST['package_details_nonce'], 'save_package_details')) {
        return;
    }
    
    if (!isset($_POST['package_itinerary_nonce']) || !wp_verify_nonce($_POST['package_itinerary_nonce'], 'save_package_itinerary')) {
        return;
    }
    
    if (!isset($_POST['package_costs_nonce']) || !wp_verify_nonce($_POST['package_costs_nonce'], 'save_package_costs')) {
        return;
    }
    
    if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) {
        return;
    }
    
    if (!current_user_can('edit_post', $post_id)) {
        return;
    }
    
    // Save package details
    if (isset($_POST['package_duration'])) {
        update_post_meta($post_id, '_package_duration', sanitize_text_field($_POST['package_duration']));
    }
    
    if (isset($_POST['package_location'])) {
        update_post_meta($post_id, '_package_location', sanitize_text_field($_POST['package_location']));
    }
    
    // Save inclusive costs
    if (isset($_POST['inclusive_costs']) && is_array($_POST['inclusive_costs'])) {
        $inclusive_costs = array();
        foreach ($_POST['inclusive_costs'] as $cost) {
            $cost = sanitize_text_field($cost);
            if (!empty($cost)) {
                $inclusive_costs[] = $cost;
            }
        }
        update_post_meta($post_id, '_package_inclusive_costs', $inclusive_costs);
    } else {
        update_post_meta($post_id, '_package_inclusive_costs', array());
    }
    
    // Save exclusive costs
    if (isset($_POST['exclusive_costs']) && is_array($_POST['exclusive_costs'])) {
        $exclusive_costs = array();
        foreach ($_POST['exclusive_costs'] as $cost) {
            $cost = sanitize_text_field($cost);
            if (!empty($cost)) {
                $exclusive_costs[] = $cost;
            }
        }
        update_post_meta($post_id, '_package_exclusive_costs', $exclusive_costs);
    } else {
        update_post_meta($post_id, '_package_exclusive_costs', array());
    }
    
    // Save itinerary
    if (isset($_POST['itinerary']) && is_array($_POST['itinerary'])) {
        $itinerary = array();
        foreach ($_POST['itinerary'] as $day => $item) {
            if (!empty($item['title']) || !empty($item['description'])) {
                $itinerary[intval($day)] = array(
                    'title' => sanitize_text_field($item['title']),
                    'description' => sanitize_textarea_field($item['description'])
                );
            }
        }
        ksort($itinerary); // Sort by day number
        update_post_meta($post_id, '_package_itinerary', $itinerary);
    }
}
add_action('save_post', 'save_package_meta');

// Add admin styles
function package_admin_styles() {
    global $post_type;
    if ($post_type == 'packages') {
        ?>
        <style>
        .itinerary-day {
            border: 1px solid #ddd;
            margin: 15px 0;
            padding: 15px;
            background: #f9f9f9;
        }
        .itinerary-day h4 {
            margin-top: 0;
            color: #8B4513;
        }
        .remove-day, .remove-cost-item {
            background: #dc3232 !important;
            border-color: #dc3232 !important;
            color: white !important;
            margin-left: 10px;
        }
        #add-itinerary-day, #add-inclusive-cost, #add-exclusive-cost {
            background: #228B22 !important;
            border-color: #228B22 !important;
            color: white !important;
        }
        .costs-container {
            max-width: 100%;
        }
        .costs-section h3 {
            color: #8B4513;
            border-bottom: 2px solid #8B4513;
            padding-bottom: 5px;
        }
        .cost-item {
            margin: 10px 0;
            padding: 10px;
            background: #f9f9f9;
            border: 1px solid #ddd;
            border-radius: 4px;
        }
        .cost-item input {
            margin-right: 10px;
        }
        </style>
        <?php
    }
}
add_action('admin_head', 'package_admin_styles');

// Flush rewrite rules on theme activation
function packages_flush_rewrite_rules() {
    create_packages_post_type();
    create_package_categories_taxonomy();
    flush_rewrite_rules();
}
register_activation_hook(__FILE__, 'packages_flush_rewrite_rules');

// Shortcode to display packages anywhere
function safari_packages_shortcode($atts) {
    $atts = shortcode_atts(array(
        'limit' => 8,
        'category' => '',
        'columns' => 4,
        'show_excerpt' => 'yes',
        'show_meta' => 'yes'

    ), $atts);
    
    $args = array(
        'post_type' => 'packages',
        'posts_per_page' => intval($atts['limit']),
        'post_status' => 'publish',
        'orderby' => 'rand'
    );
    
    if (!empty($atts['category'])) {
        $args['tax_query'] = array(
            array(
                'taxonomy' => 'package_category',
                'field' => 'slug',
                'terms' => $atts['category']
            )
        );
    }
    
    $packages = new WP_Query($args);
    
    if (!$packages->have_posts()) {
        return '<p>No packages found.</p>';
    }
    
    $columns_class = 'columns-' . intval($atts['columns']);
    
    ob_start();
    ?>
    
   <div class="safari-packages-shortcode <?php echo esc_attr($columns_class); ?>">
    <div class="packages-shortcode-grid">
        <?php while ($packages->have_posts()) : $packages->the_post(); ?>
            <div class="package-shortcode-card">
                <?php if (has_post_thumbnail()) : ?>
                    <div class="package-shortcode-image">
                        <a href="<?php the_permalink(); ?>">
                            <?php the_post_thumbnail('medium'); ?>
                        </a>
                    </div>
                <?php endif; ?>
                
                <div class="package-shortcode-content">
                    <h3 class="package-shortcode-title">
                        <a href="<?php the_permalink(); ?>"><?php the_title(); ?></a>
                    </h3>
                    
                    <?php if ($atts['show_meta'] === 'yes') : ?>
                        <div class="package-shortcode-meta">
                            <?php
                            $duration = get_post_meta(get_the_ID(), '_package_duration', true);
                            $location = get_post_meta(get_the_ID(), '_package_location', true);
                            ?>
                            
                            <?php if ($duration) : ?>
                                <span class="shortcode-duration">
                                   <i class="bi bi-calendar"></i>️ <?php echo esc_html($duration); ?> Days
                                </span>
                            <?php endif; ?>
                            
                            <?php if ($location) : ?>
                                <span class="shortcode-location">
                                    <i class="bi bi-pin-map"></i> <?php echo esc_html($location); ?>
                                </span>
                            <?php endif; ?>
                        </div>
                    <?php endif; ?>
                    
                    <?php if ($atts['show_excerpt'] === 'yes') : ?>
                        <div class="package-shortcode-excerpt">
                            <?php echo wp_trim_words(get_the_excerpt(), 30, '...'); ?>
                        </div>
                    <?php endif; ?>
                    
                    <a href="<?php the_permalink(); ?>" class="package-shortcode-button">
                        Learn More
                    </a>
                </div>
            </div>
        <?php endwhile; ?>
    </div>
</div>


    
    <?php
    wp_reset_postdata();
    return ob_get_clean();
}
add_shortcode('safari_packages', 'safari_packages_shortcode');

// Widget for displaying featured packages
class Safari_Packages_Widget extends WP_Widget {
    
    public function __construct() {
        parent::__construct(
            'safari_packages_widget',
            'Safari Packages',
            array('description' => 'Display featured safari packages')
        );
    }
    
    public function widget($args, $instance) {
        echo $args['before_widget'];
        
        if (!empty($instance['title'])) {
            echo $args['before_title'] . apply_filters('widget_title', $instance['title']) . $args['after_title'];
        }
        
        $limit = !empty($instance['limit']) ? $instance['limit'] : 3;
        $category = !empty($instance['category']) ? $instance['category'] : '';
        
        echo do_shortcode("[safari_packages limit='{$limit}' category='{$category}' columns='1' show_excerpt='no']");
        
        echo $args['after_widget'];
    }
    
    public function form($instance) {
        $title = !empty($instance['title']) ? $instance['title'] : 'Featured Packages';
        $limit = !empty($instance['limit']) ? $instance['limit'] : 3;
        $category = !empty($instance['category']) ? $instance['category'] : '';
        
        $categories = get_terms(array(
            'taxonomy' => 'package_category',
            'hide_empty' => false
        ));
        ?>
        <p>
            <label for="<?php echo esc_attr($this->get_field_id('title')); ?>">Title:</label>
            <input class="widefat" id="<?php echo esc_attr($this->get_field_id('title')); ?>" 
                   name="<?php echo esc_attr($this->get_field_name('title')); ?>" type="text" 
                   value="<?php echo esc_attr($title); ?>">
        </p>
        <p>
            <label for="<?php echo esc_attr($this->get_field_id('limit')); ?>">Number of packages:</label>
            <input class="widefat" id="<?php echo esc_attr($this->get_field_id('limit')); ?>" 
                   name="<?php echo esc_attr($this->get_field_name('limit')); ?>" type="number" 
                   value="<?php echo esc_attr($limit); ?>" min="1" max="10">
        </p>
        <p>
            <label for="<?php echo esc_attr($this->get_field_id('category')); ?>">Category:</label>
            <select class="widefat" id="<?php echo esc_attr($this->get_field_id('category')); ?>" 
                    name="<?php echo esc_attr($this->get_field_name('category')); ?>">
                <option value="">All Categories</option>
                <?php foreach ($categories as $cat) : ?>
                    <option value="<?php echo esc_attr($cat->slug); ?>" 
                            <?php selected($category, $cat->slug); ?>>
                        <?php echo esc_html($cat->name); ?>
                    </option>
                <?php endforeach; ?>
            </select>
        </p>
        <?php
    }
    
    public function update($new_instance, $old_instance) {
        $instance = array();
        $instance['title'] = (!empty($new_instance['title'])) ? sanitize_text_field($new_instance['title']) : '';
        $instance['limit'] = (!empty($new_instance['limit'])) ? absint($new_instance['limit']) : 3;
        $instance['category'] = (!empty($new_instance['category'])) ? sanitize_text_field($new_instance['category']) : '';
        
        return $instance;
    }
}

// Register the widget
function register_safari_packages_widget() {
    register_widget('Safari_Packages_Widget');
}
add_action('widgets_init', 'register_safari_packages_widget');

// Add custom columns to admin packages list
function safari_packages_admin_columns($columns) {
    $columns['duration'] = 'Duration';
    $columns['location'] = 'Location';
    $columns['package_category'] = 'Category';
    return $columns;
}
add_filter('manage_packages_posts_columns', 'safari_packages_admin_columns');

function safari_packages_admin_column_content($column, $post_id) {
    switch ($column) {
        case 'duration':
            $duration = get_post_meta($post_id, '_package_duration', true);
            echo $duration ? esc_html($duration) . ' days' : '—';
            break;
            
        case 'location':
            $location = get_post_meta($post_id, '_package_location', true);
            echo $location ? esc_html($location) : '—';
            break;
            
        case 'package_category':
            $terms = get_the_terms($post_id, 'package_category');
            if ($terms && !is_wp_error($terms)) {
                $term_names = array();
                foreach ($terms as $term) {
                    $term_names[] = $term->name;
                }
                echo implode(', ', $term_names);
            } else {
                echo '—';
            }
            break;
    }
}
add_action('manage_packages_posts_custom_column', 'safari_packages_admin_column_content', 10, 2);

// Make custom columns sortable
function safari_packages_sortable_columns($columns) {
    $columns['duration'] = 'duration';
    $columns['location'] = 'location';
    return $columns;
}
add_filter('manage_edit-packages_sortable_columns', 'safari_packages_sortable_columns');

// Handle sorting
function safari_packages_column_orderby($query) {
    if (!is_admin()) return;
    
    $orderby = $query->get('orderby');
    
    if ('duration' === $orderby) {
        $query->set('meta_key', '_package_duration');
        $query->set('orderby', 'meta_value_num');
    }
    
    if ('location' === $orderby) {
        $query->set('meta_key', '_package_location');
        $query->set('orderby', 'meta_value');
    }
}
add_action('pre_get_posts', 'safari_packages_column_orderby');
?>