<?php
session_start();
include "config.php"; 
//echo $frontEndURL;
if (!isset($_SESSION['engineer_id']) || !isset($_SESSION['machine_id'])) {
    die("Unauthorized access!");
}
// Get server timestamp for JavaScript
$serverTime = date('Y-m-d H:i:s');
$serverTimestamp = time() * 1000; // milliseconds for JS
$machine_id = intval($_SESSION['machine_id']);
$engineer_id = intval($_SESSION['engineer_id']);
$today = date('Y-m-d');
$cncMachineTableId = isset($_GET['cnc_id']) ? intval($_GET['cnc_id']) : null;
$table_id = isset($_GET['table_id']) ? intval($_GET['table_id']) : 1;
$no_of_table = 2; // Number of tables per machine

// Fetch all orders grouped by table
$ordersByTable = [];
$sql = "SELECT 
        v.id,
        v.part_id,
        v.table_id,
        v.machine_id,
        v.work_order_id,
        v.product_name,
        v.start_date,
        v.quantity,
        v.total_hours,
        v.set_id,
        v.priority,
        v.end_date,
        v.is_break,
        v.finished,
        c.start_time AS changeover_start,
        c.end_time AS changeover_end,
        c.duration_seconds
        FROM cnc_machine_table v
        LEFT JOIN cnc_machine_changeover c
            ON c.work_order_table_id = v.id
            AND c.machine_id = v.machine_id
        WHERE v.machine_id = $machine_id
        AND v.is_break = 0 
        AND v.finished = 0
        ORDER BY v.table_id, v.priority ASC, v.start_date ASC";

$result = mysqli_query($conn, $sql);
while ($row = mysqli_fetch_assoc($result)) {
    // Default part name
    $partDisplay = $row['product_name'];
    $partNumbers = [];

    // If it's part of a set, fetch all related part numbers
    if (!empty($row['set_id']) && $row['set_id'] != 0) {
        $mapSql = "SELECT part_id FROM set_mangmnt_mapping WHERE set_id = " . intval($row['set_id']);
        $mapRes = $conn->query($mapSql);
        $parts = [];

        while ($mapRow = $mapRes->fetch_assoc()) {
            $parts[] = $mapRow['part_id'];
        }

        if (!empty($parts)) {
            $partIds = implode(",", $parts);

            $itemSql = "SELECT id, part_number FROM item_management WHERE id IN ($partIds)";
            $itemRes = $conn->query($itemSql);

            $partNumbers = [];
            while ($itemRow = $itemRes->fetch_assoc()) {
                $partNumbers[] = [
                    'id' => $itemRow['id'],
                    'part_number' => $itemRow['part_number']
                ];
            }

            $partDisplay = implode(", ", array_column($partNumbers, 'part_number'));
        }
    }

    // Get document_upload based on set_id or part_id
    $document_upload = "";
    $document_dir = "../admin/route_documents/";

    if (!empty($row['set_id']) && $row['set_id'] != 0) {
        $docSql = "SELECT document_upload FROM set_route_details WHERE set_id = '" . $row['set_id'] . "'";
        $document_dir = "../admin/set_route_documents/";
    } else {
        $docSql = "SELECT document_upload FROM route_details WHERE item_id = '" . $row['part_id'] . "'";
    }

    $docResult = mysqli_query($conn, $docSql);
    if ($docResult && mysqli_num_rows($docResult) > 0) {
        $docRow = mysqli_fetch_assoc($docResult);
        $document_upload = $docRow['document_upload'];
    }

    $row['document_upload'] = $document_upload;
    $row['document_dir'] = $document_dir;
    $row['product_name'] = $partDisplay;
    $row['part_numbers'] = $partNumbers;

    $ordersByTable[$row['table_id']][] = $row;
}

function getTotalCounts($conn, $workOrderId, $partId, $cncMachineTableId, $type, $isSet = false) {
    $workOrderId = intval($workOrderId);
    $partId      = intval($partId);
    $type        = $conn->real_escape_string($type);

    $sql = "SELECT SUM(quantity) AS total 
            FROM cnc_part_count_log
            WHERE work_order_id = $workOrderId
            AND cnc_machine_table_id = $cncMachineTableId
            AND part_id = $partId
            AND type = '$type'";

    $result = $conn->query($sql);

    if (!$result) {
        return "SQL ERROR: " . $conn->error;
    }

    $row = $result->fetch_assoc();
    return $row['total'] ? $row['total'] : 0;
}

function getMachineStatus($conn, $tableId, $machineId, $workOrderId, $partId, $cncMachineTableId) {

    $sql = "SELECT action_type 
            FROM cnc_machine_activity_log 
            WHERE work_order_id = $workOrderId 
            AND part_id = $partId
            AND machine_id = $machineId 
            AND table_id = $tableId 
            AND cnc_machine_table_id = $cncMachineTableId
            ORDER BY created_at DESC 
            LIMIT 1";

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

    if ($result && mysqli_num_rows($result) > 0) {
        $row = mysqli_fetch_assoc($result);

        // ✅ check if empty OR null
        if (!empty($row['action_type'])) {
            return $row['action_type'];
        }
    }

    // ✅ default case (no record OR empty action_type)
    return 'pause';
}

function calculateAndStoreActualUPH($conn, $workOrderId, $partId, $machine_id, $cncMachineTableId, $isSet = false) {
    $countSql = "
        SELECT SUM(quantity) AS total
        FROM cnc_part_count_log
        WHERE work_order_id = $workOrderId
        AND cnc_machine_table_id = $cncMachineTableId
        AND part_id = $partId
        AND type = 'ok'
    ";

    $countResult = $conn->query($countSql);
    $countRow = $countResult->fetch_assoc();

    $okCount   = $countRow['total'] ?? 0;
    $totalMade = $okCount;

    // Get activity timestamps
    $activitySql = "SELECT 
                    MIN(CASE WHEN action_type = 'start' THEN created_at END) as first_start,
                    MAX(CASE WHEN action_type = 'finish' THEN created_at END) as last_finish
                    FROM cnc_machine_activity_log 
                    WHERE work_order_id = $workOrderId 
                    AND cnc_machine_table_id = $cncMachineTableId
                    AND part_id = '$partId'";
    $activityRes = $conn->query($activitySql);
    
    $actualUph = 0;
    
    if ($activityRes && $activityRes->num_rows > 0) {
        $activityRow = $activityRes->fetch_assoc();
        $firstStart = $activityRow['first_start'];
        $lastFinish = $activityRow['last_finish'];
        
        if ($firstStart) {
            if ($lastFinish) {
                $startTime = strtotime($firstStart);
                $finishTime = strtotime($lastFinish);
                $totalSeconds = $finishTime - $startTime;
            } else {
                $startTime = strtotime($firstStart);
                $totalSeconds = time() - $startTime;
            }
            
            // Calculate non-productive time
            $nonProductiveSql = "
                SELECT action_type, created_at 
                FROM cnc_machine_activity_log 
                WHERE work_order_id = $workOrderId 
                AND cnc_machine_table_id = $cncMachineTableId
                AND part_id = '$partId'
                AND action_type IN ('start', 'pause', 'break', 'breakdown')
                ORDER BY created_at ASC
            ";
            
            $nonProdRes = $conn->query($nonProductiveSql);
            $nonProductiveSeconds = 0;
            $lastPauseStart = null;
            
            if ($nonProdRes && $nonProdRes->num_rows > 0) {
                while ($row = $nonProdRes->fetch_assoc()) {
                    $actionType = $row['action_type'];
                    $timestamp = strtotime($row['created_at']);
                    
                    if (in_array($actionType, ['pause', 'break', 'breakdown'])) {
                        $lastPauseStart = $timestamp;
                    }
                    else if ($actionType === 'start' && $lastPauseStart !== null) {
                        $pauseDuration = $timestamp - $lastPauseStart;
                        $nonProductiveSeconds += $pauseDuration;
                        $lastPauseStart = null;
                    }
                }
                
                if ($lastPauseStart !== null) {
                    $endPoint = $lastFinish ? strtotime($lastFinish) : time();
                    $pauseDuration = $endPoint - $lastPauseStart;
                    $nonProductiveSeconds += $pauseDuration;
                }
            }
            
            $productiveSeconds = $totalSeconds - $nonProductiveSeconds;
            $totalHours = max(0, $productiveSeconds) / 3600;
            
            $actualUph = ($totalHours > 0) ? round($totalMade / $totalHours, 2) : 0;
        }
    }

    $checkSql = "SELECT id FROM cnc_part_count_log 
                 WHERE work_order_id = $workOrderId 
                 AND cnc_machine_table_id = $cncMachineTableId
                 AND part_id = '$partId' 
                 LIMIT 1";
    $checkResult = $conn->query($checkSql);
    
    if ($checkResult->num_rows > 0) {
        $updateUphSql = "UPDATE cnc_part_count_log 
                        SET uph = $actualUph 
                        WHERE work_order_id = $workOrderId 
                        AND cnc_machine_table_id = $cncMachineTableId
                        AND part_id = '$partId'";
        
        if (!mysqli_query($conn, $updateUphSql)) {
            error_log("Failed to update UPH: " . mysqli_error($conn));
        }
    }
    
    return $actualUph;
}

function getPartNumbersFromSet($conn, $setId, $partId) {
    $partNumbers = [];
    
    if (!empty($setId) && $setId != 0) {
        $mapSql = "SELECT part_id FROM set_mangmnt_mapping WHERE set_id = " . intval($setId);
        $mapRes = $conn->query($mapSql);
        
        while ($mapRow = $mapRes->fetch_assoc()) {
            $partNumbers[] = $mapRow['part_id'];
        }
    } else {
        $partNumbers[] = $partId;
    }
    
    if (!empty($partNumbers)) {
        $partIds = implode(",", $partNumbers);
        $itemSql = "SELECT id, part_number FROM item_management WHERE id IN ($partIds)";
        $itemRes = $conn->query($itemSql);
        
        $result = [];
        while ($itemRow = $itemRes->fetch_assoc()) {
            $result[] = [
                'id' => $itemRow['id'],
                'part_number' => $itemRow['part_number']
            ];
        }
        return $result;
    }
    
    return [];
}

function getShiftForDatetime($shiftsByDay, $datetime) {
    $dayOfWeek = (int)date('N', strtotime($datetime));
    $timeOfDay = date('H:i:s', strtotime($datetime));

    if (!isset($shiftsByDay[$dayOfWeek])) return null;

    foreach ($shiftsByDay[$dayOfWeek] as $shift) {
        $shiftStart = $shift['start_time']; 
        $shiftEnd   = $shift['end_time'];  

        if ($shiftStart <= $shiftEnd) {
            if ($timeOfDay >= $shiftStart && $timeOfDay < $shiftEnd) {
                return $shift['id'];
            }
        } else {
            if ($timeOfDay >= $shiftStart || $timeOfDay < $shiftEnd) {
                return $shift['id'];
            }
        }
    }
    return null;
}

function getShiftStartDate($shiftsByDay, $datetime) {
    $dayOfWeek = (int)date('N', strtotime($datetime)); 
    $timeOfDay = date('H:i:s', strtotime($datetime));
    $date      = date('Y-m-d', strtotime($datetime));

    if (!isset($shiftsByDay[$dayOfWeek])) return $date;

    foreach ($shiftsByDay[$dayOfWeek] as $shift) {
        $shiftStart = $shift['start_time'];
        $shiftEnd   = $shift['end_time'];   

        if ($shiftStart > $shiftEnd && $timeOfDay < $shiftEnd) {
            return date('Y-m-d', strtotime($date . ' -1 day'));
        }
    }

    return $date;
}

// Prepare data for JavaScript
$tableOrdersJS = [];
$machineStatuses = [];
$tableBorders = [];
$firstOffSignedByTable = [];

foreach ($ordersByTable as $tableId => $orders) {
    $tableOrdersJS[$tableId] = [];

    foreach ($orders as $order) {
        $currentStatus = getMachineStatus(
            $conn, 
            $tableId, 
            $order['machine_id'],
            $order['work_order_id'],
            $order['part_id'], 
			$order['id']
        );
        
        $order['machine_status'] = $currentStatus;
        $setId = isset($order['set_id']) ? intval($order['set_id']) : 0;
        $isSet = (!empty($setId) && $setId != 0);
        
        $okCount = getTotalCounts($conn, $order['work_order_id'], $order['part_id'], $order['id'], 'ok', $isSet);
        $nokCount = getTotalCounts($conn, $order['work_order_id'], $order['part_id'], $order['id'], 'nok', $isSet);
        $quarantineCount = getTotalCounts($conn, $order['work_order_id'], $order['part_id'], $order['id'], 'quarantine', $isSet);
        
        $actualUph = calculateAndStoreActualUPH(
            $conn,
            $order['work_order_id'],
            $order['part_id'],
            $order['machine_id'],
            $order['id'],
            $isSet
        );
        
        $originalUph = ($order['total_hours'] > 0) 
            ? round($order['quantity'] / $order['total_hours'], 2) 
            : 0;
        
        $borderColor = "green";
        if ($originalUph > 0 && $actualUph > 0) {
            $borderColor = ($actualUph >= $originalUph) ? "green" : "red";
        }
        
        $tableBorders[$tableId] = $borderColor;
        
        // Check First-Off Sign-Off for this order
        $checkFirstOff = "
            SELECT id, signed_at FROM cnc_first_off_signoff
            WHERE work_order_id = {$order['work_order_id']}
            AND part_id = {$order['part_id']}
            AND cnc_machine_table_id = {$order['id']}
            LIMIT 1
        ";
        
        $firstOffRes = mysqli_query($conn, $checkFirstOff);
        $firstOffSigned = false;
        
        if ($firstOffRes && mysqli_num_rows($firstOffRes) > 0) {
            $firstOffRow = mysqli_fetch_assoc($firstOffRes);
            $signedAt = $firstOffRow['signed_at'];

            // Load all shifts grouped by day
            $shiftsByDay = [];
            $shiftResult = mysqli_query($conn, "SELECT * FROM working_hours");
            while ($shiftRow = mysqli_fetch_assoc($shiftResult)) {
                $day = (int)$shiftRow['day_shifts'];
                $shiftsByDay[$day][] = $shiftRow;
            }

            $shiftAtSignOff = getShiftForDatetime($shiftsByDay, $signedAt);
            $shiftNow = getShiftForDatetime($shiftsByDay, date('Y-m-d H:i:s'));
            $shiftStartDateAtSignOff = getShiftStartDate($shiftsByDay, $signedAt);
            $shiftStartDateNow = getShiftStartDate($shiftsByDay, date('Y-m-d H:i:s'));

            if (
                $shiftAtSignOff !== null &&
                $shiftNow !== null &&
                $shiftAtSignOff === $shiftNow &&
                $shiftStartDateAtSignOff === $shiftStartDateNow
            ) {
                $firstOffSigned = true;
            }
        }
        
        $firstOffSignedByTable[$tableId] = $firstOffSigned;

        $tableOrdersJS[$tableId][] = [
            "id" => $order['id'],
            "part_id" => $order['part_id'],
            "set_id" => $order['set_id'],
            "machine_id" => $order['machine_id'],
            "document_upload" => $order['document_upload'],
            "document_dir"    => $order['document_dir'],
            "product_name" => $order['product_name'],
            "qty_req" => $order['quantity'],
            "original_uph" => $originalUph,
            "ok" => $okCount,
            "nok" => $nokCount,
            "quar" => $quarantineCount,
            "work_order_id" => $order['work_order_id'],
            "actual_uph" => $actualUph,
            "border" => $borderColor,
            "part_numbers" => $order['part_numbers'],
            "start_date" => $order['start_date'],
            "end_date" => $order['end_date'],
            "machine_status" => $currentStatus,
            "first_off_signed" => $firstOffSigned
        ];
    }
}

// Get document for current table if viewing single order
$document_upload = "";
$document_dir = "../admin/route_documents/";
$ext = "";
$partNumbers = [];
$workOrderId = 0;
$partId = 0;
$setId = 0;
$detail = null;

if ($cncMachineTableId) {
    $detailSql = "SELECT * FROM cnc_machine_table 
                  WHERE id = $cncMachineTableId AND machine_id = $machine_id AND table_id = $table_id";
    $detailRes = $conn->query($detailSql);
    if ($detailRes && $detailRes->num_rows > 0) {
        $detail = $detailRes->fetch_assoc();
        $partId = $detail['part_id'];
        $workOrderId = $detail['work_order_id'];
        $setId = isset($detail['set_id']) ? intval($detail['set_id']) : 0;
        $partNumbers = getPartNumbersFromSet($conn, $setId, $partId);
        
        if (!empty($setId) && $setId != 0) {
            $docSql = "SELECT document_upload FROM set_route_details WHERE set_id = '$setId'";
            $document_dir = "../admin/set_route_documents/";
        } else {
            $docSql = "SELECT document_upload FROM route_details WHERE item_id = '$partId'";
        }

        $result_edit = mysqli_query($conn, $docSql);
        if ($result_edit && mysqli_num_rows($result_edit) > 0) {
            $row_edit = mysqli_fetch_assoc($result_edit);
            $document_upload = $row_edit['document_upload'];
        }

        $ext = strtolower(pathinfo($document_upload, PATHINFO_EXTENSION));
    }
}
function isMachineInBreakdown($conn, $machineId) {
    $sql = "SELECT id 
            FROM cnc_machine_breakdown_log 
            WHERE machine_id = $machineId 
            AND status = 'active'
            ORDER BY created_at DESC 
            LIMIT 1";

    $res = mysqli_query($conn, $sql);
    return ($res && mysqli_num_rows($res) > 0);
}
$isBreakdown = isMachineInBreakdown($conn, $machine_id);
?>

<style>
.bg-purple {
    background-color: #9c4893 !important;
}
.count-controls {
    display: flex;
    align-items: center;
    width: 100%;
}
.count-btn {
    flex: 0 0 auto;
    min-width: 80px;
}
.count-display {
    flex: 1;
    max-width: 100px;
    text-align: center;
}
.partinfoBox {
    border: 1px solid #9c4893;
    background: #D9D9D9;
    padding: 0.2rem 0.6rem;
}
.br-0 {
    border-radius: 0 !important;
}
.f-w-b {
    font-weight: bold !important;
}
.undoBtn {
    background: #EFB200;
    color: #fff;
    border: 1px solid #333;
}
.status-table {
    border-collapse: collapse;
    font-size: 16px;
    text-align: center;
    width: 100%;
}
.status-table td {
    border: 1px solid purple;
    padding: 7px 12px;
    width: 50%;
}
.status-table td:first-child {
    font-weight: bold;
    text-align: left;
}
.green {
    color: green;
    font-weight: bold;
}
.status-btn {
    padding: 15px 20px;
    font-size: 16px;
    font-weight: bold;
    color: white;
    background: #888;
    border: none;
    border-radius: 3px;
    cursor: pointer;
    min-width: 160px;
    text-align: center;
}
.status-btn.break {
    background: gray;
}
.status-btn.breakdown {
    background: gray;
    border: 3px solid red;
}

/* CNC-style Part Checkbox Styling */
.part-checkbox {
    margin: 8px 0;
    padding: 12px 15px;
    border: 2px solid #ddd;
    border-radius: 6px;
    transition: all 0.3s ease;
    cursor: pointer;
}

.part-checkbox:hover {
    background-color: #f8f9fa;
    border-color: #007bff;
}

.part-checkbox .form-check-input {
    width: 24px;
    height: 24px;
    margin-top: 0;
    margin-right: 12px;
    cursor: pointer;
    flex-shrink: 0;
}

.part-checkbox .form-check-label {
    font-size: 16px;
    font-weight: 500;
    cursor: pointer;
    margin-bottom: 0;
    line-height: 24px;
}

.part-checkbox input:checked ~ label {
    color: #007bff;
    font-weight: 600;
}

.part-checkbox input:checked {
    background-color: #007bff;
    border-color: #007bff;
}

.part-checkbox:has(input:checked) {
    background-color: #e7f3ff;
    border-color: #007bff;
}

.part-checkbox .form-check {
    display: flex;
    align-items: center;
    margin-bottom: 0;
}

.part-checkbox * {
    transition: all 0.2s ease;
}

/* Larger Modal */
#partSelectionModal .modal-dialog,
#reasonModal .modal-dialog {
    max-width: 600px;
}

#reasonModal .modal-dialog {
    max-width: 700px;
}

.part-checkbox {
    margin: 12px 0; 
    padding: 18px 20px; 
    border: 2px solid #ddd;
    border-radius: 6px;
    min-height: 60px;
}

#reasonSelection .form-check {
    margin: 12px 0;
    padding: 18px 20px;
    border: 2px solid #ddd;
    border-radius: 6px;
    transition: all 0.3s ease;
    cursor: pointer;
    min-height: 60px;
}

#reasonSelection .form-check:hover {
    background-color: #f8f9fa;
    border-color: #dc3545;
}

#reasonSelection .form-check-input {
    width: 46px;
    height: 30px;
    margin-top: 0;
    margin-right: 12px;
    cursor: pointer;
}

#reasonSelection .form-check-label {
    font-size: 16px;
    font-weight: 500;
    cursor: pointer;
    line-height: 24px;
}

#reasonSelection .form-check:has(input:checked) {
    background-color: #ffe6e6;
    border-color: #dc3545;
}

#reasonSelection .form-check input:checked ~ label {
    color: #dc3545;
    font-weight: 600;
}

#partSelection,
#reasonSelection {
    max-height: 400px !important;
    overflow-y: auto;
}

.reason-item .form-check-label {
    margin-left: 28px;
}

#partSelectionModal .form-check {
    display: flex;
    align-items: center;
    gap: 12px;
    position: static;
}

#partSelectionModal .form-check-input {
    position: static;        
    margin: 0;             
    flex-shrink: 0;
}

#partSelectionModal .form-check-label {
    margin: 0;
    cursor: pointer;
}

.machine-table {
    border: 8px solid green;
    margin: 10px 0;
    padding: 0;
    border-radius: 2px;
    position: relative;
}

.table-header {
    background: #f8f9fa;
    padding: 10px;
    border-bottom: 1px solid #dee2e6;
}

.table-body {
    padding: 15px;
}

.machine-table.border-success {
    border-color: green !important;
}

.machine-table.border-danger {
    border-color: red !important;
}

.table-controls {
    position: absolute;
    top: 10px;
    right: 10px;
}
.btn-group .btn {
    height: 100px;        /* increase height */
    font-size: 16px;     /* optional: bigger text */
    display: flex;
    align-items: center;
    justify-content: center;
}
/* Changeover Overlay Styles */
/* Table Changeover Display Styles */
.table-changeover-overlay {
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background: rgba(0, 0, 0, 0.95);
    z-index: 100;
    border-radius: 8px;
    display: flex;
    align-items: center;
    justify-content: center;
    backdrop-filter: blur(8px);
}

.table-changeover-content {
    text-align: center;
    padding: 20px;
    color: white;
    width: 100%;
    max-width: 500px;
}

.table-changeover-content h4 {
    color: #ffc107;
    margin-bottom: 15px;
    font-size: 20px;
}

.table-changeover-timer {
    font-size: 48px;
    font-weight: bold;
    font-family: monospace;
    background: rgba(0,0,0,0.5);
    padding: 15px;
    border-radius: 10px;
    margin: 15px 0;
    letter-spacing: 2px;
}

.table-changeover-progress {
    width: 100%;
    height: 8px;
    background: rgba(255,255,255,0.2);
    border-radius: 4px;
    overflow: hidden;
    margin: 15px 0;
}

.table-changeover-progress-bar {
    height: 100%;
    background: linear-gradient(90deg, #28a745, #ffc107, #dc3545);
    transition: width 0.1s linear;
    border-radius: 4px;
}

.table-changeover-stop-btn {
    background: #dc3545;
    color: white;
    border: none;
    padding: 8px 20px;
    font-size: 14px;
    font-weight: bold;
    border-radius: 5px;
    cursor: pointer;
    margin-top: 10px;
    transition: all 0.3s ease;
    position: absolute;
    top: 10px;
    right: 10px;
    z-index: 101;
}

.table-changeover-stop-btn:hover {
    background: #c82333;
    transform: scale(1.05);
}

.table-changeover-info {
    font-size: 14px;
    color: #ccc;
    margin: 10px 0;
}

.machine-table {
    position: relative;
    overflow: hidden;
}

.changeover-active {
    position: relative;
}

.changeover-badge {
    display: inline-block;
    background: #dc3545;
    color: white;
    padding: 2px 8px;
    border-radius: 4px;
    font-size: 12px;
    margin-left: 10px;
    animation: pulse 1s infinite;
}

@keyframes pulse {
    0% { opacity: 1; }
    50% { opacity: 0.6; }
    100% { opacity: 1; }
}

/* Make the changeover button more prominent */
.changeoverBtn {
    animation: pulse-green 2s infinite;
    font-size: 16px !important;
    padding: 8px 20px !important;
    font-weight: bold !important;
}

@keyframes pulse-green {
    0% {
        background-color: #ffc107;
        box-shadow: 0 0 0 0 rgba(255, 193, 7, 0.7);
    }
    70% {
        background-color: #ff9800;
        box-shadow: 0 0 0 10px rgba(255, 193, 7, 0);
    }
    100% {
        background-color: #ffc107;
        box-shadow: 0 0 0 0 rgba(255, 193, 7, 0);
    }
}
@keyframes flash-ok {
    0%   { background-color: #28a745; transform: scale(1); }
    25%  { background-color: #fff; transform: scale(0.93); box-shadow: 0 0 0 5px #28a74555; }
    100% { background-color: #28a745; transform: scale(1); box-shadow: none; }
}
@keyframes flash-nok {
    0%   { background-color: #dc3545; transform: scale(1); }
    25%  { background-color: #fff; transform: scale(0.93); box-shadow: 0 0 0 5px #dc354555; }
    100% { background-color: #dc3545; transform: scale(1); box-shadow: none; }
}
@keyframes flash-quarantine {
    0%   { background-color: #ffc107; transform: scale(1); }
    25%  { background-color: #fff; transform: scale(0.93); box-shadow: 0 0 0 5px #ffc10755; }
    100% { background-color: #ffc107; transform: scale(1); box-shadow: none; }
}
@keyframes flash-undo {
    0%   { background-color: #6c757d; transform: scale(1); }
    35%  { background-color: #dee2e6; transform: scale(0.91); }
    100% { background-color: #6c757d; transform: scale(1); }
}
.do-flash-ok        { animation: flash-ok        0.38s ease forwards; }
.do-flash-nok       { animation: flash-nok       0.38s ease forwards; }
.do-flash-quarantine{ animation: flash-quarantine 0.38s ease forwards; }
.do-flash-undo      { animation: flash-undo       0.28s ease forwards; }
.table-label {
    font-weight: bold;
    font-size: 30px;
}
</style>

<section class="content" style="margin-top:5vh;">
    <div class="container-fluid">
        
            <!-- MULTI-TABLE VIEW -->
            <div class="header" style="display:flex; justify-content:space-between; align-items:center; margin-bottom:20px;">
                <h2 style="margin:0;">CNC Dashboard - Machine <?= $machine_id ?></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 if ($isBreakdown): ?>

    <div class="machine-table text-center" style="border:10px solid red; padding:50px;">
        <h1 style="color:red;">⚠ MACHINE UNDER BREAKDOWN</h1>
        <p>Please resolve the issue before continuing production</p>

        <button id="breakdownOverBtn" 
                class="btn btn-success btn-lg mt-3"
                data-machine="<?= $machine_id ?>">
            Breakdown Over
        </button>
    </div>

<?php else: ?>
            <?php for ($t=1; $t <= $no_of_table; $t++): ?>
                <?php if (!empty($tableOrdersJS[$t])): 
                    $first = $tableOrdersJS[$t][0]; 
                    $machineStatus = $first['machine_status'];
                    $borderColor = isset($tableBorders[$t]) ? $tableBorders[$t] : 'green';
                    $firstOffSigned = $first['first_off_signed'] ?? false;
                ?>
                <div class="machine-table <?= $borderColor == 'green' ? 'border-success' : 'border-danger' ?>" id="table-<?= $t ?>" style="border:10px solid <?= $borderColor ?>; margin-bottom:20px;">
                    <div class="table-header">
                        <div class="row">
                            <div class="col-md-8">
                                <strong><span class="table-label">Table <?= $t ?> |</span>
                                Part No : <span class="part_name"><?= $first["product_name"] ?></span> | 
                                UPH: <span class="planned_uph"><?= round($first["original_uph"], 2) ?></span> |
                                Actual UPH: <span class="actual_uph"><?= $first["actual_uph"] ?></span> |
 <span class="qty_req" style="font-size: 25px; font-weight: bold;">QTY Req :</span>
<span class="qty_req" style="font-size: 25px; font-weight: bold;">
    <?= $first["qty_req"] ?>
</span> |
                                QTY Good : <span class="qty_good"><?= $first["ok"] ?></span>
                                </strong>
                            </div>
                            <div class="col-md-4 text-right">
                                <?php if (!$firstOffSigned): ?>
                                    <button class="btn btn-dark btn-lg firstOffBtn mr-2" 
                                            data-table="<?= $t ?>"
                                            data-cnc-id="<?= $first['id'] ?>">
                                        <i class="fas fa-stamp"></i> First-Off
                                    </button>
                                <?php else: ?>
                                    <span class="badge bg-success mr-2">
                                        <i class="fas fa-check"></i> Approved
                                    </span>
                                <?php endif; ?>
                                
                                <button class="btn btn-warning btn-lg changeoverBtn" 
        data-table="<?= $t ?>"
        data-cnc-id="<?= $first['id'] ?>"> 
    <i class="fas fa-exchange-alt"></i> Changeover
</button>
                            </div>
                        </div>
                    </div>
                    
                    <div class="table-body">
                        <div class="row text-center">
                            <div class="col-md-3">
                                <button type="button" class="btn btn-success w-100 increment-btn mb-2 py-3" 
                                        data-type="ok" 
                                        data-table="<?= $t ?>"
                                        data-cnc-id="<?= $first['id'] ?>"
                                        <?= in_array($machineStatus, ['pause', 'break', 'breakdown']) ? 'disabled' : '' ?>>
                                    OK
                                </button>
                                <div class="input-group">
                                    <input type="number" class="form-control text-center ok-count" value="<?= $first['ok'] ?>" readonly style="font-size: 30px; font-weight: bold;">
                                    <div class="input-group-append">
                                        <button class="btn btn-outline-secondary decrement-btn" 
                                                type="button"
                                                data-type="ok" 
                                                data-table="<?= $t ?>"
                                                data-cnc-id="<?= $first['id'] ?>"
                                                <?= in_array($machineStatus, ['pause', 'break', 'breakdown']) ? 'disabled' : '' ?>>
                                            Undo
                                        </button>
                                    </div>
                                </div>
                            </div>

                            <div class="col-md-3">
                                <button type="button" class="btn btn-danger w-100 increment-btn mb-2 py-3" 
                                        data-type="nok" 
                                        data-table="<?= $t ?>"
                                        data-cnc-id="<?= $first['id'] ?>"
                                        <?= in_array($machineStatus, ['pause', 'break', 'breakdown']) ? 'disabled' : '' ?>>
                                    NOK
                                </button>
                                <div class="input-group">
                                  <input type="number" 
       class="form-control text-center nok-count" 
       value="<?= $first['nok'] ?>" 
       readonly
       style="font-size: 30px; font-weight: bold;">
                                    <div class="input-group-append">
                                        <button class="btn btn-outline-secondary decrement-btn" 
                                                type="button"
                                                data-type="nok" 
                                                data-table="<?= $t ?>"
                                                data-cnc-id="<?= $first['id'] ?>"
                                                <?= in_array($machineStatus, ['pause', 'break', 'breakdown']) ? 'disabled' : '' ?>>
                                            Undo
                                        </button>
                                    </div>
                                </div>
                            </div>

                            <div class="col-md-3">
                                <button type="button" class="btn btn-warning w-100 increment-btn mb-2 py-3" 
                                        data-type="quarantine" 
                                        data-table="<?= $t ?>"
                                        data-cnc-id="<?= $first['id'] ?>"
                                        <?= in_array($machineStatus, ['pause', 'break', 'breakdown']) ? 'disabled' : '' ?>>
                                    QUAR
                                </button>
                                <div class="input-group">
                                    <input type="number" class="form-control text-center quar-count" value="<?= $first['quar'] ?>" readonly style="font-size: 30px; font-weight: bold;">
                                    <div class="input-group-append">
                                        <button class="btn btn-outline-secondary decrement-btn" 
                                                type="button"
                                                data-type="quarantine" 
                                                data-table="<?= $t ?>"
                                                data-cnc-id="<?= $first['id'] ?>"
                                                <?= in_array($machineStatus, ['pause', 'break', 'breakdown']) ? 'disabled' : '' ?>>
                                            Undo
                                        </button>
                                    </div>
                                </div>
                            </div>

                            <div class="col-md-3">
                                <div class="btn-group w-100">
    <button class="btn <?= $machineStatus === 'pause' ? 'btn-success' : 'btn-dark' ?> machine-action" 
            data-table="<?= $t ?>" 
            data-action="<?= $machineStatus === 'pause' ? 'pause' : 'start' ?>"
            data-cnc-id="<?= $first['id'] ?>">
        <?= $machineStatus === 'pause' ? 'Start' : 'Pause' ?>
    </button>
    <button class="btn btn-primary finish-btn" 
            data-table="<?= $t ?>"
            data-cnc-id="<?= $first['id'] ?>">
        Finished
    </button>
    <button class="btn btn-info details-btn" 
            data-table="<?= $t ?>"
            data-order='<?= json_encode($first) ?>'>
        Details
    </button>
</div>
                            </div>
                        </div>
                    </div>
                </div>
                <?php else: ?>
                <div class="machine-table" style="border:1px solid #ccc; margin-bottom:20px;">
                    <div class="table-header">
                        <strong>Table <?= $t ?> - No orders scheduled</strong>
                    </div>
                </div>
                <?php endif; ?>
            <?php endfor; ?>

            <div class="footer row mt-4">
                <div class="col-md-4">
                    <button id="toggleAllBtn" class="btn btn-warning w-100 py-4">
                        <i class="fas fa-pause mr-2"></i> Pause/Start All Tables
                    </button>
                </div>  
                <div class="col-md-4">
                    <button id="scheduleBreakAll" class="btn btn-info w-100 py-4">
                        <i class="fas fa-clock mr-2"></i> Schedule Break All Tables
                    </button>
                </div>
                <div class="col-md-4">
                    <button id="breakdownAllBtn" class="btn btn-danger w-100 py-4">
                        <i class="fas fa-exclamation-triangle mr-2"></i> Machine Breakdown
                    </button>
                </div>
            </div>
        <?php endif; ?>
    </div>
</section>
<!-- Changeover Overlay -->
<div id="changeoverOverlay" class="changeover-overlay" style="display: none;">
    <div class="changeover-container">
        <div class="changeover-spinner"></div>
        <h2>🔄 CHANGEOVER IN PROGRESS</h2>
        <div class="changeover-info">
            <strong>Table: <span id="changeoverTableDisplay"></span></strong>
        </div>
        <div class="changeover-timer" id="changeoverTimer">00:00:00</div>
        <div class="changeover-progress">
            <div class="changeover-progress-bar" id="changeoverProgress"></div>
        </div>
        <div class="changeover-info" id="changeoverStartedAt"></div>
        <button class="changeover-stop-btn" onclick="stopChangeover()">
            <i class="fas fa-stop"></i> Stop Changeover
        </button>
    </div>
</div>
<!-- First-Off Modal -->
<div class="modal fade" id="firstOffModal" tabindex="-1">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content">
            <div class="modal-header bg-dark text-white">
                <h5 class="modal-title">
                    <i class="fas fa-stamp mr-2"></i>
                    First-Off Quality Approval
                </h5>
                <button type="button" class="close" data-dismiss="modal">&times;</button>
            </div>
            <div class="modal-body">
                <div class="form-group">
                    <label><strong>Enter QC Clock Number</strong></label>
                    <input type="text" 
                           id="qc_clock_no" 
                           class="form-control" 
                           placeholder="Enter Clock Number" 
                           required>
                </div>
                <div class="form-group mt-3">
                    <label><strong>QC Comment</strong></label>
                    <textarea id="qc_comment"
                              class="form-control"
                              rows="3"
                              placeholder="Enter approval comment (optional)"></textarea>
                </div>
            </div>
            <div class="modal-footer">
                <button class="btn btn-secondary" data-dismiss="modal">Cancel</button>
                <button class="btn btn-dark" id="submitFirstOff">Approve</button>
            </div>
        </div>
    </div>
</div>

<!-- Changeover Modal -->
<div class="modal fade" id="changeoverModal" tabindex="-1">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content">
            <div class="modal-header bg-warning text-white">
                <h5 class="modal-title">
                    <i class="fas fa-exchange-alt mr-2"></i>
                    Start Changeover - Table <span id="changeoverTableId"></span>
                </h5>
                <button type="button" class="close" data-dismiss="modal">&times;</button>
            </div>
            <div class="modal-body">
                <div class="form-group">
                    <label><strong>Enter Employee Clock Number</strong></label>
                    <input type="text" 
                           id="changeover_clock_no" 
                           class="form-control" 
                           placeholder="Enter Clock Number" 
                           required>
                </div>
            </div>
            <div class="modal-footer">
                <button class="btn btn-secondary" data-dismiss="modal">Cancel</button>
                <button class="btn btn-warning" id="submitChangeover">Start</button>
            </div>
        </div>
    </div>
</div>

<!-- Part Selection Modal -->
<div class="modal fade" id="partSelectionModal" tabindex="-1" role="dialog" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content">
            <div class="modal-header bg-warning text-white">
                <h5 class="modal-title"><i class="fas fa-cogs mr-2"></i>Select Part Number</h5>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>
            <div class="modal-body">
                <h6 class="mb-3">Please select the part number(s):</h6>
                <div id="partSelection" style="max-height: 200px; overflow-y: auto;">
                    <!-- Part checkboxes will be inserted here dynamically -->
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-dismiss="modal">Cancel</button>
                <button type="button" class="btn btn-warning" id="proceedToReason">Next</button>
            </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">
                <h6 class="mb-3">Select Reason</h6>
                <div id="reasonSelection" style="max-height: 400px; overflow-y: auto;">
                    <?php
                    $reasonSql = "SELECT * FROM reason_codes";
                    $reasonRes = $conn->query($reasonSql);
                    while ($r = $reasonRes->fetch_assoc()): ?>
                        <div class="form-check mb-2 reason-item">
                            <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>

<!-- Breakdown Modal -->
<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>Machine Breakdown</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="form-group">
                    <label for="breakdown_duration"><strong>Breakdown Duration (hours)</strong></label>
                    <input type="number" 
                           class="form-control" 
                           id="breakdown_duration" 
                           min="0.5" 
                           max="24" 
                           step="0.5" 
                           value="1" 
                           required>
                    <small class="form-text text-muted">Enter duration between 0.5 and 24 hours</small>
                </div>
                <div class="form-group">
                    <label for="breakdown_reason"><strong>Breakdown Reason</strong></label>
                    <?php 
                    echo Keycode::getKeycodeListValue(
                        "breakdown_reason",
                        $breakdown_reason,
                        "100%",
                        "Please Select",
                        "id",
                        "code",
                        "breakdown_reason",
                        "",
                        "form-control",
                        false,
                        "required"
                    ); 
                    ?>
                </div>
                <input type="hidden" id="breakdown_table_id" value="">
                <input type="hidden" id="breakdown_cnc_id" value="">
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-dismiss="modal">Cancel</button>
                <button type="button" class="btn btn-danger" id="submitBreakdown">Submit</button>
            </div>
        </div>
    </div>
</div>

<!-- Schedule Break Modal -->
<div class="modal fade" id="scheduleBreakModal" 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-info text-white">
                <h5 class="modal-title"><i class="fas fa-coffee mr-2"></i>Schedule Break</h5>
                <button type="button" class="close text-white" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>
            <div class="modal-body">
                <div class="form-group">
                    <label for="break_duration"><strong>Break Duration (hours)</strong></label>
                    <input type="number" 
                           class="form-control" 
                           id="break_duration" 
                           min="0.5" 
                           max="10" 
                           step="0.5" 
                           value="1" 
                           required>
                    <small class="form-text text-muted">Enter duration between 0.5 and 10 hours</small>
                </div>
                <div class="form-group">
                    <label for="break_reason"><strong>Break Reason</strong></label>
                    <select class="form-control" id="break_reason" required>
                        <option value="">-- Select Reason --</option>
                        <option value="Lunch Break">Lunch Break</option>
                        <option value="Tea Break">Tea Break</option>
                        <option value="Maintenance">Scheduled Maintenance</option>
                        <option value="Meeting">Team Meeting</option>
                        <option value="Training">Training Session</option>
                        <option value="Other">Other</option>
                    </select>
                </div>
                <div class="form-group" id="other_reason_group" style="display: none;">
                    <label for="other_break_reason"><strong>Specify Reason</strong></label>
                    <input type="text" 
                           class="form-control" 
                           id="other_break_reason" 
                           placeholder="Enter custom reason">
                </div>
                <input type="hidden" id="break_table_id" value="">
                <input type="hidden" id="break_cnc_id" value="">
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-dismiss="modal">
                    <i class="fas fa-times mr-1"></i> Cancel
                </button>
                <button type="button" class="btn btn-info" id="submitScheduleBreak">
                    <i class="fas fa-check mr-1"></i> Schedule Break
                </button>
            </div>
        </div>
    </div>
</div>

<!-- Details Modal -->
<div class="modal fade" id="detailsModal" 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-primary text-white">
                <h5 class="modal-title"><i class="fas fa-info-circle mr-2"></i>Order Details - Table <span id="detailsTableId"></span></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="row mb-2">
                    <div class="col-6"><strong>Part Number:</strong></div>
                    <div class="col-6" id="detailsPartNumber"></div>
                </div>
                <div class="row mb-2">
                    <div class="col-6"><strong>Description:</strong></div>
                    <div class="col-6" id="detailsDescription"></div>
                </div>
                <div class="row mb-2">
                    <div class="col-6"><strong>Work Order:</strong></div>
                    <div class="col-6" id="detailsWorkOrder"></div>
                </div>
                <div class="row mb-2">
                    <div class="col-6"><strong>Start Date:</strong></div>
                    <div class="col-6" id="detailsStartDate"></div>
                </div>
                <div class="row mb-2">
                    <div class="col-6"><strong>End Date:</strong></div>
                    <div class="col-6" id="detailsEndDate"></div>
                </div>
                <div class="row mb-2">
                    <div class="col-6"><strong>Quantity Required:</strong></div>
                    <div class="col-6" id="detailsQtyReq"></div>
                </div>
                <div class="row mb-2">
                    <div class="col-6"><strong>OK Count:</strong></div>
                    <div class="col-6" id="detailsOkCount"></div>
                </div>
                <div class="row mb-2">
                    <div class="col-6"><strong>NOK Count:</strong></div>
                    <div class="col-6" id="detailsNokCount"></div>
                </div>
                <div class="row mb-2">
                    <div class="col-6"><strong>Quarantine Count:</strong></div>
                    <div class="col-6" id="detailsQuarCount"></div>
                </div>
                <div class="row mb-2">
                    <div class="col-6"><strong>Target UPH:</strong></div>
                    <div class="col-6" id="detailsTargetUph"></div>
                </div>
                <div class="row mb-2">
                    <div class="col-6"><strong>Actual UPH:</strong></div>
                    <div class="col-6" id="detailsActualUph"></div>
                </div>
                <div class="row mb-2">
                    <div class="col-6"><strong>Status:</strong></div>
                    <div class="col-6" id="detailsStatus"></div>
                </div>
                <div class="row mb-2">
                    <div class="col-6"><strong>Document:</strong></div>
                    <div class="col-6">
                        <a href="#" id="detailsPdfLink" target="_blank" style="display:none;">
                            <i class="fas fa-file-pdf text-danger mr-1"></i> View PDF
                        </a>
                        <span id="detailsNoPdf" style="display:none;">No PDF available</span>
                    </div>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</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>
console.log("JavaScript loaded - Multi-table version");
const frontEndURL = "<?= $frontEndURL; ?>";
const machine_id = <?= $machine_id ?>;
const cncMachineTableId = <?= (int)$cncMachineTableId ?>;
const tableOrdersByTable = <?php echo json_encode($tableOrdersJS); ?>;

console.log("frontEndURL:", frontEndURL);
console.log("machine_id:", machine_id);
console.log("cncMachineTableId:", cncMachineTableId);
console.log("tableOrdersByTable:", tableOrdersByTable);

// Current index for each table
let currentIndex = {};
for (let t in tableOrdersByTable) {
    currentIndex[t] = 0;
}

// Global variables for modals
let currentTableId = null;
let currentCncId = null;
let currentCountType = null;
let selectedParts = [];

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);

// Back button
$('#backBtn').on('click', function() {
    window.location.href = "index?page=dashboard_cnc&machine_id=" + machine_id;
});

// First-Off Sign-Off
$(document).on('click', '.firstOffBtn', function() {
    console.log("First-Off button clicked");
    currentTableId = $(this).data('table');
    currentCncId = $(this).data('cnc-id');
    $('#firstOffModal').modal('show');
});

$('#submitFirstOff').click(function() {
    console.log("Submit First-Off clicked");
    let qcClockNo = $("#qc_clock_no").val().trim();
    let qcComment = $("#qc_comment").val().trim();

    if (!qcClockNo) {
        alert("Please enter QC clock number");
        return;
    }

    // Get work order and part ID based on current context
    let workOrderId, partId;
    
    if (cncMachineTableId) {
        // Single table view
        workOrderId = <?= isset($workOrderId) ? $workOrderId : 0 ?>;
        partId = <?= isset($partId) ? $partId : 0 ?>;
    } else {
        // Multi-table view
        const orders = tableOrdersByTable[currentTableId];
        if (!orders || orders.length === 0) {
            alert("No order found for this table");
            return;
        }
        const currentOrder = orders[currentIndex[currentTableId] || 0];
        workOrderId = currentOrder.work_order_id;
        partId = currentOrder.part_id;
    }

    $.ajax({
        url: frontEndURL + "/machine_tab/index?page=ajax_actions_cnc&action=first_off_signoff_cnc",
        method: "POST",
        data: {
            work_order_id: workOrderId,
            part_id: partId,
            cnc_machine_table_id: currentCncId,
            table_id: currentTableId,
            machine_id: machine_id,
            qc_clock_no: qcClockNo,
            qc_comment: qcComment
        },
        dataType: "json",
        success: function(response){
            console.log("First-Off response:", response);
            if(response.success){
                $("#firstOffModal").modal("hide");
                alert("✅ First-Off Approved Successfully");
                location.reload();
            } else {
                alert("❌ " + response.message);
            }
        },
        error: function(xhr, status, error) {
            console.error("AJAX Error:", error);
            console.error("Response:", xhr.responseText);
            alert("AJAX Error: " + error);
        }
    });
});

// Changeover
$(document).on('click', '.changeoverBtn', function() {
    console.log("Changeover button clicked");
    currentTableId = $(this).data('table');
    $('#changeoverTableId').text(currentTableId);
    $('#changeoverModal').modal('show');
});

$('#submitChangeover').click(function() {
    console.log("Submit Changeover clicked");
    let clockNo = $("#changeover_clock_no").val().trim();

    if (!clockNo) {
        alert("Please enter employee clock number");
        return;
    }

    $.ajax({
        url: frontEndURL + "/machine_tab/index?page=ajax_actions_cnc&action=start_changeover_cnc",
        method: "POST",
        data: {
            machine_id: machine_id,
            table_id: currentTableId,
            clock_no: clockNo
        },
        dataType: "json",
        success: function(response) {
            console.log("Changeover response:", response);
            if (response.success) {
                $("#changeoverModal").modal("hide");
                alert("✅ Changeover started for Table " + currentTableId);
                location.reload();
            } else {
                alert("❌ " + response.message);
            }
        },
        error: function(xhr, status, error) {
            console.error("AJAX Error:", error);
            alert("AJAX Error: " + error);
        }
    });
});

// Increment buttons
$(document).on('click', ".increment-btn", function() {
    console.log("Increment button clicked");
    const type = $(this).data("type");
    const tableId = $(this).data("table");
    const cncId = $(this).data("cnc-id");
	const flashMap = { ok: 'do-flash-ok', nok: 'do-flash-nok', quarantine: 'do-flash-quarantine' };
    const $btn = $(this);
    $btn.removeClass('do-flash-ok do-flash-nok do-flash-quarantine');
    void $btn[0].offsetWidth; // force reflow so animation restarts on repeated taps
    $btn.addClass(flashMap[type]);
    
    if (!tableId || !cncId) {
        console.error("Missing tableId or cncId");
        return;
    }
    
    currentTableId = tableId;
    currentCncId = cncId;
    currentCountType = type;
    
    // Get order details based on context
    let workOrderId, partId, setId;
    
    if (cncMachineTableId) {
        // Single table view
        workOrderId = <?= isset($workOrderId) ? $workOrderId : 0 ?>;
        partId = <?= isset($partId) ? $partId : 0 ?>;
        setId = <?= isset($setId) ? $setId : 0 ?>;
    } else {
        // Multi-table view
        const orders = tableOrdersByTable[tableId];
        if (!orders || orders.length === 0) {
            console.error("No orders for table", tableId);
            return;
        }
        const currentOrder = orders[currentIndex[tableId] || 0];
        workOrderId = currentOrder.work_order_id;
        partId = currentOrder.part_id;
        setId = currentOrder.set_id || 0;
    }
    
    if (type === "ok") {
        $.ajax({
            url: frontEndURL + "/machine_tab/index?page=ajax_actions_cnc&action=log_count_cnc",
            method: "POST",
            data: {
                work_order_id: workOrderId,
                part_id: partId,
                table_id: tableId,
                cnc_machine_table_id: cncId,
                type: type,
                setId: setId,
                quantity: 1
            },
            dataType: "json",
            success: function(response){
                console.log("OK count response:", response);
                if(response.success){
                    location.reload();
                } else {
                    alert("Error: " + response.message);
                }
            },
            error: function(xhr, status, error){
                console.error("AJAX Error:", error);
                console.error("Response:", xhr.responseText);
                alert("AJAX Error: " + error);
            }
        });
    } else {
        // For NOK and Quarantine, show part selection
        populatePartSelection(tableId);
        $("#partSelectionModal").modal("show");
    }
});

// Decrement buttons
$(document).on('click', ".decrement-btn", function() {
    console.log("Decrement button clicked");
    const type = $(this).data("type");
    const tableId = $(this).data("table");
    const cncId = $(this).data("cnc-id");
    
    if (!tableId || !cncId) {
        console.error("Missing tableId or cncId");
        return;
    }
    
    // Get current count value
    let currentCount = 0;
    let workOrderId, partId, setId;
    
    if (cncMachineTableId) {
        // Single table view
        currentCount = parseInt($(`#${type}_count`).val() || 0);
        workOrderId = <?= isset($workOrderId) ? $workOrderId : 0 ?>;
        partId = <?= isset($partId) ? $partId : 0 ?>;
        setId = <?= isset($setId) ? $setId : 0 ?>;
    } else {
        // Multi-table view
        const orders = tableOrdersByTable[tableId];
        if (!orders || orders.length === 0) {
            console.error("No orders for table", tableId);
            return;
        }
        const currentOrder = orders[currentIndex[tableId] || 0];
        workOrderId = currentOrder.work_order_id;
        partId = currentOrder.part_id;
        setId = currentOrder.set_id || 0;
        currentCount = parseInt($(`#table-${tableId} .${type}-count`).val() || 0);
    }
    
    if (currentCount <= 0) {
        alert("⚠ Count is already 0. Nothing to undo.");
        return;
    }
    
    if (confirm("Are you sure you want to undo the last " + type.toUpperCase() + " entry?")) {
        $.ajax({
            url: frontEndURL + "/machine_tab/index?page=ajax_actions_cnc&action=log_count_cnc",
            method: "POST",
            data: {
                work_order_id: workOrderId,
                part_id: partId,
                table_id: tableId,
                cnc_machine_table_id: cncId,
                type: type,
                setId: setId,
                quantity: -1
            },
            dataType: "json",
            success: function(response){
                console.log("Decrement response:", response);
                if(response.success){
                    location.reload();
                } else {
                    alert("❌ Error: " + response.message);
                }
            },
            error: function(xhr, status, error){
                console.error("AJAX Error:", error);
                console.error("Response:", xhr.responseText);
                alert("AJAX Error: " + error);
            }
        });
    }
});

function populatePartSelection(tableId) {
    console.log("Populating part selection for table", tableId);
    let partNumbers = [];
    
    if (cncMachineTableId) {
        // Single table view
        partNumbers = <?php echo json_encode(isset($partNumbers) ? $partNumbers : []); ?>;
    } else {
        // Multi-table view
        const orders = tableOrdersByTable[tableId];
        if (!orders || orders.length === 0) {
            console.error("No orders for table", tableId);
            return false;
        }
        const currentOrder = orders[currentIndex[tableId] || 0];
        partNumbers = currentOrder.part_numbers || [];
    }
    
    const partSelection = document.getElementById("partSelection");
    partSelection.innerHTML = '';
    
    if (partNumbers && partNumbers.length > 0) {
        partNumbers.forEach(part => {
            const partDiv = document.createElement('div');
            partDiv.className = 'part-checkbox';
            partDiv.innerHTML = `
                <div class="form-check">
                    <input class="form-check-input part-check" 
                           type="checkbox" 
                           value="${part.id}" 
                           id="part${part.id}"
                           checked>
                    <label class="form-check-label" for="part${part.id}">
                        ${part.part_number}
                    </label>
                </div>
            `;
            
            partDiv.addEventListener('click', function(e) {
                if (e.target.tagName !== 'INPUT') {
                    const checkbox = this.querySelector('input[type="checkbox"]');
                    checkbox.checked = !checkbox.checked;
                }
            });
            
            partSelection.appendChild(partDiv);
        });
        return true;
    } else {
        if (cncMachineTableId) {
            selectedParts = [<?= isset($partId) ? $partId : 0 ?>];
        } else {
            const orders = tableOrdersByTable[tableId];
            const currentOrder = orders[currentIndex[tableId] || 0];
            selectedParts = [currentOrder.part_id.toString()];
        }
        $("#reasonModal").modal("show");
        return false;
    }
}

$("#proceedToReason").click(function() {
    console.log("Proceed to reason clicked");
    selectedParts = [];
    $(".part-check:checked").each(function() {
        selectedParts.push($(this).val());
    });
    
    if (selectedParts.length === 0) {
        alert("⚠ Please select at least one part number.");
        return;
    }
    
    $("#partSelectionModal").modal("hide");
    $("#reasonModal").modal("show");
});

$("#backToParts").click(function() {
    $("#reasonModal").modal("hide");
    $("#partSelectionModal").modal("show");
});

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

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

    let workOrderId, partId, setId;
    
    if (cncMachineTableId) {
        // Single table view
        workOrderId = <?= isset($workOrderId) ? $workOrderId : 0 ?>;
        partId = <?= isset($partId) ? $partId : 0 ?>;
        setId = <?= isset($setId) ? $setId : 0 ?>;
    } else {
        // Multi-table view
        const orders = tableOrdersByTable[currentTableId];
        if (!orders || orders.length === 0) {
            alert("No order found for this table");
            return;
        }
        const currentOrder = orders[currentIndex[currentTableId] || 0];
        workOrderId = currentOrder.work_order_id;
        partId = currentOrder.part_id;
        setId = currentOrder.set_id || 0;
    }

    // Collect all part IDs for this order
    let allPartIds = [];
    $(".part-check").each(function() {
        allPartIds.push($(this).val());
    });

    // Selected parts
    let selectedPartIds = selectedParts;

    // Unselected parts
    let unselectedPartIds = allPartIds.filter(id => !selectedPartIds.includes(id));

    $.ajax({
        url: frontEndURL + "/machine_tab/index?page=ajax_actions_cnc&action=log_count_cnc",
        method: "POST",
        data: {
            work_order_id: workOrderId,
            part_id: partId,
            table_id: currentTableId,
            cnc_machine_table_id: currentCncId,
            reason_id: reason,
            part_ids: selectedParts.join(","),
            nok_q_scrap_part_ids_part_ids: selectedPartIds.join(","),
            type: currentCountType,
            setId: setId,
            quantity: 1
        },
        dataType: "json",
        success: function(response) {
            console.log("NOK submit response:", response);
            if (response.success) {
                $("#reasonModal").modal("hide");
                location.reload();
                $(".reason-radio").prop("checked", false);
                $(".part-check").prop("checked", false);
                selectedParts = [];
            } else {
                alert("Error: " + response.message);
            }
        },
        error: function(xhr, status, error) {
            console.error("AJAX Error:", error);
            console.error("Response:", xhr.responseText);
            alert("AJAX Error: " + error);
        }
    });
});

// Action buttons (start, pause, finish, break)
$(document).on('click', ".action-btn", function() {
    console.log("Action button clicked");
    let action = $(this).data("action");
    
    // Handle PDF action
    if(action === "pdf"){
        <?php if (!empty($document_upload) && $ext === 'pdf'): ?>
            window.location.href = "<?= $document_dir . $document_upload ?>";
        <?php else: ?>
            alert("No PDF file available!");
        <?php endif; ?>
        return;
    }
    
    // Handle Schedule Break action
    if(action === "break"){
        $('#break_table_id').val(<?= isset($table_id) ? $table_id : 0 ?>);
        $('#break_cnc_id').val(<?= isset($cncMachineTableId) ? $cncMachineTableId : 0 ?>);
        $('#scheduleBreakModal').modal('show');
        return;
    }

    let workOrderId, partId;
    
    if (cncMachineTableId) {
        // Single table view
        workOrderId = <?= isset($workOrderId) ? $workOrderId : 0 ?>;
        partId = <?= isset($partId) ? $partId : 0 ?>;
    } else {
        // Multi-table view
        const tableId = <?= isset($table_id) ? $table_id : 0 ?>;
        const orders = tableOrdersByTable[tableId];
        if (!orders || orders.length === 0) return;
        const currentOrder = orders[0];
        workOrderId = currentOrder.work_order_id;
        partId = currentOrder.part_id;
    }

    // Validate finish action
    if (action === "finish") {
        const okCount = parseInt($("#ok_count").val());
        const requiredQty = <?= isset($detail['quantity']) ? $detail['quantity'] : 0 ?>;
        
        if (okCount < requiredQty) {
            if (!confirm(`OK Count: ${okCount}\nRequired: ${requiredQty}\n\nAre you sure you want to finish this order?`)) {
                return;
            }
        }
        
        if (!confirm("Are you sure you want to finish this work order?")) {
            return;
        }
    } else if (action !== 'pdf' && !confirm("Are you sure you want to set this work order to " + action + "?")) {
        return;
    }

    $.ajax({
        url: frontEndURL + "/machine_tab/index?page=ajax_actions_cnc&action=log_action_cnc",
        method: "POST",
        data: {
            work_order_id: workOrderId,
            part_id: partId,
            table_id: <?= isset($table_id) ? $table_id : 0 ?>,
            cnc_machine_table_id: <?= isset($cncMachineTableId) ? $cncMachineTableId : 0 ?>,
            machine_id: machine_id,
            action_type: action
        },
        dataType: "json",
        success: function(response){
            console.log("Action response:", response);
            if(response.success){
                location.reload();
            } else {
                alert("❌ Error: " + response.message);
            }
        },
        error: function(xhr, status, error){
            console.error("AJAX Error:", error);
            console.error("Response:", xhr.responseText);
            alert("AJAX Error: " + error);
        }
    });
});

// Machine action for multi-table view
$(document).on('click', ".machine-action", function() {
    console.log("Machine action clicked");
    const tableId = $(this).data("table");
    const currentAction = $(this).data("action");
    const cncId = $(this).data("cnc-id");
    const newAction = currentAction === 'start' ? 'pause' : 'start';
    
    const orders = tableOrdersByTable[tableId];
    if (!orders || orders.length === 0) return;
    
    const currentOrder = orders[currentIndex[tableId] || 0];
    const workOrderId = currentOrder.work_order_id;
    const partId = currentOrder.part_id;
    
    $.ajax({
        url: frontEndURL + "/machine_tab/index?page=ajax_actions_cnc&action=log_action_cnc",
        method: "POST",
        data: {
            machine_id: machine_id,
            work_order_id: workOrderId,
            table_id: tableId,
            cnc_machine_table_id: cncId,
            part_id: partId,
            action_type: newAction
        },
        dataType: "json",
        success: function(response) {
            console.log("Machine action response:", response);
            if (response.success) {
                location.reload();
            } else {
                alert("Error: " + response.message);
            }
        },
        error: function(xhr, status, error) {
            console.error("AJAX Error:", error);
            alert("AJAX Error: " + error);
        }
    });
});

// Finish button for multi-table view
$(document).on('click', ".finish-btn", function() {
    console.log("Finish button clicked");
    const tableId = $(this).data("table");
    const cncId = $(this).data("cnc-id");
    
    const orders = tableOrdersByTable[tableId];
    if (!orders || orders.length === 0) return;
    
    const currentOrder = orders[currentIndex[tableId] || 0];
    const workOrderId = currentOrder.work_order_id;
    const partId = currentOrder.part_id;
    const qtyRequired = parseInt(currentOrder.qty_req);
    const qtyGood = parseInt(currentOrder.ok);
    
   /* if (qtyGood < qtyRequired) {
        alert(`Cannot finish! Quantity Good (${qtyGood}) must reach Quantity Required (${qtyRequired}) before finishing.`);
        return;
    }*/
    
    if (confirm("Are you sure you want to mark this order as finished?")) {
        $.ajax({
            url: frontEndURL + "/machine_tab/index?page=ajax_actions_cnc&action=log_action_cnc",
            method: "POST",
            data: {
                work_order_id: workOrderId,
                part_id: partId,
                table_id: tableId,
                cnc_machine_table_id: cncId,
                machine_id: machine_id,
                action_type: "finish"
            },
            dataType: "json",
            success: function(response) {
                console.log("Finish response:", response);
                if (response.success) {
                    alert("Order marked as finished!");
                    location.reload();
                } else {
                    alert("Error: " + response.message);
                }
            },
            error: function(xhr, status, error) {
                console.error("AJAX Error:", error);
                alert("AJAX Error: " + error);
            }
        });
    }
});

// Details button
$(document).on('click', ".details-btn", function() {
    console.log("Details button clicked");
    const orderData = $(this).data('order');
    
    $("#detailsTableId").text($(this).data('table'));
    $("#detailsPartNumber").text(orderData.product_name || 'N/A');
    $("#detailsDescription").text(orderData.product_name || 'N/A');
    $("#detailsWorkOrder").text(orderData.work_order_id || 'N/A');
    $("#detailsStartDate").text(orderData.start_date ? new Date(orderData.start_date).toLocaleString() : 'Not set');
    $("#detailsEndDate").text(orderData.end_date ? new Date(orderData.end_date).toLocaleString() : 'Not set');
    $("#detailsQtyReq").text(orderData.qty_req || 0);
    $("#detailsOkCount").text(orderData.ok || 0);
    $("#detailsNokCount").text(orderData.nok || 0);
    $("#detailsQuarCount").text(orderData.quar || 0);
    $("#detailsTargetUph").text(orderData.original_uph || 0);
    $("#detailsActualUph").text(orderData.actual_uph || 0);
    $("#detailsStatus").text(orderData.machine_status || 'unknown');
    
    if (orderData.document_upload && orderData.document_upload !== "") {
        const ext = orderData.document_upload.split('.').pop().toLowerCase();
        if (ext === 'pdf') {
            $("#detailsPdfLink").attr('href', orderData.document_dir + orderData.document_upload).show();
            $("#detailsNoPdf").hide();
        } else {
            $("#detailsPdfLink").hide();
            $("#detailsNoPdf").show();
        }
    } else {
        $("#detailsPdfLink").hide();
        $("#detailsNoPdf").show();
    }
    
    $("#detailsModal").modal("show");
});

// Breakdown button
$("#breakdownBtn, #breakdownAllBtn").click(function() {
    // Collect all active cnc_machine_table ids from tableOrdersByTable
    let allCncIds = [];
    for (let tableId in tableOrdersByTable) {
        const orders = tableOrdersByTable[tableId];
        if (orders && orders.length > 0) {
            allCncIds.push(orders[currentIndex[tableId] || 0].id);
        }
    }
    
    $('#breakdown_table_id').val(0);
    $('#breakdown_cnc_id').val(allCncIds.join(','));  // comma-separated
    $("#breakdownModal").modal("show");
});

$("#submitBreakdown").click(function() {
    console.log("Submit Breakdown clicked");
    let duration = parseFloat($("#breakdown_duration").val());
    let reason = $("#breakdown_reason").val();
    let cncIds = $('#breakdown_cnc_id').val();

    console.log("duration:", duration);
    console.log("reason:", reason);
    console.log("cncIds:", cncIds);

    if (!duration || duration < 0.5 || duration > 24) {
        alert("⚠ Please enter a valid breakdown duration between 0.5 and 24 hours.");
        return;
    }

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

    if (!cncIds) {
        alert("No active tables found.");
        return;
    }

    $.ajax({
        url: frontEndURL + "/machine_tab/index?page=ajax_actions_cnc&action=log_breakdown_cnc",
        method: "POST",
        data: {
            machine_id: machine_id,
            cnc_machine_table_id: cncIds,
            action_type: "breakdown",
            breakdown_reason: reason,
            breakdown_duration: duration
        },
        success: function(response) {
            console.log("Raw breakdown response:", response);
            console.log("Type:", typeof response);

            // Parse manually if it came back as string
            if (typeof response === 'string') {
                try {
                    response = JSON.parse(response);
                } catch(e) {
                    console.error("JSON parse error:", e);
                    console.error("Raw text was:", response);
                    alert("Server returned invalid JSON. Check console for raw response.");
                    return;
                }
            }

            if (response.success) {
                $("#breakdownModal").modal("hide");
                alert("✅ " + (response.message || "Breakdown logged successfully!"));
                location.reload();
            } else {
                alert("❌ Error: " + response.message);
            }
        },
        error: function(xhr, status, error) {
            console.error("AJAX Error:", error);
            console.error("Status:", status);
            console.error("Response text:", xhr.responseText);
            alert("Server response: " + xhr.responseText.substring(0, 500));
        }
    });
});

// Schedule Break
$("#scheduleBreakAll").click(function() {
    console.log("Schedule Break All clicked");
    $('#break_table_id').val('');
    $('#break_cnc_id').val('');
    $('#scheduleBreakModal').modal('show');
});

$(document).on('change', '#break_reason', function() {
    if ($(this).val() === 'Other') {
        $('#other_reason_group').slideDown();
        $('#other_break_reason').prop('required', true);
    } else {
        $('#other_reason_group').slideUp();
        $('#other_break_reason').prop('required', false);
    }
});

$('#submitScheduleBreak').click(function() {
    console.log("Submit Schedule Break clicked");
    const duration = parseFloat($('#break_duration').val());
    let reason = $('#break_reason').val();
    const tableId = $('#break_table_id').val();
    const cncId = $('#break_cnc_id').val();
    
    if (!duration || duration < 0.5 || duration > 10) {
        alert('⚠ Please enter a valid duration between 0.5 and 10 hours.');
        return;
    }
    
    if (!reason) {
        alert('⚠ Please select a break reason.');
        return;
    }
    
    if (reason === 'Other') {
        const otherReason = $('#other_break_reason').val().trim();
        if (!otherReason) {
            alert('⚠ Please specify the break reason.');
            return;
        }
        reason = otherReason;
    }

    // If tableId is empty, schedule break for all tables
    if (!tableId) {
        scheduleBreakForAllTables(duration, reason);
    } else {
        scheduleBreakForSingleTable(tableId, cncId, duration, reason);
    }
});

function scheduleBreakForSingleTable(tableId, cncId, duration, reason) {
    console.log("Scheduling break for single table", tableId);
    let workOrderId, partId;
    
    if (cncMachineTableId) {
        workOrderId = <?= isset($workOrderId) ? $workOrderId : 0 ?>;
        partId = <?= isset($partId) ? $partId : 0 ?>;
    } else {
        const orders = tableOrdersByTable[tableId];
        if (!orders || orders.length === 0) {
            alert("No order found for this table");
            return;
        }
        const currentOrder = orders[currentIndex[tableId] || 0];
        workOrderId = currentOrder.work_order_id;
        partId = currentOrder.part_id;
    }

    $.ajax({
        url: frontEndURL + "/machine_tab/index?page=ajax_actions_cnc&action=log_action_cnc",
        method: "POST",
        data: {
            work_order_id: workOrderId,
            part_id: partId,
            table_id: tableId,
            cnc_machine_table_id: cncId,
            machine_id: machine_id,
            action_type: "break",
            break_duration: duration,
            break_reason: reason
        },
        dataType: "json",
        success: function(response) {
            console.log("Schedule break response:", response);
            if (response.success) {
                $('#scheduleBreakModal').modal('hide');
                alert('✅ Break scheduled successfully!');
                location.reload();
            } else {
                alert('❌ Error: ' + (response.message || 'Failed to schedule break'));
            }
        },
        error: function(xhr, status, error) {
            console.error("AJAX Error:", error);
            alert('AJAX Error: ' + error);
        }
    });
}

function scheduleBreakForAllTables(duration, reason) {
    console.log("Scheduling break for all tables");
    // Collect all tables
    let allTables = [];
    for (let tableId in tableOrdersByTable) {
        const orders = tableOrdersByTable[tableId];
        if (orders && orders.length > 0) {
            const currentOrder = orders[currentIndex[tableId] || 0];
            allTables.push({
                table_id: tableId,
                work_order_id: currentOrder.work_order_id,
                part_id: currentOrder.part_id,
                cnc_machine_table_id: currentOrder.id,
                machine_id: machine_id
            });
        }
    }

    if (allTables.length === 0) {
        alert('⚠ No active work orders found.');
        return;
    }

    $.ajax({
        url: frontEndURL + "/machine_tab/index?page=ajax_actions_cnc&action=schedule_break_all_tables_cnc",
        method: "POST",
        data: {
            tables: JSON.stringify(allTables),
            duration: duration,
            reason: reason,
            machine_id: machine_id
        },
        dataType: "json",
        success: function(response) {
            console.log("Schedule all break response:", response);
            if (response.success) {
                $('#scheduleBreakModal').modal('hide');
                alert('✅ Break scheduled successfully for all tables!');
                location.reload();
            } else {
                alert('❌ Error: ' + (response.message || 'Failed to schedule break'));
            }
        },
        error: function(xhr, status, error) {
            console.error("AJAX Error:", error);
            alert('AJAX Error: ' + error);
        }
    });
}

// Toggle all tables
$("#toggleAllBtn").click(function() {
    console.log("Toggle all tables clicked");
    // Check current state - if any table is running, pause all; otherwise start all
    let anyRunning = false;
    for (let tableId in tableOrdersByTable) {
        const orders = tableOrdersByTable[tableId];
        if (orders && orders.length > 0) {
            const status = orders[currentIndex[tableId] || 0].machine_status;
            if (status !== 'pause' && status !== 'finish') {
                anyRunning = true;
                break;
            }
        }
    }
    
    const actionType = anyRunning ? "pause" : "start";
    
    if (confirm(`Are you sure you want to ${actionType} all tables?`)) {
        let allWorkOrders = [];
        
        for (let tableId in tableOrdersByTable) {
            const orders = tableOrdersByTable[tableId];
            if (orders && orders.length > 0) {
                const currentOrder = orders[currentIndex[tableId] || 0];
                allWorkOrders.push({
                    tableId: tableId,
                    workOrderId: currentOrder.work_order_id,
                    partId: currentOrder.part_id,
                    cncMachineTableId: currentOrder.id,
                    machineId: machine_id
                });
            }
        }
        
        $.ajax({
            url: frontEndURL + "/machine_tab/index?page=ajax_actions_cnc&action=log_bulk_action_cnc",
            method: "POST",
            data: {
                action_type: actionType,
                work_orders: JSON.stringify(allWorkOrders)
            },
            dataType: "json",
            success: function(response) {
                console.log("Toggle all response:", response);
                if (response.success) {
                    alert(`All tables have been ${actionType}ed successfully!`);
                    location.reload();
                } else {
                    alert("Error: " + response.message);
                }
            },
            error: function(xhr, status, error) {
                console.error("AJAX Error:", error);
                alert("AJAX Error: " + error);
            }
        });
    }
});

// Fullscreen toggle
$('.fullscreen-toggle').click(function() {
    if (!document.fullscreenElement) {
        document.documentElement.requestFullscreen().catch(err => {
            console.error('Error attempting to enable fullscreen:', err);
        });
        $(this).find('i').removeClass('fa-expand-arrows-alt').addClass('fa-compress-arrows-alt');
    } else {
        if (document.exitFullscreen) {
            document.exitFullscreen();
        }
        $(this).find('i').removeClass('fa-compress-arrows-alt').addClass('fa-expand-arrows-alt');
    }
});

$(document).on('fullscreenchange', function() {
    if (!document.fullscreenElement) {
        $('.fullscreen-toggle i').removeClass('fa-compress-arrows-alt').addClass('fa-expand-arrows-alt');
    }
});

// Reset modals on close
$('#scheduleBreakModal').on('hidden.bs.modal', function() {
    $('#break_duration').val('1');
    $('#break_reason').val('');
    $('#other_break_reason').val('');
    $('#other_reason_group').hide();
});

$('#breakdownModal').on('hidden.bs.modal', function() {
    $('#breakdown_duration').val('1');
    $('#breakdown_reason').val('');
});

$('#firstOffModal').on('hidden.bs.modal', function() {
    $('#qc_clock_no').val('');
    $('#qc_comment').val('');
});

// Debug: Check if buttons are bound
$(document).ready(function() {
    console.log("Document ready - Multi-table");
    console.log("Increment buttons:", $(".increment-btn").length);
    console.log("Decrement buttons:", $(".decrement-btn").length);
    console.log("Action buttons:", $(".action-btn").length);
    console.log("First-Off buttons:", $(".firstOffBtn").length);
    console.log("Changeover buttons:", $(".changeoverBtn").length);
    
    // Initialize any data attributes
    for (let tableId in tableOrdersByTable) {
        if (tableOrdersByTable[tableId].length > 0) {
            console.log(`Table ${tableId} has ${tableOrdersByTable[tableId].length} orders`);
        }
    }
});
</script>

<script>
// Changeover Variables
let changeoverInterval = null;
let changeoverStartTime = null;
let currentChangeoverTable = null;
let activeChangeoverData = {};

// Function to show changeover inside table
function showChangeoverInTable(tableId, startTime) {
    const tableDiv = $(`#table-${tableId}`);
    
    // Check if changeover overlay already exists
    if (tableDiv.find('.table-changeover-overlay').length > 0) {
        return;
    }
    
    // Change the Changeover button style to indicate active
    const changeoverBtn = tableDiv.find('.changeoverBtn');
    changeoverBtn.css('animation', 'none');
    changeoverBtn.css('opacity', '0.6');
    changeoverBtn.prop('disabled', true);
    
    // Create overlay HTML with stop button on top right
    const overlayHtml = `
        <div class="table-changeover-overlay" id="changeover-overlay-${tableId}">
            <button class="table-changeover-stop-btn" onclick="stopTableChangeover(${tableId})">
                <i class="fas fa-stop"></i> Stop Changeover
            </button>
            <div class="table-changeover-content">
                <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 10px;">
                    <h4 style="margin: 0;">
                        <i class="fas fa-exchange-alt"></i> CHANGEOVER IN PROGRESS
                    </h4>
                    <span class="changeover-badge">
                        <i class="fas fa-clock"></i> Active
                    </span>
                </div>
                <div class="table-changeover-timer" id="changeover-timer-${tableId}">00:00:00</div>
                <div class="table-changeover-progress">
                    <div class="table-changeover-progress-bar" id="changeover-progress-${tableId}" style="width: 0%"></div>
                </div>
                <div class="table-changeover-info" id="changeover-info-${tableId}"></div>
            </div>
        </div>
    `;
    
    // Append overlay to table
    tableDiv.css('position', 'relative');
    tableDiv.append(overlayHtml);
    
    // Store start time
    if (startTime) {
        changeoverStartTime = new Date(startTime);
    } else {
        changeoverStartTime = new Date();
    }
    
    // Update info
    $(`#changeover-info-${tableId}`).html(`<i class="fas fa-user-clock"></i> Started at: ${changeoverStartTime.toLocaleTimeString()}`);
    
    // Start timer for this table
    startTableChangeoverTimer(tableId);
    
    // Disable all buttons on this table
    disableTableButtons(tableId, true);
    
    // Mark table as having active changeover
    activeChangeoverData[tableId] = {
        active: true,
        startTime: changeoverStartTime
    };
}

// Start timer for specific table
function startTableChangeoverTimer(tableId) {
    // Clear existing interval for this table if any
    if (window[`changeoverInterval_${tableId}`]) {
        clearInterval(window[`changeoverInterval_${tableId}`]);
    }
    
    // Create new interval for this table
    window[`changeoverInterval_${tableId}`] = setInterval(() => {
        updateTableChangeoverTimer(tableId);
    }, 1000);
    
    updateTableChangeoverTimer(tableId);
}

// Update timer for specific table
function updateTableChangeoverTimer(tableId) {
    const overlay = $(`#changeover-overlay-${tableId}`);
    if (overlay.length === 0) return;
    
    if (!activeChangeoverData[tableId] || !activeChangeoverData[tableId].startTime) {
        return;
    }
    
    const now = new Date();
    const elapsed = Math.floor((now - activeChangeoverData[tableId].startTime) / 1000);
    
    const hours = Math.floor(elapsed / 3600);
    const minutes = Math.floor((elapsed % 3600) / 60);
    const seconds = elapsed % 60;
    
    $(`#changeover-timer-${tableId}`).text(
        `${String(hours).padStart(2, '0')}:${String(minutes).padStart(2, '0')}:${String(seconds).padStart(2, '0')}`
    );
    
    // Update progress bar (max 2 hours for changeover)
    const maxSeconds = 2 * 3600;
    const progressPercent = Math.min((elapsed / maxSeconds) * 100, 100);
    $(`#changeover-progress-${tableId}`).css('width', progressPercent + '%');
    
    // Change color based on time
    const progressBar = $(`#changeover-progress-${tableId}`);
    if (elapsed > 7200) {
        progressBar.css('background', '#dc3545');
    } else if (elapsed > 3600) {
        progressBar.css('background', '#ffc107');
    } else {
        progressBar.css('background', '#28a745');
    }
}

// Stop changeover for specific table
function stopTableChangeover(tableId) {
    if (!confirm('⚠️ Are you sure you want to STOP the changeover for Table ' + tableId + '?\n\nThis will resume normal production.')) {
        return;
    }
    
    $.ajax({
        url: frontEndURL + "/machine_tab/index?page=ajax_actions_cnc&action=end_changeover_cnc",
        method: "POST",
        data: {
            machine_id: machine_id,
            table_id: tableId
        },
        dataType: "json",
        success: function(response) {
            console.log("Stop changeover response:", response);
            if (response.success) {
                // Remove overlay from table
                removeChangeoverFromTable(tableId);
                alert("✅ Changeover stopped successfully for Table " + tableId);
                location.reload();
            } else {
                alert("❌ Error stopping changeover: " + (response.message || "Unknown error"));
            }
        },
        error: function(xhr, status, error) {
            console.error("AJAX Error:", error);
            alert("AJAX Error: " + error);
        }
    });
}

// Remove changeover overlay from table
function removeChangeoverFromTable(tableId) {
    const overlay = $(`#changeover-overlay-${tableId}`);
    if (overlay.length) {
        overlay.remove();
    }
    
    // Reset changeover button
    const tableDiv = $(`#table-${tableId}`);
    const changeoverBtn = tableDiv.find('.changeoverBtn');
    changeoverBtn.css('animation', 'pulse-green 2s infinite');
    changeoverBtn.css('opacity', '1');
    changeoverBtn.prop('disabled', false);
    
    // Clear interval
    if (window[`changeoverInterval_${tableId}`]) {
        clearInterval(window[`changeoverInterval_${tableId}`]);
        delete window[`changeoverInterval_${tableId}`];
    }
    
    // Enable buttons
    disableTableButtons(tableId, false);
    
    // Remove from active data
    delete activeChangeoverData[tableId];
}

// Disable/enable table buttons (keep changeover button enabled but styled differently)
function disableTableButtons(tableId, disabled) {
    const tableDiv = $(`#table-${tableId}`);
    
    // Disable all interactive elements except changeover button (it's already handled separately)
    tableDiv.find('.increment-btn').prop('disabled', disabled);
    tableDiv.find('.decrement-btn').prop('disabled', disabled);
    tableDiv.find('.machine-action').prop('disabled', disabled);
    tableDiv.find('.finish-btn').prop('disabled', disabled);
    tableDiv.find('.firstOffBtn').prop('disabled', disabled);
    
    // Change opacity to indicate disabled state
    if (disabled) {
        tableDiv.css('opacity', '0.7');
    } else {
        tableDiv.css('opacity', '1');
    }
}

// changeover button handler
$(document).off('click', '.changeoverBtn').on('click', '.changeoverBtn', function() {
    // Check if button is disabled
    if ($(this).prop('disabled')) {
        return;
    }
    
    console.log("Changeover button clicked");
    const tableId = $(this).data('table');
    
    // Check if changeover already active for this table
    if (activeChangeoverData[tableId] && activeChangeoverData[tableId].active) {
        alert("⚠ Changeover is already in progress for this table!");
        return;
    }
    
    // Check with server if there's an active changeover
    $.ajax({
        url: frontEndURL + "/machine_tab/index?page=ajax_actions_cnc&action=check_active_changeover_cnc",
        method: "POST",
        data: {
            machine_id: machine_id,
            table_id: tableId
        },
        dataType: "json",
        success: function(response) {
            if (response.has_active_changeover) {
                // There's an active changeover, show it in the table
                if (response.changeover_data) {
                    const startTime = response.changeover_data.start_time;
                    showChangeoverInTable(tableId, startTime);
                }
                alert("⚠ Changeover is already in progress for this table!");
                return;
            }
            
            // No active changeover, proceed with clock number prompt
            currentChangeoverTable = tableId;
            
            // Create a styled prompt for clock number
            const clockNo = prompt("🔧 ENTER EMPLOYEE CLOCK NUMBER\n\nPlease enter your clock number to start changeover:");
            if (clockNo && clockNo.trim()) {
                startChangeover(tableId, clockNo.trim());
            }
        },
        error: function(xhr, status, error) {
            console.error("AJAX Error checking changeover:", error);
            // Fallback: allow proceeding
            const clockNo = prompt("🔧 ENTER EMPLOYEE CLOCK NUMBER\n\nPlease enter your clock number to start changeover:");
            if (clockNo && clockNo.trim()) {
                startChangeover(tableId, clockNo.trim());
            }
        }
    });
});

// Function to start changeover
function startChangeover(tableId, clockNo) {
    // Show loading indicator on button
    const btn = $(`#table-${tableId} .changeoverBtn`);
	const cncId = btn.data('cnc-id');
    const originalText = btn.html();
    btn.html('<i class="fas fa-spinner fa-spin"></i> Starting...');
    btn.prop('disabled', true);
    
    $.ajax({
        url: frontEndURL + "/machine_tab/index?page=ajax_actions_cnc&action=start_changeover_cnc",
        method: "POST",
        data: {
            machine_id: machine_id,
            table_id: tableId,
			cnc_machine_table_id: cncId,
            clock_no: clockNo
        },
        dataType: "json",
        success: function(response) {
            console.log("Changeover response:", response);
            if (response.success) {
                // Show changeover overlay in the table
                showChangeoverInTable(tableId, null);
                alert("✅ Changeover started for Table " + tableId);
            } else {
                // Reset button on error
                btn.html(originalText);
                btn.prop('disabled', false);
                alert("❌ " + response.message);
            }
        },
        error: function(xhr, status, error) {
            console.error("AJAX Error:", error);
            // Reset button on error
            btn.html(originalText);
            btn.prop('disabled', false);
            alert("AJAX Error: " + error);
        }
    });
}

// Check for active changeovers on page load
function checkActiveChangeovers() {
    $.ajax({
        url: frontEndURL + "/machine_tab/index?page=ajax_actions_cnc&action=check_active_changeover_cnc",
        method: "POST",
        data: {
            machine_id: machine_id,
            table_id: null  // null = check all tables
        },
        dataType: "json",
        success: function(response) {
            if (response.has_active_changeover && response.changeover_data) {
                // If response returns array of changeovers, handle all
                if (Array.isArray(response.changeover_data)) {
                    response.changeover_data.forEach(function(co) {
                        const tableId = co.table_id;
                        // Don't re-add overlay if already present
                        if ($(`#changeover-overlay-${tableId}`).length === 0) {
                            showChangeoverInTable(tableId, co.start_time);
                        }
                    });
                } else {
                    // Single object fallback
                    const tableId = response.changeover_data.table_id;
                    if ($(`#changeover-overlay-${tableId}`).length === 0) {
                        showChangeoverInTable(tableId, response.changeover_data.start_time);
                    }
                }
            }
        },
        error: function(xhr, status, error) {
            console.error("Error checking active changeovers:", error);
        }
    });
}

// Call on page load
$(document).ready(function() {
    console.log("Document ready - Enhanced Changeover");
    checkActiveChangeovers();
});
</script>

<script>
$(document).on("click", "#breakdownOverBtn", function () {
    let machineId = $(this).data("machine");

    $.ajax({
        url: frontEndURL + "/machine_tab/index?page=ajax_actions_cnc&action=end_breakdown_cnc",
        type: "POST",
        data: {
            machine_id: machineId
        },
        success: function (res) {
            if (res.success) {
                location.reload(); // refresh UI
            } else {
                alert("Failed to end breakdown");
            }
        }
    });
});
</script>