<?php
include ("work_order_function.inc.php");
function checkProcessDepth($product_id, $conn, $depth = 0) {
    $query = "SELECT sub_part_id FROM bom WHERE main_product_id = $product_id";
    $bom_parts = $conn->query($query);

    if ($bom_parts->num_rows > 0) {
        $max_sub_depth = $depth;
        while ($bom = $bom_parts->fetch_assoc()) {
            $sub_part_id = $bom['sub_part_id'];
            $sub_depth = checkProcessDepth($sub_part_id, $conn, $depth + 1);
            $max_sub_depth = max($max_sub_depth, $sub_depth);
        }
        return $max_sub_depth;
    }
    return $depth;
}

?>
 <style>
        body {
            font-family: Arial, sans-serif;
            margin: 20px;
        }

        form {
            max-width: 400px;
            margin: 0 auto;
        }

        label {
            display: block;
            margin-bottom: 5px;
            font-weight: bold;
        }

        input[type="number"] {
            width: 100%;
            padding: 8px;
            margin-bottom: 15px;
            border: 1px solid #ccc;
            border-radius: 4px;
            box-sizing: border-box;
        }

        button {
            width: 100%;
            padding: 10px;
            background-color: #4CAF50;
            color: white;
            border: none;
            border-radius: 4px;
            font-size: 16px;
            cursor: pointer;
        }

        button:hover {
            background-color: #45a049;
        }
		em{color:red;font-size: 20px;position: absolute;}
    </style>
<body>
   <h1>Work Order</h1>
<form method="POST" action="">
    <label>Order Type:<em>*</em></label>
    <div class="mb-3">
        <label class="form-check-inline me-3">
            <input type="radio" class="form-check-input" name="order_type" value="individual"
                <?php if(isset($order_type) && $order_type == "individual") echo "checked"; ?>
                onclick="toggleFields('individual')" required>
            Individual
        </label>
        <label class="form-check-inline me-3">
            <input type="radio" class="form-check-input" name="order_type" value="group"
                <?php if(isset($order_type) && $order_type == "group") echo "checked"; ?>
                onclick="toggleFields('group')">
            Group
        </label>
        <!--<label class="form-check-inline">
            <input type="radio" class="form-check-input" name="order_type" value="set"
                <?php if(isset($order_type) && $order_type == "set") echo "checked"; ?>
                onclick="toggleFields('set')">
            Set
        </label>-->
    </div>

    <label for="customer_id">Customer<em>*</em></label>
    <div>
        <? $gsi->getCustomerList("customer_id",$customer_id,"100%",false,"form-control select2 customer_id",""); ?>
    </div>

    <!-- Product ID (Individual) -->
    <div id="product_section">
        <label for="product_id">Product ID:<em>*</em></label>
        <div>
            <? $gsi->getworkItemList("product_id",$product_id,"100%",false,"form-control select2 product_id",""); ?>
        </div>
    </div>

    <!-- Group ID (Group) -->
    <div id="group_section">
        <label for="group_id">Group ID:<em>*</em></label>
        <div>
            <? $gsi->getworkordergroupList("group_id",$group_id,"100%",false,"form-control select2 group_id",""); ?>
        </div>
    </div>

    <!-- Order Quantity (Hide when Group is selected) -->
    <div id="quantity_section">
        <label class="control-label" for="order_quantity">Order Quantity:<em>*</em></label>
        <div>
            <input type="number" class="form-control" id="order_quantity" name="order_quantity"
            value="<?php echo $order_quantity;?>" placeholder="Order Quantity" autocomplete="off"> 
        </div>
    </div>

    <label class="control-label">Required Date:<em>*</em></label>
    <div>
        <input type="text" class="form-control datepicker" id="required_date" name="required_date"
        value="<?php echo (isset($required_date) && $required_date != "") ? utility::getFormatedDate($required_date) : ""; ?>"
        placeholder="DD-MM-YYYY" autocomplete="off" required>
    </div>

    <label for="Shift Assign" class="control-label">Shift Assign<em>*</em></label>
    <div>
        <? $gsi->getShiftList("shift_id",$shift_id,"100%",true,"form-control select2",""); ?>
    </div>

    <button type="submit">Submit</button>
</form>

<!-- JavaScript to toggle fields -->
<script>
function toggleFields(type) {
    const productSection = document.getElementById('product_section');
    const groupSection = document.getElementById('group_section');
    const quantitySection = document.getElementById('quantity_section');

    if (type === 'individual') {
        productSection.style.display = 'block';
        groupSection.style.display = 'none';
        quantitySection.style.display = 'block';
    } else if (type === 'group') {
        productSection.style.display = 'none';
        groupSection.style.display = 'block';
        quantitySection.style.display = 'none';
    } else {
        productSection.style.display = 'none';
        groupSection.style.display = 'none';
        quantitySection.style.display = 'block';
    }
}

// Run on page load to set the correct visibility
window.onload = function () {
    const selected = document.querySelector('input[name="order_type"]:checked');
    if (selected) {
        toggleFields(selected.value);
    }
};
</script>




    <?php
	
   /* if ($_SERVER['REQUEST_METHOD'] == 'POST') {
        $customer_id = intval($_POST['customer_id']);
		//$product_id = intval($_POST['product_id']);
		$product_id = [119,118];
       // $order_quantity = intval($_POST['order_quantity']);
		$order_quantity = [10,8];
        $require_datee = utility::setFormatedDate( $_POST['required_date']); 
		$required_date = date('Y-m-d', strtotime($require_datee . ' -2 days'));
		$shift_ids = $_POST['shift_id'];
		$shift_idss				= implode(",",$shift_ids);
        ///////// For work order No.//////
		$rr_query = mysqli_query($conn, "SELECT IFNULL(MAX(CAST(SUBSTRING(work_order_no, 5) AS UNSIGNED)), 0) + 1 AS new_enq FROM work_order");
		$rr_row = mysqli_fetch_assoc($rr_query);
		$work_order_no = 'CCO-' . str_pad($rr_row['new_enq'], 3, '0', STR_PAD_LEFT);	
		///////////////////////////////////////		
		$query_work_order = "INSERT INTO work_order (customer_id,work_order_no, product_id, order_quantity, require_date, shift_ids) 
              VALUES ('$customer_id', '$work_order_no', '$product_id', '$order_quantity', '$require_datee', '$shift_idss')";
        $conn->query($query_work_order);
		$work_order_id = mysqli_insert_id($conn);

		$flag = 1;
        $work_schedule = checkProcessDepth($product_id, $conn, $depth = 0);		
		$depth_total = $work_schedule + 2 ;
        //processOrderHybrid($product_id, $order_quantity, $shift_ids, $conn, $required_date, $work_order_id, $flag );
		foreach ($product_id and quantity ){
		processOrderHybrid($product_id, $order_quantity, $shift_ids, $conn, $required_date, $work_order_id, $flag, $depth = $depth_total, $max_depth = 10 );
        
		}
    }*/
	
	if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    //$customer_id = intval($_POST['customer_id']);
	//$group_id = intval($_POST['group_id']);
	 
	  $customer_id =1;
	/*echo $sql_group_mapping = "SELECT * FROM group_mangmnt_mapping WHERE group_id = ".$group_id;
	$result_group_mapping = mysqli_query($conn, $sql_group_mapping);

	$product_ids = [];
	$order_quantities = [];

	while ($row_group_mapping = mysqli_fetch_array($result_group_mapping)) {
		$product_ids[] = $row_group_mapping['part_number'];
		$order_quantities[] = $row_group_mapping['quantity'];
	}*/
	
	
$setorderData =	[];
$check_for_insert =1;

	
	
	//$set_check = 1;
    //$product_ids = [151,152];
	$product_ids = [8568];
//$order_quantities = [150,100];
$order_quantities = [10];
    $require_datee = utility::setFormatedDate($_POST['required_date']); 
    $required_date = date('Y-m-d', strtotime($require_datee . ' -2 days'));
    //$shift_ids = $_POST['shift_id'];
    //$shift_idss = implode(",", $shift_ids);
	
$sql_shift = "SELECT id FROM working_hours where 1=1";
$result_result = $conn->query($sql_shift);


$shift_ids = [];

if ($result_result->num_rows > 0) {
    while ($row = $result_result->fetch_assoc()) {
        $shift_ids[] = $row['id'];
    }
}

echo $shift_idss = implode(",", $shift_ids);

   $rr_query = mysqli_query($conn, "SELECT IFNULL(MAX(CAST(SUBSTRING(work_order_no, 5) AS UNSIGNED)), 0) + 1 AS new_order FROM work_order_customer_ref_mapping");
	$rr_row = mysqli_fetch_assoc($rr_query);
	$work_order_name = 'order-' . str_pad($rr_row['new_order'], 3, '0', STR_PAD_LEFT);
   // $work_order_no = "coo767"; 


    $query_work_order = "INSERT INTO work_order (customer_id, work_order_no, product_id, order_quantity, require_date, shift_ids) 
          VALUES ('$customer_id', '$work_order_name', '" . implode(",", $product_ids) . "', '" . implode(",", $order_quantities) . "', '$require_dateet', '$shift_idss')";
    $conn->query($query_work_order);
    $work_order_id = mysqli_insert_id($conn);
	



foreach ($product_ids as $index => $product_id) {
    // Generate new work_order_no for each product_id
    $rr_query = mysqli_query($conn, "SELECT IFNULL(MAX(CAST(SUBSTRING(work_order_no, 5) AS UNSIGNED)), 0) + 1 AS new_enq FROM work_order_customer_ref_mapping");
    $rr_row = mysqli_fetch_assoc($rr_query);
    $work_order_no = 'CCO-' . str_pad($rr_row['new_enq'], 3, '0', STR_PAD_LEFT);
    $quantity = $order_quantities[$index];
    // Insert new work_order_no along with product_id and quantity into the table
     $insert_query = "INSERT INTO work_order_customer_ref_mapping (work_order_no, work_order_id, quantity) VALUES ('$work_order_no', '$work_order_id', '$quantity')";
    mysqli_query($conn, $insert_query);
    }
	
	
	
    $flag = 1;
    
    // Process all products simultaneously
    //processOrderHybrid($product_ids, $order_quantities, $shift_ids, $conn, $required_date, $work_order_id, $flag);
	   
    processOrderHybrid($product_ids, $order_quantities, $shift_ids, $conn, $required_date, $work_order_id, $flag, $setorderData);
}

$grouped_operations = [];
foreach ($operations as $operation) {
    $grouped_operations[$operation['product_code']][] = [
        'description' => $operation['operation'],
		'product_name' => $operation['product_name'],
        'product_id' => $operation['product_id'] ?? null,
        'quantity' => $operation['qty'] ?? 0,
		'process_type' => $operation['process_type'] ?? 0,
		'machine' => $operation['machine'] ?? 0,
		'Start_Date' => $operation['Start_Date'] ?? null,
        'required_date' => $operation['required_date'] ?? null,
		'parent_ids' => $operation['parent_ids'] ?? 0,
		'highlight' => $operation['highlight'] ?? 0,
		'total_time' => $operation['total_time'] ?? 0,
		'p_name' => $operation['p_name'] ?? null,
		'allocated_dates' => $operation['allocated_dates'] ?? null
    ];
}


echo "<h4>Levels Log:</h4>";
foreach ($grouped_operations as $product_code => $ops) {
    echo "<h3>Level for $product_code:</h3><ul>";
    foreach ($ops as $op) {
    echo "<li>{$op['description']} (Qty: {$op['quantity']}, parent_iddddd: " . implode(', ', $op['parent_ids']) . ", Required Date: {$op['required_date']}, P_name: {$op['p_name']}, total_time: {$op['total_time']}, process_type: {$op['process_type']})</li>";

		$operation_description = $op['description'];
		$product_name = $op['product_name'];
        $product_id = $op['product_id'] ?? null; 
        $quantity = $op['quantity'] ?? 0;
		$process_type = $op['process_type'] ?? 0;
		$machine = $op['machine'] ?? 0;
		$Start_Date = $op['Start_Date'] ?? null;
        $required_datee = $op['required_date'] ?? null; 
		$highlight = $op['highlight'] ?? 0;
		$total_time = $op['total_time'] ?? 0;
		$allocated_dates = $op['allocated_dates'] ?? null;
	    $parent_ids = implode(', ', $op['parent_ids']) ?? 0;

     if ($process_type == 6 ) {
		$rr_query = mysqli_query($conn, "SELECT IFNULL(MAX(CAST(SUBSTRING(work_order_name, 4) AS UNSIGNED)), 0) + 1 AS new_enq FROM work_order_name");
		$rr_row = mysqli_fetch_assoc($rr_query);
		
		$work_order_name = 'WO-' . str_pad($rr_row['new_enq'], 3, '0', STR_PAD_LEFT);
		
		
        $query = "INSERT INTO work_order_name (work_order_id, part_id, work_order_name) 
          VALUES ($work_order_id, $product_id, '$work_order_name')";

        $conn->query($query);
    } 
	
	
	
		
		
		
        logWorkOrder($conn, $work_order_id, $product_code, $product_name, $operation_description, $product_id, $quantity, $required_datee, $process_type, $parent_ids, $machine, $shift_idss, $highlight, $allocated_dates);
    }
    echo "</ul>";
}
function logWorkOrder($conn, $work_order_id, $product_code, $product_name, $operation_description, $product_id, $quantity, $required_datee, $process_type, $parent_ids, $machine, $shift_idss, $highlight, $allocated_dates) {
    
  
	if ($process_type == 6 || $process_type == 4 || $process_type == 12 || $process_type == 21) {
        // Prepare the SQL query
		 $parent_ids = str_replace("Array,", "", $parent_ids);
        echo $query = "INSERT INTO work_order_detail (work_order_id, product_code, product_name, operation_description, product_id, quantity, required_date, process_type, parent_ids, machine, shift_idss, total_time) 
                  
				  VALUES ($work_order_id, '$product_code', '$product_name', '$operation_description', '$product_id', $quantity, '$required_datee', '$process_type', '$parent_ids', '$machine', '$shift_idss', '$total_time')";
				  
 

        // Execute the query
        $conn->query($query);
		echo "<br>";
    }
	if ($process_type === 7) {  
	  if ($highlight === 131){
		  echo $sql = "UPDATE work_order_detail SET end_date = '$allocated_dates' WHERE product_id = $product_id And work_order_id = $work_order_id ";

    // Execute the query
    $conn->query($sql);  // Changed $query to $sql
	echo "<br>";
		  
	  }
    
}

	
}
if ($set_check == 1) { 
    $sql = "
    SELECT 
        wod.product_id, 
        wod.work_order_id, 
        wod.quantity, 
        wod.required_date, 
        wod.set_part, 
        won.part_id,
		wod.product_code,wod.end_date,
		wod.machine,
        won.work_order_name
    FROM 
        work_order_detail wod
    LEFT JOIN 
        work_order_name won 
        ON wod.work_order_id = won.work_order_id AND wod.product_id = won.part_id
    WHERE 
        wod.process_type = 6 And wod.work_order_id = $work_order_id
";
$result = $conn->query($sql);
    $productIds = [];
    $quantities = [];       // Store quantities associated with product IDs
    $required_dates = []; 
	$work_order_names = [];
	$product_codes = []; 
	$machines = []; 
	$end_dates = [];    // Store required dates associated with product IDs

    if ($result->num_rows > 0) {
        while ($row = $result->fetch_assoc()) {
            $productIds[] = $row['product_id'];
            $quantities[$row['product_id']] = $row['quantity'];
            $required_dates[$row['product_id']] = $row['required_date'];
			$work_order_names[$row['product_id']] = $row['work_order_name'];
			$product_codes[$row['product_id']] = $row['product_code'];
			$machines[$row['product_id']] = $row['machine']; 
			$end_dates[$row['product_id']] = $row['end_date']; // Store required_date with product_id as key
        }
    }

    foreach ($productIds as $productId) {
         echo "<br>";
        echo $sqlMapping = "SELECT set_id, ratio FROM set_mangmnt_mapping WHERE part_id = '$productId'";
        $resultMapping = $conn->query($sqlMapping);

        if ($resultMapping->num_rows > 0) {
            while ($rowMapping = $resultMapping->fetch_assoc()) {
                 $set_id = $rowMapping['set_id'];
                $ratio = $rowMapping['ratio'];
                $originalQuantity = $quantities[$productId]; 
                $required_date = $required_dates[$productId]; 
				$work_order_name = $work_order_names[$productId]; 
				$product_codee = $product_codes[$productId]; 
				$machineee = $machines[$productId];
				$end_date = $end_dates[$productId]; 
                echo "<br>";
                echo $sqlSet = "SELECT part_id, ratio FROM set_mangmnt_mapping WHERE set_id = '$set_id'";
                
                $resultSet = $conn->query($sqlSet);

               if ($resultSet->num_rows > 0) {
					$partNumbers = [];       
					$quantitiesForParts = []; 

					while ($rowSet = $resultSet->fetch_assoc()) {
						$partid = $rowSet['part_id'];
						$partRatio = $rowSet['ratio'];

						if ($partid == $productId) {
							continue; 
						}

						$calculatedQuantity = $originalQuantity * $partRatio;

						$partNumbers[] = $partid;
						$quantitiesForParts[] = $calculatedQuantity;
						
						$absolute_quantity_if_set = $calculatedQuantity + $originalQuantity;
						
						$part_name = utility::getTableFieldById("item_management","part_number","id",$partid);
						 echo "<br>";
						echo $query = "INSERT INTO work_order_detail (work_order_id, product_code, product_name, operation_description, product_id, quantity, required_date, process_type, parent_ids, machine, shift_idss, set_id, set_part) 
						VALUES ($work_order_id, '$product_codee', '$part_name', '$operation_description', '$partid', $calculatedQuantity, '$required_date', '6', '$parent_ids', '$machine', '$shift_idss', '$set_id', '1')";
								  
						$conn->query($query);
		
						$sql_for_set = "UPDATE work_order_detail SET set_id = '$set_id', absolute_quantity_if_set = '$absolute_quantity_if_set' WHERE product_id = $productId And work_order_id = $work_order_id ";
						$conn->query($sql_for_set);
						$query_for_work_order_name_set = "INSERT INTO work_order_name (work_order_id, part_id, work_order_name) 
						  VALUES ($work_order_id, $partid, '$work_order_name')";
						$conn->query($query_for_work_order_name_set);

						
					}
					

				}

            }
        }
			
    }
	
	

	
}


    ?>
</body>
