HEX
Server: nginx/1.24.0
System: Linux DGT-WORDPRESS-VM-SERVER 6.14.0-1014-azure #14~24.04.1-Ubuntu SMP Fri Oct 3 20:52:11 UTC 2025 x86_64
User: ubuntu (1000)
PHP: 8.4.12
Disabled: NONE
Upload Files
File: /mnt/data/dreamsrent-wp-demo/wp-content/themes/dreamsrent/functions.php
<?php
if ( ! defined('ABSPATH') ) {
    exit;
}
 if(defined('DREMSRENT_URL') 	== false) 	define('DREMSRENT_URL', get_template_directory());
 if(defined('DREMSRENT_URI') 	== false) 	define('DREMSRENT_URI', get_template_directory_uri());
 add_action('after_setup_theme', 'dreamsrent_load_textdomain');
function dreamsrent_load_textdomain() {
    load_theme_textdomain('dreamsrent', get_template_directory() . '/languages');
 }    

 

        // requires Adds PayPal email field to vendor user profile.
           //require_once get_template_directory() . '/inc/paypal-vendor-payment.php';

            //require Adds PayPal email field to vendor user profile.
           // require_once get_template_directory() . '/inc/vendor-profile-fields.php';

            // require commission/payout tables and admin pages
            require_once get_template_directory() . '/inc/vendor-commission.php';

            // require libraries, function
            require( DREMSRENT_URL.'/inc/init.php' );

            // Add js, css
            require( DREMSRENT_URL.'/inc/add_js_css.php' );
             // register menu, widget
            require( DREMSRENT_URL.'/inc/register_menu_widget.php' );

            // require menu
            require_once (DREMSRENT_URL.'/inc/dsr_walker_nav_menu.php');

            // require content
            require_once (DREMSRENT_URL.'/templates/blog/define_blocks_content.php');
            
            // require breadcrumbs
            require( DREMSRENT_URL.'/inc/breadcrumbs.php' );

            require( DREMSRENT_URL.'/inc/dreamsrent-demo-content.php' );
             // Require customize
            if( is_user_logged_in() ){
                require( DREMSRENT_URL.'/inc/customize_google_font/customizer_google_font.php' );
                require( DREMSRENT_URL.'/inc/customizer.php' );
            }
            
            //Redux Functions
            if(in_array('redux-framework/redux-framework.php', apply_filters('active_plugins', get_option('active_plugins'))))
            {
                add_action( 'after_setup_theme', 'dreamsrent_register_redux_sections', 20 );
function dreamsrent_register_redux_sections() {
                require_once ( DREMSRENT_URL.'/inc/options-init.php' );
}
            }
            // Require metabox
            if( is_admin() ){
              require( DREMSRENT_URL.'/inc/custom_metabox/add_custom_metabox.php' );
                 // Require TGM
                require_once ( DREMSRENT_URL.'/inc/active_plugins.php' );	
                require_once (DREMSRENT_URL . '/inc/class-tgm-plugin-activation.php');	
            }


            function dreamsrent_wp_body_classes( $classes ){
                $lang = get_theme_mod( 'calendar_layout', 'en' ); 
                $calendar_dis_weekend = get_theme_mod( 'calendar_dis_weekend', '0,6' );
                $cal_time = get_theme_mod( 'calendar_time', '07:00, 07:30, 08:00, 08:30, 09:00, 09:30, 10:00, 10:30, 11:00, 11:30, 12:00, 12:30, 13:00, 13:30, 14:00, 14:30, 15:00, 15:30, 16:00, 16:30, 17:00, 17:30, 18:00' );
                
                $classes[] = '" data-lang="'.$lang.'';
                $classes[] = '" data-time="'.$cal_time.'';
                $classes[] = '" data-disweek="'.$calendar_dis_weekend.'';

                return $classes;
            }
            add_filter( 'body_class','dreamsrent_wp_body_classes', 9999 );

            // Active Request Booking Form
            if( get_theme_mod( 'rd_active_request_booking', 'false' ) == 'true' ){
                add_filter( 'body_class','dreamsrent_ctive_request_booking', 9998 );
            }

            function dreamsrent_ctive_request_booking( $classes ){
                $classes[] = 'active_request_booking';
                return $classes;
            }

            function dreamsrent_remove_widget_editort() {
                remove_theme_support( 'widgets-block-editor' );
            }
            add_action( 'after_setup_theme', 'dreamsrent_remove_widget_editort' );

        //get options from wp_options for redux
            if( !function_exists('dreamsrent_fl_framework_getoptions') )
            {
                function dreamsrent_fl_framework_getoptions($get_text)
                {
                    global $dreamsrent_theme_options;
                    if(isset($dreamsrent_theme_options[$get_text]) &&  $dreamsrent_theme_options[$get_text] !=""):
                        return $dreamsrent_theme_options[$get_text];
                    else:
                        return false;
                    endif;
                }
            }

            // Remove <p> and <br/> from Contact Form 7
        add_filter('wpcf7_autop_or_not', '__return_false');


        // In manufacturer
        function dremsrent_manufacturer_getterm($taxonomy = 'manufacturer') {
            global $post;
            $term_list = '';
            $terms = get_the_terms($post->ID, $taxonomy);
            $n = '1';
            if ($terms) {
                foreach($terms as $term) {
                    if ($n <= count($terms)) {
                        $term_list .= $term->name . ', ';
                    }  
                    break;
                    ++$n;
                }
            }

            $term_list = rtrim($term_list, ', ');

            return $term_list;
        }

        // In category.php
        function dremsrent_product_cat_getterm($taxonomy = 'product_cat') {
            global $post;
            $term_list = '';
            $terms = get_the_terms($post->ID, $taxonomy);
            $n = '1';
            if ($terms) {
                foreach($terms as $term) {
                    if ($n <= count($terms)) {
                        $term_list .= $term->name . ', ';
                    }  
                    break;
                    ++$n;
                }
            }

            $term_list = rtrim($term_list, ', ');

            return $term_list;
        }

        //added for password and confirm password
        function enqueue_jquery() {
            wp_enqueue_script('jquery');
        }
        add_action('wp_enqueue_scripts', 'enqueue_jquery');

        require_once ( get_template_directory() . '/inc/typo.php');

        if ( ! function_exists( 'dreamsrent_function_name_given' ) ) :    
            /**     * get the value of view.     */ 
            function dreamsrent_function_name_given($postID) {   
            $count_key = 'wpb_post_views_count';    
            $count = get_post_meta($postID, $count_key, true);    
            if($count ==''){        
            $count = 1;        
            delete_post_meta($postID, $count_key);        
            add_post_meta($postID, $count_key, '1');    
            } else {        
            $count++;        
            update_post_meta($postID, $count_key, $count);    
            }
            }
        endif; 


        // Disable XML-RPC
        add_filter('xmlrpc_enabled', '__return_false');

        // for cart section
        // require_once ( DREMSRENT_URL.'/inc/dsrent-cart.php' );
        // require_once ( DREMSRENT_URL.'/inc/bookings/dreamsrent_booking.php' );

        add_filter( 'woocommerce_data_stores', 'dreams_woocommerce_data_stores' );

        function dreams_woocommerce_data_stores( $stores ) {
            require_once ( DREMSRENT_URL.'/inc/bookings/class-data-store-cpt.php' );
            require_once ( DREMSRENT_URL.'/inc/bookings/dreamsrent_booking.php' );
            $stores['product'] = 'Dreams_Product_Data_Store_CPT';
            return $stores;
        // do_action( ' woocommerce_new_order ');
        }


        //Enquiry coding in rental-detail.php
        function dreams_store_data() {
            // Check nonce
            check_ajax_referer('dreams_ajax_nonce_enquiry', 'nonce');
        
            // Get data from request
            $fullname = isset($_POST['fullname']) ? sanitize_text_field($_POST['fullname']) : '';
            $emailid = isset($_POST['emailid']) ? sanitize_text_field($_POST['emailid']) : '';
            $mobileno = isset($_POST['mobileno']) ? sanitize_text_field($_POST['mobileno']) : '';
            $message = isset($_POST['message']) ? sanitize_text_field($_POST['message']) : '';
            $post_id = isset($_POST['post_id']) ? sanitize_text_field($_POST['post_id']) : '';
            $date_created = current_datetime()->format('Y-m-d H:i:s');
            global $wpdb;

            $table_name = $wpdb->prefix . 'dreamsrent_enquiry';

            // Store data
            $data = array(
            'name' => $fullname,
            'email' => $emailid,
            'mobile_no' => $mobileno,
            'message' => $message,
            'post_id' => $post_id,
            'date_created' => $date_created,
            );
            // Insert data into database
            $wpdb->insert( $table_name, $data );
            // wp_die();

            // Send success response
          wp_send_json_success();
        }
        add_action( 'wp_ajax_dreams_store_data', 'dreams_store_data' );
        add_action( 'wp_ajax_nopriv_dreams_store_data', 'dreams_store_data' );


        //Enquiry admin menu for viewing enquiry
        function add_enquiry_menu() {
            add_menu_page(
                'Enquiry',             
                'Enquiry',             
                'manage_options',      
                'enquiry',             
                'enquiry_page_content',
                'dashicons-clipboard',
                28                 
            );
        }
        add_action('admin_menu', 'add_enquiry_menu');

        // Enquiry page content
        function enquiry_page_content() {
            global $wpdb; // WordPress database global object

            // Retrieve data from the dreamsrent_enquiry table
            $enquiries = $wpdb->get_results("SELECT * FROM {$wpdb->prefix}dreamsrent_enquiry ORDER BY date_created DESC");

            // Display fetched data
            echo '<div class="wrap">';
            echo '<h1>Enquiry</h1>';

            if ($enquiries) {
                echo '<table class="wp-list-table widefat fixed striped">';
                echo '<thead>';
                echo '<tr>';
                echo '<th scope="col">Car ID</th>';
                echo '<th scope="col">Car Name</th>';
                echo '<th scope="col">Name</th>';
                echo '<th scope="col">Email</th>';
                echo '<th scope="col">Mobile</th>';
                echo '<th scope="col">Message</th>';
                echo '<th scope="col">Date Received</th>';
                echo '<th scope="col">Car Link</th>';

                echo '</tr>';
                echo '</thead>';
                echo '<tbody>';
                foreach ($enquiries as $enquiry) {
                    echo '<tr>';
                    echo '<td>' . $enquiry->post_id . '</td>';
                    echo '<td>' . get_the_title($enquiry->post_id) . '</td>';
                    echo '<td>' . $enquiry->name . '</td>';
                    echo '<td>' . $enquiry->email . '</td>';
                    echo '<td>' . $enquiry->mobile_no . '</td>';
                    echo '<td>' . $enquiry->message . '</td>';
                    echo '<td>' . $enquiry->date_created . '</td>';
                    echo '<td><a href="' . get_permalink($enquiry->post_id) . '">View Car</a></td>';

                    echo '</tr>';
                }
                echo '</tbody>';
                echo '</table>';
            } else {
                echo '<p>No enquiries found.</p>';
            }

            echo '</div>';
        }


        add_filter( 'woocommerce_should_load_paypal_standard', '__return_true' );
        add_theme_support( 'woocommerce' );

        function add_paypal_standard_gateway($gateways) {
            $gateways[] = 'WC_Gateway_Paypal';
            return $gateways;
        }
        add_filter( 'woocommerce_payment_gateways', 'add_paypal_standard_gateway' );

        function create_dreamsrent_booking_table() {
            global $wpdb;
            $table_name = $wpdb->prefix . 'dreamsrent_booking';
            

            // Check if the column already exists to avoid duplication
            $column = $wpdb->get_results("SHOW COLUMNS FROM $table_name LIKE 'reserv_id'");
            $column2 = $wpdb->get_results("SHOW COLUMNS FROM $table_name LIKE 'car_id'");
            if (empty($column)) {
                $wpdb->query("ALTER TABLE $table_name ADD reserv_id TEXT NOT NULL AFTER time_option");
            }
            if (empty($column2)) {
            $wpdb->query("ALTER TABLE $table_name ADD car_id TEXT NOT NULL AFTER id");
            }
            
            if($wpdb->get_var("SHOW TABLES LIKE '$table_name'") != $table_name) {
                $charset_collate = $wpdb->get_charset_collate();

                $sql = "CREATE TABLE $table_name (
                    id mediumint(9) NOT NULL AUTO_INCREMENT,
                    car_id mediumint(9) NOT NULL,
                    product_id mediumint(9) NOT NULL,
                    order_id mediumint(9) NOT NULL,
                    product_name text NOT NULL,
                    pickup_date varchar(255) NOT NULL,
                    dropoff_date varchar(255) NOT NULL,
                    time_option text NOT NULL,
                    reserv_id text NOT NULL,
                    bkstatus text NOT NULL,
                    PRIMARY KEY  (id)
                ) $charset_collate;";

                require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
                dbDelta($sql);
            }
        }

        add_action('after_switch_theme', 'create_dreamsrent_booking_table');


 

        
        function create_dreamsrent_reservations_table() {
            global $wpdb;
            $table_name = $wpdb->prefix . 'dreamsrent_reservations';
            

                // Check if the column already exists to avoid duplication
                $column = $wpdb->get_results("SHOW COLUMNS FROM $table_name LIKE 'author_id'");
                 if (empty($column)) {
                    $wpdb->query("ALTER TABLE $table_name ADD author_id TEXT NOT NULL AFTER customer_id");
                }
          

            if($wpdb->get_var("SHOW TABLES LIKE '$table_name'") != $table_name) {
                $charset_collate = $wpdb->get_charset_collate();

                $sql = "CREATE TABLE $table_name (
                    id mediumint(9) NOT NULL AUTO_INCREMENT,
                    tarrif varchar(255) NOT NULL,
                    rental_type varchar(255) NOT NULL,
                    passengers varchar(255) NOT NULL,
                    start_date varchar(255) NOT NULL,
                    start_time varchar(255) NOT NULL,
                    end_date varchar(255) NOT NULL,
                    end_time varchar(255) NOT NULL,
                    pickup_location varchar(255) NOT NULL,
                    drop_location varchar(255) NOT NULL,
                    security_deposit varchar(255) NOT NULL,
                    return_same_location varchar(255) NOT NULL,
                    car_id varchar(255) NOT NULL,
                    customer_id varchar(255) NOT NULL,
                    customer_details varchar(255) NOT NULL,
                    driver_id varchar(255) NOT NULL,
                    driver_details varchar(255) NOT NULL,
                    extra_services varchar(255) NOT NULL,
                    base_kilometers varchar(255) NOT NULL,
                    base_kilometers_unlimited varchar(255) NOT NULL,
                    kilometers_extra_price varchar(255) NOT NULL,
                    insurance varchar(255) NOT NULL,
                    price_car varchar(255) NOT NULL,
                    es_price varchar(255) NOT NULL,
                    sd_price varchar(255) NOT NULL,
                    driver_price varchar(255) NOT NULL,
                    ins_price varchar(255) NOT NULL,
                    total_price varchar(255) NOT NULL,
                    bkstatus text NOT NULL,
                    PRIMARY KEY  (id)
                ) $charset_collate;";

                require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
                dbDelta($sql);
            }
        }

        add_action('after_switch_theme', 'create_dreamsrent_reservations_table');


        function create_dreamsrent_maintenance_table() {
            global $wpdb;
            $table_name = $wpdb->prefix . 'dreamsrent_maintenance';
            
            
            if($wpdb->get_var("SHOW TABLES LIKE '$table_name'") != $table_name) {
                $charset_collate = $wpdb->get_charset_collate();

                $sql = "CREATE TABLE $table_name (
                    id mediumint(9) NOT NULL AUTO_INCREMENT,
                    car_id mediumint(9) NOT NULL,
                    odometer varchar(255) NOT NULL,
                    start_date varchar(255) NOT NULL,
                    end_date varchar(255) NOT NULL,
                    details varchar(255) NOT NULL,
                    status varchar(255) NOT NULL,
                     PRIMARY KEY  (id)
                ) $charset_collate;";
                 require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
                dbDelta($sql);
            }
        }

        add_action('after_switch_theme', 'create_dreamsrent_maintenance_table');



        add_action('wp_ajax_check_availability', 'check_availability_callback');
        add_action('wp_ajax_nopriv_check_availability', 'check_availability_callback');

        function check_availability_callback() {

            $booking_product_id = isset($_POST['booking_product_id']) ? intval($_POST['booking_product_id']) : 0;
            $post_id = isset($_POST['post_id']) ? intval($_POST['post_id']) : 0;
            $time_option_default = isset($_POST['time_option_default']) ? sanitize_text_field($_POST['time_option_default']) : '';
            $start_date = isset($_POST['start_date']) ? sanitize_text_field($_POST['start_date']) : '';
            $end_date = isset($_POST['end_date']) ? sanitize_text_field($_POST['end_date']) : '';
            $start_time = isset($_POST['start_time']) ? sanitize_text_field($_POST['start_time']) : '';
            $end_time = isset($_POST['end_time']) ? sanitize_text_field($_POST['end_time']) : '';

            //$multicar_settings = get_post_meta($post_id, 'dreams_booking_meta_multicar_settings', true); 
$multicar_settings = intval(get_post_meta($post_id, 'dreams_booking_meta_multicar_settings', true)); 
$multicar_settings ='1';
            if (!isset($_POST['_ajax_nonce']) || !wp_verify_nonce($_POST['_ajax_nonce'], 'check_availability_nonce')) {
                wp_send_json(array(
                    'valid' => false,
                    'message' => 'Nonce verification failed'
                ));
                die();
            }

            global $wpdb;
            $table_name = $wpdb->prefix . 'dreamsrent_booking'; 
            $table_maintain = $wpdb->prefix . 'dreamsrent_maintenance'; 

            $start_date = DateTime::createFromFormat('d-m-Y', $start_date)->format('Y-m-d');
            $end_date = DateTime::createFromFormat('d-m-Y', $end_date)->format('Y-m-d');

             
             
                // Fallback: you can log an error or use the raw input
                $start_date_m = $_POST['start_date'];
                $start_date_main = date( 'd-m-Y', strtotime( $start_date_m ) );

           
                 $end_date_m= $_POST['end_date'];
                $end_date_main = date( 'd-m-Y', strtotime( $end_date_m ) );

            
            $query = $wpdb->prepare(
                "SELECT * FROM $table_name WHERE product_id = %d AND bkstatus != %s", 
                $booking_product_id, 
                'cancel'
            );

            $query2 = $wpdb->prepare(
                "SELECT * FROM $table_maintain WHERE car_id = %d", 
                $post_id 
            );
            $availability_query2 = $wpdb->get_results($query2);

            $availability_query = $wpdb->get_results($query);
            $all_dates_passed = true;
            $all_maintance_passed = true;
            
            $dates = array(); 
            $count_bookings = 0;

            if ($availability_query) {
                foreach ($availability_query as $result) {
                    $pickup_date = date('Y-m-d', strtotime($result->pickup_date));
                    $pickup_time = date('H:i', strtotime($result->pickup_date));
                    $dropoff_date = date('Y-m-d', strtotime($result->dropoff_date));
                    $dropoff_time = date('H:i', strtotime($result->dropoff_date));

                    $dates[] = array(
                        'pickup_date' => $pickup_date,
                        'dropoff_date' => $dropoff_date
                    );

                    if ($time_option_default == 'day') {
                        if (($start_date <= $dropoff_date && $end_date >= $pickup_date)) {
                            $all_dates_passed = false;
                            $count_bookings++;
                        }
                    }
                    else if ($time_option_default == 'hour') {
                        if (($start_date <= $dropoff_date && $end_date >= $pickup_date)) {
                            if ($start_date == $dropoff_date && $start_time > $dropoff_time) {
                                $all_dates_passed = true;
                            } else if ($end_date == $pickup_date && $end_time < $pickup_time) {
                                $all_dates_passed = true;
                            } else {
                                $all_dates_passed = false;
                                $count_bookings++;
                            }
                        } 
                    }
                }
            }   
                 if($availability_query2) {
                 foreach ($availability_query2 as $result2) {
                    $pickup_date = date('d-m-Y', strtotime($result2->start_date));
                    $pickup_time = date('H:i', strtotime($result2->start_date));
                    $dropoff_date = date('d-m-Y', strtotime($result2->end_date));
                    $dropoff_time = date('H:i', strtotime($result2->dropoff_date));

                    $dates[] = array(
                        'pickup_date' => $pickup_date,
                        'dropoff_date' => $dropoff_date
                    );

                    if ($time_option_default == 'day') {
                        if (($start_date_main <= $dropoff_date && $end_date_main >= $pickup_date)) {
                            $all_maintance_passed = false;
                            $count_bookings++;
                        }
                    }
                     
                }

            }

            $available_cars = $multicar_settings - $count_bookings;

            if ($available_cars > 0) {
                $all_dates_passed = true;
            }

            if($all_maintance_passed ==false) {
                wp_send_json(array(
                    'booking_product_id' => $booking_product_id,
                    'time_option_default' => $time_option_default,
                    'valid' => $all_maintance_passed,
                        
                    'message' => $all_maintance_passed ? "Under Maintanance.  cars are not available." : "Under Maintanance.  cars are not available",
                     'dates' => $dates,
                    'available_cars' => $available_cars,
                    'booked_cars' => $count_bookings
                ));

            } else { 
            wp_send_json(array(
                'booking_product_id' => $booking_product_id,
                'time_option_default' => $time_option_default,
                'valid' => $all_dates_passed,
                //'message' => $all_dates_passed ? "Booking dates are available. $available_cars cars are available. $count_bookings cars are already booked." : "Booking dates are not available. All $count_bookings cars are already booked.",
                   
                'message' => $all_dates_passed ? "Booking dates are available. cars are available." : "Booking dates are not available. Please try different dates",
                 'dates' => $dates,
                'available_cars' => $available_cars,
                'booked_cars' => $count_bookings
            ));
        }

            die();
        }



add_action('wp_ajax_get_rental_price', 'get_rental_price');
add_action('wp_ajax_nopriv_get_rental_price', 'get_rental_price');

function get_rental_price() {

     if (!isset($_POST['nonce']) || !wp_verify_nonce($_POST['nonce'], 'dreams_ajax_nonce_enquiry')) {
        wp_send_json_error(array('message' => 'Nonce verification failed'));
        wp_die();
    }
    
    // Get the rental type and post ID from the AJAX request
    $rental_type = isset($_POST['rental_type']) ? sanitize_text_field($_POST['rental_type']) : '';
    $post_id = isset($_POST['post_id']) ? intval($_POST['post_id']) : 0;

    // Start the output buffer to capture the table HTML
    ob_start(); ?>

    <table class="table table-center">
        <tbody>
        <?php
        // Default response for no price
        $no_price_msg = '<tr><td colspan="2">No price available</td></tr>';

        // Check the rental type and retrieve the appropriate price
        if ($rental_type === 'day') {
            $price = get_post_meta($post_id, 'dreams_booking_meta_rdprice', true);
            if ($price) {
                // Display the price for per day rental
                ?>
                <tr>
                    <td style="text-align: left;"><?php echo esc_html__('Per day (24 Hours)', 'dreamsrent'); ?></td>
                    <td style="text-align: right;">+ <?php echo get_woocommerce_currency_symbol(); ?> <?php echo esc_html($price); ?></td>
                </tr>
                <?php
            } else {
                // No price available for per day rental
                echo wp_kses_post($no_price_msg);
            }
        } elseif ($rental_type === 'hour') {
            $price = get_post_meta($post_id, 'dreams_booking_meta_rhprice', true);
            if ($price) {
                // Display the price for per hour rental
                ?>
                <tr>
                    <td style="text-align: left;"><?php echo esc_html__('Per hour (1 Hour)', 'dreamsrent'); ?></td>
                    <td style="text-align: right;">+ <?php echo get_woocommerce_currency_symbol(); ?> <?php echo esc_html($price); ?></td>
                </tr>
                <?php
            } else {
                // No price available for per hour rental
                echo wp_kses_post($no_price_msg);
            }
        } else {
            // No rental type selected, show default "No price available" message
            echo wp_kses_post($no_price_msg);
        }
        ?>
        </tbody>
    </table>
    <?php
    // Capture the output and return it
    $response = ob_get_clean();

    // Output the response
    echo wp_kses_post($response);

    // End the AJAX request
    wp_die();
}



        
        

        function enqueue_notification_scripts() {
            wp_enqueue_script('notification-script', get_template_directory_uri() . '/assets/js/notification.js', array('jquery'), null, true);

            wp_localize_script('notification-script', 'notificationData', array(
                'ajax_url' => admin_url('admin-ajax.php'),
                'user_id' => get_current_user_id()
            ));
        }
        add_action('wp_enqueue_scripts', 'enqueue_notification_scripts');
 

        function fetch_notifications() {
            if (!is_user_logged_in()) {
                wp_send_json_error(['message' => 'User not logged in']);
                return;
            }

            global $wpdb;
            $user_id = get_current_user_id();
            $current_user = wp_get_current_user();
            $roles = $current_user->roles;
            $role = array_shift($roles);  
            
            $table_name = $wpdb->prefix . 'user_notifications';

            // Retrieve the latest 5 unread notifications for the user
        
        if (in_array($role, array('administrator'))) {

            $notifications = $wpdb->get_results($wpdb->prepare(
                "SELECT * FROM $table_name WHERE owner_id = %d AND is_read = 0 ORDER BY created_at DESC LIMIT 10",
                $user_id
            ));
            
            } else if(in_array($role, array('subscriber'))) {
            
                $notifications = $wpdb->get_results($wpdb->prepare(
                    "SELECT * FROM $table_name WHERE user_id = %d AND user_read = 0 ORDER BY created_at DESC LIMIT 10",
                    $user_id
                ));
            }
            // Generate HTML for notifications
            ob_start();
            ?>
        
            <div class="noti-content">
                <ul class="notification-list">

                
                    <?php if ($notifications): ?>
                        <?php foreach ($notifications as $notification): ?>
                        
                            <li class="notification-message">
                                <a href="#">
                                    <div class="media d-flex">
                                    <span class="avatar avatar-lg flex-shrink-0">


                                
        <?php
        if (in_array($role, array('administrator'))) {
        $profile_picture_url = get_user_meta($notification->user_id, 'profile_picture', true);

        } else if(in_array($role, array('subscriber'))) {
        $profile_picture_url = get_user_meta($notification->owner_id, 'profile_picture', true);
        }
        $profile_picture_url_default = get_template_directory_uri() . '/assets/images/user_image.jpg';
        ?>


                    
                    
        <?php if($profile_picture_url) { ?>
        <img class="avatar-img rounded-circle" alt="User Image" src="<?php echo esc_html($profile_picture_url); ?>">
        <?php } else { ?>
        <img class="avatar-img rounded-circle" alt="User Image" src="<?php echo esc_html($profile_picture_url_default); ?>">

        <?php } ?>

                                    </span>
        <div class="media-body flex-grow-1">
        <?php 
        $user_data = get_userdata($notification->user_id);


        $order_id = $notification->order_id;

        
        if (!function_exists('get_first_product_name_by_order_id')) {
            function get_first_product_name_by_order_id($order_id) {
                // Load the WooCommerce order object
                $order = wc_get_order($order_id);
                if (!$order) {
                    return ''; // Return an empty string if the order doesn't exist
                }

                // Get the first item in the order
                foreach ($order->get_items() as $item) {
                    return $item->get_name(); // Return the first product name
                }

                return ''; // Return an empty string if there are no items
            }
        }

        // Example usage:
        $product_name = get_first_product_name_by_order_id($order_id);
        


        $user_first_name = $user_data ? $user_data->first_name : '';
        $user_last_name = $user_data ? $user_data->last_name : '';
        ?>

        <?php if($notification->type=='order_placed') { ?> 
                                    <p class="noti-details">
                                    <?php  if (in_array($role, array('administrator'))) { ?>

                                        <span class="noti-title"><?php echo esc_html($user_first_name); ?> <?php echo esc_html__('has','dreamsrent'); ?></span>

                                    <?php } else if(in_array($role, array('subscriber'))) { ?>

                                        <span class="noti-title"><?php echo esc_html__('You have','dreamsrent'); ?></span>

                                        <?php } ?>


                                        <?php echo esc_html($notification->message); ?> 
                                        
                                        <?php  if (in_array($role, array('administrator'))) { ?>

                                        <span class="noti-title"><?php echo esc_html__('your service','dreamsrent'); ?> - <?php if (!empty($product_name)) {
            echo esc_html($product_name);
        } ?> </span>

                                    <?php } else if(in_array($role, array('subscriber'))) { ?>

                                        <span class="noti-title"><?php echo esc_html__('service','dreamsrent'); ?> - <?php if (!empty($product_name)) {
            echo esc_html($product_name);
        } ?></span>

                                    <?php } ?>
                                    </p>
        
        <?php } else if($notification->type=='order_canceled') { ?>
        
            <p class="noti-details">
    <?php  if (in_array($role, array('administrator'))) { ?>
        <span class="noti-title"><?php echo esc_html($user_first_name); ?> <?php echo esc_html__('has','dreamsrent'); ?></span>
  <?php echo esc_html($notification->message); ?> <span class="noti-title"><?php echo esc_html__('booking','dreamsrent'); ?> - <?php if (!empty($product_name)) {
    echo esc_html($product_name);
} ?></span>
 <?php } else if(in_array($role, array('subscriber'))) { ?>

    <span class="noti-title"><?php echo esc_html__('You have','dreamsrent'); ?></span>
  <?php echo esc_html($notification->message); ?> <span class="noti-title"><?php echo esc_html__('booking','dreamsrent'); ?> - <?php if (!empty($product_name)) {
    echo esc_html($product_name);
} ?></span>

    <?php } ?>
    </p>
        <?php } ?>
                                        <p class="noti-time">
                                            <span class="notification-time"><?php echo human_time_diff(strtotime($notification->created_at), current_time('timestamp')); ?> <?php echo esc_html__('ago','dreamsrent'); ?></span>
                                        </p>
                                    </div>
                                    </div>
                                </a>
                            </li>
                        <?php endforeach; ?>
                    <?php else: ?>
                        <li class="notification-message">
                            <p><?php echo esc_html__('No new notifications.','dreamsrent'); ?></p>
                        </li>
                    <?php endif; ?>
                </ul>
            </div>
            
            <?php

            // Capture and send back HTML and count
            $html = ob_get_clean();
            wp_send_json_success([
                'html' => $html,
                'unread_count' => count($notifications)
            ]);
        }
        add_action('wp_ajax_fetch_notifications', 'fetch_notifications');


        function clear_notifications() {
            global $wpdb;
        
            // Get user_id from AJAX
            $user_id = isset($_POST['user_id']) ? intval($_POST['user_id']) : 0;
        
            // Debug: check if user_id is valid
            if ($user_id <= 0) {
                wp_send_json_error(array('message' => 'Invalid user ID'));
            }
        
            // Only allow current user to update their own notifications
            if ($user_id !== get_current_user_id()) {
                wp_send_json_error(array('message' => 'Unauthorized'));
            }
        
            $table_name = $wpdb->prefix . 'user_notifications';
        
            $user = get_userdata($user_id);
            if (!$user) {
                wp_send_json_error(array('message' => 'User not found'));
            }
        
            $roles = $user->roles; // Array of roles
            $primary_role = isset($roles[0]) ? $roles[0] : '';
        
            // Update only unread notifications
            switch ($primary_role) {
                case 'subscriber':
                    $updated = $wpdb->update(
                        $table_name,
                        array('user_read' => 1),
                        array('user_id' => $user_id, 'user_read' => 0)
                    );
                    break;
        
                case 'administrator':
                case 'dreamsrent_vendor':
                    $updated = $wpdb->update(
                        $table_name,
                        array('is_read' => 1),
                        array('owner_id' => $user_id, 'is_read' => 0)
                    );
                    break;
        
                default:
                    $updated = $wpdb->update(
                        $table_name,
                        array('is_read' => 1),
                        array('owner_id' => $user_id, 'is_read' => 0)
                    );
                    break;
            }
        
            wp_send_json_success(array('updated_rows' => $updated));
        }
        add_action('wp_ajax_clear_notifications', 'clear_notifications');
        
         
 
        // Order placed notification
        add_action('woocommerce_thankyou', 'add_order_placed_notification', 10, 1);

        function add_order_placed_notification($order_id) {
            if (!$order_id) return;

            $order = wc_get_order($order_id);
            $user_id = $order->get_user_id();

            // Get the first product in the order and find its post author
            $items = $order->get_items();
            $owner_id = null;

            if (!empty($items)) {
                foreach ($items as $item) {
                    $product_id = $item->get_product_id();
                    $owner_id = get_post_field('post_author', $product_id);
                    break; // Use the author of the first product only
                }
            }

            if ($user_id && $owner_id) {
                add_notification($user_id, $owner_id, $order_id, 'order_placed', 'booked');
            }
        }


        // Order canceled notification
        add_action('woocommerce_order_status_cancelled', 'add_order_canceled_notification', 10, 1);

        function add_order_canceled_notification($order_id) {
            $order = wc_get_order($order_id);
            $user_id = $order->get_user_id();

            // Retrieve the product author's ID for the first product in the order
            $items = $order->get_items();
            $owner_id = null;

            if (!empty($items)) {
                foreach ($items as $item) {
                    $product_id = $item->get_product_id();
                    $owner_id = get_post_field('post_author', $product_id);
                    break; // Use the author of the first product only
                }
            }

            if ($user_id && $owner_id) {
                add_notification($user_id, $owner_id, $order_id, 'order_canceled', 'cancelled');
            }
        }


add_action('woocommerce_order_status_cancelled', 'add_order_canceled_booking_list', 10, 1);
function add_order_canceled_booking_list($order_id) {
    global $wpdb;

    // Your custom table name
    $table_name = $wpdb->prefix . 'dreamsrent_booking';

    // Sanitize the order ID
    $order_id = absint($order_id);

    // Update the booking status to "cancel" where order_id matches
    $updated = $wpdb->update(
        $table_name,
        [ 'bkstatus' => 'cancel' ],               // Data to update
        [ 'order_id' => $order_id ],              // WHERE condition
        [ '%s' ],                                 // Format of values
        [ '%d' ]                                  // Format of WHERE condition
    );
   }


 add_action('woocommerce_order_status_processing', 'handle_cancelled_to_processing_status_change', 10, 2);

function handle_cancelled_to_processing_status_change($order_id, $order) {
    // Get order object if not already provided (for older WooCommerce versions)
    global $wpdb;
        $order = wc_get_order($order_id);
  

    // Get previous status
    //$status_from = get_post_meta($order_id, '_order_status_before', true);

    //if ($status_from === 'cancelled') {
        // Your custom logic: e.g., update your custom table
        $order_id = absint($order_id);
        $table_name = $wpdb->prefix . 'dreamsrent_booking';
          $updated = $wpdb->update(
        $table_name,
        [ 'bkstatus' => '' ],               // Data to update
        [ 'order_id' => $order_id ],              // WHERE condition
        [ '%s' ],                                 // Format of values
        [ '%d' ]                                  // Format of WHERE condition
    );

    //}
}



        // Custom hook to trigger reminder notification
        function trigger_order_reminder($order_id) {
            $order = wc_get_order($order_id);
            $user_id = $order->get_user_id();

            // Retrieve the product author's ID for the first product in the order
            $items = $order->get_items();
            $owner_id = null;

            if (!empty($items)) {
                foreach ($items as $item) {
                    $product_id = $item->get_product_id();
                    $owner_id = get_post_field('post_author', $product_id);
                    break; // Use the author of the first product only
                }
            }

            if ($user_id && $owner_id) {
                add_notification($user_id, $owner_id, $order_id, 'order_reminder', 'order is scheduled soon.');
            }
        }


        // Helper function to insert notifications into user_notifications table
        function add_notification($user_id, $owner_id, $order_id, $type, $message) {
            global $wpdb;
            $table_name = $wpdb->prefix . 'user_notifications';

            // Check if a notification already exists
            $existing_notification = $wpdb->get_var($wpdb->prepare(
                "SELECT id FROM $table_name WHERE user_id = %d AND owner_id = %d AND order_id = %d AND type = %s",
                $user_id, $owner_id, $order_id, $type
            ));

            if ($existing_notification) {
                return; // Notification already exists, so exit the function
            }
            

            $wpdb->insert($table_name, array(
                'user_id'   => $user_id,
                'owner_id'  => $owner_id,
                'order_id'  => $order_id,
                'type'      => $type,
                'message'   => $message,
                'is_read'   => 0,
                'created_at' => current_time('mysql')
            ));
        }

       





        add_action('wp_ajax_verify_otp', 'verify_otp');
        add_action('wp_ajax_nopriv_verify_otp', 'verify_otp');

        function verify_otp() {
            check_ajax_referer('send_otp_nonce', 'security');

            $email = sanitize_email($_POST['email']);
            $otp = sanitize_text_field($_POST['otp']);
            
            $stored_otp = get_transient('otp_' . md5($email));

            if ($stored_otp && $stored_otp == $otp) {
                delete_transient('otp_' . md5($email));
                wp_send_json_success();
            } else {
                wp_send_json_error(array('message' => 'Invalid or expired OTP.'));
            }

            wp_die();
        }



        add_action('woocommerce_thankyou', 'custom_new_order_notification', 10, 1);

        function custom_new_order_notification($order_id) {
            // Retrieve Redux options
            $is_enabled = dreamsrent_fl_framework_getoptions('new_order_email_enabled');
            $subject = dreamsrent_fl_framework_getoptions('new_order_email_subject');
            $email_content = dreamsrent_fl_framework_getoptions('new_order_email_content');

            $from_email = dreamsrent_fl_framework_getoptions('emails_from_email', get_bloginfo('admin_email'));
            $email_logo = dreamsrent_fl_framework_getoptions('email_logo');
            // $email_logo_url = $email_logo['url'];
            if (is_array($email_logo) && isset($email_logo['url'])) {
                $email_logo_url = $email_logo['url'];
            } else {
                // Handle the case where $email_logo is not valid (e.g., use a default logo)
                $email_logo_url = '';
            }
            
            // Check if the notification is enabled
            if (!$is_enabled) {
                return;
            }

            // Get the order object
            $order = wc_get_order($order_id);
            $customer_email = $order->get_billing_email(); // Customer's email address

            // Initialize variables for placeholders
            $product_details = ''; // Variable to hold all product details if multiple products are purchased

            if ( ! empty( $order->get_items() ) ) {
            // Build product details for each item in HTML table format with titles at the top
        $product_details .= '<table style="width: 100%; border-collapse: collapse; margin-bottom: 20px;">';
        $product_details .= '<tr style="background-color: #f2f2f2;">';
        $product_details .= '<th>Product Name</th>';
        $product_details .= '<th>Rental Type</th>';
        $product_details .= '<th >Pickup Location</th>';
        $product_details .= '<th >Dropoff Location</th>';
        $product_details .= '<th >Pickup Date</th>';
        $product_details .= '<th >Dropoff Date</th>';
        $product_details .= '<th >Deposit Amount</th>';
        $product_details .= '<th >Remaining Amount</th>';
        $product_details .= '<th >Total Amount</th>';

        $product_details .= '</tr>';
            }
            // Loop through each order item to get metadata and product details
            foreach ($order->get_items() as $item_id => $item) {
                $product_name = $item->get_name();
                $pickup_location = wc_get_order_item_meta($item_id, 'dsrent_pickup_loc', true);
                $dropoff_location = wc_get_order_item_meta($item_id, 'dsrent_pickoff_loc', true);
                $pickup_date = wc_get_order_item_meta($item_id, 'dsrent_pickup_date', true);
                $dropoff_date = wc_get_order_item_meta($item_id, 'dsrent_pickoff_date', true);
                $deposit_amount = floatval(wc_get_order_item_meta($item_id, 'dsrent_product_subtotal', true));
                $remaining_amount = floatval(wc_get_order_item_meta($item_id, 'dsrent_remain_balance', true));
                $combined_amount = $deposit_amount + $remaining_amount;
                $time_option = ucfirst($item->get_meta('time_option'));

                $product_details .= '<tr>';
                $product_details .= '<td >' . esc_html($product_name) . '</td>';
                $product_details .= '<td >' . esc_html($time_option) . '</td>';
                $product_details .= '<td >' . esc_html($pickup_location) . '</td>';
                $product_details .= '<td >' . esc_html($dropoff_location) . '</td>';
                $product_details .= '<td >' . esc_html($pickup_date) . '</td>';
                $product_details .= '<td >' . esc_html($dropoff_date) . '</td>';
                $product_details .= '<td >' . wc_price($deposit_amount) . '</td>';
                $product_details .= '<td >' . wc_price($remaining_amount) . '</td>';
                $product_details .= '<td >' . wc_price($combined_amount) . '</td>';
            
                $product_details .= '</tr>';

            }
            if ( ! empty( $order->get_items() ) ) {
            $product_details .= '</table>';
            }
            // Replace placeholders in the email content
            $replacements = array(
                '{customer_name}'    => esc_html($order->get_billing_first_name()),
                '{order_number}'     => esc_html($order->get_order_number()),
                '{order_date}'       => esc_html($order->get_date_created()->date('F j, Y')),
                '{product_details}'  => $product_details // Insert the product details into the content
            );
            $email_content = strtr($email_content, $replacements);

            // Email headers for HTML format
            $headers = [
                'Content-Type: text/html; charset=UTF-8',
                'From: ' . get_bloginfo('name') . ' <' . $from_email . '>'
            ];

            // Build the HTML message
            $message = '<!DOCTYPE html>
                        <html>
                        <head>
                            <meta charset="UTF-8">
                            <meta name="viewport" content="width=device-width, initial-scale=1.0">
                            <style>
                                body { font-family: Arial, sans-serif; color: #333; line-height: 1.6; }
                                .container { max-width: 100%; margin: 0 auto; padding: 20px; background-color: #f9f9f9; border: 1px solid #ddd; }
                                .header { text-align: center; margin-bottom: 30px; }
                                .content { background: #fff; padding: 20px; border-radius: 5px; }
                                .content ul{ padding-left: 0px; }
                                .footer { margin-top: 30px; text-align: center; color: #999; font-size: 12px; }
                                .content table th {padding: 8px; border: 1px solid #ddd;}
                                .content  table td{padding: 8px; border: 1px solid #ddd;}
                            </style>
                        </head>
                        <body>
                            <div class="container">
                                <div class="header">';
            if (!empty($email_logo_url)) {
                $message .= '<img src="' . esc_url($email_logo_url) . '" alt="Logo">';
            }
            $message .= '</div>
                                <div class="content">'
                                    . $email_content . 
                                '</div>
                                <div class="footer">
                                    &copy; ' . date("Y") . ' ' . get_bloginfo('name') . '. All rights reserved.
                                </div>
                            </div>
                        </body>
                        </html>';

            // Send the email to the customer
            dreamsrent_send_email($customer_email, $subject, $message, $headers);
        }


        add_action('woocommerce_order_status_completed', 'send_completed_order_notification', 10, 1);

        function send_completed_order_notification($order_id) { 

            
            // Retrieve Redux options
            $is_enabled = dreamsrent_fl_framework_getoptions('completed_order_email_enabled');
            $subject = dreamsrent_fl_framework_getoptions('completed_order_email_subject');
            $email_content = dreamsrent_fl_framework_getoptions('completed_order_email_content');

            $from_email = dreamsrent_fl_framework_getoptions('emails_from_email', get_bloginfo('admin_email'));
            $email_logo = dreamsrent_fl_framework_getoptions('email_logo');
            $email_logo_url = $email_logo['url'];

            // Check if the notification is enabled
            if (!$is_enabled) {
                return;
            }

            // Get the order object
            $order = wc_get_order($order_id);
            $customer_email = $order->get_billing_email(); // Customer's email address

            // Initialize variables for placeholders
            $product_details = ''; // Variable to hold all product details if multiple products are purchased

            if ( ! empty( $order->get_items() ) ) {
            // Build product details for each item in HTML table format with titles at the top
        $product_details .= '<table style="width: 100%; border-collapse: collapse; margin-bottom: 20px;">';
        $product_details .= '<tr style="background-color: #f2f2f2;">';
        $product_details .= '<th>Product Name</th>';
        $product_details .= '<th>Rental Type</th>';
        $product_details .= '<th >Pickup Location</th>';
        $product_details .= '<th >Dropoff Location</th>';
        $product_details .= '<th >Pickup Date</th>';
        $product_details .= '<th >Dropoff Date</th>';
        $product_details .= '<th >Deposit Amount</th>';
        $product_details .= '<th >Remaining Amount</th>';
        $product_details .= '<th >Total Amount</th>';

        $product_details .= '</tr>';
            }
            // Loop through each order item to get metadata and product details
            foreach ($order->get_items() as $item_id => $item) {
                $product_name = $item->get_name();
                $pickup_location = wc_get_order_item_meta($item_id, 'dsrent_pickup_loc', true);
                $dropoff_location = wc_get_order_item_meta($item_id, 'dsrent_pickoff_loc', true);
                $pickup_date = wc_get_order_item_meta($item_id, 'dsrent_pickup_date', true);
                $dropoff_date = wc_get_order_item_meta($item_id, 'dsrent_pickoff_date', true);
                $deposit_amount = floatval(wc_get_order_item_meta($item_id, 'dsrent_product_subtotal', true));
                $remaining_amount = floatval(wc_get_order_item_meta($item_id, 'dsrent_remain_balance', true));
                $combined_amount = $deposit_amount + $remaining_amount;
                $time_option = ucfirst($item->get_meta('time_option'));

                $product_details .= '<tr>';
                $product_details .= '<td >' . esc_html($product_name) . '</td>';
                $product_details .= '<td >' . esc_html($time_option) . '</td>';
                $product_details .= '<td >' . esc_html($pickup_location) . '</td>';
                $product_details .= '<td >' . esc_html($dropoff_location) . '</td>';
                $product_details .= '<td >' . esc_html($pickup_date) . '</td>';
                $product_details .= '<td >' . esc_html($dropoff_date) . '</td>';
                $product_details .= '<td >' . wc_price($deposit_amount) . '</td>';
                $product_details .= '<td >' . wc_price($remaining_amount) . '</td>';
                $product_details .= '<td >' . wc_price($combined_amount) . '</td>';
            
                $product_details .= '</tr>';

            }
            if ( ! empty( $order->get_items() ) ) {
            $product_details .= '</table>';
            }
            // Replace placeholders in the email content
            $replacements = array(
                '{customer_name}'    => esc_html($order->get_billing_first_name()),
                '{order_number}'     => esc_html($order->get_order_number()),
                '{order_date}'       => esc_html($order->get_date_created()->date('F j, Y')),
                '{product_details}'  => $product_details // Insert the product details into the content
            );
            $email_content = strtr($email_content, $replacements);

            // Email headers for HTML format
            $headers = [
                'Content-Type: text/html; charset=UTF-8',
                'From: ' . get_bloginfo('name') . ' <' . $from_email . '>'
            ];

            // Build the HTML message
            $message = '<!DOCTYPE html>
                        <html>
                        <head>
                            <meta charset="UTF-8">
                            <meta name="viewport" content="width=device-width, initial-scale=1.0">
                            <style>
                                body { font-family: Arial, sans-serif; color: #333; line-height: 1.6; }
                                .container { max-width: 100%; margin: 0 auto; padding: 20px; background-color: #f9f9f9; border: 1px solid #ddd; }
                                .header { text-align: center; margin-bottom: 30px; }
                                .content { background: #fff; padding: 20px; border-radius: 5px; }
                                .content ul{ padding-left: 0px; }
                                .footer { margin-top: 30px; text-align: center; color: #999; font-size: 12px; }
                                .content table th {padding: 8px; border: 1px solid #ddd;}
                                .content  table td{padding: 8px; border: 1px solid #ddd;}
                            </style>
                        </head>
                        <body>
                            <div class="container">
                                <div class="header">';
            if (!empty($email_logo_url)) {
                $message .= '<img src="' . esc_url($email_logo_url) . '" alt="Logo">';
            }
            $message .= '</div>
                                <div class="content">'
                                    . $email_content . 
                                '</div>
                                <div class="footer">
                                    &copy; ' . date("Y") . ' ' . get_bloginfo('name') . '. All rights reserved.
                                </div>
                            </div>
                        </body>
                        </html>';

            // Send the email to the customer
            dreamsrent_send_email($customer_email, $subject, $message, $headers);
        
        }

        add_action('woocommerce_order_status_processing', 'send_processing_order_notification', 10, 1);

        function send_processing_order_notification($order_id) { 


            

            
            // Retrieve Redux options
            $is_enabled = dreamsrent_fl_framework_getoptions('processing_order_email_enabled');
            $subject = dreamsrent_fl_framework_getoptions('processing_order_email_subject');
            $email_content = dreamsrent_fl_framework_getoptions('processing_order_email_content');

            $from_email = dreamsrent_fl_framework_getoptions('emails_from_email', get_bloginfo('admin_email'));
            $email_logo = dreamsrent_fl_framework_getoptions('email_logo');
            $email_logo_url = $email_logo['url'];

            // Check if the notification is enabled
            if (!$is_enabled) {
                return;
            }

            // Get the order object
            $order = wc_get_order($order_id);
            $customer_email = $order->get_billing_email(); // Customer's email address

            // Initialize variables for placeholders
            $product_details = ''; // Variable to hold all product details if multiple products are purchased

            if ( ! empty( $order->get_items() ) ) {
            // Build product details for each item in HTML table format with titles at the top
        $product_details .= '<table style="width: 100%; border-collapse: collapse; margin-bottom: 20px;">';
        $product_details .= '<tr style="background-color: #f2f2f2;">';
        $product_details .= '<th>Product Name</th>';
        $product_details .= '<th>Rental Type</th>';
        $product_details .= '<th >Pickup Location</th>';
        $product_details .= '<th >Dropoff Location</th>';
        $product_details .= '<th >Pickup Date</th>';
        $product_details .= '<th >Dropoff Date</th>';
        $product_details .= '<th >Deposit Amount</th>';
        $product_details .= '<th >Remaining Amount</th>';
        $product_details .= '<th >Total Amount</th>';

        $product_details .= '</tr>';
            }
            // Loop through each order item to get metadata and product details
            foreach ($order->get_items() as $item_id => $item) {
                $product_name = $item->get_name();
                $pickup_location = wc_get_order_item_meta($item_id, 'dsrent_pickup_loc', true);
                $dropoff_location = wc_get_order_item_meta($item_id, 'dsrent_pickoff_loc', true);
                $pickup_date = wc_get_order_item_meta($item_id, 'dsrent_pickup_date', true);
                $dropoff_date = wc_get_order_item_meta($item_id, 'dsrent_pickoff_date', true);
                $deposit_amount = floatval(wc_get_order_item_meta($item_id, 'dsrent_product_subtotal', true));
                $remaining_amount = floatval(wc_get_order_item_meta($item_id, 'dsrent_remain_balance', true));
                $combined_amount = $deposit_amount + $remaining_amount;
                $time_option = ucfirst($item->get_meta('time_option'));

                $product_details .= '<tr>';
                $product_details .= '<td >' . esc_html($product_name) . '</td>';
                $product_details .= '<td >' . esc_html($time_option) . '</td>';
                $product_details .= '<td >' . esc_html($pickup_location) . '</td>';
                $product_details .= '<td >' . esc_html($dropoff_location) . '</td>';
                $product_details .= '<td >' . esc_html($pickup_date) . '</td>';
                $product_details .= '<td >' . esc_html($dropoff_date) . '</td>';
                $product_details .= '<td >' . wc_price($deposit_amount) . '</td>';
                $product_details .= '<td >' . wc_price($remaining_amount) . '</td>';
                $product_details .= '<td >' . wc_price($combined_amount) . '</td>';
            
                $product_details .= '</tr>';

            }
            if ( ! empty( $order->get_items() ) ) {
            $product_details .= '</table>';
            }
            // Replace placeholders in the email content
            $replacements = array(
                '{customer_name}'    => esc_html($order->get_billing_first_name()),
                '{order_number}'     => esc_html($order->get_order_number()),
                '{order_date}'       => esc_html($order->get_date_created()->date('F j, Y')),
                '{product_details}'  => $product_details // Insert the product details into the content
            );
            $email_content = strtr($email_content, $replacements);

            // Email headers for HTML format
            $headers = [
                'Content-Type: text/html; charset=UTF-8',
                'From: ' . get_bloginfo('name') . ' <' . $from_email . '>'
            ];

            // Build the HTML message
            $message = '<!DOCTYPE html>
                        <html>
                        <head>
                            <meta charset="UTF-8">
                            <meta name="viewport" content="width=device-width, initial-scale=1.0">
                            <style>
                                body { font-family: Arial, sans-serif; color: #333; line-height: 1.6; }
                                .container { max-width: 100%; margin: 0 auto; padding: 20px; background-color: #f9f9f9; border: 1px solid #ddd; }
                                .header { text-align: center; margin-bottom: 30px; }
                                .content { background: #fff; padding: 20px; border-radius: 5px; }
                                .content ul{ padding-left: 0px; }
                                .footer { margin-top: 30px; text-align: center; color: #999; font-size: 12px; }
                                .content table th {padding: 8px; border: 1px solid #ddd;}
                                .content  table td{padding: 8px; border: 1px solid #ddd;}
                            </style>
                        </head>
                        <body>
                            <div class="container">
                                <div class="header">';
            if (!empty($email_logo_url)) {
                $message .= '<img src="' . esc_url($email_logo_url) . '" alt="Logo">';
            }
            $message .= '</div>
                                <div class="content">'
                                    . $email_content . 
                                '</div>
                                <div class="footer">
                                    &copy; ' . date("Y") . ' ' . get_bloginfo('name') . '. All rights reserved.
                                </div>
                            </div>
                        </body>
                        </html>';

            // Send the email to the customer
            dreamsrent_send_email($customer_email, $subject, $message, $headers);



        }



 add_action('woocommerce_add_to_cart', 'reset_session_location_after_add_to_cart');

function reset_session_location_after_add_to_cart($cart_item_key) {
    if (isset($_SESSION['location'])) {
        unset($_SESSION['location']);
        unset($_SESSION['location_drop']);
        unset($_SESSION['pickup_date']);
        unset($_SESSION['return_date']);
        unset($_SESSION['pickup_time']);
        unset($_SESSION['return_time']);
        
    }
}


add_action( 'init', 'replace_cart_and_checkout_page_content_with_shortcodes' );

function replace_cart_and_checkout_page_content_with_shortcodes() {
    // Replace content on the Cart page
    $cart_page = get_page_by_path( 'cart' );
    if ( $cart_page && has_block( 'woocommerce/cart', $cart_page->post_content ) ) {
        wp_update_post( [
            'ID'           => $cart_page->ID,
            'post_content' => '[woocommerce_cart]',
        ] );
    }

    // Replace content on the Checkout page
    $checkout_page = get_page_by_path( 'checkout' );
    if ( $checkout_page && has_block( 'woocommerce/checkout', $checkout_page->post_content ) ) {
        wp_update_post( [
            'ID'           => $checkout_page->ID,
            'post_content' => '[woocommerce_checkout]',
        ] );
    }
}


function my_theme_register_block_styles() {
    // Add custom styles for the Paragraph block
    register_block_style(
        'core/paragraph',
        array(
            'name'  => 'fancy-paragraph',
            'label' => __( 'Fancy Paragraph', 'dreamsrent' ),
            'inline_style' => '.wp-block-paragraph.is-style-fancy-paragraph { font-style: italic; color: #3498db; }',
        )
    );

    // Add custom styles for the Image block
    register_block_style(
        'core/image',
        array(
            'name'  => 'rounded-image',
            'label' => __( 'Rounded Image', 'dreamsrent' ),
            'inline_style' => '.wp-block-image.is-style-rounded-image img { border-radius: 50%; }',
        )
    );
}
add_action( 'init', 'my_theme_register_block_styles' );


function my_theme_register_block_patterns() {
    // Register a simple hero block pattern
    register_block_pattern(
        'my-theme/hero-section',
        array(
            'title'       => __( 'Hero Section', 'dreamsrent' ),
            'description' => __( 'A hero section with a heading, paragraph, and button.', 'dreamsrent' ),
            'content'     => '<!-- wp:group {"align":"full","style":{"spacing":{"padding":{"top":"50px","bottom":"50px"}}},"backgroundColor":"primary","textColor":"white"} -->
                <div class="wp-block-group alignfull has-white-color has-primary-background-color has-text-color has-background" style="padding-top:50px;padding-bottom:50px;">
                    <!-- wp:heading {"textAlign":"center"} -->
                    <h2 style="text-align:center">Welcome to My Website</h2>
                    <!-- /wp:heading -->

                    <!-- wp:paragraph {"align":"center"} -->
                    <p style="text-align:center">This is a hero section to grab attention and provide important information.</p>
                    <!-- /wp:paragraph -->

                    <!-- wp:buttons {"layout":{"type":"flex","justifyContent":"center"}} -->
                    <div class="wp-block-buttons">
                        <!-- wp:button {"backgroundColor":"secondary","textColor":"white"} -->
                        <div class="wp-block-button"><a class="wp-block-button__link has-white-color has-secondary-background-color has-text-color has-background">Learn More</a></div>
                        <!-- /wp:button -->
                    </div>
                    <!-- /wp:buttons -->
                </div>
                <!-- /wp:group -->',
            'categories'  => array( 'featured' ),
        )
    );
}
add_action( 'init', 'my_theme_register_block_patterns' );




/**
 * Theme setup for adding block editor support.
 */
function dreamsrent_theme_setup() {
    // Enable support for core block styles.
    add_theme_support( 'wp-block-styles' );

    // Optionally, enable support for other block editor features:
    // Add wide alignment for blocks.
    add_theme_support( 'align-wide' );

    // Add support for responsive embeds.
    add_theme_support( 'responsive-embeds' );

    // Add support for editor styles.
    add_theme_support( 'editor-styles' );

    // Enqueue a custom editor style.
    add_editor_style( 'editor-style.css' );
}
add_action( 'after_setup_theme', 'dreamsrent_theme_setup' );


/**
 * Add support for custom logo in the theme.
 */
function dreamsrent_custom_logo_setup() {
    $defaults = array(
        'height'      => 100, // Set the height of the logo.
        'width'       => 400, // Set the width of the logo.
        'flex-height' => true, // Allow flexible height.
        'flex-width'  => true, // Allow flexible width.
        'header-text' => array( 'site-title', 'site-description' ), // Elements to hide when logo is displayed.
        'unlink-homepage-logo' => true, // WordPress 5.5+: Remove the link to the homepage if the logo is set.
    );
    add_theme_support( 'custom-logo', $defaults );
}
add_action( 'after_setup_theme', 'dreamsrent_custom_logo_setup' );



add_action('admin_enqueue_scripts', 'dreams_enqueue_brand_media_uploader');
function dreams_enqueue_brand_media_uploader($hook) {
    // Load only on taxonomy edit/add pages
    if (isset($_GET['taxonomy']) && $_GET['taxonomy'] === 'brand') {
        wp_enqueue_media();
        wp_enqueue_script('dreams-brand-image-upload', get_template_directory_uri() . '/assets/js/brand-image-upload.js', ['jquery'], null, true);
    }
}




   
add_action('admin_post_nopriv_save_location_post', 'dreams_handle_location_submission');
add_action('admin_post_save_location_post', 'dreams_handle_location_submission');

function dreams_handle_location_submission() {
    if (!isset($_POST['save_location_post_nonce']) || !wp_verify_nonce($_POST['save_location_post_nonce'], 'save_location_post_action')) {
        wp_die('Invalid nonce.');
    }

    $title = sanitize_text_field($_POST['title']);
    $email = sanitize_email($_POST['email']);
    $phone = sanitize_text_field($_POST['phone']);
    $location = sanitize_text_field($_POST['location']);
    $country = sanitize_text_field($_POST['country']);
    $state = sanitize_text_field($_POST['state']);
    $city = sanitize_text_field($_POST['city']);
    $pincode = sanitize_text_field($_POST['pincode']);
    // Get the current logged-in user ID
    $author_id = get_current_user_id();

    // Handle the image upload
    if (isset($_FILES['featured_image']) && !empty($_FILES['featured_image']['name'])) {
        $uploaded_file = $_FILES['featured_image'];
        $upload_overrides = ['test_form' => false]; // Allow the upload even if the form is not submitted via a form
        $movefile = wp_handle_upload($uploaded_file, $upload_overrides);

        if ($movefile && !isset($movefile['error'])) {
            // Successfully uploaded, get the file URL and set it as the featured image
            $image_url = $movefile['url']; // URL of the uploaded image

            // Insert the image into the media library
            $attachment = array(
                'guid' => $image_url,
                'post_mime_type' => $movefile['type'],
                'post_title' => basename($image_url),
                'post_content' => '',
                'post_status' => 'inherit'
            );

            // Insert the attachment into the database
            $attachment_id = wp_insert_attachment($attachment, $movefile['file']);
            require_once(ABSPATH . 'wp-admin/includes/image.php');
            $attachment_data = wp_generate_attachment_metadata($attachment_id, $movefile['file']);
            wp_update_attachment_metadata($attachment_id, $attachment_data);

            // Save the attachment ID to term meta (or you could also use post meta depending on your use case)
            $image_id = $attachment_id;
        } else {
            wp_die('Image upload failed: ' . $movefile['error']);
        }
    }

    // // Create term
    // $result = wp_insert_term($title, 'location');
    // if (is_wp_error($result)) {
    //     wp_die($result->get_error_message());
    // }


    // Generate a unique slug
// $unique_slug = sanitize_title($title . '-' . $author_id . '-' . time());

// // Create term with the same name but different slug
// $result = wp_insert_term($title, 'location', [
//     'slug' => $unique_slug
// ]);

// if (is_wp_error($result)) {
//     wp_die($result->get_error_message());
// }



function dreams_generate_unique_term_slug($title, $taxonomy) {
    $slug = sanitize_title($title);
    $original_slug = $slug;
    $i = 1;

    while (term_exists($slug, $taxonomy)) {
        $slug = $original_slug . '-' . $i;
        $i++;
    }

    return $slug;
}


$slug = dreams_generate_unique_term_slug($title, 'location');

$result = wp_insert_term($title, 'location', [
    'slug' => $slug,
]);

    $term_id = $result['term_id'];

    // Save meta
    update_term_meta($term_id, 'location_email', $email);
    update_term_meta($term_id, 'location_phone', $phone);
    update_term_meta($term_id, 'location_address', $location);
    update_term_meta($term_id, 'location_country', $country);
    update_term_meta($term_id, 'location_state', $state);
    update_term_meta($term_id, 'location_city', $city);
    update_term_meta($term_id, 'location_pincode', $pincode);


      // Save image ID if uploaded
      if (isset($image_id)) {
        update_term_meta($term_id, 'location_image', $image_id); // Store image ID in term meta
    }

    if (isset($_POST['working_days'])) {
        $data = [];
        foreach ($_POST['working_days'] as $day => $times) {
            $data[$day] = [
                'enabled' => !empty($times['enabled']), // Ensure it’s a boolean
                'from'    => sanitize_text_field($times['from'] ?? ''), // Sanitize start time
                'to'      => sanitize_text_field($times['to'] ?? ''), // Sanitize end time
            ];
        }
    
        // Assuming you want to save this in term meta (e.g., category or custom taxonomy)
        update_term_meta($term_id, 'location_working_days', $data);
    }

       // Save author ID to term meta
       update_term_meta($term_id, 'author_id', $author_id);
    
    // You can redirect to a custom page or show a message
 
    $av_locations = dreamsrent_fl_framework_getoptions('av_locations');
    if (!empty($av_locations)) {
    $redirect_url = add_query_arg('success', 'added', get_permalink($av_locations));
    wp_redirect($redirect_url);
    }

    exit;
}
 

add_action('admin_post_nopriv_update_location_post', 'dreams_handle_location_update');
add_action('admin_post_update_location_post', 'dreams_handle_location_update');
function dreams_handle_location_update() {
    if (!isset($_POST['update_location_post_nonce']) || !wp_verify_nonce($_POST['update_location_post_nonce'], 'update_location_post_action')) {
        wp_die('Invalid nonce.');
    }

    // Sanitize input fields
    $title = sanitize_text_field($_POST['title']);
    $email = sanitize_email($_POST['email']);
    $phone = sanitize_text_field($_POST['phone']);
    $location = sanitize_text_field($_POST['location']);
    $country = sanitize_text_field($_POST['country']);
    $state = sanitize_text_field($_POST['state']);
    $city = sanitize_text_field($_POST['city']);
    $pincode = sanitize_text_field($_POST['pincode']);
    $post_id = intval($_POST['post_id']); // Get the post ID

    // Verify the post ID exists in the 'location' taxonomy
    $term = get_term($post_id, 'location');
    if (is_wp_error($term) || !$term) {
        wp_die('Invalid location.');
    }


    // Update the title of the location (term)
    $updated_term = wp_update_term($term->term_id, 'location', [
        'name' => $title,  // Set the new title here
    ]);
    // Handle the image upload (same as before)
    if (isset($_FILES['featured_image']) && !empty($_FILES['featured_image']['name'])) {
        $uploaded_file = $_FILES['featured_image'];
        $upload_overrides = ['test_form' => false]; // Allow the upload even if the form is not submitted via a form
        $movefile = wp_handle_upload($uploaded_file, $upload_overrides);

        if ($movefile && !isset($movefile['error'])) {
            // Successfully uploaded, get the file URL and set it as the featured image
            $image_url = $movefile['url']; // URL of the uploaded image

            // Insert the image into the media library
            $attachment = array(
                'guid' => $image_url,
                'post_mime_type' => $movefile['type'],
                'post_title' => basename($image_url),
                'post_content' => '',
                'post_status' => 'inherit'
            );

            // Insert the attachment into the database
            $attachment_id = wp_insert_attachment($attachment, $movefile['file']);
            require_once(ABSPATH . 'wp-admin/includes/image.php');
            $attachment_data = wp_generate_attachment_metadata($attachment_id, $movefile['file']);
            wp_update_attachment_metadata($attachment_id, $attachment_data);

            // Save the attachment ID to term meta (or you could also use post meta depending on your use case)
            update_term_meta($term->term_id, 'location_image', $attachment_id);
        } else {
            wp_die('Image upload failed: ' . $movefile['error']);
        }
    }

    // Update term meta
    update_term_meta($term->term_id, 'location_email', $email);
    update_term_meta($term->term_id, 'location_phone', $phone);
    update_term_meta($term->term_id, 'location_address', $location);
    update_term_meta($term->term_id, 'location_country', $country);
    update_term_meta($term->term_id, 'location_state', $state);
    update_term_meta($term->term_id, 'location_city', $city);
    update_term_meta($term->term_id, 'location_pincode', $pincode);

    // Update working days
    if (isset($_POST['working_days'])) {
        $data = [];
        foreach ($_POST['working_days'] as $day => $times) {
            $data[$day] = [
                'enabled' => !empty($times['enabled']), // Ensure it’s a boolean
                'from'    => sanitize_text_field($times['from'] ?? ''), // Sanitize start time
                'to'      => sanitize_text_field($times['to'] ?? ''), // Sanitize end time
            ];
        }

        // Save working days
        update_term_meta($term->term_id, 'location_working_days', $data);
    }

    // Redirect or show a success message after the update
 
    $av_locations = dreamsrent_fl_framework_getoptions('av_locations');
    if (!empty($av_locations)) {
    $redirect_url = add_query_arg('success', 'updated', get_permalink($av_locations));
    wp_redirect($redirect_url);
    }
    exit;
}
 


add_action('init', 'handle_delete_location_term');

function handle_delete_location_term() {
    if (
        isset($_GET['action']) && $_GET['action'] === 'delete_location_term' &&
        isset($_GET['term_id']) && is_numeric($_GET['term_id'])
    ) {
        $term_id = intval($_GET['term_id']);

        // Check the nonce
        if (!isset($_GET['_wpnonce']) || !wp_verify_nonce($_GET['_wpnonce'], 'delete_location_term_' . $term_id)) {
            wp_die(__('Invalid nonce. Term not deleted.', 'dreamsrent'));
        }

        // Optional: You can check if the current user is allowed to delete
        $current_user_id = get_current_user_id();
        $author_id = get_term_meta($term_id, 'author_id', true);
        if ($author_id != $current_user_id) {
            wp_die(__('You are not allowed to delete this term.', 'dreamsrent'));
        }

        // Delete the term
        $deleted = wp_delete_term($term_id, 'location');

        if (is_wp_error($deleted)) {
            wp_die(__('Failed to delete term.', 'dreamsrent'));
        }

        // Redirect back after deletion
         wp_redirect(add_query_arg(['success' => 'del_true'], remove_query_arg(['action', 'term_id', '_wpnonce'])));

        exit;
    }
}



function load_models_by_brand_callback() {
    check_ajax_referer('brand_model_nonce', 'security');

    $brand_id = intval($_POST['brand_id']);

    $models = get_terms([
        'taxonomy'   => 'model',
        'hide_empty' => false,
        'meta_query' => [
            [
                'key'     => 'model_brand',
                'value'   => $brand_id,
                'compare' => '='
            ]
        ]
    ]);

    if (!empty($models) && !is_wp_error($models)) {
        echo '<option value="">' . esc_html__('Select Model', 'dreamsrent') . '</option>';
        foreach ($models as $model) {
            echo '<option value="' . esc_attr($model->term_id) . '">' . esc_html($model->name) . '</option>';
        }
    } else {
        echo '<option value="">' . esc_html__('No models found', 'dreamsrent') . '</option>';
    }

    wp_die();
}
add_action('wp_ajax_load_models_by_brand', 'load_models_by_brand_callback');
add_action('wp_ajax_nopriv_load_models_by_brand', 'load_models_by_brand_callback');



add_action('admin_post_nopriv_save_rental_post', 'handle_save_rental_post');
add_action('admin_post_save_rental_post', 'handle_save_rental_post');

function handle_save_rental_post() {
    if (!isset($_POST['name'])) {
        wp_die('Invalid submission');
    }

    // Sanitize form inputs
    $name           = sanitize_text_field($_POST['name']);
    $permalink      = sanitize_title_with_dashes($name);
    $car_type       = sanitize_text_field($_POST['car_type']);
    $car_brand      = sanitize_text_field($_POST['car_brand']);
    $car_model      = sanitize_text_field($_POST['car_model']);
    $carcategory    = sanitize_text_field($_POST['carcategory']);
    $plate_number   = sanitize_text_field($_POST['plate_number']);
    $vin_number     = sanitize_text_field($_POST['vin_number']);
    $location       = sanitize_text_field($_POST['location']);
    $linked_locations = isset($_POST['linked_locations']) ? array_map('sanitize_text_field', $_POST['linked_locations']) : [];
    
    $car_fuel       = sanitize_text_field($_POST['car_fuel']);
    $odometer       = sanitize_text_field($_POST['odometer']);
    $car_color      = sanitize_text_field($_POST['car_color']);
    $car_transmission      = sanitize_text_field($_POST['car_transmission']);
    $car_doors      = sanitize_text_field($_POST['car_doors']);
    $year_of_car      = sanitize_text_field($_POST['year_of_car']);



    $mileage      = sanitize_text_field($_POST['mileage']);
    $passengers      = sanitize_text_field($_POST['passengers']);
    $air_bags      = sanitize_text_field($_POST['air_bags']);
    $description = sanitize_textarea_field($_POST['description']);

    $seo_title      = sanitize_text_field($_POST['seo_title']);
    $seo_keywords      = sanitize_text_field($_POST['seo_keywords']);
    $seo_description = sanitize_textarea_field($_POST['seo_description']);


    $car_features = isset($_POST['car_features']) ? array_map('sanitize_text_field', $_POST['car_features']) : [];

    $car_cylinder = sanitize_text_field($_POST['car_cylinder']);
    $car_steering = sanitize_text_field($_POST['car_steering']);
 

    $dayly      = sanitize_text_field($_POST['dayly']);
    $dayly_price      = sanitize_text_field($_POST['dayly_price']);
  
    $hourly      = sanitize_text_field($_POST['hourly']);
    $hourly_price      = sanitize_text_field($_POST['hourly_price']);

    $weekly      = sanitize_text_field($_POST['weekly']);
    $weekly_price      = sanitize_text_field($_POST['weekly_price']);
 
    $monthly      = sanitize_text_field($_POST['monthly']);
    $monthly_price      = sanitize_text_field($_POST['monthly_price']);
   
    $yearly      = sanitize_text_field($_POST['yearly']);
    $yearly_price      = sanitize_text_field($_POST['yearly_price']);
    $video_type      = sanitize_text_field($_POST['video_type']);
    $video_link      = sanitize_text_field($_POST['video_link']);


    $deposit_enable      = sanitize_text_field($_POST['deposit_enable']);
    $deposit_type      = sanitize_text_field($_POST['deposit_type']);
    $deposit_amount      = sanitize_text_field($_POST['deposit_amount']);
   // $full_payment_option      = sanitize_text_field($_POST['full_payment_option']);

    // Create post
    $post_id = wp_insert_post([
        'post_title'    => $name,
        'post_name'     => $permalink,
        'post_status'   => 'publish',
        'post_type'     => 'rental',
        'post_content' => $description, // <-- Add this line
    ]);

    if (is_wp_error($post_id)) {
        wp_die('Failed to create post.');
    }

 
$car_seats = isset($_POST['car_seats']) ? sanitize_text_field($_POST['car_seats']) : ''; // Get the selected seats term ID

// Check if a valid seat option is selected
if ($car_seats) {
    wp_set_post_terms($post_id, [$car_seats], 'seats'); // Assign selected seat to the rental post
}


 
$car_type = isset($_POST['car_type']) ? sanitize_text_field($_POST['car_type']) : ''; // Get the selected seats term ID

// Check if a valid seat option is selected
if ($car_type) {
    wp_set_post_terms($post_id, [$car_type], 'cartype'); // Assign selected seat to the rental post
}


    // Save taxonomies
   // wp_set_post_terms($post_id, [$car_type], 'cartype');
    wp_set_post_terms($post_id, [$car_brand], 'brand');
    wp_set_post_terms($post_id, [$car_model], 'model');
    wp_set_post_terms($post_id, [$carcategory], 'carcategory');
    wp_set_post_terms($post_id, [$location], 'location');
    wp_set_post_terms($post_id, $linked_locations, 'location', true); // append other linked locations

    wp_set_post_terms($post_id, $car_features, 'features');

    wp_set_post_terms($post_id, [$car_cylinder], 'cylinders');
    wp_set_post_terms($post_id, [$car_steering], 'carsteering');
 
    
    wp_set_post_terms($post_id, [$car_fuel], 'carfueltype');
    wp_set_post_terms($post_id, [$car_color], 'color');
    wp_set_post_terms($post_id, [$car_transmission], 'cartransmission');
    wp_set_post_terms($post_id, [$car_doors], 'doors');
    
    // Save meta fields
    update_post_meta( $post_id, 'main_locations', $location );
 
    if (is_array($linked_locations) && !empty($linked_locations)) {
        update_post_meta($post_id, 'linked_locations', $linked_locations);
    }
if (!empty($plate_number)) { 
    update_post_meta($post_id, 'plate_number', $plate_number);
}
 
if (!empty($vin_number)) { 
    update_post_meta($post_id, 'vin_number', $vin_number);
}
if (!empty($odometer)) { 
    update_post_meta($post_id, 'odometer', $odometer);
}
if (!empty($year_of_car)) { 
    update_post_meta($post_id, 'year_of_car', $year_of_car);
}
if (!empty($mileage)) { 
    update_post_meta($post_id, 'mileage', $mileage);
}
if (!empty($passengers)) { 
    update_post_meta($post_id, 'passengers', $passengers);
}
if (!empty($air_bags)) { 
    update_post_meta($post_id, 'air_bags', $air_bags);
}


update_post_meta($post_id, 'dreams_booking_meta_enable_deposit', $deposit_enable);
update_post_meta($post_id, 'dreams_booking_meta_type_deposit', $deposit_type);
update_post_meta($post_id, 'dreams_booking_meta_amount_deposit', $deposit_amount);
//update_post_meta($post_id, 'dreams_booking_meta_enable_full_payment', $full_payment_option);
    if( $dayly=='dayly' && !empty(trim($dayly_price)) ){  
        update_post_meta($post_id, 'dreams_booking_meta_rentaltype_day', 'day');
        update_post_meta($post_id, 'dreams_booking_meta_rdprice', $dayly_price);
    }

     if( $hourly=='hourly' && !empty(trim($hourly_price)) ){  
        update_post_meta($post_id, 'dreams_booking_meta_rentaltype_hour', 'hour');
        update_post_meta($post_id, 'dreams_booking_meta_rhprice', $hourly_price);
    }

 
    if( $weekly=='weekly' && !empty(trim($weekly_price)) ){  
        update_post_meta($post_id, 'dreams_booking_meta_rentaltype_week', 'week');
        update_post_meta($post_id, 'dreams_booking_meta_weekprice', $weekly_price);
    }

    if( $monthly=='monthly' && !empty(trim($monthly_price)) ){  
        update_post_meta($post_id, 'dreams_booking_meta_rentaltype_month', 'month');
        update_post_meta($post_id, 'dreams_booking_meta_monthprice', $monthly_price);
    }

    if( $yearly=='yearly' && !empty(trim($yearly_price)) ){  
        update_post_meta($post_id, 'dreams_booking_meta_rentaltype_year', 'year');
        update_post_meta($post_id, 'dreams_booking_meta_yearprice', $yearly_price);
    }

    if (!empty($video_type)) { 
        update_post_meta($post_id, 'video_type', $video_type);
    }
    if (!empty($video_link)) { 
        update_post_meta($post_id, 'video_link', $video_link);
    }

    if (!empty($seo_title)) { 
        update_post_meta($post_id, 'seo_title', $seo_title);
    }
    if (!empty($seo_keywords)) { 
        update_post_meta($post_id, 'seo_keywords', $seo_keywords);
    }
    if (!empty($seo_description)) { 
        update_post_meta($post_id, 'seo_description', $seo_description);
    }

  // Sanitize arrays
$tariff_names  = array_map('sanitize_text_field', $_POST['tariff_name'] ?? []);
$daily_prices  = array_map('sanitize_text_field', $_POST['daily_price'] ?? []);
$from_days     = array_map('intval', $_POST['from_days'] ?? []);
$to_days       = array_map('intval', $_POST['to_days'] ?? []);

$base_km       = array_map('sanitize_text_field', $_POST['base_km'] ?? []);
$unlimited       = array_map('sanitize_text_field', $_POST['unlimited'] ?? []);
$km_extra_price       = array_map('sanitize_text_field', $_POST['km_extra_price'] ?? []);
$tariffs = [];

// Build structured array with empty check
for ($i = 0; $i < count($tariff_names); $i++) {
    $name  = $tariff_names[$i] ?? '';
    $price = $daily_prices[$i] ?? '';

    if (!empty($name) && !empty($price)) {
        $tariffs[] = [
            'tariff_name' => $name,
            'daily_price' => $price,
            'from_days'   => $from_days[$i] ?? '',
            'to_days'     => $to_days[$i] ?? '',
            'base_km'     => $base_km[$i] ?? '',
            'unlimited'     => $unlimited[$i] ?? '',
            'km_extra_price'     => $km_extra_price[$i] ?? '',
        ];
    }
}

if (is_array($tariffs) && !empty($tariffs)) {
     update_post_meta($post_id, 'rental_tariffs', $tariffs);
}  



// Sanitize seasonal rate fields
$season_names   = array_map('sanitize_text_field', $_POST['season_name'] ?? []);
$start_dates    = array_map('sanitize_text_field', $_POST['start_date'] ?? []);
$end_dates      = array_map('sanitize_text_field', $_POST['end_date'] ?? []);
$daily_rates    = array_map('sanitize_text_field', $_POST['daily_rate'] ?? []);
$weekly_rates   = array_map('sanitize_text_field', $_POST['weekly_rate'] ?? []);
$monthly_rates  = array_map('sanitize_text_field', $_POST['monthly_rate'] ?? []);
$late_fees      = array_map('sanitize_text_field', $_POST['late_fee'] ?? []);

$seasonal_rates = [];

for ($i = 0; $i < count($season_names); $i++) {
    $name = $season_names[$i] ?? '';
    $start = $start_dates[$i] ?? '';
    $end = $end_dates[$i] ?? '';

    if (!empty($name) && !empty($start) && !empty($end)) {
        $seasonal_rates[] = [
            'season_name'  => $name,
            'start_date'   => $start,
            'end_date'     => $end,
            'daily_rate'   => $daily_rates[$i] ?? '',
            'weekly_rate'  => $weekly_rates[$i] ?? '',
            'monthly_rate' => $monthly_rates[$i] ?? '',
            'late_fee'     => $late_fees[$i] ?? '',
        ];
    }
}


// Save to post meta if data exists
if (!empty($seasonal_rates)) {
    update_post_meta($post_id, 'seasonal_rates', $seasonal_rates);
}


// Sanitize insurance fields
$insurance_names        = array_map('sanitize_text_field', $_POST['insurance_name'] ?? []);
$insurance_price_types  = array_map('sanitize_text_field', $_POST['ins_price_type'] ?? []);
$insurance_prices       = array_map('sanitize_text_field', $_POST['insurance_price'] ?? []);
$insurance_benefits     = array_map('sanitize_text_field', $_POST['insurance_benefits'] ?? []);
$insurance_benefit_groups = array_map('sanitize_text_field', $_POST['insurance_benefit_group'] ?? []);

$insurance_details = [];

for ($i = 0; $i < count($insurance_names); $i++) {
    $name = $insurance_names[$i] ?? '';
    $price_type = $insurance_price_types[$i] ?? '';
    $price = $insurance_prices[$i] ?? '';
    $benefits = $insurance_benefits[$i] ?? '';
    $benefit_group = $insurance_benefit_groups[$i] ?? '';

    if (!empty($name) && !empty($price) && !empty($benefits)) {
        $insurance_details[] = [
            'insurance_name'         => $name,
            'insurance_price_type'   => $price_type,
            'insurance_price'        => $price,
            'insurance_benefits'     => $benefits,
            'insurance_benefit_group'=> $benefit_group,
        ];
    }
}

// Save to post meta if data exists
if (!empty($insurance_details)) {
    update_post_meta($post_id, 'insurance_details', $insurance_details);
}



$selected_service_ids    = array_map('sanitize_text_field', $_POST['extra_service_id'] ?? []);
$extra_service_names     = array_map('sanitize_text_field', $_POST['extra_service_name'] ?? []);
$extra_service_types     = array_map('sanitize_text_field', $_POST['extra_service_type'] ?? []);
$extra_service_prices    = array_map('sanitize_text_field', $_POST['extra_service_price'] ?? []);
$extra_service_descriptions = array_map('sanitize_text_field', $_POST['extra_service_description'] ?? []);

$extra_service_details = [];

for ($i = 0; $i < count($selected_service_ids); $i++) {
    $id    = $selected_service_ids[$i] ?? '';
    $name  = $extra_service_names[$i] ?? '';
    $type  = $extra_service_types[$i] ?? '';
    $price = $extra_service_prices[$i] ?? '';
    $desc  = $extra_service_descriptions[$i] ?? '';

    if (!empty($id) && !empty($name)) {
        $extra_service_details[] = [
            'id'          => $id,
            'name'        => $name,
            'type'        => $type,
            'price'       => $price,
            'description' => $desc,
        ];
    }
}

if (!empty($extra_service_details)) {
    update_post_meta($post_id, 'extra_service_details', $extra_service_details);
}
    
 


  
// Sanitize the incoming POST data for damage-related information
$damage_location   = array_map('sanitize_text_field', $_POST['damage_location_data'] ?? []);
$damage_type     = array_map('sanitize_text_field', $_POST['damage_type_data'] ?? []);

$damage_description = array_map('sanitize_text_field', $_POST['damage_description_data'] ?? []);
$damage_date        = array_map('sanitize_text_field', $_POST['damage_date_data'] ?? []);

// Prepare the damage details array
$damage_details = [];

for ($i = 0; $i < count($damage_location); $i++) {
    $location    = $damage_location[$i] ?? '';
    $type        = $damage_type[$i] ?? '';
    $description = $damage_description[$i] ?? '';
    $date        = $damage_date[$i] ?? '';

    if (!empty($location) && !empty($type)) { // You can modify this check as needed
        $damage_details[] = [
            'location'    => $location,
            'type'        => $type,
            'description' => $description,
            'date'        => $date,
        ];
    }
}

// If there are damage details, update the post meta with them
if (!empty($damage_details)) {
    update_post_meta($post_id, 'damage_details', $damage_details);
}



 


// Sanitize the incoming POST data for FAQ-related information
$faq_title_data = array_map('sanitize_text_field', $_POST['faq_title_data'] ?? []);
$faq_description_data = array_map('sanitize_textarea_field', $_POST['faq_description_data'] ?? []);

// Prepare the FAQ details array
$faq_details = [];
if (!empty($faq_title_data) && !empty($faq_description_data)) {
    for ($i = 0; $i < count($faq_title_data); $i++) {
        // Get the FAQ title and description
        $faq_title = $faq_title_data[$i] ?? '';
        $faq_description = $faq_description_data[$i] ?? '';

        // Check if both FAQ title and description are not empty
        if (!empty($faq_title) && !empty($faq_description)) {
            // Add the FAQ details to the array
            $faq_details[] = [
                'faq_title' => $faq_title,
                'faq_description' => $faq_description,
            ];
        }
    }
}

// If there are FAQ details, update the post meta with them

 update_post_meta($post_id, 'faq_details', $faq_details);






$document_ids = [];
 
if (!empty($_FILES['car_documents']['name'][0])) {

  // Load required WordPress files for handling uploads
  require_once ABSPATH . 'wp-admin/includes/file.php';
  require_once ABSPATH . 'wp-admin/includes/media.php';
  require_once ABSPATH . 'wp-admin/includes/image.php';
    $files = $_FILES['car_documents'];

    foreach ($files['name'] as $index => $filename) {
        if (empty($filename)) continue;

        $file_array = [
            'name'     => sanitize_file_name($files['name'][$index]),
            'type'     => $files['type'][$index],
            'tmp_name' => $files['tmp_name'][$index],
            'error'    => $files['error'][$index],
            'size'     => $files['size'][$index],
        ];

        $_FILES['temp_file'] = $file_array;

        // Upload the file to WordPress media library
        $attachment_id = media_handle_upload('temp_file', $post_id);

        if (!is_wp_error($attachment_id)) {
            $document_ids[] = $attachment_id;
        } else {
            error_log('Upload error: ' . $attachment_id->get_error_message());
        }
    }

    if (!empty($document_ids)) {
        update_post_meta($post_id, '_car_document_attachment_ids', $document_ids);
    }
}



$policy_document_ids = [];
 
if (!empty($_FILES['policy_documents']['name'][0])) {

  // Load required WordPress files for handling uploads
  require_once ABSPATH . 'wp-admin/includes/file.php';
  require_once ABSPATH . 'wp-admin/includes/media.php';
  require_once ABSPATH . 'wp-admin/includes/image.php';
    $files = $_FILES['policy_documents'];

    foreach ($files['name'] as $index => $filename) {
        if (empty($filename)) continue;

        $file_array = [
            'name'     => sanitize_file_name($files['name'][$index]),
            'type'     => $files['type'][$index],
            'tmp_name' => $files['tmp_name'][$index],
            'error'    => $files['error'][$index],
            'size'     => $files['size'][$index],
        ];

        $_FILES['temp_file'] = $file_array;

        // Upload the file to WordPress media library
        $attachment_id = media_handle_upload('temp_file', $post_id);

        if (!is_wp_error($attachment_id)) {
            $policy_document_ids[] = $attachment_id;
        } else {
            error_log('Upload error: ' . $attachment_id->get_error_message());
        }
    }

    if (!empty($policy_document_ids)) {
        update_post_meta($post_id, '_policy_document_attachment_ids', $policy_document_ids);
    }
}



$gallery_document_ids = [];
 
if (!empty($_FILES['gallery_image']['name'][0])) {

  // Load required WordPress files for handling uploads
  require_once ABSPATH . 'wp-admin/includes/file.php';
  require_once ABSPATH . 'wp-admin/includes/media.php';
  require_once ABSPATH . 'wp-admin/includes/image.php';
    $files = $_FILES['gallery_image'];

    foreach ($files['name'] as $index => $filename) {
        if (empty($filename)) continue;

        $file_array = [
            'name'     => sanitize_file_name($files['name'][$index]),
            'type'     => $files['type'][$index],
            'tmp_name' => $files['tmp_name'][$index],
            'error'    => $files['error'][$index],
            'size'     => $files['size'][$index],
        ];

        $_FILES['temp_file'] = $file_array;

        // Upload the file to WordPress media library
        $attachment_id = media_handle_upload('temp_file', $post_id);

        if (!is_wp_error($attachment_id)) {
            $gallery_document_ids[] = $attachment_id;
        } else {
            error_log('Upload error: ' . $attachment_id->get_error_message());
        }
    }

    if (!empty($gallery_document_ids)) {
        update_post_meta($post_id, '_gallery_image_ids', $gallery_document_ids);
    }
}

    

     // Handle featured image
    if (!empty($_FILES['featured_image']['name'])) {
        require_once(ABSPATH . 'wp-admin/includes/file.php');
        require_once(ABSPATH . 'wp-admin/includes/media.php');
        require_once(ABSPATH . 'wp-admin/includes/image.php');

        $attachment_id = media_handle_upload('featured_image', $post_id);

        if (is_wp_error($attachment_id)) {
            wp_die('Image upload error.');
        } else {
            set_post_thumbnail($post_id, $attachment_id);
        }
    }


    
    dreams_save_booking_post_with_product_vendor($post_id);
    // Redirect or show success message
   
 

    $av_all_cars = dreamsrent_fl_framework_getoptions('av_all_cars');
    if (!empty($av_all_cars)) {
    $redirect_url = add_query_arg('success', '1', get_permalink($av_all_cars));
    wp_redirect($redirect_url);
    }

    exit;
}



add_action('init', function () {
    if (
        isset($_GET['action'], $_GET['post_id']) &&
        $_GET['action'] === 'delete_rental' &&
        is_user_logged_in()
    ) {
        $post_id = (int) $_GET['post_id'];

        // Verify nonce
        if (!wp_verify_nonce($_GET['_wpnonce'], 'delete_rental_' . $post_id)) {
            wp_die(__('Security check failed.', 'dreamsrent'));
        }

        // Verify user is author
        if (get_current_user_id() !== (int) get_post_field('post_author', $post_id)) {
            wp_die(__('You are not allowed to delete this post.', 'dreamsrent'));
        }

        // Delete post
        wp_delete_post($post_id, true);

        // Redirect after deletion
        //wp_redirect(remove_query_arg(['action', 'post_id', '_wpnonce']));
        wp_redirect(add_query_arg(['success' => 'del_true'], remove_query_arg(['action', 'post_id', '_wpnonce'])));
         exit;
    }
});

 


 



// Handle form submission
add_action('admin_post_nopriv_update_rental_post', 'handle_update_rental_post');
add_action('admin_post_update_rental_post', 'handle_update_rental_post');

function handle_update_rental_post() {
	if (!isset($_POST['name'])) {
		wp_die('Invalid submission');
	}

	$name = sanitize_text_field($_POST['name']);
	$permalink = sanitize_title_with_dashes($name);
	$car_type = intval($_POST['car_type']);
	$car_brand = intval($_POST['car_brand']);
	$car_model = intval($_POST['car_model']);
	$carcategory = intval($_POST['carcategory']);
	$plate_number = sanitize_text_field($_POST['plate_number']);
    $vin_number     = sanitize_text_field($_POST['vin_number']);

    $location       = sanitize_text_field($_POST['location']);
    $linked_locations = isset($_POST['linked_locations']) ? array_map('sanitize_text_field', $_POST['linked_locations']) : [];

    $car_fuel       = sanitize_text_field($_POST['car_fuel']);
    $odometer       = sanitize_text_field($_POST['odometer']);

    $car_color      = sanitize_text_field($_POST['car_color']);
    $car_transmission      = sanitize_text_field($_POST['car_transmission']);
    $car_doors      = sanitize_text_field($_POST['car_doors']);
    $year_of_car      = sanitize_text_field($_POST['year_of_car']);
    $mileage      = sanitize_text_field($_POST['mileage']);
    $passengers      = sanitize_text_field($_POST['passengers']);
    $air_bags      = sanitize_text_field($_POST['air_bags']);
    $description = sanitize_textarea_field($_POST['description']);


    $seo_title      = sanitize_text_field($_POST['seo_title']);
    $seo_keywords      = sanitize_text_field($_POST['seo_keywords']);
    $seo_description = sanitize_textarea_field($_POST['seo_description']);

    $car_cylinder = sanitize_text_field($_POST['car_cylinder']);
    $car_steering = sanitize_text_field($_POST['car_steering']);

    $car_features = isset($_POST['car_features']) ? array_map('sanitize_text_field', $_POST['car_features']) : [];

   
 

    $dayly      = sanitize_text_field($_POST['dayly']);
    $dayly_price      = sanitize_text_field($_POST['dayly_price']);
  
    $hourly      = sanitize_text_field($_POST['hourly']);
    $hourly_price      = sanitize_text_field($_POST['hourly_price']);

    $weekly      = sanitize_text_field($_POST['weekly']);
    $weekly_price      = sanitize_text_field($_POST['weekly_price']);
 
    $monthly      = sanitize_text_field($_POST['monthly']);
    $monthly_price      = sanitize_text_field($_POST['monthly_price']);
   
    $yearly      = sanitize_text_field($_POST['yearly']);
    $yearly_price      = sanitize_text_field($_POST['yearly_price']);
    $video_type      = sanitize_text_field($_POST['video_type']);
    $video_link      = sanitize_text_field($_POST['video_link']);
    
    $year_of_car      = sanitize_text_field($_POST['year_of_car']);

    $deposit_enable      = sanitize_text_field($_POST['deposit_enable']);
    $deposit_type      = sanitize_text_field($_POST['deposit_type']);
    $deposit_amount      = sanitize_text_field($_POST['deposit_amount']);
    //$full_payment_option      = sanitize_text_field($_POST['full_payment_option']);
    
    
	$post_id = isset($_POST['post_id']) ? intval($_POST['post_id']) : 0;

	$post_data = [
		'post_title'   => $name,
		'post_name'    => $permalink,
		'post_status'  => 'publish',
		'post_type'    => 'rental',
        'post_content' => $description, // <-- Add this line
	];

	if ($post_id > 0 && get_post($post_id)) {
		$post_data['ID'] = $post_id;
		wp_update_post($post_data);
	}  

	// Save featured image
	if (!empty($_FILES['featured_image']['name'])) {
		require_once ABSPATH . 'wp-admin/includes/file.php';
		require_once ABSPATH . 'wp-admin/includes/image.php';
		require_once ABSPATH . 'wp-admin/includes/media.php';

		$attachment_id = media_handle_upload('featured_image', $post_id);
		if (!is_wp_error($attachment_id)) {
			set_post_thumbnail($post_id, $attachment_id);
		}
	}
 
      
$car_type = isset($_POST['car_type']) ? sanitize_text_field($_POST['car_type']) : ''; // Get the selected seats term ID

// Check if a valid seat option is selected
if ($car_type) {
    wp_set_post_terms($post_id, [$car_type], 'cartype'); // Assign selected seat to the rental post
}

     wp_set_post_terms($post_id, [$car_brand], 'brand');
    wp_set_post_terms($post_id, [$car_model], 'model');
    wp_set_post_terms($post_id, [$carcategory], 'carcategory');
    wp_set_post_terms($post_id, [$location], 'location');
    wp_set_post_terms($post_id, $linked_locations, 'location', true); // append other linked locations

    wp_set_post_terms($post_id, $car_features, 'features');

    wp_set_post_terms($post_id, [$car_cylinder], 'cylinders');
    wp_set_post_terms($post_id, [$car_steering], 'carsteering');
 
  
    wp_set_post_terms($post_id, [$car_fuel], 'carfueltype');
    wp_set_post_terms($post_id, [$car_color], 'color');
    wp_set_post_terms($post_id, [$car_transmission], 'cartransmission');
    wp_set_post_terms($post_id, [$car_doors], 'doors');


    $car_seats = isset($_POST['car_seats']) ? sanitize_text_field($_POST['car_seats']) : ''; // Get the selected seats term ID

// Check if a valid seat option is selected
if ($car_seats) {
    wp_set_post_terms($post_id, [$car_seats], 'seats'); // Assign selected seat to the rental post
}

	// Save plate number as meta
	update_post_meta($post_id, 'plate_number', $plate_number);
    update_post_meta($post_id, 'vin_number', $vin_number);


    
    

      // Save meta fields
      update_post_meta( $post_id, 'main_locations', $location );

       // Save meta fields
    update_post_meta( $post_id, 'main_locations', $location );
 
    if (is_array($linked_locations) && !empty($linked_locations)) {
        update_post_meta($post_id, 'linked_locations', $linked_locations);
    }

 
      if (is_array($linked_locations) && !empty($linked_locations)) {
          update_post_meta($post_id, 'linked_locations', $linked_locations);
      }

      if (!empty($odometer)) { 
        update_post_meta($post_id, 'odometer', $odometer);
    }
if (!empty($year_of_car)) { 
    update_post_meta($post_id, 'year_of_car', $year_of_car);
}



if (!empty($mileage)) { 
    update_post_meta($post_id, 'mileage', $mileage);
}
if (!empty($passengers)) { 
    update_post_meta($post_id, 'passengers', $passengers);
}
if (!empty($air_bags)) { 
    update_post_meta($post_id, 'air_bags', $air_bags);
}

if( $dayly=='dayly' ){  
    update_post_meta($post_id, 'dreams_booking_meta_rentaltype_day', 'day');
} else {
    update_post_meta($post_id, 'dreams_booking_meta_rentaltype_day', '');
}
 update_post_meta($post_id, 'dreams_booking_meta_rdprice', $dayly_price);


if( $hourly=='hourly' ){  
    update_post_meta($post_id, 'dreams_booking_meta_rentaltype_hour', 'hour');
} else {
    update_post_meta($post_id, 'dreams_booking_meta_rentaltype_hour', '');
}
  update_post_meta($post_id, 'dreams_booking_meta_rhprice', $hourly_price);

 
 update_post_meta($post_id, 'dreams_booking_meta_enable_deposit', $deposit_enable);
 update_post_meta($post_id, 'dreams_booking_meta_type_deposit', $deposit_type);
 update_post_meta($post_id, 'dreams_booking_meta_amount_deposit', $deposit_amount);
 //update_post_meta($post_id, 'dreams_booking_meta_enable_full_payment', $full_payment_option);

 

        
        if( $weekly=='weekly' ){  
            update_post_meta($post_id, 'dreams_booking_meta_rentaltype_week', 'week');
        } else {
            update_post_meta($post_id, 'dreams_booking_meta_rentaltype_week', '');
        }

        update_post_meta($post_id, 'dreams_booking_meta_weekprice', $weekly_price);
  

        if( $monthly=='monthly' ){  
            update_post_meta($post_id, 'dreams_booking_meta_rentaltype_month', 'month');
        } else {
            update_post_meta($post_id, 'dreams_booking_meta_rentaltype_month', '');
        }

        update_post_meta($post_id, 'dreams_booking_meta_monthprice', $monthly_price);
    

        if( $yearly=='yearly' ){  
         update_post_meta($post_id, 'dreams_booking_meta_rentaltype_year', 'year');
        } else {
            update_post_meta($post_id, 'dreams_booking_meta_rentaltype_year', '');
         }
        update_post_meta($post_id, 'dreams_booking_meta_yearprice', $yearly_price);
   
    if (!empty($video_type)) { 
        update_post_meta($post_id, 'video_type', $video_type);
    }
    if (!empty($video_link)) { 
        update_post_meta($post_id, 'video_link', $video_link);
    }


    if (!empty($seo_title)) { 
        update_post_meta($post_id, 'seo_title', $seo_title);
    }
    if (!empty($seo_keywords)) { 
        update_post_meta($post_id, 'seo_keywords', $seo_keywords);
    }
    if (!empty($seo_description)) { 
        update_post_meta($post_id, 'seo_description', $seo_description);
    }


    
  // Sanitize arrays
$tariff_names  = array_map('sanitize_text_field', $_POST['tariff_name'] ?? []);
$daily_prices  = array_map('sanitize_text_field', $_POST['daily_price'] ?? []);
$from_days     = array_map('intval', $_POST['from_days'] ?? []);
$to_days       = array_map('intval', $_POST['to_days'] ?? []);

$base_km       = array_map('sanitize_text_field', $_POST['base_km'] ?? []);
$unlimited       = array_map('sanitize_text_field', $_POST['unlimited'] ?? []);
$km_extra_price       = array_map('sanitize_text_field', $_POST['km_extra_price'] ?? []);
$tariffs = [];

// Build structured array with empty check
if (!empty($tariff_names)) {
for ($i = 0; $i < count($tariff_names); $i++) {
    $name  = $tariff_names[$i] ?? '';
    $price = $daily_prices[$i] ?? '';

    if (!empty($name) && !empty($price)) {
        $tariffs[] = [
            'tariff_name' => $name,
            'daily_price' => $price,
            'from_days'   => $from_days[$i] ?? '',
            'to_days'     => $to_days[$i] ?? '',
            'base_km'     => $base_km[$i] ?? '',
            'unlimited'     => $unlimited[$i] ?? '',
            'km_extra_price'     => $km_extra_price[$i] ?? '',
        ];
    }
}

}
     update_post_meta($post_id, 'rental_tariffs', $tariffs);
 



// Sanitize seasonal rate fields
$season_names   = array_map('sanitize_text_field', $_POST['season_name'] ?? []);
$start_dates    = array_map('sanitize_text_field', $_POST['start_date'] ?? []);
$end_dates      = array_map('sanitize_text_field', $_POST['end_date'] ?? []);
$daily_rates    = array_map('sanitize_text_field', $_POST['daily_rate'] ?? []);
$weekly_rates   = array_map('sanitize_text_field', $_POST['weekly_rate'] ?? []);
$monthly_rates  = array_map('sanitize_text_field', $_POST['monthly_rate'] ?? []);
$late_fees      = array_map('sanitize_text_field', $_POST['late_fee'] ?? []);

$seasonal_rates = [];
if (!empty($season_names)) {

for ($i = 0; $i < count($season_names); $i++) {
    $name = $season_names[$i] ?? '';
    $start = $start_dates[$i] ?? '';
    $end = $end_dates[$i] ?? '';

    if (!empty($name) && !empty($start) && !empty($end)) {
        $seasonal_rates[] = [
            'season_name'  => $name,
            'start_date'   => $start,
            'end_date'     => $end,
            'daily_rate'   => $daily_rates[$i] ?? '',
            'weekly_rate'  => $weekly_rates[$i] ?? '',
            'monthly_rate' => $monthly_rates[$i] ?? '',
            'late_fee'     => $late_fees[$i] ?? '',
        ];
    }
}
}


// Save to post meta if data exists
     update_post_meta($post_id, 'seasonal_rates', $seasonal_rates);
 


// Sanitize insurance fields
$insurance_names        = array_map('sanitize_text_field', $_POST['insurance_name'] ?? []);
$insurance_price_types  = array_map('sanitize_text_field', $_POST['ins_price_type'] ?? []);
$insurance_prices       = array_map('sanitize_text_field', $_POST['insurance_price'] ?? []);
$insurance_benefits     = array_map('sanitize_text_field', $_POST['insurance_benefits'] ?? []);
$insurance_benefit_groups = array_map('sanitize_text_field', $_POST['insurance_benefit_group'] ?? []);

$insurance_details = [];
if (!empty($insurance_names)) {
for ($i = 0; $i < count($insurance_names); $i++) {
    $name = $insurance_names[$i] ?? '';
    $price_type = $insurance_price_types[$i] ?? '';
    $price = $insurance_prices[$i] ?? '';
    $benefits = $insurance_benefits[$i] ?? '';
    $benefit_group = $insurance_benefit_groups[$i] ?? '';

    if (!empty($name) && !empty($price) && !empty($benefits)) {
        $insurance_details[] = [
            'insurance_name'         => $name,
            'insurance_price_type'   => $price_type,
            'insurance_price'        => $price,
            'insurance_benefits'     => $benefits,
            'insurance_benefit_group'=> $benefit_group,
        ];
    }
}

} 
// Save to post meta if data exists
     update_post_meta($post_id, 'insurance_details', $insurance_details);
 


$selected_service_ids    = array_map('sanitize_text_field', $_POST['extra_service_id'] ?? []);
$extra_service_names     = array_map('sanitize_text_field', $_POST['extra_service_name'] ?? []);
$extra_service_types     = array_map('sanitize_text_field', $_POST['extra_service_type'] ?? []);
$extra_service_prices    = array_map('sanitize_text_field', $_POST['extra_service_price'] ?? []);
$extra_service_descriptions = array_map('sanitize_text_field', $_POST['extra_service_description'] ?? []);

$extra_service_details = [];
if (!empty($selected_service_ids)) {
for ($i = 0; $i < count($selected_service_ids); $i++) {
    $id    = $selected_service_ids[$i] ?? '';
    $name  = $extra_service_names[$i] ?? '';
    $type  = $extra_service_types[$i] ?? '';
    $price = $extra_service_prices[$i] ?? '';
    $desc  = $extra_service_descriptions[$i] ?? '';

    if (!empty($id) && !empty($name)) {
        $extra_service_details[] = [
            'id'          => $id,
            'name'        => $name,
            'type'        => $type,
            'price'       => $price,
            'description' => $desc,
        ];
    }
}
} 
 
    update_post_meta($post_id, 'extra_service_details', $extra_service_details);
 
    

  
// Sanitize the incoming POST data for damage-related information
$damage_location   = array_map('sanitize_text_field', $_POST['damage_location_data'] ?? []);
$damage_type     = array_map('sanitize_text_field', $_POST['damage_type_data'] ?? []);

$damage_description = array_map('sanitize_text_field', $_POST['damage_description_data'] ?? []);
$damage_date        = array_map('sanitize_text_field', $_POST['damage_date_data'] ?? []);

// Prepare the damage details array
$damage_details = [];

for ($i = 0; $i < count($damage_location); $i++) {
    $location    = $damage_location[$i] ?? '';
    $type        = $damage_type[$i] ?? '';
    $description = $damage_description[$i] ?? '';
    $date        = $damage_date[$i] ?? '';

    if (!empty($location) && !empty($type)) { // You can modify this check as needed
        $damage_details[] = [
            'location'    => $location,
            'type'        => $type,
            'description' => $description,
            'date'        => $date,
        ];
    }
}

// If there are damage details, update the post meta with them
if (!empty($damage_details)) {
    update_post_meta($post_id, 'damage_details', $damage_details);
}



// Sanitize the incoming POST data for FAQ-related information
$faq_title_data = array_map('sanitize_text_field', $_POST['faq_title_data'] ?? []);
$faq_description_data = array_map('sanitize_textarea_field', $_POST['faq_description_data'] ?? []);

// Prepare the FAQ details array
$faq_details = [];

for ($i = 0; $i < count($faq_title_data); $i++) {
    // Get the FAQ title and description
    $faq_title = $faq_title_data[$i] ?? '';
    $faq_description = $faq_description_data[$i] ?? '';

    // Check if both FAQ title and description are not empty
    if (!empty($faq_title) && !empty($faq_description)) {
        // Add the FAQ details to the array
        $faq_details[] = [
            'faq_title' => $faq_title,
            'faq_description' => $faq_description,
        ];
    }
}

// If there are FAQ details, update the post meta with them
if (!empty($faq_details)) {
    update_post_meta($post_id, 'faq_details', $faq_details);
}

 

// // 1. Load existing
// $existing_ids = get_post_meta($post_id, '_car_document_attachment_ids', true);
// if (!is_array($existing_ids)) $existing_ids = [];

// // 2. Remove requested IDs
// $removed_ids = !empty($_POST['removed_car_document_ids']) ? array_map('intval', explode(',', $_POST['removed_car_document_ids'])) : [];
// $remaining_ids = array_diff($existing_ids, $removed_ids);

// // 3. Handle uploads
// $uploaded_ids = [];

// if (!empty($_FILES['car_documents']['name'][0])) {
//     require_once ABSPATH . 'wp-admin/includes/file.php';
//     require_once ABSPATH . 'wp-admin/includes/media.php';
//     require_once ABSPATH . 'wp-admin/includes/image.php';

//     $files = $_FILES['car_documents'];

//     foreach ($files['name'] as $index => $filename) {
//         if (empty($filename)) continue;

//         $file_array = [
//             'name'     => sanitize_file_name($files['name'][$index]),
//             'type'     => $files['type'][$index],
//             'tmp_name' => $files['tmp_name'][$index],
//             'error'    => $files['error'][$index],
//             'size'     => $files['size'][$index],
//         ];

//         $_FILES['temp_file'] = $file_array;

//         $attachment_id = media_handle_upload('temp_file', $post_id);

//         if (!is_wp_error($attachment_id)) {
//             $uploaded_ids[] = $attachment_id;
//         } else {
//             error_log('Upload error: ' . $attachment_id->get_error_message());
//         }
//     }
// }

// // 4. Save merged IDs
// $final_ids = array_merge($remaining_ids, $uploaded_ids);
// update_post_meta($post_id, '_car_document_attachment_ids', $final_ids);
 
$car_document_attachment_ids = [];

// Get existing car documents
$existing_car_docs = get_post_meta($post_id, '_car_document_attachment_ids', true);
if (!is_array($existing_car_docs)) $existing_car_docs = [];

// Handle removed car documents
$removed_car_docs = !empty($_POST['removed_car_document_ids']) ? array_map('intval', explode(',', $_POST['removed_car_document_ids'])) : [];
$updated_car_docs = array_diff($existing_car_docs, $removed_car_docs);

// Handle new car document uploads
if (!empty($_FILES['car_documents']['name'][0])) {
    require_once ABSPATH . 'wp-admin/includes/file.php';
    require_once ABSPATH . 'wp-admin/includes/media.php';
    require_once ABSPATH . 'wp-admin/includes/image.php';

    $files = $_FILES['car_documents'];
    
    foreach ($files['name'] as $index => $filename) {
        if (empty($filename)) continue;

        $file_array = [
            'name'     => sanitize_file_name($files['name'][$index]),
            'type'     => $files['type'][$index],
            'tmp_name' => $files['tmp_name'][$index],
            'error'    => $files['error'][$index],
            'size'     => $files['size'][$index],
        ];

        $_FILES['temp_car_doc'] = $file_array;

        $attachment_id = media_handle_upload('temp_car_doc', $post_id);

        if (!is_wp_error($attachment_id)) {
            $car_document_attachment_ids[] = $attachment_id;
        } else {
            error_log('Car document upload error: ' . $attachment_id->get_error_message());
        }
    }
}

// Merge newly uploaded + preserved car documents
$final_car_docs = array_merge($updated_car_docs, $car_document_attachment_ids);
update_post_meta($post_id, '_car_document_attachment_ids', $final_car_docs);

// Handle policy documents
$policy_document_attachment_ids = [];

// Get existing policy documents
$existing_policy_docs = get_post_meta($post_id, '_policy_document_attachment_ids', true);
if (!is_array($existing_policy_docs)) $existing_policy_docs = [];

// Handle removed policy documents
$removed_policy_docs = !empty($_POST['removed_policy_document_ids']) ? array_map('intval', explode(',', $_POST['removed_policy_document_ids'])) : [];
$updated_policy_docs = array_diff($existing_policy_docs, $removed_policy_docs);

// Handle new policy document uploads
if (!empty($_FILES['policy_documents']['name'][0])) {
    require_once ABSPATH . 'wp-admin/includes/file.php';
    require_once ABSPATH . 'wp-admin/includes/media.php';
    require_once ABSPATH . 'wp-admin/includes/image.php';

    $files = $_FILES['policy_documents'];
    
    foreach ($files['name'] as $index => $filename) {
        if (empty($filename)) continue;

        $file_array = [
            'name'     => sanitize_file_name($files['name'][$index]),
            'type'     => $files['type'][$index],
            'tmp_name' => $files['tmp_name'][$index],
            'error'    => $files['error'][$index],
            'size'     => $files['size'][$index],
        ];

        $_FILES['temp_policy_doc'] = $file_array;

        $attachment_id = media_handle_upload('temp_policy_doc', $post_id);

        if (!is_wp_error($attachment_id)) {
            $policy_document_attachment_ids[] = $attachment_id;
        } else {
            error_log('Policy document upload error: ' . $attachment_id->get_error_message());
        }
    }
}

// Merge newly uploaded + preserved policy documents
$final_policy_docs = array_merge($updated_policy_docs, $policy_document_attachment_ids);
update_post_meta($post_id, '_policy_document_attachment_ids', $final_policy_docs);

$gallery_document_ids = [];

// Get existing gallery images
$existing_gallery_ids = get_post_meta($post_id, '_gallery_image_ids', true);
if (!is_array($existing_gallery_ids)) $existing_gallery_ids = [];

// Handle removed images
$removed_ids = !empty($_POST['removed_gallery_image_ids']) ? array_map('intval', explode(',', $_POST['removed_gallery_image_ids'])) : [];

// Filter out the removed ones
$updated_gallery_ids = array_diff($existing_gallery_ids, $removed_ids);

// Handle new uploads
if (!empty($_FILES['gallery_image']['name'][0])) {
    require_once ABSPATH . 'wp-admin/includes/file.php';
    require_once ABSPATH . 'wp-admin/includes/media.php';
    require_once ABSPATH . 'wp-admin/includes/image.php';

    $files = $_FILES['gallery_image'];

    foreach ($files['name'] as $index => $filename) {
        if (empty($filename)) continue;

        $file_array = [
            'name'     => sanitize_file_name($files['name'][$index]),
            'type'     => $files['type'][$index],
            'tmp_name' => $files['tmp_name'][$index],
            'error'    => $files['error'][$index],
            'size'     => $files['size'][$index],
        ];

        $_FILES['temp_file'] = $file_array;

        $attachment_id = media_handle_upload('temp_file', $post_id);

        if (!is_wp_error($attachment_id)) {
            $gallery_document_ids[] = $attachment_id;
        } else {
            error_log('Gallery Upload error: ' . $attachment_id->get_error_message());
        }
    }
}

// Merge newly uploaded + preserved images
$final_gallery_ids = array_merge($updated_gallery_ids, $gallery_document_ids);

// Update post meta
update_post_meta($post_id, '_gallery_image_ids', $final_gallery_ids);


	// Redirect to edit page or anywhere else
     $av_all_cars = dreamsrent_fl_framework_getoptions('av_all_cars');
    if (!empty($av_all_cars)) {
    $redirect_url = add_query_arg('success', '2', get_permalink($av_all_cars));
    wp_redirect($redirect_url);
    }

	exit;
}


/*custom order */

add_action('admin_post_nopriv_add_reservation', 'handle_add_reservation_form');
add_action('admin_post_add_reservation', 'handle_add_reservation_form');
function handle_add_reservation_form() {
    global $wpdb;
    $table_name = $wpdb->prefix . 'dreamsrent_reservations';
    $booking_table = $wpdb->prefix . 'dreamsrent_booking';

    // Sanitize input data
    $rental_type     = sanitize_text_field($_POST['rental_type']);
    $pickup_type     = sanitize_text_field($_POST['pickup_type']);
    $passengers     = sanitize_text_field($_POST['passengers']);
    
    $pickup_date     = sanitize_text_field($_POST['pickup_date']);
 
    $pickup_time_raw = sanitize_text_field($_POST['pickup_time']);
$pickup_time_obj = DateTime::createFromFormat('h:i A', $pickup_time_raw);

if ($pickup_time_obj) {
    $pickup_time = $pickup_time_obj->format('H:i'); // 24-hour format
} else {
    $pickup_time = ''; // fallback if parsing fails
}

    $end_date        = sanitize_text_field($_POST['end_date']);
 
    
    $end_time_raw = sanitize_text_field($_POST['end_time']);
$end_time = DateTime::createFromFormat('h:i A', $end_time_raw);

if ($end_time) {
    $end_time = $end_time->format('H:i'); // 24-hour format
} else {
    $end_time = ''; // fallback if parsing fails
}

    $pickup_location = sanitize_text_field($_POST['pickup_location']);
    $drop_location   = sanitize_text_field($_POST['drop_location']);

    $security_deposit   = sanitize_text_field($_POST['security_deposit']);
    $return_same_location   = sanitize_text_field($_POST['return_same_location']);
    
    
    $car_id          = sanitize_text_field($_POST['car_id']);
    $author_id = get_post_field('post_author', $car_id);
    $customer_id     = sanitize_text_field($_POST['customer_id']); // Assuming user is logged in
    $driver_id     = sanitize_text_field($_POST['driver_id']); 


  // Sanitize and serialize customer data
  $customer_data = $_POST['customer_data'] ?? [];
  $customer_data = array_map('sanitize_text_field', $customer_data);
  $customer_details = !empty($customer_data) ? serialize($customer_data) : '';

  // Sanitize and serialize driver data
  $driver_data = $_POST['driver_data'] ?? [];
  $driver_data = array_map('sanitize_text_field', $driver_data);
  $driver_details = !empty($driver_data) ? serialize($driver_data) : '';


   if (isset($_POST['extra_services']) && is_array($_POST['extra_services'])) {
    $extra_services = serialize($_POST['extra_services']); // Convert array to string
} else {
    $extra_services = '';
}

if (isset($_POST['car_insurance']) && is_array($_POST['car_insurance'])) {
    $car_insurance = serialize($_POST['car_insurance']); // Convert array to string
} else {
    $car_insurance = '';
}

$base_kilometers     = sanitize_text_field($_POST['base_kilometers']); 
$base_kilometers_unlimited     = sanitize_text_field($_POST['base_kilometers_unlimited']); 
$kilometers_extra_price     = sanitize_text_field($_POST['kilometers_extra_price']); 


  $summ_car_price     = sanitize_text_field($_POST['summ_car_price']); 
  $summ_eservice_price     = sanitize_text_field($_POST['summ_eservice_price']); 
  $summ_security_deposit_price     = sanitize_text_field($_POST['summ_security_deposit_price']); 
  $summ_driver_price     = sanitize_text_field($_POST['summ_driver_price']); 
  $summ_ins_price     = sanitize_text_field($_POST['summ_ins_price']); 
  $summ_total_price     = sanitize_text_field($_POST['summ_total_price']); 
  
    
    // Combine date and time
    $pickup_datetime_obj = DateTime::createFromFormat('d/m/Y H:i', "$pickup_date $pickup_time");
    $pickup_datetime = $pickup_datetime_obj ? $pickup_datetime_obj->format('Y-m-d H:i:s') : '';

    $end_datetime_obj = DateTime::createFromFormat('d/m/Y H:i', "$end_date $end_time");
    $end_datetime = $end_datetime_obj ? $end_datetime_obj->format('Y-m-d H:i:s') : '';

    // Insert data into custom table
    $wpdb->insert($table_name, [
        'tarrif'                     => $pickup_type,
        'rental_type'               => $rental_type,
        'passengers'                => $passengers, // Add from form if needed
        'start_date'                => $pickup_date,
        'start_time'                => $pickup_time,
        'end_date'                  => $end_date,
        'end_time'                  => $end_time,
        'pickup_location'          => $pickup_location,
        'drop_location'            => $drop_location,
        'security_deposit'         => $security_deposit, // Add from form if needed
        'return_same_location'     => $return_same_location, // Add from form if needed
        'car_id'                   => $car_id,
        'author_id'                   => $author_id,
        'customer_id'              => $customer_id,
        'customer_details'         => $customer_details,
        'driver_id'                => $driver_id, // Add from form if needed
        'driver_details'           => $driver_details, // Add from form if needed
        'extra_services'           => $extra_services, 
        'base_kilometers'          => $base_kilometers,
        'base_kilometers_unlimited'=> $base_kilometers_unlimited,
        'kilometers_extra_price'   => $kilometers_extra_price, 
        'insurance'                => $car_insurance, 
        'price_car'                => $summ_car_price,
        'es_price'                 => $summ_eservice_price,
        'sd_price'                 => $summ_security_deposit_price,
        'driver_price'             => $summ_driver_price,
        'ins_price'                => $summ_ins_price,
        'total_price'              => $summ_total_price,
        'bkstatus'                 => 'Confirmed'
    ]); 

 // Get the reservation ID
 $reserv_id = $wpdb->insert_id;

 $product_id = get_post_meta( $car_id, '_booking_product_id', true );
$product_name = get_the_title( $car_id );
$pickup_date_booking = date('Y-m-d H:i', strtotime($pickup_date . ' ' . $pickup_time));
$end_date_booking = date('Y-m-d H:i', strtotime($end_date . ' ' . $end_time));

    $wpdb->insert($booking_table, [
        'car_id'       => $car_id,
        'product_id'   => $product_id, // Ensure this is set
        'order_id'     => '',   // Ensure this is set
        'product_name' => $product_name, // Ensure this is set
        'pickup_date'  => $pickup_date_booking,
        'dropoff_date' => $end_date_booking,
        'time_option'  => $rental_type, // Ensure this is set
        'reserv_id'    => $reserv_id,
        'bkstatus'     => 'active'
    ]);

    // Redirect after submission
 
      $av_reservation = dreamsrent_fl_framework_getoptions('av_reservation');
    if (!empty($av_reservation)) {
    $redirect_url = add_query_arg('success', 'added', get_permalink($av_reservation));
    wp_redirect($redirect_url);
    }

    exit;
}

add_action('admin_post_nopriv_edit_reservation', 'handle_edit_reservation_form');
add_action('admin_post_edit_reservation', 'handle_edit_reservation_form');

function handle_edit_reservation_form() {
    global $wpdb;
    $table_name = $wpdb->prefix . 'dreamsrent_reservations';
    $booking_table = $wpdb->prefix . 'dreamsrent_booking'; // Replace with your actual table name


    $edit_id = isset($_POST['edit_id']) ? intval($_POST['edit_id']) : 0;


    $reservation_data = array();
 if ($edit_id > 0) {
    $reservation_data = $wpdb->get_row(
        $wpdb->prepare("SELECT * FROM $table_name WHERE id = %d", $edit_id),
        ARRAY_A
    );
}

    $rental_type       = sanitize_text_field($_POST['rental_type']);
    $pickup_type       = sanitize_text_field($_POST['pickup_type']);
    $passengers        = sanitize_text_field($_POST['passengers']);
    $pickup_date       = sanitize_text_field($_POST['pickup_date']);
    $pickup_time_raw   = sanitize_text_field($_POST['pickup_time']);
    $pickup_time_obj   = DateTime::createFromFormat('h:i A', $pickup_time_raw);
    $pickup_time       = $pickup_time_obj ? $pickup_time_obj->format('H:i') : '';

    $end_date          = sanitize_text_field($_POST['end_date']);
    $end_time_raw      = sanitize_text_field($_POST['end_time']);
    $end_time_obj      = DateTime::createFromFormat('h:i A', $end_time_raw);
    $end_time          = $end_time_obj ? $end_time_obj->format('H:i') : '';

    $pickup_location   = sanitize_text_field($_POST['pickup_location']);
    $drop_location     = sanitize_text_field($_POST['drop_location']);
    $security_deposit  = sanitize_text_field($_POST['security_deposit']);
    $return_same_location = isset($_POST['return_same_location']) ? 'yes' : 'no';

    if (isset($_POST['car_id']) ) {
         $car_id            =  sanitize_text_field($_POST['car_id']);
    } else {
         $car_id = sanitize_text_field($_POST['car_id_edit']);
    }
    $author_id = get_post_field('post_author', $car_id);

    $customer_id     = sanitize_text_field($_POST['customer_id']); // Assuming user is logged in
    $driver_id     = sanitize_text_field($_POST['driver_id']); 


  // Sanitize and serialize customer data
  $customer_data = $_POST['customer_data'] ?? [];
  $customer_data = array_map('sanitize_text_field', $customer_data);
  $customer_details = !empty($customer_data) ? serialize($customer_data) : '';

  // Sanitize and serialize driver data
  $driver_data = $_POST['driver_data'] ?? [];
  $driver_data = array_map('sanitize_text_field', $driver_data);
  $driver_details = !empty($driver_data) ? serialize($driver_data) : '';


   if (isset($_POST['extra_services']) && is_array($_POST['extra_services'])) {
    $extra_services = serialize($_POST['extra_services']); // Convert array to string
} else {
    $extra_services = '';
}

if (isset($_POST['car_insurance']) && is_array($_POST['car_insurance'])) {
    $car_insurance = serialize($_POST['car_insurance']); // Convert array to string
} else {
    $car_insurance = '';
}

$base_kilometers     = sanitize_text_field($_POST['base_kilometers']); 
$base_kilometers_unlimited     = sanitize_text_field($_POST['base_kilometers_unlimited']); 
$kilometers_extra_price     = sanitize_text_field($_POST['kilometers_extra_price']); 


  $summ_car_price     = sanitize_text_field($_POST['summ_car_price']); 
  $summ_eservice_price     = sanitize_text_field($_POST['summ_eservice_price']); 
  $summ_security_deposit_price     = sanitize_text_field($_POST['summ_security_deposit_price']); 
  $summ_driver_price     = sanitize_text_field($_POST['summ_driver_price']); 
  $summ_ins_price     = sanitize_text_field($_POST['summ_ins_price']); 
  $summ_total_price     = sanitize_text_field($_POST['summ_total_price']); 
  
    
    // Combine date and time
    $pickup_datetime_obj = DateTime::createFromFormat('d/m/Y H:i', "$pickup_date $pickup_time");
    $pickup_datetime = $pickup_datetime_obj ? $pickup_datetime_obj->format('Y-m-d H:i:s') : '';

    $end_datetime_obj = DateTime::createFromFormat('d/m/Y H:i', "$end_date $end_time");
    $end_datetime = $end_datetime_obj ? $end_datetime_obj->format('Y-m-d H:i:s') : '';

    $data = [
        'tarrif'                 => $pickup_type,
        'rental_type'           => $rental_type,
        'passengers'            => $passengers,
        'start_date'            => $pickup_date,
        'start_time'            => $pickup_time,
        'end_date'              => $end_date,
        'end_time'              => $end_time,
        'pickup_location'       => $pickup_location,
        'drop_location'         => $drop_location,
        'security_deposit'      => $security_deposit,
        'return_same_location'  => $return_same_location,
        'car_id'                => $car_id,
        'customer_id'              => $customer_id,
        'author_id'              => $author_id,
        'customer_details'         => $customer_details,
        'driver_id'                => $driver_id, // Add from form if needed
        'driver_details'           => $driver_details, // Add from form if needed
        'extra_services'           => $extra_services, 
        'base_kilometers'          => $base_kilometers,
        'base_kilometers_unlimited'=> $base_kilometers_unlimited,
        'kilometers_extra_price'   => $kilometers_extra_price, 
        'insurance'                => $car_insurance, 
        'price_car'                => $summ_car_price,
        'es_price'                 => $summ_eservice_price,
        'sd_price'                 => $summ_security_deposit_price,
        'driver_price'             => $summ_driver_price,
        'ins_price'                => $summ_ins_price,
        'total_price'              => $summ_total_price,
        'bkstatus'                 => 'Confirmed'
    ];

    if ($edit_id > 0) {
        // Update reservation
        $wpdb->update($table_name, $data, ['id' => $edit_id]);
    }  


 



$product_id = get_post_meta($car_id, '_booking_product_id', true);
$product_name = get_the_title($car_id);
$pickup_date_booking = date('Y-m-d H:i', strtotime($pickup_date . ' ' . $pickup_time));
$end_date_booking = date('Y-m-d H:i', strtotime($end_date . ' ' . $end_time));

// Check if a record with this reserv_id already exists
$existing_booking = $wpdb->get_var($wpdb->prepare(
    "SELECT COUNT(*) FROM $booking_table WHERE reserv_id = %s",
    $edit_id
));

$data_booking = [
    'car_id'       => $car_id,
    'product_id'   => $product_id,
    'order_id'     => '', // You can update this accordingly
    'product_name' => $product_name,
    'pickup_date'  => $pickup_date_booking,
    'dropoff_date' => $end_date_booking,
    'time_option'  => $rental_type,
    'bkstatus'     => 'active'
];

if ($existing_booking > 0) {
    // Update the existing record
    $wpdb->update(
        $booking_table,
        $data_booking,
        ['reserv_id' => $edit_id]
    );
}  



     // Redirect or show message
 
    $av_reservation = dreamsrent_fl_framework_getoptions('av_reservation');
    if (!empty($av_reservation)) {
    $redirect_url = add_query_arg('success', 'updated', get_permalink($av_reservation));
    wp_redirect($redirect_url);
    }

    exit;
}




add_action('init', 'handle_delete_reservation_post');

function handle_delete_reservation_post() {
    global $wpdb;
    if (
        isset($_GET['action'], $_GET['reserv_id']) &&
        $_GET['action'] === 'delete_reservation_post' &&
        is_numeric($_GET['reserv_id'])
    ) {
        $reserv_id = intval( $_GET['reserv_id'] );
        if ( ! isset( $_GET['_wpnonce'] ) || ! wp_verify_nonce( $_GET['_wpnonce'], 'delete_reservation_post_' . $reserv_id ) ) {
            wp_die( __( 'Invalid nonce. Record not deleted.', 'dreamsrent' ) );
        }
        
        $table_name = $wpdb->prefix . 'dreamsrent_reservations';
        $deleted = $wpdb->delete( $table_name, array( 'id' => $reserv_id ), array( '%d' ) );

        $table_name1 = $wpdb->prefix . 'dreamsrent_booking';
        $deleted = $wpdb->delete( $table_name1, array( 'reserv_id' => $reserv_id ), array( '%d' ) );
        
        if ( $deleted === false ) {
            wp_die( __( 'Failed to delete the reservation record.', 'dreamsrent' ) );
        }
        
        // Redirect back after deletion
          wp_redirect(add_query_arg(['success' => 'del_true'], remove_query_arg(['action', 'reserv_id', '_wpnonce'])));


        exit;
    }
}


/*test*/

add_action('wp_ajax_check_rental_availability', 'check_rental_availability_callback');
add_action('wp_ajax_nopriv_check_rental_availability', 'check_rental_availability_callback'); // if user is not logged in
 
 

function check_rental_availability_callback() {
    check_ajax_referer('brand_model_nonce', 'security');

    $pickup_date = sanitize_text_field($_POST['pickup_date']);
    $pickup_time = sanitize_text_field($_POST['pickup_time']);
    $end_date    = sanitize_text_field($_POST['end_date']);
    $end_time    = sanitize_text_field($_POST['end_time']);
    $pickup_location    = sanitize_text_field($_POST['pickup_location']);
    $return_location    = sanitize_text_field($_POST['return_location']);
    $user_id     = intval($_POST['c_userid']);
     
    $rental_type    = sanitize_text_field($_POST['rental_type']);
    // Convert dates to DateTime objects
    $pickup_datetime = DateTime::createFromFormat('d-m-Y', $pickup_date);
    $end_datetime    = DateTime::createFromFormat('d-m-Y', $end_date);

    if (!$pickup_datetime || !$end_datetime) {
        echo '<div class="text-danger">Invalid date/time format.</div>';
        wp_die();
    }

    global $wpdb;
    $booking_table = $wpdb->prefix . 'dreamsrent_booking';
    $meta_key = 'dreams_booking_meta_rentaltype_'.$rental_type;

    // Get all rentals for current user
    $args = array(
        'post_type'      => 'rental',
        'author'         => $user_id,
        'post_status'    => 'publish',
        'posts_per_page' => -1,
        'meta_query'     => array(
        array(
            'key'     => $meta_key,
            'value'   => $rental_type,
            'compare' => '='
        )
    ),
   'tax_query' => array(
    array(
        'taxonomy' => 'location',
        'field'    => 'term_id',
        'terms'    => array($pickup_location, $return_location),
        'operator' => 'IN',
    )
)
    
    );

    $rental_query = new WP_Query($args);

    $has_available = false;

    if ($rental_query->have_posts()) {
        while ($rental_query->have_posts()) {
            $rental_query->the_post();
            $post_id = get_the_ID();
            // // Check for booking conflict for this rental (car_id), comparing only DATE part
            // $conflict = $wpdb->get_var($wpdb->prepare("
            //     SELECT COUNT(*) FROM $booking_table
            //     WHERE car_id = %d AND (
            //         (DATE(%s) BETWEEN DATE(pickup_date) AND DATE(dropoff_date)) OR
            //         (DATE(%s) BETWEEN DATE(pickup_date) AND DATE(dropoff_date)) OR
            //         (DATE(pickup_date) BETWEEN DATE(%s) AND DATE(%s))
            //     )
            // ",
            //     $post_id,
            //     $pickup_datetime->format('Y-m-d'),
            //     $end_datetime->format('Y-m-d'),
            //     $pickup_datetime->format('Y-m-d'),
            //     $end_datetime->format('Y-m-d')
            // ));

            // if ($conflict == 0) {
            //     $has_available = true;
                ?>
                

                <div class="card">
             

 														<div class="card-body">
															<div class="row gy-3">
																<div class="col-lg-4">
																	<div class="d-flex align-items-center">
																		<div class="form-check form-check-md me-3">

 <?php 
											 $cartypes = get_the_terms($post_id, 'cartype');
											 if (!empty($cartypes) && !is_wp_error($cartypes)) {
 												 $cartype_names = wp_list_pluck($cartypes, 'name'); 
                                                 ?>

<?php 
										 if (has_post_thumbnail()) {
											$thumbnail_url = get_the_post_thumbnail_url(get_the_ID(), 'medium'); 
                                         } else {
                                            $thumbnail_url =  get_template_directory_uri() . '/assets/images/placeholder.jpg';
                                         } 
 ?>

<input class="form-check-input" type="radio" value="<?php echo get_the_ID();?>" name="car_id" 
 data-name="<?php echo get_the_title(); ?>"
 data-category="<?php echo esc_html(implode(', ', $cartype_names)); ?>"
 data-image="<?php echo esc_url($thumbnail_url); ?>"
 data-price="<?php echo get_post_meta($post_id, 'dreams_booking_meta_rdprice', true); ?>"
 data-ccymbol="<?php echo get_woocommerce_currency_symbol();?>"
data-type="<?php echo get_post_meta($post_id, 'dreams_booking_meta_rentaltype_day', true); ?>"
 required
 >
																		</div>
 <span class="avatar flex-shrink-0 me-2">
 
 <?php 
										 if (has_post_thumbnail()) {
											$thumbnail_url = get_the_post_thumbnail_url(get_the_ID(), 'medium');  
 											?>
 											<img src="<?php echo esc_url($thumbnail_url); ?>" alt="">
 <?php } else { ?>
  <img src="<?php echo esc_url( get_template_directory_uri() . '/assets/images/placeholder.jpg' ); ?>"  alt="">
  <?php } ?>

																		</span>
																		
																		<div>
 											<p class="mb-0"><?php echo esc_html(implode(', ', $cartype_names)); ?></p>
 											<?php } ?>

																			<h6 class="fs-14"><?php echo get_the_title(); ?> </h6>
																		</div>
																	</div>
																</div>
																<div class="col-lg-5">
																	<div class="row gy-3">
																		<div class="col-md-4">
																		<div>
    <p class="mb-1">Color</p>
    <div class="d-inline-flex flex-wrap align-items-center gap-2">
        <?php 
        $color_terms = get_the_terms( $post_id, 'color' );
        if ( ! empty( $color_terms ) && ! is_wp_error( $color_terms ) ) {
            foreach ( $color_terms as $term ) {
                $color_name = esc_html( $term->name );
                $color_code = get_term_meta( $term->term_id, 'color_code', true ); // replace with your actual meta key
                if ( ! $color_code ) {
                    $color_code = '#cccccc'; // default/fallback color
                }
                ?>
                <h6 class="fs-14 d-inline-flex align-items-center mb-0">
                    <i class="ti ti-square-filled me-1" style="color: <?php echo esc_attr( $color_code ); ?>;"></i> <?php echo esc_html( $color_name ); ?>
                </h6>
                <?php
            }
        }
        ?>
    </div>
</div>

																		</div>
																		<div class="col-md-4">
																			<div>
																				<p class="mb-1">Year</p>
																				<h6 class="fs-14"><?php echo get_post_meta($post_id, 'year_of_car', true); ?></h6>
																			</div>
																		</div>
																		<div class="col-md-4">
																			<?php if(get_post_meta($post_id, 'dreams_booking_meta_rdprice', true)){  ?>
																			<div>
																				<p class="mb-1">Price</p>
																				<h6 class="fs-14"><?php echo get_woocommerce_currency_symbol();?><?php echo get_post_meta($post_id, 'dreams_booking_meta_rdprice', true); ?><span class="text-gray-5">/<?php echo get_post_meta($post_id, 'dreams_booking_meta_rentaltype_day', true); ?><span class="text-gray-5"></span></h6>
																			</div>
																			<?php } ?>
																		</div>
																	</div>
																</div>
																 
															</div>
														</div>
													</div>

                <?php
           // }
        }
        wp_reset_postdata();
    } else {
         echo '<div class="text-danger mb-3">No rentals available in this time range.</div>';
    }

    

    wp_die();
}



add_action('wp_ajax_load_extra_services', 'handle_load_extra_services');
add_action('wp_ajax_nopriv_load_extra_services', 'handle_load_extra_services');

function handle_load_extra_services() {
    check_ajax_referer('brand_model_nonce', 'nonce');

    $car_id = intval($_POST['car_id']);
    $edit_id = intval($_POST['edit_id']);

    global $wpdb;
$table_name = $wpdb->prefix . 'dreamsrent_reservations';

$reservation_data = array();

if ($edit_id > 0) {
    $reservation_data = $wpdb->get_row(
        $wpdb->prepare("SELECT * FROM $table_name WHERE id = %d", $edit_id),
        ARRAY_A
    );
}
$get_extra_services = maybe_unserialize($reservation_data['extra_services']); // Ensure it's an array


    if (!$car_id) {
        wp_send_json_error('Invalid car ID');
    }

    $raw_data = get_post_meta($car_id, 'extra_service_details', true);
    $services = maybe_unserialize($raw_data);

    if (!empty($services) && is_array($services)) {
        ob_start(); // Start capturing HTML
        foreach ($services as $index => $service) {
            $name        = esc_html($service['name']);
            $description = esc_html($service['description']);
            $price       = esc_html($service['price']);
            $type        = esc_html($service['type']);
            $label       = ($type === 'per_day') ? 'Per Day' : 'One Time';
            $id          = 'custom-check-' . ($index + 1);
            $service_id  = esc_attr($service['id']);
            $is_checked = (is_array($get_extra_services) && in_array($service_id, $get_extra_services)) ? 'checked' : '';

            ?>
            <div class="col-md-6">
                <div class="custom-checkbox">
                    <div class="form-check form-check-md">
                    <input class="form-check-input" type="checkbox" id="<?php echo esc_attr($id);?>" name="extra_services[]" value="<?php echo esc_attr($service_id);?>" data-eservice-price="<?php echo esc_attr($price);?>" data-eservice-currency="<?php echo get_woocommerce_currency_symbol(); ?>" data-eservice-type="<?php echo esc_html($label);?>" <?php echo esc_attr($is_checked);?>
                    >
                    </div>
                    <div class="d-flex align-items-center justify-content-between">
                        <label class="form-check-label ms-2 ps-4" for="<?php echo esc_attr($id);?>">
                            <span class="fw-semibold text-gray-9 d-block mb-1"><?php echo esc_html($name);?></span>
                            <span class="d-block"><?php echo esc_html($description);?></span>
                        </label>
                        <div class="text-end">
                            <p class="mb-1"><?php echo esc_html($label);?></p>
                            <h6><?php echo get_woocommerce_currency_symbol(); ?> <?php echo esc_html($price);?></h6>
                        </div>
                    </div>
                </div>
            </div>
            <?php
        }
        $html = ob_get_clean(); // Get and clean the buffer
        wp_send_json_success(['html' => $html]);
    } else {
        wp_send_json_error('No extra services found.');
    }
}


add_action('wp_ajax_load_add_insurance', 'handle_load_add_insurance');
add_action('wp_ajax_nopriv_load_add_insurance', 'handle_load_add_insurance');

function handle_load_add_insurance() {
    check_ajax_referer('brand_model_nonce', 'nonce');

    $car_id = intval($_POST['car_id']);
    $edit_id = intval($_POST['edit_id']);
    
    global $wpdb;
    $table_name = $wpdb->prefix . 'dreamsrent_reservations';
    
    $reservation_data = array();
    
    if ($edit_id > 0) {
        $reservation_data = $wpdb->get_row(
            $wpdb->prepare("SELECT * FROM $table_name WHERE id = %d", $edit_id),
            ARRAY_A
        );
    }
    $get_insurance = maybe_unserialize($reservation_data['insurance']); // Ensure it's an array

    if (!$car_id) {
        wp_send_json_error('Invalid car ID');
    }

    $raw_data = get_post_meta($car_id, 'insurance_details', true);
    $insurance = maybe_unserialize($raw_data);

    if (!empty($insurance) && is_array($insurance)) {
        ob_start();
$count=1;
        foreach ($insurance as $index => $service) {
            $name        = esc_html($service['insurance_name']);
            $description = esc_html($service['insurance_benefits']);
            $price       = esc_html($service['insurance_price']);
            $type        = esc_html($service['insurance_price_type']);
            $label       = ($type === 'daily') ? 'Per Day' : 'One Time';
            $id          = 'custom-check-' . ($index + 1);
            $ins_id  = esc_attr($service['id']);
            $is_checked = (is_array($get_insurance) && in_array($ins_id, $get_insurance)) ? 'checked' : '';
            ?>

            <div class="col-md-6 mb-3">
                <div class="custom-checkbox active">
                    <div class="form-check form-check-md">
                        <input class="form-check-input" type="checkbox" 
                               id="<?php echo esc_attr($id);?>" 
                               name="car_insurance[]" 
                               value="<?php echo esc_attr($ins_id);?>"
                               data-insurance-name="<?php echo esc_attr($name); ?>"
                               data-insurance-price="<?php echo esc_attr($price); ?>"
                               data-insurance-type="<?php echo esc_attr($label); ?>" <?php echo esc_attr($is_checked);?>>
                    </div>
                    <div class="d-flex align-items-center justify-content-between">
                        <label class="form-check-label ms-2 ps-4" for="<?php echo esc_attr($id);?>">
                            <span class="fw-semibold text-gray-9 d-block mb-1"><?php echo esc_html($name);?></span>
                            <span class="d-block text-info"><?php esc_html_e('Benefits', 'dreamsrent');?>
                                <i class="ti ti-info-circle-filled text-gray-5 ms-1" 
                                   data-bs-toggle="tooltip" 
                                   data-bs-placement="top" 
                                   title="<?php echo esc_attr($description);?>"> </i>
                            </span>
                        </label>
                        <div class="text-end">
                            <p class="mb-1"> <?php echo esc_html($label);?></p>
                            <h6><?php echo get_woocommerce_currency_symbol(); ?><?php echo esc_html($price);?><</h6>
                        </div>
                    </div>
                </div>
            </div>

            <?php
            $count++;
        }

        $html = ob_get_clean();
        wp_send_json_success(['html' => $html]);
    } else {
        wp_send_json_error('No extra services found.');
    }
}




/* Customers */

add_action('admin_post_save_customer_post', 'handle_save_customer_post');
add_action('admin_post_nopriv_save_customer_post', 'handle_save_customer_post'); // if non-logged-in users are allowed

function handle_save_customer_post() {
    // Security check (optional but recommended)
    // check_admin_referer('save_customer_post_nonce');

    if (!empty($_POST['name'])) {
        $post_id = wp_insert_post([
            'post_type'   => 'customers',
            'post_status' => 'publish',
            'post_title'  => sanitize_text_field($_POST['name']),
        ]);

        if (!is_wp_error($post_id)) {
            // Save custom fields (meta)
            update_post_meta($post_id, 'dob', sanitize_text_field($_POST['dob']));
            update_post_meta($post_id, 'gender', sanitize_text_field($_POST['gender']));
            update_post_meta($post_id, 'language', sanitize_text_field($_POST['language']));
            update_post_meta($post_id, 'phone', sanitize_text_field($_POST['phone']));
            update_post_meta($post_id, 'email', sanitize_email($_POST['email']));
            update_post_meta($post_id, 'address', sanitize_text_field($_POST['address']));
            update_post_meta($post_id, 'card_number', sanitize_text_field($_POST['card_number']));
            update_post_meta($post_id, 'date_of_issue', sanitize_text_field($_POST['date_of_issue']));
            update_post_meta($post_id, 'valid_date', sanitize_text_field($_POST['valid_date']));

            // Upload image
            if (!empty($_FILES['customer_image']['name'])) {
                require_once(ABSPATH . 'wp-admin/includes/file.php');
                require_once(ABSPATH . 'wp-admin/includes/image.php');

                $upload = media_handle_upload('customer_image', 0);
                if (!is_wp_error($upload)) {
                    update_post_meta($post_id, 'customer_image', $upload);
                }
            }

            // Handle document upload
            if (!empty($_FILES['customer_documents']['name'][0])) {
                $doc_ids = [];
                foreach ($_FILES['customer_documents']['name'] as $key => $value) {
                    if ($_FILES['customer_documents']['name'][$key]) {
                        $file = [
                            'name'     => $_FILES['customer_documents']['name'][$key],
                            'type'     => $_FILES['customer_documents']['type'][$key],
                            'tmp_name' => $_FILES['customer_documents']['tmp_name'][$key],
                            'error'    => $_FILES['customer_documents']['error'][$key],
                            'size'     => $_FILES['customer_documents']['size'][$key]
                        ];

                        $_FILES['single_file'] = $file;

                        $upload_id = media_handle_upload('single_file', $post_id);
                        if (!is_wp_error($upload_id)) {
                            $doc_ids[] = $upload_id;
                        }
                    }
                }

                if (!empty($doc_ids)) {
                    update_post_meta($post_id, 'documents', $doc_ids);
                }
            }
        }
    }

    // Redirect after save
 
     $av_customers = dreamsrent_fl_framework_getoptions('av_customers');
    if (!empty($av_customers)) {
    $redirect_url = add_query_arg('success', 'added', get_permalink($av_customers));
    wp_redirect($redirect_url);
    }

    exit;
}
add_action('admin_post_update_customer_post', 'handle_update_customer_post');
add_action('admin_post_nopriv_update_customer_post', 'handle_update_customer_post'); // In case it's submitted from frontend for non-logged-in users

function handle_update_customer_post() {
    // Verify the user has permission
     

    if (!isset($_POST['post_id'])) {
        wp_die('Post ID is missing.');
    }

    $post_id = intval($_POST['post_id']);

    // Sanitize fields
    $name           = sanitize_text_field($_POST['name']);
    $dob            = sanitize_text_field($_POST['dob']);
    $gender         = sanitize_text_field($_POST['gender']);
    $language       = sanitize_text_field($_POST['language']);
    $phone          = sanitize_text_field($_POST['phone']);
    $email          = sanitize_email($_POST['email']);
    $address        = sanitize_text_field($_POST['address']);
    $card_number    = sanitize_text_field($_POST['card_number']);
    $date_of_issue  = sanitize_text_field($_POST['date_of_issue']);
    $valid_date     = sanitize_text_field($_POST['valid_date']);

    // Update post title and optionally content
    wp_update_post([
        'ID'         => $post_id,
        'post_title' => $name,
    ]);

    // Update post meta
    update_post_meta($post_id, 'dob', $dob);
    update_post_meta($post_id, 'gender', $gender);
    update_post_meta($post_id, 'language', $language);
    update_post_meta($post_id, 'phone', $phone);
    update_post_meta($post_id, 'email', $email);
    update_post_meta($post_id, 'address', $address);
    update_post_meta($post_id, 'card_number', $card_number);
    update_post_meta($post_id, 'date_of_issue', $date_of_issue);
    update_post_meta($post_id, 'valid_date', $valid_date);

    // ✅ Upload image if exists
   // Upload image
   if (!empty($_FILES['customer_image']['name'])) {
    require_once(ABSPATH . 'wp-admin/includes/file.php');
    require_once(ABSPATH . 'wp-admin/includes/image.php');

    $upload = media_handle_upload('customer_image', 0);
    if (!is_wp_error($upload)) {
        update_post_meta($post_id, 'customer_image', $upload);
    }
}

    // ✅ Handle multiple documents upload
    if (!empty($_FILES['customer_documents']['name'][0])) {
        $docs = [];
        $files = $_FILES['customer_documents'];

        foreach ($files['name'] as $i => $name) {
            if ($files['error'][$i] === 0) {
                $file = [
                    'name'     => $files['name'][$i],
                    'type'     => $files['type'][$i],
                    'tmp_name' => $files['tmp_name'][$i],
                    'error'    => $files['error'][$i],
                    'size'     => $files['size'][$i],
                ];

                $_FILES['temp_doc'] = $file;

                $attachment_id = media_handle_upload('temp_doc', $post_id);
                if (!is_wp_error($attachment_id)) {
                    $docs[] = $attachment_id;
                }
            }
        }

        if (!empty($docs)) {
            update_post_meta($post_id, 'customer_documents', $docs);
        }
    }

    // Redirect back to referring page or any page
   
    $av_customers = dreamsrent_fl_framework_getoptions('av_customers');
    if (!empty($av_customers)) {
    $redirect_url = add_query_arg('success', 'updated', get_permalink($av_customers));
    wp_redirect($redirect_url);
    }

    exit;
}



add_action('init', 'handle_delete_customer_post');

function handle_delete_customer_post() {
    if (
        isset($_GET['action'], $_GET['post_id']) &&
        $_GET['action'] === 'delete_customer_post' &&
        is_numeric($_GET['post_id'])
    ) {
        $post_id = intval($_GET['post_id']);

        // Verify nonce
        if (!isset($_GET['_wpnonce']) || !wp_verify_nonce($_GET['_wpnonce'], 'delete_customer_post_' . $post_id)) {
            wp_die(__('Invalid nonce. Post not deleted.', 'dreamsrent'));
        }

        // Optional: check if current user is post author
        $current_user_id = get_current_user_id();
        $post = get_post($post_id);
        if (!$post || $post->post_type !== 'customers') {
            wp_die(__('Invalid post.', 'dreamsrent'));
        }

        if ((int) $post->post_author !== $current_user_id && !current_user_can('delete_post', $post_id)) {
            wp_die(__('You are not allowed to delete this customer post.', 'dreamsrent'));
        }

        // Delete the post
        $deleted = wp_delete_post($post_id, true); // true = force delete (skip trash)

        if (!$deleted) {
            wp_die(__('Failed to delete the customer post.', 'dreamsrent'));
        }

 
        wp_redirect(add_query_arg(['success' => 'del_true'], remove_query_arg(['action', 'post_id', '_wpnonce'])));


        exit;
    }
}



/*Drivers */

add_action('admin_post_save_driver_post', 'handle_save_driver_post');
add_action('admin_post_nopriv_save_driver_post', 'handle_save_driver_post'); // optional for non-logged-in users

function handle_save_driver_post() {
    if (!empty($_POST['name'])) {
        $post_id = wp_insert_post([
            'post_type'   => 'drivers',
            'post_status' => 'publish',
            'post_title'  => sanitize_text_field($_POST['name']),
        ]);

        if (!is_wp_error($post_id)) {
            // Save driver meta
             update_post_meta($post_id, 'driver_price', sanitize_text_field($_POST['driver_price']));
            update_post_meta($post_id, 'gender', sanitize_text_field($_POST['gender']));
            update_post_meta($post_id, 'phone', sanitize_text_field($_POST['phone']));
            update_post_meta($post_id, 'email', sanitize_email($_POST['email']));
            update_post_meta($post_id, 'address', sanitize_text_field($_POST['address']));
            update_post_meta($post_id, 'card_number', sanitize_text_field($_POST['card_number']));
            update_post_meta($post_id, 'date_of_issue', sanitize_text_field($_POST['date_of_issue']));
            update_post_meta($post_id, 'valid_date', sanitize_text_field($_POST['valid_date']));
            update_post_meta($post_id, 'status', '1');

            // Handle image upload
            if (!empty($_FILES['driver_image']['name'])) {
                require_once(ABSPATH . 'wp-admin/includes/file.php');
                require_once(ABSPATH . 'wp-admin/includes/image.php');

                $upload_id = media_handle_upload('driver_image', $post_id);
                if (!is_wp_error($upload_id)) {
                    update_post_meta($post_id, 'driver_image', $upload_id);
                }
            }

            // Handle multiple document upload
            if (!empty($_FILES['driver_documents']['name'][0])) {
                $doc_ids = [];

                foreach ($_FILES['driver_documents']['name'] as $key => $value) {
                    if (!empty($value)) {
                        $file = [
                            'name'     => $_FILES['driver_documents']['name'][$key],
                            'type'     => $_FILES['driver_documents']['type'][$key],
                            'tmp_name' => $_FILES['driver_documents']['tmp_name'][$key],
                            'error'    => $_FILES['driver_documents']['error'][$key],
                            'size'     => $_FILES['driver_documents']['size'][$key]
                        ];

                        $_FILES['single_driver_file'] = $file;

                        $upload_id = media_handle_upload('single_driver_file', $post_id);
                        if (!is_wp_error($upload_id)) {
                            $doc_ids[] = $upload_id;
                        }
                    }
                }

                if (!empty($doc_ids)) {
                    update_post_meta($post_id, 'driver_documents', $doc_ids);
                }
            }
        }
    }

    // Redirect after save
 
     $av_drivers = dreamsrent_fl_framework_getoptions('av_drivers');
    if (!empty($av_drivers)) {
    $redirect_url = add_query_arg('success', 'added', get_permalink($av_drivers));
    wp_redirect($redirect_url);
    }

    exit;
}



add_action('admin_post_update_driver_post', 'handle_update_driver_post');
add_action('admin_post_nopriv_update_driver_post', 'handle_update_driver_post'); // Optional: if front-end submission

function handle_update_driver_post() {
    if (!isset($_POST['post_id'])) {
        wp_die('Post ID is missing.');
    }

    $post_id = intval($_POST['post_id']);

    // Sanitize input fields
    $name           = sanitize_text_field($_POST['name']);
    $gender         = sanitize_text_field($_POST['gender']);
    $phone          = sanitize_text_field($_POST['phone']);
    $email          = sanitize_email($_POST['email']);
    $address        = sanitize_text_field($_POST['address']);
    $driver_price        = sanitize_text_field($_POST['driver_price']);
    $card_number    = sanitize_text_field($_POST['card_number']);
    $date_of_issue  = sanitize_text_field($_POST['date_of_issue']);
    $valid_date     = sanitize_text_field($_POST['valid_date']);
    $status = isset($_POST['status']) ? 1 : 0;
 
    // Update post title
    wp_update_post([
        'ID'         => $post_id,
        'post_title' => $name,
    ]);

    // Update post meta
    update_post_meta($post_id, 'gender', $gender);
    update_post_meta($post_id, 'phone', $phone);
    update_post_meta($post_id, 'email', $email);
    update_post_meta($post_id, 'address', $address);
    update_post_meta($post_id, 'driver_price', $driver_price);
    update_post_meta($post_id, 'card_number', $card_number);
    update_post_meta($post_id, 'date_of_issue', $date_of_issue);
    update_post_meta($post_id, 'valid_date', $valid_date);
    update_post_meta($post_id, 'status', sanitize_text_field($status));

    // ✅ Upload driver image
    if (!empty($_FILES['driver_image']['name'])) {
        require_once(ABSPATH . 'wp-admin/includes/file.php');
        require_once(ABSPATH . 'wp-admin/includes/image.php');

        $upload = media_handle_upload('driver_image', $post_id);
        if (!is_wp_error($upload)) {
            update_post_meta($post_id, 'driver_image', $upload);
        }
    }



    if (!empty($_FILES['driver_documents']['name'][0])) {
        $doc_ids = [];

        foreach ($_FILES['driver_documents']['name'] as $key => $value) {
            if (!empty($value)) {
                $file = [
                    'name'     => $_FILES['driver_documents']['name'][$key],
                    'type'     => $_FILES['driver_documents']['type'][$key],
                    'tmp_name' => $_FILES['driver_documents']['tmp_name'][$key],
                    'error'    => $_FILES['driver_documents']['error'][$key],
                    'size'     => $_FILES['driver_documents']['size'][$key]
                ];

                $_FILES['single_driver_file'] = $file;

                $upload_id = media_handle_upload('single_driver_file', $post_id);
                if (!is_wp_error($upload_id)) {
                    $doc_ids[] = $upload_id;
                }
            }
        }

        if (!empty($doc_ids)) {
            update_post_meta($post_id, 'driver_documents', $doc_ids);
        }
    }
 
     $av_drivers = dreamsrent_fl_framework_getoptions('av_drivers');
    if (!empty($av_drivers)) {
    $redirect_url = add_query_arg('success', 'updated', get_permalink($av_drivers));
    wp_redirect($redirect_url);
    }

    exit;
}



add_action('init', 'handle_delete_driver_post');

function handle_delete_driver_post() {
    if (
        isset($_GET['action'], $_GET['post_id']) &&
        $_GET['action'] === 'delete_driver_post' &&
        is_numeric($_GET['post_id'])
    ) {
        $post_id = intval($_GET['post_id']);

        // Verify nonce
        if (!isset($_GET['_wpnonce']) || !wp_verify_nonce($_GET['_wpnonce'], 'delete_driver_post_' . $post_id)) {
            wp_die(__('Invalid nonce. Post not deleted.', 'dreamsrent'));
        }

        // Optional: check if current user is post author
        $current_user_id = get_current_user_id();
        $post = get_post($post_id);
        if (!$post || $post->post_type !== 'drivers') {
            wp_die(__('Invalid post.', 'dreamsrent'));
        }

        if ((int) $post->post_author !== $current_user_id && !current_user_can('delete_post', $post_id)) {
            wp_die(__('You are not allowed to delete this driver post.', 'dreamsrent'));
        }

        // Delete the post
        $deleted = wp_delete_post($post_id, true); // true = force delete (skip trash)

        if (!$deleted) {
            wp_die(__('Failed to delete the driver post.', 'dreamsrent'));
        }

        // Redirect after delete
         wp_redirect(add_query_arg(['success' => 'del_true'], remove_query_arg(['action', 'post_id', '_wpnonce'])));

        exit;
    }
}



add_action('admin_post_save_maintenance_post', 'handle_save_maintenance_post');
add_action('admin_post_nopriv_save_maintenance_post', 'handle_save_maintenance_post');

function handle_save_maintenance_post() {
    global $wpdb;

    if (
        isset($_POST['car_id'], $_POST['odometer'], $_POST['start_date'], $_POST['end_date'], $_POST['status'])
    ) {
        // Sanitize all inputs
        $car_id     = intval($_POST['car_id']);
        $odometer   = sanitize_text_field($_POST['odometer']);
        $start_date = sanitize_text_field($_POST['start_date']);
        $end_date   = sanitize_text_field($_POST['end_date']);
        $status     = sanitize_text_field($_POST['status']);
        $details    = isset($_POST['details']) ? sanitize_textarea_field($_POST['details']) : '';

        $table_name = $wpdb->prefix . 'dreamsrent_maintenance';

        $inserted = $wpdb->insert($table_name, [
            'car_id'     => $car_id,
            'odometer'   => $odometer,
            'start_date' => $start_date,
            'end_date'   => $end_date,
            'details'    => $details,
            'status'     => $status,
        ]);

        if ($inserted !== false) {
 
    $av_maintenance = dreamsrent_fl_framework_getoptions('av_maintenance');
    if (!empty($av_maintenance)) {
    $redirect_url = add_query_arg('success', 'added', get_permalink($av_maintenance));
    wp_redirect($redirect_url);
    }

            exit;
        }  
    }

    // Fallback redirect
 
     $av_maintenance = dreamsrent_fl_framework_getoptions('av_maintenance');
    if (!empty($av_maintenance)) {
    $redirect_url = add_query_arg('error', '1', get_permalink($av_maintenance));
    wp_redirect($redirect_url);
    }

    exit;
}


add_action('admin_post_update_maintenance_post', 'handle_update_maintenance_post');
add_action('admin_post_nopriv_update_maintenance_post', 'handle_update_maintenance_post');

function handle_update_maintenance_post() {
    global $wpdb;

    if (
        isset($_POST['post_id'], $_POST['car_id'], $_POST['odometer'], $_POST['start_date'], $_POST['end_date'], $_POST['status'])
    ) {
        // Sanitize all inputs
        $post_id    = intval($_POST['post_id']);
        $car_id     = intval($_POST['car_id']);
        $odometer   = sanitize_text_field($_POST['odometer']);
        $start_date = sanitize_text_field($_POST['start_date']);
        $end_date   = sanitize_text_field($_POST['end_date']);
        $status     = sanitize_text_field($_POST['status']);
        $details    = isset($_POST['details']) ? sanitize_textarea_field($_POST['details']) : '';

        $table_name = $wpdb->prefix . 'dreamsrent_maintenance';

        $updated = $wpdb->update(
            $table_name,
            [
                'car_id'     => $car_id,
                'odometer'   => $odometer,
                'start_date' => $start_date,
                'end_date'   => $end_date,
                'details'    => $details,
                'status'     => $status,
            ],
            [ 'id' => $post_id ], // WHERE clause
            null,
            [ '%d' ] // WHERE clause format
        );

        if ($updated !== false) {
 
             $av_maintenance = dreamsrent_fl_framework_getoptions('av_maintenance');
    if (!empty($av_maintenance)) {
    $redirect_url = add_query_arg('success', 'updated', get_permalink($av_maintenance));
    wp_redirect($redirect_url);
    }

            exit;
        }
    }

    // Fallback redirect
 
     $av_maintenance = dreamsrent_fl_framework_getoptions('av_maintenance');
    if (!empty($av_maintenance)) {
    $redirect_url = add_query_arg('error', '1', get_permalink($av_maintenance));
    wp_redirect($redirect_url);
    }

    exit;
}



add_action('init', 'handle_delete_maintenance_post');

function handle_delete_maintenance_post() {
    global $wpdb;
    if (
        isset($_GET['action'], $_GET['record_id']) &&
        $_GET['action'] === 'delete_maintenance_post' &&
        is_numeric($_GET['record_id'])
    ) {
        $record_id = intval( $_GET['record_id'] );
        if ( ! isset( $_GET['_wpnonce'] ) || ! wp_verify_nonce( $_GET['_wpnonce'], 'delete_maintenance_post_' . $record_id ) ) {
            wp_die( __( 'Invalid nonce. Record not deleted.', 'dreamsrent' ) );
        }
        
        $table_name = $wpdb->prefix . 'dreamsrent_maintenance';
        $deleted = $wpdb->delete( $table_name, array( 'id' => $record_id ), array( '%d' ) );
        
        if ( $deleted === false ) {
            wp_die( __( 'Failed to delete the maintenance record.', 'dreamsrent' ) );
        }
        
        // Redirect back after deletion
         wp_redirect(add_query_arg(['success' => 'del_true'], remove_query_arg(['action', 'record_id', '_wpnonce'])));

        exit;
    }
}

// Custom Style enque
    
function dreamsrent_enqueue_styles() {
    wp_enqueue_style('dreamsrent-style', get_stylesheet_uri());
}
add_action('wp_enqueue_scripts', 'dreamsrent_enqueue_styles');


// version 1.2.0
// Add this to handle the availability check with pricing
add_action('wp_ajax_check_availability_with_pricing', 'handle_availability_check_with_pricing');
add_action('wp_ajax_nopriv_check_availability_with_pricing', 'handle_availability_check_with_pricing');

function handle_availability_check_with_pricing() {
    // Verify nonce
    if (!wp_verify_nonce($_POST['_ajax_nonce'], 'check_availability_nonce')) {
        wp_send_json_error(array('message' => 'Nonce verification failed'));
        return;
    }
    
    // Get all posted data
    $post_id = intval($_POST['post_id']);
    $booking_product_id = intval($_POST['booking_product_id']);
    $time_option = sanitize_text_field($_POST['time_option_default']);
    $start_date = sanitize_text_field($_POST['start_date']);
    $end_date = sanitize_text_field($_POST['end_date']);
    $start_time = sanitize_text_field($_POST['start_time']);
    $end_time = sanitize_text_field($_POST['end_time']);
    $pickup_loc = sanitize_text_field($_POST['pickup_loc']);
    $dropoff_loc = sanitize_text_field($_POST['dropoff_loc']);
    $insurance = sanitize_text_field($_POST['insurance']);
    $insurance_type = sanitize_text_field($_POST['insurance_type']);
    $extra_services = isset($_POST['extra_services']) ? $_POST['extra_services'] : array();
    $deposit_type = sanitize_text_field($_POST['deposit_type']);
    
    // First check availability (reuse your existing availability check logic)
    // $is_available = check_car_availability($post_id, $start_date, $end_date, $start_time, $end_time);
    $is_available = check_car_availability(
            $booking_product_id,
            $time_option,
            $start_date,
            $end_date,
            $start_time,
            $end_time
        );

    
    if ($is_available) {
        // Calculate pricing using the same logic as in your cart calculations
        $pricing = calculate_booking_pricing(
            $post_id,
            $time_option,
            $start_date,
            $end_date,
            $start_time,
            $end_time,
            $pickup_loc,
            $dropoff_loc,
            $insurance,
            $insurance_type,
            $extra_services,
            $deposit_type
        );
        WC()->session->set('booking_pricing_data', array(
        'post_id' => $post_id,
        'pricing' => $pricing,
        'time_option' => $time_option,
        'booking_data' => array(
            'time_option' => $time_option,
            'start_date' => $start_date,
            'end_date' => $end_date,
            'start_time' => $start_time,
            'end_time' => $end_time,
            'pickup_loc' => $pickup_loc,
            'dropoff_loc' => $dropoff_loc,
            'insurance' => $insurance,
            'insurance_type' => $insurance_type,
            'extra_services' => $extra_services,
            'deposit_type' => $deposit_type
        )
    ));
        wp_send_json_success(array(
            'message' => __('Vehicle is available for your selected dates.', 'dreamsrent'),
            'pricing' => $pricing
        ));
    } else {
        wp_send_json_error(array(
            'message' => __('Sorry, the vehicle is not available for your selected dates.', 'dreamsrent')
        ));
    }
}

function check_car_availability($booking_product_id, $time_option, $start_date, $end_date, $start_time, $end_time) {
    global $wpdb;
    $table_name = $wpdb->prefix . 'dreamsrent_booking';

    // Build start and end datetime objects from incoming params
    $start_datetime = DateTime::createFromFormat('d-m-Y H:i', $start_date . ' ' . $start_time);
    $end_datetime   = DateTime::createFromFormat('d-m-Y H:i', $end_date . ' ' . $end_time);

    if (!$start_datetime || !$end_datetime) {
        return false; // Invalid datetime input
    }

    // Format into Y-m-d and H:i for comparison
    $start_date_fmt = $start_datetime->format('Y-m-d');
    $end_date_fmt   = $end_datetime->format('Y-m-d');
    $start_time_fmt = $start_datetime->format('H:i');
    $end_time_fmt   = $end_datetime->format('H:i');

    // Fetch all existing bookings for the product except cancelled
    $query = $wpdb->prepare(
            "SELECT * FROM $table_name WHERE product_id = %d",
            $booking_product_id
        );

    $existing_bookings = $wpdb->get_results($query);

    $available = true;

    if ($existing_bookings) {
        foreach ($existing_bookings as $booking) {
            $pickup_datetime  = new DateTime($booking->pickup_date);
            $dropoff_datetime = new DateTime($booking->dropoff_date);

            $pickup_date  = $pickup_datetime->format('Y-m-d');
            $pickup_time  = $pickup_datetime->format('H:i');
            $dropoff_date = $dropoff_datetime->format('Y-m-d');
            $dropoff_time = $dropoff_datetime->format('H:i');

            if ($time_option === 'day') {
                // Overlap check for days
                if (($start_date_fmt <= $dropoff_date) && ($end_date_fmt >= $pickup_date)) {
                    $available = false;
                    break;
                }
            } elseif ($time_option === 'hour') {
                // First check if dates overlap
                if (($start_date_fmt <= $dropoff_date) && ($end_date_fmt >= $pickup_date)) {
                    if ($start_date_fmt === $dropoff_date && $start_time_fmt > $dropoff_time) {
                        $available = true; // pickup is after an existing dropoff
                    } elseif ($end_date_fmt === $pickup_date && $end_time_fmt < $pickup_time) {
                        $available = true; // dropoff is before an existing pickup
                    } else {
                        $available = false; // times overlap
                        break;
                    }
                }
            }
        }
    }

    return $available;
}

function calculate_booking_pricing($post_id, $time_option, $start_date, $end_date, $start_time, $end_time, $pickup_loc, $dropoff_loc, $insurance, $insurance_type, $extra_services, $deposit_type) {
    // This function replicates the pricing calculation logic from your cart system
    
    $pricing = array();
    
    // Calculate rental duration
    $start_datetime = DateTime::createFromFormat('d-m-Y H:i', $start_date . ' ' . $start_time);
    $end_datetime = DateTime::createFromFormat('d-m-Y H:i', $end_date . ' ' . $end_time);
    $interval = $start_datetime->diff($end_datetime);
    
    // Calculate days and hours
    $days = $interval->days;
    $hours = $interval->h;
    $minutes = $interval->i;
    
    // For day rentals: if more than 1 day with any minutes, consider as 2 days
    if ($time_option === 'day') {
        if ($days > 0 && ($hours > 0 || $minutes > 0)) {
            $days = $days + 1; // Add an extra day
        } elseif ($days == 0 && ($hours > 0 || $minutes > 0)) {
            $days = 1; // Minimum 1 day
        }
    }
    
    // Add rental period information
    $pricing['rental_period'] = array(
        'pickup' => sprintf(__('Pickup: %s at %s', 'dreamsrent'), $start_date, $start_time),
        'dropoff' => sprintf(__('Dropoff: %s at %s', 'dreamsrent'), $end_date, $end_time),
        'duration' => sprintf(__('Duration: %d days, %d hours, %d minutes', 'dreamsrent'), $interval->days, $hours, $minutes)
    );
    
    // Get base pricing components
    $rental_day_price = floatval(get_post_meta($post_id, 'dreams_booking_meta_rdprice', true));
    $rental_hour_price = floatval(get_post_meta($post_id, 'dreams_booking_meta_rhprice', true));
    $rental_week_price = floatval(get_post_meta($post_id, 'dreams_booking_meta_weekprice', true));
    $rental_month_price = floatval(get_post_meta($post_id, 'dreams_booking_meta_monthprice', true));
    
    // Check for seasonal pricing first
    $seasonal_price = calculate_seasonal_pricing($post_id, $start_datetime, $end_datetime, $time_option, $days);
    
    // Get base rental price based on time option
    $base_price         = 0;
    $base_price_details = '';

    if ($seasonal_price) {
        // Seasonal pricing found
        if ($time_option === 'day' && isset($seasonal_price['seasonal_days'])) {
            // Apply seasonal rate only to overlapping days
            $seasonal_days      = max(0, intval($seasonal_price['seasonal_days']));
            $non_seasonal_days  = max(0, $days - $seasonal_days);

            $base_price         = $seasonal_price['total'];
            $base_price_details = $seasonal_price['details'];

            // Add base pricing for the remaining (non-seasonal) days
            if ($non_seasonal_days > 0) {
                $tariff_price = calculate_tariff_pricing($post_id, $non_seasonal_days, 'day');

                if ($tariff_price) {
                    $base_price        += $tariff_price['total'];
                    $base_price_details .= ' + ' . $tariff_price['details'];
                } else {
                    $base_price        += $non_seasonal_days * $rental_day_price;
                    $base_price_details .= ' + ' . sprintf(__('Base Rental: %s × %d days', 'dreamsrent'), wc_price($rental_day_price), $non_seasonal_days);
                }
            }
        } else {
            // For non-day options, keep existing behaviour: entire booking uses seasonal rate
            $base_price         = $seasonal_price['total'];
            $base_price_details = $seasonal_price['details'];
        }
    } else {
        // Use regular or tariff pricing
        if ($time_option === 'day') {
            // Check for tariff rates first
            $tariff_price = calculate_tariff_pricing($post_id, $days, 'day');
            
            if ($tariff_price) {
                $base_price = $tariff_price['total'];
                $base_price_details = $tariff_price['details'];
            } else {
                // Use standard daily rate
                $base_price = $days * $rental_day_price;
                $base_price_details = sprintf(__('Base Rental: %s × %d days', 'dreamsrent'), wc_price($rental_day_price), $days);
            }
            
        } elseif ($time_option === 'hour') {
            // Calculate total hours including minutes
            $total_hours = $interval->days * 24 + $interval->h;
            if ($interval->i > 0) {
                $total_hours += 1; // Add an extra hour for any minutes
            }
            
            if ($total_hours == 0) $total_hours = 1; // Minimum 1 hour
            
            // Check for tariff rates first
            // $tariff_price = calculate_tariff_pricing($post_id, $total_hours, 'hour');
            
            // if ($tariff_price) {
            //     $base_price = $tariff_price['total'];
            //     $base_price_details = $tariff_price['details'];
            // } else {
                // Use standard hourly rate
            $base_price = $total_hours * $rental_hour_price;
            $base_price_details = sprintf(__('Base Rental: %s × %d hours', 'dreamsrent'), wc_price($rental_hour_price), $total_hours);
            // }
            
        } elseif ($time_option === 'week') {
            $weeks = ceil($interval->days / 7);
            if ($weeks == 0) $weeks = 1; // Minimum 1 week
            
            $base_price = $weeks * $rental_week_price;
            $base_price_details = sprintf(__('Base Rental: %s × %d weeks', 'dreamsrent'), wc_price($rental_week_price), $weeks);
            
        } elseif ($time_option === 'month') {
            $months = ceil($interval->days / 30);
            if ($months == 0) $months = 1; // Minimum 1 month
            
            $base_price = $months * $rental_month_price;
            $base_price_details = sprintf(__('Base Rental: %s × %d months', 'dreamsrent'), wc_price($rental_month_price), $months);
        }
    }
    
    $pricing['base_price'] = wc_price($base_price);
    $pricing['base_price_details'] = array(
        'description' => __('Base Rental', 'dreamsrent'),
        'calculation' => $base_price_details . ' = ' . wc_price($base_price)
    );
    
    // Calculate insurance cost
    $insurance_cost = 0;
    $insurance_details = '';
    if ($insurance && $insurance_type) {
        $insurance_amount = floatval($insurance);
        
        if ($insurance_type === 'day' && ($time_option === 'day' || $time_option === 'week' || $time_option === 'month')) {
            $insurance_cost = $insurance_amount * $days;
            $insurance_details = sprintf(__('Insurance: %s × %d days', 'dreamsrent'), wc_price($insurance_amount), $days);
        } elseif ($insurance_type === 'day' && $time_option === 'hour') {
            // Convert hours to days for insurance calculation
            $total_hours = $interval->days * 24 + $interval->h;
            if ($interval->i > 0) {
                $total_hours += 1; // Add an extra hour for any minutes
            }
            $insurance_days = ceil($total_hours / 24);
            $insurance_cost = $insurance_amount * $insurance_days;
            $insurance_details = sprintf(__('Insurance: %s × %d days', 'dreamsrent'), wc_price($insurance_amount), $insurance_days);
        } else {
            // Fixed insurance
            $insurance_cost = $insurance_amount;
            $insurance_details = sprintf(__('Insurance: %s (fixed)', 'dreamsrent'), wc_price($insurance_cost));
        }
        
        $pricing['insurance_details'] = array(
            'description' => __('Insurance', 'dreamsrent'),
            'calculation' => $insurance_details . ' = ' . wc_price($insurance_cost)
        );
    }
    
    // Calculate extra services cost
    $extra_services_cost = 0;
    $extra_services_details = array();
    if (!empty($extra_services)) {
        foreach ($extra_services as $service) {
            $service_price = floatval($service['price']);
            $service_type = $service['type'];
            
            // Get service name
            $service_post = get_page_by_path($service['id'], OBJECT, 'extra_service');
            $service_name = $service_post ? $service_post->post_title : $service['id'];
            
            $service_total = 0;
            $service_calculation = '';
            
            if ($service_type === 'per_day' && ($time_option === 'day' || $time_option === 'week' || $time_option === 'month')) {
                $service_total = $service_price * $days;
                $service_calculation = sprintf('%s × %d days = %s', wc_price($service_price), $days, wc_price($service_total));
            } elseif ($service_type === 'per_day' && $time_option === 'hour') {
                $total_hours = $interval->days * 24 + $interval->h;
                if ($interval->i > 0) {
                    $total_hours += 1; // Add an extra hour for any minutes
                }
                $service_days = ceil($total_hours / 24);
                $service_total = $service_price * $service_days;
                $service_calculation = sprintf('%s × %d days = %s', wc_price($service_price), $service_days, wc_price($service_total));
            } elseif ($service_type === 'per_hour' && $time_option === 'hour') {
                $total_hours = $interval->days * 24 + $interval->h;
                if ($interval->i > 0) {
                    $total_hours += 1; // Add an extra hour for any minutes
                }
                $service_total = $service_price * $total_hours;
                $service_calculation = sprintf('%s × %d hours = %s', wc_price($service_price), $total_hours, wc_price($service_total));
            } else {
                // One-time fee
                $service_total = $service_price;
                $service_calculation = sprintf('%s (one-time)', wc_price($service_total));
            }
            
            $extra_services_cost += $service_total;
            $extra_services_details[] = array(
                'name' => $service_name,
                'calculation' => $service_calculation
            );
        }
    }
    $pricing['extra_services'] = $extra_services_details;
    
    // Calculate relocation fee if different locations
    $relocation_fee = 0;
    $relocation_details = '';
    if ($pickup_loc !== $dropoff_loc) {
        $diff_pickup_drop_locations_price = dreamsrent_fl_framework_getoptions('diff_pickup_drop_locations_price');
        if ($diff_pickup_drop_locations_price) {
            $relocation_fee = floatval($diff_pickup_drop_locations_price);
            $relocation_details = sprintf(__('%s', 'dreamsrent'), wc_price($relocation_fee));
            
            $pricing['relocation_details'] = array(
                'description' => __('Relocation Fee', 'dreamsrent'),
                'calculation' => $relocation_details
            );
        }
    }

    $pricing['date_difference'] = $days;
    
    // Calculate subtotal
    $subtotal = $base_price + $insurance_cost + $extra_services_cost + $relocation_fee;
    $pricing['subtotal'] = wc_price($subtotal);
        // Calculate booking total (subtotal + tax)
    $booking_total = $subtotal;
    // Calculate tax
    if (get_option('woocommerce_calc_taxes') === 'yes') {
        $tax_rate = 0;
        $tax_rates = WC_Tax::get_rates();
        if (!empty($tax_rates)) {
            $tax_rate = reset($tax_rates)['rate'];
        }
        $tax_amount = ($subtotal * $tax_rate) / 100;
        $pricing['tax'] = wc_price($tax_amount);
        $pricing['tax_details'] = array(
            'description' => __('Tax', 'dreamsrent'),
            'calculation' => sprintf(__('%s × %d%% = %s', 'dreamsrent'), wc_price($subtotal), $tax_rate, wc_price($tax_amount))
        );
            // Calculate booking total (subtotal + tax)
    $booking_total = $subtotal + $tax_amount;
    }
    

    $pricing['booking_total'] = wc_price($booking_total);
    $pricing['booking_total_amount'] = $booking_total; // Store numeric value
    
    // Calculate deposit if applicable
    $deposit_enable = get_post_meta($post_id, 'dreams_booking_meta_enable_deposit', true);
    $deposit_amount = 0;
    $deposit_details = '';
    
    if (($deposit_enable === 'yes' || $deposit_enable === 'yeswithfull') && $deposit_type === 'deposit') {
        $deposit_type_meta = get_post_meta($post_id, 'dreams_booking_meta_type_deposit', true);
        $deposit_value = floatval(get_post_meta($post_id, 'dreams_booking_meta_amount_deposit', true));
        
        if ($deposit_type_meta === 'percent') {
            $deposit_amount = ($booking_total * $deposit_value) / 100;
            $deposit_details = sprintf(__('Deposit: %s × %d%% = %s', 'dreamsrent'), wc_price($booking_total), $deposit_value, wc_price($deposit_amount));
        } elseif ($deposit_type_meta === 'value') {
            $deposit_amount = $deposit_value;
            $deposit_details = sprintf(__('Deposit: %s (fixed)', 'dreamsrent'), wc_price($deposit_amount));
        }
        
        $pricing['deposit_details'] = array(
            'description' => __('Deposit', 'dreamsrent'),
            'calculation' => $deposit_details
        );
        
        // Calculate final total (booking total + deposit)
        $final_total = $booking_total + $deposit_amount;
        $pricing['final_total'] = wc_price($final_total);
        $pricing['final_total_amount'] = $final_total; // Store numeric value for form submission
        
        // Calculate remaining balance
        $remain_balance = $booking_total - $deposit_amount;
        $pricing['remain_balance'] = wc_price($remain_balance);
        $pricing['remain_balance_details'] = array(
            'description' => __('Remaining Balance', 'dreamsrent'),
            'calculation' => sprintf(__('%s - %s = %s', 'dreamsrent'), wc_price($booking_total), wc_price($deposit_amount), wc_price($remain_balance))
        );
    } else {
        // No deposit, so final total is the same as booking total
        $pricing['final_total'] = wc_price($booking_total);
        $pricing['final_total_amount'] = $booking_total;
    }
    
    $pricing['base_price_amount'] = $base_price;
    $pricing['insurance_amount'] = $insurance_cost;
    $pricing['extra_services_amount'] = $extra_services_cost;
    $pricing['relocation_fee_amount'] = $relocation_fee;
    $pricing['subtotal_amount'] = $subtotal;
    $pricing['tax_amount'] = $tax_amount;
    $pricing['booking_total_amount'] = $booking_total;
    $pricing['deposit_amount'] = $deposit_amount;
    $pricing['final_total_amount'] = isset($final_total) ? $final_total : $booking_total;
    $pricing['remain_balance_amount'] = isset($remain_balance) ? $remain_balance : 0;
   
    return $pricing;
}

// Helper function to calculate time difference in hours (replicating your cart logic)
function calculate_time_difference_hours($start_datetime, $end_datetime) {
    if ($start_datetime == $end_datetime) {
        // Same day calculation
        $time_difference = $start_datetime->diff($end_datetime);
        $hours = $time_difference->h;
        $minutes = $time_difference->i;
        $total_minutes = ($hours * 60) + $minutes;
        $total_hours = ceil($total_minutes / 60);
    } else {
        // Different days calculation
        $midnight = clone $start_datetime;
        $midnight->setTime(23, 59);

        $time_difference_start_day = $start_datetime->diff($midnight);
        $hours_start_day = $time_difference_start_day->h;
        $minutes_start_day = $time_difference_start_day->i;
        $total_minutes_start_day = ($hours_start_day * 60) + $minutes_start_day + 1; // adding 1 minute to include the final minute

        $start_of_day = clone $end_datetime;
        $start_of_day->setTime(0, 0);

        $time_difference_end_day = $start_of_day->diff($end_datetime);
        $hours_end_day = $time_difference_end_day->h;
        $minutes_end_day = $time_difference_end_day->i;
        $total_minutes_end_day = ($hours_end_day * 60) + $minutes_end_day;

        $days_difference = $start_datetime->diff($end_datetime)->days;

        if ($start_datetime > $end_datetime) {
            $total_hours = ($total_minutes_start_day / 60) + ($total_minutes_end_day / 60) + ($days_difference * 24);
        } else {
            $total_hours = ($total_minutes_start_day / 60) + ($total_minutes_end_day / 60) + (($days_difference - 1) * 24);
        }
        $total_hours = ceil($total_hours);
    }

    return $total_hours;
}

// Helper function to calculate seasonal pricing
function calculate_seasonal_pricing($post_id, $start_datetime, $end_datetime, $time_option, $days) {
    $seasonal_rates = get_post_meta($post_id, 'seasonal_rates', true);
    // echo '<pre>'; print_r($seasonal_rates); echo '</pre>';
    // echo $start_datetime->format('Y-m-d') . ' to ' . $end_datetime->format('Y-m-d');
    if (empty($seasonal_rates) || !is_array($seasonal_rates)) {
        return false;
    }
    
    $start_timestamp = $start_datetime->getTimestamp();
    $end_timestamp   = $end_datetime->getTimestamp();

    // Also work with date-only values for overlapping-day calculations
    $booking_start_date = strtotime($start_datetime->format('Y-m-d'));
    $booking_end_date   = strtotime($end_datetime->format('Y-m-d'));
    
    foreach ($seasonal_rates as $season) {
        $season_start = strtotime($season['start_date']);
        $season_end   = strtotime($season['end_date']);

        // Any overlap between booking and season (timestamp based)
        if ($start_timestamp <= $season_end && $end_timestamp >= $season_start) {

            $daily_rate   = floatval($season['daily_rate']);
            $weekly_rate  = floatval($season['weekly_rate']);
            $monthly_rate = floatval($season['monthly_rate']);
            $late_fee     = floatval($season['late_fee']);

            $total         = 0;
            $details       = '';
            $seasonal_days = 0;

            if ($time_option === 'day') {
                // Calculate overlapping days between booking and seasonal period (date-based, inclusive)
                $overlap_start = max($booking_start_date, $season_start);
                $overlap_end   = min($booking_end_date, $season_end);

                if ($overlap_start <= $overlap_end) {
                    // +1 to make the range inclusive of both start and end dates
                    $seasonal_days = (int) floor(($overlap_end - $overlap_start) / DAY_IN_SECONDS) + 1;
                }

                if ($seasonal_days <= 0) {
                    // No effective overlapping days
                    continue;
                }

                $total   = $seasonal_days * $daily_rate;
                $details = sprintf(
                    __('Seasonal Daily Rate: %s × %d days', 'dreamsrent'),
                    wc_price($daily_rate),
                    $seasonal_days
                );
            } elseif ($time_option === 'week') {
                $weeks  = ceil($days / 7);
                $total  = $weeks * $weekly_rate;
                $details = sprintf(
                    __('Seasonal Weekly Rate: %s × %d weeks', 'dreamsrent'),
                    wc_price($weekly_rate),
                    $weeks
                );
            } elseif ($time_option === 'month') {
                $months = ceil($days / 30);
                $total  = $months * $monthly_rate;
                $details = sprintf(
                    __('Seasonal Monthly Rate: %s × %d months', 'dreamsrent'),
                    wc_price($monthly_rate),
                    $months
                );
            } else {
                $total   = $days * $daily_rate;
                $details = sprintf(
                    __('Seasonal Daily Rate: %s × %d days', 'dreamsrent'),
                    wc_price($daily_rate),
                    $days
                );
            }

            $result = [
                'total'       => $total,
                'details'     => $details,
                'season_name' => $season['season_name'],
            ];

            // For day-based bookings, also return how many days were priced at seasonal rate
            if ($time_option === 'day') {
                $result['seasonal_days'] = $seasonal_days;
            }

            return $result;
        }
    }
    // echo 'No seasonal match';
    return false;
}

// Helper function to calculate tariff pricing
function calculate_tariff_pricing($post_id, $duration, $time_option) {
    $tariffs = get_post_meta($post_id, 'rental_tariffs', true);
    // ... rest of the code remains the same ...
    
    if (empty($tariffs) || !is_array($tariffs)) {
        return false;
    }
    
    foreach ($tariffs as $tariff) {
        $from_days = intval($tariff['from_days']);
        $to_days = intval($tariff['to_days']);
        $daily_price = floatval($tariff['daily_price']);
        $base_km = $tariff['base_km'];
        $unlimited = $tariff['unlimited'];
        $km_extra_price = floatval($tariff['km_extra_price']);
        
        // Check if duration falls within this tariff range
        if ($duration >= $from_days && $duration <= $to_days) {
            $total = $duration * $daily_price;
            
            if ($time_option === 'day') {
                $details = sprintf(__('Tariff Rate: %s × %d days (%d-%d days)', 'dreamsrent'), 
                    wc_price($daily_price), $duration, $from_days, $to_days);
            } else {
                $details = sprintf(__('Tariff Rate: %s × %d hours (%d-%d hours)', 'dreamsrent'), 
                    wc_price($daily_price), $duration, $from_days, $to_days);
            }
            
            // Add KM information
            if ($unlimited === '1') {
                $details .= ' ' . __('(Unlimited KM)', 'dreamsrent');
            } else {
                $details .= ' ' . sprintf(__('(%s KM included)', 'dreamsrent'), $base_km);
            }
            
            return array(
                'total' => $total,
                'details' => $details,
                'tariff_name' => $tariff['tariff_name']
            );
        }
    }
    
    return false;
}

//fair summary popup pricing details
// Add AJAX handler for pricing details
add_action('wp_ajax_get_pricing_details', 'get_pricing_details');
add_action('wp_ajax_nopriv_get_pricing_details', 'get_pricing_details');

function get_pricing_details() {
    // Verify nonce
    if (!wp_verify_nonce($_POST['nonce'], 'pricing_details_nonce')) {
        wp_send_json_error(array('message' => 'Nonce verification failed'));
        return;
    }
    
    $post_id = intval($_POST['post_id']);
    $rental_type = sanitize_text_field($_POST['rental_type']);
    
    $pricing_data = array(
        'tariff_pricing' => array(),
        'seasonal_pricing' => array(),
        'base_pricing' => array()
    );
    
    // Get base pricing
    if ($rental_type === 'day') {
        $daily_price = get_post_meta($post_id, 'dreams_booking_meta_rdprice', true);
        if ($daily_price) {
            $pricing_data['base_pricing'][] = array(
                'type' => __('Daily Rate', 'dreamsrent'),
                'price' => wc_price($daily_price)
            );
        }
    } elseif ($rental_type === 'hour') {
        $hourly_price = get_post_meta($post_id, 'dreams_booking_meta_rhprice', true);
        if ($hourly_price) {
            $pricing_data['base_pricing'][] = array(
                'type' => __('Hourly Rate', 'dreamsrent'),
                'price' => wc_price($hourly_price)
            );
        }
    }
    
    // Get weekly price if available
    $weekly_price = get_post_meta($post_id, 'dreams_booking_meta_weekprice', true);
    if ($weekly_price) {
        $pricing_data['base_pricing'][] = array(
            'type' => __('Weekly Rate', 'dreamsrent'),
            'price' => wc_price($weekly_price)
        );
    }
    
    // Get monthly price if available
    $monthly_price = get_post_meta($post_id, 'dreams_booking_meta_monthprice', true);
    if ($monthly_price) {
        $pricing_data['base_pricing'][] = array(
            'type' => __('Monthly Rate', 'dreamsrent'),
            'price' => wc_price($monthly_price)
        );
    }
    
    // Get tariff pricing
    $tariff_data = get_post_meta($post_id, 'rental_tariffs', true);
    if ($tariff_data && is_array($tariff_data)) {
        foreach ($tariff_data as $tariff) {
            if (isset($tariff['from_days']) && isset($tariff['daily_price'])) {
                $from_days = intval($tariff['from_days']);
                $to_days = isset($tariff['to_days']) ? intval($tariff['to_days']) : $from_days;
                
                $duration = '';
                if ($from_days == $to_days) {
                    $duration = sprintf(_n('%d day', '%d days', $from_days, 'dreamsrent'), $from_days);
                } else {
                    $duration = sprintf(__('%d-%d days', 'dreamsrent'), $from_days, $to_days);
                }
                
                $base_km = isset($tariff['base_km']) ? $tariff['base_km'] : '';
                $unlimited = isset($tariff['unlimited']) && $tariff['unlimited'] === '1';
                $km_extra_price = isset($tariff['km_extra_price']) ? $tariff['km_extra_price'] : '';
                
                $pricing_data['tariff_pricing'][] = array(
                    'name' => isset($tariff['tariff_name']) ? $tariff['tariff_name'] : __('Tariff', 'dreamsrent'),
                    'duration' => $duration,
                    'daily_price' => wc_price($tariff['daily_price']),
                    'base_km' => $unlimited ? __('Unlimited', 'dreamsrent') : $base_km,
                    'km_extra_price' => wc_price($km_extra_price)
                );
            }
        }
    }
    
    // Get seasonal pricing
    $seasonal_data = get_post_meta($post_id, 'seasonal_rates', true);
    if ($seasonal_data && is_array($seasonal_data)) {
        foreach ($seasonal_data as $season) {
            if (isset($season['start_date']) && isset($season['end_date'])) {
                $start_date = date('M j', strtotime($season['start_date']));
                $end_date = date('M j', strtotime($season['end_date']));
                
                $pricing_data['seasonal_pricing'][] = array(
                    'name' => isset($season['season_name']) ? $season['season_name'] : __('Season', 'dreamsrent'),
                    'dates' => $start_date . ' - ' . $end_date,
                    'daily_rate' => isset($season['daily_rate']) ? wc_price($season['daily_rate']) : '-',
                    'weekly_rate' => isset($season['weekly_rate']) ? wc_price($season['weekly_rate']) : '-',
                    'monthly_rate' => isset($season['monthly_rate']) ? wc_price($season['monthly_rate']) : '-',
                    'late_fee' => isset($season['late_fee']) ? wc_price($season['late_fee']) : '-'
                );
            }
        }
    }
    
    wp_send_json_success($pricing_data);
}

// cart
add_filter('woocommerce_add_cart_item_data', 'add_booking_data_to_cart_item', 10, 3);

function add_booking_data_to_cart_item($cart_item_data, $product_id, $variation_id) {
    if (!empty($_POST['calculated_total_amount'])) {
        // Store all pricing data in cart item
        $cart_item_data['booking_pricing'] = array(
            'base_price' => floatval($_POST['calculated_base_price']),
            'insurance' => floatval($_POST['calculated_insurance']),
            'extra_services' => floatval($_POST['calculated_extra_services']),
            'relocation_fee' => floatval($_POST['calculated_relocation_fee']),
            'subtotal' => floatval($_POST['calculated_subtotal']),
            'tax' => floatval($_POST['calculated_tax']),
            'booking_total' => floatval($_POST['calculated_booking_total']),
            'deposit' => floatval($_POST['calculated_deposit']),
            'final_total' => floatval($_POST['calculated_final_total']),
            'remain_balance' => floatval($_POST['calculated_remain_balance']),
            'total_amount' => floatval($_POST['calculated_total_amount']),
            'base_price_details' => array(
                'description' => __('Base Rental', 'dreamsrent'),
                'calculation' => !empty($_POST['base_price_calculation']) ? sanitize_text_field($_POST['base_price_calculation']) : ''
            ),
            'insurance_details' => array(
                'description' => __('Insurance', 'dreamsrent'),
                'calculation' => !empty($_POST['insurance_calculation']) ? sanitize_text_field($_POST['insurance_calculation']) : ''
            ),
            'extra_services_details' => !empty($_POST['extra_services_data']) ? json_decode(stripslashes($_POST['extra_services_data']), true) : array(),
            'relocation_details' => array(
                'description' => __('Relocation Fee', 'dreamsrent'),
                'calculation' => !empty($_POST['relocation_calculation']) ? sanitize_text_field($_POST['relocation_calculation']) : ''
            ),
            'tax_details' => array(
                'description' => __('Tax', 'dreamsrent'),
                'calculation' => !empty($_POST['tax_calculation']) ? sanitize_text_field($_POST['tax_calculation']) : ''
            ),
            'deposit_details' => array(
                'description' => __('Deposit', 'dreamsrent'),
                'calculation' => !empty($_POST['deposit_calculation']) ? sanitize_text_field($_POST['deposit_calculation']) : ''
            )

        );
        
        // Store booking data
         $cart_item_data['time-option'] = sanitize_text_field($_POST['time-option']);
         $cart_item_data['date_difference'] = sanitize_text_field($_POST['date_difference']);
         $cart_item_data['car_product_id'] = sanitize_text_field($_POST['car_id']);
         $cart_item_data['car_id'] = sanitize_text_field($_POST['car_id_new']);
        $term_pickup = get_term_by( 'id', sanitize_text_field($_POST['pickup_loc']), 'location' );
    $term_pickup_name = $term_pickup ? $term_pickup->name : '';
    
    // Get drop-off location term
    $term_pickoff = get_term_by( 'id', sanitize_text_field($_POST['pickoff_loc']), 'location' );
    $term_pickoff_name = $term_pickoff ? $term_pickoff->name : '';

        $cart_item_data['booking_data'] = array(
            'time-option' => sanitize_text_field($_POST['time-option']),
            'start_date' => sanitize_text_field($_POST['dsrent_pickup_date']),
            'end_date' => sanitize_text_field($_POST['dsrent_pickoff_date']),
            'start_time' => sanitize_text_field($_POST['starttimePicker']),
            'end_time' => sanitize_text_field($_POST['endtimePicker']),
            'pickup_loc' => $term_pickup_name,
            'dropoff_loc' => $term_pickoff_name,
            'insurance' => sanitize_text_field($_POST['insurance_price']),
            'insurance_type' => sanitize_text_field($_POST['insurance_type']),
            'extra_services' => isset($_POST['selected_extra_services']) ? $_POST['selected_extra_services'] : array(),
            'deposit_type' => sanitize_text_field($_POST['dsr_type_deposit']),
            'date_difference' => !empty($_POST['date_difference']) ? $_POST['date_difference'] : array()
        );
        
        error_log('Cart item data added from hidden fields: ' . print_r($cart_item_data, true));
    }
    
    return $cart_item_data;
}

add_filter('woocommerce_cart_item_name', 'display_booking_details_in_cart', 10, 3);

function display_booking_details_in_cart($product_name, $cart_item, $cart_item_key) {
    if (isset($cart_item['booking_data'])) {
        $booking_data = $cart_item['booking_data'];
        
        $details_html = '<div class="mt-3 mb-2">';
        $details_html .= '<p><strong>' . __('Rental Period:', 'dreamsrent') . '</strong><br>';
        $details_html .= __('From:', 'dreamsrent') . ' ' . $booking_data['start_date'] . ' ' . $booking_data['start_time'] . '<br>';
        $details_html .= __('To:', 'dreamsrent') . ' ' . $booking_data['end_date'] . ' ' . $booking_data['end_time'] . '</p>';
        
        if (!empty($booking_data['pickup_loc'])) {
            $details_html .= '<p><strong>' . __('Pickup Location:', 'dreamsrent') . '</strong> ' . $booking_data['pickup_loc'] . '</p>';
        }
        
        if (!empty($booking_data['dropoff_loc'])) {
            $details_html .= '<p><strong>' . __('Dropoff Location:', 'dreamsrent') . '</strong> ' . $booking_data['dropoff_loc'] . '</p>';
        }
        
        $details_html .= '</div>';
        
        return $product_name . $details_html;
    }
    
    return $product_name;
}

// Display pricing breakdown in cart
add_action('woocommerce_after_cart_item_name', 'display_pricing_breakdown_in_cart', 10, 2);

function display_pricing_breakdown_in_cart($cart_item, $cart_item_key) {
    if (isset($cart_item['booking_pricing'])) {
        $pricing = $cart_item['booking_pricing'];
        
        echo '<div class="booking-pricing-breakdown">';
        echo '<p><strong>' . __('Pricing Breakdown:', 'dreamsrent') . '</strong></p>';
        
        // Base price
        if (!empty($pricing['base_price_details']['calculation'])) {
            echo '<p>' . esc_html($pricing['base_price_details']['calculation']) . '</p>';
        }
        
        // Insurance
        if (!empty($pricing['insurance_details']['calculation'])) {
            echo '<p>' . esc_html($pricing['insurance_details']['calculation']) . '</p>';
        }
        
        // Extra services
        if (!empty($pricing['extra_services_details'])) {
            foreach ($pricing['extra_services_details'] as $service) {
                echo '<p>' . esc_html($service['name']) . ': ' . wp_kses_post($service['calculation']) . '</p>';
            }
        }

        
        // Relocation fee
        if (!empty($pricing['relocation_details']['calculation'])) {
            echo '<p>' . esc_html($pricing['relocation_details']['description']).': '. esc_html($pricing['relocation_details']['calculation']) . '</p>';
        }
        
        // Tax
        if (!empty($pricing['tax_details']['calculation'])) {
            echo '<p>' . esc_html($pricing['tax_details']['calculation']) . '</p>';
        }
        
        // Deposit
        if (!empty($pricing['deposit_details']['calculation'])) {
            echo '<p>' . esc_html($pricing['deposit_details']['calculation']) . '</p>';
        }
        
        // Total
        if (!empty($pricing['total_amount'])) {
            echo '<p><strong>' . __('Total:', 'dreamsrent') . ' ' . wc_price($pricing['total_amount']) . '</strong></p>';
        }
        
        echo '</div>';
    }
}

add_action('woocommerce_checkout_create_order_line_item', 'save_booking_data_to_order', 10, 4);

function save_booking_data_to_order($item, $cart_item_key, $values, $order) {
    if(isset($values['car_product_id'])) {
        $item->add_meta_data('dsrent_car_product_id', $values['car_product_id']);
    }
    if (isset($values['booking_data'])) {
        $item->add_meta_data('_booking_data', $values['booking_data']);
        $item->add_meta_data('dsrent_pickup_date', $values['booking_data']['start_date']);
        $item->add_meta_data('dsrent_pickoff_date', $values['booking_data']['end_date']);
        $item->add_meta_data('dsrent_pickup_time', $values['booking_data']['start_time']);
        $item->add_meta_data('dsrent_pickoff_time', $values['booking_data']['end_time']);
        $item->add_meta_data('dsrent_pickup_loc', $values['booking_data']['pickup_loc']);
        $item->add_meta_data('dsrent_pickoff_loc', $values['booking_data']['dropoff_loc']);

        
    }
    
    if (isset($values['booking_pricing'])) {
        $item->add_meta_data('_booking_pricing', $values['booking_pricing']);
        $item->add_meta_data('dsrent_product_subtotal', $values['booking_pricing']['total_amount']);
        $item->add_meta_data('dsrent_deposite_subtotal', $values['booking_pricing']['deposit']);
    }

   if (isset($values['car_id'])) {


    
    $post_author_id = get_post_field('post_author', $values['car_id']);
    $order->update_meta_data('post_author', $post_author_id);
    $order->update_meta_data('dsrent_car_id_post',$values['car_id']);
    $order->update_meta_data('_dsrent_car_id', $values['car_id']);
    
        $car_id = $values['car_id'];
        $order_id = $order->get_id();
        $product_id = $values['car_product_id']?:'';
        
        // Get time option (assuming it's stored in booking_data)
        $time_option = isset($values['booking_data']['time-option']) ? $values['booking_data']['time-option'] : '';
        
        // Get hour format setting
        $hour_format = dreamsrent_fl_framework_getoptions('hour_format');
        
        // Convert dates to 24-hour format
        $pickup_date_24h = '';
        $pickoff_date_24h = '';
        
        if ($hour_format == '12') {
            // Combine date and time for 12-hour format conversion
            $pickup_datetime = $values['booking_data']['start_date'] . ' ' . $values['booking_data']['start_time'];
            $pickoff_datetime = $values['booking_data']['end_date'] . ' ' . $values['booking_data']['end_time'];
            
            $pickup_date = DateTime::createFromFormat('d-m-Y h:i A', $pickup_datetime);
            $pickup_date_24h = $pickup_date ? $pickup_date->format('Y-m-d H:i') : '';

            $pickoff_date = DateTime::createFromFormat('d-m-Y h:i A', $pickoff_datetime);
            $pickoff_date_24h = $pickoff_date ? $pickoff_date->format('Y-m-d H:i') : '';
        } else if ($hour_format == '24') {
            // For 24-hour format, just combine date and time
            $pickup_date_24h = $values['booking_data']['start_date'] . ' ' . $values['booking_data']['start_time'];
            $pickoff_date_24h = $values['booking_data']['end_date'] . ' ' . $values['booking_data']['end_time'];
        }
        
        // Call the function to save to custom table
        save_booking_data_to_custom_table($car_id, $order_id, $product_id, $pickup_date_24h, $pickoff_date_24h, $time_option);
    }

}

add_action('woocommerce_order_item_meta_end', 'display_booking_details_in_order', 10, 3);

function save_booking_data_to_custom_table($car_id, $order_id, $product_id, $pickup_date, $pickoff_date, $time_option) {
    global $wpdb;

    $product_name = get_the_title($product_id);
    $pickup_date = preg_replace('/(\d{2}:\d{2})\s+\1/', '$1', $pickup_date);
    $pickoff_date = preg_replace('/(\d{2}:\d{2})\s+\1/', '$1', $pickoff_date);
    
    error_log('Cleaned dates - pickup: ' . $pickup_date . ', dropoff: ' . $pickoff_date);

    $pdate = DateTime::createFromFormat('d-m-Y H:i', $pickup_date);
    $formatted_pdate = $pdate ? $pdate->format('Y-m-d H:i') : '';

    $ddate = DateTime::createFromFormat('d-m-Y H:i', $pickoff_date);
    $formatted_ddate = $ddate ? $ddate->format('Y-m-d H:i') : '';
    
    $result = $wpdb->insert(
        $wpdb->prefix . 'dreamsrent_booking',
         array(
            'car_id' => $car_id,
            'product_id' => $product_id,
            'order_id' => $order_id,
            'product_name' => $product_name,
            'pickup_date' => $formatted_pdate,
            'dropoff_date' => $formatted_ddate,
            'time_option' => $time_option,
        ),
        array(
            '%d',
            '%d',
            '%d',
            '%s',
            '%s',
            '%s',
            '%s'
        )
    );

    if ($result === false) {
        error_log('Error inserting booking data: ' . $wpdb->last_error);
    } else {
        error_log('Booking data inserted successfully: ' . print_r(array(
            'product_id' => $product_id,
            'order_id' => $order_id,
            'product_name' => $product_name,
            'pickup_date' => $pickup_date,
            'dropoff_date' => $pickoff_date,
            'time_option' => $time_option,
        ), true));
        $_SESSION['booking_id'] = $wpdb->insert_id; // Store the booking ID in the session
        return $wpdb->insert_id; // Return the ID of the inserted row
    }
}


function display_booking_details_in_order($item_id, $item, $order) {
    $booking_data = $item->get_meta('_booking_data');
    $pricing = $item->get_meta('_booking_pricing');
    
    if ($booking_data) {
        echo '<div>';
        echo '<h5 class=" mt-3 mb-2">' . __('Booking Details', 'dreamsrent') . '</h5>';
        echo '<p><strong>' . __('Rental Period:', 'dreamsrent') . '</strong><br>';
        echo __('From:', 'dreamsrent') . ' ' . esc_html($booking_data['start_date']) . ' ' . esc_html($booking_data['start_time']) . '<br>';
        echo __('To:', 'dreamsrent') . ' ' . esc_html($booking_data['end_date']) . ' ' . esc_html($booking_data['end_time']) . '</p>';
        
        if (!empty($booking_data['pickup_loc'])) {
            echo '<p><strong>' . __('Pickup Location:', 'dreamsrent') . '</strong> ' . esc_html($booking_data['pickup_loc']) . '</p>';
        }
        
        if (!empty($booking_data['dropoff_loc'])) {
            echo '<p><strong>' . __('Dropoff Location:', 'dreamsrent') . '</strong> ' . esc_html($booking_data['dropoff_loc']) . '</p>';
        }
        
        // Display time option (day/hour/week/month)
        if (!empty($booking_data['time_option'])) {
            echo '<p><strong>' . __('Rental Type:', 'dreamsrent') . '</strong> ' . ucfirst(esc_html($booking_data['time_option'])) . '</p>';
        }
        
        echo '</div>';
    }
    
    if ($pricing && is_array($pricing)) {
        echo '<div class="booking-pricing-breakdown">';
        echo '<h5 class="mt-3 mb-2">' . __('Pricing Breakdown', 'dreamsrent') . '</h5>';
        
        // Base price
        if (!empty($pricing['base_price_details']['calculation'])) {
            echo '<p style="margin: 5px 0;"><strong>' . __('Base Rental:', 'dreamsrent') . '</strong> ' . wp_kses_post($pricing['base_price_details']['calculation']) . '</p>';
        } elseif (!empty($pricing['base_price'])) {
            echo '<p style="margin: 5px 0;"><strong>' . __('Base Rental:', 'dreamsrent') . '</strong> ' . wp_kses_post($pricing['base_price']) . '</p>';
        }
        
        // Insurance
        if (!empty($pricing['insurance_details']['calculation'])) {
            echo '<p style="margin: 5px 0;"><strong>' . __('Insurance:', 'dreamsrent') . '</strong> ' . wp_kses_post($pricing['insurance_details']['calculation']) . '</p>';
        } elseif (!empty($pricing['insurance'])) {
            echo '<p style="margin: 5px 0;"><strong>' . __('Insurance:', 'dreamsrent') . '</strong> ' . wp_kses_post($pricing['insurance']) . '</p>';
        }
        
        // Extra services
        if (!empty($pricing['extra_services']) && is_array($pricing['extra_services'])) {
            echo '<p style="margin: 5px 0;"><strong>' . __('Extra Services:', 'dreamsrent') . '</strong></p>';
            foreach ($pricing['extra_services'] as $service) {
                if (is_array($service) && !empty($service['calculation'])) {
                    echo '<p style="margin: 2px 0 2px 20px;">• ' . esc_html($service['name'] . ': ' . $service['calculation']) . '</p>';
                }
            }
        }
        
        // Relocation fee
        if (!empty($pricing['relocation_details']['calculation'])) {
            echo '<p style="margin: 5px 0;"><strong>' . __('Relocation Fee:', 'dreamsrent') . '</strong> ' . wp_kses_post($pricing['relocation_details']['calculation']) . '</p>';
        } elseif (!empty($pricing['relocation_fee'])) {
            echo '<p style="margin: 5px 0;"><strong>' . __('Relocation Fee:', 'dreamsrent') . '</strong> ' . wp_kses_post($pricing['relocation_fee']) . '</p>';
        }
        
        // Tax
        if (!empty($pricing['tax_details']['calculation'])) {
            echo '<p style="margin: 5px 0;"><strong>' . __('Tax:', 'dreamsrent') . '</strong> ' . wp_kses_post($pricing['tax_details']['calculation']) . '</p>';
        } elseif (!empty($pricing['tax'])) {
            echo '<p style="margin: 5px 0;"><strong>' . __('Tax:', 'dreamsrent') . '</strong> ' . wp_kses_post($pricing['tax']) . '</p>';
        }
        
        // Subtotal
        if (!empty($pricing['subtotal'])) {
            echo '<p style="margin: 5px 0;"><strong>' . __('Subtotal:', 'dreamsrent') . '</strong> ' . wp_kses_post($pricing['subtotal']) . '</p>';
        }
        
        // Deposit
        if (!empty($pricing['deposit_details']['calculation'])) {
            echo '<p style="margin: 5px 0;"><strong>' . __('Deposit:', 'dreamsrent') . '</strong> ' . wp_kses_post($pricing['deposit_details']['calculation']) . '</p>';
        } elseif (!empty($pricing['deposit'])) {
            echo '<p style="margin: 5px 0;"><strong>' . __('Deposit:', 'dreamsrent') . '</strong> ' . wp_kses_post($pricing['deposit']) . '</p>';
        }
        
        // Remaining balance
        if (!empty($pricing['remain_balance'])) {
            echo '<p style="margin: 5px 0;"><strong>' . __('Remaining Balance:', 'dreamsrent') . '</strong> ' . wp_kses_post($pricing['remain_balance']) . '</p>';
        }
        
        // Final total
        if (!empty($pricing['final_total'])) {
            echo '<p style="margin: 10px 0 5px 0; padding-top: 10px; border-top: 1px solid #ddd;"><strong>' . __('Total Amount:', 'dreamsrent') . '</strong> ' . wp_kses_post($pricing['final_total']) . '</p>';
        } elseif (!empty($pricing['booking_total'])) {
            echo '<p style="margin: 10px 0 5px 0; padding-top: 10px; border-top: 1px solid #ddd;"><strong>' . __('Total Amount:', 'dreamsrent') . '</strong> ' . wp_kses_post($pricing['booking_total']) . '</p>';
        }
        
        echo '</div>';
    }
}

add_action('woocommerce_before_order_itemmeta', 'display_booking_details_in_admin_order', 10, 3);

function display_booking_details_in_admin_order($item_id, $item, $product) {
    if (is_admin()) {
        $booking_data = $item->get_meta('_booking_data');
        $pricing = $item->get_meta('_booking_pricing');
        
        if ($booking_data) {
            echo '<div>';
            echo '<h5 class="mt-3 mb-2">' . __('Booking Details', 'dreamsrent') . '</h5>';
            echo '<p><strong>' . __('Rental Period:', 'dreamsrent') . '</strong><br>';
            echo __('From:', 'dreamsrent') . ' ' . esc_html($booking_data['start_date']) . ' ' . esc_html($booking_data['start_time']) . '<br>';
            echo __('To:', 'dreamsrent') . ' ' . esc_html($booking_data['end_date']) . ' ' . esc_html($booking_data['end_time']) . '</p>';
            
            if (!empty($booking_data['pickup_loc'])) {
                echo '<p><strong>' . __('Pickup Location:', 'dreamsrent') . '</strong> ' . esc_html($booking_data['pickup_loc']) . '</p>';
            }
            
            if (!empty($booking_data['dropoff_loc'])) {
                echo '<p><strong>' . __('Dropoff Location:', 'dreamsrent') . '</strong> ' . esc_html($booking_data['dropoff_loc']) . '</p>';
            }
            
            // Display time option (day/hour/week/month)
            if (!empty($booking_data['time_option'])) {
                echo '<p><strong>' . __('Rental Type:', 'dreamsrent') . '</strong> ' . ucfirst(esc_html($booking_data['time_option'])) . '</p>';
            }
            
            echo '</div>';
        }
        
        if ($pricing && is_array($pricing)) {
            echo '<div class="booking-pricing-breakdown">';
            echo '<h5 class="mt-3 mb-2">' . __('Pricing Breakdown', 'dreamsrent') . '</h5>';
            
            // Display all pricing details similar to the frontend function
            if (!empty($pricing['base_price_details']['calculation'])) {
                echo '<p style="margin: 5px 0;"><strong>' . __('Base Rental:', 'dreamsrent') . '</strong> ' . wp_kses_post($pricing['base_price_details']['calculation']) . '</p>';
            }
            
            if (!empty($pricing['insurance_details']['calculation'])) {
                echo '<p style="margin: 5px 0;"><strong>' . __('Insurance:', 'dreamsrent') . '</strong> ' . wp_kses_post($pricing['insurance_details']['calculation']) . '</p>';
            }
            
            if (!empty($pricing['extra_services']) && is_array($pricing['extra_services'])) {
                echo '<p style="margin: 5px 0;"><strong>' . __('Extra Services:', 'dreamsrent') . '</strong></p>';
                foreach ($pricing['extra_services'] as $service) {
                    if (is_array($service) && !empty($service['calculation'])) {
                        echo '<p style="margin: 2px 0 2px 20px;">• ' . esc_html($service['name'] . ': ' . $service['calculation']) . '</p>';
                    }
                }
            }
            
            if (!empty($pricing['relocation_details']['calculation'])) {
                echo '<p style="margin: 5px 0;"><strong>' . __('Relocation Fee:', 'dreamsrent') . '</strong> ' . wp_kses_post($pricing['relocation_details']['calculation']) . '</p>';
            }
            
            if (!empty($pricing['tax_details']['calculation'])) {
                echo '<p style="margin: 5px 0;"><strong>' . __('Tax:', 'dreamsrent') . '</strong> ' . wp_kses_post($pricing['tax_details']['calculation']) . '</p>';
            }
            
            if (!empty($pricing['subtotal'])) {
                echo '<p style="margin: 5px 0;"><strong>' . __('Subtotal:', 'dreamsrent') . '</strong> ' . wp_kses_post($pricing['subtotal']) . '</p>';
            }
            
            if (!empty($pricing['deposit_details']['calculation'])) {
                echo '<p style="margin: 5px 0;"><strong>' . __('Deposit:', 'dreamsrent') . '</strong> ' . wp_kses_post($pricing['deposit_details']['calculation']) . '</p>';
            }
            
            if (!empty($pricing['remain_balance'])) {
                echo '<p style="margin: 5px 0;"><strong>' . __('Remaining Balance:', 'dreamsrent') . '</strong> ' . wp_kses_post($pricing['remain_balance']) . '</p>';
            }
            
            if (!empty($pricing['final_total'])) {
                echo '<p style="margin: 10px 0 5px 0; padding-top: 10px; border-top: 1px solid #ddd;"><strong>' . __('Total Amount:', 'dreamsrent') . '</strong> ' . wp_kses_post($pricing['final_total']) . '</p>';
            }
            
            echo '</div>';
        }
    }
}
// Set the product price based on hidden field value
add_filter('woocommerce_product_get_price', 'set_booking_product_price', 10, 2);

function set_booking_product_price($price, $product) {
    if (!is_a($product, 'WC_Product')) {
        return $price;
    }
    
    // Check if this is a booking product and we have calculated total
    $is_booking_product = get_post_meta($product->get_id(), 'dreams_booking_meta_rdprice', true);
    
    if ($is_booking_product && !empty($_POST['calculated_total_amount'])) {
        return floatval($_POST['calculated_total_amount']);
    }
    
    return $price;
}

// Update cart item price
add_action('woocommerce_before_calculate_totals', 'update_booking_product_price', 10, 1);

function update_booking_product_price($cart) {
    if (is_admin() && !defined('DOING_AJAX')) return;
    
    foreach ($cart->get_cart() as $cart_item_key => $cart_item) {
        if (isset($cart_item['booking_pricing']['total_amount'])) {
            $cart_item['data']->set_price($cart_item['booking_pricing']['total_amount']);
        }
    }
}
add_action('woocommerce_before_calculate_totals', 'update_cart_item_prices', 10, 1);
function update_cart_item_prices($cart) {
    if (is_admin() && !defined('DOING_AJAX')) return;
    
    foreach ($cart->get_cart() as $cart_item_key => $cart_item) {
        if (isset($cart_item['booking_pricing']['final_total_amount'])) {
            // Set the price directly on the cart item
            $cart_item['data']->set_price($cart_item['booking_pricing']['final_total_amount']);
            
            // Debug output
            error_log('Cart item price set to: ' . $cart_item['booking_pricing']['final_total_amount']);
        }
    }
}
// Add this to ensure the price is being set
add_action('woocommerce_after_calculate_totals', 'check_booking_pricing_applied', 10, 1);

function check_booking_pricing_applied($cart) {
    if (is_admin() && !defined('DOING_AJAX')) return;
    
    foreach ($cart->get_cart() as $cart_item_key => $cart_item) {
        if (isset($cart_item['booking_pricing']['final_total_amount'])) {
            $calculated_price = $cart_item['booking_pricing']['final_total_amount'];
            $actual_price = $cart_item['data']->get_price();
            
            if ($calculated_price != $actual_price) {
                // Force update the price
                $cart_item['data']->set_price($calculated_price);
            }
        }
    }
}

// Handle coupon application for booking products
add_action('woocommerce_applied_coupon', 'handle_coupon_application_for_booking_products');

function handle_coupon_application_for_booking_products($coupon_code) {
    $coupon = new WC_Coupon($coupon_code);
    
    // Check if coupon is valid for booking products
    if ($coupon->is_valid()) {
        // Recalculate cart totals to ensure booking products stay in cart
        WC()->cart->calculate_totals();
    }
}

// Prevent coupon validation from removing booking products
add_filter('woocommerce_coupon_validate_product_id', 'validate_coupon_for_booking_products', 10, 4);

function validate_coupon_for_booking_products($valid, $product_id, $coupon, $values) {
    $is_booking_product = get_post_meta($product_id, 'dreams_booking_meta_rdprice', true);
    
    if ($is_booking_product !== '') {
        // Allow coupons to be applied to booking products
        return true;
    }
    
    return $valid;
}
// Update cart totals calculation to handle coupons properly
// add_action('woocommerce_after_calculate_totals', 'update_booking_product_totals_with_coupons', 10, 1);

function update_booking_product_totals_with_coupons($cart) {
    if (is_admin() && !defined('DOING_AJAX')) return;
    
    // Get applied coupons
    $applied_coupons = $cart->get_applied_coupons();
    
    if (!empty($applied_coupons)) {
        foreach ($cart->get_cart() as $cart_item_key => $cart_item) {
            if (isset($cart_item['booking_pricing']['total_amount'])) {
                $original_price = $cart_item['booking_pricing']['total_amount'];
                $discounted_price = $original_price;
                
                // Apply each coupon discount
                foreach ($applied_coupons as $coupon_code) {
                    $coupon = new WC_Coupon($coupon_code);
                    
                    if ($coupon->is_valid()) {
                        if ($coupon->is_type('percent')) {
                            // Percentage discount
                            $discount_percentage = $coupon->get_amount();
                            $discount_amount = ($original_price * $discount_percentage) / 100;
                            $discounted_price -= $discount_amount;
                        } elseif ($coupon->is_type('fixed_cart') || $coupon->is_type('fixed_product')) {
                            // Fixed amount discount
                            $discount_amount = $coupon->get_amount();
                            $discounted_price -= $discount_amount;
                        }
                    }
                }
                
                // Ensure price doesn't go below zero
                $discounted_price = max(0, $discounted_price);
                
                // Set the discounted price
                $cart_item['data']->set_price($discounted_price);
                
                // Store the discounted price in session for reference
                WC()->session->set('discounted_price_' . $cart_item_key, $discounted_price);
            }
        }
    }
}
// Display coupon discounts for booking products
add_action('woocommerce_cart_totals_before_order_total', 'display_booking_product_coupon_discounts');

function display_booking_product_coupon_discounts() {
    $applied_coupons = WC()->cart->get_applied_coupons();
    
    if (!empty($applied_coupons)) {
        foreach ($applied_coupons as $coupon_code) {
            $coupon = new WC_Coupon($coupon_code);
            
            if ($coupon->is_valid()) {
                $discount_amount = WC()->cart->get_coupon_discount_amount($coupon_code, false);
                
                if ($discount_amount > 0) {
                    echo '<tr class="cart-discount coupon-' . esc_attr(sanitize_title($coupon_code)) . '">';
                    echo '<th>' . sprintf(esc_html__('Coupon: %s', 'woocommerce'), esc_html($coupon_code)) . '</th>';
                    echo '<td data-title="' . esc_attr(sprintf(__('Coupon: %s', 'woocommerce'), $coupon_code)) . '">';
                    echo '-' . wc_price($discount_amount);
                    echo '</td>';
                    echo '</tr>';
                }
            }
        }
    }
}
// Prevent duplicate coupon application
add_filter('woocommerce_coupon_error', 'prevent_duplicate_coupon_application', 10, 3);

function prevent_duplicate_coupon_application($err, $err_code, $coupon) {
    if ($err_code === WC_Coupon::E_WC_COUPON_ALREADY_APPLIED) {
        // Remove the default error message and replace with a custom one
        return __('This coupon has already been applied to your booking.', 'dreamsrent');
    }
    
    return $err;
}
// Comprehensive solution for coupon handling with booking products
add_action('wp_loaded', 'handle_booking_product_coupon_issues');

function handle_booking_product_coupon_issues() {
    // 1. Prevent booking products from being removed
    add_filter('woocommerce_coupon_is_valid_for_product', function($valid, $product, $coupon, $values) {
        $is_booking_product = get_post_meta($product->get_id(), 'dreams_booking_meta_rdprice', true);
        return $is_booking_product !== '' ? true : $valid;
    }, 10, 4);
    
    // 2. Ensure booking products are always purchasable
    add_filter('woocommerce_is_purchasable', function($purchasable, $product) {
        $is_booking_product = get_post_meta($product->get_id(), 'dreams_booking_meta_rdprice', true);
        return $is_booking_product !== '' ? true : $purchasable;
    }, 10, 2);
    
    // 3. Handle coupon application (disabled to avoid double-recalculating totals)
    // add_action('woocommerce_applied_coupon', function($coupon_code) {
    //     WC()->cart->calculate_totals();
    // });
    
    // 4. Update prices when coupons are applied (disabled manual discount application)
    // add_action('woocommerce_after_calculate_totals', function($cart) {
    //     if (is_admin() && !defined('DOING_AJAX')) return;
    //     
    //     $applied_coupons = $cart->get_applied_coupons();
    //     
    //     if (!empty($applied_coupons)) {
    //         foreach ($cart->get_cart() as $cart_item_key => $cart_item) {
    //             if (isset($cart_item['booking_pricing']['total_amount'])) {
    //                 $original_price = $cart_item['booking_pricing']['total_amount'];
    //                 $discounted_price = $original_price;
    //                 
    //                 foreach ($applied_coupons as $coupon_code) {
    //                     $coupon = new WC_Coupon($coupon_code);
    //                     
    //                     if ($coupon->is_valid()) {
    //                         if ($coupon->is_type('percent')) {
    //                             $discount_percentage = $coupon->get_amount();
    //                             $discount_amount = ($original_price * $discount_percentage) / 100;
    //                             $discounted_price -= $discount_amount;
    //                         } elseif ($coupon->is_type('fixed_cart') || $coupon->is_type('fixed_product')) {
    //                             $discount_amount = $coupon->get_amount();
    //                             $discounted_price -= $discount_amount;
    //                         }
    //                     }
    //                 }
    //                 
    //                 $discounted_price = max(0, $discounted_price);
    //                 $cart_item['data']->set_price($discounted_price);
    //             }
    //         }
    //     }
    // }, 20, 1);
}
// Prevent booking products from being removed when coupons are applied
add_filter('woocommerce_coupon_is_valid_for_product', 'prevent_booking_product_removal_with_coupons', 10, 4);

function prevent_booking_product_removal_with_coupons($valid, $product, $coupon, $values) {
    // Check if this is a booking product
    $is_booking_product = get_post_meta($product->get_id(), 'dreams_booking_meta_rdprice', true);
    
    if ($is_booking_product !== '') {
        // For booking products, always return true to prevent removal
        return true;
    }
    
    return $valid;
}

// Ensure booking products are always considered purchasable
add_filter('woocommerce_is_purchasable', 'make_booking_products_always_purchasable', 10, 2);

function make_booking_products_always_purchasable($purchasable, $product) {
    $is_booking_product = get_post_meta($product->get_id(), 'dreams_booking_meta_rdprice', true);
    
    if ($is_booking_product !== '') {
        return true;
    }
    
    return $purchasable;
}


// Include and initialize vendor commissions admin
if (is_admin()) {
    require_once get_template_directory() . '/inc/admin/class-dreamsrent-commissions.php';
    add_action('init', 'dreamsrent_commissions_admin_init');
}



/*custom code */
add_filter( 'woocommerce_add_to_cart_validation', 'allow_only_one_product_in_cart', 10, 3 );
function allow_only_one_product_in_cart( $passed, $product_id, $quantity ) {

    // If cart already has something
    if ( ! WC()->cart->is_empty() ) {
        wc_add_notice( __( 'You can only book one rental at a time. Please remove the existing rental from your cart before adding a new one.', 'woocommerce' ), 'error' );
        return false;
    }

    return $passed;
}
add_filter( 'site_status_tests', function( $tests ) {
    unset( $tests['direct']['persistent_object_cache'] );
    return $tests;
  });
  
  add_filter( 'site_status_tests', function( $tests ) {
    unset( $tests['async']['background_updates'] );
    return $tests;
  });
  
  add_filter( 'site_status_tests', function( $tests ) {
    // Remove WooCommerce Action Scheduler late cron check
    if ( isset( $tests['async']['action_scheduler_queue_runner'] ) ) {
        unset( $tests['async']['action_scheduler_queue_runner'] );
    }
    return $tests;
  }, 20 );

//   Security codes
// Remove WordPress version number
remove_action('wp_head', 'wp_generator');
// Disable XML-RPC
add_filter('xmlrpc_enabled', '__return_false');
function add_security_headers() {
    header( 'X-Frame-Options: SAMEORIGIN' );
    header( 'X-Content-Type-Options: nosniff' );
    header( 'X-XSS-Protection: 1; mode=block' );
    header( 'Referrer-Policy: strict-origin-when-cross-origin' );
}
add_action( 'send_headers', 'add_security_headers' );

add_filter('rest_authentication_errors', function($result){
    if (!is_user_logged_in()) {
        return new WP_Error('rest_forbidden', 'Login required', ['status'=>401]);
    }
    return $result;
});