<?php
include("../../../include/startup.php"); 
ob_clean();
if(isset($_REQUEST['action']) && $_REQUEST['action']=='get_package_price'){
	$packages_id = $_REQUEST['packages_id'];
	$row = utility::getTableRowByField("fixed_packages","id",$packages_id);
	$returnArray["price"] = $row["price"];
	echo json_encode($returnArray);
}else if (isset($_REQUEST['action']) && $_REQUEST['action'] == 'assign_engineer') {

    $work_order_id = $_POST['work_order_id'];
    $engineer_ids = $_POST['engineer_id']; // This should be an array
    $machine_id = $_POST['machine_id'];
    $schedule_date = Utility::setFormatedDate($_POST['work_order_sched_date']);
    $customer_id = $_POST['customer_id'];
    $part_id = $_POST['part_id'];
    $work_order_no = $_POST['work_order_no'];

    
    $deleteQuery = "DELETE FROM work_order_assign WHERE work_order_id = '$work_order_id' AND part_id = '$part_id' AND machine_id = '$machine_id' ";
    $conn->query($deleteQuery);

    $inserted = false;
    foreach ($engineer_ids as $engineer_id) {
        $insertQuery = "INSERT INTO work_order_assign (
                            work_order_id, work_order_no, engineer_id, machine_id,
                            work_order_sched_date, customer_id, part_id
                        ) VALUES (
                            '$work_order_id', '$work_order_no', '$engineer_id', '$machine_id',
                            '$schedule_date', '$customer_id', '$part_id'
                        )";

        if ($conn->query($insertQuery) === TRUE) {
            $inserted = true;
        } else {
            $inserted = false;
            break;
        }
    }

    if ($inserted) {
        echo "inserted";
    } else {
        echo "error";
    }
}else if (isset($_REQUEST['action']) && $_REQUEST['action'] == 'calculate_efficiency') {

    $selected_date = $_REQUEST['selected_date'];
    $formatted_date = date("Y-m-d", strtotime($selected_date));
    
    $sql = "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) = '$formatted_date'
    LEFT JOIN (
        SELECT engineer_id, COUNT(DISTINCT machine_id) AS engineer_machine_total
        FROM work_order_assign
        WHERE DATE(created_on) = '$formatted_date'
        GROUP BY engineer_id
    ) AS engineer_machine_count 
        ON e.engineer_id = engineer_machine_count.engineer_id
    WHERE DATE(e.created_on) = '$formatted_date'
    GROUP BY e.machine_id";
    
    $report_result = $conn->query($sql);
    
    if ($report_result->num_rows > 0) {
        while($row = $report_result->fetch_assoc()) {
            $efficiency = round($row['efficiency']);
            $machine_id = $row['machine_id'];
            $work_order_ids = explode(',', $row['work_order_ids']); 

            foreach ($work_order_ids as $wo_id) {
                $wo_id = trim($wo_id);
                $get_hours_sql = "SELECT total_hours, total_hours_update, setup_hours FROM vac_machine_table 
                                  WHERE machine_id = '$machine_id' AND work_order_id = '$wo_id' LIMIT 1";
                $hours_result = $conn->query($get_hours_sql);
                
                if ($hours_result && $hours_result->num_rows > 0) {
                    $hours_row = $hours_result->fetch_assoc();
                    $original_total_hours_update = $hours_row['total_hours_update'];
$original_setup_hours       = $hours_row['setup_hours'];

// Add both values to get original_hours
$original_hours = $original_total_hours_update + $original_setup_hours;

$adjusted_hours = round(($original_hours * 100) / $efficiency, 2);

                    
					$machine_type = utility::getTableFieldById("station_detail_table","machine_type","id",$machine_id);
					if($machine_type == 1){
                    $update_sql_for_vac = "UPDATE vac_machine_table 
                                   SET total_hours = $adjusted_hours 
                                   WHERE machine_id = '$machine_id' AND work_order_id = '$wo_id'";
                    $conn->query($update_sql_for_vac);
					}elseif($machine_type == 2){
					$update_sql_for_cnc = "UPDATE assbly_machine_table  
                                   SET total_hours = $adjusted_hours 
                                   WHERE machine_id = '$machine_id' AND work_order_id = '$wo_id'";
                    $conn->query($update_sql_for_cnc);
					}elseif($machine_type == 4){
					$update_sql_for_cnc = "UPDATE pu_machine_table 
                                   SET total_hours = $adjusted_hours 
                                   WHERE machine_id = '$machine_id' AND work_order_id = '$wo_id'";
                    $conn->query($update_sql_for_cnc);
					}
					
                }
            }
        }
        echo "success";
    } else {
        echo "No data found for efficiency calculation";
    }
    exit();
}
die;
?>