<?php 
include("includes/FCKeditor/fckeditor.php");
$file_name		= "index?page=view";
$show_all_page = "page=add";
$form_action	= "insert";
$button_value 	= "Submit";
$table_name 	= "work_order_assign";
$id	 = "";
$vat = "";
$query_string = "";
$page_name      = "Engineer Assign Works Order";
$from = $_REQUEST['from'];
//$rr_query = mysqli_query($conn, "SELECT IFNULL(MAX(CAST(SUBSTRING(enquiry_no, 5) AS UNSIGNED)), 0) + 1 AS new_enq FROM enquiry_management");
//$rr_row = mysqli_fetch_assoc($rr_query);
//$enquiry_no = 'ENQ-' . str_pad($rr_row['new_enq'], 3, '0', STR_PAD_LEFT);
################################################## START INSERT ##################################################
?>
<style>
em{color:red;font-size: 20px;position: absolute;}
.highlight-row {
    background-color: #ffff99  !important; /* हल्का लाल रंग */
    font-weight: bold; /* टेक्स्ट को बोल्ड बनाएं */
}

fieldset {
    border-top: 4px solid #dedede; 
    border-right: 1px solid #dedede;
    border-bottom: 1px solid #dedede; 
    border-left: 1px solid #dedede; 
    padding: 15px;
    margin-bottom: 10px;
}

legend {
    width: auto;
    color: #a423a4;
}
</style>
<style>
em{color:red;font-size: 20px;position: absolute;}
.highlight-row {
    background-color: #ffff99  !important;
    font-weight: bold;
}

fieldset {
    border-top: 4px solid #dedede; 
    border-right: 1px solid #dedede;
    border-bottom: 1px solid #dedede; 
    border-left: 1px solid #dedede; 
    padding: 15px;
    margin-bottom: 10px;
}

legend {
    width: auto;
    color: #a423a4;
}

.efficiency-report {
    display: none;
    margin-top: 20px;
    padding: 15px;
    background-color: #f8f9fa;
    border-radius: 5px;
    box-shadow: 0 0 10px rgba(0,0,0,0.1);
}

.efficiency-report table {
    width: 100%;
    margin-top: 10px;
}

.efficiency-report th, .efficiency-report td {
    padding: 8px;
    text-align: left;
    border: 1px solid #ddd;
}

.efficiency-report th {
    background-color: #e9ecef;
}


form.disabled {
    opacity: 0.7;
    pointer-events: none;
}

</style>
<style>
.btn-group {
    display: inline-flex;
    gap: 10px;
}
.text-right {
    text-align: right;
}
.mr-2 {
    margin-right: 8px;
}
</style>
<section class="content-header">
	<div class="container-fluid">
		<div class="row mb-2">
			<div class="col-sm-6">
				<h1>
					<?=$page_name;?>
				</h1>
			</div>
			<div class="col-sm-6">
			<?
			$query_string 	=  (isset($_POST['query_string'])) ? $_POST['query_string'] : $_SERVER['QUERY_STRING'];
			if(isset($from) && $from == "view_enquiry_details"){
				$query_string = str_ireplace("page=add", "page=view_enquiry_details", $query_string);
			}else {
				$query_string = str_ireplace("page=add", "page=view", $query_string);
			}
				
			?>
			<button type="button" id="back" name="back" value="back"  style="float:right;margin-right:5px;margin-bottom:8px;" class="btn btn-primary" onclick="window.location.href = 'index?<?=$query_string;?>'">Back</button>
			</div>
		</div>
	</div>
</section>
<section class="content">
	<div class="row">
		<div class="col-12">
			<!----------------------- Message ------------------------------->
			<? if(isset($_SESSION['info_message'])){ ?>
			  <div class="alert alert-info alert-dismissable">
				<button type="button" class="close" data-dismiss="alert" aria-hidden="true">&times;</button>
				<? echo $_SESSION['info_message']; unset($_SESSION['info_message']);?>
			  </div>
			  <? }
		$selected_date = isset($_GET['filter_date']) ? $_GET['filter_date'] : date('d-m-Y'); ?>
					<!----------------------- End Message ------------------------------->
		<!-- Date Filter Form -->
		<form method="GET" action="">
			<input type="hidden" name="page" value="add">
			
			 <div class="row m-1 mb-2">
			 <div class="col-lg-4 col-12">
				 <label class="control-label" for="filter_date">Select Date<em></em></label>
				  <div class="">
					<input type="text" class="form-control datepicker" id="filter_date" name="filter_date" value="<?php echo (isset($selected_date) && $selected_date != "") ? utility::getFormatedDate($selected_date) : ""; ?>" placeholder="DD-MM-YYYY" autocomplete="off" >
				  </div>
			  </div>
			 <div class="col-lg-2 col-12">
			 <label for="Search" class="control-label">&nbsp;</label><br>
			<button type="submit" class="btn btn-success">Search
				<i class="fa fa-refresh fa-spin" style="display:none;" id="page_load_div"></i>
			</button>
			<button type="button" value="Show All" onclick="javascript:window.location='?<?php echo $show_all_page ?>'" class="btn btn-info">Clear</button>
		  </div>
		</div>
		</form>

			<!-- general form elements -->
<? 
 ###########################################  PAGING WITH PER PAGE  #####################################
 
$formatted_date = date("Y-m-d", strtotime($selected_date));
//$formatted_date = '2025-10-13';
$file_name		= "index"; // this is file name which is used during paging  , included at the bottom of the page
$table_name		= "vac_machine_table";
$paging_table_name	= $table_name;
$paging_query		= $where;
$join_query_for_paging = "SELECT * FROM $table_name  where '$formatted_date' BETWEEN start_date AND end_date ";
$page_header = " ";
include("paging/paging_query.inc.php");

############################################ END PAGING WITH PER PAGE  #######################################
 //$query = "SELECT DISTINCT m.id,m.work_order_id, m.part_id, m.machine_id FROM vac_machine_table m JOIN working_hours w ON FIND_IN_SET(w.shift_name, m.shift_ids) > 0 WHERE '$formatted_date'  BETWEEN m.start_date AND m.end_date  AND w.day_shifts = ((DAYOFWEEK('$formatted_date' ) + 5) % 7) + 1 ORDER BY m.id ASC LIMIT $eu, $limit;";
$query = "
    SELECT DISTINCT id, work_order_id, part_id, machine_id, 'vac' AS source_table
    FROM vac_machine_table
    WHERE start_date >= '$formatted_date 00:00:00'
      AND start_date <  '$formatted_date 23:59:59'
    
    UNION ALL
    
SELECT DISTINCT 
    id, 
    work_order_id, 
    part_id, 
    LEFT(machine_id, LENGTH(machine_id) - 1) AS machine_id,
    'pu' AS source_table
FROM pu_machine_table
WHERE start_date >= '$formatted_date 00:00:00'
  AND start_date <  '$formatted_date 23:59:59'
    
    UNION ALL
    
    SELECT DISTINCT id, work_order_id, part_id, machine_id, 'assbly' AS source_table
    FROM assbly_machine_table
    WHERE start_date >= '$formatted_date 00:00:00'
      AND start_date <  '$formatted_date 23:59:59'
    
    ORDER BY id ASC
    LIMIT $eu, $limit
";



$sql=mysqli_query($conn,$query);
$result=mysqli_num_rows($sql);

$total_no_of_records = mysqli_num_rows(mysqli_query($conn,$query));
#################################   DELETE    #########################################
// when we click on delete this area of php code will execute
if(isset($_REQUEST['action']) && $_REQUEST['action']=='delete')
{
	mysqli_query($conn,"DELETE FROM $table_name WHERE id = '".$_REQUEST['id']."' ");
	
	$_SESSION['info_message'] = "Enquiry deleted successfully";
	header("location: $file_name?page=view".$next_page_condition.$paging);
	exit();
}
#################################  END DELETE    #########################################
?>

<section class="content">
	<div class="container-fluid">
		<div class="row">
			<div class="col-lg-12">
				<div class="card">
					<!----------------------- Message ------------------------------->
					<? if(isset($_SESSION['info_message'])){ ?>
					  <div class="alert alert-info alert-dismissable">
						<button type="button" class="close" data-dismiss="alert" aria-hidden="true">&times;</button>
						<? echo $_SESSION['info_message']; unset($_SESSION['info_message']);?>
					  </div>
					  <? } ?>
					<!----------------------- End Message ------------------------------->
					<div class="">
						<div class="card-body">
						<!-- search form -->
						<?php //include_once('asign_management_search_options.inc.php');?>
						<!-- /.search form -->
						
<div class="row mb-3">
    <div class="col-md-6">
        <h5>Total No. of Works Order: <?=$total_no_of_records;?></h5>
    </div>
    <div class="col-md-6 text-right">
        <div class="btn-group" role="group">
            <button type="button" id="lock_efficiency" class="btn btn-warning lock-btn mr-2 hide">
                <i class="fas fa-lock"></i> Lock For Efficiency
            </button>
            <button type="button" id="showEfficiencyBtn" class="btn btn-primary">
                Show Efficiency Report
            </button>
        </div>
    </div>
</div>
<input type="hidden" id="is_locked" value="0">
                        <div id="efficiencyReport" class="efficiency-report">
                            <h4>Efficiency Report for <?php echo $selected_date; ?></h4>
                            <?php
                             
								$sqll = "
								SELECT 
									e.machine_id,
									GROUP_CONCAT(DISTINCT e.work_order_id) AS work_order_ids,
									GROUP_CONCAT(DISTINCT e.engineer_id) AS assigned_engineers,
									COUNT(DISTINCT ee.engineer_id) AS engineers_on_machine,
									MAX(engineer_machine_count.engineer_machine_total) AS max_machine_count_for_any_engineer,
									CASE
										WHEN COUNT(DISTINCT ee.engineer_id) > 1 THEN 98
										WHEN MAX(engineer_machine_count.engineer_machine_total) = 1 THEN 98
										WHEN MAX(engineer_machine_count.engineer_machine_total) > 1 THEN 85
										ELSE 0
									END AS efficiency
								FROM work_order_assign e
								LEFT JOIN work_order_assign ee 
									ON e.machine_id = ee.machine_id AND DATE(ee.created_on) = CURDATE()
								LEFT JOIN (
									SELECT engineer_id, COUNT(DISTINCT machine_id) AS engineer_machine_total
									FROM work_order_assign
									WHERE DATE(created_on) = CURDATE()
									GROUP BY engineer_id
								) AS engineer_machine_count 
									ON e.engineer_id = engineer_machine_count.engineer_id
								WHERE DATE(e.created_on) = CURDATE()
								GROUP BY e.machine_id;
								";

                            $report_result = $conn->query($sqll);

                            if ($report_result->num_rows > 0) {
                                echo "<table>
                                        <tr>
                                           <th>Machine ID</th>
											<th>Work Order IDs</th>
											<th>Assigned Engineers</th>
											<th>Engineer Count</th>
											<th>Max Machine Count (Per Engineer)</th>
											<th>Efficiency</th>
                                        </tr>";
                               while($roww = $report_result->fetch_assoc()) {
    echo "<tr>
            <td>" . htmlspecialchars($gsi->getStationById($roww["machine_id"])) . "</td>
             <td>{$roww['work_order_ids']}</td>
             <td>{$roww['assigned_engineers']}</td>
             <td>{$roww['engineers_on_machine']}</td>
             <td>{$roww['max_machine_count_for_any_engineer']}</td>
             <td>{$roww['efficiency']}%</td>
          </tr>";


  
}
                                echo "</table>";
                            } else {
                                echo "<p>No efficiency data available for selected date.</p>";
                            }
                            ?>
                        </div>
						
							<form action="index?page=add" method="post" name="form1" id="form1">
							<div class="card-footer">
							    
							  
							</div>
							<?php if ($result > 0) { ?>
							<div class="table-responsive">
								<table id="example1" class="table table-bordered table-striped">
									<thead>
										<tr>
											<th>Customer Name</th>
											<th>Works Order No</th>
											<th>Part Number</th>
											<th style="width:290px;">Machine Scheduled</th>
											<th class="" style="width:210px;">Works Order Scheduled</th>
											<th class="" style="width:200px;">Engineer</th>
										</tr>
									</thead>
									<tbody>
										<?php
										while ($row = mysqli_fetch_array($sql)) {
											$row = utility::validate_crypt_data($row);
	                                        $customer_id = utility::getTableFieldById("work_order","customer_id","id",$row["work_order_id"]);
										    $assigned_engineer_id = utility::getTableFieldById("work_order_assign","engineer_id","work_order_no",$row["id"]);
											
											
											$assigned_engineers_query = mysqli_query($conn, 
												"SELECT engineer_id FROM work_order_assign WHERE work_order_no = '".$row["id"]."' AND machine_id = '".$row["machine_id"]."' AND part_id = '".$row["part_id"]."'");
											$assigned_engineers = [];
											while ($eng = mysqli_fetch_assoc($assigned_engineers_query)) {
												$assigned_engineers[] = $eng['engineer_id'];
											}
        
											
											
											$work_order_name = utility::getTableFieldByTwoCondition("work_order_name","work_order_name","work_order_id",$row["work_order_id"],"part_id",$row["part_id"]);
											
										?>
										<tr <?php echo empty($assigned_engineer_id) ? 'class="highlight-row"' : ''; ?>>
											<td><?php echo $gsi->getCustomerById($customer_id); ?></td>
											<!--<td><?php echo $gsi->getworkOrderNewById($row["work_order_id"]); ?></td>-->	
										    <td>	<?php echo $work_order_name; ?></td>
											<td><?php echo $gsi->getPartNumberById($row["part_id"]); ?></td>
											<td><?php echo $gsi->getStationById($row["machine_id"]); ?></td>
											<td><?php echo $selected_date; ?></td>
											<td>
												<select name="engineer_id[]" class="form-control select2" multiple 
														id="engineer_<?php echo $row['id']; ?>" required>
													<option value="">Assign Engineer</option>
													<?php
														$query = "SELECT id, uname FROM admin";
														$result = $conn->query($query);
														while ($admin = $result->fetch_assoc()) {
															$selected = in_array($admin['id'], $assigned_engineers) ? 'selected' : '';
															echo '<option value="' . $admin['id'] . '" ' . $selected . '>' . $admin['uname'] . '</option>';
														}
													?>
												</select>
											</td>
											<td>
												<button 
													class="btn btn-sm btn-primary"
													onclick="submitEngineerViaButton(this)"
													data-workorder="<?php echo $row['work_order_id']; ?>"
													data-workorderno="<?php echo $row['id']; ?>"
													data-machine="<?php echo $row['machine_id']; ?>"
													data-date="<?php echo $selected_date; ?>"
													data-customer="<?php echo $customer_id; ?>"
													data-part="<?php echo $row['part_id']; ?>"
													data-engineer-id="engineer_<?php echo $row['id']; ?>"
												>Assign</button>
											</td>
										</tr>

										<?php } ?>
									</tbody>
								</table>
							</div>
						<?php } else { ?>
							<p>No records found.</p>
						<?php } ?>

							
							<div class="box-footer clearfix">
								<!-- Paging starts here  -->
								<? 
								$next_page_condition .="&page=view";
								include("paging/paging_row.inc.php") 
								?>
								<!-- Paging ends starts here  -->
							</div>
						</div>
						<div class="card-footer hide">
						   <button type="submit" name="add" class="btn btn-primary">Add </button>
						</div>
						</form>
					</div>
				</div>
			</div>
		</div>
	</div>
</section>

		</div>
	</div>
</section>
<script type="text/javascript">
function submitEngineerViaButton(button) {
    const engineerSelectId = button.getAttribute("data-engineer-id");
    const engineerSelect = document.getElementById(engineerSelectId);
    const selectedEngineers = $(engineerSelect).val(); // get array for multiple selection

    if (!selectedEngineers || selectedEngineers.length === 0) {
        alert("Please select at least one engineer.");
        return;
    }

    if (!confirm("Are you sure you want to assign/update engineer(s)?")) return;

    $.ajax({
        url: site_url + "/modules/engineer_asign_work_order/index.php?page=ajax_actions&action=assign_engineer",
        type: "POST",
        data: {
            work_order_id: button.dataset.workorder,
            work_order_no: button.dataset.workorderno,
            engineer_id: selectedEngineers, // array
            machine_id: button.dataset.machine,
            work_order_sched_date: button.dataset.date,
            customer_id: button.dataset.customer,
            part_id: button.dataset.part
        },
       success: function (response) {
    let res = response.trim();
    if (res === "inserted" || res === "updated") {
        alert("Engineer(s) " + (res === "inserted" ? "assigned" : "updated") + " successfully!");

        // ✅ Auto-trigger efficiency calculation after assignment
        $.ajax({
            url: site_url + "/modules/engineer_asign_work_order/index.php?page=ajax_actions&action=calculate_efficiency",
            type: "POST",
            data: {
                selected_date: '<?php echo $selected_date; ?>'
            },
            success: function(calcRes) {
                if (calcRes.trim() === "success") {
                    console.log("Efficiency recalculated successfully after assignment.");
                } else {
                    console.warn("Efficiency recalculation issue:", calcRes);
                }
            },
            error: function(xhr, status, error) {
                console.error("Error recalculating efficiency:", error);
            }
        });
    } else {
        alert("Unexpected response: " + res);
    }
},

        error: function (xhr, status, error) {
            alert("Error: " + error);
        }
    });
}



</script> 
<script>
$(document).ready(function() {
    // Lock/Unlock functionality
    $('#lock_efficiency').click(function() {
        if ($('#is_locked').val() === '0') {
            // Locking - calculate efficiency without showing table
            if (!confirm("Are you sure you want to lock and calculate efficiency? This will adjust hours based on engineer assignments.")) return;
            
            $.ajax({
                url: site_url + "/modules/engineer_asign_work_order/index.php?page=ajax_actions&action=calculate_efficiency",
                type: "POST",
                data: {
                    selected_date: '<?php echo $selected_date; ?>'
                },
                success: function(response) {
                    if (response.trim() === "success") {
                        $('#lock_efficiency').html('<i class="fas fa-lock"></i> Unlock For Changes');
                        $('#is_locked').val('1');
                        alert("Efficiency calculated and locked successfully!");
                        disableFormInputs(true);
                    } else {
                        alert("Error calculating efficiency: " + response);
                    }
                },
                error: function(xhr, status, error) {
                    alert("Error: " + error);
                }
            });
        } else {
            // Unlocking
            $('#lock_efficiency').html('<i class="fas fa-lock-open"></i> Lock For Efficiency');
            $('#is_locked').val('0');
            disableFormInputs(false);
            alert("Changes are now unlocked. You can modify assignments.");
        }
    });

    // Function to disable/enable form inputs
    function disableFormInputs(disabled) {
        $('select[name^="engineer_id"]').prop('disabled', disabled);
        $('button[onclick^="submitEngineerViaButton"]').prop('disabled', disabled);
    }

    // Show/hide efficiency report
$('#showEfficiencyBtn').click(function() {
    $('#efficiencyReport').toggle();
    if ($('#efficiencyReport').is(':visible')) {
        $(this).text('Hide Efficiency Report');
    } else {
        $(this).text('Show Efficiency Report');
    }
});
});

 </script> 