<?php
session_start();
$where = " WHERE 1=1 ";
$next_page_condition = "";
$paging = "";

if ($_REQUEST['start']) {
	$paging .= "&start=" . $_REQUEST['start'];
}
if (isset($_REQUEST["from"]) && $_REQUEST["from"] != "") {
	$_SESSION["from"] = $_REQUEST["from"];
}
if (isset($_REQUEST['id']) && $_REQUEST['id'] != "") {
	$where .= " AND id = " . $_REQUEST['id'] . " ";
}
$work_order_id = utility::app_crypt($_REQUEST['work_order_id'], 'd');
if ($_REQUEST['id'] != $work_order_id) {
	die("Invaild URL");
}

$query_work_order_main = "SELECT * FROM work_order WHERE id = $work_order_id";
$rs_work_order_main = mysqli_query($conn, $query_work_order_main);
$work_order_main_row = mysqli_fetch_assoc($rs_work_order_main);
$work_order_main_row = utility::validate_crypt_data($work_order_main_row);
$product_id = $work_order_main_row['product_id'];
$customer_id = $work_order_main_row['customer_id'];
$order_quantity = $work_order_main_row['order_quantity'];
$require_date = $work_order_main_row['require_date'];
$shift_ids = $work_order_main_row['shift_ids'];

$query_count = "SELECT COUNT(DISTINCT product_code) as distinct_count FROM work_order_detail WHERE work_order_id = $work_order_id";
$rs_count = mysqli_query($conn, $query_count);
$row_count = mysqli_fetch_assoc($rs_count);
$distinct_no_of_operation = $row_count['distinct_count'];

// Query to fetch grouped data by product_code
$query = "SELECT * FROM work_order_detail WHERE work_order_id = $work_order_id ORDER BY product_code DESC";

$rs = mysqli_query($conn, $query);
$work_order_data = [];
while ($row = mysqli_fetch_assoc($rs)) {
    $work_order_data[$row['product_code']][] = $row; // Group by product_code
}
//print_r($work_order_data);
?>

<section class="content-header responsebar">
	<div class="container-fluid">
		<div class="row">
			<div class="col-lg-12 col-md-6 col-sm-6">
				<div class="col-sm-6">
					<h1 style="float:left;clear:right;">
						Work Order Creation: - <span style='color:#ed5c5c;'><?= $gsi->getworkItemById($product_id); ?></span>
					</h1>
				</div>
				<?
				$query_string = (isset($_POST['query_string'])) ? $_POST['query_string'] : $_SERVER['QUERY_STRING'];
				$query_string = str_ireplace("page=view_work_order_detail", "page=view", $query_string);
				?>
				<button type="button" id="back" name="back" value="back" style="float:right;margin-bottom: 15px;"
					class="btn btn-primary"
					onclick="window.location.href = 'index?<?= $query_string . $next_page_condition . $paging; ?>'">Back</button>
			</div>
		</div>
	</div>
</section>

<section class="content">
    <div class="container-fluid">
        <div class="row">
            <div class="col-lg-12 no-padding">
                <div class="row">
                   <div class="form-group col-lg-6 d-flex">
						<label for="Item No." class="col-sm-4 control-label">Group No.</label>
						<div class="col-sm-8">
							<? echo $gsi->getworkItemById($product_id); ?>
						</div>
					</div>
					<div class="form-group col-lg-6 d-flex">
						<label for="Tax Code" class="col-sm-4 control-label">Order Quantity</label>
						<div class="col-sm-8">
							<? echo $order_quantity; ?>
						</div>
					</div>
					<div class="form-group col-lg-6 d-flex">
						<label for="Tax Code" class="col-sm-4 control-label">Required Date</label>
						<div class="col-sm-8">
							<? echo  utility::getFormatedDate($require_date); ?>
						</div>
					</div>
					<div class="form-group col-lg-6 d-flex">
						<label for="Tax Code" class="col-sm-4 control-label">Customer</label>
						<div class="col-sm-8">
							<? echo $gsi->getCustomerById($customer_id); ?>
						</div>
					</div>
					<div class="form-group col-lg-6 d-flex">
						<label for="Tax Code" class="col-sm-4 control-label">Shifts</label>
						<div class="col-sm-8">
							<? $shift_id_array = explode(',', $shift_ids);
							   $shift_id_name = ""; 

								foreach ($shift_id_array as $shift_id) {
									$shift_id_name .= $gsi->getShiftNameById($shift_id) . ", ";
								}

								$shift_id_name = substr($shift_id_name, 0, -2); 

								echo $shift_id_name;
							?>
						</div>
					</div>
                </div>
            </div>
        </div>
    </div>
</section>
<section class="content">
    <div class="container-fluid">
        <div class="row">
            <div class="col-lg-12 no-padding">
                <div class="row">
                    <?php
                    if ($distinct_no_of_operation > 0) {
                        // First, separate process type 4 from other data
                        $regular_data = [];
                        $process_type_4_data = [];
                        
                        foreach ($work_order_data as $product_code => $rows) {
                            foreach ($rows as $row) {
                                if ($row['process_type'] == 4) {
                                    $process_type_4_data[$product_code][] = $row;
                                } else {
                                    $regular_data[$product_code][] = $row;
                                }
                            }
                        }
                        
                        // Group regular data by level
                        $level_groups = [
                            'M10' => [],
                            'M20' => [],
                            'M30' => []
                        ];
                        
                        foreach ($regular_data as $product_code => $rows) {
                            if (strpos($product_code, 'Level-30') !== false) {
                                $level_groups['M10'][$product_code] = $rows;
                            } elseif (strpos($product_code, 'Level-20') !== false) {
                                $level_groups['M20'][$product_code] = $rows;
                            } elseif (strpos($product_code, 'Level-10') !== false) {
                                $level_groups['M30'][$product_code] = $rows;
                            } else {
                                // Default group if no level matches
                                $level_groups['M10'][$product_code] = $rows;
                            }
                        }
                        
                        // Calculate column width based on number of level groups (max 3)
                        $col_width = 12 / min(3, count($level_groups));
                        
                        // Display regular data grouped by level
                        foreach ($level_groups as $level => $products) {
                            if (!empty($products)) {
                                ?>
                                <div class="col-lg-<?php echo $col_width; ?> col-md-<?php echo $col_width; ?> col-sm-12">
                                    <div class="card card-primary card-outline">
                                        <div class="card-header">
                                            <h3 class="card-title">
                                                <i class="fas fa-layer-group mr-2"></i>
                                                <?php echo htmlspecialchars($level); ?> Operations
                                            </h3>
                                            <div class="card-tools">
                                                <button type="button" class="btn btn-tool" data-card-widget="collapse">
                                                    <i class="fas fa-minus"></i>
                                                </button>
                                            </div>
                                        </div>
                                        <div class="card-body p-0">
                                            <div class="table-responsive">
                                                <table class="table table-hover table-striped">
                                                    <thead class="bg-lightblue">
                                                        <tr>
                                                            <th style="width: 30%">Product</th>
                                                            <th style="width: 40%">Operation</th>
                                                            <th style="width: 5%">Qty</th>
															<th style="width: 5%">Set</th>
                                                            <th style="width: 20%">Req Date</th>
                                                        </tr>
                                                    </thead>
                                                    <tbody>
                                                        <?php
														foreach ($products as $product_code => $rows) {
															foreach ($rows as $row) {
																$row_class = '';
																if (in_array($row['process_type'], [12, 21])) {
																	$row_class = 'class="bg-info"';
																} elseif ($row['process_type'] == 6) {
																	/* $row_class = 'class="bg-warning"';*/
																	$row_class = 'class=""';
																}

																$set_number = '';
																if ($row['set_id'] != 0) {
																	$set_number = utility::getTableFieldById("set_mangmnt", "set_number", "id", $row['set_id']);
																}

																echo '<tr ' . $row_class . '>
																	<td>' . htmlspecialchars($row['product_id']) . ' ' . htmlspecialchars($row['product_name']) . '</td>
																	<td>' . htmlspecialchars($row['operation_description']) . '</td>
																	<td>' . htmlspecialchars($row['quantity']) . '</td>
																	<td>' . htmlspecialchars($set_number) . '</td>
																	<td>' . htmlspecialchars($row['end_date']) . '</td>
																</tr>';
															}
														}
														?>

                                                    </tbody>
                                                </table>
                                            </div>
                                        </div>
                                     
                                    </div>
                                </div>
                                <?php
                            }
                        }
                        
                        // Display process type 4 data in a separate section at the bottom
                        if (!empty($process_type_4_data)) {
                            ?>
                            <div class="col-lg-12 col-md-12 col-sm-12 mt-4">
                                <div class="card card-danger card-outline">
                                    <div class="card-header">
                                        <h3 class="card-title">
                                            <i class="fas fa-boxes mr-2"></i>
                                            Raw Materials
                                        </h3>
                                        <div class="card-tools">
                                            <button type="button" class="btn btn-tool" data-card-widget="collapse">
                                                <i class="fas fa-minus"></i>
                                            </button>
                                        </div>
                                    </div>
                                    <div class="card-body p-0">
                                        <div class="table-responsive">
                                            <table class="table table-hover table-striped">
                                                <thead class="bg-pink">
                                                    <tr>
                                                        <th style="width: 30%">Product Code</th>
                                                        <th style="width: 30%">Material</th>
                                                        <th style="width: 20%">Qty</th>
                                                        <th style="width: 20%">Req Date</th>
                                                    </tr>
                                                </thead>
                                                <tbody>
                                                    <?php
                                                    foreach ($process_type_4_data as $product_code => $rows) {
                                                      
                                                        
                                                        foreach ($rows as $row) {
                                                            echo '<tr class="">
                                                                <td>' . htmlspecialchars($row['product_id']) . '</td>
                                                                <td>' . htmlspecialchars($row['product_name']) . ' - ' . htmlspecialchars($row['operation_description']) . '</td>
                                                                <td>' . htmlspecialchars($row['quantity']) . '</td>
                                                                <td>' . htmlspecialchars($row['required_date']) . '</td>
                                                            </tr>';
                                                        }
                                                    }
                                                    ?>
                                                </tbody>
                                            </table>
                                        </div>
                                    </div>
                                 
                                </div>
                            </div>
                            <?php
                        }
                    }
                    ?>
                </div>
            </div>
        </div>
    </div>
</section>

<style>
    .card {
        box-shadow: 0 4px 8px rgba(0,0,0,0.1);
        border-radius: 8px;
        margin-bottom: 20px;
    }
    .card-header {
        border-bottom: 1px solid rgba(0,0,0,0.1);
        border-top-left-radius: 8px !important;
        border-top-right-radius: 8px !important;
    }
    .card-title {
        font-weight: 600;
    }
    .bg-lightblue {
        background-color: #b550b0 !important;
    }
    .bg-pink {
        background-color: #b550b0 !important;
    }
    .table-hover tbody tr:hover {
        background-color: rgba(0,0,0,0.03);
    }
    .bg-gray {
        background-color: #f8f9fa !important;
    }
    .bg-gray-dark {
        background-color: #e9ecef !important;
    }
</style>

<script>
$(document).ready(function() {
    // Initialize card collapse/expand functionality
    $('[data-card-widget="collapse"]').click(function() {
        var card = $(this).closest('.card');
        card.toggleClass('collapsed-card');
    });
});
</script>