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

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

Upload File :
current_dir [ Writeable ] document_root [ Writeable ]

 

Command :


[ Back ]     

Current File : /var/www/html/rentals_updated/wp-content/plugins/operators/operator.php
<?php
/*
Plugin Name: Operator Module
Description: Multiple Operator Assignment, Operator Logsheet, Service Request, Initial Inspection.
Version: 3.6
Author: Itrosys
*/

if (!defined("ABSPATH")) {
    exit(); // Exit if accessed directly
}

// Include the admin Logsheet functionality
include plugin_dir_path(__FILE__) . "admin-logsheet.php";

// Include the admin Service Request functionality
include plugin_dir_path(__FILE__) . "admin-servicerequest.php";

// Operator Dashboard
include plugin_dir_path(__FILE__) . "operator-dashboard.php";

// Include the admin Terms & condition functionality
include plugin_dir_path(__FILE__) . "admin-inspection.php";

// Include the admin Terms & condition functionality
include plugin_dir_path(__FILE__) . "admin-check-out-inspection.php";

// Include the admin Terms & condition functionality
include plugin_dir_path(__FILE__) . "admin-operational-status.php";

// Include the admin Expenses
include plugin_dir_path(__FILE__) . "expenses.php";

// Include the Terms & Conditions
 include plugin_dir_path(__FILE__) . "admin-termscondition.php";

// Create the operator related tables on plugin activation
function create_operators_table()
{
    global $wpdb;
    
	$table_name = $wpdb->prefix . "logsheet";
    $charset_collate = $wpdb->get_charset_collate();

    $sql = "CREATE TABLE $table_name (
        id mediumint(9) NOT NULL AUTO_INCREMENT,
        equipment_id mediumint(9) NOT NULL,
		equipment_no varchar(50) NOT NULL,
        model_no varchar(100) NOT NULL,
        machine_serial_no varchar(100) NOT NULL,
        registration_no varchar(100) NOT NULL,
        operator_id int(11) NOT NULL,
		log_date date NOT NULL,
        start_time varchar(100) NOT NULL,
        end_time varchar(100) NOT NULL,
        shift varchar(1) NOT NULL,
        working_hour mediumint(9) NOT NULL,
        down_hour mediumint(9) NOT NULL,
		breakdown int,
		fuel varchar(100) NOT NULL,
		log_status mediumint NOT NULL,
		log_remarks varchar(255) NOT NULL,
		remarks_by mediumint,	
		log_created_on datetime NOT NULL,
		start_smu int,
		end_smu int,
		attend tinyint(1),
		order_id int,
        PRIMARY KEY  (id)
    ) $charset_collate;";
	
	$table_name1 = $wpdb->prefix . "service_request";
    $charset_collate1 = $wpdb->get_charset_collate();

    $sql1 = "CREATE TABLE $table_name1 (
        id mediumint(9) NOT NULL AUTO_INCREMENT,
		operator_id mediumint(9) NOT NULL,
        equipment_id mediumint(9) NOT NULL,
		problem_description text NOT NULL,
        attachment text NOT NULL,
        priority_level varchar(20) NOT NULL,
		status varchar(255) NOT NULL DEFAULT 'Raised',
		remarks varchar(255) NOT NULL,
		remarks_by mediumint(9) NOT NULL,
        created_on datetime NOT NULL,
		updated_on datetime NOT NULL,
		ins_remarks varchar(255) NOT NULL,
		stype mediumint(9),
		order_id int,
        PRIMARY KEY  (id)
    ) $charset_collate1;";
	
	$table_name2 = $wpdb->prefix . "raise_tickets";
    $charset_collate2 = $wpdb->get_charset_collate();

    $sql2 = "CREATE TABLE $table_name2 (
        id mediumint(9) NOT NULL AUTO_INCREMENT,
		operator_id mediumint(9) NOT NULL,        
		problem_title varchar(255) NOT NULL,
		problem_type mediumint(9) NOT NULL,
		problem_description text NOT NULL,
		equipment_id mediumint(9) NOT NULL,
        priority_level varchar(20) NOT NULL,
		additional_notes text NOT NULL,
		status varchar(255) NOT NULL DEFAULT 'Raised',
		remarks varchar(255) NOT NULL,
		remarks_by mediumint(9) NOT NULL,
        created_on datetime NOT NULL,
		updated_on datetime NOT NULL,
        PRIMARY KEY  (id)
    ) $charset_collate2;";
	
	$table_name3 = $wpdb->prefix . "assign_operators_contracts";
    $charset_collate3 = $wpdb->get_charset_collate();

    $sql3 = "CREATE TABLE $table_name3 (
        id mediumint(9) NOT NULL AUTO_INCREMENT,
		contract_id mediumint(9) NOT NULL, 
	    meachine_id mediumint(9) NOT NULL,   
        operator_id varchar(255) NOT NULL,
		shift varchar(1) NOT NULL,
		assigned_by mediumint(9) NOT NULL,
		op_status varchar(50) NOT NULL DEFAULT 'Assigned',
        created_on datetime NOT NULL,
		updated_on datetime NOT NULL,
        PRIMARY KEY  (id)
    ) $charset_collate3;";
	
	$table_name4 = $wpdb->prefix . "ticket_attachment_docs";
    $charset_collate4 = $wpdb->get_charset_collate();

    $sql4 = "CREATE TABLE $table_name4 (
        id mediumint(9) NOT NULL AUTO_INCREMENT,
		ticket_id mediumint(9) NOT NULL,        
		attachment varchar(255) NOT NULL,
        created_on datetime NOT NULL,
        PRIMARY KEY  (id)
    ) $charset_collate4;";
	
	$table_name5 = $wpdb->prefix . "termscondition";
    $charset_collate5 = $wpdb->get_charset_collate();

    $sql5 = "CREATE TABLE $table_name5 (
        id mediumint(9) NOT NULL AUTO_INCREMENT,
		terms_name varchar(50) NOT NULL,
        termscondition text NOT NULL,
        created_on datetime NOT NULL,
		updated_on datetime NOT NULL,
        PRIMARY KEY  (id)
    ) $charset_collate5;";
 
$table_name6 = $wpdb->prefix . "expenses_request";
$charset_collate6 = $wpdb->get_charset_collate();

$sql6 = "CREATE TABLE $table_name6 (
	id mediumint(9) NOT NULL AUTO_INCREMENT,
	operator_id mediumint(9) NOT NULL,
	equipment_id mediumint(9) NOT NULL,
	problem_description text NOT NULL,
	attachment text NOT NULL,
	exp_reason varchar(20) NOT NULL,
	status varchar(255) NOT NULL DEFAULT 'Raised',
	remarks varchar(255) NOT NULL,
	remarks_by mediumint(9) NOT NULL,
	created_on datetime NOT NULL,
	updated_on datetime NOT NULL,
	exp_amount Decimal(16,2),
	order_id int,
	PRIMARY KEY  (id)
) $charset_collate6;";

$table_name7 = $wpdb->prefix . "service_attachment_docs";
$charset_collate7 = $wpdb->get_charset_collate();

$sql7 = "CREATE TABLE $table_name7 (
	id mediumint(9) NOT NULL AUTO_INCREMENT,
	log_id mediumint(9) NOT NULL,
	attachment  varchar(255) NOT NULL,
	created_on datetime NOT NULL,
	PRIMARY KEY  (id)
) $charset_collate7;";

$table_name8 = $wpdb->prefix . "expenses_attachment_docs";
$charset_collate8 = $wpdb->get_charset_collate();

$sql8 = "CREATE TABLE $table_name8 (
	id mediumint(9) NOT NULL AUTO_INCREMENT,
	log_id mediumint(9) NOT NULL,
	attachment  varchar(255) NOT NULL,
	created_on datetime NOT NULL,
	PRIMARY KEY  (id)
) $charset_collate8;";


require_once ABSPATH . "wp-admin/includes/upgrade.php"; 
dbDelta($sql);
dbDelta($sql1);
dbDelta($sql2);
dbDelta($sql3);
dbDelta($sql4);
dbDelta($sql5);
dbDelta($sql6);
dbDelta($sql7);
dbDelta($sql8);
}
register_activation_hook(__FILE__, "create_operators_table");

function create_sos_table() {
    global $wpdb;
    $table_name = $wpdb->prefix . 'sos';

    $charset_collate = $wpdb->get_charset_collate();

    $sql = "CREATE TABLE $table_name (
        sos_id mediumint(9) NOT NULL AUTO_INCREMENT,
        operator_id mediumint(9) NOT NULL,
        sos_messag varchar(255) NOT NULL,
		order_id int,
        created_on TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
        notification_status tinyint(1) NOT NULL DEFAULT 1,
        PRIMARY KEY  (sos_id)
    ) $charset_collate;";

    require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
    dbDelta($sql);
}
add_action('after_setup_theme', 'create_sos_table');


// Add admin menu
add_action('admin_menu', 'operator_admin_menu');
function operator_admin_menu() {
    add_menu_page(
        'Operators',    // Page title
        'Operators',    // Menu title
        'manage_options',    // Capability
        'operator-dashboard',     // Menu slug
        'operators_list',// Callback function
        'dashicons-buddicons-buddypress-logo', // Icon URL
        6                    // Position
    );
	// Add a submenu page
    add_submenu_page(
        'operator-dashboard', // The slug name for the parent menu
        'Create Operators', // The text to be displayed in the title tags of the page when the submenu is selected
        'Create Operators', // The text to be used for the submenu
        'manage_options', // The capability required for this menu to be displayed to the user
        'create_operators', // The slug name to refer to this submenu
        'create_operators' // The function to be called to output the content for this page
    );
	add_submenu_page(
        'operator-dashboard', // The slug name for the parent menu
        'SOS', // The text to be displayed in the title tags of the page when the submenu is selected
        'SOS', // The text to be used for the submenu
        'manage_options', // The capability required for this menu to be displayed to the user
        'sos', // The slug name to refer to this submenu
        'sos' // The function to be called to output the content for this page
    );
	add_submenu_page(null, //parent slug
	'Edit Operator', //page title
	'Edit', //menu title
	'manage_options', //capability
	'edit-operator', //menu slug
	'edit_operator'); //function
	add_submenu_page(null, //parent slug
	'Delete Operator', //page title
	'Delete', //menu title
	'manage_options', //capability
	'delete-operator', //menu slug
	'delete_operator'); //function

	add_submenu_page(
        'operator-dashboard',
        'Check-In Inspection',    // Page title
        'Check-In Inspection',    // Menu title
        'manage_options',    // Capability
        'initial-inspection',     // Menu slug
        'initial_inspection',// Callback function
       
    );

	add_submenu_page(null, //parent slug
	'Edit Check-In Inspection', //page title
	'Edit', //menu title
	'manage_options', //capability
	'edit-initial-inspection', //menu slug
	'edit_initial_inspection'); //function

	add_submenu_page(
        'operator-dashboard',
        'Check-Out Inspection',    // Page title
        'Check-Out Inspection',    // Menu title
        'manage_options',    // Capability
        'check-out-inspection',     // Menu slug
        'check_out_inspection',// Callback function
       
    );

	add_submenu_page(null, //parent slug
	'Edit Check-Out Inspection', //page title
	'Edit', //menu title
	'manage_options', //capability
	'edit-check-out-inspection', //menu slug
	'edit_check_out_inspection'); //function
		add_submenu_page(
        'operator-dashboard',
		'Operational Status',    // Page title
        'Operational Status',    // Menu title
        'manage_options',    // Capability
        'operational-status',     // Menu slug
        'operational_status',// Callback function
    );
	
}

function operator_enqueue_custom_styles_and_scripts($hook) {
	
    // Load only on the Operator dashboard page and operator dashboard page
if ($hook !== 'toplevel_page_operator-dashboard') {
        return;
    }

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

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

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

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

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

add_action('admin_enqueue_scripts', 'operator_enqueue_custom_styles_and_scripts');

// Display the data
function operators_list() {
    $args = array(
		'role'    => 'operator',
		'orderby' => 'ID',
		'order'   => 'DESC'
	);
	$users = get_users( $args );
    ?>
	
    <div class="wrap rfq-wrap">
        <h1 class="wp-heading-inline mb-2 font-weight-bold">Operators</h1>
		<!-- button and filter added -->
        <div  style="display:flex; margin-bottom:20px;">
                <div class="operator-export-btn" style="display:flex;">
                    <button id="operatorexport" class="btn custom-btn" style="padding: 2px 21px 4px 21px;" >Export</button>
                    <div class="multi-rfq-column" style="margin-left:20px;"><?php include 'multiselect-operator-columns.php'; ?></div>
                </div>
                
            </div>
            <!-- /end button and filter added -->
		<div class="table-responsive ">
			<table id="operator-table" class="table table-striped table-bordered user-table" style="width:100%";>
				<thead style="background-color:#FFBD2B !important;">
					<tr>
						<th scope="row" class="manage-column">Sr. No</th>
						<th scope="row" class="manage-column">Profile Pic</th>
						<th scope="col" class="manage-column">First Name</th>
						<th scope="col" class="manage-column">Last Name </th>
						<th scope="col" class="manage-column">Employee ID </th>
						<th scope="col" class="manage-column">Email</th>
						<th scope="col" class="manage-column">Phone Number</th>
						<th scope="col" class="manage-column">Work Location</th>
						<th scope="col" class="manage-column">Status</th>
						<th scope="col" class="manage-column">Actions</th>
					</tr>
				</thead>
				<tbody>
				<?php
				/*class="tags" title="Skill: <?php echo $user->skills ? $user->skills : 'Not Available';?> Work Exprience: <?php echo $user->work_experience ? $user->work_experience : 'Not Available';?>"> */
				$i = 1;
				foreach($users as $user){
					?>
					<tr>
					<td><?php echo $i;?></td>
					<td>
					<?php
					 $profile_image =$user->profile_image;

									// Default image dynamically generated from the plugin's directory
        $default_image = plugins_url('assets/profile-placeholder.png', __FILE__);

        // Use uploaded image if available; otherwise, fallback to default
        $profile_image = !empty($profile_image) ? $profile_image : $default_image; 
        ?>
        <img src="<?php echo esc_url($profile_image); ?>" class="img-responsive" width="100" height="100">
					</td>
					<td><?php echo $user->first_name;?></td>
					<td><?php echo $user->last_name;?> </td>
					<td><?php echo $user->Operator_id;?></td>
					<td><?php echo $user->user_email;?></td>
					<td><?php echo $user->user_phone;?></td>
					<td><?php echo $user->work_location;?></td>
					<td><?php 
					$res = ($user->operator_status == 1) ? "Available" : (($user->operator_status == 2)  ? "Assigned" : "NA");
					echo $res; 
					?></td>	
					<td>
					<a href="<?php echo admin_url('admin.php?page=edit-operator&id=' . $user->ID); ?>">Edit</a> | 
					<a href="javascript:void(0);" data-toggle="modal" data-target="#exampleModal<?php echo $user->ID;?>" id="submit">View</a>| 
				
				<?php
				if($user->contract_id == ''){
				?>
					 <a href="javascript:void(0);" data-toggle="modal" 
				data-target="#assignOperator<?php echo $user->ID;?>">Assign</a>
				<?php
				}else{
				?>
					 <a href="javascript:void(0);" onclick="unAssignedOperator('<?php echo $user->ID;?>','<?php echo $user->contract_id;?>')">Unassign</a>
				<?php
				}
				?><?php
				if($user->user_status == 1){
				?>
					| <a href="javascript:void(0);" onclick="changeUserStatus('<?php echo $user->ID;?>','2')">Inactive</a>
				<?php
				}else if($user->user_status == 2){
				?>
					| <a href="javascript:void(0);" onclick="changeUserStatus('<?php echo $user->ID;?>','1')">Acitve</a>
				<?php
				}else{
				?>
					| <a href="javascript:void(0);" onclick="changeUserStatus('<?php echo $user->ID;?>','1')">Acitve</a>
				<?php
				}
				?>
				</td>
				</tr>
				<div class="modal fade" id="exampleModal<?php echo $user->ID;?>" 
				tabindex="-1" 
				aria-labelledby="exampleModalLabel" 
				aria-hidden="true">
				
				<div class="modal-dialog modal-lg">
					<div class="modal-content">
						<div class="modal-header">
							<h5 class="modal-title" 
								id="exampleModalLabel">
								Operator Details
							</h5>
							
							<button type="button" 
								class="close" 
								data-dismiss="modal" 
								aria-label="Close">
								<span aria-hidden="true">
									&times;
								</span>
							</button>

						</div>

						<div class="modal-body">

							<!-- Data passed is displayed 
								in this part of the 
								modal body -->
							<h4 id="modal_body">Login Information</h4>
							<div class="row profile-tab">
								<div class="col-md-6">
									<div class="col-md-6">
										<label>First Name</label>
									</div>
									<div class="col-md-6">
										<p><?php echo $user->first_name;?></p>
									</div>
								</div>
								<div class="col-md-6">
									<div class="col-md-6">
										<label>Profile Picture</label>
									</div>
									<div class="col-md-6">
									<?php

									$profile_image = $user->profile_image;
									// Default image dynamically generated from the plugin's directory
        $default_image = plugins_url('assets/profile-placeholder.png', __FILE__);

        // Use uploaded image if available; otherwise, fallback to default
        $profile_image = !empty($profile_image) ? $profile_image : $default_image; 
        ?>
        <img src="<?php echo esc_url($profile_image); ?>" class="img-responsive" width="100" height="100">
																		</div>
								</div>
								<div class="col-md-6">
									<div class="col-md-6">
										<label>Last Name</label>
									</div>
									<div class="col-md-6">
										<p><?php echo $user->last_name;?></p>
									</div>
								</div>	
								<div class="col-md-6">
									<div class="col-md-6">
										<label>Employe Id</label>
									</div>
									<div class="col-md-6">
										<p><?php echo $user->Operator_id;?></p>
									</div>
								</div>								
								<div class="col-md-6">
									<div class="col-md-6">
										<label>User Name</label>
									</div>
									<div class="col-md-6">
										<p><?php echo $user->user_login;?></p>
									</div>
								</div>
								<div class="col-md-6">
									<div class="col-md-6">
										<label>User Email</label>
									</div>
									<div class="col-md-6">
										<p><?php echo $user->user_email;?></p>
									</div>
								</div>
								<div class="col-md-6">
									<div class="col-md-6">
										<label>Skills</label>
									</div>
									<div class="col-md-6">
										<p><?php echo $user->skills ? $user->skills : 'N/A';?></p>
									</div>
								</div>
								<div class="col-md-6">
									<div class="col-md-6">
										<label>Age</label>
									</div>
									<div class="col-md-6">
										<p><?php echo $user->age ? $user->age : 'N/A';?></p>
									</div>
								</div>
								<div class="col-md-6">
									<div class="col-md-6">
										<label>Gender</label>
									</div>
									<div class="col-md-6">
										<p><?php echo $user->gender ? $user->gender : 'N/A';?></p>
									</div>
								</div>
								<div class="col-md-12">
									<div class="col-md-6">
										<label>Total Work Experience</label>
									</div>
									<div class="col-md-6">
										<p><?php echo $user->work_experience ? $user->work_experience : 'N/A';?></p>
									</div>
								</div>
							</div>
							<h4 id="modal_body">Personal Information</h4>
							<div class="row profile-tab">
								<div class="col-md-6">
									<div class="col-md-6">
										<label>Phone Number</label>
									</div>
									<div class="col-md-6">
										<p><?php echo $user->user_phone;?></p>
									</div>
								</div>
								<div class="col-md-6">
									<div class="col-md-6">
										<label>Aadhar Number</label>
									</div>
									<div class="col-md-6">
										<p><?php echo $user->aadhar_no;?></p>
									</div>
								</div>
								<div class="col-md-6">
									<div class="col-md-6">
										<label>PAN Number</label>
									</div>
									<div class="col-md-6">
										<p><?php echo $user->pan_no;?></p>
									</div>
								</div>
								<div class="col-md-6">
									<div class="col-md-6">
										<label>Driving License Number</label>
									</div>
									<div class="col-md-6">
										<p><?php echo $user->dl_no;?></p>
									</div>
								</div>
								<div class="col-md-12">
									<div class="col-md-6">
										<label>Driving License Type</label>
									</div>
									<div class="col-md-6">
										<p><?php echo $user->dl_type;?></p>
									</div>
								</div>
							</div>
							<h4 id="modal_body">Operators Information</h4>
							<div class="row profile-tab">
								<div class="col-md-6">
									<div class="col-md-6">
										<label>Customer Associated to</label>
									</div>
									<div class="col-md-6">
										<p>
											<?php 
												$userAssoc = get_user_meta($user->ID, 'customer_associated', true);
												$assoc = get_user_by( 'ID', $userAssoc );
												echo $display_name = $assoc->user_nicename;
											/* print_r($userAssoc);
											print_r($assoc); */
												
											?>
										</p>
									</div>
								</div>
								<div class="col-md-6">
									<div class="col-md-6">
										<label>Machine Associated With</label>
									</div>
									<div class="col-md-6">
										<p>
										<?php 
										$machineassoc = get_user_meta($user->ID, 'machine_associated', true);
									 	$product = get_post( $machineassoc );
                                        echo $product->post_title;
										?></p>
									</div>
								</div>
								<div class="col-md-6">
									<div class="col-md-6">
										<label>Work Location</label>
									</div>
									<div class="col-md-6">
										<p><?php echo $user->work_location;?></p>
									</div>
								</div>
								<div class="col-md-6">
									<div class="col-md-6">
										<label>FIR Status</label>
									</div>
									<div class="col-md-6">
										<p><?php echo $user->fir_status;?></p>
									</div>
								</div>
								<div class="col-md-6">
									<div class="col-md-6">
										<label>Contract Information</label>
									</div>
									<div class="col-md-6">
										<p><?php echo $user->contract_info;?></p>
									</div>
								</div>
							</div>
							<?php
							if(isset($user->contract_id)){
							?>
							<h4 id="modal_body">Recent Contract Assigned Details</h4>
							<div class="row profile-tab">
								<div class="col-md-6">
									<div class="col-md-6">
										<label>Equipment Name</label>
									</div>
									<div class="col-md-6">
										<p>
										<?php
										global $wpdb;
										//echo "SELECT ord.customer_id,p.product_id FROM `wp_wc_order_product_lookup` as p left join wp_wc_orders as ord on p.order_id = ord.id where ord.id = ".$user->contract_id;
											$getContractdata = $wpdb->get_row($wpdb->prepare("SELECT ord.customer_id,p.product_id FROM `wp_wc_order_product_lookup` as p left join wp_wc_orders as ord on p.order_id = ord.id where ord.id = %d", $user->contract_id));
											$eq = get_post( $getContractdata->product_id);
											echo $eq->post_title;
										?>
										</p>
									</div>
								</div>
								<div class="col-md-6">
									<div class="col-md-6">
										<label>Customer Name</label>
									</div>
									<div class="col-md-6">
									<?php
									$ownerDetails = get_userdata($getContractdata->customer_id);
									?>
										<p><?php echo esc_html($ownerDetails->user_nicename); ?></p>
									</div>
								</div>
							</div>
							<?php
							}
							?>
							<h4 id="modal_body">Operators Bank Account Information</h4>
							<div class="row profile-tab">
								<div class="col-md-6">
									<div class="col-md-6">
										<label>Account Number</label>
									</div>
									<div class="col-md-6">
										<p><?php echo $user->account_no;?></p>
									</div>
								</div>
								<div class="col-md-6">
									<div class="col-md-6">
										<label>IFSC Code</label>
									</div>
									<div class="col-md-6">
										<p><?php echo $user->ifsc_code;?></p>
									</div>
								</div>
								<div class="col-md-6">
									<div class="col-md-6">
										<label>Passbook</label>
									</div>
									<div class="col-md-6">
									<?php 
       

	   $passbook_image = $user->passbook_image;
        // Default image dynamically generated from the plugin's directory
        $default_image = plugins_url('assets/passbook-placeholder.png', __FILE__);

        // Use uploaded image if available; otherwise, fallback to default
        $passbook_image = !empty($bank_passbook) ? $bank_passbook : $default_image; 
        ?>
        <img src="<?php echo esc_url($passbook_image); ?>" class="img-responsive" width="100" height="100">
									</div>
								</div>
							</div>
							<h4 id="modal_body">Attachments</h4>
							<div class="row profile-tab">
								<div class="col-md-6">
									<div class="col-md-6">
										<label>Profile Picture</label>
									</div>
									<div class="col-md-6">
										<?php
										$profile_image =$user->profile_image;
									// Default image dynamically generated from the plugin's directory
        $default_image = plugins_url('assets/profile-placeholder.png', __FILE__);

        // Use uploaded image if available; otherwise, fallback to default
        $profile_image = !empty($profile_image) ? $profile_image : $default_image; 
        ?>
        <img src="<?php echo esc_url($profile_image); ?>" class="img-responsive" width="100" height="100">
									</div>
								</div>
								<div class="col-md-6">
									<div class="col-md-6">
										<label>Aadhar Card</label>
									</div>
									<div class="col-md-6">
									<?php
									
									$aadhar = $user->aadhar;
									// Default image dynamically generated from the plugin's directory
        $default_image = plugins_url('assets/aadhar-placeholder.png', __FILE__);

        // Use uploaded image if available; otherwise, fallback to default
        $aadhar = !empty($aadhar) ? $aadhar : $default_image; 
        ?>
        <img src="<?php echo esc_url($aadhar); ?>" class="img-responsive" width="100" height="100">
										
									</div>
								</div>
								<div class="col-md-6">
									<div class="col-md-6">
										<label>Pancard</label>
									</div>
									<div class="col-md-6">
										<?php
										
										$pancard = $user->pancard;
									// Default image dynamically generated from the plugin's directory
        $default_image = plugins_url('assets/pan-placeholder.png', __FILE__);

        // Use uploaded image if available; otherwise, fallback to default
        $pancard = !empty($pancard) ? $pancard : $default_image; 
        ?>
        <img src="<?php echo esc_url($pancard); ?>" class="img-responsive" width="100" height="100">									</div>
								</div>
								<div class="col-md-6">
									<div class="col-md-6">
										<label>Driving License</label>
									</div>
									<div class="col-md-6">
										<?php
										
										$driving_license_photo = $user->driving_license_photo;
									$default_image = plugins_url('assets/driving-license-placeholder.png', __FILE__);

// Use uploaded image if available; otherwise, fallback to default
$driving_license_photo = !empty($driving_license_photo) ? $driving_license_photo : $default_image; 
?>
<img src="<?php echo esc_url($driving_license_photo); ?>" class="img-responsive" width="100" height="100">									</div>
								</div>
								<div class="col-md-6">
									<div class="col-md-6">
										<label>Resume</label>
									</div>
									<div class="col-md-6">
										<a href="<?php echo $user->resume;?>" class="btn btn-primary" width="100" height="100"download>Download</a>
										<?php
											$parsedUrl = parse_url($user->resume, PHP_URL_PATH);
											// Use pathinfo to get the file name
											$fileName = pathinfo($parsedUrl, PATHINFO_BASENAME);
											echo $fileName;
										?>
									</div>
								</div>
								<div class="col-md-6">
									<div class="col-md-6">
										<label>Additional Documents</label>
									</div>
									<div class="col-md-6">
										<a href="<?php echo $user->additional_docs;?>" class="btn btn-primary" width="100" height="100"download>Download</a>
									</div>
								</div>
							</div>							
						</div>
					</div>
				</div>
			</div>
			<div class="modal fade" id="assignOperator<?php echo $user->ID;?>" 
				tabindex="-1" 
				aria-labelledby="exampleModalLabel" 
				aria-hidden="true">
				
				<div class="modal-dialog modal-lg">
					<div class="modal-content">
						<div class="modal-header">
							<h5 class="modal-title"	id="exampleModalLabel">
								Assign Contract To Operators
							</h5>
							
								
							
							<button type="button" 
								class="close" 
								data-dismiss="modal" 
								aria-label="Close">
								<span aria-hidden="true">
									&times;
								</span>
							</button>
						</div>

						<div class="modal-body">
							<form id="assignContractForm<?php echo $user->ID;?>" method="post" action="javascript:void(0);">
							<div class="row">
								<div class="col-md-12">
									<div class="col-md-6">
										<label>Select Contract List</label>										
									</div>
									<div class="col-md-6">
									<select id="opcontract_id<?php echo esc_attr($user->ID); ?>" name="opcontract_id" class="form-control">
    <option value="">Select Contract</option>
    <?php
    global $wpdb;
    $sql = "SELECT p.ID, pm.meta_value as contract_id 
            FROM {$wpdb->prefix}posts p
            JOIN {$wpdb->prefix}postmeta pm ON p.ID = pm.post_id
            JOIN {$wpdb->prefix}wc_orders wo ON p.ID = wo.id
            WHERE p.post_type = 'shop_order'
            AND wo.status = 'wc-equipmentassigned'
            AND pm.meta_key = 'contract_id'
            AND pm.meta_value != ''
            ORDER BY pm.meta_value DESC";
    
    $results = $wpdb->get_results($sql);
    foreach ($results as $result) {
        echo '<option value="' . esc_attr($result->ID) . '">RMS Contract #'. esc_attr($result->ID) . '-- SAP Contract #' . esc_html($result->contract_id) . '-- No Of Operators : '. get_post_meta($result->ID, '_number_of_operators', true) . '</option>';
    }
    ?>
</select>
											
									</div>
								</div>
								
								<input type="hidden" id="operator_id" name="operator_id" value="<?php echo $user->ID;?>">
							</div>
							<br>
							<div class="row">
								<div class="col-md-6">
									<div id="spinner<?php echo $user->ID;?>" class="mb-5" style="display:none;">
										<img style="width:22px;" src="<?php echo plugin_dir_url(
											__FILE__
										); ?>spinner.gif" alt="Loading...">
									</div>
									<div id="operator-message<?php echo $user->ID;?>" class="mb-5" style="display:none;"></div>
									<input type="submit" name="assignOperators" id="assignOperators" class="button button-primary" value="Assign Operator" onclick="assignOperator('<?php echo $user->ID;?>')">
								</div>
							</div>
							</form>
						</div>
					</div>
				</div>
			</div>
					<?php
					$i++;
				}
				?>
				</tbody>
			</table>
		</div> 
	</div>	
	<div id="loader" class="loader" style="display:none">
        <img src="<?php echo plugin_dir_url(__FILE__); ?>spinner.gif" alt="Loading...">
    </div> 
	<script>
        // Initialize DataTable
        jQuery(document).ready(function($) {
	// 		if ($.fn.dataTable.isDataTable('#operator-table')) {
    //     // Destroy the existing instance
    //     $('#operator-table').DataTable().destroy();
    // }
			jQuery('#operator-table').DataTable();			// for export operators
			function exportTableToCSV(filename) {
				var csv = [];
				var rows = document.querySelectorAll("#operator-table tbody tr");

				// Get table headers (column names)
				var headers = [];
				var headerCols = document.querySelectorAll("#operator-table thead th");
				for (var k = 0; k < headerCols.length - 1; k++) { // exclude last header
					headers.push(headerCols[k].innerText);
				}
				csv.push(headers.join(",")); // Push headers to CSV

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

					for (var j = 0; j < cols.length - 1; j++) { // exclude last column
						row.push(cols[j].innerText);
					}

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

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

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

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

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

				// File name
				downloadLink.download = filename;

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

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

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

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

			// Attach event listener to export button
			document.getElementById("operatorexport").addEventListener("click", function () {
				exportTableToCSV("Operators-data.csv");
			});
        });
    </script>
	<script type="text/javascript">
				function changeUserStatus(id,status){
			jQuery('#loader').fadeIn();
			jQuery.ajax({
				url: '<?php echo admin_url("admin-ajax.php"); ?>',
				type: 'POST',
				data: {
					action: 'change_user_status',
					status: status,
					operator_id: id
				},
				success: function(response) {
					console.log(response.success);
					if(response.success == false){
						alert(response.data.message);
						return false;
					}
					// Show success operator-message
					alert("Operator Activated/Deactivated Successfully");
					location.reload();
				},
				error: function(error) {
					// Hide the spinner
					alert("Error Occurs!!!");
					location.reload();
				},
				complete: function() {
					// Hide the loader after the AJAX call completes (success or error)
					jQuery('#loader').fadeOut();
				}
			});
		}
		function unAssignedOperator(id,contract_id){
			jQuery('#loader').fadeIn();
			jQuery.ajax({
				url: '<?php echo admin_url("admin-ajax.php"); ?>',
				type: 'POST',
				beforeSend:function(){
					return confirm("Are you sure to unassigned this operator?");
				},
				data: {
					action: 'unassigned_operator',
					operator_id: id,
					contract_id: contract_id
				},
				success: function(response) {
					// Show success operator-message
					alert("Operator Unassigned Successfully");
					location.reload();
				},
				error: function(error) {
					// Hide the spinner
					alert("Error Occurs!!!");
					location.reload();
				},
				complete: function() {
					// Hide the loader after the AJAX call completes (success or error)
					jQuery('#loader').fadeOut();
				}
			});
		}
	</script>
	<?php
} 

//-----SOS Function-----Bhaskara 

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

    // Fetch SOS entries from the database, order by latest first
    $results = $wpdb->get_results("SELECT * FROM $table_name ORDER BY created_on DESC", ARRAY_A);

	echo '<h2 style="padding-top:50px;"> SOS Notifications</h2>'; 

    if (empty($results)) {
        echo '<div class="notice notice-info"><p>No SOS notifications found.</p></div>';
        return;
    }
    echo '<table class="wp-list-table widefat fixed striped">';
    echo '<thead>
            <tr>
                <th>SOS ID</th>
                <th>Operator ID</th>
                <th>Message</th>
                <th>Created On</th>
                <th>Notification Status</th>
            </tr>
          </thead>';
    echo '<tbody>';

    foreach ($results as $row) {
        $notification_status = $row['notification_status'] ? 'Received' : 'Acknowledged';

        echo '<tr>';
        echo '<td>' . esc_html($row['sos_id']) . '</td>';
        echo '<td>' . esc_html($row['operator_id']) . '</td>';
        echo '<td>' . esc_html($row['sos_messag']) . '</td>';
        echo '<td>' . esc_html($row['created_on']) . '</td>';
        echo '<td>' . esc_html($notification_status) . '</td>';
        echo '</tr>';
    }

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

function check_new_sos_entries() {
    global $wpdb;
    $table_name = $wpdb->prefix . 'sos';

    // Fetch all active notifications (notification_status = 1)
    $new_entries = $wpdb->get_results("SELECT * FROM $table_name WHERE notification_status = 1 ORDER BY created_on DESC", ARRAY_A);

    if ($new_entries) {
        wp_send_json_success(array('new_entries' => $new_entries));
    } else {
        wp_send_json_success(array('new_entries' => false));
    }
    wp_die();
}
add_action('wp_ajax_check_new_sos_entries', 'check_new_sos_entries');
add_action('wp_ajax_nopriv_check_new_sos_entries', 'check_new_sos_entries');

function add_real_time_sos_check() {
    ?>
    <script type="text/javascript">
    jQuery(document).ready(function($) {
        function checkForNewSOS() {
            $.ajax({
                url: "<?php echo admin_url('admin-ajax.php'); ?>",
                type: "POST",
                data: {
                    action: "check_new_sos_entries"
                },
                success: function(response) {
                    if (response.success && response.data.new_entries) {
                        response.data.new_entries.forEach(function(entry) {
                            if ($("#sos-floating-notification-" + entry.sos_id).length === 0) {
                                $("body").append(
                                    '<div id="sos-floating-notification-' + entry.sos_id + '" class="sos-floating-notification" ' +
                                    'style="position:fixed;bottom:20px;right:20px;background:red;color:white;padding:20px;border-radius:5px;z-index:9999;margin-bottom:' + ($('.sos-floating-notification').length * 110) + 'px;">' +
                                    '<p><strong>Emergency Notification:</strong> SOS ID: ' + entry.sos_id + ' - ' + entry.sos_messag + '</p>' +
                                    '<button class="sos-view-details button button-primary" data-sos-id="' + entry.sos_id + '">Turn Off</button></div>'
                                );
								//var audio = new Audio('/wp-content/plugins/operators/assets/sos_alert.mp3');  
                                audio.loop = true;
								audio.play().catch(function(error) {
                                console.error("Audio playback failed:", error);
                                });
                            }
							
                        });

                        // Handle button click for all notifications
                        $(".sos-view-details").off('click').on("click", function(e) {
                            e.preventDefault();
                            var sosId = $(this).data('sos-id');
                            clearSOSNotification(sosId);
                        });
                    }
                }
            });
        }

        function clearSOSNotification(sosId) {
            $.ajax({
                url: "<?php echo admin_url('admin-ajax.php'); ?>",
                type: "POST",
                data: {
                    action: "clear_sos_notification",
                    sos_id: sosId
                },
                success: function(response) {
                    if (response.success) {
                        $("#sos-floating-notification-" + sosId).remove();
                        // Reposition remaining notifications
                        $('.sos-floating-notification').each(function(index) {
                            $(this).css('margin-bottom', (index * 110) + 'px');
                        });
                        // Redirect to SOS page after clearing the notification
                        window.location.href = "<?php echo admin_url('admin.php?page=sos'); ?>";
                    }
                }
            });
        }

        // Set the interval to check every 10 seconds (10000 milliseconds)
        setInterval(checkForNewSOS, 10000);
    });
    </script>
    <?php
}
add_action('admin_footer', 'add_real_time_sos_check');

function clear_sos_notification() {
    global $wpdb;
    $table_name = $wpdb->prefix . 'sos';

    $sos_id = isset($_POST['sos_id']) ? intval($_POST['sos_id']) : 0;

    if ($sos_id) {
        // Update the notification_status to 0 (inactive) for the specific SOS entry
        $wpdb->update(
            $table_name,
            array('notification_status' => 0),  // Set to inactive
            array('sos_id' => $sos_id),        // Only affect the specific SOS entry
            array('%d'),
            array('%d')
        );
		
    }

    wp_send_json_success();
}
add_action('wp_ajax_clear_sos_notification', 'clear_sos_notification');


//end SOS

//------------------create Operator---------------//
// check th ephone number exist status
function check_phone_number_exists($phone_number) {
    $users = get_users(array(
        'meta_key' => 'user_phone',
        'meta_value' => $phone_number,
        'number' => 1, // We only need to know if at least one exists
        'count_total' => false
    ));
    return !empty($users);
}

function create_operators(){
	global $wpdb;
	if(isset($_POST['createoperators'])!=''){

		if(check_phone_number_exists($_POST['user_phone'])) {
            echo '<div class="error"><p>Error: This phone number is already registered with another operator. Please use a different phone number.</p></div>';
            return;
        }
		$username = $_POST['user_login'];
		$password = $_POST['password'];
		$email = $_POST['email'];
		$user_id = wp_create_user($username, $password, $email);
        // Get current user object
        $user = get_user_by('id', $user_id);
		// Remove role
		$user->remove_role( 'customer' );
        // Add role
        $user->add_role('operator');
		update_user_meta( $user_id, 'first_name', $_POST['first_name']);
		update_user_meta( $user_id, 'last_name', $_POST['last_name']); 
		update_user_meta( $user_id, 'skills', $_POST['skills']);
		update_user_meta( $user_id, 'work_experience', $_POST['work_experience']);
		add_user_meta( $user_id, 'user_phone', $_POST['user_phone']);
		add_user_meta( $user_id, 'aadhar_no', $_POST['aadhar_no']);
		add_user_meta( $user_id, 'pan_no', $_POST['pan_no']);  
		add_user_meta( $user_id, 'dl_no', $_POST['dl_no']);
		add_user_meta( $user_id, 'dl_type', $_POST['dl_type']);
		add_user_meta( $user_id, 'customer_associated', $_POST['customer_associated']);  
		add_user_meta( $user_id, 'machine_associated', $_POST['machine_associated']);
		add_user_meta( $user_id, 'work_location', $_POST['work_location']);  
		add_user_meta( $user_id, 'fir_status', $_POST['fir_status']);
		add_user_meta( $user_id, 'contract_info', $_POST['contract_info']);
		add_user_meta( $user_id, 'vendor_name', $_POST['vendor_name']);
		add_user_meta( $user_id, 'operator_status', 1); // 1=>avaialble,2=>assigned
		add_user_meta( $user_id, 'user_status', 1); // 1=>active,2=>inactive
		if (isset($_FILES['profile_image']) && $_FILES['profile_image']['size'] > 0) {
			// Handle file upload
			$upload = wp_handle_upload($_FILES['profile_image'], array('test_form' => false));
			if (isset($upload['url']) && !isset($upload['error'])) {
				update_user_meta($user_id, 'profile_image', $upload['url']);
			}			
		}
		if (isset($_FILES['aadhar']) && $_FILES['aadhar']['size'] > 0) {
			// Handle file upload
			$upload_aadhar = wp_handle_upload($_FILES['aadhar'], array('test_form' => false));
			if (isset($upload_aadhar['url']) && !isset($upload_aadhar['error'])) {
				update_user_meta($user_id, 'aadhar', $upload_aadhar['url']);
			}			
		}
		if (isset($_FILES['pancard']) && $_FILES['pancard']['size'] > 0) {
			// Handle file upload
			$upload_pan = wp_handle_upload($_FILES['pancard'], array('test_form' => false));
			if (isset($upload_pan['url']) && !isset($upload_pan['error'])) {
				update_user_meta($user_id, 'pancard', $upload_pan['url']);
			}			
		}
		if (isset($_FILES['driving_license_photo']) && $_FILES['driving_license_photo']['size'] > 0) {
			// Handle file upload
			$upload_dl = wp_handle_upload($_FILES['driving_license_photo'], array('test_form' => false));
			if (isset($upload_dl['url']) && !isset($upload_dl['error'])) {
				update_user_meta($user_id, 'driving_license_photo', $upload_dl['url']);
			}			
		}
		if (isset($_FILES['resume']) && $_FILES['resume']['size'] > 0) {
			// Handle file upload
			$upload_resume = wp_handle_upload($_FILES['resume'], array('test_form' => false));
			if (isset($upload_resume['url']) && !isset($upload_resume['error'])) {
				update_user_meta($user_id, 'resume', $upload_resume['url']);
			}			
		}
		if (isset($_FILES['additional_docs']) && $_FILES['additional_docs']['size'] > 0) {
			// Handle file upload
			$upload_adocs = wp_handle_upload($_FILES['additional_docs'], array('test_form' => false));
			if (isset($upload_adocs['url']) && !isset($upload_adocs['error'])) {
				update_user_meta($user_id, 'additional_docs', $upload_adocs['url']);
			}			
		}
		add_user_meta( $user_id, 'account_no', $_POST['account_no']);  
		add_user_meta( $user_id, 'ifsc_code', $_POST['ifsc_code']);
		if (isset($_FILES['bank_passbook']) && $_FILES['bank_passbook']['size'] > 0) {
			// Handle file upload
			$upload_passbook = wp_handle_upload($_FILES['bank_passbook'], array('test_form' => false));
			if (isset($upload_passbook['url']) && !isset($upload_passbook['error'])) {
				update_user_meta($user_id, 'bank_passbook', $upload_passbook['url']);
			}			
		}
		echo "<p>Operators Created Successfully</p>";
		wp_redirect(admin_url('admin.php?page=operator-dashboard'));
		exit;
	}
	?>
	<style>
	.row { 
            display: flex; 
            flex-wrap: wrap; 
            justify-content: space-between; 
            margin: 20px; 
        }   
        .column { 
            border-collapse: collapse; 
            width: 100%; 
            
        }  
        /* Media query for small screens */ 
        @media (min-width: 768px) { 
            .column { 
                width: 48%; 
                margin-bottom: 0; 
            } 
        } 
	</style>
<div class="wrap">
	<form method="post" name="createopfrm" id="createopfrm" class="form" enctype="multipart/form-data">
		
		<div class="row">
			<div class="column">
			<h3>Login Information</h3>
			<table class="form-table" role="presentation">
				<tbody>
					<tr class="form-field form-required">
						<th scope="row"><label for="user_login">Username <span class="description">(required)</span></label></th>
						<td><input name="user_login" type="text" id="user_login" value="" aria-required="true" autocapitalize="none" autocorrect="off" autocomplete="off" maxlength="60" required></td>
					</tr>
					<tr class="form-field form-required">
						<th scope="row"><label for="email">Email <span class="description">(optional)</span></label></th>
						<td><input name="email" type="email" id="email" value=""></td>
					</tr>
					<tr class="form-field">
						<th scope="row"><label for="first_name">First Name (required)</label></th>
						<td><input name="first_name" type="text" id="first_name" value="" required></td>
					</tr>
					<tr class="form-field">
						<th scope="row"><label for="last_name">Last Name (required)</label></th>
						<td><input name="last_name" type="text" id="last_name" value="" required></td>
					</tr>
					<tr class="form-field">
						<th scope="row"><label for="last_name">Password (required)</label></th>
						<td><input name="password" type="password" id="password" value="" required></td>
					</tr>
					<tr class="form-field">
						<th scope="row"><label for="skills">Skills (required)</label></th>
						<td><input name="skills" type="text" id="skills" value=""></td>
					</tr>
					<tr class="form-field">
						<th scope="row"><label for="age">Age</label></th>
						<td><input name="age" type="number" id="age" value=""></td>
					</tr>
					<tr class="form-field">
						<th scope="row"><label for="gender">Gender</label></th>
						<td>
							<select name="gender" id="gender"class="regular-text" >
								<option value="">Select Gender</option>
								<option value="male">Male</option>
								<option value="female">Female</option>
								<option value="other">Other</option>
							</select>
						</td>
					</tr>
					<tr class="form-field">
						<th scope="row"><label for="skills">Total Work Experience (required)</label></th>
						<td><input name="work_experience" type="text" id="work_experience" value=""></td>
					</tr>
				</tbody>
			</table>
			</div>
			<div class="column">
			<h3>Personal Information</h3>
			<table class="form-table">
				<tbody>
					<tr>
						<th><label for="user_phone">Phone Number</label></th>
						<td>
							<input type="text" name="user_phone" id="user_phone" value="" class="regular-text" maxlength="10" oninput="this.value = this.value.replace(/[^0-9.]/g, ''); this.value = this.value.replace(/(\..*)\./g, '$1');" required>
						</td>
					</tr>
					<tr>
						<th><label for="aadhar_no">Aadhar Card Number</label></th>
						<td>
							<input type="text" name="aadhar_no" id="aadhar_no" value="" class="regular-text" maxlength="12" required>
						</td>
					</tr>
					<tr>
						<th><label for="pan_no">PAN Card Number</label></th>
						<td>
							<input type="text" name="pan_no" id="pan_no" value="" class="regular-text" maxlength="10" required>
						</td>
					</tr>
					<tr>
						<th><label for="pan_no">Driving License Number</label></th>
						<td>
							<input type="text" name="dl_no" id="dl_no" value="" class="regular-text" maxlength="12" required>
						</td>
					</tr>
					<tr>
						<th><label for="pan_no">Driving License Type</label></th>
						<td>
							<select name="dl_type" id="dl_type"class="regular-text" required>
								<option value="">Select Driving License Type</option>
								<option value="light">LMV(Light Motor Vehicle)</option>
								<option value="heavy">HMV(Heavy Motor Vehicle)</option>
								<option value="heavyconstruction">HEC(Heavy Construction Equipment)</option>
							</select>
						</td>
					</tr>
				</tbody>
			</table>
			</div>
			<div class="column">
			<h3>Operators Information</h3>
			<table class="form-table">
				<tbody>
					<tr>
						<th><label for="customer_associated">Customer Associated</label></th>
						<td>
							<select name="customer_associated" id="customer_associated" class="regular-text">
								<option value="">Select Customer Associated</option>
								<?php
								$args = array(
									'role'    => 'Customer',
									'orderby' => 'user_nicename',
									'order'   => 'ASC'
								);
								$users = get_users( $args );
								foreach($users as $user){
								?>
								<option value="<?php echo $user->ID;?>"><?php echo $user->user_nicename;?></option>
								<?php
								}
								?>
							</select>
						</td>
					</tr>
					<tr>
						<th><label for="machine_associated">Machine Associated</label></th>
						<td>
							<select name="machine_associated" id="machine_associated"class="regular-text">
								<option value="">Select Machine Associated</option>
								<?php
								$pargs = array(
									'post_type'=> 'product',
									'orderby'    => 'post_title',
									'post_status' => 'publish',
									'order'    => 'ASC',
									'posts_per_page' =>-1 // this will retrive all the post that is published 
								);
								$products = new WP_Query( $pargs );
								foreach($products->posts as $product){
								?>
								<option value="<?php echo $product->ID;?>"><?php echo $product->post_title;?></option>
								<?php
								}
								?>
							</select>
						</td>
					</tr>
					
					<tr>
						<th><label for="work_location">Working Location</label></th>
						<td>
							<input type="text" name="work_location" id="work_location" value="" class="regular-text">
						</td>
					</tr>
					<tr>
						<th><label for="fir_status">FIR Status</label></th>
						<td>
							<select name="fir_status" id="fir_status"class="regular-text">
								<option value="">Select FIR Status</option>
								<option value="Verified">Verified</option>
								<option value="Not Verified">Not Verified</option>
								<option value="Cleared">Cleared</option>
							</select>
						</td>
					</tr>
					<tr>
						<th><label for="contract_info">Contract Information</label></th>
						<td>
							<input type="text" name="contract_info" id="contract_info" value="" class="regular-text">
						</td>
					</tr>
					<tr>
						<th><label for="contract_info">Vendor Name</label></th>
						<td>
							<input type="text" name="vendor_name" id="vendor_name" value="" class="regular-text">
						</td>
					</tr>
				</tbody>
			</table>
			</div>
			<div class="column">
			<h3>Attachments</h3>
			<table class="form-table">
				<tbody>
					<tr>
						<th><label for="profile_image">Profile Picture</label></th>
						<td>
							<input type="file" name="profile_image" id="profile_image" value="" class="regular-text">
						</td>
					</tr>
					<tr>
						<th><label for="aadhar">Aadhar Card</label></th>
						<td>
							<input type="file" name="aadhar" id="aadhar" value="" class="regular-text">
						</td>
					</tr>
					<tr>
						<th><label for="pancard">PAN Card</label></th>
						<td>
							<input type="file" name="pancard" id="pancard" value="" class="regular-text">
						</td>
					</tr>
					<tr>
						<th><label for="driving_license_photo">Driving License</label></th>
						<td>
							<input type="file" name="driving_license_photo" id="driving_license_photo" value="" class="regular-text">
						</td>
					</tr>
					<tr>
						<th><label for="driving_license_photo">Resume</label></th>
						<td>
							<input type="file" name="resume" id="resume" value="" class="regular-text">
						</td>
					</tr>
					<tr>
						<th><label for="additional_docs">Additional Documents</label></th>
						<td>
							<input type="file" name="additional_docs" id="additional_docs" value="" class="regular-text">
						</td>
					</tr>
				</tbody>
			</table>
			</div>
			<div class="column">
			<h3>Operators Bank Account Information</h3>
			<table class="form-table">
				<tbody>
					<tr>
						<th><label for="account_no">Account Number</label></th>
						<td>
							<input type="text" name="account_no" id="account_no" value="" class="regular-text" maxlength="12">
						</td>
					</tr>
					<tr>
						<th><label for="ifsc_code">IFSC Code</label></th>
						<td>
							<input type="text" name="ifsc_code" id="ifsc_code" value="" class="regular-text">
						</td>
					</tr>
					<tr>
						<th><label for="bank_passbook">Upload Bank Passbook</label></th>
						<td>
							<input type="file" name="bank_passbook" id="bank_passbook" value="" class="regular-text">
						</td>
					</tr>
				</tbody>
			</table>
			</div>
			
		</div>
		<p class="submit"><input type="submit" name="createoperators" id="createoperators" class="button button-primary" value="Add New Operator"></p>
	</form>
</div>
<script type="text/javascript">
jQuery(document).ready(function($) {
	jQuery("#user_phone").on('change', function() {
            var phone = jQuery(this).val();
            if(phone.length === 10) {
                // Make AJAX call to check phone number
                jQuery.ajax({
                    url: ajaxurl,
                    type: 'POST',
                    data: {
                        action: 'check_operator_phone',
                        phone: phone,
                        nonce: '<?php echo wp_create_nonce("check_operator_phone_nonce"); ?>'
                    },
                    success: function(response) {
                        if(response.exists) {
                            alert('This phone number is already registered with another operator. Please use a different number.');
                            jQuery('#user_phone').val('');
                            jQuery('#createoperators').prop('disabled', true);
                        } else {
                            jQuery('#createoperators').prop('disabled', false);
                        }
                    }
                });
            }
        });
	jQuery("#createopfrm").on("submit", function(event) {
		var isValid = true;
		var user_phone = jQuery('#user_phone').val();
		var aadhar_no = jQuery('#aadhar_no').val();
		var pan_no = jQuery('#pan_no').val();
		var dl_no = jQuery('#dl_no').val();
		var account_no = jQuery('#account_no').val();
		if(user_phone.length<10){
			isValid = false;
			alert("Invalid Phone Number!!! Please Enter 10 digit Mobile Number");
			return false;
		}
		if(aadhar_no.length<12){
			isValid = false;
			alert("Invalid Aadhar Number!!! Please Enter 12 digit Aadhar Number");
			return false;
		}
		if(pan_no.length<10){
			isValid = false;
			alert("Invalid PAN Number!!! Please Enter 10 digit PAN Number");
			return false;
		}
		if(dl_no.length<12){
			isValid = false;
			alert("Invalid Driving License Number!!! Please Enter 12 digit Driving License Number");
			return false;
		}
		if(account_no.length<=9 || account_no.length >=18){
			isValid = false;
			alert("Invalid Bank Account Number!!! Please Enter Minimum 9 digit Bank Account Number");
			return false;
		}
		if (!isValid) {
			event.preventDefault();
		}
	});
});
</script>
	<?php
} 
add_action('wp_ajax_check_operator_phone', 'check_operator_phone_ajax');
function check_operator_phone_ajax() {
    // Verify nonce
    check_ajax_referer('check_operator_phone_nonce', 'nonce');
    
    $phone = sanitize_text_field($_POST['phone']);
    $exists = check_phone_number_exists($phone);
    
    wp_send_json(array('exists' => $exists));
}

// Hook to run when a user role is changed or user is created for OPERATOR
add_action('set_user_role', 'set_operator_status', 10, 3);
add_action('user_register', 'check_and_set_operator_status');

// Function to set operator_status when role is changed
function set_operator_status($user_id, $role, $old_roles) {
    // Check if new role is operator
    if ($role === 'operator') {
        update_user_meta($user_id, 'operator_status', '1');
    }
}

// Function to check and set operator_status for new users
function check_and_set_operator_status($user_id) {
    $user = get_user_by('id', $user_id);
    
    // Check if user has operator role
    if (in_array('operator', (array) $user->roles)) {
        update_user_meta($user_id, 'operator_status', '1');
    }
}
// end of default operator status


//------------Edit Operator ------//
function edit_operator(){
	global $wpdb;
	if(isset($_POST['editoperators'])!=''){
		$user_id = $_REQUEST['id'];
		if(isset($_POST['first_name'])){
			update_user_meta( $user_id, 'first_name', $_POST['first_name']);
		}
		if(isset($_POST['last_name'])){
			update_user_meta( $user_id, 'last_name', $_POST['last_name']); 
		}
		if(isset($_POST['Operator_id'])){
			update_user_meta( $user_id, 'Operator_id', $_POST['Operator_id']); 
		}
		if(isset($_POST['skills'])){
			update_user_meta( $user_id, 'skills', $_POST['skills']);
		}
		if(isset($_POST['age'])){
			update_user_meta( $user_id, 'age', $_POST['age']);
		}
		if(isset($_POST['gender'])){
			update_user_meta( $user_id, 'gender', $_POST['gender']);
		}
		if(isset($_POST['work_experience'])){
			update_user_meta( $user_id, 'work_experience', $_POST['work_experience']);
		}
		if(isset($_POST['user_phone'])){
			update_user_meta( $user_id, 'user_phone', $_POST['user_phone']);
		}
		if(isset($_POST['aadhar_no'])){
			update_user_meta( $user_id, 'aadhar_no', $_POST['aadhar_no']);
		}
		if(isset($_POST['pan_no'])){
			update_user_meta( $user_id, 'pan_no', $_POST['pan_no']);  
		}
		// if(isset($_POST['aadhar_no'])){
		// 	// Remove hyphens before saving Aadhar
		// 	$aadhar = str_replace('-', '', $_POST['aadhar_no']);
		// 	update_user_meta($user_id, 'aadhar_no', $aadhar);
		// }
		// if(isset($_POST['pan_no'])){
		// 	// Remove hyphens before saving PAN
		// 	$pan = str_replace('-', '', $_POST['pan_no']);
		// 	update_user_meta($user_id, 'pan_no', $pan);
		// }

		if(isset($_POST['dl_no'])){
			update_user_meta( $user_id, 'dl_no', $_POST['dl_no']);
		}
		if(isset($_POST['dl_type'])){
			update_user_meta( $user_id, 'dl_type', $_POST['dl_type']);
		}
		if(isset($_POST['customer_associated'])){
			update_user_meta( $user_id, 'customer_associated', $_POST['customer_associated']);  
		}
		if(isset($_POST['machine_associated'])){
			update_user_meta( $user_id, 'machine_associated', $_POST['machine_associated']);
		}
		if(isset($_POST['work_location'])){
			update_user_meta( $user_id, 'work_location', $_POST['work_location']); 
		}		
		if(isset($_POST['fir_status'])){
			update_user_meta( $user_id, 'fir_status', $_POST['fir_status']);
		}
		if(isset($_POST['contract_info'])){
			update_user_meta( $user_id, 'contract_info', $_POST['contract_info']);
		}
		if(isset($_POST['vendor_name'])){
			update_user_meta( $user_id, 'vendor_name', $_POST['vendor_name']);
		}
		if(isset($_POST['operator_status'])){
			update_user_meta( $user_id, 'operator_status', 1); // 1=>avaialble,2=>assigned
		}
		if(isset($_POST['user_status'])){
			update_user_meta( $user_id, 'user_status', 1); // 1=>active,2=>inactive
		}
		if (isset($_FILES['profile_image']) && $_FILES['profile_image']['size'] > 0) {
			// Handle file upload
			$upload = wp_handle_upload($_FILES['profile_image'], array('test_form' => false));
			if (isset($upload['url']) && !isset($upload['error'])) {
				update_user_meta($user_id, 'profile_image', $upload['url']);
			}			
		}
		if (isset($_FILES['aadhar']) && $_FILES['aadhar']['size'] > 0) {
			// Handle file upload
			$upload_aadhar = wp_handle_upload($_FILES['aadhar'], array('test_form' => false));
			if (isset($upload_aadhar['url']) && !isset($upload_aadhar['error'])) {
				update_user_meta($user_id, 'aadhar', $upload_aadhar['url']);
			}			
		}
		if (isset($_FILES['pancard']) && $_FILES['pancard']['size'] > 0) {
			// Handle file upload
			$upload_pan = wp_handle_upload($_FILES['pancard'], array('test_form' => false));
			if (isset($upload_pan['url']) && !isset($upload_pan['error'])) {
				update_user_meta($user_id, 'pancard', $upload_pan['url']);
			}			
		}
		if (isset($_FILES['driving_license_photo']) && $_FILES['driving_license_photo']['size'] > 0) {
			// Handle file upload
			$upload_dl = wp_handle_upload($_FILES['driving_license_photo'], array('test_form' => false));
			if (isset($upload_dl['url']) && !isset($upload_dl['error'])) {
				update_user_meta($user_id, 'driving_license_photo', $upload_dl['url']);
			}			
		}
		if (isset($_FILES['resume']) && $_FILES['resume']['size'] > 0) {
			// Handle file upload
			$upload_resume = wp_handle_upload($_FILES['resume'], array('test_form' => false));
			if (isset($upload_resume['url']) && !isset($upload_resume['error'])) {
				update_user_meta($user_id, 'resume', $upload_resume['url']);
			}			
		}
		if (isset($_FILES['additional_docs']) && $_FILES['additional_docs']['size'] > 0) {
			// Handle file upload
			$upload_adocs = wp_handle_upload($_FILES['additional_docs'], array('test_form' => false));
			if (isset($upload_adocs['url']) && !isset($upload_adocs['error'])) {
				update_user_meta($user_id, 'additional_docs', $upload_adocs['url']);
			}			
		}
		if(isset($_POST['account_no'])){
			update_user_meta( $user_id, 'account_no', $_POST['account_no']);  
		}
		if(isset($_POST['ifsc_code'])){
			update_user_meta( $user_id, 'ifsc_code', $_POST['ifsc_code']);
		}
		if (isset($_FILES['bank_passbook']) && $_FILES['bank_passbook']['size'] > 0) {
			// Handle file upload
			$upload_passbook = wp_handle_upload($_FILES['bank_passbook'], array('test_form' => false));
			if (isset($upload_passbook['url']) && !isset($upload_passbook['error'])) {
				update_user_meta($user_id, 'bank_passbook', $upload_passbook['url']);
			}			
		}
		echo "<div class='notice notice-success'>Operators Updated Successfully</div>";
		wp_redirect(admin_url('admin.php?page=operator-dashboard'));
		exit;
	}
	$id = $_REQUEST['id'];
	$users = get_userdata( $id );
	//print_r($users->data);exit;
	?>
	<style>
	.row { 
            display: flex; 
            flex-wrap: wrap; 
            justify-content: space-between; 
            margin: 20px; 
        } 
  
        .column { 
            border-collapse: collapse; 
            width: 100%; 
            
        }     
  
        /* Media query for small screens */ 
        @media (min-width: 768px) { 
            .column { 
                width: 48%; 
                margin-bottom: 0; 
            } 
        } 
	</style>
	<div class="wrap">
		<form method="post" name="editoperator" id="createuser" class="form" enctype="multipart/form-data">
			<div class="row">
				<div class="column">
					<h3>User Information</h3>
					<table class="form-table" role="presentation">
						<tbody>
							<tr class="form-field">
								<th scope="row"><label for="first_name">First Name </label></th>
								<td><input name="first_name" type="text" id="first_name" value="<?php echo get_user_meta($id, 'first_name', true);?>" readonly></td>
							</tr>
							<tr class="form-field">
								<th scope="row"><label for="last_name">Last Name </label></th>
								<td><input name="last_name" type="text" id="last_name" value="<?php echo get_user_meta($id, 'last_name', true);?>" readonly></td>
							</tr>
							<tr class="form-field">
								<th scope="row"><label for="operator_id">Operator ID </label></th>
								<td><input name="Operator_id" type="text" id="Operator_id" value="<?php echo get_user_meta($id, 'Operator_id', true);?>" ></td>
							</tr>
							<tr class="form-field">
								<th scope="row"><label for="skills">Skills </label></th>
								<td><input name="skills" type="text" id="skills" value="<?php echo get_user_meta($id, 'skills', true);?>"></td>
							</tr>
							<tr class="form-field">
								<th scope="row"><label for="age">Age</label></th>
								<td><input name="age" type="number" id="age" value="<?php echo get_user_meta($id, 'age', true);?>"></td>
							</tr>
							<tr class="form-field">
								<th scope="row"><label for="gender">Gender</label></th>
								<td>
									<select name="gender" id="gender"class="regular-text">
										<option value="">Select Gender</option>
										<option value="male">Male</option>
										<option value="female">Female</option>
										<option value="other">Other</option>
									</select>
									<script> document.getElementById('gender').value = "<?php echo get_user_meta($id, 'gender', true);?>"; </script>
								</td>
							<tr class="form-field">
								<th scope="row"><label for="skills">Total Work Experience </label></th>
								<td><input name="work_experience" type="text" id="work_experience" value="<?php echo get_user_meta($id, 'work_experience', true);?>"></td>
							</tr>
							<tr>
								<th><label for="phone_number">Phone Number</label></th>
								<td>
									<input type="text" name="user_phone" id="user_phone" value="<?php echo get_user_meta($id, 'user_phone', true);?>" class="regular-text" pattern="[0-9]{10}"
									placeholder="9898989898"  title="Please enter valid Phone number in format: 9876543210">
								</td>
							</tr>					
						</tbody>
					</table>
				</div>
				<div class="column">
					<h3>Personal Information</h3>
					<table class="form-table">
						<tbody>
							<tr>
								<th><label for="aadhar_no">Aadhar Card Number</label></th>
								<td>
									<input type="text" name="aadhar_no" id="aadhar_no" value="<?php echo get_user_meta($id, 'aadhar_no', true);?>" class="regular-text" pattern="[0-9]{12}"
					placeholder="123456789123"  title="Please enter valid Aadhar number in format: 123456789123">
								</td>
							</tr>
							<tr>
								<th><label for="pan_no">PAN Card Number</label></th>
								<td>
									<input type="text" name="pan_no" id="pan_no" value="<?php echo get_user_meta($id, 'pan_no', true);?>" class="regular-text" pattern="[A-Z]{5}[0-9]{4}[A-Z]{1}" placeholder="ABCDE1234F"
					title="Please enter valid PAN number in format: ABCDE1234A">
								</td>
							</tr>
							<tr>
								<th><label for="pan_no">Driving License Number</label></th>
								<td>
									<input type="text" name="dl_no" id="dl_no" value="<?php echo get_user_meta($id, 'dl_no', true);?>" class="regular-text">
								</td>
							</tr>
							<tr>
								<th><label for="pan_no">Driving License Type</label></th>
								<td>
									<select name="dl_type" id="dl_type"class="regular-text">
										<option value="">Select Driving License Type</option>
										<option value="light" <?php echo (get_user_meta($id, 'dl_type', true) == 'light') ? 'selected' : ''; ?>>LMV(Light Motor Vehicle)</option>
										<option value="heavy" <?php echo (get_user_meta($id, 'dl_type', true) == 'heavy') ? 'selected' : ''; ?>>HMV(Heavy Motor Vehicle)</option>
										<option value="heavyconstruction" <?php echo (get_user_meta($id, 'dl_type', true) == 'heavyconstruction') ? 'selected' : ''; ?>>HEC(Heavy Construction Equipment)</option>
									</select>
								</td>
							</tr>
						</tbody>
					</table>
				</div>
				<div class="column">
					<h3>Operators Information</h3>
					<table class="form-table">
						<tbody>
							<tr>
								<th><label for="customer_associated">Customer Associated</label></th>
								<td>
									<select name="customer_associated" id="customer_associated" class="regular-text">
										<option value="">Select Customer Associated</option>
										<?php
										$args = array(
											'role'    => 'Customer',
											'orderby' => 'user_nicename',
											'order'   => 'ASC'
										);
										$nusers = get_users( $args );
										foreach($nusers as $nuser){
										?>
										<option value="<?php echo $nuser->ID;?>" <?php echo (get_user_meta($id, 'customer_associated', true) == $nuser->ID) ? 'selected' : ''; ?>><?php echo $nuser->user_nicename;?></option>
										<?php
										}
										?>
									</select>
								</td>
							</tr>
							<tr>
								<th><label for="machine_associated">Machine Associated</label></th>
								<td>
									<select name="machine_associated" id="machine_associated"class="regular-text">
										<option value="">Select Machine Associated</option>
										<?php
										$pargs = array(
											'post_type'=> 'product',
											'orderby'    => 'post_title',
											'post_status' => 'publish',
											'order'    => 'ASC',
											'posts_per_page' =>-1 // this will retrive all the post that is published 
										);
										$products = new WP_Query( $pargs );
										foreach($products->posts as $product){
										?>
										<option value="<?php echo $product->ID;?>" <?php echo (get_user_meta($id, 'machine_associated', true) == $product->ID) ? 'selected' : ''; ?>><?php echo $product->post_title;?></option>
										<?php
										}
										?>
									</select>
								</td>
							</tr>
							<tr>
								<th><label for="work_location">Working Location</label></th>
								<td>
									<input type="text" name="work_location" id="work_location" value="<?php echo get_user_meta($id, 'work_location', true);?>" class="regular-text">
								</td>
							</tr>
							<tr>
								<th><label for="fir_status">FIR Status</label></th>
								<td>
									<select name="fir_status" id="fir_status"class="regular-text">
										<option value="">Select FIR Status</option>
										<option value="Verified" <?php echo (get_user_meta($id, 'fir_status', true) == 'Verified') ? 'selected' : ''; ?>>Verified</option>
										<option value="Not Verified" <?php echo (get_user_meta($id, 'fir_status', true) == 'Not Verified') ? 'selected' : ''; ?>>Not Verified</option>
										<option value="Cleared" <?php echo (get_user_meta($id, 'fir_status', true) == 'Cleared') ? 'selected' : ''; ?>>Cleared</option>
									</select>
								</td>
							</tr>
							<tr>
								<th><label for="contract_info">Contract Information</label></th>
								<td>
									<input type="text" name="contract_info" id="contract_info" value="<?php echo get_user_meta($id, 'contract_info', true);?>" class="regular-text">
								</td>
							</tr>
							<tr>
								<th><label for="contract_info">Vendor Name</label></th>
								<td>
									<input type="text" name="vendor_name" id="vendor_name" value="<?php echo get_user_meta($id, 'vendor_name', true);?>" class="regular-text">
								</td>
							</tr>
						</tbody>
					</table>
				</div>
				<div class="column">
					<h3>Operators Bank Account Information</h3>
					<table class="form-table">
						<tbody>
							<tr>
								<th><label for="account_no">Account Number</label></th>
								<td>
									<input type="text" name="account_no" id="account_no" value="<?php echo get_user_meta($id, 'account_no', true);?>" class="regular-text">
								</td>
							</tr>
							<tr>
								<th><label for="ifsc_code">IFSC Code</label></th>
								<td>
									<input type="text" name="ifsc_code" id="ifsc_code" value="<?php echo get_user_meta($id, 'ifsc_code', true);?>" class="regular-text">
								</td>
							</tr>
							<tr>
							<tr>
							<th><label for="bank_passbook">Upload Bank Passbook</label></th>
							<td>
								<input type="file" name="bank_passbook" id="bank_passbook" value="" class="regular-text">
								<?php 
								// Fetch the bank passbook metadata
								$bank_passbook = get_user_meta($id, 'bank_passbook', true);

								// Default image dynamically generated from the plugin's directory
								$default_image = plugins_url('assets/passbook-placeholder.png', __FILE__);

								// Use uploaded image if available; otherwise, fallback to default
								$passbook_image = !empty($bank_passbook) ? $bank_passbook : $default_image; 
								?>
								<img src="<?php echo esc_url($passbook_image); ?>" class="img-responsive" width="100" height="100">
							</td>
						</tr>
						</tbody>
					</table>
				</div>
				<div class="column">
					<h3>Attachments</h3>
					<table class="form-table">
						<tbody>
							<tr>
								<th><label for="profile_image">Profile Picture</label></th>
								<td>
									<input type="file" name="profile_image" id="profile_image" value="" class="regular-text">
									<?php
										$profile_image = get_user_meta($id, 'profile_image', true);

											// Default image dynamically generated from the plugin's directory
											$default_image = plugins_url('assets/profile-placeholder.png', __FILE__);

											// Use uploaded image if available; otherwise, fallback to default
											$profile_image = !empty($profile_image) ? $profile_image : $default_image; 
											?>
											<img src="<?php echo esc_url($profile_image); ?>" class="img-responsive" width="100" height="100">
															</td>
														</tr>
														<tr>
															<th><label for="aadhar">Aadhar Card</label></th>
															<td>
																<input type="file" name="aadhar" id="aadhar" value="" class="regular-text">
																<?php
																$aadhar = get_user_meta($id, 'aadhar', true);
																		// Default image dynamically generated from the plugin's directory
											$default_image = plugins_url('assets/aadhar-placeholder.png', __FILE__);

											// Use uploaded image if available; otherwise, fallback to default
											$aadhar = !empty($aadhar) ? $aadhar : $default_image; 
											?>
											<img src="<?php echo esc_url($aadhar); ?>" class="img-responsive" width="100" height="100">
								</td>
							</tr>
							<tr>
								<th><label for="pancard">PAN Card</label></th>
								<td>
									<input type="file" name="pancard" id="pancard" value="" class="regular-text">
									<?php
									$aadhar = get_user_meta($id, 'pancard', true);
											// Default image dynamically generated from the plugin's directory
											$default_image = plugins_url('assets/pan-placeholder.png', __FILE__);

											// Use uploaded image if available; otherwise, fallback to default
											$pancard = !empty($pancard) ? $pancard : $default_image; 
											?>
											<img src="<?php echo esc_url($pancard); ?>" class="img-responsive" width="100" height="100">
															</td>
														</tr>
														<tr>
															<th><label for="driving_license_photo">Driving License</label></th>
															<td>
																<input type="file" name="driving_license_photo" id="driving_license_photo" value="" class="regular-text">
																<?php
																$aadhar = get_user_meta($id, 'driving_license_photo', true);
																		// Default image dynamically generated from the plugin's directory
											$default_image = plugins_url('assets/driving-license-placeholder.png', __FILE__);

											// Use uploaded image if available; otherwise, fallback to default
											$driving_license_photo = !empty($driving_license_photo) ? $driving_license_photo : $default_image; 
											?>
											<img src="<?php echo esc_url($driving_license_photo); ?>" class="img-responsive" width="100" height="100">
									</td>
							</tr>
							<tr>
								<th><label for="driving_license_photo">Resume</label></th>
								<td>
									<input type="file" name="resume" id="resume" value="" class="regular-text">
									<a href="<?php echo get_user_meta($id, 'resume', true);?>" class="btn btn-primary" width="100" height="100"download>Download</a>
								</td>
							</tr>
							<tr>
								<th><label for="additional_docs">Additional Documents</label></th>
								<td>
									<input type="file" name="additional_docs" id="additional_docs" value="" class="regular-text">
									<a href="<?php echo get_user_meta($id, 'additional_docs', true);?>" class="btn btn-primary" width="100" height="100"download>Download</a>
								</td>
							</tr>
						</tbody>
					</table>
				</div>
			</div>
			<p class="submit">
				<button type="submit" name="editoperators" id="editoperators" class="button button-primary">
					Update Operator
				</button>
			</p>
		</form>
	</div>
	<script type="text/javascript">
	</script>
	<?php
}

 //----Operator functions-----//
function delete_operator(){
	global $wpdb;
	$user_id = $_REQUEST['id'];
	// Delete User metadata
	$wpdb->delete($wpdb->usermeta, ['user_id' => $user_id], ['%d']);
	// Delete User
	$wpdb->delete($wpdb->users, ['ID' => $user_id], ['%d']);
	wp_redirect(admin_url('admin.php?page=operator-dashboard'));
	exit;
}	

function assign_operator_data() {
    global $wpdb;
    $operator_id = intval($_POST["operator_id"]);
    $contract_id = intval($_POST["contract_id"]);
    
    // Get the operator limit
    $operator_limit = intval(get_post_meta($contract_id, '_number_of_operators', true));
    
    if ($operator_limit <= 0) {
        wp_send_json_error(array('message' => 'Invalid operator limit for this contract.'));
        return;
    }

    // Count current assigned operators
    $current_count = $wpdb->get_var($wpdb->prepare(
        "SELECT COUNT(*) FROM {$wpdb->prefix}assign_operators_contracts WHERE contract_id = %d",
        $contract_id
    ));
    
    error_log("Current count: " . $current_count);
    error_log("Operator limit: " . $operator_limit);

    if ($current_count >= $operator_limit) {
        wp_send_json_error(array('message' => 'Maximum operator limit reached for this contract.'));
        return;
    }
    
    $order = wc_get_order($contract_id);
    if (!$order) {
        wp_send_json_error(array('message' => 'Invalid order.'));
        return;
    }
    
    // Start transaction
    $wpdb->query('START TRANSACTION');

    try {
		// Get the machine_id from the first product in the order
        $machine_id = null;
        $previous_status = $order->get_status();

        foreach ($order->get_items() as $item) {
            $machine_id = $item->get_product_id();
            break; // Take only the first product
        }

        // Insert assignment into custom table
        $table_name = $wpdb->prefix . 'assign_operators_contracts';
        $inserted = $wpdb->insert($table_name, [
            "contract_id"   => $contract_id,
            "meachine_id"   => $machine_id,
            "operator_id"   => $operator_id,
            "assigned_by"   => get_current_user_id(),
            "op_status"     => "Assigned",
            "created_on"    => current_time('mysql'),
        ]);

        if ($inserted === false) {
            throw new Exception('Failed to insert assignment record.');
        }

        // Update user meta
        update_user_meta($operator_id, 'operator_status', 2); // Assigned
        update_user_meta($operator_id, 'contract_id', $contract_id);
        update_user_meta($operator_id, 'machine_associated', $machine_id); // ✅ THIS LINE SETS IT

        // Update order status
        $updated_count = $wpdb->get_var($wpdb->prepare(
            "SELECT COUNT(*) FROM {$wpdb->prefix}assign_operators_contracts WHERE contract_id = %d",
            $contract_id
        ));

        if ($updated_count >= $operator_limit) {
            $order->set_status('wc-opassigned', 'All operators are assigned to this Contract.');
        } else {
            $order->set_status($previous_status, '');
        }

        $order->save();
        $wpdb->query('COMMIT');

        wp_send_json_success([
            'message' => 'Operator assigned successfully.',
            'current_count' => $updated_count,
            'limit' => $operator_limit
        ]);
    } catch (Exception $e) {
        $wpdb->query('ROLLBACK');
        wp_send_json_error(array('message' => 'Error: ' . $e->getMessage()));
    }
}

add_action("wp_ajax_assign_operator_data", "assign_operator_data");
add_action("wp_ajax_nopriv_assign_operator_data", "assign_operator_data");

function add_operator_scripts() {
    ?>
    <script type="text/javascript">
    function assignOperator(operator_id) {    
        var contract_id = jQuery('#opcontract_id'+operator_id).val();
        
        if(!contract_id) {
            alert("Please select a contract first!");
            return false;
        }

        if(!confirm("Are you sure to assign this contract to this operator?")) {
            return false;
        }

        jQuery('#spinner'+operator_id).show();
        jQuery('#operator-message'+operator_id).hide();

        jQuery.ajax({
            url: ajaxurl,
            type: 'POST',
            data: {
                action: 'assign_operator_data',
                contract_id: contract_id,
                operator_id: operator_id
            },
            success: function(response) {
                jQuery('#spinner'+operator_id).hide();
                
                if(response.success) {
                    jQuery('#operator-message'+operator_id)
                        .html('Operator Successfully Assigned Contract #' + contract_id)
                        .css({
                            'color': '#008000',
                            'font-weight': 'bold'
                        })
                        .show();
                    
                    // Reload after short delay to show success message
                    setTimeout(function() {
                        location.reload();
                    }, 1500);
                } else {
                    alert(response.data.message || 'Error assigning operator');
                }
            },
            error: function() {
                jQuery('#spinner'+operator_id).hide();
                alert("Error occurred while assigning operator. Please try again.");
            }
        });
    }
    </script>
    <?php
}
add_action('admin_footer', 'add_operator_scripts');

function check_operator_limit() {
    $contract_id = intval($_POST['contract_id']);
    
    // Get the operator limit from order meta
    $operator_limit = intval(get_post_meta($contract_id, '_number_of_operators', true));

    // Count current assigned operators
    $args = array(
        'meta_key' => 'contract_id',
        'meta_value' => $contract_id,
        'meta_compare' => '=',
        'count_total' => true
    );
    
    $current_operators = get_users($args);
    $current_count = count($current_operators);

    if ($current_count < $operator_limit) {
        wp_send_json_success();
    } else {
        wp_send_json_error();
    }
}
add_action('wp_ajax_check_operator_limit', 'check_operator_limit');
add_action('wp_ajax_nopriv_check_operator_limit', 'check_operator_limit');

function change_user_status()
{ 
	global $wpdb;
    $operator_id = intval($_POST["operator_id"]);
    $status = intval($_POST["op_status"]);
	$existing_meta_value = get_user_meta( $operator_id, 'contract_id', true );
	if(!empty( $existing_meta_value )){
		$existing_contractid = get_user_meta( $operator_id, 'contract_id', true );
		if(isset($existing_contractid)){
			wp_send_json_error(array('message' => 'Please Unassign the operator first'));
		}
	}
	$result_check = $wpdb->update('wp_users', [
			"user_status" => $status,
		],['ID'=>$operator_id]
		);
    wp_send_json_success();
	
}
add_action("wp_ajax_change_user_status", "change_user_status");
add_action("wp_ajax_nopriv_change_user_status", "change_user_status");

function unassigned_operator()
{ 
	global $wpdb;
    $operator_id = intval($_POST["operator_id"]);
	$contract_id = intval($_POST["contract_id"]);
	update_user_meta( $operator_id, 'operator_status', 1);
	update_user_meta( $operator_id, 'contract_id', '');
	//  Remove machine_associated from usermeta
	delete_user_meta($operator_id, 'machine_associated');
	$wpdb->delete('wp_assign_operators_contracts', ['contract_id' => $contract_id, 'operator_id' => $operator_id], ['%d','%d']);
	custom_update_order_status($contract_id, 'wc-equipmentassigned');
    wp_send_json_success();
	
}
function custom_update_order_status($order_id, $new_status) {
    if (!function_exists('wc_get_order')) {
        return;
    }

    $order = wc_get_order($order_id);
    if ($order && $order->get_status() != $new_status) {
        $order->update_status($new_status, 'Order status changed programmatically.', true);
    }
}
add_action("wp_ajax_unassigned_operator", "unassigned_operator");
add_action("wp_ajax_nopriv_unassigned_operator", "unassigned_operator");

//----------operator Meta Box in the Contract Section-----//

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

// Display Operator content in the custom meta box --bhaskara
function display_operator_order_meta_box($post) {
    // Get the current order ID
    global $post;
    $order_id = $post->ID;
    $order = wc_get_order($order_id);
	$order = wc_get_order($post->ID);
	if ($order) {
		$ord_status = $order->get_status(); // Get the status slug, e.g., 'sdp'
	} else {
		$ord_status = null; // Fallback if the order is invalid
	}

    // Get the "Number of Operators" value from order meta
    $num_operators = get_post_meta($order_id, '_number_of_operators', true);

	if (empty($num_operators)) {
        $num_operators = 1;
        update_post_meta($order_id, '_number_of_operators', $num_operators);
    }

	global $wpdb;

    // Get the number of operators limit from post meta
    $number_of_operators = intval(get_post_meta($post->ID, '_number_of_operators', true));

    // Get the count of currently assigned operators
    $current_assigned_count = $wpdb->get_var($wpdb->prepare(
        "SELECT COUNT(*) FROM {$wpdb->prefix}assign_operators_contracts WHERE contract_id = %d",
        $post->ID
    ));

    // Debugging: Check the retrieved values
    error_log("Order ID: $post->ID | Number of Operators: $number_of_operators | Currently Assigned Count: $current_assigned_count");

    // Ensure $current_assigned_count and $number_of_operators are valid
    if (!is_numeric($current_assigned_count)) {
        $current_assigned_count = 0;
    }

	$current_assigned_count = (int) $current_assigned_count;
    $number_of_operators = (int) $number_of_operators;

	if ($current_assigned_count < $number_of_operators){
		if ($ord_status === 'equipmentassigned' || $ord_status === 'opassigned'){
			$order->update_status('wc-equipmentassigned', 'Order status changed programmatically.', true);
		}
		else{
		
		$order->update_status($ord_status, 'Order status changed programmatically.', true);

	     }
    }
	elseif ($current_assigned_count === $number_of_operators){
		if ($ord_status === 'equipmentassigned'){
		$order->update_status('wc-opassigned', 'Order status changed programmatically.', true);

		}
		
	}
	
    // Display input field for "Number Of Operators" with Save and Edit buttons
    echo '<div class="operator-meta-box-content">';
    echo '<h3>' . __('Assigned Operators', 'textdomain') . '</h3>';
    
    echo '<p>';
    echo '<label for="number_of_operators">' . __('Number Of Operators:', 'textdomain') . '</label>';
    echo '<input type="number" id="number_of_operators" name="number_of_operators" value="' . esc_attr($num_operators) . '" min="1" onkeydown="return event.keyCode !== 189" oninput="this.value = this.value.replace(/[^1-9]/g, \'\'); if(this.value < 1) this.value = 1;" readonly />';
    echo '<button type="button" id="edit_operators" class="button">' . __('Update', 'textdomain') . '</button>';
    echo '<button type="button" id="save_operators" class="button button-primary" style="display:none;">' . __('Save', 'textdomain') . '</button>';
    echo '</p>';
    
    // Loop through assigned operators and display info
    $args = array(
        'meta_key'     => 'contract_id',
        'meta_value'   => $order_id,
        'meta_compare' => '='
    );
    $users = get_users($args);

	
	if ($ord_status === 'pending'){
		// Default case if order status is not 'sdp'
		echo '<p><strong>' . __('Operator can be assigned only after security deposit is paid.', 'textdomain') . '</strong></p>';
	
	}else if ($ord_status === 'sdp'){
		// Default case if order status is not 'sdp'
		echo '<p><strong>' . __('Operator can be assigned only after adding Equipment to Contract.', 'textdomain') . '</strong></p>';
	
	}else if ($ord_status === 'equipmentassigned') {
   
    if ($current_assigned_count < $number_of_operators) {
        // Display the "Assign Operator" button and progress
		$contract = get_post_meta($order->get_id(), 'contract_id', true);
    if (empty($contract)) {
    echo '<p><strong>' . __('Get Contract ID to assign Operators.', 'textdomain') . '</strong></p>';
      }
	  else {
	     if($current_assigned_count === 0){
        echo '<p><strong>' . __('No Operator is assigned.', 'textdomain') . '</strong></p>';
	     }
	     else{
		echo '<p><strong>' . __('Operators are partially assigned.', 'textdomain') . '</strong></p>';
	     }
		 echo '<a href="' . admin_url('admin.php?page=operator-dashboard') . '" class="button button-primary">' . __('Assign Operator', 'textdomain') . '</a>';
        echo '<p>' . sprintf(
            __('Currently assigned: %d / %d', 'textdomain'),
            $current_assigned_count,
            $number_of_operators
        ) . '</p>';
    } }
	// else {
    //     // All operators assigned
    //     echo '<p>' . __('All operators have been assigned.', 'textdomain') . '</p>';
    // }
}
else if ($ord_status === 'opassigned'){
	echo '<p><strong>' . __('All Operators have been assigned', 'textdomain') . '</strong></p>';

}

		
		if (!empty($users)) {
			echo '<ul>';
			foreach ($users as $user) {
				$first_name = get_user_meta($user->ID, 'first_name', true);
				$mobile = get_user_meta($user->ID, 'user_phone', true);
				$operator_doj = get_user_meta($user->ID, 'operator_doj', true);
				$hide_edit_flag = 1; // Set flag value as needed (1 to hide, 0 to show)
		
				echo '<li><strong><a href="' . esc_url(admin_url('admin.php?page=edit-operator&id=' . $user->ID . '&hide_edit=' . $hide_edit_flag)) . '" target="_blank">' . esc_html($first_name) . ' -- ' . esc_html($user->ID) . '</a></strong></li>';
				echo '<li><strong> Mobile Number: ' . esc_html($mobile) . '</strong></li>';
				echo '<li><strong> Date of Joining: ' . esc_html($operator_doj) . '</strong></li>';
				echo '<hr>';
			}
			echo '</ul>';
		}
	
	
    echo '</div>';

    // Add AJAX JavaScript code for saving the value without refresh
    ?>
    <script type="text/javascript">
        jQuery(document).ready(function($) {
            $('#edit_operators').click(function() {
                $('#number_of_operators').prop('readonly', false);
                $('#edit_operators').hide();
                $('#save_operators').show();
            });

            $('#save_operators').click(function() {
                var order_id = <?php echo $order_id; ?>;
                var num_operators = $('#number_of_operators').val();

                $.ajax({
                    url: ajaxurl,
                    type: 'POST',
                    data: {
                        action: 'save_number_of_operators',
                        order_id: order_id,
                        num_operators: num_operators,
                        _ajax_nonce: '<?php echo wp_create_nonce('save_operator_nonce'); ?>'
                    },
                    success: function(response) {
                        if (response.success) {
                            $('#number_of_operators').prop('readonly', true);
                            $('#save_operators').hide();
                            $('#edit_operators').show();
                            alert('<?php echo __('Number of Operators saved successfully!', 'textdomain'); ?>');
							setTimeout(() => {
                              location.reload(true);
                               setTimeout(() => {
                                  location.reload(true);
                                       }, 2000);
                                  }, 0); 
	                       } else {
                            alert('<?php echo __('Failed to save. Please try again.', 'textdomain'); ?>');
                        }
                    }
                });
            });
        });
    </script>
    <?php
}

// Handle AJAX request to save the Number Of Operators -- bhaskara
add_action('wp_ajax_save_number_of_operators', 'save_number_of_operators');
function save_number_of_operators() {
    // Check nonce for security
    check_ajax_referer('save_operator_nonce');

    // Get the order ID and new number of operators value from AJAX request
    $order_id = intval($_POST['order_id']);
    $num_operators = sanitize_text_field($_POST['num_operators']);

    if (!empty($order_id) && !empty($num_operators)) {
        // Update the order meta with the new value
        update_post_meta($order_id, '_number_of_operators', $num_operators);

        // Return a success response
        wp_send_json_success();

    } else {
        // Return a failure response
        wp_send_json_error();
    }
}

// End of Display Operator Meta Box

// remove Download Permissions from Meta box & Contract Action Dropdown


function remove_downloads_meta_box() {
    remove_meta_box('woocommerce-order-downloads', 'shop_order', 'normal');
}
add_action('add_meta_boxes', 'remove_downloads_meta_box', 40);

// Optional: If you also want to remove download permissions
function revoke_download_permissions($order_id) {
    global $wpdb;
    $order = wc_get_order($order_id);

    if (!$order || empty($order->get_items())) {
        return;
    }

    foreach ($order->get_items() as $item) {
        $product = $item->get_product();

        if (!$product || !$product->is_downloadable()) {
            continue;
        }

        $downloads = $product->get_downloads();

        foreach ($downloads as $download_id => $download) {
            $wpdb->update(
                $wpdb->prefix . 'woocommerce_downloadable_product_permissions',
                array('downloads_remaining' => '0'),
                array(
                    'order_id' => $order_id,
                    'download_id' => $download_id
                )
            );
        }
    }
}
// Uncomment the following line if you want to revoke permissions when editing an order
// add_action('woocommerce_before_order_object_save', 'revoke_download_permissions');

function remove_regenerate_download_permissions($actions) {
    // Remove the regenerate download permissions action
    if (isset($actions['regenerate_download_permissions'])) {
        unset($actions['regenerate_download_permissions']);
    }
   
    return $actions;
}
add_filter('woocommerce_order_actions', 'remove_regenerate_download_permissions');

?>

Youez - 2016 - github.com/yon3zu
LinuXploit