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.33
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 :  /opt/rms/wp-content/themes/hello-elementor-child/

Upload File :
current_dir [ Writeable ] document_root [ Writeable ]

 

Command :


[ Back ]     

Current File : /opt/rms/wp-content/themes/hello-elementor-child//functions.php
<?php
// Your code to enqueue parent theme styles
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') );
}
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' );


// 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>';
}
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;
}

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
   }
  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' ) );
  }
   
}

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>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>
   </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']);

  // 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 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';
}
// 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();
    $model_name = get_post_meta($order_id, 'model_name', 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);
    $custom_field_value = 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);

     
    // 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) {
            $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" readonly  />
        </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" readonly />
        </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" readonly />
        </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($shift_text); ?>" class="widefat" readonly />
        </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 " readonly />
        </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('Assign Location Name'); ?></h3>
               <input type="text" id="assign_location_name" name="assign_location_name" value="<?php echo esc_attr($assign_location_name); ?>" class="widefat" readonly />
          </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('woocommerce_process_shop_order_meta', 'save_custom_order_meta_and_dates');
function save_custom_order_meta_and_dates($order_id) {
  // 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() {
    global $product;
    if ( $product && $product->get_sku() ) {
        echo '<div class="product-sku" style="padding-bottom:2px; color:#db9500;font-weight: 700;font-size: 15px;">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_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: 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>*Immidiet Delivery</span>'; // Customize your note here
        return $price . $price_note;
    } elseif($purpose_of_listing === 'Sales') {
        $price_note = '<br><span style="font-size: 12px;">*Plus Applicable Taxes </span>'; // Customize your note here
        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
) );

  // 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="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="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="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="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="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>'; 
    }
  }

// 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())) {
            $account_url = site_url('/my-account/');
            echo '<a href="' . esc_url($account_url) . '" class="button non-logged-in-rfq" style="margin-left:10px;"><i class="icon icon-shopping-cart"></i>&nbsp;Rent Now</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 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);
    }
}
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);
    }
}

// Add the Purpose of Listing dropdown filter in Product Page
add_action('restrict_manage_posts', 'filter_products_by_purpose_of_listing');
function filter_products_by_purpose_of_listing() {
    global $typenow;

    if ($typenow == 'product') {
        $selected = isset($_GET['purpose_of_listing']) ? $_GET['purpose_of_listing'] : '';
        ?>
        <select name="purpose_of_listing" id="purpose_of_listing">
            <option value=""><?php _e('Filter by Purpose', 'woocommerce'); ?></option>
            <option value="Renting" <?php selected($selected, 'Renting'); ?>><?php _e('Renting', 'woocommerce'); ?></option>
            <option value="Sales" <?php selected($selected, 'Sales'); ?>><?php _e('Sales', 'woocommerce'); ?></option>
            <option value="Display" <?php selected($selected, 'Display'); ?>><?php _e('Display', 'woocommerce'); ?></option>
        </select>
        <?php
    }
}
// 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');

// Displaying Short Description content in "Category Product List"
function add_short_description_to_product_list() {
    // Get the current product object
    $product = wc_get_product(get_the_ID());
    
    if ($product && $product->get_short_description()) {
        echo '<div class="woocommerce-product-details__short-description">';
        // Output the short description
        echo apply_filters('woocommerce_short_description', $product->get_short_description());
        echo '</div>';
    }
}
add_action('woocommerce_after_shop_loop_item_title', 'add_short_description_to_product_list', 25);

// 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 

// filter by status --- Bhaskara

// custom filter dropdown for 'status'
add_action('restrict_manage_posts', 'filter_by_custom_status');
function filter_by_custom_status() {
    global $typenow;

    if ($typenow == 'product') {
        $selected_status = isset($_GET['product_status_filter']) ? esc_attr($_GET['product_status_filter']) : '';
        ?>
        <select name="product_status_filter" id="dropdown_product_status_filter">
            <option value=""><?php _e('Filter by Status', 'woocommerce'); ?></option>
            <option value="idle" <?php selected($selected_status, 'idle'); ?>>IDLE</option>
            <option value="ONRENT" <?php selected($selected_status, 'ONRENT'); ?>>ONRENT</option>
            <option value="Sold" <?php selected($selected_status, 'Sold'); ?>>Sold</option>
            <option value="OnRent_Breakdown" <?php selected($selected_status, 'OnRent_Breakdown'); ?>>OnRent_Breakdown</option>
            <option value="Idle_Breakdown" <?php selected($selected_status, 'Idle_Breakdown'); ?>>Idle_Breakdown</option>
        </select>
        <?php
    }
}

// Modify the product query to filter by the custom 'status' meta field
add_action('pre_get_posts', 'filter_products_by_custom_status');
function filter_products_by_custom_status($query) {
    global $typenow, $pagenow;

    if ($typenow == 'product' && is_admin() && $pagenow == 'edit.php' && isset($_GET['product_status_filter']) && !empty($_GET['product_status_filter'])) {
        $status_filter = esc_attr($_GET['product_status_filter']);

        $meta_query = $query->get('meta_query');
        if (!is_array($meta_query)) {
            $meta_query = array();
        }

        $meta_query[] = array(
            'key'     => 'status',
            'value'   => $status_filter,
            'compare' => '='
        );

        $query->set('meta_query', $meta_query);
    }
}

// end of filter

// 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 class="shop_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) {
            ?>
            <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); ?>" 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); ?>" />
                </td>
                <td>
                    <select name="log_approve_status[<?php echo esc_attr($log->contract_id); ?>]">
                        <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" name="save_log_approval">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);

        // 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();

                // Reduce stock
                $product = wc_get_product($product_id);
                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();

                        // 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()
                        ));
                    }
                }
            }

            // Update the order status to 'equipmentassigned'
            $order->update_status('equipmentassigned', 'Equipment added to Contract.');
        }
    }
}

// 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 ( 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);
                            window.location.reload(); // Reload the page after successful login
                        } 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'); 
    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']);
    $location = sanitize_text_field($_POST['location']);
    $application = sanitize_text_field($_POST['application']);

    $product = wc_get_product($product_id);
    $base_price = $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;

    $cart_item_data = [
        'rfq_data' => [
            'start_date' => $start_date,
            'end_date' => $end_date,
            'shift' => $shift,
            'location' => $location,
            'application' => $application,
            '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');

// // 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() {
    if (is_checkout()) {
        wp_enqueue_script('custom-checkout', get_stylesheet_directory_uri() . '/custom-checkout.js', array('jquery'), null, true);
    }
}

// Cart Count--08-03-2025
function woo_cart_count_shortcode() {
    $count = WC()->cart->get_cart_contents_count();
    return '<span id="cart_icon cart-count">' . $count . '</span>';
    
}
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;
}

// ---------------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'])) {
            $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 (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');

Youez - 2016 - github.com/yon3zu
LinuXploit