<?php
/**
 * dashboard_vac.php  (shop-floor tablet dashboard)
 * =====================================================================
 * ALL CHANGES FROM ORIGINAL, IN ONE PLACE:
 *
 *   1. Breakdown check now goes through vac_isMachineInBreakdown() from
 *      vac_scheduler_lib.php — same underlying query
 *      (vac_machine_breakdown_log), now guaranteed to never drift from
 *      the same check used elsewhere, since the admin side now mirrors
 *      breakdown starts/stops into that table too.
 *
 *   2. calculateAndStoreActualUPH() (the local, correct, session-based
 *      UPH algorithm) has been REMOVED from this file and replaced with
 *      calls to the shared vac_calculateAndStoreActualUPH(). This is the
 *      fix for the "Actual UPH disagrees with itself" bug: this file's
 *      version was always correct, but get_live_uph_vac had a SECOND,
 *      different, broken calculation that overwrote it every 30 seconds.
 *      Now there is exactly one algorithm, used both here (page load)
 *      and by the poll (ajax_actions_vac.php), so they can't disagree.
 *
 *   3. $plannedUph now computed via vac_calculateBasicUph() — route-based
 *      (operation_time / parts_per_operation), never quantity/total_hours
 *      (which drifts with setup-hour reassignment, breakdown splits, and
 *      manual splits — none of which reflect how fast the route runs).
 *
 *   4. Live-UPH polling JS: removed the SKIP_POLLING list that disabled
 *      the AJAX refresh for pause/break/breakdown/finish states — same
 *      "only updates on refresh" bug already fixed in the PU module. The
 *      underlying UPH algorithm being fixed (#2) also makes this safe:
 *      the poll no longer produces a noisy, different-looking number
 *      than the page-load render, so there's no reason to hold it back
 *      in any state.
 * =====================================================================
 */
session_start();
include "config.php";
require_once __DIR__ . '/vac_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');
$vacMachineTableId = isset($_GET['vac_id']) ? intval($_GET['vac_id']) : null;

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

    $sql = "SELECT SUM(quantity) AS total
            FROM vac_part_count_log
            WHERE work_order_id = $workOrderId
            AND vac_machine_table_id = $vacMachineTableId
            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 vac_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 vac_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 {
        $partNumbers[] = [
            'id'          => $partId,
            'part_number' => '',
            'ratio'       => 1,
        ];
    }
    return $partNumbers;
}

// FIX: these were previously declared INSIDE the `if ($vacMachineTableId)`
// block, conditionally — hoisted to top-level, unconditional, so this
// file is safe even if it's ever included from a context where that
// branch doesn't execute first.
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;
}

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

if ($vacMachineTableId) {
    $detailSql = " SELECT v.*, won.work_order_name
                    FROM vac_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 = $vacMachineTableId
                      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;
        $vacMachineTableId = (int)$detail['manuf_id'];
        $workOrderId       = (int)$detail['work_order_id'];
        $partNumbers       = getPartNumbersFromSet($conn, $setId, $partId);

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

            $shiftsByDay = vac_getShiftsByDay($conn);

            $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: route-based, quantity-independent — was
        // round($detail['quantity'] / $detail['total_hours'], 2).
        $plannedUph = vac_calculateBasicUph($conn, $partId, $setId);

        $isSet           = (!empty($setId) && $setId != 0);
        $okCount         = getTotalCounts($conn, $workOrderId, $partId, $vacMachineTableId, 'ok', $isSet);
        $nokCount        = getTotalCounts($conn, $workOrderId, $partId, $vacMachineTableId, 'nok', $isSet);
        $quarantineCount = getTotalCounts($conn, $workOrderId, $partId, $vacMachineTableId, 'quarantine', $isSet);

        // FIX: now the shared, single algorithm — was a local duplicate
        // of the same logic that could disagree with the poll.
        $actualUph       = vac_calculateAndStoreActualUPH($conn, $workOrderId, $partId, $machine_id, $vacMachineTableId);

        $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: single shared check, was inline SQL duplicating the same query
// logic that lived in isMachineInBreakdown() elsewhere.
$isBreakdown = vac_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; }
.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 <?= $vacMachineTableId ? $borderClass : '' ?>"
             id="main-card-border"
             style="<?= $vacMachineTableId ? 'border:9px solid;' : '' ?>">

        <?php if ($vacMachineTableId): ?>
            <?php
            $detailsql = "
    SELECT v.*, won.work_order_name
    FROM vac_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 = $vacMachineTableId
      AND v.machine_id = $machine_id
      AND v.part_id = $partId
";
            $detailRes = $conn->query($detailsql);
            if ($detailRes->num_rows > 0) {
                $detail       = $detailRes->fetch_assoc();
                $partId       = $detail['part_id'];
                $vac_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 vac_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 vac_machine_activity_log
                        (work_order_id, part_id, machine_id, engineer_id, vac_machine_table_id, action_type, created_at)
                        VALUES ($workOrderId, $partId, $machine_id, $engineer_id, $vac_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));
                                ?>

                                <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>
                                                <?= (int)$detail['quantity']; ?>
                                            </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">
                                        <button type="button" class="btn btn-success count-btn increment-btn w-100 br-0 f-w-b"
                                                data-type="ok" style="height:250px; font-size:48px; font-weight:bold;">
                                            OK
                                        </button>
                                    </div>
                                    <div class="col-md-4 mb-3">
                                        <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:250px; font-size:48px; font-weight:bold;">
                                            NOK
                                        </button>
                                    </div>
                                    <div class="col-md-4 mb-3">
                                        <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:250px; 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="OK units produced ÷ productive session time (excludes pause/break/breakdown gaps)">
                                                (session avg)
                                            </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 vac_machine_table v
            LEFT JOIN vac_machine_changeover c
                ON c.id = (
                    SELECT c2.id
                    FROM vac_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_vac = ($rcRes && $rcRes->num_rows > 0) ? $rcRes->fetch_assoc()['resource_code'] : '';
                        ?>
                        <button id="logoutBtnVac"
                                data-code="<?= htmlspecialchars($resource_code_vac, 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>
                    </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=dashboard&vac_id=<?= $row['manuf_id']; ?>'"><?= htmlspecialchars($row['product_name']); ?></td>
                                                <td onclick="window.location.href='index?page=dashboard&vac_id=<?= $row['manuf_id']; ?>'"><?= utility::getTableFieldById("item_management", "product_description", "id", $row['part_id']); ?></td>
                                                <td onclick="window.location.href='index?page=dashboard&vac_id=<?= $row['manuf_id']; ?>'"><?= $row['quantity']; ?></td>
                                                <td onclick="window.location.href='index?page=dashboard&vac_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</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(
                        "vac_machine_breakdown_reason", $vac_machine_breakdown_reason, "100%", "Please Select",
                        "id", "code", "vac_machine_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 vacMachineTableId = <?= (int)$vacMachineTableId ?>;
    const lastStatus       = "<?= $lastStatus ?? '' ?>";
</script>

<script>
$(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' });
    }

    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');
        $('#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;
    }
});

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

<script>
$(function () {
    let selectedParts    = [];
    let currentCountType = null;
    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);
        }
    });

    $(".increment-btn").click(function () {
        const type      = $(this).data("type");
        currentCountType = 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_vac&action=log_count_vac",
                method: "POST",
                data: {
                    work_order_id:        <?= $workOrderId ?? 0 ?>,
                    vac_machine_table_id: vacMachineTableId,
                    engineer_id:          <?= $engineer_id ?>,
                    machine_id:           <?= $machine_id ?>,
                    part_id:              <?= $partId ?? 0 ?>,
                    set_id:               <?= $setId ?? 0 ?>,
                    type:                 type,
                    quantity:             1
                },
                dataType: "json",
                success: function (response) {
                    if (response.success) {
                        const cur = parseInt($(`#${type}_count`).val());
                        const newOkCount = cur + 1;
                        const requiredQty = <?= (int)$detail['quantity'] ?>;

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

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

                        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) $("#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(',');

    $("#partSelectionModal").modal("hide");
    $("#reasonModal").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_vac&action=log_count_vac",
        method: "POST",
        data: {
            work_order_id:                 <?= $workOrderId ?? 0 ?>,
            engineer_id:                   <?= $engineer_id ?>,
            vac_machine_table_id:          vacMachineTableId,
            machine_id:                    <?= $machine_id ?>,
            part_id:                       <?= $partId ?? 0 ?>,
            set_id:                        <?= $setId ?? 0 ?>,
            reason_id:                     reason,
            type:                          currentCountType,
            quantity:                      1,
            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 + 1);
                location.reload();
                $(".reason-radio, .part-check").prop("checked", false);
            } else {
                alert("Error: " + response.message);
            }
        }
    });
});

    $(".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_vac&action=log_count_vac",
                method: "POST",
                data: {
                    work_order_id:        <?= $workOrderId ?? 0 ?>,
                    engineer_id:          <?= $engineer_id ?>,
                    machine_id:           <?= $machine_id ?>,
                    vac_machine_table_id: vacMachineTableId,
                    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 = <?= $detail['quantity'] ?? 0 ?>;

            if (okCount < requiredQty) {
                if (!confirm(`Are you sure to finish order?\n\nOK Count: ${okCount}\nRequired: ${requiredQty}\n\nYou need ${requiredQty - okCount} more OK parts.\n\nPress OK to continue or Cancel to stop.`)) {
                    return;
                }
            }

            if (!confirm(`⚠ Are you sure you want to finish this work order?\n\nOK Count: ${okCount}\nRequired: ${requiredQty}`)) {
                return;
            }

            if (!confirm("This will mark the work order as FINISHED.\n\nPress OK to continue or Cancel to go back.")) {
                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_vac&action=log_action_vac",
            method: "POST",
            data: {
                work_order_id:        <?= $workOrderId ?? 0 ?>,
                part_id:              <?= $partId ?? 0 ?>,
                vac_machine_table_id: vacMachineTableId,
                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   = $("#vac_machine_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_vac&action=log_breakdown_vac",
                method: "POST",
                data: {
                    work_order_id:        <?= $workOrderId ?? 0 ?>,
                    part_id:              <?= $partId ?? 0 ?>,
                    vac_machine_table_id: vacMachineTableId,
                    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=dashboard&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_vac&action=log_action_vac",
        type: "POST",
        data: {
            action_type:          "break",
            work_order_id:        <?= $workOrderId ?? 0 ?>,
            part_id:              <?= $partId ?? 0 ?>,
            vac_machine_table_id: <?= $vacMachineTableId ?? 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_vac&action=end_breakdown_vac",
        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_vac&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_vac&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_vac&action=first_off_signoff",
        method: "POST",
        data: {
            work_order_id:        <?= $workOrderId ?? 0 ?>,
            part_id:              <?= $partId ?? 0 ?>,
            vac_machine_table_id: vacMachineTableId,
            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 POLL_INTERVAL_MS = 30000;

    if (!vacMachineTableId) return;

    // FIX: previously skipped polling entirely for
    // ['finish','pause','break','breakdown'] states, re-displaying the
    // frozen page-load value until a full reload -- the same
    // "only updates on refresh" bug fixed in the PU module. Every state
    // now polls; the underlying UPH algorithm fix (see file header, #2)
    // means the poll's answer is always consistent with the page-load
    // value, so there's no risk of it flickering to something different.

    function fetchLiveUph() {
        fetch(frontEndURL + '/machine_tab/index?page=ajax_actions_vac&action=get_live_uph_vac', {
            method: 'POST',
            headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
            body: new URLSearchParams({
                work_order_id:        <?= $workOrderId ?? 0 ?>,
                part_id:              <?= $partId ?? 0 ?>,
                vac_machine_table_id: vacMachineTableId
            })
        })
        .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, session average';
            }
        })
        .catch(function() { /* silent — keeps last displayed value on network error */ });
    }

    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('logoutBtnVac').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_vac&action=logout_vac', {
        method: 'POST',
        keepalive: true
    })
    .catch(() => {})
    .finally(() => {
        window.location.href = logoutRedirectUrl;
    });
});
setInterval(function () {
    $.get('keep_alive.php');
}, 300000);
</script>