<?php
session_start();
include "config.php"; 
echo "hiiiiiiiiiiii";
echo $machine_id =$_REQUEST['machine_id'];
$no_of_table = 4; 


$ordersByTable = [];
 $sql = $sql = "SELECT * 
        FROM pu_machine_table 
        WHERE finished = 0 
        ORDER BY table_id, priority ASC, start_date ASC";

$result = mysqli_query($conn, $sql);
while ($row = mysqli_fetch_assoc($result)) {
    $ordersByTable[$row['table_id']][] = $row;
}
//print_r($ordersByTable);
function getPartCount($conn, $workOrderId, $partId) {
    if (empty($workOrderId) || empty($partId)) {
        return ['ok' => 0, 'nok' => 0, 'quar' => 0];
    }

    $sql = "
        SELECT 
            SUM(CASE WHEN type = 'ok' THEN quantity ELSE 0 END) AS ok,
            SUM(CASE WHEN type = 'nok' THEN quantity ELSE 0 END) AS nok,
            SUM(CASE WHEN type = 'quarantine' THEN quantity ELSE 0 END) AS quar
        FROM part_count_log
        WHERE work_order_id = " . intval($workOrderId) . "
          AND part_id = " . intval($partId) . "
    ";

    $res = mysqli_query($conn, $sql);
    return mysqli_fetch_assoc($res) ?: ['ok' => 0, 'nok' => 0, 'quar' => 0];
}


function getMachineStatus($conn, $tableId, $machineId) {
    // Fetch the latest action for this machine
    $sql = "SELECT action_type 
            FROM machine_activity_log 
            WHERE machine_id = $machineId AND table_id = $tableId 
            ORDER BY created_at DESC 
            LIMIT 1";

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

    if ($result && mysqli_num_rows($result) > 0) {
        $row = mysqli_fetch_assoc($result);
        return $row['action_type']; // returns start, finish, pause, break, breakdown
    }

    return 'pause'; // default if no activity found
}


$reasonCodes = [];
$reasonSql = "SELECT * FROM reason_codes";
$reasonRes = mysqli_query($conn, $reasonSql);
while ($r = mysqli_fetch_assoc($reasonRes)) {
    $reasonCodes[] = $r;
}

// Prepare JS data structure
$tableOrdersJS = [];
$machineStatuses = [];
foreach ($ordersByTable as $tableId => $orders) {
    $tableOrdersJS[$tableId] = [];

    foreach ($orders as $order) {
        $machineStatuses[$tableId] = getMachineStatus($conn, $tableId, $order['machine_id']);
        
        $counts = getPartCount($conn, $order['work_order_id'], $order['part_id']);
        $tableOrdersJS[$tableId][] = [
            "part_id" => $order['part_id'],
            "machine_id" => $order['machine_id'],
            "product_name" => $order['product_name'],
            "qty_req" => $order['quantity'],
            "original_uph" => $order['quantity'] / $order['total_hours'], 
            "ok" => $counts['ok'],
            "nok" => $counts['nok'],
            "quar" => $counts['quar'],
            "work_order_id" => $order['work_order_id']
        ];
    }
}

?>

    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">
    <style>
        
        h2, h3 {
            margin: 10px 0;
        }

        .machine { 
            border: 3px solid green; 
            margin: 5px; 
            padding: 5px; 
            border-radius: 2px;
            position: relative;
        }

        .row { 
            display: flex; 
            justify-content: space-around; 
            align-items: center; 
            flex-wrap: wrap;
            margin: 10px 0; 
        }

        .box { 
            flex: 1; 
            padding: 20px; 
            margin: 5px; 
            border-radius: 8px;
            color: white; 
            font-weight: bold; 
            font-size: 20px; /* bigger for touch */
            min-width: 120px; 
            cursor: pointer;
        }

        .ok { background: green; }
        .nok { background: red; }
        .quar { background: orange; }
        .pause { background: darkred; }
        .finished { background: lightblue; }
        .details { background: purple; }

        .footer { 
            display: flex; 
            justify-content: center; 
            flex-wrap: wrap;
            margin: 20px 0; 
        }

        .footer button { 
            padding: 20px 30px; 
            margin: 8px; 
            font-size: 20px; 
            font-weight: bold; 
            border-radius: 10px;
            cursor: pointer; 
        }

        .pauseall { background: red; color: white; }
        .schedule { background: grey; color: white; }
        .breakdown { background: darkred; color: white; }

        .order-controls {
            position: absolute;
            top: 15px;
            right: 15px;
            display: flex;
            gap: 10px;
        }
        
        .order-control {
            background: #f0f0f0;
            border: 1px solid #ccc;
            border-radius: 5px;
            padding: 8px;
            cursor: pointer;
            font-size: 18px;
            width: 40px;
            height: 40px;
            display: flex;
            align-items: center;
            justify-content: center;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
        }
        
        .order-control:hover {
            background: #e0e0e0;
        }

        .count-controls {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin: 5px 0;
            background: white;
            border-radius: 5px;
            padding: 5px;
        }
        
        .count-btn {
            flex: 1;
            padding: 10px;
            margin: 0 2px;
            border: none;
            border-radius: 5px;
            color: white;
            font-weight: bold;
            cursor: pointer;
        }
        
        .increment-btn.ok { background: green; }
        .increment-btn.nok { background: red; }
        .increment-btn.quar { background: orange; }
        
        .decrement-btn {
            background: #6c757d;
            color: white;
        }
        
        .count-input {
            width: 60px;
            text-align: center;
            margin: 0 5px;
            font-weight: bold;
            border: 1px solid #ccc;
            border-radius: 5px;
            padding: 5px;
        }
        
        .start { background: blue; color: white; }
        .pause { background: darkred; color: white; }
        .finished { background: lightblue; color: black; }
        

    </style>

	<div class="header" style="display:flex; justify-content:space-between; align-items:center;">
		<h2 style="margin:0;">CNC Dashboard</h2>
		<div id="clock" style="
			font-family: monospace;
			font-size: 18px;
			color: #2575fc;
			padding: 4px 10px;
			border-radius: 6px;
			background-color: #f0f0f0;
			text-align: center;
			min-width: 80px;
		">00:00:00</div>
	</div>




<?php for ($t=1; $t <= $no_of_table; $t++): ?>
    <h6>Table <?= $t ?></h6>
    <div class="machine" id="table-<?= $t ?>">
	        <?php if (!empty($tableOrdersJS[$t])): 
            $first = $tableOrdersJS[$t][0]; 
            $machineStatus = $machineStatuses[$t];
		    $machineStatus;
            ?>
       
            <?php if (count($tableOrdersJS[$t]) > 1): ?>
               <!-- <div class="order-controls">
                    <div class="order-control" title="Show First Order" onclick="showFirstOrder(<?= $t ?>)">
                        <i class="fa fa-undo"></i>
                    </div>
                    <div class="order-control" title="Next Order" onclick="showNextOrder(<?= $t ?>)">
                        <i class="fas fa-forward"></i>
                    </div>
                </div>-->
            <?php endif; ?>
            
          <strong>   <div class="row">
               Table <?= $t ?> |
                <span class="hide">Part No : <span class="part"><? echo $first["part_id"] ?></span></span>   
				<span>Part No : <span class="part_name"><? echo $first["product_name"] ?></span></span> |
                <span>QTY Req : <span class="qty"><?= $first["qty_req"] ?></span></span> |
                <span>QTY Good : <span class="qtygood"><?= $first["ok"] ?></span></span>
            </div></strong>
            
           
           <div class="row text-center">
				<div class="col">
					<button type="button" class="btn btn-success w-100 increment-btn mb-2 py-3" data-type="ok" data-table="<?= $t ?>">OK</button>

					<div class="row g-2">
						<div class="col-6">
							<input type="number" class="form-control text-center ok-count h-100" value="<?= $first['ok'] ?>" readonly>
						</div>
						<div class="col-6">
							<button type="button" class="btn btn-outline-secondary w-100 h-100 decrement-btn" data-type="ok" data-table="<?= $t ?>">Undo</button>
						</div>
					</div>
				</div>

				<div class="col">
					<button type="button" class="btn btn-danger w-100 increment-btn mb-2 py-3" data-type="nok" data-table="<?= $t ?>">NOK</button>
					<div class="row g-2">
						<div class="col-6">
							<input type="number" class="form-control text-center nok-count h-100" value="<?= $first['nok'] ?>" readonly>
						</div>
						<div class="col-6">
							<button type="button" class="btn btn-outline-secondary w-100 h-100 decrement-btn" data-type="nok" data-table="<?= $t ?>">Undo</button>
						</div>
					</div>
				</div>

				<div class="col">
					<button type="button" class="btn btn-warning w-100 increment-btn mb-2 py-3" data-type="quarantine" data-table="<?= $t ?>">QUAR</button>
					<div class="row g-2">
						<div class="col-6">
							<input type="number" class="form-control text-center quar-count h-100" value="<?= $first['quar'] ?>" readonly>
						</div>
						<div class="col-6">
							<button type="button" class="btn btn-outline-secondary w-100 h-100 decrement-btn" data-type="quarantine" data-table="<?= $t ?>">Undo</button>
						</div>
					</div>
				</div>

				<div class="col d-flex flex-row gap-3">
    <div class="btn <?= $machineStatus === 'pause' ? 'btn-success' : 'btn-warning' ?> flex-fill py-5 machine-action" 
         data-table="<?= $t ?>" 
         data-action="<?= $machineStatus === 'pause' ? 'pause' : 'start' ?>">
        <?= $machineStatus === 'pause' ? 'Start' : 'Pause' ?>
    </div>
	
    <div class="btn btn-primary flex-fill py-5 finish-btn" data-table="<?= $t ?>">Finished</div>
    <div class="btn btn-dark flex-fill py-5">Details</div>
</div>





           </div>


        <?php else: ?>
					<p>No orders scheduled for Table <?= $t ?></p>
				<?php endif; ?>
			</div>
		<?php endfor; ?>

		<div class="footer">
			<button class="pauseall">Pause All</button>
			<button class="schedule">Schedule Break</button>
			<!--<button class="breakdown">Machine Breakdown</button>-->
			 <div class="col-md-6 mb-2">
                                            <button id="breakdownBtn" class="btn btn-danger w-100 py-3">
                                                <i class="fas fa-exclamation-triangle mr-2"></i> Machine<br>Breakdown
                                            </button>
                                        </div>
			                        <div class="modal fade" id="breakdownModal" tabindex="-1" role="dialog" aria-hidden="true">
                            <div class="modal-dialog modal-dialog-centered" role="document">
                                <div class="modal-content">
                                    <div class="modal-header bg-danger text-white">
                                        <h5 class="modal-title"><i class="fas fa-tools mr-2"></i>Select Breakdown Reason</h5>
                                        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                                    </div>
                                    <div class="modal-body">
                                        <?php 
                                        echo Keycode::getKeycodeListValue(
                                            "breakdown_reason",
                                            $breakdown_reason,
                                            "100%",
                                            "Please Select",
                                            "id",
                                            "code",
                                            "breakdown_reason",
                                            "",
                                            "form-control",
                                            false,
                                            "required"
                                        ); 
                                        ?>
                                    </div>
                                    <div class="modal-footer">
                                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                                        <button type="button" class="btn btn-danger" id="submitBreakdown">Submit</button>
                                    </div>
                                </div>
                            </div>
                        </div>
		</div>

<!-- Reason Selection Modal -->
    <div class="modal fade" id="reasonModal" tabindex="-1" role="dialog" aria-hidden="true">
        <div class="modal-dialog modal-lg modal-dialog-centered">
            <div class="modal-content">
                <div class="modal-header bg-danger text-white">
                    <h5 class="modal-title"><i class="fas fa-exclamation-circle mr-2"></i>Select Reason</h5>
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                        <span aria-hidden="true">&times;</span>
                    </button>
                </div>
                <div class="modal-body">
                    <!-- Reason Codes -->
                    <h6 class="mb-3">Select Reason</h6>
                    <div id="reasonSelection" style="max-height: 200px; overflow-y: auto;">
                        <?php
                        $reasonSql = "SELECT * FROM reason_codes";
                        $reasonRes = $conn->query($reasonSql);
                        while ($r = $reasonRes->fetch_assoc()): ?>
                            <div class="form-check mb-2">
                                <input class="form-check-input reason-radio" type="radio" name="reason_id" value="<?= $r['id'] ?>" id="reason<?= $r['id'] ?>">
                                <label class="form-check-label" for="reason<?= $r['id'] ?>">
                                    <?= htmlspecialchars($r['reason_name']); ?>
                                </label>
                            </div>
                        <?php endwhile; ?>
                    </div>
                </div>
                <div class="modal-footer">
                    <button class="btn btn-secondary" id="backToParts">Back</button>
                    <button class="btn btn-danger" id="submitNok">Submit</button>
                </div>
            </div>
        </div>
    </div>


<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"></script>
<script>
   function updateClock() {
        const now = new Date();
        const hours = String(now.getHours()).padStart(2, '0');
        const minutes = String(now.getMinutes()).padStart(2, '0');
        const seconds = String(now.getSeconds()).padStart(2, '0');
        document.getElementById('clock').textContent = `${hours}:${minutes}:${seconds}`;
    }
   
    updateClock();
    setInterval(updateClock, 1000);
let ordersByTable = <?php echo json_encode($tableOrdersJS); ?>;
let currentIndex = {};
for (let t in ordersByTable) currentIndex[t] = 0;

// Variables for modal handling
let currentTableId = null;
let currentCountType = null;
let selectedParts = [];

function showNextOrder(tableId) {
    let orders = ordersByTable[tableId];
    if (!orders || orders.length === 0) return;

    currentIndex[tableId] = (currentIndex[tableId] + 1) % orders.length;
    updateOrderDisplay(tableId);
}

function showFirstOrder(tableId) {
    let orders = ordersByTable[tableId];
    if (!orders || orders.length === 0) return;

    currentIndex[tableId] = 0;
    updateOrderDisplay(tableId);
}

function updateOrderDisplay(tableId) {
    let orders = ordersByTable[tableId];
    let order = orders[currentIndex[tableId]];
    
    let container = document.getElementById("table-" + tableId);
    container.querySelector(".part").innerText = order.part_id;
	container.querySelector(".part_name").innerText = order.product_name;
    container.querySelector(".qty").innerText = order.qty_req;
    container.querySelector(".qtygood").innerText = order.ok;
    container.querySelector(".ok-count").value = order.ok;
    container.querySelector(".nok-count").value = order.nok;
    container.querySelector(".quar-count").value = order.quar;
}

$(document).on("click", ".machine-action", function() {
    const tableId = $(this).data("table");
    const currentAction = $(this).data("action");
    const newAction = currentAction === 'start' ? 'pause' : 'start';
	//alert(newAction);
    
    const orders = ordersByTable[tableId];
	//alert(tableId);
    const currentOrderIndex = currentIndex[tableId];
    const workOrderId = orders[currentOrderIndex].work_order_id;
    const partId = orders[currentOrderIndex].part_id;
	const machineId = orders[currentOrderIndex].machine_id;
	//alert(machineId);
    
    $.ajax({
        url: site_url + "/modules/machine_tab/index.php?page=ajax_actions&action=log_action_pu",
        method: "POST",
        data: {
            machine_id: machineId, 
			work_order_id: workOrderId, 
			tableId: tableId,
            part_id: partId,
            action_type: newAction
        },
        dataType: "json",
        success: function(response) {
            if (response.success) {
                const button = $(`#table-${tableId} .machine-action`);
                button.removeClass('start pause').addClass(newAction);
                button.text(newAction.charAt(0).toUpperCase() + newAction.slice(1));
                button.data("action", newAction);
                
                //machineStatuses[tableId] = newAction === 'start' ? 'stopped' : 'running';
				location.reload();
            } else {
                alert("Error: " + response.message);
            }
        },
        error: function(xhr, status, error) {
            alert("AJAX Error: " + error);
        }
    });
});
$(document).on("click", ".finish-btn", function() {
    const tableId = $(this).data("table");
    
    const orders = ordersByTable[tableId];
    const currentOrderIndex = currentIndex[tableId];
	alert(currentOrderIndex);
    const workOrderId = orders[currentOrderIndex].work_order_id;
    const partId = orders[currentOrderIndex].part_id;
    
    if (confirm("Are you sure you want to mark this order as finished?")) {
        $.ajax({
          url: site_url + "/modules/machine_tab/index.php?page=ajax_actions&action=log_action_pu",
            method: "POST",
            data: {
                work_order_id: workOrderId,
                part_id: partId,
                action_type: "finish"
            },
            dataType: "json",
            success: function(response) {
                if (response.success) {
                    alert("Order marked as finished!");
                    // Move to next order if available
                    if (orders.length > 1) {
                        showNextOrder(tableId);
                    }
                } else {
                    alert("Error: " + response.message);
                }
            },
            error: function(xhr, status, error) {
                alert("AJAX Error: " + error);
            }
        });
    }
});
// Increment button click
$(document).on("click", ".increment-btn", function() {
    const type = $(this).data("type");
    const tableId = $(this).data("table");
    currentTableId = tableId;
    currentCountType = type;
    
    const orders = ordersByTable[tableId];
    const currentOrderIndex = currentIndex[tableId];
    const workOrderId = orders[currentOrderIndex].work_order_id;
    const partId = orders[currentOrderIndex].part_id;
	//alert(partId);
    
    if (type === "ok") {
        // For OK, just increment without showing modals
        $.ajax({
			url: site_url + "/modules/machine_tab/index.php?page=ajax_actions&action=log_count",
            //url: "ajax_actions.php",
            method: "POST",
            data: {
                action: "log_count",
                work_order_id: workOrderId,
                part_id: partId,
                type: type,
                quantity: 1
            },
            dataType: "json",
            success: function(response) {
                if (response.success) {
                    // Update the count display
                    const currentCount = parseInt($(`#table-${tableId} .${type}-count`).val());
                    $(`#table-${tableId} .${type}-count`).val(currentCount + 1);
                    
                    // Update the data structure
                    ordersByTable[tableId][currentOrderIndex][type] = currentCount + 1;
                    
                    // Update total good count
                    $(`#table-${tableId} .qtygood`).text(ordersByTable[tableId][currentOrderIndex].ok);
                    
                    // Check if work order is completed
                    checkWorkOrderCompletion(tableId);
                } else {
                    alert("Error: " + response.message);
                }
            },
            error: function(xhr, status, error) {
                alert("AJAX Error: " + error);
            }
        });
    } else {
        // For NOK and Quarantine, show reason modal
        $("#reasonModal").modal("show");
    }
});

// Decrement button click
$(document).on("click", ".decrement-btn", function() {
    const type = $(this).data("type");
    const tableId = $(this).data("table");
    
    const orders = ordersByTable[tableId];
    const currentOrderIndex = currentIndex[tableId];
    const workOrderId = orders[currentOrderIndex].work_order_id;
    const partId = orders[currentOrderIndex].part_id;
    
    const currentCount = parseInt($(`#table-${tableId} .${type}-count`).val());
    
    if (currentCount <= 0) {
        alert("Count cannot be negative.");
        return;
    }
    
    if (confirm("Are you sure you want to decrement the " + type.toUpperCase() + " count?")) {
        $.ajax({
            url: site_url + "/modules/machine_tab/index.php?page=ajax_actions&action=log_count",
            method: "POST",
            data: {
                work_order_id: workOrderId,
                part_id: partId,
                type: type,
                quantity: -1
            },
            dataType: "json",
            success: function(response) {
                if (response.success) {
                    // Update the count display
                    $(`#table-${tableId} .${type}-count`).val(currentCount - 1);
                    
                    // Update the data structure
                    ordersByTable[tableId][currentOrderIndex][type] = currentCount - 1;
                    
                    // Update total good count for OK
                    if (type === "ok") {
                        $(`#table-${tableId} .qtygood`).text(ordersByTable[tableId][currentOrderIndex].ok);
                    }
                } else {
                    alert("Error: " + response.message);
                }
            },
            error: function(xhr, status, error) {
                alert("AJAX Error: " + error);
            }
        });
    }
});

// Submit NOK / Quarantine log
$("#submitNok").click(function() {
    let reason = $(".reason-radio:checked").val();

    if (!reason) {
        alert("⚠ Please select a reason.");
        return;
    }

    const tableId = currentTableId;
    const type = currentCountType;
    const orders = ordersByTable[tableId];
    const currentOrderIndex = currentIndex[tableId];
    const workOrderId = orders[currentOrderIndex].work_order_id;
    const partId = orders[currentOrderIndex].part_id;

    $.ajax({
        url: site_url + "/modules/machine_tab/index.php?page=ajax_actions&action=log_count",
        method: "POST",
        data: {
            work_order_id: workOrderId,
            part_id: partId,
            reason_id: reason,
			part_ids: selectedParts.join(","),
            type: type,
            quantity: 1
        },
        dataType: "json",
        success: function(response) {
            if (response.success) {
                $("#reasonModal").modal("hide");
                
                // Update the count display
                const currentCount = parseInt($(`#table-${tableId} .${type}-count`).val());
                $(`#table-${tableId} .${type}-count`).val(currentCount + 1);
                
                // Update the data structure
                ordersByTable[tableId][currentOrderIndex][type] = currentCount + 1;
                
                // Reset modal selections
                $(".reason-radio").prop("checked", false);
            } else {
                alert("Error: " + response.message);
            }
        },
        error: function(xhr, status, error) {
            alert("AJAX Error: " + error);
        }
    });
});
  $("#breakdownBtn").click(function () {
		//alert("hii");
        $("#breakdownModal").modal("show");
    });
	    $("#submitBreakdown").click(function () {
        let reason = $("#breakdown_reason").val();
		//alert(reason);
        if (!reason) {
            alert("⚠ Please select a breakdown reason.");
            return;
        }


        if (confirm("Are you sure you want to log this breakdown?")) {
            $.ajax({
                url: site_url + "/modules/machine_tab/index.php?page=ajax_actions&action=log_action_pu",
                method: "POST",
                data: {
                    action_type: "breakdown",
                    breakdown_reason: reason
                },
                dataType: "json",
                success: function (response) {
                    if (response.success) {
                        $("#breakdownModal").modal("hide");
                        location.reload();
                    } else {
                        alert("Error: " + response.message);
                    }
                },
                error: function (xhr, status, error) {
                    alert("AJAX Error: " + error);
                }
            });
        }
    });
// Check if work order is completed
function checkWorkOrderCompletion(tableId) {
    const orders = ordersByTable[tableId];
    const currentOrderIndex = currentIndex[tableId];
    const totalMade = orders[currentOrderIndex].ok;
    const plannedQuantity = orders[currentOrderIndex].qty_req;
    
    if (totalMade >= plannedQuantity) {
		alert("Work order completed! Total made: " + totalMade);
        // Log finish action
        /*$.ajax({
            url: "ajax_actions.php",
            method: "POST",
            data: {
                action: "log_action",
                work_order_id: orders[currentOrderIndex].work_order_id,
                action_type: "finish"
            },
            dataType: "json",
            success: function(response) {
                if (response.success) {
                    // Show completion message
                    alert("Work order completed! Total made: " + totalMade);
                    
                    // Move to next order if available
                    if (orders.length > 1) {
                        showNextOrder(tableId);
                    }
                } else {
                    alert("Error logging finish action: " + response.message);
                }
            },
            error: function(xhr, status, error) {
                alert("AJAX Error: " + error);
            }
        });*/
    }
}


for (let t in ordersByTable) {
    updateOrderDisplay(t);
}
</script>

