<?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 = "
    SELECT customer_reff, RefSalesCode
    FROM production_planning
    WHERE work_order_id = $work_order_id
";

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

$customer_reff  = '';
$RefSalesCode   = '';

if ($result && mysqli_num_rows($result) > 0) {
    // If multiple rows exist, this will take the last one
    while ($row = mysqli_fetch_assoc($result)) {
        $customer_reff = $row['customer_reff'];
        $RefSalesCode  = $row['RefSalesCode'];
    }
}
$query_manufacture_machine = "
    SELECT 
        mm.id AS manufacture_id,
        mm.work_order_id,
        mm.part_id,
        mm.machine_id,
        mm.end_date,
        mm.quantity,
        mm.product_name,
        mm.set_id,
        mm.total_hours,
        mm.in_scheduler_check,
        sd.resource_code,
        sd.machine_type,
        wo.operation_description,
        wo.process_type,
        won.work_order_name
    FROM manufacture_machine_table AS mm
    JOIN station_detail_table AS sd 
        ON sd.id = mm.machine_id
    LEFT JOIN work_order_detail AS wo 
        ON wo.product_id = mm.part_id 
       AND wo.work_order_id = mm.work_order_id
    LEFT JOIN work_order_name AS won
        ON won.part_id = mm.part_id
       AND won.work_order_id = mm.work_order_id
    WHERE mm.work_order_id = $work_order_id
    ORDER BY mm.part_id DESC
";


$rs_manufacture = mysqli_query($conn, $query_manufacture_machine);
$manufacture_data = [];
while ($row = mysqli_fetch_assoc($rs_manufacture)) {
    $manufacture_data[$row['part_id']][] = $row; // Group by part_id
}

// Count distinct part_ids
$distinct_no_of_operation = count($manufacture_data);

// Query for raw materials (process_type = 4) from work_order_detail
$query_raw_materials = "SELECT * FROM work_order_detail 
WHERE work_order_id = $work_order_id AND process_type = 4 
ORDER BY product_code DESC";

$rs_raw = mysqli_query($conn, $query_raw_materials);
$raw_materials_data = [];
while ($row = mysqli_fetch_assoc($rs_raw)) {
    $raw_materials_data[$row['product_code']][] = $row;
}
?>
<style>
.set-parts-cell:hover {
    background-color: #f8f9fa !important;
    cursor: pointer;
}

.set-parts-cell[data-set-id="0"] {
    cursor: default !important;
    text-decoration: none !important;
    color: inherit !important;
}

.bg-warning {
    background-color: #fff3cd !important;
}
</style>
<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">Part Number(s)</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">RefSalesCode</label>
						<div class="col-sm-8">
							<? echo $RefSalesCode; ?>
						</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 || !empty($raw_materials_data)) {
                        // Group manufacture data by machine type
                        $machine_type_groups = [
                            'M10' => [], // Machine type 1 or 4
                            'M20' => [], // Machine type 3
                            'M30' => []  // Machine type 2
                        ];
                        
                        foreach ($manufacture_data as $part_id => $rows) {
                            foreach ($rows as $row) {
                                $machine_type = $row['machine_type'];
                                
                                if ($machine_type == 1 || $machine_type == 4) {
                                    $machine_type_groups['M10'][$part_id][] = $row;
                                } elseif ($machine_type == 3) {
                                    $machine_type_groups['M20'][$part_id][] = $row;
                                } elseif ($machine_type == 2 || $machine_type == 5) {
                                    $machine_type_groups['M30'][$part_id][] = $row;
                                } else {
                                    // Default to M10 if machine type doesn't match any condition
                                    $machine_type_groups['M10'][$part_id][] = $row;
                                }
                            }
                        }
                        
                        // Calculate column width based on number of non-empty machine type groups
                        $non_empty_groups = array_filter($machine_type_groups, function($group) {
                            return !empty($group);
                        });
                        $group_count = count($non_empty_groups);
                        $col_width = $group_count > 0 ? 12 / min(3, $group_count) : 12;
                        
                        // Display machine type groups
                        foreach ($machine_type_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: 30%">WO</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 $part_id => $rows) {
    foreach ($rows as $row) {
        $row_class = '';
        if (isset($row['process_type']) && in_array($row['process_type'], [12, 21])) {
            $row_class = 'class="bg-info"';
        } elseif (isset($row['process_type']) && $row['process_type'] == 6) {
            $row_class = 'class=""';
        }

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

        $operation_desc = isset($row['operation_description']) ? $row['operation_description'] : 'N/A';
        
        echo '<tr ' . $row_class . '>
            <td class="set-parts-cell" 
                style="cursor: pointer; color: #007bff; text-decoration: underline;" 
                data-set-id="' . htmlspecialchars($set_id) . '" 
                data-part-id="' . htmlspecialchars($row['part_id']) . '"
                data-toggle="tooltip" title="Click to view all parts in this set">
                ' . htmlspecialchars($row['part_id']) . ' ' . htmlspecialchars($row['product_name']) . '
            </td>
            <td>' . htmlspecialchars($row['work_order_name']). '</td>
			<td>' . htmlspecialchars($operation_desc) . '</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 empty groups if no data exists
                   
                        
                        // Display raw materials data
                        if (!empty($raw_materials_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 ($raw_materials_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['required_date']) . '</td>
                                                            </tr>';
                                                        }
                                                    }
                                                    ?>
                                                </tbody>
                                            </table>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            <?php
                        }
                    } else {
                        echo '<div class="col-lg-12"><div class="alert alert-info text-center">No data found for this work order.</div></div>';
                    }
                    ?>
                </div>
            </div>
        </div>
    </div>
<div class="modal fade" id="setPartsModal" tabindex="-1" role="dialog" aria-labelledby="setPartsModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-lg" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="setPartsModalLabel">Set Parts Details</h5>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>
            <div class="modal-body">
                <div class="table-responsive">
                    <table class="table table-bordered table-striped">
                        <thead class="bg-lightblue">
                            <tr>
                                <th>Part Number</th>
                                <th style="width: 10%">Ratio</th>
                                <th style="width: 20%">Actual Qty</th>
                            </tr>
                        </thead>
                        <tbody id="setPartsTableBody">
                            <!-- AJAX content will be loaded here -->
                        </tbody>
                    </table>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
            </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');
    });

    // Initialize tooltips
    $('[data-toggle="tooltip"]').tooltip();

    // Click event for set parts cells
    $('.set-parts-cell').click(function() {
        var set_id = $(this).data('set-id');
        var part_id = $(this).data('part-id');
        var quantity = $(this).closest('tr').find('td:nth-child(4)').text().trim(); // Get quantity from 3rd column
		//alert(quantity);
        
        // Only show modal if it's actually a set (set_id != 0)
        if (set_id != 0) {
            fetchSetParts(set_id, part_id, quantity);
        }
    });

    function fetchSetParts(set_id, current_part_id, quantity) {
        // Show loading state
        $('#setPartsTableBody').html('<tr><td colspan="5" class="text-center">Loading...</td></tr>');
        $('#setPartsModal').modal('show');

        $.ajax({
            url: site_url + "/modules/machines_management/index.php?page=ajax_actions&action=ajax_get_set_parts",
            type: 'POST',
            data: {
                set_id: set_id,
                current_part_id: current_part_id,
                quantity: quantity
            },
            dataType: 'json',
            success: function(response) {
                if (response.success) {
                    var html = '';
                    if (response.data.length > 0) {
                        // Add header information about the calculation
                        html += '<tr class="bg-light">';
                        html += '<td colspan="5" class="text-center"><small>Based on Quantity: <strong>' + quantity + '</strong> × Ratio = Actual Quantity</small></td>';
                        html += '</tr>';
                        
                        response.data.forEach(function(part) {
                            html += '<td>' + (part.part_number !== 'N/A' ? part.part_number : '') + '</td>';
                            html += '<td class="text-center">' + part.ratio + '</td>';
                            html += '<td class="text-center"><strong>' + part.actual_quantity + '</strong>';
                            html += '<br><small class="text-muted">(' + quantity + ' × ' + part.ratio + ')</small></td>';
                            html += '</tr>';
                        });
                    } else {
                        html = '<tr><td colspan="5" class="text-center">No parts found in this set</td></tr>';
                    }
                    $('#setPartsTableBody').html(html);
                } else {
                    $('#setPartsTableBody').html('<tr><td colspan="5" class="text-center text-danger">Error: ' + response.message + '</td></tr>');
                }
            },
            error: function() {
                $('#setPartsTableBody').html('<tr><td colspan="5" class="text-center text-danger">Error loading set parts</td></tr>');
            }
        });
    }
});
</script>
<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>