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.37
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/work-order/

Upload File :
current_dir [ Writeable ] document_root [ Writeable ]

 

Command :


[ Back ]     

Current File : /var/www/html/rentals_updated/wp-content/plugins/work-order/index.php
<?php
/*
Plugin Name: Work Orders
Description: A simple plugin to manage work orders, sale order, invoices sales with a custom form and database table.
Version: 1.4
Author: Itrosys
*/

// Prevent direct access
if (!defined('ABSPATH')) {
    exit;
}

include plugin_dir_path(__FILE__) . "sales-order-listing.php";
include plugin_dir_path(__FILE__) . "invoice-order-listing.php";
include plugin_dir_path(__FILE__) . "invoices-for-myaccount.php";
include plugin_dir_path(__FILE__) . "rentalorder-to-workorder.php";


// Main class for Work Orders plugin
class WorkOrdersPlugin
{
    public function __construct()
    {
        global $wpdb;
        $this->invoice_api = new InvoiceApi($wpdb);
        
        register_activation_hook(__FILE__, array($this, 'create_work_orders_table'));
        register_activation_hook(__FILE__, array($this, 'create_sales_orders_table'));
        register_activation_hook(__FILE__, array($this, 'create_invoice_sales_table'));
        add_action('admin_menu', array($this, 'add_work_order_menu'));
        add_action('admin_init', array($this, 'handle_form_submission'));
        // Enqueue CSS in admin area
        add_action('admin_enqueue_scripts', array($this, 'enqueue_admin_css'));
    }

    // Create custom database table for Work Orders on plugin activation
    public function create_work_orders_table()
    {
        global $wpdb;
        $table_name = $wpdb->prefix . 'work_orders'; // Table name with prefix
        $charset_collate = $wpdb->get_charset_collate();

        // SQL to create table
        $sql = "CREATE TABLE $table_name (
            id mediumint(9) NOT NULL AUTO_INCREMENT,
            contract_id varchar(255) NOT NULL,
            user_id int(255) NOT NULL,
            user_name VARCHAR(255)NOT NULL,
            pdi_document_file_path varchar(255),
            shipping_document_file_path varchar(255),
            equipement_name VARCHAR(255),
            region VARCHAR(255),
            location VARCHAR(255),
            monthly_log_hours INT NOT NULL,
            wo_type VARCHAR(255),
            is_work_order_generated TINYINT(1) NOT NULL,
            created_date date NOT NULL,
            min_monthly_hours INT NOT NULL,
            contract_monthly_rate INT NOT NULL,
            start_date DATE NOT NULL,
            end_date DATE NOT NULL,
            billing_start_date DATE NOT NULL,
            billing_end_date DATE NOT NULL,
            order_total VARCHAR(255) NOT NULL,
            equip_asset_id INT NOT NULL,
            PRIMARY KEY (id)
        ) $charset_collate;";

        require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
        dbDelta($sql); // Use dbDelta to create or upgrade table
        
    }

    public function create_sales_orders_table()
    {
        global $wpdb;
        $table_name = $wpdb->prefix . 'sales_order'; // Table name with prefix
        $charset_collate = $wpdb->get_charset_collate();

        // SQL to create table
        $sql = "CREATE TABLE $table_name (
            id mediumint(9) NOT NULL AUTO_INCREMENT,
            work_order_id INT NOT NULL,
            contract_id varchar(255) NOT NULL,
            user_id INT NOT NULL,
            created_date DATE NOT NULL,
            min_hour_billing INT NOT NULL,
            user_name VARCHAR(255) NOT NULL,
            equipement_name VARCHAR(255) NOT NULL,
            region VARCHAR(255) NOT NULL,
            location VARCHAR(255)NOT NULL,
            contract_monthly_rate INT NOT NULL,
            min_monthly_hours INT NOT NULL,
            start_date DATE NOT NULL,
            end_date DATE NOT NULL,
            billing_start_date DATE NOT NULL,
            billing_end_date DATE NOT NULL,
            order_total VARCHAR(255) NOT NULL,
            equip_asset_id INT NOT NULL,
            invoice_number INT(11),
            invoice_date DATE,
            irnno VARCHAR(255),
            qrcode LONGTEXT,
            created_by VARCHAR(255) NOT NULL,
            token VARCHAR(255),
            PRIMARY KEY (id)
        ) $charset_collate;";

        require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
        dbDelta($sql); // Use dbDelta to create or upgrade table
    }

    public function create_invoice_sales_table()
    {
        global $wpdb;
        $table_name = $wpdb->prefix . 'order_invoice_details'; // Table name with prefix
        $charset_collate = $wpdb->get_charset_collate();

        // SQL to create table
        $sql = "CREATE TABLE $table_name (
            id MEDIUMINT NOT NULL AUTO_INCREMENT,
            sale_order_id INT NOT NULL,
            contract_id VARCHAR(255) NOT NULL,
            min_hour_billing INT NOT NULL,
            user_id INT NOT NULL,
            user_name VARCHAR(255) NOT NULL,
            equipement_name VARCHAR(255) NOT NULL,
            region VARCHAR(255) NOT NULL,
            location VARCHAR(255) NOT NULL,
            created_by VARCHAR(255) NOT NULL,
            invoice_value INT NOT NULL,
            start_date DATE NOT NULL,
            end_date DATE NOT NULL,
            billing_start_date DATE NOT NULL,
            billing_end_date DATE NOT NULL,
            order_total VARCHAR(255) NOT NULL,
            equip_asset_id INT NOT NULL,
            invoice_number INT(11),
            invoice_date DATE,
            irnno VARCHAR(255),
            qrcode LONGTEXT,
            created_date DATE NOT NULL,
            PRIMARY KEY (id)
        ); $charset_collate;";

        require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
        dbDelta($sql); // Use dbDelta to create or upgrade table
    }
    
    public function add_work_order_menu()
    {
        add_menu_page(
            page_title: 'Work Orders',
            menu_title: 'Work Orders',
            capability: 'manage_options',
            menu_slug: 'work_orders',
            callback: array($this, 'display_work_orders_page'),
            icon_url: 'dashicons-list-view',
            position: 20
        );
        add_menu_page(
            'Sales Order Listing',   // Page title
            'Sales Orders',          // Menu title in the admin sidebar
            'manage_options',        // Capability required to access the page
            'sales-order-listing',   // Slug to identify the page
            'display_sales_order_listing', // Function that renders the page content
            'dashicons-list-view',   // Icon for the menu item
            20                       // Position in the menu
        );
        add_submenu_page(
            parent_slug: null,
            page_title: 'Add New Work Order',
            menu_title: null,
            capability: 'manage_options',
            menu_slug: 'add_work_order',
            callback: array($this, 'display_add_work_order_form')
        );
        add_submenu_page(
            parent_slug: null,  // Change parent_slug to 'sales-order-listing'
            page_title: 'Create Sales Order',
            menu_title: null,
            capability: 'manage_options',
            menu_slug: 'create_sales_order',
            callback: array($this, 'display_create_sales_order_form')
        );
       
        add_submenu_page(
            parent_slug: null,
            page_title: 'Create Invoice',
            menu_title: null,        //  Made it blank to hide submenu
            capability: 'manage_options',
            menu_slug: 'create_invoice',
            callback: array($this, 'display_create_invoice_form')
        );

    }

    // Enqueue CSS in the admin area
    public function enqueue_admin_css($hook_suffix)
    {
        // Only enqueue on the pages relevant to your plugin
        if (strpos($hook_suffix, 'work_orders') !== false) {
            wp_enqueue_style(
                'work-order-css', // Handle name
                plugin_dir_url(__FILE__) . 'css/style.css',
                array(),
                '1.0'
            );
        }
    }


// Display the page for viewing all work orders
public function display_work_orders_page()
{
    global $wpdb;
    $table_name = $wpdb->prefix . 'work_orders';
    // $results = $wpdb->get_results("SELECT * FROM $table_name");

    // Get the current user's visible columns from their preferences
    $user_id = get_current_user_id();
    $user = wp_get_current_user();
    $user_roles = $user->roles;
    $user_meta_region = get_user_meta($user_id, 'ba_region_location', true);
    if ((in_array('rue_manager', $user_roles) || in_array('commercial_representative', $user_roles)) && !empty($user_meta_region)) {
        // Restrict to the manager's assigned region
        // $results = $wpdb->get_results($wpdb->prepare("SELECT * FROM $table_name WHERE region = %s", $user_meta_region));
        $results = $wpdb->get_results($wpdb->prepare("SELECT * FROM $table_name WHERE region = %s ORDER BY id DESC", $user_meta_region));
    } else {
        // Show all work orders for other roles
        // $results = $wpdb->get_results("SELECT * FROM $table_name");
        $results = $wpdb->get_results("SELECT * FROM $table_name ORDER BY id DESC");
    }

    // Get current user role
    $user = wp_get_current_user();
    $user_roles = $user->roles;
    $visible_columns = get_user_meta($user_id, 'work_order_visible_columns', true);
    $visible_columns = $visible_columns ? explode(',', $visible_columns) : ['machine_sr_no', 'actions'];

    ?>
    
    <!-- /end button and filter added -->

    <div class="wrap work-order-wrap">
        <h1 class="wp-heading-inline mb-2 font-weight-bold">Work Orders</h1>

        <div style="display: flex; align-items: center; margin-bottom: 15px; gap: 10px;">
            <button id="toggle-dropdown" style="margin-bottom: 10px;padding: 5px;background-color: #000;color:#FFBD2B; border-radius:5px;flex-shrink: 0;">Show More Columns</button>
            
            <button id="exportbutton" style="margin-top: -11px; padding: 5px 20px; background-color: #000; color: #FFBD2B; border-radius: 5px;flex-shrink: 0;">Export</button>
        </div>
        <div id="dropdown" style="display: none; border: 1px solid #ccc; padding: 10px; width: 100%; background-color: white; position: relative;margin-bottom:30px;">
                <h6>Select Columns to Display:</h6>
                <form method="POST" action="">
                    <div style="display: flex; flex-direction: row; flex-wrap: wrap; gap: 20px;">
                        
                        <label>
                            <input type="checkbox" name="columns[]" value="region" <?php checked(in_array('region', $visible_columns)); ?>> Region
                        </label>
                        <label>
                            <input type="checkbox" name="columns[]" value="min_monthly_hrs" <?php checked(in_array('min_monthly_hrs', $visible_columns)); ?>> Minimum Monthly Hours
                        </label>
                        <label>
                            <input type="checkbox" name="columns[]" value="monthly_log_hrs" <?php checked(in_array('monthly_log_hrs', $visible_columns)); ?>> Monthly Log Hours
                        </label>
                        <label>
                            <input type="checkbox" name="columns[]" value="wo_type" <?php checked(in_array('wo_type', $visible_columns)); ?>> WO Type
                        </label>
                        <label>
                            <input type="checkbox" name="columns[]" value="created_date" <?php checked(in_array('created_date', $visible_columns)); ?>> Created Date
                        </label>
                    </div>
                    <input type="submit" name="save_columns" value="Save Columns" style="margin-top: 10px;" class="button button-primary">
                </form>
        </div>
        <div >
            <table id="work-order-table" class="display wp-list-table widefat fixed striped work-order-listing">
                <thead>
                    <tr>
                        <th>WO No.</th>
                        <th>Contract ID</th>
                        <th>User Name</th>
                        <th style="white-space: nowrap;">Equipment Name</th>
                        <th>Location</th>
                        <!-- <th>Region</th> -->
                        <th class="manage-column" 
                        <?php 
                            if (in_array('region', $visible_columns)) {
                                echo 'style="font-weight:700;"' ;
                            } else {
                                echo 'style="display:none"';  // Hide column if not visible
                            }
                        ?>
                        >Region</th>
                        <!-- <th>Min Monthly Hours</th> -->
                        <th class="manage-column" 
                        <?php 
                            if (in_array('min_monthly_hrs', $visible_columns)) {
                                echo 'style="font-weight:700;"' ;
                            } else {
                                echo 'style="display:none"';  // Hide column if not visible
                            }
                        ?>
                        >Min Monthly Hours</th>
                        <!-- <th>Monthly Log Hours</th> -->
                        <th class="manage-column" 
                        <?php 
                            if (in_array('monthly_log_hrs', $visible_columns)) {
                                echo 'style="font-weight:700;"' ;
                            } else {
                                echo 'style="display:none"';  // Hide column if not visible
                            }
                        ?>
                        >Monthly Log Hours</th>
                        <!-- <th>WO Type</th> -->
                        <th class="manage-column" 
                        <?php 
                            if (in_array('wo_type', $visible_columns)) {
                                echo 'style="font-weight:700;"' ;
                            } else {
                                echo 'style="display:none"';  // Hide column if not visible
                            }
                        ?>
                        >WO Type</th>
                        <!-- <th>Created Date</th> -->
                        <th class="manage-column" 
                        <?php 
                            if (in_array('created_date', $visible_columns)) {
                                echo 'style="font-weight:700;"' ;
                            } else {
                                echo 'style="display:none"';  // Hide column if not visible
                            }
                        ?>
                        >Created Date</th>
                        <th class="sticky-edit">Edit</th> <!-- Class for sticky "Edit" column -->
                        <th class="sticky-monthly">Monthly Work Order</th> <!-- Class for sticky "Monthly Work Order" column -->
                    </tr>
                </thead>
                <tbody>
                    <?php
                    if ($results) {
                        $contract_counters = [];
                        foreach ($results as $row) {
                            echo '<tr>';
                            echo '<td style="font-size:15px !important;">' . esc_html($row->id) . '</td>';
                            if (!isset($contract_counters[$row->contract_id])) {
                                $contract_counters[$row->contract_id] = [
                                    'first' => false,
                                    'monthly_counter' => 0
                                ];
                            }

                            if ($row->wo_type === 'First Work Order') {
                                echo '<td style="font-size:15px !important;">' . esc_html($row->contract_id) . '-0</td>';
                                $contract_counters[$row->contract_id]['first'] = true;
                            } elseif ($row->wo_type === 'Monthly Work Order') {
                                $monthly_count = $contract_counters[$row->contract_id]['monthly_counter'] + 1;
                                echo '<td style="font-size:15px !important;">' . esc_html($row->contract_id) . '-' . $monthly_count . '</td>';
                                $contract_counters[$row->contract_id]['monthly_counter'] = $monthly_count;
                            } else {
                                echo '<td style="font-size:15px !important;">' . esc_html($row->contract_id) . '</td>';
                            }

                            echo '<td style="font-size:15px !important;">' . esc_html($row->user_name) . '</td>';
                            echo '<td style="font-size:15px !important;">' . esc_html($row->equipement_name) . '</td>';
                            echo '<td style="font-size:15px !important;">' . esc_html($row->location) . '</td>';
                            // echo '<td>' . esc_html($row->region) . '</td>';
                            echo '<td class="manage-column" style="' . (in_array('region', $visible_columns) ? 'font-size:15px !important;' : 'display:none;') . '">';
                            echo esc_html($row->region);
                            echo '</td>';

                            // echo '<td>' . esc_html($row->min_monthly_hours) . '</td>';
                            echo '<td class="manage-column" style="' . (in_array('min_monthly_hrs', $visible_columns) ? 'font-size:15px !important;' : 'display:none;') . '">';

                            echo esc_html($row->min_monthly_hours);
                            echo '</td>';

                            // echo '<td>' . esc_html($row->monthly_log_hours) . '</td>';
                            echo '<td class="manage-column" style="' . (in_array('monthly_log_hrs', $visible_columns) ? 'font-size:15px !important;' : 'display:none;') . '">';
                            echo esc_html($row->monthly_log_hours);
                            echo '</td>';
                            // echo '<td>' . esc_html($row->wo_type ?? '') . '</td>';
                            echo '<td class="manage-column" style="' . (in_array('wo_type', $visible_columns) ? 'font-size:15px !important;' : 'display:none;') . '">';
                            echo esc_html($row->wo_type ?? '');
                            echo '</td>';

                            // echo '<td>' . esc_html($row->created_date) . '</td>';
                            echo '<td class="manage-column" style="' . (in_array('created_date', $visible_columns) ? 'font-size:15px !important;' : 'display:none;') . '">';
                            echo esc_html(!empty($row->created_date) ? date('d-m-Y', strtotime($row->created_date)) : '');
                            echo '</td>';

                            $is_monthly_sales = !empty($row->monthly_log_hours) && $row->monthly_log_hours > 0;
                            if ($is_monthly_sales) {
                                echo '<td class="sticky-edit">--</td>';
                            } else {
                                $edit_url = admin_url('admin.php?page=add_work_order&action=edit&id=' . $row->id);
                                echo '<td class="sticky-edit"><a href="' . esc_url($edit_url) . '">Edit</a></td>';
                            }

                            if ($row->is_work_order_generated == 1) {
                                $monthly_sales_url = admin_url('admin.php?page=add_work_order&action=edit&id=' . $row->id . '&monthly_sales=true');
                                echo '<td class="sticky-monthly"><a href="' . esc_url($monthly_sales_url) . '"><span class="dashicons dashicons-edit"></span></a></td>';
                            } else {
                                echo '<td class="sticky-monthly">--</td>';
                            }

                            echo '</tr>';
                        }
                    } else {
                        echo '<tr><td colspan="12">No work orders found</td></tr>';
                    }
                    ?>
                </tbody>
            </table>
        </div>
    </div>


    <style>
        .sticky-edit {
            position: -webkit-sticky; /* Safari */
            position: sticky !important;
            right: 100px; /* Width of the "Monthly Work Order" column */
            background-color: #fff; /* Prevent text overlap */
            z-index: 10; /* Ensure it stays above other content */
            box-shadow: -1px 0px 3px rgba(0, 0, 0, 0.1); /* Optional shadow */
        }

        .sticky-monthly {
            position: -webkit-sticky; /* Safari */
            position: sticky !important;
            right: 0; /* Sticks to the right edge */
            background-color: #fff;
            z-index: 10;
            box-shadow: -1px 0px 3px rgba(0, 0, 0, 0.1); /* Optional shadow */
        }
        #work-order-table tbody tr:nth-child(even) {
            background-color: #ffbd2b30  !important /* Red background for even rows */
        }
        table.dataTable.display tbody tr:hover>.sorting_1 ,table.dataTable.display tbody tr.even>.sorting_1 {
            background-color: unset !important;
        }
        #work-order-table_wrapper .work-order-listing {
            overflow-x: unset;
        }
        
    </style>

    <!-- Include styles and scripts -->
    <link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.24/css/jquery.dataTables.min.css">
    <link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.3/css/all.min.css">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-multiselect@0.9.15/dist/css/bootstrap-multiselect.css">

    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.bundle.min.js"></script>
    <script src="https://cdn.datatables.net/1.10.24/js/jquery.dataTables.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap-multiselect@0.9.15/dist/js/bootstrap-multiselect.min.js"></script>

    <script>
    jQuery(document).ready(function(jQuery) {
        // Initialize DataTable with initial column visibility settings
        var dataTable = jQuery('#work-order-table').DataTable({
            "scrollX": true,
            "order": []
        });

        $('#toggle-dropdown').on('click', function() {
            $('#dropdown').toggle();
        });

        
        function exportTableToCSV() {
                var csv = [];
                var table = document.querySelector("#work-order-table");
                
                // Get visible table headers (column names)
                var headers = [];
                var headerCols = table.querySelectorAll("thead th");
                var visibleColumnsIndexes = []; // To track visible columns

                headerCols.forEach((header, index) => {
                    if (header.style.display !== "none") { // Check if the column is visible
                        headers.push(header.innerText.trim());
                        visibleColumnsIndexes.push(index); // Track visible column indexes
                    }
                });
                csv.push(headers.join(",")); // Push headers to CSV

                // Get table rows data
                var rows = table.querySelectorAll("tbody tr");
                rows.forEach((row) => {
                    var rowData = [];
                    var cols = row.querySelectorAll("td");
                    visibleColumnsIndexes.forEach((colIndex) => {
                        rowData.push(cols[colIndex].innerText.trim()); // Include only visible columns
                    });
                    csv.push(rowData.join(",")); // Add the row data to CSV
                });

                // Create a timestamp for the filename
                var date = new Date();
                var timestamp = date.toISOString().slice(0, 10).split("-").reverse().join("-"); 

                // Construct filename
                var filename = `WorkOrder__${timestamp}.csv`;

                // Trigger CSV download
                downloadCSV(csv.join("\n"), filename);
            }

            function downloadCSV(csvContent, filename) {
                var csvBlob = new Blob([csvContent], { type: "text/csv" });
                var csvURL = window.URL.createObjectURL(csvBlob);
                var downloadLink = document.createElement("a");

                downloadLink.href = csvURL;
                downloadLink.download = filename;
                downloadLink.style.display = "none";

                document.body.appendChild(downloadLink);
                downloadLink.click();
                document.body.removeChild(downloadLink);
            }


            // Attach event listener to the export button
            document.getElementById("exportbutton").addEventListener("click", function() {
                exportTableToCSV("work-order-table.csv");
            });
    });
    </script>


    <?php
    // Handle saving selected columns
    if (isset($_POST['save_columns'])) {
        $selected_columns = isset($_POST['columns']) ? $_POST['columns'] : [];
        update_user_meta($user_id, 'work_order_visible_columns', implode(',', $selected_columns));
        echo '<script>location.reload();</script>';
    }
}





    // Display the form for adding or editing work orders

    function display_add_work_order_form()
    {
        global $wpdb;

        // Fetch id from the URL, if provided
        $work_order_id = isset($_GET['id']) ? intval(value: $_GET['id']) : 0;
        $is_monthly_sales = isset($_GET['monthly_sales']) && $_GET['monthly_sales'] === 'true';

        // If we are editing, fetch the existing work order details
        if ($work_order_id) {
            $table_name = $wpdb->prefix . 'work_orders';
            $work_order = $wpdb->get_row($wpdb->prepare("SELECT * FROM $table_name WHERE id = %d", $work_order_id));

            if (!$work_order) {
                echo '<div class="error"><p>Work order not found.</p></div>';
                return;
            }

            // Check if both documents are uploaded
            $is_pdi_uploaded = !empty($work_order->pdi_document_file_path);
            $is_shipping_uploaded = !empty($work_order->shipping_document_file_path);
            $is_work_order_generated = !empty($work_order->is_work_order_generated);
            $monthly_log_hours = !empty($work_order->monthly_log_hours) ? $work_order->monthly_log_hours : 0;
            $billing_start_date = !empty($work_order->billing_start_date) ? $work_order->billing_start_date : 0;
            $billing_end_date = !empty($work_order->billing_end_date) ? $work_order->billing_end_date : 0;
            // Fetch start and end dates from the database if available
            $start_date = !empty($work_order->start_date) ? $work_order->start_date : '';  // Set to empty string if not available
            $end_date = !empty($work_order->end_date) ? $work_order->end_date : '';  // Set to empty string if not available
            
            //To update the order status
            $order_id = $work_order->contract_id;
            $order = wc_get_order($order_id);
            $order_status = $order->get_status();

        } else {
            $is_pdi_uploaded = false;
            $is_shipping_uploaded = false;
            $is_work_order_generated = false;
            $monthly_log_hours = 0;
            $billing_start_date = 0;
            $billing_end_date = 0;
            $start_date = '';
            $end_date = '';
           
        }

        // Handle form submission to mark work order as generated
        if (isset($_POST['generate_work_order']) && !$is_work_order_generated) {
            // Mark the work order as generated
            $wpdb->update(
                $table_name,
                array(
                    'is_work_order_generated' => true,
                    'wo_type' => 'First work order' // Set WO Type to "First work order"
                ),
                array('id' => $work_order_id)
            );
            $is_work_order_generated = true;
            // Update Order Status
            if($is_work_order_generated){
                $order->update_status('wc-equipment_sent', 'Equipment Dispatch Documents Uploaded & Dispatched.');
            }
            wp_redirect(admin_url('admin.php?page=work_orders'));
            exit;

            // Set localStorage item to disable button
            echo '<script>
            localStorage.setItem("workOrderGenerated_' . $work_order_id . '", "true");
            window.location.reload(); // Refresh the page to reflect changes
        </script>';
        }
         // Fetch existing data from the wp_work_orders table based on work_order_id
        $result = $wpdb->get_row($wpdb->prepare("SELECT contract_id, user_id,user_name,equipement_name, region, location, monthly_log_hours, min_monthly_hours,contract_monthly_rate,min_monthly_hours,start_date,end_date,order_total,equip_asset_id ,billing_start_date,billing_end_date FROM wp_work_orders WHERE id = %d", $work_order_id));
            
            
        if ($result) {
            $contract_id = $result->contract_id;
            $user_id = $result->user_id;
            $user_name = $result->user_name;
            $equipement_name = $result->equipement_name;
            $region = $result->region;
            $location = $result->location;
            $contract_monthly_rate = $result->contract_monthly_rate;
            $min_monthly_hours = $result->min_monthly_hours;
            $monthly_log_hours = floatval($result->monthly_log_hours);
            $min_monthly_hours = floatval($result->min_monthly_hours);
            $start_date = $result->start_date;
            $end_date = $result->end_date;
            $equipement_cost = $result->order_total;
            $equip_asset_id = $result->equip_asset_id;
            $billing_start_date = $result->billing_start_date;
            $billing_end_date = $result->billing_end_date;
    
            

            // Compare and set the greater value for billing hours
            $min_hour_billing = max($monthly_log_hours, $min_monthly_hours);
        } else {
            $contract_id = '';
            echo '<div class="error"><p>No work order found with the provided ID.</p></div>';
        }
    
        // Check if the sales order already exists based on work_order_id
        $existing_sales_order = $wpdb->get_row($wpdb->prepare("SELECT id, min_hour_billing FROM wp_sales_order WHERE work_order_id = %d", $work_order_id));
    
        // Initialize min_hour_billing from form data (only if a form submission happened)
        if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['min_hour_billing'])) {
            $min_hour_billing = sanitize_text_field($_POST['min_hour_billing']);
        }
    
        if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['create_saless_order'])) {
            if ($existing_sales_order) {
                // If a sales order exists, update the existing row
                $wpdb->update(
                    'wp_sales_order',
                    array('min_hour_billing' => $min_hour_billing),
                    array('work_order_id' => $work_order_id),
                    array('%s'),
                    array('%d')
                );
    
                if ($wpdb->last_error) {
                    echo '<div class="error"><p>Error updating sales order: ' . esc_html($wpdb->last_error) . '</p></div>';
                } else {
                    echo '<div class="updated"><p>Sales Order updated successfully!</p></div>';
                }
            } else {
                // If no sales order exists, insert a new row
                $wpdb->insert(
                    'wp_sales_order',
                    array(
                        'work_order_id' => $work_order_id,
                        'contract_id' => $contract_id,
                        'min_hour_billing' => $min_hour_billing,
                        'user_id' => $user_id,
                        'user_name' => $user_name,
                        'equipement_name' => $equipement_name,
                        'region' => $region,
                        'location' => $location,
                        'contract_monthly_rate'=>$contract_monthly_rate,
                        'min_monthly_hours' => $min_monthly_hours,
                        'start_date' => $start_date,
                        'end_date' => $end_date,
                        'created_date' => current_time('mysql'),
                        'created_by' => 'admin',
                        'order_total' => $equipement_cost,
                        'equip_asset_id'  => $equip_asset_id,
                        'billing_start_date'  => $billing_start_date,
                        'billing_end_date'  => $billing_end_date
                    ),
                    array(
                        '%d',  // work_order_id
                        '%d',  // contract_id
                        '%f',  // min_hour_billing (float)
                        '%d', // user_id
                        '%s',  
                        '%s',  // 
                        '%s',  // region
                        '%s',  // location
                        '%f',  // contract_monthly_rate (float)
                        '%f',  // min_monthly_hours (float)
                        '%s',  // start date (string)
                        '%s',
                        '%s',  // created_date (string in MySQL datetime format)
                        '%s',// created_by (string, could be user ID or username)
                        '%s',
                        '%s' ,
                        '%s',
                        '%s'
                    )
                );
    
                if ($wpdb->last_error) {
                    echo '<div class="error"><p>Error inserting new sales order: ' . esc_html($wpdb->last_error) . '</p></div>';
                } else {
                    echo '<div class="updated"><p>New Sales Order created successfully!</p></div>';
                    wp_redirect(admin_url('admin.php?page=sales-order-listing'));
                    exit;
                }
            }
        }

        ?>
        <div class="wrap">
            <h1>
                <?php if ($is_monthly_sales): ?>
                    Edit Monthly Work Order
                <?php else: ?>
                    Edit First Work Order Form
                <?php endif; ?>
            </h1>
            <!-- Display the success message if it's set -->
            <?php if (!empty($success_message)): ?>
                <div class="notice notice-success is-dismissible">
                    <p><?php echo esc_html($success_message); ?></p>
                </div>
            <?php endif; ?>
            <form method="post" action="" enctype="multipart/form-data" id="work_order_form">
                <?php wp_nonce_field('save_work_order_form', 'work_order_form_nonce'); ?>
                <?php
                    $contract_id = $work_order_id ? $work_order->contract_id : '';
                    
                    $start_date = '';
                    $end_date = '';
                    if ($contract_id) {
                        $start_date = get_post_meta($contract_id, 'start_date', true); 
                        $end_date = get_post_meta($contract_id, 'end_date', true); 
                    }
                    ?>
                <input type="hidden" name="work_order_id" value="<?php echo $work_order_id; ?>">
                <table class="form-table">
                    <tr>
                        <th><label for="contract_id">Contract ID</label></th>
                        <td><input type="text" name="contract_id" id="contract_id"
                                value="<?php echo $work_order_id ? esc_attr($work_order->contract_id) : ''; ?>" disabled></td>
                    </tr>
                    

                    <tr>
                        <th><label for="created_date">Created Date</label></th>
                        <td><input type="text" name="created_date" id="created_date"
                        value="<?php echo $work_order_id ? date('d-m-Y', strtotime($work_order->created_date)) : date('d-m-Y'); ?>"  
                                disabled></td>
                    </tr>
                    <tr>
                        <th><label for="user_name">User name</label></th>
                        <td><input type="text" name="user_name" id="user_name"
                                value="<?php echo $work_order_id ? esc_attr($work_order->user_name) : ''; ?>" disabled></td>
                    </tr>
                    <tr>
                        <th><label for="equipement_name">Equipment Name</label></th>
                        <td><input type="text" name="equipement_name" id="equipement_name"
                                value="<?php echo $work_order_id ? esc_attr($work_order->equipement_name) : ''; ?>" disabled>
                        </td>
                    </tr>
                    <tr>
                        <th><label for="asset_id">Asset Id</label></th>
                        <td><input type="number" name="asset_id" id="asset_id"
                                value="<?php echo $work_order_id ? esc_attr($work_order->equip_asset_id) : ''; ?>" disabled>
                        </td>
                    </tr>
                    <tr>
                        <th><label for="order_total">Equipment Cost</label></th>
                        <td><input type="text" name="order_total" id="order_total"
                                value="<?php echo $work_order_id ? esc_attr($work_order->order_total) : ''; ?>" disabled>
                        </td>
                    </tr>
                    <tr>
                        <th><label for="location">Location</label></th>
                        <td><input type="text" name="location" id="location"
                                value="<?php echo $work_order_id ? esc_attr($work_order->location) : ''; ?>" disabled></td>
                    </tr>
                    <tr>
                        <th><label for="region">Region</label></th>
                        <td><input type="text" name="region" id="region"
                                value="<?php echo $work_order_id ? esc_attr($work_order->region) : ''; ?>" disabled></td>
                    </tr>

                    <tr>
                        <th><label for="start_date">Contract Start Date</label></th>
                        <td>
                            <input type="text" name="start_date" id="start_date"
                            value="<?php echo esc_attr($start_date ? date('d-m-Y', strtotime($start_date)) : ''); ?>" disabled>
                        </td>
                    </tr>
                    
                    <tr>
                        <th><label for="end_date">Contract End Date</label></th>
                        <td>
                            <input type="text" name="end_date" id="end_date"
                                value="<?php echo esc_attr($end_date ? date('d-m-Y', strtotime($end_date)) : ''); ?>" disabled>
                        </td>
                    </tr>

                    <!-- Success Message Container -->
                    <div id="success-message" style="display: none; color: green; font-weight: bold; margin-bottom: 20px;">
                        Work order generated successfully!
                    </div>

                    <?php if ($is_monthly_sales): ?>
                        <!-- This section is for Monthly Sales -->
                         
                        <tr>
                            <th><label for="monthly_sales_hours">Update Log Hours</label></th>
                            <td><input type="number" name="monthly_log_hours" id="monthly_log_hours"
                                    value="<?php echo $work_order_id ? esc_attr($work_order->monthly_log_hours) : ''; ?>" required></td>
                        </tr>
                        <tr>
                            <th><label for="billing_start_date">Billing Start Date</label></th>
                            <td><input type="date" name="billing_start_date" id="billing_start_date"
                                    value="<?php echo $work_order_id ? esc_attr($work_order->billing_start_date) : ''; ?>" required></td>
                        </tr>
                        <tr>
                            <th><label for="billing_end_date">Billing End Date</label></th>
                            <td><input type="date" name="billing_end_date" id="billing_end_date"
                                    value="<?php echo $work_order_id ? esc_attr($work_order->billing_end_date) : ''; ?>" required></td>
                        </tr>
                        
                    <?php else: ?>
                        <!-- Normal fields for work orders -->
                        <tr>
                            <th><label for="pdi_document">Upload PDI (PDF)</label></th>
                            <td>
                                <input type="file" name="pdi_document" id="pdi_document" accept="application/pdf" <?php echo $is_pdi_uploaded ? 'disabled' : ''; ?> onchange="validatePDF(this)">
                                <?php if ($is_pdi_uploaded): ?>
                                    <p>Current PDI: <a href="<?php echo esc_url($work_order->pdi_document_file_path); ?>"
                                            target="_blank"><?php echo basename($work_order->pdi_document_file_path); ?></a></p>
                                <?php endif; ?>
                            </td>
                        </tr>
                        <tr>
                            <th><label for="shipping_document">Upload Shipping Document (PDF)</label></th>
                            <td>
                                <input type="file" name="shipping_document" id="shipping_document" accept="application/pdf" <?php echo $is_shipping_uploaded ? 'disabled' : ''; ?> onchange="validatePDF(this)">
                                <?php if ($is_shipping_uploaded): ?>
                                    <p>Current Shipping Document: <a
                                            href="<?php echo esc_url($work_order->shipping_document_file_path); ?>"
                                            target="_blank"><?php echo basename($work_order->shipping_document_file_path); ?></a></p>
                                <?php endif; ?>
                            </td>
                        </tr>
                        <script>
                            function validatePDF(input) {
                                const file = input.files[0];
                                if (file && file.type !== 'application/pdf') {
                                    alert("Please upload a valid PDF file.");
                                    input.value = ''; // Clear the input
                                }
                            }
                        </script>
                    <?php endif; ?>
                    <!-- Aseema --> 
                    <script>
                        document.addEventListener("DOMContentLoaded", function () {
                            const contractStartDate = document.getElementById("start_date");
                            const contractEndDate = document.getElementById("end_date");
                            const billingStartDate = document.getElementById("billing_start_date");
                            const billingEndDate = document.getElementById("billing_end_date");

                            // Set minimum date for billing start date based on contract start date
                            if (contractStartDate && billingStartDate) {
                                billingStartDate.min = contractStartDate.value;
                                
                                contractStartDate.addEventListener("change", function () {
                                    billingStartDate.min = contractStartDate.value;
                                });
                            }

                            // Set minimum date for billing end date after billing start date
                            if (billingStartDate && billingEndDate) {
                                billingEndDate.min = billingStartDate.value;
                                
                                billingStartDate.addEventListener("change", function () {
                                    billingEndDate.min = billingStartDate.value;
                                });
                            }

                            // Set maximum date for billing end date based on contract end date
                            if (contractEndDate && billingEndDate) {
                                billingEndDate.max = contractEndDate.value;
                                
                                contractEndDate.addEventListener("change", function () {
                                    billingEndDate.max = contractEndDate.value;
                                });
                            }
                        });
                    </script>

                </table>

                <p class="submit">
                    <?php if ($is_monthly_sales): ?>
                        <!-- Check if monthly_log_hours is greater than 0 -->
                        <?php if ($monthly_log_hours <= 0 && $order_status === 'work_location'): ?>
                            <!-- Submit button for monthly sales -->
                            <input type="submit" name="save_monthly_log" id="save_monthly_log" class="button button-primary"
                                value="Save Monthly Work Order">
                        <?php endif; ?>

                        <!-- Cancel button -->
                        <a href="<?php echo esc_url(admin_url("admin.php?page=work_orders")); ?>"
                            class="button button-primary">Cancel</a>

                        <?php if ($monthly_log_hours > 0): ?>
                            <!-- If monthly_log_hours is greater than 0, show these buttons -->
                            <input type="submit" name="edit_monthly_log" id="edit_monthly_log" class="button button-primary"
                                value="Save Log Hours">

                            <!-- Create Sales Order button -->
                            <!-- <a href="<?php echo esc_url(admin_url('admin.php?page=create_sales_order&work_order_id=' . $work_order_id)); ?>"
                                class="button button-primary">
                                Create Sales Order
                            </a> -->
                            <input type="submit" class="button-primary" value="Generate Sales Order" name="create_saless_order"
                            <?php echo $existing_sales_order ? 'disabled' : ''; ?> />
                        <?php endif; ?>
                    <?php else: ?>
                        <!-- Normal buttons if not monthly sales -->
                        <input type="submit" name="upload_pdi" id="upload_pdi" class="button button-primary" value="Upload PDI"
                            <?php echo $is_pdi_uploaded ? 'disabled' : ''; ?>>
                        <input type="submit" name="upload_shipping_document" id="upload_shipping_document"
                            class="button button-primary" value="Upload Shipping Document" <?php echo $is_shipping_uploaded ? 'disabled' : ''; ?>>

                        <!-- Generate Work Order button -->
                        <input type="submit" name="generate_work_order" id="generate_work_order" class="button button-primary"
                            value="Generate Work Order" <?php echo (!$is_pdi_uploaded || !$is_shipping_uploaded || $is_work_order_generated) ? 'disabled' : ''; ?>>

                        <!-- Reset button -->
                        <input type="button" id="reset_form" class="button button-primary" value="Reset">

                        <!-- Cancel button -->
                        <a href="<?php echo esc_url(admin_url("admin.php?page=work_orders")); ?>"
                            class="button button-primary">Cancel</a>

                    <div id="work-order-success-message" style="margin-top: 20px; color: green; font-weight: bold; display: none;">
                        Generate Work Order successfully!
                    </div>
                <?php endif; ?>
                </p>

                <?php if (!empty($this->pdi_success_message)): ?>
                    <div class="notice notice-success">
                        <p><?php echo esc_html($this->pdi_success_message); ?></p>
                    </div>
                <?php endif; ?>
                <!-- Success Message Container for Save Monthly Work Order -->
               <?php
               if (empty($billing_start_date) || empty($billing_end_date)) {
                    echo '<div class="notice notice-error"><p>Please fill in both Billing Start Date and Billing End Date.</p></div>';
                } else {
                // Proceed to save the data and display the success message
                $success_message = 'Monthly Work Order saved successfully!';
                }
               ?>
                <div id="edit_monthly_log-success-message" style="display: none; color: green; font-weight: bold; margin-bottom: 20px;">
                    Log Hours Updated Successfully!
                </div>
            </form>
        </div>

        <script>
            document.addEventListener('DOMContentLoaded', function () {
                var saveMonthlyWorkOrderButton = document.getElementById('save_monthly_log');
                if (saveMonthlyWorkOrderButton) {
                    saveMonthlyWorkOrderButton.addEventListener('click', function (event) {
                        // Show the success message for Save Monthly Work Order
                        document.getElementById('monthly-work-order-success-message').style.display = 'block';
                    });
                }

                var editMonthlyLogButton = document.getElementById('edit_monthly_log');
                if (editMonthlyLogButton) {
                    editMonthlyLogButton.addEventListener('click', function (event) {
                        // Show the success message for Save Monthly Work Order
                        document.getElementById('edit_monthly_log-success-message').style.display = 'block';
                    });
                }

                // Check if localStorage has the item for the monthly work order success message
                // if (localStorage.getItem('monthlyWorkOrderSaved') === 'true') {
                //     // Show the success message
                //     document.getElementById('monthly-work-order-success-message').style.display = 'block';

                //     // Set the message to disappear after 10 seconds on page reload
                //     setTimeout(function () {
                //         document.getElementById('monthly-work-order-success-message').style.display = 'none';

                //         // Clear the localStorage item so the message doesn't keep showing on future reloads
                //         localStorage.removeItem('monthlyWorkOrderSaved');
                //     }, 10000);
                // }

                // Reset button event
                document.getElementById('reset_form').addEventListener('click', function () {
                    // Enable all buttons 
                    document.getElementById('pdi_document').disabled = false;
                    document.getElementById('shipping_document').disabled = false;
                    document.getElementById('upload_pdi').disabled = false;
                    document.getElementById('upload_shipping_document').disabled = false;


                    // Clear the file inputs if necessary
                    document.getElementById('pdi_document').value = '';
                    document.getElementById('shipping_document').value = '';

                    // Clear the localStorage item
                    localStorage.removeItem('workOrderGenerated_' + workOrderId);
                });

                // show success message after generate work order
                var generateWorkOrderButton = document.getElementById('generate_work_order');
                generateWorkOrderButton.addEventListener('click', function (event) {
                    document.getElementById('work-order-success-message').style.display = 'block';
                    setTimeout(function () {
                        document.getElementById('work-order-success-message').style.display = 'none';
                    }, 10000);
                    localStorage.setItem('workOrderGenerated', 'true');
                });

                // Check if localStorage has the item to persist the message visibility on reload
                if (localStorage.getItem('workOrderGenerated') === 'true') {
                    // Show the success message
                    document.getElementById('work-order-success-message').style.display = 'block';

                    // Set the message to disappear after 10 seconds on page reload
                    setTimeout(function () {
                        document.getElementById('work-order-success-message').style.display = 'none';

                        // Clear the localStorage item so the message doesn't keep showing on future reloads
                        localStorage.removeItem('workOrderGenerated');
                    }, 10000);
                }
                


            });
        </script>


        <?php
    }



    public function handle_form_submission()
    {
        global $wpdb;
        $table_name = $wpdb->prefix . 'work_orders';


        // Get the work order ID for update
        $work_order_id = isset($_POST['work_order_id']) ? intval($_POST['work_order_id']) : 0;

        if (isset($_POST['save_monthly_log'])) {
            $monthly_log_hours = isset($_POST['monthly_log_hours']) ? intval($_POST['monthly_log_hours']) : 0; 
            $billing_start_date = isset($_POST['billing_start_date']) ? sanitize_text_field($_POST['billing_start_date']) : '';
            $billing_end_date = isset($_POST['billing_end_date']) ? sanitize_text_field($_POST['billing_end_date']) : '';
            if ($monthly_log_hours > 0 && !empty($billing_start_date)) {
                // Fetch the existing work order details
                $existing_order = $wpdb->get_row($wpdb->prepare("SELECT * FROM $table_name WHERE id = %d", $work_order_id));

                if ($existing_order) {
                    // Insert a new row with the updated monthly log hours
                    $insert_result = $wpdb->insert(
                        $table_name,
                        array(
                            'contract_id' => $existing_order->contract_id,
                            'user_id' => $existing_order->user_id,
                            'user_name' => $existing_order->user_name,
                            'created_date' => current_time('mysql'),
                            'pdi_document_file_path' => $existing_order->pdi_document_file_path,
                            'shipping_document_file_path' => $existing_order->shipping_document_file_path,
                            'equipement_name' => $existing_order->equipement_name,
                            'location' => $existing_order->location,
                            'region' => $existing_order->region,
                            'monthly_log_hours' => $monthly_log_hours,
                            'wo_type' => "Monthly Work Order",
                            'is_work_order_generated' => 1,
                            'min_monthly_hours'=> $existing_order->min_monthly_hours,
                            'contract_monthly_rate'=> 330000,
                            'start_date' => $existing_order->start_date,
                            'end_date'=>$existing_order->end_date,
                            'billing_start_date'=>$billing_start_date,
                            'billing_end_date'=>$billing_end_date,
                            'order_total' => $existing_order->order_total,
                            'equip_asset_id' => $existing_order->equip_asset_id,
                        ),
                        array(
                            '%d',  // contract_id (Integer)
                            '%d', 
                            '%s', // user_id (Integer)
                            '%s',  // created_date (String)
                            '%s',  // pdi_document_file_path (String)
                            '%s',  // shipping_document_file_path (String)
                            '%s',  // equipement_name (Integer)
                            '%s',  // location (String)
                            '%s',  // region (String)
                            '%d',  // monthly_log_hours (Integer)
                            '%s',  // wo_type (String)
                            '%d',  // is_work_order_generated (Integer, Boolean-like)
                            '%d',  // min_monthly_hours (Integer)
                            '%f',  // contract_monthly_rate (Float/Integer)
                            '%s',  // monthly_order_start_date (String, Date)
                            '%s' ,
                            '%s' ,
                            '%s' ,
                            '%s' ,
                            '%s'


                        )
                        );

                    if ($insert_result === false) {
                        echo '<div class="error"><p>Error inserting the new monthly log hours.</p></div>';
                    } else { 
                    wp_redirect(admin_url('admin.php?page=work_orders'));
                    exit;
                    }
                } else {
                    echo '<div class="error"><p>Work order not found.</p></div>';
                }
            } else {
                echo '<div class="error"><p>Invalid monthly log hours value.</p></div>';
            }
        }
        if (isset($_POST['edit_monthly_log'])) {
            $monthly_log_hours = isset($_POST['monthly_log_hours']) ? intval($_POST['monthly_log_hours']) : 0;
            $billing_start_date = isset($_POST['billing_start_date']) ? sanitize_text_field($_POST['billing_start_date']) : '';
            $billing_end_date = isset($_POST['billing_end_date']) ? sanitize_text_field($_POST['billing_end_date']) : '';
            // Get the start and end date for the update
            
            if ($monthly_log_hours > 0 && !empty($billing_start_date)) {
                // Update the work order with the new log hours, start date, and end date
                $update_result = $wpdb->update(
                    $table_name,
                    array(
                        'monthly_log_hours' => $monthly_log_hours,
                        'billing_start_date' => $billing_start_date,
                        'billing_end_date' => $billing_end_date,
                    ),
                    array('id' => $work_order_id),
                    array(
                        '%d',  // monthly_log_hours (Integer)
                        '%s',
                        '%s',  // billing_end_date 
                    ),
                    array('%d') // Condition: work_order_id (Integer)
                );


                if ($update_result === false) {
                    echo '<div class="error"><p>Error updating the monthly log hours.</p></div>';
                } else {
                    wp_redirect(add_query_arg('log_hours_updated', 'true', wp_get_referer()));
                    exit;
                }
            } else {
                echo '<div class="error"><p>Invalid monthly log hours value.</p></div>';
            }
        }

        if (isset($_POST['submit_work_order']) || isset($_POST['upload_pdi']) || isset($_POST['upload_shipping_document']) || isset($_POST['save_monthly_log'])) {
            // Verify nonce
            if (!isset($_POST['work_order_form_nonce']) || !wp_verify_nonce($_POST['work_order_form_nonce'], 'save_work_order_form')) {
                return;
            }

            // Get the work order ID for update
            $work_order_id = isset($_POST['work_order_id']) ? intval($_POST['work_order_id']) : 0;

            if ($work_order_id) {
                // Initialize file path variables
                $pdi_file_path = '';
                $pdi_success_message = ''; // Store success message here

                // Handle PDI file upload only if the "Upload PDI" button was clicked
                if (isset($_POST['upload_pdi'])) {
                    if (isset($_FILES['pdi_document']) && $_FILES['pdi_document']['error'] === UPLOAD_ERR_OK) {
                        $pdi_upload = wp_handle_upload($_FILES['pdi_document'], array('test_form' => false));

                        if ($pdi_upload && !isset($pdi_upload['error'])) {
                            $pdi_file_path = $pdi_upload['url'];

                            // Update PDI file path in the database
                            $wpdb->update(
                                $table_name,
                                array('pdi_document_file_path' => $pdi_file_path),
                                array('id' => $work_order_id),
                                array('%s'),
                                array('%d')
                            );

                            // Set success message for PDI update
                            $pdi_success_message = 'PDI document updated successfully!';
                        } else {
                            // Handle upload error and show error message
                            echo '<div class="error"><p>Error uploading the PDI file: ' . esc_html($pdi_upload['error']) . '</p></div>';
                            return;
                        }
                    } else {
                        // If no file was selected or another error occurred
                        echo '<div class="error"><p>Please select a valid PDI document (PDF) for upload.</p></div>';
                        return;
                    }
                }

                if (isset($_POST['upload_shipping_document'])) {
                    if (isset($_FILES['shipping_document']) && $_FILES['shipping_document']['error'] === UPLOAD_ERR_OK) {
                        $shipping_upload = wp_handle_upload($_FILES['shipping_document'], array('test_form' => false));

                        if ($shipping_upload && !isset($shipping_upload['error'])) {
                            $shipping_file_path = $shipping_upload['url'];

                            // Update Shipping document file path in the database
                            $wpdb->update(
                                $table_name,
                                array('shipping_document_file_path' => $shipping_file_path),
                                array('id' => $work_order_id),
                                array('%s'),
                                array('%d')
                            );

                            // Set success message for Shipping document update
                            $pdi_success_message = 'Shipping document updated successfully!';
                        } else {
                            // Handle upload error and show error message
                            echo '<div class="error"><p>Error uploading the Shipping document: ' . esc_html($shipping_upload['error']) . '</p></div>';
                            return;
                        }
                    } else {
                        // If no file was selected or another error occurred
                        echo '<div class="error"><p>Please select a valid Shipping document (PDF) for upload.</p></div>';
                        return;
                    }
                }

                // Handle full form submission (update both PDI and Shipping document)
                if (isset($_POST['submit_work_order'])) {
                    // Handle Shipping document file upload
                    if (isset($_FILES['shipping_document']) && $_FILES['shipping_document']['error'] === UPLOAD_ERR_OK) {
                        $shipping_upload = wp_handle_upload($_FILES['shipping_document'], array('test_form' => false));

                        if ($shipping_upload && !isset($shipping_upload['error'])) {
                            $shipping_file_path = $shipping_upload['url'];

                            // Update Shipping document path in the database
                            $wpdb->update(
                                $table_name,
                                array('shipping_document_file_path' => $shipping_file_path),
                                array('id' => $work_order_id),
                                array('%s'),
                                array('%d')
                            );
                        } else {
                            echo '<div class="error"><p>Error uploading the Shipping file: ' . esc_html($shipping_upload['error']) . '</p></div>';
                            return;
                        }
                    }
                }

                // If a PDI success message exists, store it in the class property for displaying later
                if (!empty($pdi_success_message)) {
                    $this->pdi_success_message = $pdi_success_message;
                }
            }
        }
    }

    public function display_create_sales_order_form() {
        global $wpdb;
    
        // Get work_order_id from query string
        $work_order_id = isset($_GET['work_order_id']) ? intval($_GET['work_order_id']) : 0;
    
        // Debugging: Output the work_order_id
        // echo '<p>Debug: Work Order ID = ' . esc_html($work_order_id) . '</p>';
    
        // Fetch existing data from the wp_work_orders table based on work_order_id
        $result = $wpdb->get_row($wpdb->prepare("SELECT contract_id, user_id,user_name,equipement_name, region, location, monthly_log_hours, min_monthly_hours,contract_monthly_rate,min_monthly_hours,start_date,end_date,order_total,equip_asset_id ,billing_start_date,billing_end_date FROM wp_work_orders WHERE id = %d", $work_order_id));
    
        if ($result) {
            $contract_id = $result->contract_id;
            $user_id = $result->user_id;
            $user_name = $result->user_name;
            $equipement_name = $result->equipement_name;
            $region = $result->region;
            $location = $result->location;
            $contract_monthly_rate = $result->contract_monthly_rate;
            $min_monthly_hours = $result->min_monthly_hours;
            $monthly_log_hours = floatval($result->monthly_log_hours);
            $min_monthly_hours = floatval($result->min_monthly_hours);
            $start_date = $result->start_date;
            $end_date = $result->end_date;
            $equipement_cost = $result->order_total;
            $equip_asset_id = $result->equip_asset_id;
            $billing_start_date = $result->billing_start_date;
            $billing_end_date = $result->billing_end_date;
    
            // Compare and set the greater value for billing hours
            $min_hour_billing = max($monthly_log_hours, $min_monthly_hours);
        } else {
            $contract_id = '';
            echo '<div class="error"><p>No work order found with the provided ID.</p></div>';
        }
    
        // Check if the sales order already exists based on work_order_id
        $existing_sales_order = $wpdb->get_row($wpdb->prepare("SELECT id, min_hour_billing FROM wp_sales_order WHERE work_order_id = %d", $work_order_id));
    
        // Initialize min_hour_billing from form data (only if a form submission happened)
        if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['min_hour_billing'])) {
            $min_hour_billing = sanitize_text_field($_POST['min_hour_billing']);
        }
    
        if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['update_log_hours'])) {
            if ($existing_sales_order) {
                // If a sales order exists, update the existing row
                $wpdb->update(
                    'wp_sales_order',
                    array('min_hour_billing' => $min_hour_billing),
                    array('work_order_id' => $work_order_id),
                    array('%s'),
                    array('%d')
                );
    
                if ($wpdb->last_error) {
                    echo '<div class="error"><p>Error updating sales order: ' . esc_html($wpdb->last_error) . '</p></div>';
                } else {
                    echo '<div class="updated"><p>Sales Order updated successfully!</p></div>';
                }
            } else {
                // If no sales order exists, insert a new row
                $wpdb->insert(
                    'wp_sales_order',
                    array(
                        'work_order_id' => $work_order_id,
                        'contract_id' => $contract_id,
                        'min_hour_billing' => $min_hour_billing,
                        'user_id' => $user_id,
                        'user_name' => $user_name,
                        'equipement_name' => $equipement_name,
                        'region' => $region,
                        'location' => $location,
                        'contract_monthly_rate'=>$contract_monthly_rate,
                        'min_monthly_hours' => $min_monthly_hours,
                        'start_date' => $start_date,
                        'end_date' => $end_date,
                        'created_date' => current_time('mysql'),
                        'created_by' => 'admin',
                        'order_total' => $equipement_cost,
                        'equip_asset_id'  => $equip_asset_id,
                        'billing_start_date'  => $billing_start_date,
                        'billing_end_date'  => $billing_end_date
                    ),
                    array(
                        '%d',  // work_order_id
                        '%d',  // contract_id
                        '%f',  // min_hour_billing (float)
                        '%d', // user_id
                        '%s',  
                        '%s',  // 
                        '%s',  // region
                        '%s',  // location
                        '%f',  // contract_monthly_rate (float)
                        '%f',  // min_monthly_hours (float)
                        '%s',  // start date (string)
                        '%s',
                        '%s',  // created_date (string in MySQL datetime format)
                        '%s',// created_by (string, could be user ID or username)
                        '%s',
                        '%s' ,
                        '%s',
                        '%s'
                    )
                );
    
                if ($wpdb->last_error) {
                    echo '<div class="error"><p>Error inserting new sales order: ' . esc_html($wpdb->last_error) . '</p></div>';
                } else {
                    echo '<div class="updated"><p>New Sales Order created successfully!</p></div>';
                    wp_redirect(admin_url('admin.php?page=sales-order-listing'));
                    exit;
                }
            }
        }
    
        // Display the form
        ?>
        <?php

            $contract_id = $result ->contract_id;

            $start_date = '';
            $end_date = '';
            if ($contract_id) {
                $start_date = get_post_meta($contract_id, 'start_date', true); 
                $end_date = get_post_meta($contract_id, 'end_date', true);
            }
        ?>

        <div class="wrap">
            <h1>Edit Sales Order</h1>
            <form method="post" action="">
                <table class="form-table">
                    <tr valign="top" style="display:none;">
                        <th scope="row">Sales Order ID</th>
                        <td><input type="text" name="sales_order_id" value="<?php echo esc_attr($existing_sales_order ? $existing_sales_order->id : ''); ?>" readonly></td>
                    </tr>
                    <tr valign="top">
                        <th scope="row">Work Order ID</th>
                        <td><input type="number" name="work_order_id" value="<?php echo esc_attr($work_order_id); ?>" readonly disabled></td>
                    </tr>
                    <tr valign="top">
                        <th scope="row">Contract ID</th>
                        <td><input type="number" name="contract_id" value="<?php echo esc_attr($contract_id); ?>" readonly disabled></td>
                    </tr>
                    <tr valign="top">
                        <th scope="row">User name</th>
                        <td><input type="text" name="user_name" value="<?php echo esc_attr($user_name); ?>" readonly disabled></td>
                    </tr>
                    <tr valign="top">
                        <th scope="row">Equipment Name</th>
                        <td><input type="text" name="equipement_name" value="<?php echo esc_attr($equipement_name); ?>" readonly disabled></td>
                    </tr>
                    <tr valign="top">
                        <th scope="row">Asset ID</th>
                        <td><input type="text" name="asset_id" value="<?php echo esc_attr($equip_asset_id); ?>" readonly disabled></td>
                    </tr>
                    <tr valign="top">
                        <th scope="row">Equipment Cost</th>
                        <td><input type="text" name="order_total" value="<?php echo esc_attr($equipement_cost); ?>" readonly disabled></td>
                    </tr>
                    <tr valign="top">
                        <th scope="row">Region</th>
                        <td><input type="text" name="region" value="<?php echo esc_attr($region); ?>" readonly disabled></td>
                    </tr>
                    <tr valign="top">
                        <th scope="row">Location</th>
                        <td><input type="text" name="location" value="<?php echo esc_attr($location); ?>" readonly disabled></td>
                    </tr>
                    <tr valign="top">
                        <th scope="row">Billing Hours</th>
                        <td><input type="text" name="min_hour_billing" value="<?php echo esc_attr($min_hour_billing); ?>" readonly disabled></td>
                    </tr>
                    <tr valign="top">
                        <th scope="row">Billing Start Date</th>
                        <td><input type="text" name="billing_start_date" value="<?php echo esc_attr(date('d-m-Y', strtotime($billing_start_date))); ?>" readonly disabled></td>
                    </tr>
                    <tr valign="top">
                        <th scope="row">Billing End Date</th>
                        <td><input type="text" name="billing_end_date" value="<?php echo esc_attr(date('d-m-Y', strtotime($billing_end_date))); ?>" readonly disabled></td>
                    </tr>
                    <!-- <?php echo  $start_date;?> -->
                    <tr>
                        <th><label for="start_date">Contract Start Date</label></th>
                        <td>
                            <input type="text" name="start_date" id="start_date"
                            value="<?php echo esc_attr($start_date ? date('d-m-Y', strtotime($start_date)) : ''); ?>" disabled>
                        </td>
                    </tr>
                    <tr>
                        <th><label for="end_date">Contract End Date</label></th>
                        <td>
                            <input type="text" name="end_date" id="end_date"
                                value="<?php echo esc_attr($end_date ? date('d-m-Y', strtotime($end_date)) : ''); ?>" disabled>
                        </td>
                    </tr>
                </table>
                <p class="submit">
                   
                        <a href="<?php echo esc_url(admin_url('admin.php?page=create_invoice&id=' . ($existing_sales_order ? $existing_sales_order->id : ''))); ?>" class="button button-primary">Caliculate RMS Invoice Value</a>
                    <a href="<?php echo esc_url(admin_url('admin.php?page=add_work_order&action=edit&id=' . $work_order_id . '&monthly_sales=true')); ?>" class="button button-primary">Cancel</a>
                </p>
            </form>
        </div>
        <?php
    }
    
  
    // invoice form
   
   
    function display_create_invoice_form() {
        global $wpdb;
    
        // Get the sale order ID from the URL query parameter (e.g., ?id=123)
        if (isset($_GET['id']) && is_numeric($_GET['id'])) {
            $sale_order_id = intval($_GET['id']); // Ensure it's a valid integer
    
            // Fetch the details from wp_sales_order table for the given sale_order_id
            $result = $wpdb->get_row($wpdb->prepare(
                "SELECT contract_id, user_id,user_name,equipement_name, region, min_hour_billing,contract_monthly_rate, min_monthly_hours,start_date,end_date, location,order_total,equip_asset_id,billing_start_date,billing_end_date
                FROM wp_sales_order 
                WHERE id = %d",
                $sale_order_id
            ));
    
           
            // Check if the result exists
            if ($result) {
                // Extract details
                $contract_id = isset($result->contract_id) ? $result->contract_id : '';
                $min_hour_billing = isset($result->min_hour_billing) ? $result->min_hour_billing : '';
                $contract_monthly_rate = isset($result->contract_monthly_rate) ? $result->contract_monthly_rate : '';
                $order_total = isset($result->order_total) ? $result->order_total : '';
                $min_monthly_hours = isset($result->min_monthly_hours) ? $result->min_monthly_hours : 0;
                $user_id = isset($result->user_id) ? $result->user_id : '';
                $user_name = isset($result->user_name) ? $result->user_name : '';
                $equipement_name = isset($result->equipement_name) ? $result->equipement_name : '';
                $region = isset($result->region) ? $result->region : '';
                $location = isset($result->location) ? $result->location : '';
                $start_date= isset($result->start_date) ? $result->start_date : '';
                $end_date= isset($result->end_date) ? $result->end_date : '';
              
                $order_start_date = get_post_meta($contract_id, 'start_date', true);
                $order_end_date = get_post_meta($contract_id, 'end_date', true);


                if(!empty($order_start_date)&&!empty($order_end_date)) {
                    // Convert date strings to DateTime objects
                    $start = new DateTime($order_start_date);
                    $end = new DateTime($order_end_date);
                    
                    // Calculate total days between start and end dates
                    $total_days = $start->diff($end)->days + 1; // +1 to include end date
                }
                $total_hours = $total_days * 8;
                $hour_price = $order_total / $total_hours ;
                // Calculate invoice value
                $invoice_value = round(($order_total > 0 ? $hour_price : 0) * $min_hour_billing);
                $equip_asset_id = isset($result->equip_asset_id) ? $result->equip_asset_id : '';
                $billing_start_date = isset($result->billing_start_date) ? $result->billing_start_date : '';
                $billing_end_date = $result->billing_end_date;
    
                // // Check if the form was submitted with the submit_invoice button
                // if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['submit_invoice'])) {
                //     // Sanitize the input
                //     $new_invoice_value = sanitize_text_field($_POST['invoice_value']);  
                //     // Insert a new record into wp_order_invoice_details table
                //     $wpdb->insert(
                //         'wp_order_invoice_details', // Table name
                //         array(
                //             'sale_order_id'       => $sale_order_id,
                //             'contract_id'         => $contract_id,
                //             'user_id'             => $user_id,
                //             'user_name'           => $user_name,
                //             'equipement_name'     => $equipement_name, // Correct field name and value
                //             'region'              => $region,
                //             'location'            => $location,
                //             'min_hour_billing'    => $min_hour_billing,
                //             'invoice_value'       => $new_invoice_value,
                //             'created_date'        => current_time('mysql'),
                //             'start_date' => $start_date,
                //             'end_date'   => $end_date,
                //             'created_by'          => "aseema@gmail.com",
                //             'order_total'     => $order_total,
                //             'equip_asset_id' => $equip_asset_id,
                //             'billing_start_date' => $billing_start_date,
                //             'billing_end_date' => $billing_end_date,
                //         ),
                //         array(
                //             '%d',  // sale_order_id format (integer)
                //             '%d',  // contract_id format (integer)
                //             '%d',  // user_id format (integer)
                //             '%s',  // user_name format (string)
                //             '%s',  // equipement_name format (string) — Corrected to string format
                //             '%s',  // region format (string)
                //             '%s',  // location format (string)
                //             '%d',  // min_hour_billing format (integer)
                //             '%f',  // invoice_value format (float)
                //             '%s',  // created_date format (string, datetime)
                //             '%s',  // monthly_order_start_date format (string, date)
                //             '%s',  // monthly_order_end_date format (string, date)
                //             '%s' ,// created_by format (string)
                //             '%s' ,
                //             '%s',
                //             '%s',
                //             '%s'

                //         )
                //     );

                //     // After successful insertion, set a transient or option to flag the submission
                //     set_transient('invoice_submitted_' . $sale_order_id, true, 12 * HOUR_IN_SECONDS);

    
                //     echo '<div class="updated"><p>Invoice Value updated and new invoice record created successfully!</p></div>';

                //     wp_redirect(admin_url('admin.php?page=invoice-order-listing'));
                //     exit; 
                // }
    
                if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['submit_invoice'])) {
                    // Sanitize the input
                    $new_invoice_value = sanitize_text_field($_POST['invoice_value']);  
                   
                    try {
                        // Insert a new record into wp_order_invoice_details table
                        $result = $wpdb->insert(
                            'wp_order_invoice_details',
                            array(
                                'sale_order_id'       => $sale_order_id,
                                'contract_id'         => $contract_id,
                                'user_id'             => $user_id,
                                'user_name'           => $user_name,
                                'equipement_name'     => $equipement_name,
                                'region'              => $region,
                                'location'            => $location,
                                'min_hour_billing'    => $min_hour_billing,
                                'invoice_value'       => $new_invoice_value,
                                'created_date'        => current_time('mysql'),
                                'start_date'          => $start_date,
                                'end_date'            => $end_date,
                                'created_by'          => "aseema@gmail.com",
                                'order_total'         => $order_total,
                                'equip_asset_id'      => $equip_asset_id,
                                'billing_start_date'  => $billing_start_date,
                                'billing_end_date'    => $billing_end_date
                                
                               
                            ),
                            array(
                                '%d', '%d', '%d', '%s', '%s', '%s', '%s', '%d', '%f', 
                                '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s'
                            )
                        );
                 
                        if ($result === false) {
                            throw new Exception($wpdb->last_error);
                        }
                
                        // Set transient after successful DB insertion
                        set_transient('invoice_submitted_' . $sale_order_id, true, 12 * HOUR_IN_SECONDS);
                
                        // Trigger API call after successful DB insertion
                        $api_result = $this->invoice_api->trigger_invoice_api($contract_id);
                        if (!$api_result['success']) {
                            // If API fails, optionally rollback the database insertion
                            $wpdb->delete(
                                'wp_order_invoice_details',
                                array('sale_order_id' => $sale_order_id),
                                array('%d')
                            );
                            throw new Exception('API Error: ' . ($api_result['message'] ?? 'Unknown error'));
                        }
                        elseif ($api_result['success']) {
                             $invoice_number = $api_result['invoice_number'];
                             $invoice_date = date('Y-m-d', strtotime($api_result['invoice_date']));
                            $update_query = $wpdb->prepare(
                                "UPDATE {$wpdb->prefix}order_invoice_details 
                                 SET invoice_number = %s, 
                                     invoice_date = %s                                      
                                 WHERE contract_id = %d AND sale_order_id = %d",
                                sanitize_text_field($invoice_number),
                                sanitize_text_field($invoice_date),                                
                                $contract_id,
                                $sale_order_id
                            );
                        
                            $update_result = $wpdb->query($update_query);
                        
                            if ($update_result === false) {
                                error_log("Update failed: " . $wpdb->last_error);
                            }
                        }
                
                        // If everything succeeds, set success message and redirect
                        set_transient('invoice_message', 'Invoice Value updated and new invoice record created successfully!', 30);
                       
                        // trigger email 
                       // if ($api_result['success']) {
                        //do_action('invoice_created_notification', $sales_order_id, $result);    
                        //}                   
                        wp_redirect(admin_url('admin.php?page=invoice-order-listing'));
                        exit;
                
                    } catch (Exception $e) {
                        // Log error for debugging
                        error_log('Invoice Creation Error: ' . $e->getMessage());
                        
                        // Display error message to user
                        echo '<div class="error"><p>Error: ' . esc_html($e->getMessage()) . '</p></div>';
                    }
                }
                
                // Display success/error messages from transients (add this at the beginning of your form display)
                if ($message = get_transient('invoice_message')) {
                    echo '<div class="updated"><p>' . esc_html($message) . '</p></div>';
                    delete_transient('invoice_message');
                }
                ?>
                <?php

                $contract_id = $result ->contract_id;

                $start_date = '';
                $end_date = '';
                if ($contract_id) {
                    $start_date = get_post_meta($contract_id, 'start_date', true); 
                    $end_date = get_post_meta($contract_id, 'end_date', true);
                }
                ?>
                <div class="wrap">
                    <h1>Edit Sales Invoice Form</h1>
                    <form method="post" action="">
                        <table class="form-table">
                            <tr valign="top">
                                <th scope="row">Contract ID</th>
                                <td>
                                    <input type="number" name="contract_id" value="<?php echo esc_attr($contract_id); ?>" required disabled>
                                </td>
                            </tr>
    
                            <tr valign="top">
                                <th scope="row">Sale Order ID</th>
                                <td>
                                    <input type="number" name="sale_order_id" value="<?php echo esc_attr($sale_order_id); ?>" required disabled>
                                </td>
                            </tr>
    
                            <tr valign="top">
                                <th scope="row">Minimum Hour Billing</th>
                                <td>
                                    <input type="number" name="min_hour_billing" value="<?php echo esc_attr($min_hour_billing); ?>" required disabled>
                                </td>
                            </tr>
    
                            <tr valign="top">
                                <th scope="row">User name</th>
                                <td>
                                    <input type="text" name="user_name" value="<?php echo esc_attr($user_name); ?>" required disabled>
                                </td>
                            </tr>
    
                            <tr valign="top">
                                <th scope="row">Equipment name</th>
                                <td>
                                    <input type="text" name="equipement_name" value="<?php echo esc_attr($equipement_name); ?>" required disabled>
                                </td>
                            </tr>

                            <tr valign="top">
                                <th scope="row">Asset Id</th>
                                <td>
                                    <input type="number" name="asset_id" value="<?php echo esc_attr($equip_asset_id); ?>" required disabled>
                                </td>
                            </tr>

                            <tr valign="top">
                                <th scope="row">Equipment Cost</th>
                                <td>
                                    <input type="text" name="order_total" value="<?php echo esc_attr($order_total); ?>" required disabled>
                                </td>
                            </tr>
    
                            <tr valign="top">
                                <th scope="row">Region</th>
                                <td>
                                    <input type="text" name="region" value="<?php echo esc_attr($region); ?>" required disabled>
                                </td>
                            </tr>
    
                            <tr valign="top">
                                <th scope="row">Location</th>
                                <td>
                                    <input type="text" name="location" value="<?php echo esc_attr($location); ?>" required disabled>
                                </td>
                            </tr>
                            <tr valign="top">
                                <th scope="row">Billing Start Date</th>
                                <td>
                                    <input type="text" name="billing_start_date" value="<?php echo $billing_start_date ? date('d-m-Y', strtotime($billing_start_date)) : ''; ?>"  required disabled>
                                </td>
                            </tr>
                            <tr valign="top">
                                <th scope="row">Billing End Date</th>
                                <td>
                                    <input type="date" name="billing_end_date" value="<?php echo $billing_end_date ? date('d-m-Y', strtotime($billing_end_date)) : ''; ?>" required disabled>
                                </td>
                            </tr>
                            <tr>
                                <th><label for="start_date">Contract Start Date</label></th>
                                <td>
                                    <input type="text" name="start_date" id="start_date"
                                        value="<?php echo esc_attr($start_date ? date('d-m-Y', strtotime($start_date)) : ''); ?>" disabled>
                                </td>
                            </tr>
                            <tr>
                                <th><label for="end_date">Contract End Date</label></th>
                                <td>
                                    <input type="text" name="end_date" id="end_date"
                                        value="<?php echo esc_attr($end_date ? date('d-m-Y', strtotime($end_date)) : ''); ?>" disabled>
                                </td>
                            </tr>
    
                            <tr valign="top">
                                <th scope="row">Invoice Value</th>
                                <td>
                                    <input type="number" name="invoice_value" value="<?php echo esc_attr($invoice_value); ?>" required readonly>
                                </td>
                            </tr>
                        </table>
                        <p class="submit">
                            <input type="submit" id="submit_invoice" name="submit_invoice" class="button-primary" value="Get SAP Invoice Details" />
                        </p>
                    </form>
                </div>
                <?php
            } else {
                echo "<p>No sales order found for ID: " . esc_html($sale_order_id) . "</p>";
            }
        } else {
            echo "<p>Invalid or missing Sale Order ID.</p>";
        }
    }
}


// Initialize the plugin
new WorkOrdersPlugin();

function hide_screen_options_for_work_orders() {
    ?>
    <style>
    <?php 
    if (isset($_GET['page']) && ( $_GET['page'] === 'work_orders' || $_GET['page'] === 'add_work_order' )) : ?>
        #screen-meta-links {
            display: none !important;
        }
    <?php endif; ?>
    </style>
    <?php
}
add_action('admin_head', 'hide_screen_options_for_work_orders');
function workOrderNotification() {
    if (is_user_logged_in()) {
        global $wpdb;
        $user_id = get_current_user_id();

        // Query to get 'First work order' where 'is_work_order_generated' = 1
        $work_order = $wpdb->get_row($wpdb->prepare(
            "SELECT id, contract_id 
             FROM wp_work_orders 
             WHERE wo_type = 'First work order' 
             AND is_work_order_generated = 1 
             ORDER BY updated_at DESC 
             LIMIT 1",
            $user_id
        ));

        if ($work_order) {
            // Check if a 'Monthly Work Order' exists for the same contract_id
            $monthly_work_order = $wpdb->get_var($wpdb->prepare(
                "SELECT COUNT(*) 
                 FROM wp_work_orders 
                 WHERE wo_type = 'Monthly Work Order' 
                 AND contract_id = %d",
                $work_order->contract_id
            ));

            // Show notification only if no 'Monthly Work Order' exists
            if ($monthly_work_order == 0) {
                echo '<div class="woocommerce-info">      
                <span>First work order created and Equipement Shipped Successfully.</span>               
                <a href="' . esc_url(home_url('/my-account/contracts')) . '" class="button wc-forward" style="display: inline-block; background-color:#000;padding:5px 10px;border-radius:5px;font-size:13px;">
                        View Contracts
                    </a>             
                </div>';
            }
        }
    }
}

add_action('woocommerce_account_notification_endpoint', 'workOrderNotification');
?>


Youez - 2016 - github.com/yon3zu
LinuXploit