<?php
session_start();
$where 					= " WHERE 1=1 ";
$next_page_condition 	= "";
$paging ="";
if($_REQUEST['start']){
	$paging .="&start=".$_REQUEST['start'];
}
###########################################  STRAT FILTER CONITIONS    #####################################
$customer 	= isset($_REQUEST['customer']) ? $_REQUEST['customer'] : "";
if($customer) {
    $where	.= " AND id = '$customer' ";
    $next_page_condition.="&customer=$customer";
}
###########################################  	END  FILTER CONITIONS 	#####################################
###########################################  PAGING WITH PER PAGE  #####################################
$file_name		= "index"; // this is file name which is used during paging  , included at the bottom of the page
$table_name		= "production_planning";
$paging_table_name	= $table_name;
$paging_query		= $where;
$join_query_for_paging = "SELECT * FROM $table_name  $where ";
$page_header = "Production Planning Management";
include("paging/paging_query.inc.php");
############################################ END PAGING WITH PER PAGE  #######################################
//$query = "SELECT * FROM $table_name $where ORDER BY id ASC LIMIT $eu, $limit";
// Fetch minimum and maximum req_date
$date_range_query = "SELECT MIN(req_date) AS min_date, MAX(req_date) AS max_date FROM production_planning";
$date_range_result = mysqli_query($conn, $date_range_query);
$date_range = mysqli_fetch_assoc($date_range_result);
$min_date = date('Y-m-d');

// Adjust min_date to the nearest Monday
$min_date = date('Y-m-d', strtotime('monday this week', strtotime($min_date)));

$max_date = date('Y-m-d', strtotime($min_date . ' +9 weeks')); 

$start_week = date('oW', strtotime($min_date)); 
$end_week = date('oW', strtotime($max_date));


// Fetch Data Grouped by Part Number and Week
$query = "
    SELECT 
        part_number, 
        YEARWEEK(req_date, 3) AS week_number,  
        SUM(req_qty) as total_req_qty
    FROM production_planning 
    $where
    GROUP BY part_number, YEARWEEK(req_date, 3) 
    ORDER BY part_number, week_number 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')
{
	$sql=mysql_query("DELETE FROM $table_name WHERE id = '".$_REQUEST['id']."' ");
	$_SESSION['info_message'] = "IteM deleted sucessfully";
	header("location: $file_name?page=view_country".$next_page_condition.$paging);
	exit;
}
$set_check = 1;
#################################  END DELETE    #########################################
?>
<section class="content-header">
  <h1>
	<?=$page_header;?>
  </h1>
</section>
<style> 
 table {
        width: 100%;
        border-collapse: collapse;
        table-layout: fixed;
    }
    th ,td{
        border: 1px solid #ddd;
        padding: 8px;
        text-align: center;
       white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;
    }
	th:nth-last-child(2), td:nth-last-child(2) {
    width: 90px; /* Adjust width as needed */
}

 th:first-child, td:first-child { width: 90px; }
 th:last-child, td:last-child { width: 170px; }
    th:nth-child(2), td:nth-child(2) { width: 100px; }
    th:nth-child(3), td:nth-child(3) { width: 100px; }
    th,td { width: 65px; }
</style>
<section class="content">
	<div class="row">
		<div class="col-lg-12">
			<!----------------------- Message ------------------------------->
			<? if(isset($_SESSION['info_message'])){ ?>
			  <div class="alert alert-success 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="box">
				<div class="box-body">
				<!-- search form -->
				<?php include_once('planning_search_options.inc.php');?>
				<!-- /.search form -->
					
					<div class="box-footer">
					   <button type="submit" name="add" class="hide btn btn-success">Add </button>
					</div>
					
				<div class="table-responsive">
				<div style="margin-bottom: 10px;">
						<span style="background-color: #adf79d; color: black; padding: 5px; margin-right: 10px;">  In Stock</span>
						<span style="background-color: #fbf9ab; color: black; padding: 5px;">Works Order raised</span>
					</div>
					<?php if ($result > 0) { ?>
					 <table id="example1" class="table table-bordered table-striped" style="font-size:12px;">
        <thead>
            <tr>
                <th>Part Number</th>
                <th>Stock</th>
                <th>Works Order Outstanding</th>
                <?php 
                    $weeks = [];
                    for ($week = $start_week; $week <= $end_week; $week++) {
                        $week_start_date = date('d-M', strtotime($min_date . " +".($week - $start_week)." week"));
                        echo "<th>$week_start_date</th>";
                        $weeks[] = $week;
                    }
                ?>
                <th>Qty</th>
                <th>Set</th>
                <th>Efficiency</th>
                <th>Action</th>
            </tr>
        </thead>
        <tbody>
            <?php
                $part_data = [];

                while ($row = mysqli_fetch_assoc($sql)) {
                    $part_id = $row['part_number'];
                    $week = $row['week_number'];
                    $part_data[$part_id][$week] = $row['total_req_qty'];
                }

                $work_order_query = "
                    SELECT 
                        w.product_id, 
                        i.part_number, 
                        SUM(w.order_quantity) AS total_production
                    FROM work_order w
                    JOIN item_management i ON w.product_id = i.id
                    GROUP BY w.product_id, i.part_number";

                $work_order_result = mysqli_query($conn, $work_order_query);
                $work_order_data = [];

                while ($wo_row = mysqli_fetch_assoc($work_order_result)) {
                    $work_order_data[$wo_row['part_number']] = $wo_row['total_production'];
                }

                foreach ($part_data as $part_id => $weeks_data) {    
					$order_query = "
					SELECT SUM(w.order_quantity) AS total_ordered , im.id as item_id
					FROM work_order w
					JOIN item_management im ON im.id = w.product_id
					WHERE im.part_number = '$part_id'
				";
				$order_result = mysqli_query($conn, $order_query);
				$order_row = mysqli_fetch_assoc($order_result);
				$produced_qty = $order_row['total_ordered'] ?? 0;
				
				$item_query = "
					SELECT id FROM item_management 
					WHERE part_number = '$part_id'
				";
				$item_result = mysqli_query($conn, $item_query);
				$item_row = mysqli_fetch_assoc($item_result);
				
				$item_id = $item_row['id'];
				//$item_id = 181;


									$inventory_query = "
					SELECT i.quantity_in_stock 
					FROM inventory i 
					JOIN item_management im ON im.id = i.item_id 
					WHERE im.part_number = '$part_id'
				";
				$inventory_result = mysqli_query($conn, $inventory_query);
				$inventory_row = mysqli_fetch_assoc($inventory_result);
				$stock = $inventory_row['quantity_in_stock'] ?? 0;

									

                    ?>
               <tr>
					<td><?php echo ucfirst($part_id); ?></td>
					<td><?php echo $stock; ?></td>
					<td><?php echo ($produced_qty); ?></td>

					<?php
					$remaining_stock = $stock;
						$remaining_production = $produced_qty;

						$nonZeroIndexes = [];
						foreach ($weeks as $index => $week) {
							if (($weeks_data[$week] ?? 0) > 0) {
								$nonZeroIndexes[] = $index;
							}
						}

						$totalWeeks = count($weeks);

						foreach ($weeks as $index => $week) {
							$qty = $weeks_data[$week] ?? 0;
							$color = "white";

							if ($qty > 0) {
								if ($remaining_stock >= $qty) {
									$color = "#5bc236"; // Green
									$remaining_stock -= $qty;
								} elseif ($remaining_production >= $qty) {
									$color = "#fff38c"; // Yellow
									$remaining_production -= $qty;
								}
							} else {
								$nextGreenIndex = null;
								for ($i = $index + 1; $i < $totalWeeks; $i++) {
									$future_qty = $weeks_data[$weeks[$i]] ?? 0;
									if ($future_qty > 0 && $remaining_stock >= $future_qty) {
										$nextGreenIndex = $i;
										break;
									}
								}
								if ($remaining_stock > 0 && $nextGreenIndex !== null) {
									$color = "#5bc236"; 
								}

								if ($remaining_production > 0) {
									$prev = ($index > 0) ? ($weeks_data[$weeks[$index - 1]] ?? 0) : 0;
									$next = ($index < $totalWeeks - 1) ? ($weeks_data[$weeks[$index + 1]] ?? 0) : 0;
									if ($prev > 0 && $next > 0) {
										$color = "#fff38c"; 
									}
								}
							}

							echo "<td style='background-color: $color; text-align: center;'>$qty</td>";
						}

					?>

					<td>
						<input type="number" id="order_qty_<?php echo $part_id; ?>" class="form-control" min="1" placeholder="Qty">
					</td>
					<td>
					<input type="hidden" name="set_check_hidden" id="set_check_hidden_<?php echo $item_id; ?>" value="<?php echo ($set_check == 1) ? '1' : '0'; ?>">
					<input type="checkbox" class="form-check-input set_check" id="set_check_<?php echo $item_id; ?>" name="set_check" value="1" <?php echo ($set_check == 1) ? 'checked' : ''; ?>>
				</td>
                  <td>
					<input type="text" id="efficiency_<?php echo $item_id; ?>" name="efficiency" value="<?php echo $efficiency; ?>" class="form-control" placeholder="">

					<td>
						<button class="btn btn-danger create-order" data-part-id="<?php echo $item_id; ?>">Create Work Order</button>

					</td>
				</tr>



                <?php } ?>
				<? 
				$next_page_condition .="&page=view_production";
				include("paging/paging_row.inc.php") ?>
        </tbody>
    </table>
			<?php } else { ?>
				No Order found...
			<?php } ?>


				</div>
				<div class="box-footer">
                   <button type="submit" name="add" class="hide btn btn-success">Add Country</button>
                </div>
				
			</div>
		</div>
	</div>
</section> 
<div class="modal fade" id="groupModal" tabindex="-1" role="dialog">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title"> Group Items</h5>
                <button type="button" class="close" data-dismiss="modal">&times;</button>
            </div>
            <div class="modal-body">
                <div id="groupItemsContainer"></div>
            </div>
        </div>
    </div>
</div>
 
<script>
$(document).ready(function () {
	
	$(document).on("change", ".set_check", function () {
			let partId = $(this).attr("id").split("_")[2];
			let isChecked = $(this).is(":checked") ? "1" : "0";
			$("#set_check_hidden_" + partId).val(isChecked);
		});

    $(".create-order").click(function () {
        let partId = $(this).data("part-id");
       let set_check = $("#set_check_hidden_" + partId).val();
       let efficiency = $("#efficiency_" + partId).val();
        alert(partId);
        let userConfirmation = confirm("Do you want to include the group items?");
        if (userConfirmation) {
            $.ajax({
                 url: site_url+"/modules/production_planning/index.php?page=ajax_actions&action=fetch_group_items",
                type: "POST",
                data: { part_id: partId,set_check: set_check ,efficiency: efficiency },
                success: function (response) {
                    $("#groupItemsContainer").html(response);
                    $("#groupModal").modal("show");
                }
            });
        } else {
            // Proceed with normal work order creation (handle this separately)
        }
    });


});
$(document).on("click", "#submitGroupOrder", function (e) { 
    e.preventDefault();  // Prevents default form submission behavior
    alert("hii");

    let orderData = [];
    $(".group-item-row").each(function () {
        let groupItemId = $(this).data("group-item-id");
        let quantity = $(this).find(".group-item-qty").val();
        let set_check = $(this).find(".set_check_value").val();
        let customer_reff = $(this).find(".customer_reff").val();
        let efficiency = $(this).find(".efficiency").val();
        orderData.push({ groupItemId: groupItemId, quantity: quantity, set_check: set_check, customer_reff: customer_reff , efficiency: efficiency });
    });
    
    console.log(orderData);

	$.ajax({
    url: site_url+"/modules/production_planning/index.php?page=ajax_actions&action=work_order_fuction",
    type: 'POST',
    data: {
        orderData: JSON.stringify(orderData)
    },
    success: function (response) {
        try {
            var res = JSON.parse(response);
            if (res.status === 'success') {
                alert(res.message);
                console.log(response);
            } else {
                alert('An error occurred while processing the order.');
                console.log(response);
            }
        } catch (e) {
            alert('An unexpected error occurred.');
            console.log(e);
        }
    },
    error: function (error) {
        alert('Something went wrong.');
        console.log(error);
    }
});

	
});


    </script>

	