<?php
/**
 * Kipya functions and definitions.
 *
 * @link https://afiego.org
 *
 * @package Kipya
 */
set_time_limit(300); // Set to a higher value if needed
if ( ! function_exists( 'kipya_setup' ) ) :
	/**
	 * Sets up theme defaults and registers support for various WordPress features.
	 */
	function kipya_setup() {
		// Make the theme available for translation.
		load_theme_textdomain( 'kipya', get_template_directory() . '/languages' );

		// Add default posts and comments RSS feed links to head.
		add_theme_support( 'automatic-feed-links' );

        //Upload Logo in website.
        add_theme_support('custom-logo');

		// Let WordPress manage the document title.
		add_theme_support( 'title-tag' );

		// Enable support for Post Thumbnails on posts and pages.
		add_theme_support( 'post-thumbnails' );


		// Register navigation menus.
		register_nav_menus( array(
			'primary'   => esc_html__( 'Primary Menu', 'kipya' ),
			'top-menu'  => esc_html__( 'Top Menu', 'kipya' ),
            'sidebar'   => esc_html__( 'Sidebar Menu', 'kipya' ),
            'footer'    => esc_html__( 'Footer Menu', 'kipya' ),
		) );

		// Switch default core markup for search form, comment form, and comments to output valid HTML5.
		add_theme_support( 'kipya', array(
			'search-form',
			'comment-form',
			'comment-list',
			'gallery',
			'caption',
		) );

		// Set up the WordPress core custom background feature.
		add_theme_support( 'custom-background', apply_filters( 'kipya_custom_background_args', array(
			'default-color' => 'ffffff',
			'default-image' => '',
		) ) );

		// Add theme support for selective refresh for widgets.
		add_theme_support( 'customize-selective-refresh-widgets' );

        /**
		 * Enable support for the following post formats:
		 * aside, gallery, quote, image, and video
		 */
        add_theme_support( 'post-formats', array( 'aside', 'gallery', 'quote', 'image', 'video' ) );
	}
endif;
add_action( 'after_setup_theme', 'kipya_setup' );

// Enqueue styles.
function kipya_styles() {
    wp_register_style('kipya-style', get_template_directory_uri() . '/style.css', array(), '1.0.0', 'all');
    wp_register_style('custom', get_template_directory_uri() . '/assets/css/custom.css', array(), '1.0.0', 'all');
    wp_register_style('bootstrap.min', get_template_directory_uri() . '/assets/vendor/bootstrap/css/bootstrap.min.css', array(), '5.3.2', 'all');
    wp_register_style('bootstrap-icons', get_template_directory_uri() . '/assets/vendor/bootstrap-icons/font/bootstrap-icons.min.css', array(), '1.11.3', 'all');
    wp_register_style('aos', get_template_directory_uri() . '/assets/vendor/aos/aos.css', array(), '2.3.4', 'all');
    wp_register_style('swiper', get_template_directory_uri() . '/assets/vendor/swiper/swiper.min.css', array(), '5.4.5', 'all');
    wp_register_style('toastr.min', get_template_directory_uri() . '/assets/vendor/toastr/toastr.min.css', array(), '2.1.3', 'all');
    wp_register_style('datatables.min', get_template_directory_uri() . '/assets/vendor/DataTables/datatables.min.css', array(), '1.13.3', 'all');



    wp_enqueue_style( 'kipya-style');
    wp_enqueue_style( 'custom');
    wp_enqueue_style( 'bootstrap.min');
    wp_enqueue_style( 'bootstrap-icons');
    wp_enqueue_style( 'aos');
    wp_enqueue_style( 'swiper');
    wp_enqueue_style( 'toastr.min');
    wp_enqueue_style( 'datatables.min');
}
add_action( 'wp_enqueue_scripts', 'kipya_styles' );

// Enqueue scripts.
function kipya_scripts() {

    wp_enqueue_script( 'bootstrap-script', get_template_directory_uri() . '/assets/vendor/bootstrap/js/bootstrap.bundle.min.js', array(), '4.5.2', 'all');
    wp_enqueue_script( 'aos-script', get_template_directory_uri() . '/assets/vendor/aos/aos.js', array(), '2.3.4', 'all');
    wp_enqueue_script( 'swiper-script', get_template_directory_uri() . '/assets/vendor/swiper/swiper.min.js', array(), '5.4.5', 'all');
    wp_enqueue_script( 'toastr-script', get_template_directory_uri() . '/assets/vendor/toastr/toastr.min.js', array(), '2.1.3', 'all');
    wp_enqueue_script( 'jquery-script', get_template_directory_uri() . '/assets/vendor/jquery/jquery-3.7.1.min.js', array( ), '3.7.1', 'all');
    wp_enqueue_script( 'kipya-script', get_template_directory_uri() . '/assets/js/main.js', array(), '1.0.0', 'all');
    wp_enqueue_script( 'search-script', get_template_directory_uri() . '/assets/js/search.js', array(), '1.0.0', 'all');
    wp_enqueue_script( 'datatables.min', get_template_directory_uri() . '/assets/vendor/DataTables/datatables.min.js', array(), '1.13.3', 'all');

function enqueue_glightbox() {
    wp_enqueue_script('glightbox', 'https://cdn.jsdelivr.net/npm/glightbox/dist/js/glightbox.min.js', array(), null, true);
    wp_enqueue_style('glightbox-css', 'https://cdn.jsdelivr.net/npm/glightbox/dist/css/glightbox.min.css');
}
add_action('wp_enqueue_scripts', 'enqueue_glightbox');


function force_gallery_links_to_media($block_content, $block) {
    if ($block['blockName'] === 'core/gallery' && !empty($block['innerBlocks'])) {
        foreach ($block['innerBlocks'] as &$innerBlock) {
            if ($innerBlock['blockName'] === 'core/image' && isset($innerBlock['attrs']['id'])) {
                $image_id = $innerBlock['attrs']['id'];
                $image_url = wp_get_attachment_url($image_id);
                if ($image_url) {
                    $innerBlock['attrs']['linkDestination'] = 'media';
                    $innerBlock['attrs']['href'] = $image_url;
                }
            }
        }
    }
    return $block_content;
}
add_filter('render_block', 'force_gallery_links_to_media', 10, 2);



    // Pass the ajaxurl to search.js
    wp_localize_script('search-script', 'kipya_ajax_object', array(
        'ajaxurl' => admin_url('admin-ajax.php'),
    ));
}
//add_action( 'wp_enqueue_scripts', 'kipya_scripts' );
add_action('wp_footer','kipya_scripts');

// ligtbox-gallery
function enqueue_custom_scripts() {
    // Enqueue lightbox library
    wp_enqueue_style('lightbox-css', 'https://cdnjs.cloudflare.com/ajax/libs/lightbox2/2.11.3/css/lightbox.min.css');
    wp_enqueue_script('lightbox-js', 'https://cdnjs.cloudflare.com/ajax/libs/lightbox2/2.11.3/js/lightbox.min.js', array('jquery'), null, true);

    // Enqueue custom JavaScript
    wp_enqueue_script('custom-gallery-lightbox', get_template_directory_uri() . '/assets/js/gallery-lightbox.js', array('jquery'), null, true);

    // Enqueue custom AJAX script for projects page
    if (is_page('projects-page')) {
        wp_enqueue_script('custom-ajax-script', get_template_directory_uri() . '/assets/js/custom-ajax-script.js', array('jquery'), null, true);
        wp_localize_script('custom-ajax-script', 'ajax_object', array('ajax_url' => admin_url('admin-ajax.php')));
    }
}
add_action('wp_enqueue_scripts', 'enqueue_custom_scripts');

// If Dynamic Sidebar Exists
if (function_exists('register_sidebar'))
{
    // Define Sidebar Widget Area 1
    register_sidebar(array(
        'name' => __('Widget Area 1', 'kipya'),
        'description' => __('Description for this widget-area...', 'kipya'),
        'id' => 'widget-area-1',
        'before_widget' => '<div id="%1$s" class="%2$s">',
        'after_widget' => '</div>',
        'before_title' => '<h3>',
        'after_title' => '</h3>'
    ));

    // Define Sidebar Widget Area 2
    register_sidebar(array(
        'name' => __('Widget Area 2', 'kipya'),
        'description' => __('Description for this widget-area...', 'kipya'),
        'id' => 'widget-area-2',
        'before_widget' => '<div id="%1$s" class="%2$s">',
        'after_widget' => '</div>',
        'before_title' => '<h3>',
        'after_title' => '</h3>'
    ));
    
    register_sidebar( array(
        'name'          => esc_html__( 'Top Left', 'kipya' ),
        'id'            => 'topl',
        'description'   => esc_html__( 'Add widgets here.', 'kipya' ),
        'before_widget' => '<section id="%1$s" class="widget %2$s">',
        'after_widget'  => '</section>',
        'before_title'  => '<h3 class="widget-title">',
        'after_title'   => '</h3>',
    ) );
	register_sidebar( array(
        'name'          => esc_html__( 'Top Right', 'kipya' ),
        'id'            => 'topr',
        'description'   => esc_html__( 'Add widgets here.', 'kipya' ),
        'before_widget' => '<section id="%1$s" class="widget %2$s">',
        'after_widget'  => '</section>',
        'before_title'  => '<h3 class="widget-title">',
        'after_title'   => '</h3>',
    ) );
	register_sidebar( array(
        'name'          => esc_html__( 'Search Area', 'kipya' ),
        'id'            => 'searchi',
        'description'   => esc_html__( 'Add widgets here.', 'kipya' ),
        'before_widget' => '<section id="%1$s" class="widget %2$s">',
        'after_widget'  => '</section>',
        'before_title'  => '<h3 class="widget-title">',
        'after_title'   => '</h3>',
    ) );
	register_sidebar( array(
        'name'          => esc_html__( 'Quick Number', 'kipya' ),
        'id'            => 'inno',
        'description'   => esc_html__( 'Add widgets here.', 'kipya' ),
        'before_widget' => '<section id="%1$s" class="widget %2$s">',
        'after_widget'  => '</section>',
        'before_title'  => '<h3 class="widget-title">',
        'after_title'   => '</h3>',
    ) );
    register_sidebar( array(
        'name'          => esc_html__( 'Menu Right', 'kipya' ),
        'id'            => 'nav-right',
        'description'   => esc_html__( 'Add widgets here.', 'kipya' ),
        'before_widget' => '<section id="%1$s" class="widget %2$s">',
        'after_widget'  => '</section>',
        'before_title'  => '<h3 class="widget-title">',
        'after_title'   => '</h3>',
    ) );
    register_sidebar(array(
        'name' => __('Services Sidebar', 'kipya'),
        'description' => __('Description for this widget-area...', 'kipya'),
        'id' => 'servsidebar',
        'before_widget' => '<div id="%1$s" class="%2$s">',
        'after_widget' => '</div>',
        'before_title' => '<h3>',
        'after_title' => '</h3>'
    ));
    register_sidebar( array(
        'name'          => esc_html__( 'Advert Top', 'kipya' ),
        'id'            => 'advtop',
        'description'   => esc_html__( 'Add widgets here.', 'kipya' ),
        'before_widget' => '<section id="%1$s" class="widget %2$s">',
        'after_widget'  => '</section>',
        'before_title'  => '<h3 class="widget-title">',
        'after_title'   => '</h3>',
    ) );
     register_sidebar( array(
        'name'          => esc_html__( 'Newsletter', 'kipya' ),
        'id'            => 'footernewz',
        'description'   => esc_html__( 'Add widgets here.', 'kipya' ),
        'before_widget' => '<section id="%1$s" class="widget %2$s">',
        'after_widget'  => '</section>',
        'before_title'  => '<h4 class="widget-title">',
        'after_title'   => '</h4>',
    ) );
    register_sidebar( array(
        'name'          => esc_html__( 'Footer Starter', 'kipya' ),
        'id'            => 'footeri',
        'description'   => esc_html__( 'Add widgets here.', 'kipya' ),
        'before_widget' => '<section id="%1$s" class="widget %2$s">',
        'after_widget'  => '</section>',
        'before_title'  => '<h4 class="widget-title">',
        'after_title'   => '</h4>',
    ) );
	register_sidebar( array(
        'name'          => esc_html__( 'Footer A', 'kipya' ),
        'id'            => 'footera',
        'description'   => esc_html__( 'Add widgets here.', 'kipya' ),
        'before_widget' => '<section id="%1$s" class="widget %2$s">',
        'after_widget'  => '</section>',
        'before_title'  => '<h4 class="widget-title">',
        'after_title'   => '</h4>',
    ) );
	register_sidebar( array(
        'name'          => esc_html__( 'Footer B', 'kipya' ),
        'id'            => 'footerb',
        'description'   => esc_html__( 'Add widgets here.', 'kipya' ),
        'before_widget' => '<section id="%1$s" class="widget %2$s">',
        'after_widget'  => '</section>',
        'before_title'  => '<h4 class="widget-title">',
        'after_title'   => '</h4>',
    ) );
	register_sidebar( array(
        'name'          => esc_html__( 'Footer C', 'kipya' ),
        'id'            => 'footerc',
        'description'   => esc_html__( 'Add widgets here.', 'kipya' ),
        'before_widget' => '<section id="%1$s" class="widget %2$s">',
        'after_widget'  => '</section>',
        'before_title'  => '<h4 class="widget-title">',
        'after_title'   => '</h4>',
    ) );
    register_sidebar( array(
        'name'          => esc_html__( 'Footer D', 'kipya' ),
        'id'            => 'footerd',
        'description'   => esc_html__( 'Add widgets here.', 'kipya' ),
        'before_widget' => '<section id="%1$s" class="widget %2$s">',
        'after_widget'  => '</section>',
        'before_title'  => '<h4 class="widget-title">',
        'after_title'   => '</h4>',
    ) );
     register_sidebar( array(
        'name'          => esc_html__( 'Copyright Links', 'kipya' ),
        'id'            => 'footer-links',
        'description'   => esc_html__( 'Add widgets here.', 'kipya' ),
        'before_widget' => '<section id="%1$s" class="widget %2$s">',
        'after_widget'  => '</section>',
        'before_title'  => '<h4 class="widget-title">',
        'after_title'   => '</h4>',
    ) );
}

//Activate Excerpt in PAGES
function enable_page_excerpts() {
    add_post_type_support('page', 'excerpt');
}
add_action('init', 'enable_page_excerpts');




//Custom BOOTSTRAP Menu 
include get_template_directory() . '/inc/bootstrap-5-wordpress-navbar-walker.php';
include get_template_directory() . '/inc/custom-nav-walker.php';

//Custom Post Type :: SEO / SEARCH / PAGE CATS
include get_template_directory() . '/inc/seo-post-types.php';
include get_template_directory() . '/inc/accordion.php';
include get_template_directory() . '/inc/ajax-search.php';
include get_template_directory() . '/inc/add_page_category.php';

//Custom Post Type :: SLIDING PHOTOS 
//include get_template_directory() . '/inc/slides-post-types.php';
include get_template_directory() . '/inc/text-slider-post-type.php';

//Custom Post Type :: UPCOMING EVENTS
include get_template_directory() . '/inc/upcoming-events-post-types.php';
include get_template_directory() . '/inc/more-upcoming-events.php';
include get_template_directory() . '/inc/past-events.php';

//Custom Post Type :: DOWNLOADS
include get_template_directory() . '/inc/downloads-post-types.php';

//Custom Post Type :: TEAMS
include get_template_directory() . '/inc/team-post-types.php';

//Custom Post Type :: PARTNERS
include get_template_directory() . '/inc/partners-post-types.php';

// Shortcode :: AOS
include get_template_directory() . '/inc/aos-animation.php'; 
include get_template_directory() . '/inc/breadcrumbs.php'; 

//ALL News Shortcode
include get_template_directory() . '/inc/news_front.php'; 


//ALL Beaute Sauvage Safaris Shortcodes
include get_template_directory() . '/inc/beaute-home-shortcode.php';
include get_template_directory() . '/inc/beaute-sauvage-affiliations.php';
include get_template_directory() . '/inc/beaute-sauvage-overview.php';
include get_template_directory() . '/inc/airticketing.php';
include get_template_directory() . '/inc/visa_support_posttype.php';
include get_template_directory() . '/inc/visa-content.php';
include get_template_directory() . '/inc/destinations-shortcode.php';
include get_template_directory() . '/inc/travel-packages-shortcode.php';
include get_template_directory() . '/inc/romantic_packages.php';



//Duplicate Pages
include get_template_directory() . '/inc/duplicate-page.php'; 

//ALL Associates Shortcode
include get_template_directory() . '/inc/all_partners-page.php'; 

//ALL Publications Shortcode
include get_template_directory() . '/inc/home-pubs-shortcode.php'; 

//ALL Contact Form
include get_template_directory() . '/inc/contact-form.php'; 
include get_template_directory() . '/inc/all-gallery-shortcode.php';

//ALL Single Gallery Shortcode
function load_custom_single_template($template) {
    if (is_single() && in_category('photo-gallery')) {
        $new_template = locate_template(array('single-gallery.php'));
        if ($new_template) {
            return $new_template;
        }
    }
    if (is_singular('events')) {
        $eve_template = locate_template(array('single-event.php'));
        if ($eve_template) {
            return $eve_template;
        }
    }
    return $template;
}
add_filter('single_template', 'load_custom_single_template');

// //FORM PROCESSOR
// include get_template_directory() . '/inc/process-form.php'; 

//BACK BUTTON (previous page)
add_action( 'back_button', 'kipya_back_button' );
function kipya_back_button() {
    if ( wp_get_referer() ) {
        $back_text = __( '&laquo; BACK' );
        $button    = "\n<button id='my-back-button' class='btn button my-back-button' onclick='javascript:history.back()'>$back_text</button>";
        echo ( $button );
    }
}

// Pagination for paged posts, Page 1, Page 2, Page 3, with Next and Previous Links, No plugin
function html5wp_pagination()
{
    global $wp_query;
    $big = 999999999;
    echo paginate_links(array(
        'base' => str_replace($big, '%#%', get_pagenum_link($big)),
        'format' => '?paged=%#%',
        'current' => max(1, get_query_var('paged')),
        'total' => $wp_query->max_num_pages
    ));
}
function enqueue_datatables_assets() {
    wp_enqueue_style('datatables-css', 'https://cdn.datatables.net/1.11.3/css/jquery.dataTables.min.css');
    wp_enqueue_script('datatables-js', 'https://cdn.datatables.net/1.11.3/js/jquery.dataTables.min.js', array('jquery'), null, true);
}
add_action('wp_enqueue_scripts', 'enqueue_datatables_assets');

// Custom Excerpts
function html5wp_index($length) // Create 20 Word Callback for Index page Excerpts, call using html5wp_excerpt('html5wp_index');
{
    return 50;
}

// Create 40 Word Callback for Custom Post Excerpts, call using html5wp_excerpt('html5wp_custom_post');
function html5wp_custom_post($length)
{
    return 50;
}

//Allow upload of SVG Images
function enable_svg_support($mimes) {
    $mimes['svg'] = 'image/svg+xml';
    return $mimes;
}
add_filter('upload_mimes', 'enable_svg_support');

// Create the Custom Excerpts callback
function html5wp_excerpt($length_callback = '', $more_callback = '')
{
    global $post;
    if (function_exists($length_callback)) {
        add_filter('excerpt_length', $length_callback);
    }
    if (function_exists($more_callback)) {
        add_filter('excerpt_more', $more_callback);
    }
    $output = get_the_excerpt();
    $output = apply_filters('wptexturize', $output);
    $output = apply_filters('convert_chars', $output);
    $output = '<p>' . $output . '</p>';
    echo $output;
}

// Custom View Article link to Post
function html5_blank_view_article($more)
{
    global $post;
    return '... <a class="view-article" href="' . get_permalink($post->ID) . '">' . __('Read More', 'kipya') . '</a>';
}

// Remove Admin bar
function remove_admin_bar() {
    return false;
}
add_filter('show_admin_bar', 'remove_admin_bar');

// Remove 'text/css' from our enqueued stylesheet
function html5_style_remove($tag)
{
    return preg_replace('~\s+type=["\'][^"\']++["\']~', '', $tag);
}

function enqueue_destination_styles() {
    wp_enqueue_style(
        'destination-custom-css',
        get_stylesheet_directory_uri() . '/assets/css/custom.css',
        array(),
        filemtime(get_stylesheet_directory() . '/assets/css/custom.css')
    );
}
add_action('wp_enqueue_scripts', 'enqueue_destination_styles');

add_filter('single_template', function($template) {
    global $post;
    if ($post->post_type === 'destination') {
        return locate_template('single-destination.php');
    }
    return $template;
});


// Remove thumbnail width and height dimensions that prevent fluid images in the_thumbnail
function remove_thumbnail_dimensions( $html )
{
    $html = preg_replace('/(width|height)=\"\d*\"\s/', "", $html);
    return $html;
}
function load_bootstrap_icons_footer() {
    ?>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons/font/bootstrap-icons.css" type="text/css" />
    <?php
}
add_action('wp_footer', 'load_bootstrap_icons_footer');



/**
 * Redirect both romantic_package and travel_package post types to use single-package.php template
 */
function load_custom_package_template($template) {
    global $post;
    
    // Check if we're viewing a single post of either package type
    if ($post && in_array($post->post_type, ['romantic_package', 'travel_package'])) {
        // Look for single-package.php in the active theme
        $custom_template = locate_template('single-package.php');
        
        if ($custom_template) {
            return $custom_template;
        }
    }
    
    return $template;
}
add_filter('template_include', 'load_custom_package_template');


function flush_package_rewrite_rules() {
    // Only flush if we haven't done it recently
    if (get_option('package_templates_flushed') !== '1') {
        flush_rewrite_rules();
        update_option('package_templates_flushed', '1');
    }
}
add_action('init', 'flush_package_rewrite_rules', 999);






// ==============================================
// 1. DATABASE TABLE CREATION
// ==============================================

function create_package_bookings_table() {
    global $wpdb;
    $table_name = $wpdb->prefix . 'package_bookings';
    $charset_collate = $wpdb->get_charset_collate();

    $sql = "CREATE TABLE $table_name (
        id mediumint(9) NOT NULL AUTO_INCREMENT,
        package_id bigint(20) NOT NULL,
        package_name varchar(255) NOT NULL,
        customer_name varchar(255) NOT NULL,
        customer_email varchar(255) NOT NULL,
        customer_phone varchar(50) NOT NULL,
        customer_dob date NOT NULL,
        num_adults int(11) NOT NULL,
        num_children int(11) NOT NULL,
        departure_date date NOT NULL,
        budget_preference varchar(100) NOT NULL,
        special_requests text,
        status varchar(20) DEFAULT 'pending',
        booking_date datetime DEFAULT CURRENT_TIMESTAMP,
        PRIMARY KEY  (id)
    ) $charset_collate;";

    require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
    dbDelta($sql);
    
    error_log('Package bookings table creation attempted for: ' . $table_name);
}

// Function to update existing table structure
function update_package_bookings_table() {
    global $wpdb;
    $table_name = $wpdb->prefix . 'package_bookings';
    
    // Check if booking_date column exists
    $column_exists = $wpdb->get_results("SHOW COLUMNS FROM $table_name LIKE 'booking_date'");
    
    if (empty($column_exists)) {
        error_log('Adding missing booking_date column to ' . $table_name);
        $wpdb->query("ALTER TABLE $table_name ADD COLUMN booking_date datetime DEFAULT CURRENT_TIMESTAMP");
        error_log('booking_date column added successfully');
    }
}

// Initialize table on theme/plugin activation
function init_package_bookings_table() {
    global $wpdb;
    $table_name = $wpdb->prefix . 'package_bookings';
    
    // Check if table exists
    $table_exists = $wpdb->get_var("SHOW TABLES LIKE '$table_name'");
    
    if($table_exists != $table_name) {
        error_log('Table does not exist. Creating table: ' . $table_name);
        create_package_bookings_table();
    } else {
        error_log('Table already exists: ' . $table_name);
        // Update table structure if needed
        update_package_bookings_table();
    }
}
add_action('init', 'init_package_bookings_table');

// ==============================================
// 2. DEBUG FUNCTION (Remove after debugging)
// ==============================================

function check_booking_table_status() {
    global $wpdb;
    $table_name = $wpdb->prefix . 'package_bookings';
    
    // Check if table exists
    $table_exists = $wpdb->get_var("SHOW TABLES LIKE '$table_name'");
    
    error_log('=== BOOKING TABLE STATUS CHECK ===');
    error_log('Table name: ' . $table_name);
    error_log('Table exists: ' . ($table_exists ? 'YES' : 'NO'));
    
    if ($table_exists) {
        // Check table structure
        $columns = $wpdb->get_results("DESCRIBE $table_name");
        error_log('Table columns: ' . print_r($columns, true));
    }
}
add_action('admin_init', 'check_booking_table_status');

// ==============================================
// 3. AJAX FORM SUBMISSION HANDLER
// ==============================================

function handle_package_booking_submission() {
    error_log('=== BOOKING SUBMISSION STARTED ===');
    error_log('Timestamp: ' . current_time('mysql'));
    
    // Verify nonce
    if (!isset($_POST['booking_nonce']) || !wp_verify_nonce($_POST['booking_nonce'], 'package_booking_nonce')) {
        error_log('ERROR: Nonce verification failed');
        error_log('Received nonce: ' . (isset($_POST['booking_nonce']) ? $_POST['booking_nonce'] : 'NOT SET'));
        wp_send_json_error('Invalid security token');
        return;
    }
    error_log('✓ Nonce verified successfully');

    // Log all received POST data (sanitized for logging)
    error_log('POST data received: ' . print_r(array_map('sanitize_text_field', $_POST), true));

    // Validate required fields
    $required_fields = array('customer_name', 'customer_email', 'customer_phone', 'customer_dob', 
                            'num_adults', 'departure_date', 'budget_preference', 'package_id', 'package_name');
    
    foreach ($required_fields as $field) {
        if (!isset($_POST[$field]) || empty($_POST[$field])) {
            error_log('ERROR: Missing required field: ' . $field);
            wp_send_json_error('Missing required field: ' . $field);
            return;
        }
    }
    error_log('✓ All required fields present');

    // Sanitize form data
    $customer_name = sanitize_text_field($_POST['customer_name']);
    $customer_email = sanitize_email($_POST['customer_email']);
    $customer_phone = sanitize_text_field($_POST['customer_phone']);
    $customer_dob = sanitize_text_field($_POST['customer_dob']);
    $num_adults = intval($_POST['num_adults']);
    $num_children = isset($_POST['num_children']) ? intval($_POST['num_children']) : 0;
    $departure_date = sanitize_text_field($_POST['departure_date']);
    $budget_preference = sanitize_text_field($_POST['budget_preference']);
    $special_requests = isset($_POST['special_requests']) ? sanitize_textarea_field($_POST['special_requests']) : '';
    $package_id = intval($_POST['package_id']);
    $package_name = sanitize_text_field($_POST['package_name']);

    error_log('✓ Data sanitized successfully');

    // Validate email
    if (!is_email($customer_email)) {
        error_log('ERROR: Invalid email format: ' . $customer_email);
        wp_send_json_error('Invalid email address');
        return;
    }

    // Generate booking reference
    $booking_reference = 'BK' . date('Ymd') . rand(1000, 9999);
    error_log('Generated booking reference: ' . $booking_reference);

    // Database operations
    global $wpdb;
    $table_name = $wpdb->prefix . 'package_bookings';
    
    error_log('Using table: ' . $table_name);
    
    // Verify table exists before insert
    $table_exists = $wpdb->get_var("SHOW TABLES LIKE '$table_name'");
    if (!$table_exists) {
        error_log('ERROR: Table does not exist! Attempting to create it...');
        create_package_bookings_table();
        
        // Check again
        $table_exists = $wpdb->get_var("SHOW TABLES LIKE '$table_name'");
        if (!$table_exists) {
            error_log('ERROR: Failed to create table');
            wp_send_json_error('Database table not found. Please contact administrator.');
            return;
        }
    }
    error_log('✓ Table exists');
    
    // Prepare data for insertion
    $data = array(
        'package_id' => $package_id,
        'package_name' => $package_name,
        'customer_name' => $customer_name,
        'customer_email' => $customer_email,
        'customer_phone' => $customer_phone,
        'customer_dob' => $customer_dob,
        'num_adults' => $num_adults,
        'num_children' => $num_children,
        'departure_date' => $departure_date,
        'budget_preference' => $budget_preference,
        'special_requests' => $special_requests,
        'status' => 'pending',
        'booking_date' => current_time('mysql')
    );
    
    error_log('Data prepared for insertion: ' . print_r($data, true));
    
    // Insert into database
    $insert_result = $wpdb->insert(
        $table_name,
        $data,
        array('%d', '%s', '%s', '%s', '%s', '%s', '%d', '%d', '%s', '%s', '%s', '%s', '%s')
    );

    // Check for database errors
    if ($insert_result === false) {
        error_log('ERROR: Database insert failed');
        error_log('wpdb->last_error: ' . $wpdb->last_error);
        error_log('wpdb->last_query: ' . $wpdb->last_query);
        wp_send_json_error('Database error: ' . $wpdb->last_error);
        return;
    }
    
    $insert_id = $wpdb->insert_id;
    error_log('✓ Database insert successful. Insert ID: ' . $insert_id);

    // Send admin notification email
    $admin_email = 'info@thetravelerportal.com';
    $admin_subject = 'New Booking Request - ' . $package_name;
    $headers = array('Content-Type: text/html; charset=UTF-8');
    
    $admin_message = "
    <html>
    <head>
        <style>
            body { font-family: Arial, sans-serif; line-height: 1.6; color: #333; }
            .email-container { max-width: 600px; margin: 0 auto; padding: 20px; }
            .email-header { background: linear-gradient(135deg, #e67e22 0%, #d35400 100%); color: white; padding: 30px; text-align: center; border-radius: 8px 8px 0 0; }
            .email-body { background-color: #f5f8fa; padding: 30px; }
            .field-section { margin-bottom: 25px; }
            .section-title { color: #e67e22; font-size: 16px; font-weight: bold; margin-bottom: 15px; text-transform: uppercase; border-bottom: 2px solid #e67e22; padding-bottom: 5px; }
            .field-row { margin-bottom: 12px; }
            .field-label { font-weight: bold; color: #2c3e50; }
            .field-value { margin-top: 3px; padding: 10px; background-color: white; border-left: 3px solid #e67e22; }
            .email-footer { text-align: center; padding: 20px; font-size: 12px; color: #666; background-color: #f5f8fa; border-radius: 0 0 8px 8px; }
            .booking-ref { background: #fff3cd; padding: 10px; border-radius: 5px; text-align: center; font-size: 18px; font-weight: bold; color: #856404; margin-bottom: 20px; }
        </style>
    </head>
    <body>
        <div class='email-container'>
            <div class='email-header'>
                <h2>New Package Booking Request</h2>
            </div>
            <div class='email-body'>
                <div class='booking-ref'>
                    Booking Reference: {$booking_reference}
                </div>
                
                <div class='field-section'>
                    <div class='section-title'>Package Information</div>
                    <div class='field-row'>
                        <div class='field-label'>Package Name:</div>
                        <div class='field-value'>{$package_name}</div>
                    </div>
                    <div class='field-row'>
                        <div class='field-label'>Departure Date:</div>
                        <div class='field-value'>{$departure_date}</div>
                    </div>
                    <div class='field-row'>
                        <div class='field-label'>Budget Preference:</div>
                        <div class='field-value'>{$budget_preference}</div>
                    </div>
                    <div class='field-row'>
                        <div class='field-label'>Group Size:</div>
                        <div class='field-value'>{$num_adults} Adult(s), {$num_children} Child(ren)</div>
                    </div>
                </div>
                
                <div class='field-section'>
                    <div class='section-title'>Customer Information</div>
                    <div class='field-row'>
                        <div class='field-label'>Full Name:</div>
                        <div class='field-value'>{$customer_name}</div>
                    </div>
                    <div class='field-row'>
                        <div class='field-label'>Email:</div>
                        <div class='field-value'>{$customer_email}</div>
                    </div>
                    <div class='field-row'>
                        <div class='field-label'>Phone:</div>
                        <div class='field-value'>{$customer_phone}</div>
                    </div>
                    <div class='field-row'>
                        <div class='field-label'>Date of Birth:</div>
                        <div class='field-value'>{$customer_dob}</div>
                    </div>
                </div>
                
                " . (!empty($special_requests) ? "
                <div class='field-section'>
                    <div class='section-title'>Special Requests</div>
                    <div class='field-value'>{$special_requests}</div>
                </div>
                " : "") . "
            </div>
            <div class='email-footer'>
                <p>This booking was submitted on " . date('F j, Y, g:i a') . "</p>
                <p><strong>The Travel Portal</strong> - Package Booking System</p>
            </div>
        </div>
    </body>
    </html>
    ";

    $admin_mail_sent = wp_mail($admin_email, $admin_subject, $admin_message, $headers);
    error_log('Admin email sent: ' . ($admin_mail_sent ? 'YES' : 'NO'));

    // Send customer confirmation email
    $customer_subject = 'Booking Confirmation - ' . $package_name;
    
    $customer_message = "
    <html>
    <head>
        <style>
            body { font-family: Arial, sans-serif; line-height: 1.6; color: #333; }
            .email-container { max-width: 600px; margin: 0 auto; padding: 20px; background-color: #f5f8fa; }
            .email-header { background: linear-gradient(135deg, #e67e22 0%, #d35400 100%); color: white; padding: 40px 20px; text-align: center; border-radius: 8px 8px 0 0; }
            .email-header h1 { margin: 0; font-size: 28px; }
            .email-body { background-color: white; padding: 40px 30px; }
            .greeting { font-size: 18px; color: #e67e22; margin-bottom: 20px; }
            .booking-ref-box { background: linear-gradient(135deg, #fff3cd 0%, #ffeaa7 100%); padding: 20px; border-radius: 8px; text-align: center; margin: 20px 0; border: 2px dashed #e67e22; }
            .booking-ref-label { font-size: 14px; color: #856404; text-transform: uppercase; margin-bottom: 5px; }
            .booking-ref-number { font-size: 24px; font-weight: bold; color: #e67e22; letter-spacing: 2px; }
            .field-section { margin-bottom: 25px; }
            .section-title { color: #e67e22; font-size: 16px; font-weight: bold; margin-bottom: 15px; text-transform: uppercase; border-bottom: 2px solid #e67e22; padding-bottom: 5px; }
            .field-row { margin-bottom: 12px; }
            .field-label { font-weight: bold; color: #2c3e50; font-size: 14px; }
            .field-value { margin-top: 3px; color: #555; font-size: 15px; }
            .next-steps { background-color: #e8f5e9; padding: 20px; border-radius: 8px; margin: 25px 0; border-left: 4px solid #4caf50; }
            .next-steps h3 { color: #2e7d32; margin-top: 0; }
            .email-footer { text-align: center; padding: 30px 20px; color: #666; font-size: 13px; background-color: #f5f8fa; border-radius: 0 0 8px 8px; }
        </style>
    </head>
    <body>
        <div class='email-container'>
            <div class='email-header'>
                <h1>Booking Confirmed!</h1>
                <p style='margin: 10px 0 0 0; font-size: 16px;'>Your adventure begins here</p>
            </div>
            <div class='email-body'>
                <p class='greeting'>Dear {$customer_name},</p>
                <p>Thank you for choosing The Travel Portal! We're excited to help you create unforgettable memories.</p>
                
                <div class='booking-ref-box'>
                    <div class='booking-ref-label'>Your Booking Reference</div>
                    <div class='booking-ref-number'>{$booking_reference}</div>
                    <p style='margin: 10px 0 0 0; font-size: 13px; color: #856404;'>Please keep this reference number for your records</p>
                </div>
                
                <div class='field-section'>
                    <div class='section-title'>Package Details</div>
                    <div class='field-row'>
                        <div class='field-label'>Package Name:</div>
                        <div class='field-value'>{$package_name}</div>
                    </div>
                    <div class='field-row'>
                        <div class='field-label'>Departure Date:</div>
                        <div class='field-value'>{$departure_date}</div>
                    </div>
                    <div class='field-row'>
                        <div class='field-label'>Budget Preference:</div>
                        <div class='field-value'>{$budget_preference}</div>
                    </div>
                    <div class='field-row'>
                        <div class='field-label'>Travelers:</div>
                        <div class='field-value'>{$num_adults} Adult(s)" . ($num_children > 0 ? ", {$num_children} Child(ren)" : "") . "</div>
                    </div>
                </div>
                
                <div class='field-section'>
                    <div class='section-title'>Your Information</div>
                    <div class='field-row'>
                        <div class='field-label'>Name:</div>
                        <div class='field-value'>{$customer_name}</div>
                    </div>
                    <div class='field-row'>
                        <div class='field-label'>Email:</div>
                        <div class='field-value'>{$customer_email}</div>
                    </div>
                    <div class='field-row'>
                        <div class='field-label'>Phone:</div>
                        <div class='field-value'>{$customer_phone}</div>
                    </div>
                </div>
                
                " . (!empty($special_requests) ? "
                <div class='field-section'>
                    <div class='section-title'>Your Special Requests</div>
                    <div class='field-value'>{$special_requests}</div>
                </div>
                " : "") . "
                
                <div class='next-steps'>
                    <h3>What Happens Next?</h3>
                    <ul style='margin: 10px 0; padding-left: 20px; line-height: 1.8;'>
                        <li>Our travel specialists will review your booking within 24 hours</li>
                        <li>We'll contact you to confirm availability and discuss your itinerary</li>
                        <li>You'll receive a detailed quote and payment options</li>
                        <li>Once confirmed, we'll send you a comprehensive travel package</li>
                    </ul>
                </div>
                
                <p style='margin-top: 30px;'>If you have any questions, feel free to contact us at <strong>+256 771 456146</strong> or reply to this email.</p>
                <p style='margin-top: 20px;'>Safe travels,<br><strong>The Travel Portal Team</strong></p>
            </div>
            <div class='email-footer'>
                <p><strong>The Travel Portal</strong></p>
                <p>Email: info@thetravelerportal.com | Phone: +256 771 456146</p>
                <p>Kampala, Uganda</p>
            </div>
        </div>
    </body>
    </html>
    ";

    $customer_mail_sent = wp_mail($customer_email, $customer_subject, $customer_message, $headers);
    error_log('Customer email sent: ' . ($customer_mail_sent ? 'YES' : 'NO'));

    // Store data in session for thank you page
    if (!session_id()) {
        session_start();
    }
    
    $_SESSION['booking_submission'] = array(
        'booking_reference' => $booking_reference,
        'package_name' => $package_name,
        'customer_name' => $customer_name,
        'customer_email' => $customer_email,
        'customer_phone' => $customer_phone,
        'customer_dob' => $customer_dob,
        'num_adults' => $num_adults,
        'num_children' => $num_children,
        'departure_date' => $departure_date,
        'budget_preference' => $budget_preference,
        'special_requests' => $special_requests,
        'submission_time' => date('F j, Y, g:i a')
    );
    
    error_log('✓ Session data stored');
    error_log('Redirect URL: ' . home_url('/booking-thank-you'));
    error_log('=== BOOKING SUBMISSION COMPLETED SUCCESSFULLY ===');

    // Return success with redirect URL
    wp_send_json_success(array(
        'redirect_url' => home_url('/booking-thank-you'),
        'booking_reference' => $booking_reference,
        'message' => 'Booking submitted successfully'
    ));
}

add_action('wp_ajax_submit_package_booking', 'handle_package_booking_submission');
add_action('wp_ajax_nopriv_submit_package_booking', 'handle_package_booking_submission');

// ==============================================
// 4. CUSTOM BREADCRUMB FUNCTION
// ==============================================

if (!function_exists('custom_breadcrumb')) {
    function custom_breadcrumb() {
        echo '<div class="breadcrumb-container">';
        echo '<div class="breadcrumb">';
        echo '<a href="' . home_url() . '">Home</a>';
        echo '<span class="breadcrumb-separator">›</span>';
        echo '<span class="breadcrumb-current">Page Not Found</span>';
        echo '</div>';
        echo '</div>';
    }
}



// ==================== BUDGET CARDS METABOX ====================
function add_budget_cards_metabox() {
    add_meta_box(
        'budget_cards_metabox',
        'Budget Cards', 
        'budget_cards_metabox_callback',
        array('romantic_package', 'travel_package'),
        'normal',
        'high'
    );
}
add_action('add_meta_boxes', 'add_budget_cards_metabox');

function budget_cards_metabox_callback($post) {
    wp_nonce_field('budget_cards_metabox', 'budget_cards_nonce');
    $budget_cards = get_post_meta($post->ID, '_budget_cards', true);
    if (empty($budget_cards)) $budget_cards = array();
    ?>
    <div id="budget-cards-container" style="margin-top:20px;">
        <div id="budget-cards-list">
            <?php foreach($budget_cards as $index => $card): ?>
            <div class="budget-card-item" data-index="<?php echo $index; ?>" style="border:2px solid #0073aa;padding:20px;margin-bottom:20px;background:#f9f9f9;border-radius:8px;">
                <div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:15px;">
                    <h3 style="margin:0;color:#0073aa;">Budget Card #<?php echo ($index + 1); ?></h3>
                    <button type="button" class="button remove-budget-card" style="background:#dc3545;color:white;border-color:#dc3545;">Remove Card</button>
                </div>
                
                <table class="form-table">
                    <tr>
                        <th style="width:200px;"><label>Budget Tier Name *</label></th>
                        <td>
                            <input type="text" name="budget_cards[<?php echo $index; ?>][card_name]" value="<?php echo esc_attr($card['card_name'] ?? ''); ?>" style="width:100%;" placeholder="e.g., Budget Friendly, Standard, Premium, Luxury" required />
                            <p class="description">The name of this budget tier (e.g., "Premium Experience")</p>
                        </td>
                    </tr>
                    <tr>
                        <th><label>Starting Price (USD) *</label></th>
                        <td>
                            <input type="number" name="budget_cards[<?php echo $index; ?>][card_price]" value="<?php echo esc_attr($card['card_price'] ?? ''); ?>" style="width:100%;" placeholder="e.g., 1500" step="0.01" required />
                            <p class="description">The starting price in USD for this budget tier</p>
                        </td>
                    </tr>
                    <tr>
                        <th><label>Benefits *</label></th>
                        <td>
                            <textarea name="budget_cards[<?php echo $index; ?>][card_benefits_text]" rows="8" style="width:100%;" placeholder="Enter each benefit on a new line:&#10;✓ 3-star accommodation&#10;✓ Daily breakfast&#10;✓ Airport transfers&#10;✓ Local guide" required><?php 
                                if(!empty($card['card_benefits'])) {
                                    if(is_array($card['card_benefits'])) {
                                        echo esc_textarea(implode("\n", $card['card_benefits']));
                                    } else {
                                        echo esc_textarea($card['card_benefits']);
                                    }
                                } elseif(!empty($card['card_benefits_text'])) {
                                    echo esc_textarea($card['card_benefits_text']);
                                }
                            ?></textarea>
                            <p class="description">List each benefit on a new line. These will appear as bullet points on the card.</p>
                        </td>
                    </tr>
                </table>
            </div>
            <?php endforeach; ?>
        </div>
        
        <button type="button" id="add-budget-card" class="button button-primary button-large">
            <span class="dashicons dashicons-plus-alt" style="vertical-align:middle;"></span>
            Add Budget Card
        </button>
        
        <p class="description" style="margin-top:10px;">
            <strong>Note:</strong> You can add unlimited budget cards. Fill in all required fields (*) for each card.
        </p>
    </div>

    <script>
    jQuery(document).ready(function($) {
        var cardIndex = <?php echo count($budget_cards); ?>;

        $('#add-budget-card').click(function() {
            var html = '<div class="budget-card-item" data-index="' + cardIndex + '" style="border:2px solid #0073aa;padding:20px;margin-bottom:20px;background:#f9f9f9;border-radius:8px;">';
            html += '<div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:15px;">';
            html += '<h3 style="margin:0;color:#0073aa;">Budget Card #' + (cardIndex + 1) + '</h3>';
            html += '<button type="button" class="button remove-budget-card" style="background:#dc3545;color:white;border-color:#dc3545;">Remove Card</button>';
            html += '</div>';
            html += '<table class="form-table">';
            html += '<tr><th style="width:200px;"><label>Budget Tier Name *</label></th>';
            html += '<td><input type="text" name="budget_cards[' + cardIndex + '][card_name]" value="" style="width:100%;" placeholder="e.g., Budget Friendly, Standard, Premium" required />';
            html += '<p class="description">The name of this budget tier</p></td></tr>';
            html += '<tr><th><label>Starting Price (USD) *</label></th>';
            html += '<td><input type="number" name="budget_cards[' + cardIndex + '][card_price]" value="" style="width:100%;" placeholder="e.g., 1500" step="0.01" min="0" required />';
            html += '<p class="description">The starting price in USD for this budget tier</p></td></tr>';
            html += '<tr><th><label>Benefits *</label></th>';
            html += '<td><textarea name="budget_cards[' + cardIndex + '][card_benefits_text]" rows="8" style="width:100%;" placeholder="Enter each benefit on a new line" required></textarea>';
            html += '<p class="description">List each benefit on a new line.</p></td></tr>';
            html += '</table></div>';
            
            $('#budget-cards-list').append(html);
            cardIndex++;
        });

        $(document).on('click', '.remove-budget-card', function() {
            if (confirm('Are you sure you want to remove this budget card?')) {
                $(this).closest('.budget-card-item').remove();
                $('.budget-card-item').each(function(index) {
                    $(this).find('h3').text('Budget Card #' + (index + 1));
                });
            }
        });

        $('form#post').on('submit', function(e) {
            var hasErrors = false;
            $('.budget-card-item').each(function() {
                var cardName = $(this).find('input[name*="[card_name]"]').val().trim();
                var cardPrice = $(this).find('input[name*="[card_price]"]').val().trim();
                var benefits = $(this).find('textarea[name*="[card_benefits_text]"]').val().trim();
                
                if (!cardName || !cardPrice || !benefits) {
                    hasErrors = true;
                    $(this).css('border-color', 'red');
                } else {
                    $(this).css('border-color', '#0073aa');
                }
            });
            
            if (hasErrors) {
                alert('Please fill in all required fields for each budget card before saving.');
                e.preventDefault();
                return false;
            }
        });
    });
    </script>
    <?php
}
   
function save_budget_cards_metabox($post_id) {
    if (!isset($_POST['budget_cards_nonce']) || !wp_verify_nonce($_POST['budget_cards_nonce'], 'budget_cards_metabox')) {
        return;
    }

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

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

    if (isset($_POST['budget_cards']) && is_array($_POST['budget_cards'])) {
        $budget_cards = array();
        
        foreach($_POST['budget_cards'] as $card_data) {
            if (!empty(trim($card_data['card_name'])) && !empty(trim($card_data['card_price']))) {
                $benefits = array();
                
                if (!empty($card_data['card_benefits_text'])) {
                    $benefits_text = sanitize_textarea_field($card_data['card_benefits_text']);
                    $benefits = array_filter(
                        array_map('trim', explode("\n", $benefits_text)),
                        function($item) {
                            return !empty($item);
                        }
                    );
                }
                
                $budget_cards[] = array(
                    'card_name' => sanitize_text_field($card_data['card_name']),
                    'card_price' => floatval($card_data['card_price']),
                    'card_benefits' => $benefits,
                    'card_benefits_text' => sanitize_textarea_field($card_data['card_benefits_text'])
                );
            }
        }
        
        if (!empty($budget_cards)) {
            update_post_meta($post_id, '_budget_cards', $budget_cards);
        } else {
            delete_post_meta($post_id, '_budget_cards');
        }
    } else {
        delete_post_meta($post_id, '_budget_cards');
    }
}
add_action('save_post', 'save_budget_cards_metabox');


// ==================== PACKAGE DETAILS METABOX ====================
function add_package_details_metabox() {
    add_meta_box(
        'package_details_metabox',
        'Package Details',
        'package_details_metabox_callback',
        array('romantic_package', 'travel_package'),
        'side',
        'high'
    );
}
add_action('add_meta_boxes', 'add_package_details_metabox');

function package_details_metabox_callback($post) {
    wp_nonce_field('package_details_metabox', 'package_details_nonce');
    
    $country = get_post_meta($post->ID, '_package_country', true);
    $city = get_post_meta($post->ID, '_package_city', true);
    $group_size_min = get_post_meta($post->ID, '_group_size_min', true);
    $group_size_max = get_post_meta($post->ID, '_group_size_max', true);
    $trip_duration = get_post_meta($post->ID, '_trip_duration', true);
    $best_season = get_post_meta($post->ID, '_best_season', true);
    $starting_price = get_post_meta($post->ID, '_starting_price', true);
    ?>
    
    <p>
        <label for="package_country"><strong>Country:</strong></label><br>
        <input type="text" id="package_country" name="package_country" value="<?php echo esc_attr($country); ?>" style="width:100%;" placeholder="e.g., Maldives" />
    </p>
    
    <p>
        <label for="package_city"><strong>City/Area:</strong></label><br>
        <input type="text" id="package_city" name="package_city" value="<?php echo esc_attr($city); ?>" style="width:100%;" placeholder="e.g., Male" />
    </p>
    
    <p>
        <label for="trip_duration"><strong>Duration (Days):</strong></label><br>
        <input type="text" id="trip_duration" name="trip_duration" value="<?php echo esc_attr($trip_duration); ?>" style="width:100%;" placeholder="e.g., 7 Days" />
    </p>
    
    <p>
        <label><strong>Group Size:</strong></label><br>
        <div style="display:flex;gap:10px;">
            <input type="number" id="group_size_min" name="group_size_min" value="<?php echo esc_attr($group_size_min); ?>" style="width:48%;" placeholder="Min" min="1" />
            <input type="number" id="group_size_max" name="group_size_max" value="<?php echo esc_attr($group_size_max); ?>" style="width:48%;" placeholder="Max" min="1" />
        </div>
        <small style="color:#666;">Leave max empty for "unlimited"</small>
    </p>
    
    <p>
        <label for="best_season"><strong>Best Season:</strong></label><br>
        <input type="text" id="best_season" name="best_season" value="<?php echo esc_attr($best_season); ?>" style="width:100%;" placeholder="e.g., Dec - Mar" />
    </p>
    
    <p>
        <label for="starting_price"><strong>Starting Price (USD):</strong></label><br>
        <input type="number" id="starting_price" name="starting_price" value="<?php echo esc_attr($starting_price); ?>" style="width:100%;" placeholder="1500" step="0.01" min="0" />
    </p>
    <?php
}

function save_package_details_metabox($post_id) {
    if (!isset($_POST['package_details_nonce']) || !wp_verify_nonce($_POST['package_details_nonce'], 'package_details_metabox')) {
        return;
    }

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

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

    // Save all fields
    $fields = array(
        'package_country',
        'package_city',
        'group_size_min',
        'group_size_max',
        'trip_duration',
        'best_season',
        'starting_price'
    );

    foreach ($fields as $field) {
        if (isset($_POST[$field])) {
            update_post_meta($post_id, '_' . $field, sanitize_text_field($_POST[$field]));
        }
    }
}
add_action('save_post', 'save_package_details_metabox');
?>