<?php
/**
 * dashboard_assbly.php  (shop-floor tablet dashboard)
 * =====================================================================
 * CHANGES FROM ORIGINAL:
 *
 *   1. calculateAndStoreActualUPH() removed from this file — it was
 *      already CORRECT (session-based: first start to now/last finish,
 *      minus pause/break/breakdown gaps from the real activity log), but
 *      is now the single shared assbly_calculateAndStoreActualUPH() in
 *      assbly_scheduler_lib.php, so it can never disagree with a second
 *      implementation growing elsewhere.
 *
 *   2. Planned/target UPH ($plannedUph) now computed via
 *      assbly_calculateBasicUph() — route-based (operation_time /
 *      parts_per_operation from route_details / set_route_details),
 *      never quantity / total_hours. The old quantity/total_hours
 *      figure drifts every time total_hours changes (breakdown split,
 *      reschedule) even though the true target cycle time hasn't
 *      changed — the same drift bug already fixed in PU/VAC/Assypu.
 *
 *   3. Live-UPH polling JS: removed the SKIP_POLLING list that disabled
 *      AJAX refresh entirely for pause/break/breakdown/finish states —
 *      the same bug found and fixed in the PU, VAC, and Assypu
 *      dashboards. Now polls on every cycle regardless of status.
 *
 *   4. The breakdown check at the top of this file now goes through the
 *      shared assbly_isMachineInBreakdown() instead of a local inline
 *      query, for consistency with the other three modules.
 *
 * NOT CHANGED: getRemainingAssblyRequiredQty() — reviewed carefully
 * (it derives "Req Qty" from the upstream VAC/CNC/PU stage's actual
 * completed output, proportionally scaled, minus what other assbly rows
 * for the same work order have already produced) and found correct on
 * close reading. Left exactly as-is.
 *
 * Everything else in this file (queries, HTML, JS -- changeover timers,
 * bulk-qty count inputs, part/reason selection modals, breakdown modal,
 * schedule-break modal, first-off sign-off, logout) is UNCHANGED from
 * the original.
 * =====================================================================
 */
session_start();
include "config.php";
require_once __DIR__ . '/assbly_scheduler_lib.php';

if (!isset($_SESSION['engineer_id']) || !isset($_SESSION['machine_id'])) {
    die("Unauthorized access!");
}

$machine_id = intval($_SESSION['machine_id']);
$engineer_id = intval($_SESSION['engineer_id']);
$today = date('Y-m-d');
$assblyMachineTableId = isset($_GET['assbly_id']) ? intval($_GET['assbly_id']) : null;



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

    $sql = "SELECT SUM(quantity) AS total 
            FROM assbly_part_count_log
            WHERE work_order_id = $workOrderId
            AND assbly_machine_table_id = $assblyMachineTableId
            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 getActualStartDate($conn, $workOrderId, $partId) {
    $sql = "SELECT created_at FROM assbly_machine_activity_log 
            WHERE work_order_id = $workOrderId 
            AND part_id = $partId 
            AND action_type = 'start' 
            ORDER BY created_at ASC LIMIT 1";
    $result = $conn->query($sql);
    if ($result->num_rows > 0) {
        $row = $result->fetch_assoc();
        return date('Y-m-d H:i:s', strtotime($row['created_at']));
    }
    return null;
}

function getActualFinishDate($conn, $workOrderId, $partId) {
    $sql = "SELECT created_at FROM assbly_machine_activity_log 
            WHERE work_order_id = $workOrderId 
            AND part_id = $partId 
            AND action_type = 'finish' 
            ORDER BY created_at DESC LIMIT 1";
    $result = $conn->query($sql);
    if ($result->num_rows > 0) {
        $row = $result->fetch_assoc();
        return date('Y-m-d H:i:s', strtotime($row['created_at']));
    }
    return null;
}

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

/**
 * NOT CHANGED — reviewed carefully, found correct. Derives Req Qty from
 * the upstream stage's (VAC/CNC/PU, whichever one actually produced the
 * parent part) real completed output, proportionally scaled by the
 * assbly/parent quantity ratio, minus whatever other assbly rows for the
 * same work order + part have already produced (e.g. remainder rows from
 * a prior breakdown split).
 */
function getRemainingAssblyRequiredQty($conn, $currentManufId) {
    $currentManufId = intval($currentManufId);

    $linkSql = "
        SELECT
            mt_a.part_id       AS mt_a_part_id,
            mt_a.quantity      AS mt_a_quantity,
            mt_a.work_order_id AS work_order_id,
            mt_p.id            AS mt_p_id,
            mt_p.quantity      AS mt_p_quantity
        FROM assbly_machine_table a
        INNER JOIN manufacture_machine_table mt_a
                ON mt_a.id = a.manuf_id
        INNER JOIN manufacture_machine_table mt_p
                ON mt_p.parent_ids    = mt_a.part_id
               AND mt_p.work_order_id = mt_a.work_order_id
        WHERE a.manuf_id = $currentManufId
        LIMIT 1";

    $linkRes = mysqli_query($conn, $linkSql);
    if (!$linkRes || mysqli_num_rows($linkRes) == 0) {
        return null; // no parent-chain link — caller should fall back to planned quantity
    }
    $link = mysqli_fetch_assoc($linkRes);

    $mtAQuantity = floatval($link['mt_a_quantity']);
    $mtAPartId   = intval($link['mt_a_part_id']);
    $workOrderId = intval($link['work_order_id']);
    $mtPId       = intval($link['mt_p_id']);
    $mtPQuantity = floatval($link['mt_p_quantity']);

    // Figure out which upstream stage (VAC / CNC / PU) actually produced mt_p,
    // and how much it has counted as 'ok' so far.
    $stages = [
        ['machine_table' => 'vac_machine_table', 'log_table' => 'vac_part_count_log', 'fk_col' => 'vac_machine_table_id'],
        ['machine_table' => 'cnc_machine_table', 'log_table' => 'cnc_part_count_log', 'fk_col' => 'cnc_machine_table_id'],
        ['machine_table' => 'pu_machine_table',  'log_table' => 'pu_part_count_log',  'fk_col' => 'pu_machine_table_id'],
    ];

    $parentOkQty = 0;
    $stageFound  = false;
    foreach ($stages as $stage) {
        $checkRes = mysqli_query($conn, "SELECT manuf_id FROM {$stage['machine_table']} WHERE manuf_id = $mtPId LIMIT 1");
        if ($checkRes && mysqli_num_rows($checkRes) > 0) {
            $stageFound = true;
            $okRes = mysqli_query($conn, "SELECT COALESCE(SUM(quantity),0) AS ok_qty 
                                          FROM {$stage['log_table']} 
                                          WHERE {$stage['fk_col']} = $mtPId AND type = 'ok'");
            if ($okRes) {
                $parentOkQty = floatval(mysqli_fetch_assoc($okRes)['ok_qty'] ?? 0);
            }
            break; // found the parent's actual stage table — stop checking others
        }
    }

    if (!$stageFound) {
        return null; // no upstream VAC/CNC/PU stage actually produced this part — caller should fall back
    }

    $targetQty = ($mtPQuantity > 0) ? ($mtAQuantity * $parentOkQty / $mtPQuantity) : 0;

    // Already produced by OTHER assbly rows for the same work order/part
    // (e.g. remainder rows created by a prior breakdown split)
    $alreadyDoneRes = mysqli_query($conn, "
        SELECT COALESCE(SUM(l.quantity),0) AS already_done
        FROM assbly_part_count_log l
        INNER JOIN assbly_machine_table a2 ON a2.manuf_id = l.assbly_machine_table_id
        WHERE a2.work_order_id = $workOrderId
          AND a2.part_id       = $mtAPartId
          AND l.type           = 'ok'
          AND a2.manuf_id     <> $currentManufId");
    $alreadyDone = $alreadyDoneRes ? floatval(mysqli_fetch_assoc($alreadyDoneRes)['already_done'] ?? 0) : 0;

    $remaining = max(0, $targetQty - $alreadyDone);
    return round($remaining, 2);
}

$plannedUph       = 0;
$actualUph        = 0;
$borderClass      = "";
$actualStartDate  = "";
$actualFinishDate = "";
$partId           = 0;
$setId            = 0;
$partNumbers      = [];

if ($assblyMachineTableId) {
    $detailSql = " SELECT v.*, won.work_order_name
                    FROM assbly_machine_table v
                    LEFT JOIN work_order_name won 
                        ON won.work_order_id = v.work_order_id 
                       AND won.part_id = v.part_id
                    WHERE v.manuf_id = $assblyMachineTableId 
                      AND v.machine_id = $machine_id ";
    $detailRes = $conn->query($detailSql);
    if ($detailRes && $detailRes->num_rows > 0) {
        $detail            = $detailRes->fetch_assoc();
        $partId            = intval($detail['part_id']);
        $setId             = isset($detail['set_id']) ? intval($detail['set_id']) : 0;
        $assblyMachineTableId = (int)$detail['manuf_id'];
        $workOrderId       = (int)$detail['work_order_id'];
        $partNumbers       = getPartNumbersFromSet($conn, $setId, $partId);

        // Req Qty is driven by the parent stage's actual output (VAC/CNC/PU)
        $reqQty = getRemainingAssblyRequiredQty($conn, $assblyMachineTableId);
         if ($reqQty === null) {
            // No parent-chain link found — fall back to the planned quantity
            $reqQty = (int)$detail['quantity'];
        } else {
            // Round off to a whole unit for display (was returning e.g. 45.33)
            $reqQty = (int)round($reqQty);
        }

        $firstOffSigned = false;
        $checkFirstOff  = "
            SELECT id, signed_at FROM assbly_first_off_signoff
            WHERE work_order_id = $workOrderId
            AND part_id = $partId
            AND assbly_machine_table_id = $assblyMachineTableId
            LIMIT 1
        ";
        $firstOffRes = mysqli_query($conn, $checkFirstOff);
        if ($firstOffRes && mysqli_num_rows($firstOffRes) > 0) {
            $firstOffRow = mysqli_fetch_assoc($firstOffRes);
            $signedAt    = $firstOffRow['signed_at'];

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

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

            $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;
            }
        }

        // FIX: was quantity/total_hours (drifts with reschedule/split).
        // Route-derived via the shared library instead.
        $plannedUph = assbly_calculateBasicUph($conn, $partId, $setId);

        $isSet           = (!empty($setId) && $setId != 0);
        $okCount         = getTotalCounts($conn, $workOrderId, $partId, $assblyMachineTableId, 'ok', $isSet);
        $nokCount        = getTotalCounts($conn, $workOrderId, $partId, $assblyMachineTableId, 'nok', $isSet);
        $quarantineCount = getTotalCounts($conn, $workOrderId, $partId, $assblyMachineTableId, 'quarantine', $isSet);
        // FIX: was a local copy of this exact algorithm; now the shared
        // assbly_calculateAndStoreActualUPH() so it can't diverge from
        // any other caller.
        $actualUph       = assbly_calculateAndStoreActualUPH($conn, $workOrderId, $partId, $machine_id, $assblyMachineTableId);
        $totalMade       = $okCount;
        $actualStartDate = getActualStartDate($conn, $workOrderId, $partId);
        $actualFinishDate = getActualFinishDate($conn, $workOrderId, $partId);

        if ($plannedUph > 0 && $actualUph > 0) {
            $borderClass = ($actualUph >= $plannedUph) ? "border-success" : "border-danger";
        }
    }
}
?>
<?php
// FIX: routed through the shared assbly_isMachineInBreakdown() instead
// of a local inline query, for consistency with CNC/PU/VAC/Assypu.
$isBreakdown = assbly_isMachineInBreakdown($conn, $machine_id);
?>
<style>
.bg-purple { background-color: #9c4893 !important; }
.count-controls {
    display: flex;
    width: 100%;
    height: 70px;
}
.count-controls > * {
    height: 100% !important;
}
.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; }
.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: #ffe5e5;
    border-color: #dc3545;
}
.part-checkbox input:checked ~ label { 
    color: #dc3545; 
    font-weight: 600; 
}
.part-checkbox:not(:has(input:checked)) {
    background-color: #e8fbe8;
    border-color: #28a745;
}
.part-checkbox:not(:has(input:checked)) .form-check-label {
    color: #28a745;
    font-weight: 600;
}
.part-checkbox .form-check { display: flex; align-items: center; margin-bottom: 0; }
.part-checkbox * { transition: all 0.2s ease; }
.btn-xl { font-size: 20px; padding: 14px 28px; border-radius: 8px; }
.btn-icon-xl i { font-size: 22px; }

.bulk-qty-wrapper {
    position: relative;
    margin-bottom: 6px;
}
.bulk-qty-input {
    width: 100%;
    font-size: 26px !important;
    font-weight: bold !important;
    height: 58px !important;
    text-align: center;
    border-radius: 6px 6px 0 0 !important;
    border-bottom: none !important;
}
.bulk-qty-input.ok-input    { border: 2px solid #28a745 !important; color: #28a745; }
.bulk-qty-input.nok-input   { border: 2px solid #dc3545 !important; color: #dc3545; }
.bulk-qty-input.q-input     { border: 2px solid #ffc107 !important; color: #856404; }
.bulk-qty-label {
    display: block;
    text-align: center;
    font-size: 11px;
    font-weight: 600;
    letter-spacing: 1px;
    text-transform: uppercase;
    padding: 2px 0 4px;
    border-radius: 0 0 4px 4px;
    border: 2px solid;
    border-top: none;
    background: #f8f9fa;
}
.bulk-qty-label.ok-label    { border-color: #28a745; color: #28a745; }
.bulk-qty-label.nok-label   { border-color: #dc3545; color: #dc3545; }
.bulk-qty-label.q-label     { border-color: #ffc107; color: #856404; }

/* Qty to log +/- stepper — matches the Assypu dashboard's stepper */
.bulk-qty-stepper {
    display: flex;
    align-items: stretch;
}
.bulk-qty-stepper .bulk-qty-input {
    border-radius: 0 !important;
    flex: 1;
    min-width: 0;
}
.bulk-qty-step {
    flex: 0 0 44px;
    font-size: 22px;
    font-weight: bold;
    border: 2px solid;
    background: #fff;
    cursor: pointer;
    user-select: none;
    display: flex;
    align-items: center;
    justify-content: center;
}
.bulk-qty-step:active { filter: brightness(0.92); }
.bulk-qty-step.step-minus { border-radius: 6px 0 0 0; border-right: none; }
.bulk-qty-step.step-plus  { border-radius: 0 6px 0 0; border-left: none; }

.bulk-qty-step.ok-step    { border-color: #28a745; color: #28a745; }
.bulk-qty-step.nok-step   { border-color: #dc3545; color: #dc3545; }
.bulk-qty-step.q-step     { border-color: #ffc107; color: #856404; }

.co-timer-block { margin-top: 6px; font-size: 12px; line-height: 2; }
.co-elapsed-label { color: #856404; font-weight: 600; }
.co-elapsed { font-family: monospace; font-size: 13px; }
.co-countdown { font-family: monospace; font-size: 13px; font-weight: 600; }
.co-countdown.overdue { color: #dc3545 !important; }
.co-countdown.ontime { color: #28a745 !important; }

.uph-live-badge {
    display: inline-flex;
    align-items: center;
    gap: 5px;
    font-size: 12px;
    font-weight: 500;
    padding: 2px 8px;
    border-radius: 20px;
    vertical-align: middle;
    margin-left: 4px;
}
.uph-live-badge.green  { background: #d4edda; color: #155724; }
.uph-live-badge.red    { background: #f8d7da; color: #721c24; }
.uph-live-badge.loading { background: #e9ecef; color: #6c757d; }
.uph-live-badge .dot {
    width: 7px; height: 7px; border-radius: 50%; flex-shrink: 0;
}
.uph-live-badge.green .dot  { background: #28a745; animation: uph-pulse-green 1.4s ease-in-out infinite; }
.uph-live-badge.red   .dot  { background: #dc3545; animation: uph-pulse-red   1.4s ease-in-out infinite; }
.uph-live-badge.loading .dot { background: #adb5bd; }
@keyframes uph-pulse-green { 0%,100%{opacity:1} 50%{opacity:.3} }
@keyframes uph-pulse-red   { 0%,100%{opacity:1} 50%{opacity:.3} }
.uph-window-note { font-size: 11px; color: #888; margin-left: 5px; }
</style>

<section class="content" style="margin-top:5vh;">
    <div class="container-fluid d-flex justify-content-center">
        <div class="p-3 rounded shadow-sm w-100 <?= $assblyMachineTableId ? $borderClass : '' ?>"
     id="main-card-border"
     style="<?= $assblyMachineTableId ? 'border:9px solid;' : '' ?>">

        <?php if ($assblyMachineTableId): ?>
            <?php
            $detailSql = "
    SELECT a.*, won.work_order_name
    FROM assbly_machine_table a
    LEFT JOIN work_order_name won
        ON won.work_order_id = a.work_order_id
       AND won.part_id = a.part_id
    WHERE a.manuf_id = $assblyMachineTableId
      AND a.machine_id = $machine_id
      AND a.part_id = $partId
";
            $detailRes = $conn->query($detailSql);
            if ($detailRes->num_rows > 0) {
                $detail       = $detailRes->fetch_assoc();
                $partId       = $detail['part_id'];
                $assbly_machine_table_id = $detail['manuf_id'];
                $workOrderId  = $detail['work_order_id'];
                $setId        = isset($detail['set_id']) ? intval($detail['set_id']) : 0;

                $statusSql = "SELECT action_type 
                              FROM assbly_machine_activity_log 
                              WHERE work_order_id = $workOrderId 
                              AND part_id = $partId 
                              ORDER BY created_at DESC LIMIT 1";
                $statusRes  = $conn->query($statusSql);
                $lastStatus = $statusRes->num_rows > 0 ? $statusRes->fetch_assoc()['action_type'] : null;

                if (!$lastStatus) {
                    $createdOn = date('Y-m-d H:i:s');
                    $start     = "start";
                    $insertSql = "
                        INSERT INTO assbly_machine_activity_log 
                        (work_order_id, part_id, machine_id, engineer_id, assbly_machine_table_id, action_type, created_at)
                        VALUES ($workOrderId, $partId, $machine_id, $engineer_id, $assbly_machine_table_id, '$start', '$createdOn')
                    ";
                    $conn->query($insertSql);
                    $lastStatus      = "start";
                    $actualStartDate = $createdOn;
                }

                $badgeClass = [
                    "start"     => "badge bg-success",
                    "pause"     => "badge bg-warning",
                    "break"     => "badge bg-info",
                    "breakdown" => "badge bg-danger",
                    "finish"    => "badge bg-primary"
                ];
            ?>
                <div class="card shadow-sm">
                    <div class="card" style="margin-bottom: 0rem;">
                        <div class="card-header w-100 d-flex justify-content-between align-items-center py-3">
                            <button id="backBtn" class="btn btn-secondary btn-xl btn-icon-xl">
                                <i class="fas fa-arrow-left mr-2"></i> Back
                            </button>

                            <span class="<?= $badgeClass[$lastStatus] ?? 'badge bg-secondary'; ?> px-3 py-1 mx-auto">
                                <i class="fas fa-circle mr-1"></i> <?= ucfirst($lastStatus); ?>
                            </span>

                            <div>
                                <?php if (!in_array($lastStatus, ["pause", "break", "breakdown", "finish"])): ?>
                                    <button class="btn btn-warning btn-xl btn-icon-xl action-btn"
                                            data-action="pause" style="min-width:180px;">
                                        <i class="fas fa-pause-circle me-2"></i> Pause
                                    </button>
                                <?php endif; ?>

                                <?php if (!$firstOffSigned): ?>
                                    <button class="btn btn-dark btn-xl btn-icon-xl"
                                            id="firstOffBtn" style="min-width:200px;">
                                        <i class="fas fa-stamp me-2"></i> First-Off Sign-Off
                                    </button>
                                <?php else: ?>
                                    <span class="badge bg-success px-3 py-2">
                                        <i class="fas fa-check"></i> First-Off Approved
                                    </span>
                                <?php endif; ?>

                                <button class="btn btn-info btn-xl btn-icon-xl action-btn"
                                        data-action="pdf" style="min-width:180px;">
                                    <i class="fas fa-file-pdf me-2"></i> SER PDF
                                </button>

                                <?php
                                if (!empty($setId) && $setId != 0) {
                                    $sql = "SELECT document_upload FROM set_route_details WHERE set_id = '$setId'";
                                    $dir = "../admin/set_route_documents/";
                                } else {
                                    $sql = "SELECT document_upload FROM route_details WHERE item_id = '$partId'";
                                    $dir = "../admin/route_documents/";
                                }
                                $result_edit = mysqli_query($conn, $sql);
                                if ($result_edit && mysqli_num_rows($result_edit) > 0) {
                                    $row_edit        = mysqli_fetch_assoc($result_edit);
                                    $document_upload = $row_edit['document_upload'];
                                } else {
                                    $document_upload = "";
                                }
                                $ext = strtolower(pathinfo($document_upload, PATHINFO_EXTENSION));
                                if (!empty($document_upload) && $ext === 'pdf') {
                                    $image_path = '<a href="'.$dir.$document_upload.'" target="_blank">
                                        <span class="primary text-primary" title="'.$document_upload.'">'
                                        . utility::ellipsis($document_upload, 20) .
                                        '</span></a>';
                                } else {
                                    $image_path = '<img style="width:100px;border:1px solid #777" src="'.$dir.'no-image.gif">';
                                }
                                ?>

                                <button type="button" class="btn btn-secondary btn-sm py-3 ml-2 fullscreen-toggle hide">
                                    <i class="fas fa-expand-arrows-alt"></i>
                                </button>
                            </div>
                        </div>
                    </div>

                    <div class="card-body">
                        <h6 class="text-center mb-1" style="color:#212529;">
                            <i class="fas fa-clipboard-list mr-2"></i><?= $detail['work_order_name']; ?>
                        </h6>

                        <div class="row mb-1">
                            <div class="col-12">
                                <div class="card border-0 shadow-sm">
                                    <div class="card-body partinfoBox" style="color:black; padding:15px;">
                                        <div class="mb-2 d-flex align-items-center">
											<div>
												<strong>Part Number:</strong>
												<?php
												if (!empty($partNumbers)) {
													$partDisplay = implode(", ", array_column($partNumbers, 'part_number'));
													echo htmlspecialchars($partDisplay);
												} else {
													echo htmlspecialchars($detail['product_name']);
												}
												?>
											</div>

											<div class="ml-4">
												<strong>Req Qty:</strong>
												<?= $reqQty; ?>
											</div>
										</div>
                                        <div class="mb-0">
                                            <strong>Description:</strong> <?= htmlspecialchars($detail['product_name']); ?>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <div class="row mb-1">
                            <div class="col-md-8">
                                <div class="row">

                                    <div class="col-md-4 mb-3">
                                        <div class="bulk-qty-wrapper">
                                            <div class="bulk-qty-stepper">
                                                <button type="button" class="bulk-qty-step ok-step step-minus" data-step="-1" data-target="ok_bulk_qty">−</button>
                                                <input type="number"
                                                       id="ok_bulk_qty"
                                                       value="1"
                                                       min="1"
                                                       max="9999"
                                                       class="form-control bulk-qty-input ok-input"
                                                       placeholder="Qty">
                                                <button type="button" class="bulk-qty-step ok-step step-plus" data-step="1" data-target="ok_bulk_qty">+</button>
                                            </div>
                                            <span class="bulk-qty-label ok-label">Qty to log</span>
                                        </div>
                                        <button type="button"
                                                class="btn btn-success count-btn increment-btn w-100 br-0 f-w-b"
                                                data-type="ok"
                                                style="height:190px; font-size:48px; font-weight:bold;">
                                            OK
                                        </button>
                                    </div>

                                    <div class="col-md-4 mb-3">
                                        <div class="bulk-qty-wrapper">
                                            <div class="bulk-qty-stepper">
                                                <button type="button" class="bulk-qty-step nok-step step-minus" data-step="-1" data-target="nok_bulk_qty">−</button>
                                                <input type="number"
                                                       id="nok_bulk_qty"
                                                       value="1"
                                                       min="1"
                                                       max="9999"
                                                       class="form-control bulk-qty-input nok-input"
                                                       placeholder="Qty">
                                                <button type="button" class="bulk-qty-step nok-step step-plus" data-step="1" data-target="nok_bulk_qty">+</button>
                                            </div>
                                            <span class="bulk-qty-label nok-label">Qty to log</span>
                                        </div>
                                        <button type="button"
                                                class="btn btn-danger count-btn increment-btn w-100 br-0 f-w-b"
                                                data-type="nok"
                                                id="nokBtn"
                                                style="height:190px; font-size:48px; font-weight:bold;">
                                            NOK
                                        </button>
                                    </div>

                                    <div class="col-md-4 mb-3">
                                        <div class="bulk-qty-wrapper">
                                            <div class="bulk-qty-stepper">
                                                <button type="button" class="bulk-qty-step q-step step-minus" data-step="-1" data-target="quarantine_bulk_qty">−</button>
                                                <input type="number"
                                                       id="quarantine_bulk_qty"
                                                       value="1"
                                                       min="1"
                                                       max="9999"
                                                       class="form-control bulk-qty-input q-input"
                                                       placeholder="Qty">
                                                <button type="button" class="bulk-qty-step q-step step-plus" data-step="1" data-target="quarantine_bulk_qty">+</button>
                                            </div>
                                            <span class="bulk-qty-label q-label">Qty to log</span>
                                        </div>
                                        <button type="button"
                                                class="btn btn-warning count-btn increment-btn w-100 br-0 f-w-b"
                                                data-type="quarantine"
                                                id="quarantineBtn"
                                                style="height:190px; font-size:48px; font-weight:bold; color:white;">
                                            Q
                                        </button>
                                    </div>

                                </div>
                            </div>

                            <div class="col-md-4">
                                <div class="mb-3">
                                    <div class="count-controls">
                                        <div style="width:20px; height:100px; background-color:#28a745; border-radius:5px 0 0 5px;"></div>
                                        <input type="number" id="ok_count" value="<?= $okCount ?>"
                                               class="form-control text-center br-0" readonly
                                               style="flex:1; font-size:48px; font-weight:bold; height:100px;">
                                        <button type="button" class="btn undoBtn count-btn decrement-btn br-0 f-w-b"
                                                data-type="ok" style="width:100px; height:100px; font-size:18px; font-style:italic;">
                                            Undo
                                        </button>
                                    </div>
                                </div>
                                <div class="mb-3">
                                    <div class="count-controls">
                                        <div style="width:20px; height:100px; background-color:#dc3545; border-radius:5px 0 0 5px;"></div>
                                        <input type="number" id="nok_count" value="<?= $nokCount ?>"
                                               class="form-control text-center br-0" readonly
                                               style="flex:1; font-size:48px; font-weight:bold; height:100px;">
                                        <button type="button" class="btn undoBtn count-btn decrement-btn br-0 f-w-b"
                                                data-type="nok" style="width:100px; height:100px; font-size:18px; font-style:italic;">
                                            Undo
                                        </button>
                                    </div>
                                </div>
                                <div class="mb-3">
                                    <div class="count-controls">
                                        <div style="width:20px; height:100px; background-color:#ffc107; border-radius:5px 0 0 5px;"></div>
                                        <input type="number" id="quarantine_count" value="<?= $quarantineCount ?>"
                                               class="form-control text-center br-0" readonly
                                               style="flex:1; font-size:48px; font-weight:bold; height:100px;">
                                        <button type="button" class="btn undoBtn count-btn decrement-btn br-0 f-w-b"
                                                data-type="quarantine" style="width:100px; height:100px; font-size:18px; font-style:italic;">
                                            Undo
                                        </button>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <div class="row">
                            <div class="col-md-6 mb-3 mb-md-0">
                                <table class="status-table">
                                    <tr>
                                        <td style="color:black;"><strong>Total Made:</strong></td>
                                        <td style="color:black;"><span class="h5 mb-0" id="total-made"><?= $totalMade ?></span> / <?= $detail['quantity']; ?></td>
                                    </tr>
                                    <tr>
                                        <td style="color:black;"><strong>Target UPH:</strong></td>
                                        <td style="color:black;"><span class="h5 mb-0" id="planned-uph-display"><?= $plannedUph ?></span></td>
                                    </tr>
                                    <tr>
										<td style="color:black;">
											<strong>Actual UPH</strong>
											<span id="uph-live-badge" class="uph-live-badge loading">
												<span class="dot"></span>
												<span id="uph-badge-label">…</span>
											</span>
										</td>
										<td>
											<span class="h5 mb-0" id="actual-uph-display"
												  style="transition: color .4s; <?= ($actualUph >= $plannedUph) ? 'color:#28a745;' : 'color:#dc3545;' ?>">
												<?= $actualUph ?>
											</span>
											<span class="uph-window-note" id="uph-window-note"
												  title="Units produced ÷ active minutes in the last 60 min">
												(last <span id="uph-window-val">60</span> min)
											</span>
										</td>
									</tr>
                                </table>
                            </div>
                            <div class="col-md-6">
                                <div class="row">
                                    <?php if ($lastStatus === "finish"): ?>
                                        <div class="col-12 mb-2">
                                            <button class="btn btn-primary w-100 py-3" disabled>
                                                <i class="fas fa-check-circle mr-2"></i> Work Order Completed
                                            </button>
                                        </div>
                                    <?php elseif (in_array($lastStatus, ["pause", "break", "breakdown"])): ?>
                                        <div class="col-12 mb-2">
                                            <button class="btn btn-success w-100 py-3 action-btn" data-action="start">
                                                <i class="fas fa-play-circle mr-2"></i> Resume Work
                                            </button>
                                        </div>
                                    <?php else: ?>
                                        <div class="col-md-4 mb-2">
                                            <button class="btn action-btn" data-action="finish"
                                                    style="background-color:#9c4893; color:white; width:100%; padding:20px; font-size:14px; border-radius:8px;">
                                                <i class="fas fa-check-circle" style="display:block; font-size:24px; margin-bottom:5px;"></i>
                                                <strong>Finish</strong><br>Work Order
                                            </button>
                                        </div>
                                        <div class="col-md-4 mb-2">
                                            <button class="btn btn-info action-btn" data-action="break"
                                                    style="width:100%; padding:20px; font-size:14px; border-radius:8px;">
                                                <i class="fas fa-coffee" style="display:block; font-size:24px; margin-bottom:5px;"></i>
                                                <strong>Schedule</strong><br>Break
                                            </button>
                                        </div>
                                        <div class="col-md-4 mb-2">
                                            <button id="breakdownBtn" class="btn btn-danger"
                                                    style="width:100%; padding:20px; font-size:14px; border-radius:8px;">
                                                <i class="fas fa-exclamation-triangle" style="display:block; font-size:24px; margin-bottom:5px;"></i>
                                                <strong>Machine</strong><br>Breakdown
                                            </button>
                                        </div>
                                    <?php endif; ?>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            <?php
            } else {
                echo "<p class='text-danger'>Work order not found.</p>";
            }
            ?>

        <?php else: ?>
            <?php
            $sql = "SELECT 
                v.id,v.manuf_id,
                v.part_id,
                v.work_order_id,
                v.product_name,
                v.start_date,
                v.quantity,
                v.end_date,
                c.id AS changeover_id,
                c.start_time AS changeover_start,
                c.end_time AS changeover_end,
                c.duration_seconds
            FROM assbly_machine_table v
            LEFT JOIN assbly_machine_changeover c
                ON c.id = (
                    SELECT c2.id
                    FROM assbly_machine_changeover c2
                    WHERE c2.work_order_table_id = v.manuf_id
                      AND c2.machine_id = v.machine_id
                    ORDER BY c2.end_time DESC
                    LIMIT 1
                )
            WHERE v.machine_id = $machine_id
            AND v.is_break = 0 
            AND v.finished = 0
            ORDER BY v.start_date ASC";

            $res = $conn->query($sql);
            ?>

            <div class="card shadow-sm">
                <?php if ($isBreakdown): ?>
                    <div class="alert alert-danger d-flex justify-content-between align-items-center mb-3">
                        <div>
                            <strong>⚠ MACHINE BREAKDOWN</strong><br>
                            Machine is currently stopped
                        </div>
                        <button id="breakdownOverBtn" class="btn btn-success">
                            Machine Breakdown Over
                        </button>
                    </div>
                <?php endif; ?>

                <div class="card-header bg-purple text-white py-3 d-flex align-items-center">
                    <div>
                        <?php
							$rcSql = "SELECT resource_code FROM station_detail_table WHERE id = $machine_id LIMIT 1";
							$rcRes = $conn->query($rcSql);
							$resource_code_assbly = ($rcRes && $rcRes->num_rows > 0) ? $rcRes->fetch_assoc()['resource_code'] : '';
							?>
							<button id="logoutBtnAssbly"
									data-code="<?= htmlspecialchars($resource_code_assbly, ENT_QUOTES) ?>"
									style="background:#dc3545; color:#fff; border:none; padding:10px 22px;
										   font-size:16px; font-weight:bold; border-radius:6px; cursor:pointer;
										   display:flex; align-items:center; gap:8px; min-width:130px; justify-content:center;">
								<i class="fas fa-sign-out-alt"></i> Log Out
							</button>
							<button type="button" class="btn btn-secondary hide btn-sm py-3 ml-2 fullscreen-toggle">
								<i class="fas fa-expand-arrows-alt"></i>
							</button>
                        <button type="button" class="btn btn-secondary hide btn-sm py-3 ml-2 fullscreen-toggle">
                            <i class="fas fa-expand-arrows-alt"></i>
                        </button>
                    </div>

                    <h5 class="mb-0 mx-auto text-center">
                        <i class="fas fa-list-alt me-2"></i> Upcoming Work Orders
                    </h5>

                    <div style="min-width:160px;"></div>
                </div>

                <div class="card-body p-0">

                    <div id="bigClockSection" style="display:none; background:#1a1a1a; color:#fff; padding:30px 20px; text-align:center; border-bottom:4px solid #ffc107;">
                        <div style="font-size:15px; letter-spacing:3px; text-transform:uppercase; color:#ffc107; margin-bottom:6px;">
                            CHANGEOVER IN PROGRESS
                        </div>
                        <div style="font-size:13px; color:#aaa; margin-bottom:18px;" id="bigClockWoName">—</div>

                        <div style="font-size:11px; letter-spacing:2px; color:#aaa; margin-bottom:4px;">ELAPSED</div>
                        <div id="bigElapsed"
                             style="font-size:90px; font-weight:700; font-family:monospace; letter-spacing:6px; color:#ffc107; line-height:1;">
                            00:00:00
                        </div>
                    </div>

                    <div id="workOrderTableSection">
                        <div class="table-responsive">
                            <table class="table table-hover table-bordered mb-0">
                                <thead class="thead-light">
                                    <tr>
                                        <th>Product Name</th>
                                        <th>Description</th>
                                        <th>Quantity</th>
                                        <th>Start Date</th>
                                        <th>Changeover Duration</th>
                                        <th>Action</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php if ($res->num_rows > 0): ?>
                                        <?php while ($row = $res->fetch_assoc()): ?>
                                            <tr style="cursor:pointer;">
                                                <td onclick="window.location.href='index?page=view_machines_assambly&assbly_id=<?= $row['manuf_id']; ?>'"><?= htmlspecialchars($row['product_name']); ?></td>
                                                <td onclick="window.location.href='index?page=view_machines_assambly&assbly_id=<?= $row['manuf_id']; ?>'"><?= utility::getTableFieldById("item_management", "product_description", "id", $row['part_id']); ?></td>
                                                <td onclick="window.location.href='index?page=view_machines_assambly&assbly_id=<?= $row['manuf_id']; ?>'"><?= $row['quantity']; ?></td>
                                                <td onclick="window.location.href='index?page=view_machines_assambly&assbly_id=<?= $row['manuf_id']; ?>'"><?= $row['start_date']; ?></td>

                                                <td>
                                                    <?php if (!empty($row['duration_seconds'])): ?>
                                                        <?php
                                                            $s = $row['duration_seconds'];
                                                            printf('%02d:%02d:%02d', floor($s/3600), floor(($s%3600)/60), $s%60);
                                                        ?>
                                                    <?php elseif (!empty($row['changeover_start']) && empty($row['changeover_end'])): ?>
                                                        <span style="color:red; font-weight:bold;">Running</span>
                                                    <?php else: ?>
                                                        -
                                                    <?php endif; ?>
                                                </td>

                                                <td onclick="event.stopPropagation()">
                                                    <?php if (!empty($row['changeover_start']) && empty($row['changeover_end'])): ?>
                                                        <button class="btn btn-danger btn-sm"
                                                                onclick="endChangeoverRow(<?= intval($row['changeover_id']) ?>, this)">
                                                            <i class="fas fa-stop me-1"></i> End Changeover
                                                        </button>
                                                        <div class="co-timer-block">
                                                            <div class="co-elapsed-label">
                                                                ⏱ Elapsed:&nbsp;
                                                                <span class="co-elapsed"
                                                                      data-start="<?= strtotime($row['changeover_start']) ?>">
                                                                    00:00:00
                                                                </span>
                                                            </div>
                                                        </div>

                                                    <?php elseif (!empty($row['duration_seconds'])): ?>
                                                        <span class="badge badge-secondary" style="font-size:13px; padding:6px 10px;">
                                                            <i class="fas fa-check me-1"></i>
                                                            <?php
                                                                $s = $row['duration_seconds'];
                                                                printf('%02d:%02d:%02d', floor($s/3600), floor(($s%3600)/60), $s%60);
                                                            ?>
                                                        </span>

                                                    <?php else: ?>
                                                        <button class="btn btn-warning btn-sm"
                                                                onclick="openChangeoverModal(<?= intval($row['manuf_id']) ?>)">
                                                            <i class="fas fa-exchange-alt me-1"></i> Start Changeover
                                                        </button>
                                                    <?php endif; ?>
                                                </td>
                                            </tr>
                                        <?php endwhile; ?>
                                    <?php else: ?>
                                        <tr><td colspan="6" class="text-center py-4">No upcoming work orders found.</td></tr>
                                    <?php endif; ?>
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
            </div>

        <?php endif; ?>
    </div>
</section>

<style>
#partSelectionModal .modal-dialog, #reasonModal .modal-dialog { max-width: 600px; }
#reasonModal .modal-dialog { max-width: 700px; }
.part-checkbox { margin: 12px 0; padding: 25px 20px; border: 2px solid #ddd; border-radius: 6px; transition: all 0.3s ease; cursor: pointer; min-height: 60px; }
#reasonSelection .form-check { margin: 12px 0; padding: 25px 20px; border: 2px solid #ddd; border-radius: 6px; transition: all 0.3s ease; cursor: pointer; min-height: 60px; display: flex; align-items: center; gap: 14px; position: static; }
#reasonSelection .form-check:hover { background-color: #f8f9fa; border-color: #dc3545; }
#reasonSelection .form-check-input { width: 24px; height: 24px; margin-top: 0; margin-right: 12px; cursor: pointer; position: static; margin: 0; flex-shrink: 0; }
#reasonSelection .form-check-label { font-size: 16px; font-weight: 600; cursor: pointer; line-height: 24px; margin: 0; }
#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: 0px; }
#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; }
.modal-footer .btn-xl { font-size: 20px; padding: 12px 30px; min-width: 140px; border-radius: 8px; }
.btn-flash-ok    { animation: flash-ok 0.35s ease forwards; }
.btn-flash-nok   { animation: flash-nok 0.35s ease forwards; }
.btn-flash-quarantine { animation: flash-quarantine 0.35s ease forwards; }
@keyframes flash-ok        { 0%{background-color:#28a745;transform:scale(1)} 30%{background-color:#fff;transform:scale(0.94);box-shadow:0 0 0 4px #28a74566} 100%{background-color:#28a745;transform:scale(1)} }
@keyframes flash-nok       { 0%{background-color:#dc3545;transform:scale(1)} 30%{background-color:#fff;transform:scale(0.94);box-shadow:0 0 0 4px #dc354566} 100%{background-color:#dc3545;transform:scale(1)} }
@keyframes flash-quarantine{ 0%{background-color:#ffc107;transform:scale(1)} 30%{background-color:#fff;transform:scale(0.94);box-shadow:0 0 0 4px #ffc10766} 100%{background-color:#ffc107;transform:scale(1)} }
</style>

<!-- 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 btn-xl" data-dismiss="modal">Cancel</button>
                <button class="btn btn-dark btn-xl" 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</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 btn-xl" data-dismiss="modal">Cancel</button>
                <button class="btn btn-warning btn-xl" 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;"></div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary btn-xl" data-dismiss="modal">Cancel</button>
                <button type="button" class="btn btn-warning btn-xl" 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
                    <span id="bulkQtyDisplay"></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">
                <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 btn-xl" id="backToParts">Back</button>
                <button class="btn btn-danger btn-xl" 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>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary btn-xl" data-dismiss="modal">Cancel</button>
                <button type="button" class="btn btn-danger btn-xl" id="submitBreakdown">Submit</button>
            </div>
        </div>
    </div>
</div>

<!-- Schedule Break Modal -->
<div class="modal fade" id="scheduleBreakModal" tabindex="-1">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content">
            <div class="modal-header bg-warning">
                <h5 class="modal-title"><i class="fas fa-coffee mr-2"></i> Start Break</h5>
                <button type="button" class="close" data-dismiss="modal">&times;</button>
            </div>
            <div class="modal-body">
                <div class="form-group">
                    <label><b>Break Type</b></label>
                    <select id="breakType" class="form-control">
                        <option value="">-- Select Break --</option>
                        <option value="20">EARLY BREAK (20 mins)</option>
                        <option value="30">LUNCH BREAK (30 mins)</option>
                        <option value="custom">OTHER</option>
                    </select>
                </div>
                <div class="form-group mt-3">
                    <label><b>Duration (Minutes)</b></label>
                    <input type="text" id="breakDuration" class="form-control" placeholder="Auto-filled" readonly>
                </div>
                <div class="form-group mt-3">
                    <label><b>Remarks (Optional)</b></label>
                    <textarea id="breakRemarks" class="form-control" rows="2" placeholder="Enter remarks..."></textarea>
                </div>
            </div>
            <div class="modal-footer justify-content-center" style="gap:15px;">
                <button class="btn btn-secondary btn-xl" data-dismiss="modal">
                    <i class="fas fa-times mr-1"></i> Cancel
                </button>
                <button class="btn btn-warning btn-xl" id="submitBreak">
                    <i class="fas fa-play mr-1"></i> Start Break
                </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>
    const frontEndURL          = "<?= $frontEndURL; ?>";
    const assblyMachineTableId = <?= (int)$assblyMachineTableId ?>;
    const lastStatus           = "<?= $lastStatus ?? '' ?>";
</script>

<script>
function getBulkQty(type) {
    const inputMap = { ok: '#ok_bulk_qty', nok: '#nok_bulk_qty', quarantine: '#quarantine_bulk_qty' };
    const val = parseInt($(inputMap[type]).val()) || 1;
    return Math.max(1, Math.min(9999, val));
}

$(function () {
    const blockedStatuses = ['pause', 'break', 'breakdown'];
    if (blockedStatuses.includes(lastStatus)) {
        $('.increment-btn, .decrement-btn').prop('disabled', true)
            .addClass('disabled').css({ opacity: 0.5, cursor: 'not-allowed' });
        $('.bulk-qty-input, .bulk-qty-step').prop('disabled', true).css({ opacity: 0.5, pointerEvents: 'none' });
    }

    if (lastStatus === 'finish') {
        $('button').not('#backBtn').prop('disabled', true)
            .addClass('disabled').css({ opacity: 0.5, cursor: 'not-allowed' });
        $('.increment-btn, .decrement-btn, .action-btn').off('click');
        $('.bulk-qty-input, .bulk-qty-step').prop('disabled', true).css({ opacity: 0.5, pointerEvents: 'none' });
        $('#breakdownBtn').off('click');
    }
});

$(document).on('click', '.increment-btn, .decrement-btn', function (e) {
    if (['pause', 'break', 'breakdown'].includes(lastStatus)) {
        e.preventDefault();
        alert('⚠ Resume work before logging OK / NOK / Quarantine');
        return false;
    }
});


['ok', 'nok', 'quarantine'].forEach(function(type) {
    const saved = sessionStorage.getItem('bulk_qty_' + type);
    if (saved) $('#' + type + '_bulk_qty').val(saved);
});

$(document).on('input', '.bulk-qty-input', function () {
    let v = parseInt($(this).val());
    if (isNaN(v) || v < 1) { v = 1; $(this).val(1); }
    if (v > 9999)           { v = 9999; $(this).val(9999); }

    const type = $(this).attr('id').replace('_bulk_qty', '');
    sessionStorage.setItem('bulk_qty_' + type, v);
});

$(document).on('click', '.bulk-qty-step', function () {
    if (['pause', 'break', 'breakdown', 'finish'].includes(lastStatus)) return;

    const $input = $('#' + $(this).data('target'));
    const step   = parseInt($(this).data('step'), 10);
    let v = (parseInt($input.val(), 10) || 1) + step;

    if (v < 1)    v = 1;
    if (v > 9999) v = 9999;

    $input.val(v).trigger('input'); // reuses existing clamp + sessionStorage save logic
});

$('#backBtn').on('click', function () {
    if (['pause', 'break', 'breakdown', 'finish'].includes(lastStatus)) {
        window.location.href = "index?page=view_machines_assambly";
        return;
    }
    $.ajax({
        url: frontEndURL + "/machine_tab/index?page=ajax_actions_assbly&action=log_action_assbly",
        method: "POST",
        data: {
            work_order_id:           <?= $workOrderId ?? 0 ?>,
            part_id:                 <?= $partId ?? 0 ?>,
            assbly_machine_table_id: assblyMachineTableId,
            action_type:             "pause"
        },
        dataType: "json",
        complete: function () {
            window.location.href = "index?page=view_machines_assambly";
        }
    });
});
</script>

<script>
$(function () {
let selectedNokPartIds   = '';
let unselectedNokPartIds = '';
let currentCountType     = null;
let currentBulkQty       = 1;
let partNumbers          = <?php echo json_encode($partNumbers ?? []); ?>;


function buildExpandedParts() {
    let expanded = [];
    partNumbers.forEach(part => {
        let ratio = parseInt(part.ratio) || 1;
        for (let i = 0; i < ratio; i++) {
            expanded.push({
                id: part.id,
                part_number: part.part_number,
                unit_index: i + 1,
                uid: part.id + '_' + i
            });
        }
    });
    return expanded;
}

function populatePartSelection() {
    const partSelection = document.getElementById("partSelection");
    partSelection.innerHTML = '';

    let expanded = buildExpandedParts();

    if (expanded.length <= 1) {
    selectedParts = expanded.map(e => e.id).join(',');
    selectedPartUids = expanded.map(e => e.uid);

    selectedNokPartIds   = selectedParts;
    unselectedNokPartIds = '';

    $("#reasonModal").modal("show");
    return false;
}

    expanded.forEach(item => {
        const label = expanded.filter(e => e.id === item.id).length > 1
            ? `${item.part_number} — unit ${item.unit_index}`
            : item.part_number;

        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="${item.id}"
                       data-uid="${item.uid}"
                       id="part_${item.uid}"
                       checked>
                <label class="form-check-label" for="part_${item.uid}">
                    ${label}
                </label>
            </div>`;
        partDiv.addEventListener('click', function(e) {
            if (e.target.tagName !== 'INPUT') {
                const cb = this.querySelector('input[type="checkbox"]');
                cb.checked = !cb.checked;
            }
        });
        partSelection.appendChild(partDiv);
    });
    return true;
}

    $(document).on('click', '#reasonSelection .form-check', function (e) {
        if (e.target.tagName !== 'INPUT') {
            $(this).find('input[type="radio"]').prop('checked', true);
        }
    });


function checkTargetReached(newOkCount) {

    const requiredQty = <?= (int)$detail['quantity'] ?>;

    if (newOkCount === requiredQty) {

        alert(
            "🎉 TARGET ACHIEVED!\n\n" +
            "Required Quantity: " + requiredQty + "\n" +
            "OK Quantity: " + newOkCount + "\n\n" +
            "The required quantity has now been completed."
        );

    } else if (newOkCount > requiredQty) {

        alert(
            "⚠ TARGET EXCEEDED!\n\n" +
            "Required Quantity: " + requiredQty + "\n" +
            "OK Quantity: " + newOkCount
        );
    }
}
    $(".increment-btn").click(function () {
        const type       = $(this).data("type");
        currentCountType = type;
        currentBulkQty   = getBulkQty(type);

        const flashClass = { ok: 'btn-flash-ok', nok: 'btn-flash-nok', quarantine: 'btn-flash-quarantine' }[type];
        const $btn = $(this);
        $btn.removeClass('btn-flash-ok btn-flash-nok btn-flash-quarantine');
        void $btn[0].offsetWidth;
        $btn.addClass(flashClass);

        if (type === "ok") {
            $.ajax({
                url: frontEndURL + "/machine_tab/index?page=ajax_actions_assbly&action=log_count_assbly",
                method: "POST",
                data: {
                    work_order_id:           <?= $workOrderId ?? 0 ?>,
                    assbly_machine_table_id: assblyMachineTableId,
                    engineer_id:             <?= $engineer_id ?>,
                    machine_id:              <?= $machine_id ?>,
                    part_id:                 <?= $partId ?? 0 ?>,
                    set_id:                  <?= $setId ?? 0 ?>,
                    type:                    type,
                    quantity:                currentBulkQty
                },
                dataType: "json",
                success: function (response) {
                    if (response.success) {
                        const cur = parseInt($(`#${type}_count`).val());
						const newOkCount = cur + currentBulkQty;

						$(`#${type}_count`).val(newOkCount);
						$("#total-made").text(newOkCount);

						checkTargetReached(newOkCount);

						location.reload();
                    } else {
                        alert("Error: " + response.message);
                    }
                },
                error: function (xhr, status, error) {
                    console.error("AJAX Error", status, error, xhr.responseText);
                    alert("AJAX failed. Check console.");
                }
            });
        } else {
            const hasPartSelection = populatePartSelection();
            if (hasPartSelection) {
                $('#bulkQtyDisplay').text('× ' + currentBulkQty);
                $("#partSelectionModal").modal("show");
            }
        }
    });

    $("#proceedToReason").click(function () {
    let checked   = [];
    let unchecked = [];

    document.querySelectorAll('.part-check').forEach(cb => {
        (cb.checked ? checked : unchecked).push({
            part_id: cb.value,
            uid: cb.dataset.uid
        });
    });

    if (checked.length === 0) {
        alert("⚠ Please select at least one part unit.");
        return;
    }

    selectedNokPartIds   = checked.map(c => c.part_id).join(',');
    unselectedNokPartIds = unchecked.map(c => c.part_id).join(',');

    $('#bulkQtyDisplay').text('× ' + currentBulkQty);
    $("#partSelectionModal").modal("hide");
    $("#reasonModal").modal("show");
});

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

$("#submitNok").click(function () {
    let reason = $(".reason-radio:checked").val();
    if (!reason) { alert("⚠ Please select a reason."); return; }

    $.ajax({
        url: frontEndURL + "/machine_tab/index?page=ajax_actions_assbly&action=log_count_assbly",
        method: "POST",
        data: {
            work_order_id:                 <?= $workOrderId ?? 0 ?>,
            engineer_id:                   <?= $engineer_id ?>,
            assbly_machine_table_id:       assblyMachineTableId,
            machine_id:                    <?= $machine_id ?>,
            part_id:                       <?= $partId ?? 0 ?>,
            set_id:                        <?= $setId ?? 0 ?>,
            reason_id:                     reason,
            type:                          currentCountType,
            quantity:                      currentBulkQty,
            nok_q_scrap_part_ids_part_ids: selectedNokPartIds,
            nok_q_ok_part_ids:             unselectedNokPartIds
        },
        dataType: "json",
        success: function (response) {
            if (response.success) {
                $("#reasonModal").modal("hide");
                const cur = parseInt($(`#${currentCountType}_count`).val());
                $(`#${currentCountType}_count`).val(cur + currentBulkQty);
                $("#total-made").text(parseInt($("#total-made").text()) + currentBulkQty);
                location.reload();
                $(".reason-radio, .part-check").prop("checked", false);
                selectedNokPartIds   = '';
                unselectedNokPartIds = '';
                currentBulkQty       = 1;
            } else {
                alert("Error: " + response.message);
            }
        },
        error: function (xhr, status, error) { alert("AJAX Error: " + error); }
    });
});

    $(".decrement-btn").click(function () {
        const type         = $(this).data("type");
        const currentCount = parseInt($(`#${type}_count`).val());
        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_assbly&action=log_count_assbly",
                method: "POST",
                data: {
                    work_order_id:           <?= $workOrderId ?? 0 ?>,
                    engineer_id:             <?= $engineer_id ?>,
                    machine_id:              <?= $machine_id ?>,
                    assbly_machine_table_id: assblyMachineTableId,
                    part_id:                 <?= $partId ?? 0 ?>,
                    set_id:                  <?= $setId ?? 0 ?>,
                    type:                    type,
                    quantity:                -1
                },
                dataType: "json",
                success: function (response) {
                    if (response.success) {
                        $(`#${type}_count`).val(currentCount - 1);
                        $("#total-made").text(parseInt($("#total-made").text()) - 1);
                        location.reload();
                    } else {
                        alert("❌ Error: " + response.message);
                    }
                },
                error: function (xhr, status, error) { alert("AJAX Error: " + error); }
            });
        }
    });

    $(".action-btn").click(function () {
        let action = $(this).data("action");

        if (action === "pdf") {
            let pdfFile = "<?= $document_upload ?? '' ?>";
            let dir     = "<?= $dir ?? '' ?>";
            if (pdfFile) { window.location.href = dir + pdfFile; }
            else { alert("No PDF file available!"); }
            return;
        }

        if (action === "break") {
            $('#scheduleBreakModal').modal('show');
            return;
        }

        if (action === "finish") {

    const okCount     = parseInt($("#ok_count").val());
    const requiredQty = <?= (int)$detail['quantity'] ?>;

    if (okCount < requiredQty) {

        if (!confirm(
            "⚠ Required quantity has NOT been completed.\n\n" +
            "Required Qty : " + requiredQty + "\n" +
            "OK Qty       : " + okCount + "\n\n" +
            "Remaining    : " + (requiredQty - okCount) + "\n\n" +
            "Do you still want to finish this work order?"
        )) {
            return;
        }

    } else if (okCount === requiredQty) {

        if (!confirm(
            "🎉 Target achieved!\n\n" +
            "Required Qty : " + requiredQty + "\n" +
            "OK Qty       : " + okCount + "\n\n" +
            "Finish this work order?"
        )) {
            return;
        }

    } else {

        if (!confirm(
            "⚠ Target exceeded!\n\n" +
            "Required Qty : " + requiredQty + "\n" +
            "OK Qty       : " + okCount + "\n\n" +
            "Finish this work order?"
        )) {
            return;
        }
    }
} else if (!confirm("Are you sure you want to set this work order to " + action + "?")) {
            return;
        }

        $.ajax({
            url: frontEndURL + "/machine_tab/index?page=ajax_actions_assbly&action=log_action_assbly",
            method: "POST",
            data: {
                work_order_id:           <?= $workOrderId ?? 0 ?>,
                part_id:                 <?= $partId ?? 0 ?>,
                assbly_machine_table_id: assblyMachineTableId,
                action_type:             action
            },
            dataType: "json",
            success: function (response) {
                if (response.success) {
                    if (action === "finish") {
                        alert("✅ Work order completed!\n\nTotal parts made: " + parseInt($("#total-made").text()));
                    }
                    location.reload();
                } else {
                    alert("❌ Error: " + response.message);
                }
            },
            error: function (xhr, status, error) { alert("AJAX Error: " + error); }
        });
    });

    $('#scheduleBreakModal').on('hidden.bs.modal', function () {
        $('#breakDuration').val('');
        $('#breakType').val('');
        $('#breakRemarks').val('');
    });

    $("#breakdownBtn").click(function () { $("#breakdownModal").modal("show"); });

    $("#submitBreakdown").click(function () {
        let duration = parseFloat($("#breakdown_duration").val());
        let reason   = $("#breakdown_reason").val();
        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 (confirm("Are you sure you want to log this breakdown?\n\nDuration: " + duration + " hours\nReason: " + $("#breakdown_reason option:selected").text())) {
            $(this).prop('disabled', true).html('<i class="fas fa-spinner fa-spin mr-1"></i> Processing...');
            $.ajax({
                url: frontEndURL + "/machine_tab/index?page=ajax_actions_assbly&action=log_breakdown_assbly",
                method: "POST",
                data: {
                    work_order_id:           <?= $workOrderId ?? 0 ?>,
                    part_id:                 <?= $partId ?? 0 ?>,
                    assbly_machine_table_id: assblyMachineTableId,
                    breakdown_reason:        reason,
                    breakdown_duration:      duration
                },
                dataType: "json",
                success: function (response) {
                    if (response.success) {
                        $("#breakdownModal").modal("hide");
                        alert("✅ " + (response.message || "Breakdown logged successfully!"));
                        window.location.href = frontEndURL + "/machine_tab/index?page=view_machines_assambly&breakdown=1";
                    } else {
                        alert("❌ Error: " + response.message);
                        $("#submitBreakdown").prop('disabled', false).html('Submit');
                    }
                },
                error: function (xhr, status, error) {
                    alert("AJAX Error: " + error);
                    $("#submitBreakdown").prop('disabled', false).html('Submit');
                }
            });
        }
    });
});
</script>

<script>
document.addEventListener("DOMContentLoaded", function () {
    document.getElementById("breakType").addEventListener("change", function () {
        const type          = this.value;
        const durationInput = document.getElementById("breakDuration");
        if (type === "20" || type === "30") {
            durationInput.value    = type;
            durationInput.readOnly = true;
        } else if (type === "custom") {
            durationInput.value    = "";
            durationInput.readOnly = false;
            durationInput.focus();
        } else {
            durationInput.value    = "";
            durationInput.readOnly = true;
        }
    });

document.getElementById("submitBreak").addEventListener("click", function () {
    const type         = document.getElementById("breakType").value;
    const durationMins = parseFloat(document.getElementById("breakDuration").value);
    const remarks       = document.getElementById("breakRemarks").value.trim();

    if (!type) { alert("Please select break type"); return; }
    if (!durationMins || durationMins <= 0) { alert("Enter valid duration"); return; }

    const durationHours = durationMins / 60;

    let reasonLabel;
    if (type === "20") reasonLabel = "EARLY BREAK (20 mins)";
    else if (type === "30") reasonLabel = "LUNCH BREAK (30 mins)";
    else reasonLabel = "OTHER BREAK (" + durationMins + " mins)";
    if (remarks) reasonLabel += " - " + remarks;

    const $btn = $(this);
    $btn.prop("disabled", true).html('<i class="fas fa-spinner fa-spin"></i> Starting...');

    $.ajax({
        url: frontEndURL + "/machine_tab/index?page=ajax_actions_assbly&action=log_action_assbly",
        type: "POST",
        data: {
            action_type:             "break",
            work_order_id:           <?= $workOrderId ?? 0 ?>,
            part_id:                 <?= $partId ?? 0 ?>,
            assbly_machine_table_id: <?= $assblyMachineTableId ?? 0 ?>,
            break_duration:          durationHours,
            break_reason:            reasonLabel
        },
        dataType: "json",
        success: function (res) {
            if (res.success) {
                location.reload();
            } else {
                alert("Error: " + res.message);
                $btn.prop("disabled", false).html('<i class="fas fa-play mr-1"></i> Start Break');
            }
        },
        error: function () {
            alert("AJAX failed");
            $btn.prop("disabled", false).html('<i class="fas fa-play mr-1"></i> Start Break');
        }
    });
});
});
</script>

<script>
const isBreakdown = <?= $isBreakdown ? 'true' : 'false' ?>;
if (isBreakdown) {
    $('.increment-btn, .decrement-btn, .action-btn')
        .prop('disabled', true)
        .css({ opacity: 0.5, cursor: 'not-allowed' });
}

$("#breakdownOverBtn").click(function () {
    if (!confirm("Are you sure machine breakdown is over?")) return;
    $.ajax({
        url: frontEndURL + "/machine_tab/index?page=ajax_actions_assbly&action=end_breakdown_assbly",
        method: "POST",
        dataType: "json",
        success: function (response) {
            if (response.success) { alert("✅ Machine resumed successfully"); location.reload(); }
            else { alert("❌ Error: " + response.message); }
        },
        error: function () { alert("AJAX Error"); }
    });
});
</script>

<script>
$('.fullscreen-toggle').click(function () {
    if (!document.fullscreenElement) {
        document.documentElement.requestFullscreen().catch(err => console.error(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');
    }
});
</script>

<script>
let activeWoTableId = null;

function openChangeoverModal(woTableId) {
    activeWoTableId = woTableId;
    $("#changeover_clock_no").val("");
    $("#changeoverModal").modal("show");
}

$("#submitChangeover").click(function () {
    const clockNo = $("#changeover_clock_no").val().trim();
    if (!clockNo) { alert("Please enter employee clock number"); return; }

    $(this).prop("disabled", true).html('<i class="fas fa-spinner fa-spin"></i> Starting...');

    $.ajax({
        url: frontEndURL + "/machine_tab/index?page=ajax_actions_assbly&action=start_changeover",
        method: "POST",
        data: {
            machine_id:          <?= $machine_id ?>,
            clock_no:            clockNo,
            work_order_table_id: activeWoTableId
        },
        dataType: "json",
        success: function (response) {
            if (response.success) {
                $("#changeoverModal").modal("hide");
                location.reload();
            } else {
                alert("❌ " + response.message);
                $("#submitChangeover").prop("disabled", false).html("Start");
            }
        },
        error: function () {
            alert("AJAX error");
            $("#submitChangeover").prop("disabled", false).html("Start");
        }
    });
});

function endChangeoverRow(changeoverId, btn) {
    if (!confirm("End this changeover?")) return;

    $(btn).prop("disabled", true).html('<i class="fas fa-spinner fa-spin"></i> Ending...');

    $.ajax({
        url: frontEndURL + "/machine_tab/index?page=ajax_actions_assbly&action=end_changeover",
        method: "POST",
        data: {
            machine_id:    <?= $machine_id ?>,
            changeover_id: changeoverId
        },
        dataType: "json",
        success: function (response) {
            if (response.success) {
                location.reload();
            } else {
                alert("❌ " + response.message);
                $(btn).prop("disabled", false).html('<i class="fas fa-stop me-1"></i> End Changeover');
            }
        },
        error: function () {
            alert("AJAX error");
            $(btn).prop("disabled", false).html('<i class="fas fa-stop me-1"></i> End Changeover');
        }
    });
}

function formatDuration(totalSeconds) {
    const h = Math.floor(totalSeconds / 3600);
    const m = Math.floor((totalSeconds % 3600) / 60);
    const s = totalSeconds % 60;
    return String(h).padStart(2, "0") + ":" +
           String(m).padStart(2, "0") + ":" +
           String(s).padStart(2, "0");
}

function syncBigClock(now) {
    const elapsedEl = document.querySelector(".co-elapsed");

    if (!elapsedEl) {
        document.getElementById("bigClockSection").style.display = "none";
        return;
    }

    document.getElementById("bigClockSection").style.display = "block";

    const row    = elapsedEl.closest("tr");
    const woName = row ? (row.cells[0] ? row.cells[0].innerText.trim() : "—") : "—";
    document.getElementById("bigClockWoName").textContent = woName;

    const elapsedDiff = now - parseInt(elapsedEl.dataset.start);
    document.getElementById("bigElapsed").textContent = formatDuration(Math.max(0, elapsedDiff));
}

function tickChangeoverTimers() {
    const now = Math.floor(Date.now() / 1000);

    document.querySelectorAll(".co-elapsed").forEach(function (el) {
        const diff     = now - parseInt(el.dataset.start);
        el.textContent = formatDuration(Math.max(0, diff));
    });

    document.querySelectorAll(".co-countdown").forEach(function (el) {
        const diff = parseInt(el.dataset.end) - now;
        if (diff <= 0) {
            el.textContent = "-" + formatDuration(Math.abs(diff));
            el.classList.remove("ontime");
            el.classList.add("overdue");
        } else {
            el.textContent = formatDuration(diff);
            el.classList.remove("overdue");
            el.classList.add("ontime");
        }
    });

    syncBigClock(now);
}

if (document.readyState === "loading") {
    document.addEventListener("DOMContentLoaded", function () {
        tickChangeoverTimers();
    });
} else {
    tickChangeoverTimers();
}
setInterval(tickChangeoverTimers, 1000);
</script>

<script>
$("#firstOffBtn").click(function () { $("#firstOffModal").modal("show"); });

$("#submitFirstOff").click(function () {
    const qcClockNo = $("#qc_clock_no").val().trim();
    const qcComment = $("#qc_comment").val().trim();
    if (!qcClockNo) { alert("Please enter QC clock number"); return; }

    $.ajax({
        url: frontEndURL + "/machine_tab/index?page=ajax_actions_assbly&action=first_off_signoff",
        method: "POST",
        data: {
            work_order_id:           <?= $workOrderId ?? 0 ?>,
            part_id:                 <?= $partId ?? 0 ?>,
            assbly_machine_table_id: assblyMachineTableId,
            machine_id:              <?= $machine_id ?>,
            qc_clock_no:             qcClockNo,
            qc_comment:              qcComment
        },
        dataType: "json",
        success: function (response) {
            if (response.success) {
                $("#firstOffModal").modal("hide");
                alert("✅ First-Off Approved Successfully");
                location.reload();
            } else {
                alert("❌ " + response.message);
            }
        }
    });
});
</script>
<script>
(function () {
    const WINDOW_MINUTES   = 60;
    const POLL_INTERVAL_MS = 30000;

    if (!assblyMachineTableId) return;

    const winValEl = document.getElementById('uph-window-val');
    if (winValEl) winValEl.textContent = WINDOW_MINUTES;

    // FIX: removed the SKIP_POLLING list ('finish','pause','break',
    // 'breakdown') that previously disabled the live-UPH refresh
    // entirely during those states — the same bug found and fixed in
    // the PU, VAC, and Assypu dashboards. The badge/number now stay
    // live regardless of work-order status; the increment/decrement
    // buttons are still disabled separately during those states, so
    // this doesn't re-enable logging, it only keeps the readout current.

    function fetchLiveUph() {
        fetch(frontEndURL + '/machine_tab/index?page=ajax_actions_assbly&action=get_live_uph_assbly', {
            method: 'POST',
            headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
            body: new URLSearchParams({
                work_order_id:           <?= $workOrderId ?? 0 ?>,
                part_id:                 <?= $partId ?? 0 ?>,
                assbly_machine_table_id: assblyMachineTableId,
                window_minutes:          WINDOW_MINUTES
            })
        })
        .then(function(r) { return r.json(); })
        .then(function(data) {
            if (!data.success) return;
            renderUph(data.live_uph, data.planned_uph, true);
            const noteEl = document.getElementById('uph-window-note');
            if (noteEl) {
                noteEl.title = data.ok_units + ' OK units in ' + data.productive_min + ' min window';
            }
        })
        .catch(function() {});
    }

    function renderUph(liveUph, plannedUph, updateBorder) {
        const isGreen = plannedUph > 0 && liveUph >= plannedUph;
        const colour  = isGreen ? '#28a745' : '#dc3545';

        const numEl = document.getElementById('actual-uph-display');
        if (numEl) {
            numEl.textContent = liveUph;
            numEl.style.color = colour;
        }

        const badge = document.getElementById('uph-live-badge');
        const label = document.getElementById('uph-badge-label');
        if (badge && label) {
            badge.className   = 'uph-live-badge ' + (isGreen ? 'green' : 'red');
            label.textContent = isGreen ? 'on target' : 'below target';
        }

        if (updateBorder) {
            const card = document.getElementById('main-card-border');
            if (card) {
                card.classList.remove('border-success', 'border-danger');
                card.classList.add(isGreen ? 'border-success' : 'border-danger');
            }
        }
    }

    fetchLiveUph();
    setInterval(fetchLiveUph, POLL_INTERVAL_MS);
})();
</script>
<script>
document.getElementById('logoutBtnAssbly').addEventListener('click', function () {
    if (!confirm('Are you sure you want to log out?')) return;

    const machineCode = this.getAttribute('data-code');
    const logoutRedirectUrl = window.location.origin + '/thermotec/machine_tab/index.php?l=2&code=' + encodeURIComponent(machineCode);

    const btn = this;
    btn.disabled = true;
    btn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Logging out...';

    fetch(frontEndURL + '/machine_tab/index?page=ajax_actions_assbly&action=logout_assbly', {
        method: 'POST',
        keepalive: true
    })
    .catch(() => {})
    .finally(() => {
        window.location.href = logoutRedirectUrl;
    });
});
setInterval(function () {
    $.get('keep_alive.php');
}, 300000);
</script>