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.47
Web Server : Apache/2.4.52 (Ubuntu)
System : Linux ip-11-115-0-196 6.8.0-1039-aws #41~22.04.1-Ubuntu SMP Thu Sep 11 10:54:48 UTC 2025 x86_64
User : www-data ( 33)
PHP Version : 8.3.17
Disable Function : NONE
MySQL : OFF  |  cURL : ON  |  WGET : ON  |  Perl : ON  |  Python : OFF  |  Sudo : ON  |  Pkexec : ON
Directory :  /var/www/html/rentals_updated/wp-content/plugins/woocommerce-rfq/

Upload File :
current_dir [ Writeable ] document_root [ Writeable ]

 

Command :


[ Back ]     

Current File : /var/www/html/rentals_updated/wp-content/plugins/woocommerce-rfq/admin-rfq.php
<?php
// Ensure the file is not accessed directly
if (!defined('ABSPATH')) {
    exit;
}


// Add admin menu
add_action('admin_menu', 'rfq_admin_menu');

function rfq_admin_menu() {
    add_menu_page(
        'RFQ',    // Page title
        'Request For Quote',    // Menu title
        'manage_options',    // Capability
        'rfq-dashboard',     // Menu slug
        'rfq_display_quotes',// Callback function
        'dashicons-list-view', // Icon URL
        6                    // Position
    );
	add_submenu_page(null, //parent slug
	'Edit Request Quotes', //page title
	'Edit', //menu title
	'manage_options', //capability
	'edit-quote', //menu slug
	'rfq_edit'); //function

    add_submenu_page(
        null,      
        'Create RFQ',     
        null,      
        'manage_options',  
        'create-rfq',    
        'rfq_create'     
    );
    add_submenu_page(
        'rfq-dashboard', 
        'Add New RFQ', 
        'Add New RFQ', 
        'manage_options', 
        'add-new-rfq', 
        'rfq_add_new_page' 
    );
}

function rfq_create() {
    global $wpdb;
    $current_user = wp_get_current_user();  // Get the current logged-in user

    // Initial empty values for form fields
    $results = (object) [
        'user_name' => '',
        'user_email' => '',
        'product_id' => '',
        'product_name' => '',
        'start_date' => '',
        'end_date' => '',
        'shift' => '',
        'calculated_price' => '',
        'rfq_status' => '',
        'location' => '',  
        'region' => '', 
    ];

    // Get all products for the dropdown
    $sql = "SELECT ID, post_title FROM wp_posts WHERE post_status = 'publish' AND post_type = 'product'";
    $products = $wpdb->get_results($sql);

    // Check if an enquiry_id is present in the URL
    if (isset($_GET['enquiry_id']) && is_numeric($_GET['enquiry_id'])) {
        $enquiry_id = intval($_GET['enquiry_id']);

        // Fetch the lead_email, product_name, location, region, rental_startdate, and rental_enddate associated with the enquiry_id from wp_leads
        $lead_data = $wpdb->get_row($wpdb->prepare(
            "SELECT lead_email, product_name, location, region, rental_startdate, rental_enddate FROM wp_leads WHERE id = %d",
            $enquiry_id
        ));

        // Populate form fields with retrieved data
        if ($lead_data) {
            $results->user_email = $lead_data->lead_email;
            $results->user_name = $wpdb->get_var($wpdb->prepare(
                "SELECT full_name FROM wp_leads WHERE lead_email = %s",
                $lead_data->lead_email
            ));
            $results->product_name = $lead_data->product_name;
            $results->location = $lead_data->location;
            $results->region = $lead_data->region;
            $results->start_date = $lead_data->rental_startdate;
            $results->end_date = $lead_data->rental_enddate;
            // count number of days
            if ($results->start_date && $results->end_date) {
                $start_date = new DateTime($results->start_date);
                $end_date = new DateTime($results->end_date);
                $date_diff = $start_date->diff($end_date);
                $results->number_of_days = $date_diff->days + 1; // Add 1 to include both start and end dates
            }
            

            if ($results->product_name) {
                $results->product_id = $wpdb->get_var($wpdb->prepare(
                    "SELECT p.ID 
                     FROM wp_posts p
                     INNER JOIN wp_postmeta pm ON p.ID = pm.post_id
                     WHERE p.post_title = %s 
                     AND p.post_type = 'product'
                     AND pm.meta_key = 'purpose_of_listing' 
                     AND pm.meta_value = 'display'",
                    $results->product_name
                ));
            }
            
        }
    }
    // If product ID is available, fetch the calculated price based on purpose_of_listing
    if ($results->product_id) {
        // Check if the product has a 'display' purpose of listing
        $purpose_of_listing = $wpdb->get_var($wpdb->prepare(
            "SELECT meta_value FROM wp_postmeta 
             WHERE post_id = %d AND meta_key = 'purpose_of_listing' 
             AND meta_value = 'display'",
            $results->product_id
        ));
    
        if ($purpose_of_listing) {
            // Fetch the actual price from the '_price' meta key
            $actual_price = $wpdb->get_var($wpdb->prepare(
                "SELECT meta_value FROM wp_postmeta 
                 WHERE post_id = %d AND meta_key = '_price'",
                $results->product_id
            ));
    
            // If the '_price' value is empty or null, default to '100'
            $results->calculated_price = !empty($actual_price) ? $actual_price : '100';
        }
    }
    

    if (isset($_POST['save_rfq'])) {
        // Sanitize and retrieve the posted data
        $user_name = sanitize_text_field($_POST['user_name']);
        $user_email = sanitize_email($_POST['user_email']);
        $product_id = $results->product_id;
        $product_name = $results->product_name;
        $start_date = $results->start_date;
        $end_date = $results->end_date;
        $shift = intval($_POST['shift']);
        $calculated_price = sanitize_text_field($_POST['calculated_price']);
        $rfq_status = 'Request Received';
        $location = sanitize_text_field($results->location);
        $region = sanitize_text_field($results->region);
        $requested_on = current_time('mysql');
        $created_by = $current_user->user_email;

        // Retrieve the enquiry_id from Enquiry URL
       // Aseema 
        $enquiry_id = isset($_GET['enquiry_id']) ? intval($_GET['enquiry_id']) : 0;

        // Generate the rmsID
        $table_name = $wpdb->prefix . "request_quote";
        $max_value = $wpdb->get_var("SELECT MAX(id) FROM $table_name");

        // If no value found, default to 0
        if (is_null($max_value)) {
            $max_value = 0;
        }

        // Increment the value by 1
        $rmsID = $max_value + 1;
        $user = get_user_by('email', $user_email);
        if ($user && !is_wp_error($user)) {
            $user_id = $user->ID; 
        } 
        // Insert the new RFQ into the wp_request_quote table
        $insert_result = $wpdb->insert(
            $table_name,
            [
                'user_id' => $user_id,
                'user_name' => $user_name,
                'user_email' => $user_email,
                'product_id' => $product_id,
                'start_date' => $start_date,
                'end_date' => $end_date,
                'shift' => $shift,
                'calculated_price' => $calculated_price,
                'rfq_status' => $rfq_status,
                'enquiry_id' => $enquiry_id,
                'product_name' => $product_name,
                'requested_on' => $requested_on,
                'rmsID' => "RMS00".$rmsID,
                'location' => $location,
                'region' => $region,
                'created_by' => $created_by,
            ]
        );

        // Check if insert was successful
        if ($insert_result === false) {
            // Output the last error
            echo '<div class="error"><p>Failed to create RFQ. Error: ' . $wpdb->last_error . '</p></div>';
        } else {
            echo '<div class="updated"><p>RFQ Created Successfully!</p></div>';
            echo '<script type="text/javascript">
            setTimeout(function() {
                window.location.href = "' . esc_url(admin_url('admin.php?page=rfq-dashboard')) . '";
            }, 2000);
        </script>';
        }
    }
    $email_exists = true;
    if (!empty($results->user_email)) {
        $email_exists = $wpdb->get_var($wpdb->prepare(
            "SELECT COUNT(*) FROM {$wpdb->users} WHERE user_email = %s",
            $results->user_email
        )) > 0;
    }

    // Form rendering starts here
    echo '<h2>Create RFQ</h2>';
    echo '<form method="post">';
    echo '<input type="hidden" id="email_exists_flag" value="' . esc_attr($email_exists ? '1' : '0') . '">';
    
    echo '<input type="hidden" name="create_id" value="new">';

    echo '<table class="form-table">';

    // User Name
    echo '<tr>';
    echo '<th><label for="user_name">User Name</label></th>';
    echo '<td><input type="text" name="user_name" id="user_name" value="' . esc_attr($results->user_name) . '" class="regular-text" required readonly></td>';
    echo '</tr>';

    // User Email
    
    echo '<tr>';
    echo '<th><label for="user_email">User Email</label></th>';
    echo '<td><input type="email" name="user_email" id="user_email" value="' . esc_attr($results->user_email) . '" class="regular-text" required readonly></td>';
    echo '</tr>';
    
    // Product Name
    echo '<tr>';
    echo '<th><label for="product_id">Product Name</label></th>';
    echo '<td><input type="text" name="product_name" id="product_name" value="' . esc_attr($results->product_name) . '" class="regular-text" required readonly></td>';
    echo '</tr>';

    // Start Date
    echo '<tr>';
    echo '<th><label for="rfq_startdate">Start Date</label></th>';
    echo '<td><input type="date" name="rfq_startdate" id="rfq_startdate" value="' . esc_attr($results->start_date) . '" class="regular-text rfq-date-field" required readonly></td>';
    echo '</tr>';

    // End Date
    echo '<tr>';
    echo '<th><label for="rfq_enddate">End Date</label></th>';
    echo '<td><input type="date" name="rfq_enddate" id="rfq_enddate" value="' . esc_attr($results->end_date) . '" class="regular-text rfq-date-field" required readonly></td>';
    echo '</tr>';

    // Shift
    echo '<tr>';
    echo '<th><label for="rfqshift">Shift</label></th>';
    echo '<td>';
    echo '<select class="form-control rfq-date-field" id="rfqshift" name="shift" style="background:unset !important;pointer-events: none;" required  >';
    echo '<option value="">Select Shift</option>';
    echo '<option value="1" selected>1 Shift (8 hours)</option>';
    
    echo '</select>';
    echo '</td>';
    echo '</tr>';

    // Listing Price
    echo '<tr>';
    echo '<th><label for="pricingtxt">Price</label></th>';
    echo '<td><input type="number" name="calculated_price" id="pricingtxt" value="' . esc_attr($results->calculated_price) . '" class="regular-text" readonly></td>';
    echo '</tr>';

    echo '<input type="hidden" id="total_price_value" value="<?php echo esc_attr($total_price); ?>">';

    // RFQ Status
    echo '<tr>';
    echo '<th><label for="rfq_status">RFQ Status</label></th>';
    echo '<td><input type="text" name="rfq_status" id="rfq_status" value="Request Received" class="regular-text" readonly></td>';
    echo '</tr>';

    // Location (Optional display)
    echo '<tr>';
    echo '<th><label for="location">Location</label></th>';
    echo '<td><input type="text" name="location" id="location" value="' . esc_attr($results->location) . '" class="regular-text" readonly></td>';
    echo '</tr>';

    // Region (Optional display)
    echo '<tr>';
    echo '<th><label for="region">Region</label></th>';
    echo '<td><input type="text" name="region" id="region" value="' . esc_attr($results->region) . '" class="regular-text" readonly></td>';
    echo '</tr>';

    echo '</table>';

    echo '<p><input type="submit" name="save_rfq" class="button-primary" id="save_rfq_btn" value="Create RFQ"></p>';

    echo '</form>';

    // Display the warning message if the email is not registered
    if (!$email_exists) {
        echo '<div id="email-warning" style="color: red; margin-bottom: 15px; font-weight: bold;">';
        echo '<p style="font-size:14px;">The email entered is not registered. Please create usercode first with the same email-id.</p>';
        echo '</div>';
    }
    ?>
    <script type="text/javascript">
document.addEventListener('DOMContentLoaded', function() {
    var saveButton = document.getElementById('save_rfq_btn');
    var emailWarning = document.getElementById('email-warning');
    var emailExistsFlag = document.getElementById('email_exists_flag').value === '1';

    // Disable the button and show the warning if email is not registered
    if (!emailExistsFlag) {
        saveButton.disabled = true;
        emailWarning.style.display = 'block';
    } else {
        saveButton.disabled = false;
        emailWarning.style.display = 'none';
    }
    // Get references to the relevant DOM elements
    var shiftSelect = document.getElementById('rfqshift');
    var priceInput = document.getElementById('pricingtxt');
    var numberOfDays = <?php echo json_encode($results->number_of_days); ?>;
    var basePrice = <?php echo json_encode($results->calculated_price); ?>;

    // Function to update the calculated price
    function updatePrice() {
        var shift = parseInt(shiftSelect.value, 10);
        if (isNaN(shift) || shift <= 0) {
            shift = 1; // Default to 1 if shift is not valid
        }
        var totalPrice = numberOfDays * shift * basePrice;
        priceInput.value = totalPrice.toFixed(2); // Update the price field
    }
    // Attach the updatePrice function to the change event of the shift dropdown
    shiftSelect.addEventListener('change', updatePrice);

    // Initialize the price calculation on page load
    updatePrice();
});
</script>

    <?php
    
}


function rfq_enqueue_custom_styles_and_scripts($hook) {
    // Load only on the RFQ dashboard page
    if ($hook != 'toplevel_page_rfq-dashboard') {
        return;
    }

    // Enqueue Bootstrap CSS
    wp_enqueue_style('bootstrap-css', 'https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css');

    // Enqueue DataTables CSS
    wp_enqueue_style('datatables-css', 'https://cdn.datatables.net/1.10.24/css/jquery.dataTables.min.css');
	
	// Enqueue Font Awesome CSS
    wp_enqueue_style('fontawesome-css', 'https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.3/css/all.min.css');	

    // Enqueue css for multiselct
    wp_enqueue_style('multiselct', 'https://cdnjs.cloudflare.com/ajax/libs/bootstrap-multiselect/0.9.16/css/bootstrap-multiselect.css');
   

    // Enqueue your custom CSS
    wp_enqueue_style('rfq-custom-styles', plugin_dir_url(__FILE__) . 'css/custom-style.css');

    // Enqueue jQuery and DataTables JS
    wp_enqueue_script('jquery');
    wp_enqueue_script('datatables-js', 'https://cdn.datatables.net/1.10.24/js/jquery.dataTables.min.js', array('jquery'), '1.10.24', true);
	

    // Enqueue Bootstrap JS and your custom JS
    wp_enqueue_script('bootstrap-js', 'https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js', array('jquery'), '4.5.2', true);
    wp_enqueue_script('rfq-custom-scripts', plugin_dir_url(__FILE__) . 'js/custom-script.js', array('jquery'), '1.0', true);
	
	
}

add_action('admin_enqueue_scripts', 'rfq_enqueue_custom_styles_and_scripts');

// Fetch data from the database and region wise filteration- Aseema
function rfq_get_quotes($status_filter = '', $user_region = '', $user_roles = []) {
    global $wpdb;
    $table_name = $wpdb->prefix . 'request_quote';

    $current_user = wp_get_current_user();
    $user_roles = $current_user->roles;
    $rue_region_location = get_user_meta($current_user->ID, 'ba_region_location', true);
    $sales_rep_region_location = get_user_meta($current_user->ID, 'sales_rep_region_location', true);

    // Base query
    $query = "SELECT * FROM $table_name WHERE 1=1";

    // Adding conditions for roles and region
    if (in_array('rue_manager', $user_roles) && !empty($rue_region_location)) {
        $query .= $wpdb->prepare(" AND region = %s", $rue_region_location);
    } 
    if (in_array('sales_representative', $user_roles) && !empty($sales_rep_region_location)) {
        $query .= $wpdb->prepare(" AND region = %s", $sales_rep_region_location);
    } 

    // Adding condition for status filter
    if (!empty($status_filter)) {
        $query .= $wpdb->prepare(" AND rfq_status = %s", $status_filter);
    }

    $query .= " ORDER BY id DESC";

    // Fetch all data based on the query
    $results = $wpdb->get_results($query, ARRAY_A);

    return $results;
}

// Display the data
function rfq_display_quotes() {
    global $wpdb;

    $current_user = wp_get_current_user();
    $user_roles = $current_user->roles;
    $user_region = get_user_meta($current_user->ID, 'ba_region_location', true);
    $user_for_sale_region = get_user_meta($current_user->ID, 'sales_rep_region_location', true);
    // Check if the current page matches rfq-dashboard
    $current_page = isset($_GET['page']) ? sanitize_text_field($_GET['page']) : '';
    // Check if a filter by status is applied
    $status_filter = '';
    if ($current_page === 'rfq-dashboard' && isset($_GET['status'])) {
        $status_filter = sanitize_text_field($_GET['status']);
    }

    // Fetch the count of each status
    $region_condition = "";
    if (in_array('rue_manager', $user_roles) && !empty($user_region)) {
        $region_condition = $wpdb->prepare("WHERE region = %s", $user_region);
    } elseif (in_array('sales_representative', $user_roles) && !empty($user_for_sale_region)) {
        $region_condition = $wpdb->prepare("WHERE region = %s", $user_for_sale_region);
    }

    $statuses_count_query = "
        SELECT rfq_status, COUNT(*) as count
        FROM {$wpdb->prefix}request_quote
        $region_condition
        GROUP BY rfq_status
    ";
    $statuses_count = $wpdb->get_results($statuses_count_query, OBJECT_K);

    // Fetch all distinct RFQ statuses
    $statuses_query = "SELECT DISTINCT rfq_status FROM {$wpdb->prefix}request_quote $region_condition";
    $results = $wpdb->get_results($statuses_query);

    // Initialize an array to hold the links with counts
    $rfq_statuses = array();

    // Loop through the results and create a link for each status with its count
    foreach ($results as $result) {
        $status = $result->rfq_status;
        $count = isset($statuses_count[$status]) ? $statuses_count[$status]->count : 0;
        // Add the link to the array only if count > 0
        if ($count > 0) {
            // Modify this line to directly add filter links without 'users.php' link
            if ($current_page === 'rfq-dashboard') {
                // Ensure the current page is rfq-dashboard before adding filter links
                $rfq_statuses[] = '<a href="?page=rfq-dashboard&status=' . urlencode($status) . '">' . esc_html($status) . ' (' . $count . ')</a>';
            } else {
                // For other pages, simply display the status count without filter links
                $rfq_statuses[] = esc_html($status) . ' (' . $count . ')';
            }
        }
    }
    $quotes = rfq_get_quotes($status_filter, $user_region, $user_roles);
    ?>
    <div class="wrap rfq-wrap">
        <h1 class="wp-heading-inline mb-2 font-weight-bold">RFQ- Request For Quote</h1>

        <!-- button and filter added -->
        <div  style="display:flex; margin-bottom:20px;">
        <div class="rfq-export-btn">
                    <button id="rfqexport" class="btn custom-btn" style="padding: 2px 21px 4px 21px;" >Export</button>
                </div>
                <div class="multi-rfq-column" style="margin-left:20px;"><?php include 'multiselect-rfq-column.php'; ?></div>
                <div><span style="margin-left:20px;">
                    Filter by status: <span class="rfq-filter-status"><?php echo implode(' ', $rfq_statuses); ?></span>
                </span></div>
            </div>
            <!-- /end button and filter added -->
        <div class="table-responsive">
            <table id="rfq-table" class="table display pb-30 dataTable table-data">
                <thead style="background-color:#FFBD2B;">
                <tr>
                        <th scope="row" class="manage-column sticky-col">Sr. No</th>
                        <th scope="col" class="manage-column">RMS ID</th>
                        <th scope="col" class="manage-column">RMS Order ID</th>
                        <th scope="col" class="manage-column">Customer Name</th>
                        <th scope="col" class="manage-column">Customer Email</th>
						<th scope="col" class="manage-column">Product ID</th>
						<th scope="col" class="manage-column">Product Name</th>
                        <th scope="col" class="manage-column">Start Date</th>
                        <th scope="col" class="manage-column">End Date</th>
                        <th scope="col" class="manage-column">Shifts</th>
                        <th scope="col" class="manage-column">Location</th>
                        <th scope="col" class="manage-column">Offered Price</th>
						<th scope="col" class="manage-column">Discount</th>
                        <th scope="col" class="manage-column">Final Price</th>
                        <th scope="col" class="manage-column">Customer Type</th>
                        <th scope="col" class="manage-column">RFQ Status</th>
<!--                         <th scope="col" class="manage-column">Application Type</th> -->
                        <th scope="col" class="manage-column">Requested On</th>
                        <th scope="col" class="manage-column">Quote Status</th>
                        <th scope="col" class="manage-column" style="background-color:#FFBD2B;">Actions
                        </th>
                    </tr>
                </thead>
                <tbody>
                    <?php if ($quotes) : ?>
                        <?php $count = 1; ?>
                        <?php foreach ($quotes as $quote) : ?>
                        <?php
                                    global $wpdb;

                                    // Check if rfq_id exists in wp_quotation table
                                    $rfq_id = $quote['id']; // Assuming 'id' is the rfq_id
                                    $exists = $wpdb->get_var($wpdb->prepare(
                                        "SELECT COUNT(*) FROM wp_quotation WHERE rfq_id = %d",
                                        $rfq_id
                                    ));
                    
                                    // Determine the action status and customer status
                                    if ($exists > 0) {
                                        $generateQuoteStatus = 'Quote Generated';
                                        // $actionSts = '<a href="" title="Generate Quote"><i class="fas fa-paper-plane" alt="Generate Quote"></i></a>';
                                    } else {
                                        $generateQuoteStatus = 'Not Yet Generated';
                                        // $actionSts = '<a href="https://gmmco.connecticons.app/customer/registration/portal" title="Register Customer" target="_blank"><i class="fa fa-link" aria-hidden="true" alt="Register Customer"></i></a>';
                                    }
                                    $metaData = get_user_meta( $quote['user_id'], 'sap_customer_id', $single = false );
                                    if(!empty($metaData[0])){
                                        // $actionSts =  '<a href="" title="Generate Quote"><i class="fas fa-paper-plane" alt="Generate Quote"></i></a>';
                                        $customerStatus = 'Exisiting Customer';
                                    }else{
                                        // $actionSts = '<a href="https://gmmco.connecticons.app/customer/registration/portal" title="Register Customer
                                        // " target="_blank"><i class="fa fa-link" aria-hidden="true" alt="Register Customer"></i></a>';
                                        $customerStatus = 'New Customer';
                                    }                                    
                                    ?>
                                    <tr>
                                <td class="sticky-col"><?php echo $count++; ?></td>
                                <td><?php echo esc_html($quote['rmsID']); ?></td>
                                <td><?php echo esc_html($quote['order_id']); ?></td>
                                <td><?php echo esc_html($quote['user_name']); ?></td>
                                <td><?php echo esc_html($quote['user_email']); ?></td>
								<td><?php echo esc_html($quote['product_id']); ?></td>
								<td><?php echo esc_html($quote['product_name']); ?></td>
                                <td><?php echo esc_html(date('d-m-Y', strtotime($quote['start_date']))); ?></td>
                                <td><?php echo esc_html(date('d-m-Y', strtotime($quote['end_date']))); ?></td>
                                <td><?php echo esc_html($quote['shift']); ?></td>
                                <td><?php echo esc_html($quote['location'] ? $quote['location'] : 'N/A'); ?></td>
                                <td><?php echo esc_html($quote['calculated_price']); ?></td>
								<td><?php echo esc_html($quote['rfqdiscount']); ?>%</td>
                                <td>
                                    <?php 
                                    if (is_null($quote['final_price'])) {
                                        echo esc_html($quote['calculated_price']);
                                    } else {
                                        echo esc_html($quote['final_price']);
                                    }
                                    ?>
                                </td>
                                <td><?php echo esc_html($customerStatus); ?></td>
		                        <td> <?php 
                                     if($generateQuoteStatus != 'Quote Generated'){
                                        echo esc_html($quote['rfq_status']);
                                     }
                                     else{
                                        echo "Completed";
                                     }
                                    ?></td>
                                <!-- Completed status not saved in database. -->
                                <td>
                                   <?php echo esc_html(date("d-m-y", strtotime($quote['requested_on']))); ?>
                                </td>
                                
<!--                                 <td>
								<?php 
								echo $quote['application'];
								?>
								</td> -->
                                <td><?php echo esc_html($generateQuoteStatus); ?></td>
                                <td> <?php if ($generateQuoteStatus == 'Quote Generated'): ?>
                                        <a href="javascript:void(0);" style="pointer-events: none; opacity: 0.5;"><i class="fas fa-edit"></i></a>
                                    <?php else: ?>
                                        <a href="<?php echo admin_url('admin.php?page=edit-quote&id=' . $quote['id']); ?>"><i class="fas fa-edit"></i></a>
                                    <?php endif; ?></td> 
                                <!-- When quote is generated the diable the edit option -->
                                <td>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                    <?php else : ?>
                        <tr>
                            <td colspan="11" class="no-quotes">No quotes found.</td>
                        </tr>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>
    </div>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js" integrity="sha384-ZMP7rVo3mIykV+2+9J3UJ46jBk0WLaUAdn689aCwoqbBJiSnjAK/l8WvCWPIPm49" crossorigin="anonymous"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-multiselect/0.9.16/js/bootstrap-multiselect.min.js"></script>
    <style>
        #rfq-table_wrapper .dataTables_scroll .dataTables_scrollHead .dataTables_scrollHeadInner table {
            margin-left:unset !important;
            margin:auto !important;
        }
        .dataTables_scrollHeadInner {
            width:unset !important;
        }
        </style>
    <script>
        // Initialize DataTable
        jQuery(document).ready(function($) {
            $('#rfq-table').DataTable();
            function exportTableToCSV(filename) {
                var csv = [];
                var rows = document.querySelectorAll("#rfq-table tbody tr");

                // Get table headers (column names)
                var headers = [];
                var actionColumnIndex = -1; // Variable to store the index of the "Action" column
                var headerCols = document.querySelectorAll("#rfq-table thead th");
                for (var k = 0; k < headerCols.length; k++) {
                    var headerText = headerCols[k].innerText.trim().toLowerCase(); // Normalize header text
                    if (headerText === "actions") {
                        actionColumnIndex = k; // Save the index of the "Action" column
                    } else {
                        headers.push(headerCols[k].innerText.trim());
                    }
                }
                csv.push(headers.join(",")); // Push headers to CSV
                console.log("Headers:", headers); // Debugging log
                console.log("Action Column Index:", actionColumnIndex); // Debugging log

                // Get table rows data
                for (var i = 0; i < rows.length; i++) {
                    var row = [];
                    var cols = rows[i].querySelectorAll("td, th");

                    for (var j = 0; j < cols.length; j++) {
                        if (j !== actionColumnIndex) { // Skip the "Action" column data
                            row.push(cols[j].innerText.trim()); // Trim cell content
                        }
                    }

                    csv.push(row.join(","));
                }

                // Download CSV file
                downloadCSV(csv.join("\n"), filename);
            }

            function downloadCSV(csv, filename) {
                var csvFile;
                var downloadLink;

                // CSV file
                csvFile = new Blob([csv], { type: "text/csv" });

                // Download link
                downloadLink = document.createElement("a");

                // File name
                downloadLink.download = filename;

                // Create a link to the file
                downloadLink.href = window.URL.createObjectURL(csvFile);

                // Hide download link
                downloadLink.style.display = "none";

                // Add the link to DOM
                document.body.appendChild(downloadLink);

                // Click download link
                downloadLink.click();
            }

    // Attach event listener to export button
    document.getElementById("rfqexport").addEventListener("click", function() {
        exportTableToCSV("RFQ-DATA.csv");
    });
    jQuery('#rfq_status').on('change', function() {
        var rfq_status = jQuery(this).val();
        if (rfq_status === 'Generate Quote') {
            var user_name = jQuery('#user_name').val();
            var user_email = jQuery('#user_email').val();
            var start_date = jQuery('#rfq_startdate').val();
            var end_date = jQuery('#rfq_enddate').val();
            var shift = jQuery('#rfqshift').val();
            var product_id = jQuery('#product_id').val();
            var user_id = jQuery('#user_id').val();
            var calculated_price = $('#pricingtxt').val();
            var final_price = jQuery('#final_pricetxt').val();
            var rfqdiscount = jQuery('#rfqdiscount').val();

            
        }
    });
            });
    </script>
    <?php
}
// Display the data
function rfq_edit() {
	global $wpdb;
	$id = $_REQUEST['id'];
	$table_name = $wpdb->prefix . 'request_quote';

    // Fetch all data from the wp_request_quote table
    $results = $wpdb->get_row("SELECT * FROM $table_name where id=$id");

     // Use prepared statements to prevent SQL injection
     $user_email = $results->user_email; // Assuming $results->user_email is already sanitized
     $userdetails = $wpdb->get_row($wpdb->prepare("SELECT ID FROM `wp_users` WHERE user_email = %s", $user_email));
     
     if ($userdetails) {
         // User found, you can access the ID
         $user_id = $userdetails->ID;
        // echo 'User ID: ' . $user_id;
     } else {
         // Handle case where no user is found
        // echo 'No user found with that email.';
     }

    // Get user meta sap_customer_id
    $sap_customer_id = get_user_meta($user_id, 'sap_customer_id', true);
    $rfq_status = empty($sap_customer_id) ? 'Request Received' : 'Customer Registered';

	// Check if RFQ ID already exists in wp_quotation table
    $quotation_table_name = $wpdb->prefix . 'quotation';
    $existing_quotation = $wpdb->get_row("SELECT * FROM $quotation_table_name WHERE rfq_id = $id");

    if ($existing_quotation) {
        $quote_already_generated = true;
        ?>
        <div style="color: red; font-weight: bold;font-size:20px; margin-top:10px;">Quote generated.</div>
        <?php
    } else {
        $quote_already_generated = false;
    }

    ?>
	<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/selectize/dist/css/selectize.default.css">
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/selectize/dist/js/standalone/selectize.min.js"></script>
    <h2>Edit Request For Quote</h2>
	<form method="post">
        <input type="hidden" name="edit_id" value="<?php echo esc_attr($results->id); ?>">
            <table class="form-table">
                <tr>
                    <th><label for="user_name">User Name</label></th>
                    <td><input type="text" name="user_name" id="user_name"
                            value="<?php echo esc_attr($results->user_name); ?>" class="regular-text" readonly></td>
                </tr>
                <tr>
                    <th><label for="user_email">User Email</label></th>
                    <td><input type="text" name="user_email" id="user_email"
                            value="<?php echo esc_attr($results->user_email); ?>" class="regular-text" readonly></td>
                </tr>
                <tr>
                    <th><label for="product_id">Product Name</label></th>
                    <td>
                        <select style="display:none;" name="product_id" id="product_id" class="regular-text">
                            <option value="">Select Product</option>
                            <?php
                            $sql = "SELECT ID,post_title FROM wp_posts WHERE post_status = 'publish' and post_type = 'product'";
                            $result = $wpdb->get_results($sql);
                            $opt = '';
                            foreach ($result as $list) {
                                if ($results->product_id == $list->ID) {
                                    $selected = "selected";
                                } else {
                                    $selected = '';
                                }
                                ;
                                $opt .= '<option value="' . $list->ID . '" ' . $selected . '>' . $list->post_title . '</option>';
                            }
                            echo $opt;
                            ?>
                        </select>
                        <input type="text" name="product_name" id="product_name"
                        value="<?php echo esc_attr($results->product_name); ?>" class="regular-text" readonly></td>
                           
                </tr>
                <tr>
                    <th><label for="rfq_startdate">Start Date</label></th>
                    <td><input type="date" name="rfq_startdate" id="rfq_startdate" onkeydown="return false;"
                            value="<?php echo esc_attr($results->start_date); ?>" class="regular-text rfq-date-field" required></td>
                </tr>
                <tr>
                    <th><label for="rfq_enddate">End Date</label></th>
                    <td><input type="date" name="rfq_enddate" id="rfq_enddate" onkeydown="return false;"
                            value="<?php echo esc_attr($results->end_date); ?>" class="regular-text rfq-date-field" required></td>
                </tr>
<!--                 <tr>
                    <th><label for="user_email">Shift</label></th>
                    <td>
                        <select class="form-control rfq-date-field" id="rfqshift" name="shift">
                            <option value="">Select Shift</option>
                            <?php
                            ;
                            ?>
                            <option value="1" <?php if ($results->shift == 1) {
                                echo "selected";
                            } ?>>1 Shift (8 hours)</option>
                            <option value="2" <?php if ($results->shift == 2) {
                                echo "selected";
                            } ?>>2 Shifts (16 hours)</option>
                            <option value="3" <?php if ($results->shift == 3) {
                                echo "selected";
                            } ?>>3 Shifts (24 hours)</option>
                    </td>
                </tr> -->
                <tr>
                    <th><label for="calculated_price">Listing Price</label></th>
                    <td>
                        <input type="text" name="calculated_price" id="pricingtxt"
                            value="<?php echo esc_attr($results->calculated_price); ?>" class="regular-text" readonly>
                    </td>
                </tr>
                <tr>
                    <th><label for="region">Region</label></th>
                    <td>
                        <input type="text" name="region" id="region"
                            value="<?php echo esc_attr($results->region); ?>" class="regular-text" readonly>
                    </td>
                </tr>
                <tr>
                    <th><label for="location">Location</label></th>
                    <td>
                        <input type="text" name="location" id="location"
                            value="<?php echo esc_attr($results->location); ?>" class="regular-text" readonly>
                    </td>
                </tr>
                <tr>
                    <th><label for="rfq_status">RFQ Status</label></th>
                    <td>
                        <input type="text" name="rfq_status" id="rfq_status" value="<?php echo esc_attr($results->rfq_status); ?>"
                            class="regular-text" readonly>
                    </td>
                </tr>
            </table>
            <div id="rfq-spinner" style="display:none;">
                <img style="width:22px;" src="<?php echo plugin_dir_url(
                    __FILE__
                ); ?>spinner.gif" alt="Loading...">
            </div>
            <p style="font-weight:600;">Note: Save the changes before generating Quote</p>
            <input type="hidden" name="user_id" id="user_id" value="<?php echo esc_attr($results->user_id); ?>">
            <input type="hidden" name="rfq_id" id="rfq_id" value="<?php echo esc_attr($id); ?>">
            <div id="imgspinner" style="display:none;">
                <img style="width:22px;" src="<?php echo plugin_dir_url(
                    __FILE__
                ); ?>spinner.gif" alt="Loading...">
            </div>
        <div id="rfq-message" style="display:none;"></div>
        	<!--Validate before update  -->
        <?php if ($rfq_status != "Request Received") { ?>
        <div style="margin-top:10px">
            <?php if ($quote_already_generated) { ?>
                <input type="submit" name="update_data" id="update_data" class="button-primary" value="Update RFQ" disabled>
                <input style="margin-left:10px;" type="submit" name="create_quote" id="create_quote" class="button-primary" value="Generate Quote" disabled>
            <?php } else { ?>
                <input type="submit" name="update_data" id="update_data" class="button-primary" value="Update RFQ">
                <input style="margin-left:10px;" type="submit" name="create_quote" id="create_quote" class="button-primary" value="Generate Quote">
            <?php } ?>
        </div>
        <?php } else { ?>
        <div style="margin-top:10px">
            <input type="submit" name="update_data" id="update_data" class="button-primary" value="Update RFQ" disabled>
            <input style="margin-left:10px;" type="submit" name="create_quote" id="create_quote" class="button-primary" value="Generate Quote" disabled>
            <p style="color: red; font-weight:600; font-size:18px; margin-top: 10px;">Please register customer in SAP then update SAP ID in user profile.<br>After that only you can update and generate the Qoute.Checking </p>
        </div>
        <?php } ?>


    </form>
    <script>
	jQuery(document).ready(function($) {
		// Function to validate that the start date is not in the past
		function validateStartDate() {
			var start_date = $('#rfq_startdate').val();
			var today = new Date().toISOString().split('T')[0]; // Get today's date in 'YYYY-MM-DD' format

			if (start_date < today) {
				alert('Start date cannot be in the past. Please select a valid start date.');
				return false;
			}
			return true;
		}

		// Function to validate that the end date is not before the start date
		function validateEndDate() {
			var start_date = $('#rfq_startdate').val();
			var end_date = $('#rfq_enddate').val();

			if (start_date && end_date && end_date < start_date) {
				alert('End date cannot be before the start date. Please select a valid end date.');
				$('#rfq_enddate').val(''); // Clear invalid end date
				return false;
			}
			return true;
		}

		// Set minimum date for the start date field
		var today = new Date().toISOString().split('T')[0];
		$('#rfq_startdate').attr('min', today);

		// Update the minimum date for end date whenever start date changes
		$('#rfq_startdate').on('change', function() {
			var start_date = $(this).val();
			$('#rfq_enddate').attr('min', start_date);
			// Also validate end date if it's already set
			validateEndDate();
		});

		$('.rfq-date-field').on('change', function() {
			var start_date = $('#rfq_startdate').val();
			var end_date = $('#rfq_enddate').val();
			var shift = $('#rfqshift').val();
			var product_id = $('#product_id').val();
			var user_id = $('#user_id').val();

			// Validate start date, end date and if date fields are selected
			if (!validateStartDate() || !validateEndDate() || start_date === '' || end_date === '') {
				return;
			}

			// Show the spinner
			$('#rfq-spinner').show();

			$.ajax({
				url: '<?php echo admin_url("admin-ajax.php"); ?>',
				type: 'POST',
				data: {
					action: 'get_pricing_data',
					start_date: start_date,
					end_date: end_date,
					shift: shift,
					product_id: product_id,
					user_id: user_id
				},
				success: function(response) {
					// Hide the spinner
					$('#rfq-spinner').hide();
					// Show success rfq-message
					$('#pricingtxt').val(response);
				},
				error: function(error) {
					// Hide the spinner
					$('#spinner').hide();
					// Show error rfq-message
					$('#rfq-message').html('There was an error submitting your request. Please try again.').show();
				}
			});
		});

		$('#update_data').on('click', function(e) {
			e.preventDefault();

			var start_date = $('#rfq_startdate').val();
			var end_date = $('#rfq_enddate').val();
			var shift = $('#rfqshift').val();
			var product_id = $('#product_id').val();
			var user_id = $('#user_id').val();
			var rfq_id = $('#rfq_id').val();
			var calculated_price = $('#pricingtxt').val();
			var final_price = $('#final_pricetxt').val();
			var rfqdiscount = $('#rfqdiscount').val();
			var rfq_status = $('#rfq_status').val();
			var user_name = $('#user_name').val();
			var user_email = $('#user_email').val();

			// Validate start date, end date and if date fields are selected
			if (!validateStartDate() || !validateEndDate() || start_date === '' || end_date === '') {
				return;
			}

			// Show the spinner
			$('#imgspinner').show();

			$.ajax({
				url: '<?php echo admin_url("admin-ajax.php"); ?>',
				type: 'POST',
				data: {
					action: 'update_rfq_data',
					user_name: user_name,
					user_email: user_email,
					start_date: start_date,
					end_date: end_date,
					shift: shift,
					product_id: product_id,
					user_id: user_id,
					rfq_id: rfq_id,
					calculated_price: calculated_price,
					rfqdiscount: rfqdiscount,
					final_price: final_price,
					rfq_status: rfq_status
				},
				success: function(response) {
					console.log(response.success);
					$('#rfq-message').html('');
					$('#imgspinner').hide();
					if (response.success == true) {
                        $.ajax({
                    url: '<?php echo admin_url("admin-ajax.php"); ?>', // Fix: Use proper URL
                    type: 'POST',
                    data: {
                        action: 'send_modify_rfq_email',
                        rfq_id: rfq_id,
                        nonce: '<?php echo wp_create_nonce("send_modify_rfq_email_nonce"); ?>'
                    },
                    success: function(emailResponse) { // Add: Handle email response
                        console.log('Email sent:', emailResponse);
                    },
                    error: function(emailError) { // Add: Handle email errors
                        console.error('Email sending failed:', emailError);
                    }
                });
						$('#rfq-message').html('Request Quotes Data Updated Successfully. Please wait for the page to fully reload.').css({
							'color': '#008000',
							'font-weight': 'bold'
						}).show();
						setTimeout(function() {
							window.location.reload();
						}, 1000);
					} else {
						$('#rfq-message').html('Error Occurs').css({
							'color': 'red',
							'font-weight': 'bold'
						}).show();
					}
				},
				error: function(error) {
					$('#imgspinner').hide();
					$('#rfq-message').html('There was an error submitting your request. Please try again.').show();
				}
			});
		});

		$('#create_quote').on('click', function(e) {
			e.preventDefault();

			var user_name = $('#user_name').val();
			var user_email = $('#user_email').val();
			var start_date = $('#rfq_startdate').val();
			var end_date = $('#rfq_enddate').val();
// 			var shift = $('#rfqshift').val();
			var product_id = $('#product_id').val();
			var user_id = $('#user_id').val();
			var rfq_id = $('#rfq_id').val();
			var final_price = $('#final_pricetxt').val();
			var calculated_price = $('#pricingtxt').val();
            var region = $('#region').val();
            var location = $('#location').val();

			// Validate start date, end date and if date fields are selected
			if (!validateStartDate() || !validateEndDate() || start_date === '' || end_date === '') {
				return;
			}

			// Show the spinner
			$('#imgspinner').show();

			$.ajax({
				url: '<?php echo admin_url("admin-ajax.php"); ?>',
				type: 'POST',
				data: {
					action: 'save_quotation_data',
					user_name: user_name,
					user_email: user_email,
					start_date: start_date,
					end_date: end_date,
// 					shift: shift,
					product_id: product_id,
					user_id: user_id,
					rfq_id: rfq_id,
					final_price: final_price,
					calculated_price: calculated_price,
                    region: region,
                    location: location
				},
				success: function(response) {
					// console.log(response.success);
                    var quotationId = response.data.quotation_id; // Get quotation ID from response
					$('#rfq-message').html('');
					$('#imgspinner').hide();
					if (response.success == true) {
						$('#rfq-message').html('Quotation generated successfully. Please wait while the quotation page opens automatically. ').css({
							'color': '#008000',
							'font-weight': 'bold'
						}).show();
						setTimeout(function() {
                            window.location.href = "<?php echo admin_url('admin.php?page=edit-quotation'); ?>" + "&id=" + quotationId;
                        }, 1000);


					} else {
						$('#rfq-message').html('Error Occurs').css({
							'color': 'red',
							'font-weight': 'bold'
						}).show();
					}
				},
				error: function(error) {
					$('#imgspinner').hide();
					$('#rfq-message').html('There was an error submitting your request. Please try again.').show();
				}
			});
		});

		// Function to calculate final price
		function calculateFinalPrice() {
			var calculatedPrice = $('#pricingtxt').val();
			var rfqdiscount = $('#rfqdiscount').val();
			var finalPrice = calculatedPrice - (calculatedPrice * (rfqdiscount / 100));
			$('#final_pricetxt').val(finalPrice.toFixed(2));
		}

		// Calculate final price on page load
		calculateFinalPrice();

		// Calculate final price when discount select box changes
		$('#rfqdiscount').on('change', function() {
			calculateFinalPrice();
		});
	});
</script>

	</div>
	<?php
}
function update_rfq_data_callback() {
    global $wpdb;

    // Get the posted data
    $user_name = sanitize_text_field($_POST['user_name']);
    $user_email = sanitize_email($_POST['user_email']);
    $start_date = sanitize_text_field($_POST['start_date']);
    $end_date = sanitize_text_field($_POST['end_date']);
    $shift = sanitize_text_field($_POST['shift']);
    $product_id = intval($_POST['product_id']);
    $user_id = intval($_POST['user_id']);
    $rfq_id = intval($_POST['rfq_id']);
    $calculated_price = $_POST["calculated_price"];
    $rfq_status = sanitize_text_field($_POST['rfq_status']);
    $final_price = $_POST["final_price"];
    $rfqdiscount = sanitize_text_field($_POST['rfqdiscount']);

    // Update the RFQ data in the wp_request table
    $request_table_name = $wpdb->prefix . 'request_quote';
    $price = str_replace( ',', '', $calculated_price );
    $final_price_amount = str_replace( ',', '', $final_price );

    $request_update_result = $wpdb->update(
        $request_table_name,
        array(
            'user_name' => $user_name,
            'user_email' => $user_email,
            'start_date' => $start_date,
            'end_date' => $end_date,
            'shift' => $shift,
            'product_id' => $product_id,
            'user_id' => $user_id,
            'calculated_price' => $price,
            'rfq_status' => $rfq_status,
            'final_price' => $final_price_amount,
            'rfqdiscount' => $rfqdiscount
        ),
        array('id' => $rfq_id)
    );

    if ($request_update_result === false) {
        wp_send_json_error('Error updating request_quote table: ' . $wpdb->last_error);
        wp_die();
    }

    // Insert or update the data in the wp_quotation table
    

    // Return a success message
    wp_send_json_success('Request Quotes Data Updated Successfully!');
    wp_die();
}

add_action('wp_ajax_update_rfq_data', 'update_rfq_data_callback');

function save_quotation_data_callback() {
    global $wpdb;

    // Get the posted data
    $rfq_id = intval($_POST["rfq_id"]);
    $user_name = sanitize_text_field($_POST['user_name']);
    $user_email = sanitize_email($_POST['user_email']);
    $start_date = sanitize_text_field($_POST['start_date']);
    $end_date = sanitize_text_field($_POST['end_date']);
//     $shift = sanitize_text_field($_POST['shift']);
    $product_id = intval($_POST['product_id']);
    $user_id = intval($_POST['user_id']);
    $calculated_price = sanitize_text_field($_POST['calculated_price']);
    $final_price = sanitize_text_field($_POST['calculated_price']);
    $region = sanitize_text_field($_POST['region']);
    $location = sanitize_text_field($_POST['location']);

    $request_quote_table_name = $wpdb->prefix . 'request_quote';
    $quote_data = $wpdb->get_row($wpdb->prepare(
        "SELECT location, region FROM $request_quote_table_name WHERE rfq_id = %d",
        $rfq_id
    ));

// Shejad removed it
    
    // $location = sanitize_text_field($quote_data->location);
    // $region = sanitize_text_field($quote_data->region);

    // Get the product name from WooCommerce
    $product = wc_get_product($product_id);
    $product_name = $product ? $product->get_title() : '';

    // Insert the data into the wp_quotation table
    $quotation_table_name = $wpdb->prefix . 'quotation';
    // $existing_quotation = $wpdb->get_row("SELECT * FROM $quotation_table_name WHERE rfq_id = $rfq_id");

    
        // Insert a new quotation
        $quotation_insert_result = $wpdb->insert(
            $quotation_table_name,
            array(
                'rfq_id' => $rfq_id,
                'user_name' => $user_name,
                'user_email' => $user_email,
                'start_date' => $start_date,
                'end_date' => $end_date,
//                 'shift' => $shift,
                'product_id' => $product_id,
                'product_name' => $product_name,
                'user_id' => $user_id,
                'calculated_price'=> $calculated_price,
                'final_price' => $final_price,
                'region' => $region,
                'location' => $location
            )
        );
	


        if ($quotation_insert_result === false) {
            wp_send_json_error('Error inserting into quotation table: ' . $wpdb->last_error);
            wp_die();
        }

        $quotation_id = $wpdb->insert_id; // Get the ID of the newly created quotation
        wp_send_json_success(array('quotation_id' => $quotation_id)); // Pass the ID back

        // Return a success message
        // wp_send_json_success('Quotation Data Saved Successfully!');
        wp_die();
    }


add_action('wp_ajax_save_quotation_data', 'save_quotation_data_callback');



// Add new RFQ 13-11-24 --Aseema
function rfq_add_new_page() {
    global $wpdb;

    // Query for products that have 'purpose_of_listing' = 'display' and are published
    $args = array(
        'post_type'      => 'product', // Change 'product' to your custom post type slug if necessary
        'posts_per_page' => -1, // Get all products
        'post_status'    => 'publish', // Only get published products
        'meta_query'     => array(
            array(
                'key'   => 'purpose_of_listing',
                'value' => 'display', // The value we are looking for in the 'purpose_of_listing' field
                'compare' => '='
            )
        )
    );

    // Get the products
    $products_query = new WP_Query($args);
    
    ?>
    <div class="wrap">
        <h2>Add New RFQ</h2>

        <form method="post" >
            <input type="hidden" name="action" value="save_new_rfq">
            <?php wp_nonce_field('save_new_rfq_nonce', 'rfq_nonce'); ?>

            <table class="form-table">
            <tr>
                <th><label for="user_name">User Name</label></th>
                <td>
                    <select name="user_name" id="user_name" class="regular-text" required>
                        <option value="">Select a User</option>
                        <?php
                        // Get all users with the role 'customer'
                        $customers = get_users(array('role' => 'customer'));

                        // Loop through each customer and add them as options in the dropdown
                        foreach ($customers as $customer) {
                            echo '<option value="' . esc_attr($customer->user_login) . '" data-email="' . esc_attr($customer->user_email) . '">' . esc_html($customer->display_name) . '</option>';
                        }
                        ?>
                    </select>
                </td>
            </tr>

            <tr>
                <th><label for="user_email">User Email</label></th>
                <td><input type="email" name="user_email" id="user_email" class="regular-text" required readonly></td>
            </tr>

            <script type="text/javascript">
                // JavaScript to update the email field based on the selected user
                document.getElementById('user_name').addEventListener('change', function() {
                    var selectedOption = this.options[this.selectedIndex];
                    var userEmail = selectedOption.getAttribute('data-email');
                    
                    // Populate the email input field with the selected user's email
                    document.getElementById('user_email').value = userEmail;
                });
            </script>

                <tr>
                    <th><label for="product_name">Product Name</label></th>
                    <td>
                        <select name="product_name" id="product_name" class="regular-text" required>
                            <option value="">Select a Product</option>
                            <?php if ($products_query->have_posts()) : ?>
                                <?php while ($products_query->have_posts()) : $products_query->the_post(); ?>
                                    <option value="<?php the_ID(); ?>"><?php the_title(); ?></option>
                                <?php endwhile; ?>
                                <?php wp_reset_postdata(); ?>
                            <?php else : ?>
                                <option value="">No products found</option>
                            <?php endif; ?>
                        </select>
                        <span id="price-spinner" style="display: none;">Loading...</span>
                    </td>
                </tr>
                <tr>
                    <th><label for="product_price">Product Price</label></th>
                    <td><input type="text" name="product_price" id="product_price" class="regular-text" readonly></td>
                </tr>
                <tr>
                    <th><label for="rfq_startdate">Start Date</label></th>
                    <td><input type="date" name="rfq_startdate" id="rfq_startdate" class="regular-text" required min="<?php echo date('Y-m-d'); ?>" onkeydown="return false;" onchange="updateEndDateMin();"></td>
                </tr>
                <tr>
                    <th><label for="rfq_enddate">End Date</label></th>
                    <td><input type="date" name="rfq_enddate" id="rfq_enddate" class="regular-text" required min="<?php echo date('Y-m-d'); ?>" onkeydown="return false;" onchange="validateEndDate();"></td>
                </tr>
                <tr>
                    <th><label for="shift">Shift</label></th>
                    <td>
                        <select name="shift" id="shift" class="regular-text" required>
                            <option value="">Select Shift</option>
                            <option value="1">1 Shift (8 hours)</option>
                            <option value="2">2 Shifts (16 hours)</option>
                            <option value="3">3 Shifts (24 hours)</option>
                        </select>
                    </td>
                </tr>
                <tr>
                    <th><label for="calculated_price">Calculated Price</label></th>
                    <td><input type="text" name="calculated_price" id="calculated_price" class="regular-text"  readonly></td>
                </tr>

                <tr>
                     <th><label for="location">Location</label></th>
                    <td>
                        <select name="location" id="location" class="regular-text" required>
                            <option value="">Select Location</option>
                            <option value="Andhra Pradesh">Andhra Pradesh</option>
                            <option value="Arunachal Pradesh">Arunachal Pradesh</option>
                            <option value="Assam">Assam</option>
                            <option value="Bihar">Bihar</option>
                            <option value="Chhattisgarh">Chhattisgarh</option>
                            <option value="Goa">Goa</option>
                            <option value="Gujarat">Gujarat</option>
                            <option value="Haryana">Haryana</option>
                            <option value="Himachal Pradesh">Himachal Pradesh</option>
                            <option value="Jharkhand">Jharkhand</option>
                            <option value="Karnataka">Karnataka</option>
                            <option value="Kerala">Kerala</option>
                            <option value="Madhya Pradesh">Madhya Pradesh</option>
                            <option value="Maharashtra">Maharashtra</option>
                            <option value="Manipur">Manipur</option>
                            <option value="Meghalaya">Meghalaya</option>
                            <option value="Mizoram">Mizoram</option>
                            <option value="Nagaland">Nagaland</option>
                            <option value="Odisha">Odisha</option>
                            <option value="Punjab">Punjab</option>
                            <option value="Rajasthan">Rajasthan</option>
                            <option value="Sikkim">Sikkim</option>
                            <option value="Tamil Nadu">Tamil Nadu</option>
                            <option value="Telangana">Telangana</option>
                            <option value="Tripura">Tripura</option>
                            <option value="Uttar Pradesh">Uttar Pradesh</option>
                            <option value="Uttarakhand">Uttarakhand</option>
                            <option value="West Bengal">West Bengal</option>
                            <option value="Andaman and Nicobar Islands">Andaman and Nicobar Islands</option>
                            <option value="Chandigarh">Chandigarh</option>
                            <option value="Dadra and Nagar Haveli and Daman and Diu">Dadra and Nagar Haveli and Daman and Diu</option>
                            <option value="Lakshadweep">Lakshadweep</option>
                            <option value="Delhi">Delhi</option>
                            <option value="Puducherry">Puducherry</option>
                        </select>
                    </td>
                </tr>

                <tr>
                    <th><label for="region">Region</label></th>
                    <td>
                        <select name="region" id="region" class="regular-text" required>
                            <option value="">Select a Region</option>
                            <option value="north">North</option>
                            <option value="south">South</option>
                            <option value="east">East</option>
                            <option value="west">West</option>
                            <option value="others">others</option>
                        </select>
                    </td>
                </tr>

                <tr>
                    <th><label style="color:#000;" class="form-label font-weight-bold" for="application">Select Application:</label></th>
                        <td>
                            <div class="col-md-12 mt-2">
                    
                                <select class="form-control rfq-date-field" id="application" name="application" required>
                                    <option value="">Select Application</option>
                                    <option value="Mining">Mining</option>
                                    <option value="Road/Rail/Metro Construction">Road/Rail/Metro Construction</option>
                                    <option value="Irrigation">Irrigation</option>
                                    <option value="Building Construction">Building Construction</option>
                                    <option value="Material Handling">Material Handling</option>
                                    <option value="Earth Work">Earth Work</option>
                                    <option value="Others">Others</option>
                                </select>
                            </div>
                        </td> 
                </tr>

                <tr>
                    <th><label for="rfq_status">RFQ Status</label></th>
                    <td>
                        <input type="text" name="rfq_status" id="rfq_status" class="regular-text" value="Request Generated" readonly>
                    </td>
                </tr>
            </table>

            <div>
                <input type="submit" name="submit_rfq" id="submit_rfq" class="button-primary" value="Add New RFQ">
            </div>
        </form>
    </div>
    <?php
        global $wpdb, $current_user;

        if (isset($_POST['submit_rfq'])) {
            // Check nonce
            if (!isset($_POST['rfq_nonce']) || !wp_verify_nonce($_POST['rfq_nonce'], 'save_new_rfq_nonce')) {
                echo '<div class="error"><p>Nonce verification failed. Please try again.</p></div>';
                return;
            }

            // Sanitize and retrieve form data
            $user_name = sanitize_text_field($_POST['user_name']);
            $user_email = sanitize_email($_POST['user_email']);
            $product_id = intval($_POST['product_name']); // Use product_name to store product ID
            $product_name = get_the_title($product_id); // Fetch product name using product_id
            $start_date = sanitize_text_field($_POST['rfq_startdate']);
            $end_date = sanitize_text_field($_POST['rfq_enddate']);
//             $shift = intval($_POST['shift']);
            $calculated_price = floatval($_POST['calculated_price']);
            $rfq_status = 'Request Generated';
            $region = sanitize_text_field($_POST['region']);
            $requested_on = current_time('mysql');
            $created_by = $current_user->user_email;
            // $user_id = get_current_user_id();
            $location = sanitize_text_field($_POST['location']); // Sanitize and retrieve location
//             $application = sanitize_text_field($_POST['application']);

            $user = get_user_by('email', $user_email);
            if ($user && !is_wp_error($user)) {
                $user_id = $user->ID; 
            } 
            // Generate a new rmsID
            $table_name = $wpdb->prefix . "request_quote";
            $max_value = $wpdb->get_var("SELECT MAX(id) FROM $table_name");
            $rmsID = "RMS00" . (($max_value !== null ? $max_value : 0) + 1);

            // Insert RFQ data into the database
            $insert_result = $wpdb->insert(
                $table_name,
                [
                    'user_id'          => $user_id,
                    'user_name'        => $user_name,
                    'user_email'       => $user_email,
                    'product_id'       => $product_id,
                    'product_name'     => $product_name, // Now stores the actual product name
                    'start_date'       => $start_date,
                    'end_date'         => $end_date,
//                     'shift'            => $shift,
                    'calculated_price' => $calculated_price,
                    'rfq_status'       => $rfq_status,
                    'region'           => $region,
                    'requested_on'     => $requested_on,
                    'created_by'       => $created_by,
                    'rmsID'            => $rmsID,
                    'location'         => $location,
//                     'application'      => $application,
                ],
                [
                    '%d',  // user_id
                    '%s',  // user_name
                    '%s',  // user_email
                    '%d',  // product_id
                    '%s',  // product_name (updated to save product title)
                    '%s',  // rfq_startdate
                    '%s',  // rfq_enddate
//                     '%d',  // shift
                    '%f',  // calculated_price
                    '%s',  // rfq_status
                    '%s',  // region
                    '%s',  // requested_on
                    '%s',  // created_by
                    '%s',  // rmsID
                    '%s',  // location
//                     '%s'  // application 

                ]
            );

            // Check if data insertion was successful
            if ($insert_result === false) {
                echo '<div class="error"><p>Failed to create RFQ. Error: ' . esc_html($wpdb->last_error) . '</p></div>';
            } else {
                echo '<div class="updated"><p>RFQ Created Successfully!</p></div>';
                echo '<script type="text/javascript">
                        setTimeout(function() {
                            window.location.href = "' . esc_url(admin_url('admin.php?page=rfq-dashboard')) . '";
                        }, 2000);
                    </script>';
            }
        }

    ?>

    <script type="text/javascript">
        function updateEndDateMin() {
            const startDate = document.getElementById('rfq_startdate').value;
            const endDateField = document.getElementById('rfq_enddate');

            if (startDate) {
                // Set the minimum value for the end date field to match the selected start date
                endDateField.min = startDate;

                // Reset the end date field if its value is earlier than the start date
                if (new Date(endDateField.value) < new Date(startDate)) {
                    endDateField.value = '';
                }
            }
        }

        function validateEndDate() {
            const startDate = document.getElementById('rfq_startdate').value;
            const endDate = document.getElementById('rfq_enddate').value;

            if (startDate && endDate) {
                if (new Date(endDate) < new Date(startDate)) {
                    alert("End date should not be earlier than the start date.");
                    document.getElementById('rfq_enddate').value = ''; // Clear the end date field
                }
            }
        }

       document.getElementById('product_name').addEventListener('change', function() {
    var productId = this.value;
    var priceField = document.getElementById('product_price');
    var startDateField = document.getElementById('rfq_startdate');
    var endDateField = document.getElementById('rfq_enddate');
//     var shiftField = document.getElementById('shift');
    var calculatedPriceField = document.getElementById('calculated_price');
    var spinner = document.getElementById('price-spinner'); 
    // Show the spinner while loading the price
    spinner.style.display = 'inline';


    if (productId) {
        // Use AJAX to fetch the price for the selected product
        var data = {
            action: 'get_product_price',
            product_id: productId
        };

        jQuery.post(ajaxurl, data, function(response) {
                // Hide the spinner once response is received
                spinner.style.display = 'none';
            if (response.success) {
                var productPrice = parseFloat(response.data.price); // Get the product price
                priceField.value = productPrice.toFixed(2);

                // Calculate the price when start date, end date, or shift changes
                calculateCalculatedPrice(productPrice);
            } else {
                priceField.value = 'Price not available';
                calculatedPriceField.value = '';
            }
        });
    } else {
        spinner.style.display = 'none';
        priceField.value = '';
        calculatedPriceField.value = '';
    }

    // Function to calculate calculated price based on shift and date range
    function calculateCalculatedPrice(productPrice) {
        var startDate = startDateField.value;
        var endDate = endDateField.value;
        var shift = shiftField.value;

        // If both start date and end date are selected
        if (startDate && endDate && shift) {
            var start = new Date(startDate);
            var end = new Date(endDate);

            // Calculate the number of days between the start and end date
            var timeDiff = end - start;
            var days = timeDiff / (1000 * 3600 * 24) + 1;

            // Handle cases where the number of days is less than or equal to 0
            if (days < 1) {
            alert('End date should be the same as or greater than the start date.');
            return;
        }

            // Calculate the shift-based price
            var calculatedPrice = 0;

            if (shift == "1") {
                // 1 shift (price stays the same as product price)
                calculatedPrice = productPrice * days; // Price per day
            } else if (shift == "2") {
                // 2 shifts (double the product price)
                calculatedPrice = productPrice * 2 * days; // Price per day
            } else if (shift == "3") {
                // 3 shifts (triple the product price)
                calculatedPrice = productPrice * 3 * days; // Price per day
            }

            // Update the calculated price field
            calculatedPriceField.value = calculatedPrice.toFixed(2);
        } else {
            // If dates or shift are not selected, reset the calculated price
            calculatedPriceField.value = '';
        }
    }

    // Recalculate when start date, end date, or shift changes
    startDateField.addEventListener('change', function() {
        var productPrice = parseFloat(priceField.value);
        if (productPrice) {
            calculateCalculatedPrice(productPrice);
        }
    });

    endDateField.addEventListener('change', function() {
        var productPrice = parseFloat(priceField.value);
        if (productPrice) {
            calculateCalculatedPrice(productPrice);
        }
    });

    shiftField.addEventListener('change', function() {
        var productPrice = parseFloat(priceField.value);
        if (productPrice) {
            calculateCalculatedPrice(productPrice);
        }
    });

    
});

    </script>
    <?php
}

// 13-11-24 --Aseema
function get_product_price() {
    if (isset($_POST['product_id'])) {
        $product_id = intval($_POST['product_id']);
        $product = wc_get_product($product_id); // WooCommerce function to get the product
        if ($product) {
            $price = $product->get_regular_price(); // Get the regular price of the product
            wp_send_json_success(['price' => $price]);
        } else {
            wp_send_json_error('Product not found');
        }
    }
    wp_send_json_error('Invalid product ID');
}

add_action('wp_ajax_get_product_price', 'get_product_price');
add_action('wp_ajax_nopriv_get_product_price', 'get_product_price');

// hide screen option
function hide_screen_options_for_rfq() {
    ?>
    <style>
    <?php if (isset($_GET['page']) && ($_GET['page'] === 'rfq-dashboard' || $_GET['page'] === 'create-rfq' ||$_GET['page'] === 'add-new-rfq' ||$_GET['page'] === 'edit-quote')) : ?>
        #screen-meta-links {
            display: none !important;
        }
    <?php endif; ?>
    </style>
    <?php
}
add_action('admin_head', 'hide_screen_options_for_rfq');


?>

Youez - 2016 - github.com/yon3zu
LinuXploit