<?php
/**
 * dashboard_pu.php  (shop-floor tablet dashboard)
 * =====================================================================
 * ALL CHANGES FROM ORIGINAL, IN ONE PLACE:
 *
 *   1. isMachineInBreakdown() removed; replaced with pu_isMachineInBreakdown()
 *      from pu_scheduler_lib.php — same underlying query
 *      (pu_machine_breakdown_log), now guaranteed to never drift from the
 *      same check used by every other file in the module, since the
 *      admin side now mirrors breakdown starts/stops into that table too.
 *
 *   2. Changeover LEFT JOIN fixed: was comparing c.machine_id (physical,
 *      per how start_changeover_pu writes it) against v.machine_id
 *      (composite/virtual) — these could never be equal for a real row,
 *      so the join silently never matched anything. Now compares against
 *      v.v_machine_id (physical), with c.status = 'running' added so a
 *      task only ever picks up its CURRENT changeover.
 *
 *   3. $originalUph now computed via pu_calculateBasicUph() — route-based
 *      (operation_time / parts_per_operation from route_details /
 *      set_route_details), never quantity / total_hours. total_hours
 *      drifts with setup adjustments, breakdown recompute, and splits;
 *      none of that changes how fast the route itself runs.
 *
 *   4. Live-UPH polling JS: removed the SKIP list that silently disabled
 *      AJAX refresh for any table in pause/break/breakdown/finish state
 *      (i.e. most of a real shift) — that was the actual "only updates on
 *      refresh" bug, since those tables just kept re-displaying whatever
 *      the PHP render computed at last page load. Also exposed the fetch
 *      function as window.refreshUphForTable() and wired it into the
 *      OK/decrement/NOK success handlers, so the number updates the
 *      moment you click instead of waiting up to 30s for the next poll.
 *
 *   5. get_live_uph_pu itself (in ajax_actions_pu.php) had a deeper bug —
 *      its "elapsed hours" was a hard-coded constant, not real elapsed
 *      time — fixed there; this file just consumes the corrected
 *      response, no other change needed on this side for that one.
 * =====================================================================
 */
session_start();
include "config.php";
require_once __DIR__ . '/pu_scheduler_lib.php';

$serverTime = date('Y-m-d H:i:s');
$serverTimestamp = time() * 1000;
$engineer_id = intval($_SESSION['engineer_id']);
$today = date('Y-m-d');
$puMachineTableId = isset($_GET['pu_id']) ? intval($_GET['pu_id']) : null;
$machine_id = intval($_REQUEST['machine_id']);

// ── resource_code for logout redirect ────────────────────────────────────────
$resource_code = '';
$rcSql = "SELECT resource_code FROM station_detail_table WHERE id = $machine_id LIMIT 1";
$rcRes = $conn->query($rcSql);
if ($rcRes && $rcRes->num_rows > 0) {
    $resource_code = $rcRes->fetch_assoc()['resource_code'];
}

// ── 1. COUNT TABLES ──────────────────────────────────────────────────────────
$result = mysqli_query($conn, "
    SELECT COUNT(*) AS table_count
    FROM pu_mapping_tables pm
    JOIN station_detail_table sm ON pm.machine_id = sm.id
    WHERE sm.machine_type = 4 AND sm.id = '$machine_id'
");
$no_of_table = ($row = mysqli_fetch_assoc($result)) ? (int)$row['table_count'] : 1;

// ── 2. BREAKDOWN CHECK ───────────────────────────────────────────────────────
// FIX: single call to the shared, single-source-of-truth check (still
// reads pu_machine_breakdown_log — behaviourally identical, just can no
// longer drift from what every other file checks).
$isBreakdown = pu_isMachineInBreakdown($conn, $machine_id);

// ── 3. BULK-FETCH ALL ORDERS IN ONE QUERY ────────────────────────────────────
$orderRows = [];
if (!$isBreakdown) {
    $sql = "
        SELECT
            v.id AS row_id, v.manuf_id AS id, v.part_id, v.table_id, v.v_machine_id, v.work_order_id,
            v.product_name, v.start_date, v.quantity, v.total_hours,
            v.set_id, v.priority, v.end_date, v.is_break, v.finished,
            v.changeover_pending,
            v.machine_id,
            c.start_time AS changeover_start,
            c.end_time   AS changeover_end,
            c.duration_seconds
        FROM pu_machine_table v
        LEFT JOIN pu_machine_changeover c
               ON c.work_order_table_id = v.manuf_id
              AND c.machine_id = v.v_machine_id
              AND c.status = 'running'
        WHERE v.v_machine_id = $machine_id
          AND v.is_break  = 0
          AND (v.finished = 0 OR (v.finished = 1 AND v.changeover_pending = 1))
        ORDER BY v.table_id, v.priority ASC, v.start_date ASC
    ";
    $res = mysqli_query($conn, $sql);
    while ($r = mysqli_fetch_assoc($res)) $orderRows[] = $r;
}

// ── 4. COLLECT IDS FOR BULK SUB-QUERIES ──────────────────────────────────────
$allPuIds    = array_column($orderRows, 'id');
$allWoIds    = array_unique(array_column($orderRows, 'work_order_id'));
$allPartIds  = array_unique(array_column($orderRows, 'part_id'));
$allSetIds   = array_unique(array_filter(array_column($orderRows, 'set_id')));

// ── 5. BULK: PART COUNTS ─────────────────────────────────────────────────────
$countsByPuId = [];
if ($allPuIds) {
    $puIdList = implode(',', $allPuIds);
    $cRes = mysqli_query($conn, "
        SELECT pu_machine_table_id, part_id, type, COALESCE(SUM(quantity),0) AS total
        FROM pu_part_count_log
        WHERE pu_machine_table_id IN ($puIdList)
          AND type IN ('ok','nok','quarantine')
        GROUP BY pu_machine_table_id, part_id, type
    ");
    while ($r = mysqli_fetch_assoc($cRes)) {
        $countsByPuId[$r['pu_machine_table_id']][$r['part_id']][$r['type']] = (int)$r['total'];
    }
}

// ── 6. BULK: MACHINE LAST STATUS ─────────────────────────────────────────────
$statusByKey = [];
if ($allPuIds) {
    $puIdList = implode(',', $allPuIds);
    $sRes = mysqli_query($conn, "
        SELECT l1.pu_machine_table_id, l1.action_type
        FROM pu_machine_activity_log l1
        INNER JOIN (
            SELECT pu_machine_table_id, MAX(created_at) AS max_at
            FROM pu_machine_activity_log
            WHERE pu_machine_table_id IN ($puIdList)
            GROUP BY pu_machine_table_id
        ) l2 ON l1.pu_machine_table_id = l2.pu_machine_table_id
             AND l1.created_at         = l2.max_at
    ");
    while ($r = mysqli_fetch_assoc($sRes)) {
        $statusByKey[$r['pu_machine_table_id']] = $r['action_type'];
    }
}

// ── 7. BULK: DOCUMENTS ───────────────────────────────────────────────────────
$docByPartId  = [];
$docBySetId   = [];
if ($allPartIds) {
    $pList = implode(',', $allPartIds);
    $dRes  = mysqli_query($conn, "SELECT item_id, document_upload FROM route_details WHERE item_id IN ($pList)");
    while ($r = mysqli_fetch_assoc($dRes)) $docByPartId[$r['item_id']] = $r['document_upload'];
}
if ($allSetIds) {
    $sList = implode(',', $allSetIds);
    $dRes  = mysqli_query($conn, "SELECT set_id, document_upload FROM set_route_details WHERE set_id IN ($sList)");
    while ($r = mysqli_fetch_assoc($dRes)) $docBySetId[$r['set_id']] = $r['document_upload'];
}

// ── 8. BULK: SET PART NUMBERS ────────────────────────────────────────────────
$setPartNumbers = [];
if ($allSetIds) {
    $sList = implode(',', $allSetIds);
    $mRes  = mysqli_query($conn, "
        SELECT smm.set_id, smm.part_id, smm.ratio, im.part_number
        FROM set_mangmnt_mapping smm
        JOIN item_management im ON im.id = smm.part_id
        WHERE smm.set_id IN ($sList)
    ");
    while ($r = mysqli_fetch_assoc($mRes)) {
        $setPartNumbers[$r['set_id']][] = [
            'id'          => $r['part_id'],
            'part_number' => $r['part_number'],
            'ratio'       => intval($r['ratio']) ?: 1,
        ];
    }
}

// ── 9. BULK: FIRST-OFF SIGN-OFF ──────────────────────────────────────────────
$firstOffByPuId = [];
if ($allPuIds) {
    $puIdList = implode(',', $allPuIds);
    $foRes    = mysqli_query($conn, "
        SELECT pu_machine_table_id, signed_at
        FROM pu_first_off_signoff
        WHERE pu_machine_table_id IN ($puIdList)
    ");
    while ($r = mysqli_fetch_assoc($foRes)) {
        $firstOffByPuId[$r['pu_machine_table_id']] = $r['signed_at'];
    }
}

// ── 10. SHIFTS ───────────────────────────────────────────────────────────────
$shiftsByDay = [];
$shiftRes    = mysqli_query($conn, "SELECT * FROM working_hours");
while ($r = mysqli_fetch_assoc($shiftRes)) {
    $shiftsByDay[(int)$r['day_shifts']][] = $r;
}

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) {
        $s = $shift['start_time']; $e = $shift['end_time'];
        if ($s <= $e) { if ($timeOfDay >= $s && $timeOfDay < $e) return $shift['id']; }
        else          { if ($timeOfDay >= $s || $timeOfDay < $e) 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) {
        if ($shift['start_time'] > $shift['end_time'] && $timeOfDay < $shift['end_time'])
            return date('Y-m-d', strtotime($date . ' -1 day'));
    }
    return $date;
}

$tableOrdersJS  = [];
$tableBorders   = [];
$firstOffSignedByTable = [];

foreach ($orderRows as $order) {
    $tableId = $order['table_id'];
    $puId    = $order['id'];
    $partId  = $order['part_id'];
    $setId   = intval($order['set_id']);
    $isSet   = ($setId > 0);

    $okCount         = $countsByPuId[$puId][$partId]['ok']         ?? 0;
    $nokCount        = $countsByPuId[$puId][$partId]['nok']        ?? 0;
    $quarantineCount = $countsByPuId[$puId][$partId]['quarantine'] ?? 0;

    $currentStatus = $statusByKey[$puId] ?? 'pause';

    if ($isSet) {
        $document_upload = $docBySetId[$setId]   ?? '';
        $document_dir    = '../admin/set_route_documents/';
    } else {
        $document_upload = $docByPartId[$partId] ?? '';
        $document_dir    = '../admin/route_documents/';
    }

    $partNumbers  = [];
    $displayParts = [];
    if ($isSet && !empty($setPartNumbers[$setId])) {
        foreach ($setPartNumbers[$setId] as $pn) {
            $partNumbers[] = $pn;
            for ($i = 0; $i < $pn['ratio']; $i++) $displayParts[] = $pn['part_number'];
        }
        $productName = implode(', ', $displayParts);
    } else {
        $productName = $order['product_name'];
    }

    // FIX: route-based, quantity-independent planned UPH. The original
    // `round($order['quantity'] / $order['total_hours'], 2)` drifted every
    // time this work order's total_hours changed for reasons unrelated to
    // actual machine speed (setup_hours, breakdown recompute, split).
    // pu_calculateBasicUph() answers "how fast does this route run" and
    // nothing else, so it stays stable across all of that.
    $originalUph = pu_calculateBasicUph($conn, $partId, $setId);

    $actualUphSql = "SELECT uph FROM pu_part_count_log
                     WHERE work_order_id = {$order['work_order_id']}
                       AND pu_machine_table_id = $puId
                       AND part_id = $partId
                     LIMIT 1";
    $uphRes   = mysqli_query($conn, $actualUphSql);
    $actualUph = ($uphRes && $r = mysqli_fetch_assoc($uphRes)) ? floatval($r['uph']) : 0;

    $borderColor = ($originalUph > 0 && $actualUph > 0)
        ? (($actualUph >= $originalUph) ? 'green' : 'red')
        : 'green';
    $tableBorders[$tableId] = $borderColor;

    $firstOffSigned = false;
    if (isset($firstOffByPuId[$puId])) {
        $signedAt       = $firstOffByPuId[$puId];
        $shiftAtSign    = getShiftForDatetime($shiftsByDay, $signedAt);
        $shiftNow       = getShiftForDatetime($shiftsByDay, date('Y-m-d H:i:s'));
        $dateAtSign     = getShiftStartDate($shiftsByDay, $signedAt);
        $dateNow        = getShiftStartDate($shiftsByDay, date('Y-m-d H:i:s'));
        $firstOffSigned = ($shiftAtSign !== null && $shiftNow !== null
            && $shiftAtSign === $shiftNow && $dateAtSign === $dateNow);
    }
    $firstOffSignedByTable[$tableId] = $firstOffSigned;

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

// ── 12. MACHINE STATUSES (for production clock) ───────────────────────────────
$machineStatuses = [];
foreach ($tableOrdersJS as $tableId => $orders) {
    $machineStatuses[$tableId] = !empty($orders) ? $orders[0]['machine_status'] : 'pause';
}
$shouldRunClock = in_array('start', $machineStatuses);

// ── 13. PRODUCTION CLOCK ─────────────────────────────────────────────────────
$prodDate = ((int)date('H') < 6)
    ? date('Y-m-d', strtotime('-1 day'))
    : date('Y-m-d');

$clockSql = "SELECT * FROM pu_machine_clock_daily
             WHERE machine_id = $machine_id
               AND production_date = '$prodDate'
             LIMIT 1";
$clockRes = mysqli_query($conn, $clockSql);

if ($clockRes && mysqli_num_rows($clockRes) > 0) {
    $clockRow = mysqli_fetch_assoc($clockRes);
} else {
    mysqli_query($conn, "INSERT INTO pu_machine_clock_daily
        (machine_id, production_date, production_seconds, last_start_time, is_running)
        VALUES ($machine_id, '$prodDate', 0, NULL, 0)");
    $clockRow = [
        'production_seconds' => 0,
        'last_start_time'    => null,
        'is_running'         => 0,
    ];
}

if ($shouldRunClock && !$clockRow['is_running']) {
    mysqli_query($conn, "UPDATE pu_machine_clock_daily
        SET is_running = 1, last_start_time = NOW()
        WHERE machine_id = $machine_id AND production_date = '$prodDate'");
    $clockRow['is_running']      = 1;
    $clockRow['last_start_time'] = date('Y-m-d H:i:s');
} elseif (!$shouldRunClock && $clockRow['is_running']) {
    $elapsed = time() - strtotime($clockRow['last_start_time']);
    mysqli_query($conn, "UPDATE pu_machine_clock_daily
        SET production_seconds = production_seconds + $elapsed,
            is_running = 0, last_start_time = NULL
        WHERE machine_id = $machine_id AND production_date = '$prodDate'");
    $clockRow['production_seconds'] += $elapsed;
    $clockRow['is_running']          = 0;
    $clockRow['last_start_time']     = null;
}

$storedSeconds = (int)$clockRow['production_seconds'];
if ($clockRow['is_running'] && $clockRow['last_start_time']) {
    $elapsed        = time() - strtotime($clockRow['last_start_time']);
    $storedSeconds += max(0, $elapsed);
}

// ── Single-order detail ───────────────────────────────────────────────────────
$document_upload = '';
$document_dir    = '../admin/route_documents/';
$ext = $partNumbers = [];
$workOrderId = $partId = $setId = 0;
$detail = null;
if ($puMachineTableId) {
    $detailRes = mysqli_query($conn,
        "SELECT * FROM pu_machine_table WHERE manuf_id = $puMachineTableId AND machine_id = $machine_id LIMIT 1"
    );
    if ($detailRes && $detailRes->num_rows > 0) {
        $detail      = $detailRes->fetch_assoc();
        $partId      = $detail['part_id'];
        $workOrderId = $detail['work_order_id'];
        $setId       = intval($detail['set_id']);
        if ($setId > 0) {
            $document_upload = $docBySetId[$setId]   ?? '';
            $document_dir    = '../admin/set_route_documents/';
            $partNumbers     = $setPartNumbers[$setId] ?? [];
        } else {
            $document_upload = $docByPartId[$partId] ?? '';
            $partNumbers     = [];
        }
        $ext = strtolower(pathinfo($document_upload, PATHINFO_EXTENSION));
    }
}
?>

<style>
.bg-purple { background-color: #9c4893 !important; }
.count-controls { display:flex; align-items:center; width:100%; }
.count-btn { flex:0 0 auto; min-width:80px; }
.count-display { flex:1; max-width:100px; text-align:center; }
.partinfoBox { border:1px solid #9c4893; background:#D9D9D9; padding:.2rem .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 .3s; cursor:pointer; }
.part-checkbox:hover { background:#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:#e7f3ff; border-color:#007bff; }
.part-checkbox .form-check { display:flex; align-items:center; margin-bottom:0; }
.part-checkbox * { transition:all .2s; }
#partSelectionModal .modal-dialog, #reasonModal .modal-dialog { max-width:600px; }
#reasonModal .modal-dialog { max-width:700px; }
.part-checkbox { margin:12px 0; padding:18px 20px; border:2px solid #ddd; border-radius:6px; min-height:60px; }
#reasonSelection .form-check { margin:12px 0; padding:18px 20px; border:2px solid #ddd; border-radius:6px; transition:all .3s; cursor:pointer; min-height:60px; }
#reasonSelection .form-check:hover { background:#f8f9fa; border-color:#dc3545; }
#reasonSelection .form-check-input { width:46px; height:30px; margin-top:0; margin-right:12px; cursor:pointer; }
#reasonSelection .form-check-label { font-size:16px; font-weight:500; cursor:pointer; line-height:24px; }
#reasonSelection .form-check:has(input:checked) { background:#ffe6e6; border-color:#dc3545; }
#reasonSelection .form-check input:checked~label { color:#dc3545; font-weight:600; }
#partSelection, #reasonSelection { max-height:400px !important; overflow-y:auto; }
.reason-item .form-check-label { margin-left:28px; }
#partSelectionModal .form-check { display:flex; align-items:center; gap:12px; position:static; }
#partSelectionModal .form-check-input { position:static; margin:0; flex-shrink:0; }
#partSelectionModal .form-check-label { margin:0; cursor:pointer; }
.machine-table { border:8px solid green; margin:10px 0; padding:0; border-radius:2px; position:relative; }
.table-header { background:#f8f9fa; padding:10px; border-bottom:1px solid #dee2e6; }
.table-body { padding:15px; }
.machine-table.border-success { border-color:green !important; }
.machine-table.border-danger  { border-color:red  !important; }
.table-controls { position:absolute; top:10px; right:10px; }
.btn-group .btn { height:100px; font-size:16px; display:flex; align-items:center; justify-content:center; }
.table-changeover-overlay { position:absolute; top:0; left:0; right:0; bottom:0; background:rgba(0,0,0,.95); z-index:100; border-radius:8px; display:flex; align-items:center; justify-content:center; }
.table-changeover-content { text-align:center; padding:20px; color:white; width:100%; max-width:500px; }
.table-changeover-content h4 { color:#ffc107; margin-bottom:15px; font-size:20px; }
.table-changeover-timer { font-size:48px; font-weight:bold; font-family:monospace; background:rgba(0,0,0,.5); padding:15px; border-radius:10px; margin:15px 0; letter-spacing:2px; }
.table-changeover-progress { width:100%; height:8px; background:rgba(255,255,255,.2); border-radius:4px; overflow:hidden; margin:15px 0; }
.table-changeover-progress-bar { height:100%; background:linear-gradient(90deg,#28a745,#ffc107,#dc3545); border-radius:4px; }
.table-changeover-stop-btn { background:#dc3545; color:white; border:none; padding:8px 20px; font-size:14px; font-weight:bold; border-radius:5px; cursor:pointer; margin-top:10px; position:absolute; top:10px; right:10px; z-index:101; }
.table-changeover-stop-btn:hover { background:#c82333; }
.machine-table { position:relative; overflow:hidden; }
.changeover-active { position:relative; }
.changeover-badge { display:inline-block; background:#dc3545; color:white; padding:2px 8px; border-radius:4px; font-size:12px; margin-left:10px; animation:pulse 1s infinite; }
@keyframes pulse { 0%{opacity:1} 50%{opacity:.6} 100%{opacity:1} }
.changeoverBtn { font-size:16px !important; padding:8px 20px !important; font-weight:bold !important; }
@keyframes flash-ok        { 0%{background-color:#28a745;transform:scale(1)} 25%{background-color:#fff;transform:scale(.93);box-shadow:0 0 0 5px #28a74555} 100%{background-color:#28a745;transform:scale(1);box-shadow:none} }
@keyframes flash-nok       { 0%{background-color:#dc3545;transform:scale(1)} 25%{background-color:#fff;transform:scale(.93);box-shadow:0 0 0 5px #dc354555} 100%{background-color:#dc3545;transform:scale(1);box-shadow:none} }
@keyframes flash-quarantine{ 0%{background-color:#ffc107;transform:scale(1)} 25%{background-color:#fff;transform:scale(.93);box-shadow:0 0 0 5px #ffc10755} 100%{background-color:#ffc107;transform:scale(1);box-shadow:none} }
@keyframes flash-undo      { 0%{background-color:#6c757d;transform:scale(1)} 35%{background-color:#dee2e6;transform:scale(.91)} 100%{background-color:#6c757d;transform:scale(1)} }
.do-flash-ok        { animation:flash-ok         .38s ease forwards; }
.do-flash-nok       { animation:flash-nok        .38s ease forwards; }
.do-flash-quarantine{ animation:flash-quarantine  .38s ease forwards; }
.do-flash-undo      { animation:flash-undo        .28s ease forwards; }
.table-label { font-weight:bold; font-size:30px; }
.uph-live-badge { display:inline-flex; align-items:center; gap:4px; font-size:11px; font-weight:500; padding:2px 7px; 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 1.4s ease-in-out infinite; }
.uph-live-badge.red   .dot   { background:#dc3545; animation:uph-pulse 1.4s ease-in-out infinite; }
.uph-live-badge.loading .dot { background:#adb5bd; }
@keyframes uph-pulse { 0%,100%{opacity:1} 50%{opacity:.3} }

/* ── Break button loading state ── */
#submitScheduleBreak:disabled { opacity:.7; cursor:not-allowed; }

/* ── Finished-pending-changeover banner ── */
.finished-banner {
    font-size: 16px;
    font-weight: bold;
    border-radius: 4px;
}

/* ══════════════════════════════════════════════════════════════════════════
   HEIGHT REDUCTION ONLY — layout stays single column, full-width stacked
   cards. Trims border weight, padding, and label sizes so more cards fit
   on screen before scrolling kicks in.
   ══════════════════════════════════════════════════════════════════════════ */

.machine-table {
    border-width: 4px !important;   /* was 8-10px */
    margin: 6px 0 !important;       /* was 10px 0 */
    border-radius: 4px;
}
.table-header { padding: 6px 12px; }
.table-body   { padding: 8px 12px; }

.table-label { font-size: 22px !important; }   /* was 30px */
.table-header strong { font-size: 15px; line-height: 1.6; }
.qty_req  { font-size: 20px !important; }      /* was 25px */
.uph-live-badge { font-size: 10px; padding: 1px 6px; }

.table-header .btn-lg.firstOffBtn,
.table-header .btn-lg.changeoverBtn {
    padding: 6px 14px !important;
    font-size: 13px !important;
}

/* Control row (OK/NOK/QUAR/Actions) — same col-md-3 layout, just shorter */
.increment-btn { padding: 8px 4px !important; font-size: 14px; }
.py-3 { padding-top: .5rem !important; padding-bottom: .5rem !important; }
.form-control.text-center[readonly] { font-size: 22px !important; padding: 4px; height: auto; }
.decrement-btn { font-size: 12px; padding: 4px 10px; }

/* Actions column: Start/Pause, Finished, Details — kept comfortably tappable */
.btn-group .btn { height: 90px !important; font-size: 15px !important; }
.details-btn.w-100 { height: 64px !important; font-size: 15px; }

/* No-orders placeholder card — match the slimmer chrome */
.machine-table .table-header strong { font-size: 13px; }
</style>

<section class="content" style="margin-top:1vh;">
<div class="container-fluid">

    <!-- ── HEADER ─────────────────────────────────────────────────────────── -->
    <div class="header" style="display:flex;justify-content:space-between;align-items:center;margin-bottom:20px;">

        <!-- LEFT: Logout + Title -->
        <div style="display:flex;align-items:center;gap:15px;">
            <button id="logoutBtn"
                    data-code="<?= htmlspecialchars($resource_code, 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>
            <h2 style="margin:0;">PU Dashboard - <?= htmlspecialchars($resource_code) ?></h2>
        </div>

        <!-- RIGHT: Wall clock + Production clock -->
        <div style="display:flex;align-items:center;gap:20px;">

            <div id="clock" style="font-family:monospace;font-size:18px;color:#2575fc;
                                    padding:4px 10px;border-radius:6px;background:#f0f0f0;
                                    text-align:center;min-width:100px;">00:00:00</div>

            <div style="text-align:center;min-width:180px;">
                <div style="font-size:11px;font-weight:500;letter-spacing:1px;
                            color:var(--color-text-secondary);text-transform:uppercase;margin-bottom:2px;">
                    Production Clock
                </div>
                <div id="productionClock" style="font-family:monospace;font-size:28px;
                                                  font-weight:bold;color:#28a745;line-height:1;">
                    00:00:00
                </div>
                <div id="clockStatusBadge" style="display:inline-block;font-size:11px;font-weight:bold;
                                                   letter-spacing:1px;padding:2px 8px;border-radius:4px;
                                                   margin-top:3px;background:#dc3545;color:#fff;">
                    PAUSED
                </div>
            </div>

        </div>
    </div>

<?php if ($isBreakdown): ?>
    <div class="machine-table text-center" style="border:10px solid red;padding:50px;">
        <h1 style="color:red;">⚠ MACHINE UNDER BREAKDOWN</h1>
        <p>Please resolve the issue before continuing production</p>
        <button id="breakdownOverBtn" class="btn btn-success btn-lg mt-3"
                data-machine="<?= $machine_id ?>">Breakdown Over</button>
    </div>
<?php else: ?>
    <?php for ($t = 1; $t <= $no_of_table; $t++): ?>
        <?php if (!empty($tableOrdersJS[$t])):
            $first             = $tableOrdersJS[$t][0];
            $machineStatus     = $first['machine_status'];
            $borderColor       = $tableBorders[$t] ?? 'green';
            $firstOffSigned    = $first['first_off_signed'] ?? false;
            $changeoverPending = intval($first['changeover_pending'] ?? 0);
        ?>
        <div class="machine-table <?= $borderColor == 'green' ? 'border-success' : 'border-danger' ?>"
             id="table-<?= $t ?>" style="border:4px solid <?= $borderColor ?>;">
            <div class="table-header">
                <div class="row">
                    <div class="col-md-8">
                        <strong>
                            <span class="table-label">Table <?= $t ?> |</span>
                            Part No: <span class="part_name"><?= htmlspecialchars($first['product_name']) ?></span> |
                            UPH: <span class="planned_uph"><?= round($first['original_uph'], 2) ?></span> |
                            Actual UPH: <span class="actual_uph" id="actual-uph-t<?= $t ?>"><?= $first['actual_uph'] ?></span>
                            <span class="uph-live-badge loading" id="uph-badge-t<?= $t ?>">
                                <span class="dot"></span><span class="uph-badge-label">…</span>
                            </span> |
                            <strong>QTY Req:</strong>
                            <span class="qty_req"><?= $first['qty_req'] ?></span> |
                            QTY Good: <span class="qty_good"><?= $first['ok'] ?></span>
                        </strong>
                    </div>
                    <div class="col-md-4 text-right">
                        <?php if (!$firstOffSigned && !$changeoverPending): ?>
                            <button class="btn btn-dark btn-lg firstOffBtn mr-2"
                                    data-table="<?= $t ?>" data-pu-id="<?= $first['id'] ?>">
                                <i class="fas fa-stamp"></i> First-Off
                            </button>
                        <?php elseif ($firstOffSigned && !$changeoverPending): ?>
                            <span class="badge bg-success mr-2"><i class="fas fa-check"></i> Approved</span>
                        <?php endif; ?>
                        <button class="btn btn-warning btn-lg changeoverBtn" data-table="<?= $t ?>">
                            <i class="fas fa-exchange-alt"></i> Changeover
                        </button>
                    </div>
                </div>
            </div>

            <div class="table-body">
                <?php if ($changeoverPending): ?>
                <!-- ── Finished banner — shown when changeover_pending = 1 ── -->
                <div class="finished-banner alert alert-success text-center py-2 mb-3">
                    <i class="fas fa-check-circle"></i>
                    Order Finished — Complete changeover to remove from dashboard
                </div>
                <?php endif; ?>

                <div class="row text-center">
                    <!-- OK -->
                    <div class="col-md-3">
                        <button type="button" class="btn btn-success w-100 increment-btn mb-2 py-3"
                                data-type="ok" data-table="<?= $t ?>" data-pu-id="<?= $first['id'] ?>"
                                <?= ($changeoverPending || in_array($machineStatus, ['pause','break','breakdown'])) ? 'disabled' : '' ?>>OK</button>
                        <div class="input-group">
                            <input type="number" class="form-control text-center ok-count"
                                   value="<?= $first['ok'] ?>" readonly>
                            <div class="input-group-append">
                                <button class="btn btn-outline-secondary decrement-btn" type="button"
                                        data-type="ok" data-table="<?= $t ?>" data-pu-id="<?= $first['id'] ?>"
                                        <?= $changeoverPending ? 'disabled' : '' ?>>Undo</button>
                            </div>
                        </div>
                    </div>
                    <!-- NOK -->
                    <div class="col-md-3">
                        <button type="button" class="btn btn-danger w-100 increment-btn mb-2 py-3"
                                data-type="nok" data-table="<?= $t ?>" data-pu-id="<?= $first['id'] ?>"
                                <?= ($changeoverPending || in_array($machineStatus, ['pause','break','breakdown'])) ? 'disabled' : '' ?>>NOK</button>
                        <div class="input-group">
                            <input type="number" class="form-control text-center nok-count"
                                   value="<?= $first['nok'] ?>" readonly>
                            <div class="input-group-append">
                                <button class="btn btn-outline-secondary decrement-btn" type="button"
                                        data-type="nok" data-table="<?= $t ?>" data-pu-id="<?= $first['id'] ?>"
                                        <?= $changeoverPending ? 'disabled' : '' ?>>Undo</button>
                            </div>
                        </div>
                    </div>
                    <!-- QUAR -->
                    <div class="col-md-3">
                        <button type="button" class="btn btn-warning w-100 increment-btn mb-2 py-3"
                                data-type="quarantine" data-table="<?= $t ?>" data-pu-id="<?= $first['id'] ?>"
                                <?= ($changeoverPending || in_array($machineStatus, ['pause','break','breakdown'])) ? 'disabled' : '' ?>>QUAR</button>
                        <div class="input-group">
                            <input type="number" class="form-control text-center quar-count"
                                   value="<?= $first['quar'] ?>" readonly>
                            <div class="input-group-append">
                                <button class="btn btn-outline-secondary decrement-btn" type="button"
                                        data-type="quarantine" data-table="<?= $t ?>" data-pu-id="<?= $first['id'] ?>"
                                        <?= $changeoverPending ? 'disabled' : '' ?>>Undo</button>
                            </div>
                        </div>
                    </div>
                    <!-- Actions -->
                    <div class="col-md-3">
                        <?php if (!$changeoverPending): ?>
                        <div class="btn-group w-100">
                            <button class="btn <?= $machineStatus === 'pause' ? 'btn-success' : 'btn-dark' ?> machine-action"
                                    data-table="<?= $t ?>"
                                    data-action="<?= $machineStatus === 'pause' ? 'pause' : 'start' ?>"
                                    data-pu-id="<?= $first['id'] ?>">
                                <?= $machineStatus === 'pause' ? 'Start' : 'Pause' ?>
                            </button>
                            <button class="btn btn-primary finish-btn"
                                    data-table="<?= $t ?>" data-pu-id="<?= $first['id'] ?>">Finished</button>
                            <button class="btn btn-info details-btn"
                                    data-table="<?= $t ?>"
                                    data-order='<?= json_encode($first) ?>'>Details</button>
                        </div>
                        <?php else: ?>
                        <button class="btn btn-info details-btn w-100"
                                data-table="<?= $t ?>"
                                data-order='<?= json_encode($first) ?>'>
                            <i class="fas fa-info-circle"></i> Details
                        </button>
                        <?php endif; ?>
                    </div>
                </div>
            </div>
        </div>
        <?php else: ?>
        <div class="machine-table" style="border:1px solid #ccc;">
            <div class="table-header"><strong>Table <?= $t ?> - No orders scheduled</strong></div>
        </div>
        <?php endif; ?>
    <?php endfor; ?>

    <div class="footer row mt-4">
        <div class="col-md-4">
            <button id="toggleAllBtn" class="btn btn-warning w-100 py-4">
                <i class="fas fa-pause mr-2"></i> Pause/Start All Tables
            </button>
        </div>
        <div class="col-md-4">
            <button id="scheduleBreakAll" class="btn btn-info w-100 py-4">
                <i class="fas fa-clock mr-2"></i> Schedule Break All Tables
            </button>
        </div>
        <div class="col-md-4">
            <button id="breakdownAllBtn" class="btn btn-danger w-100 py-4">
                <i class="fas fa-exclamation-triangle mr-2"></i> Machine Breakdown
            </button>
        </div>
    </div>
<?php endif; ?>
</div>
</section>

<!-- ── MODALS ─────────────────────────────────────────────────────────────── -->

<!-- Changeover Overlay -->
<div id="changeoverOverlay" class="changeover-overlay" style="display:none;">
    <div class="changeover-container">
        <div class="changeover-spinner"></div>
        <h2>🔄 CHANGEOVER IN PROGRESS</h2>
        <div class="changeover-info"><strong>Table: <span id="changeoverTableDisplay"></span></strong></div>
        <div class="changeover-timer" id="changeoverTimer">00:00:00</div>
        <div class="changeover-progress"><div class="changeover-progress-bar" id="changeoverProgress"></div></div>
        <div class="changeover-info" id="changeoverStartedAt"></div>
        <button class="changeover-stop-btn" onclick="stopChangeover()"><i class="fas fa-stop"></i> Stop Changeover</button>
    </div>
</div>

<!-- First-Off Modal -->
<div class="modal fade" id="firstOffModal" tabindex="-1">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content">
            <div class="modal-header bg-dark text-white">
                <h5 class="modal-title"><i class="fas fa-stamp mr-2"></i>First-Off Quality Approval</h5>
                <button type="button" class="close" data-dismiss="modal">&times;</button>
            </div>
            <div class="modal-body">
                <div class="form-group">
                    <label><strong>Enter QC Clock Number</strong></label>
                    <input type="text" id="qc_clock_no" class="form-control" placeholder="Enter Clock Number" required>
                </div>
                <div class="form-group mt-3">
                    <label><strong>QC Comment</strong></label>
                    <textarea id="qc_comment" class="form-control" rows="3" placeholder="Enter approval comment (optional)"></textarea>
                </div>
            </div>
            <div class="modal-footer">
                <button class="btn btn-secondary" data-dismiss="modal">Cancel</button>
                <button class="btn btn-dark" id="submitFirstOff">Approve</button>
            </div>
        </div>
    </div>
</div>

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

<!-- Part Selection Modal -->
<div class="modal fade" id="partSelectionModal" tabindex="-1" role="dialog" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content">
            <div class="modal-header bg-warning text-white">
                <h5 class="modal-title"><i class="fas fa-cogs mr-2"></i>Select Part Number</h5>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span>&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" data-dismiss="modal">Cancel</button>
                <button type="button" class="btn btn-warning" id="proceedToReason">Next</button>
            </div>
        </div>
    </div>
</div>

<!-- Reason 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>&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
                    $reasonRes = $conn->query("SELECT * FROM reason_codes");
                    while ($r = $reasonRes->fetch_assoc()):
                    ?>
                    <div class="form-check mb-2 reason-item">
                        <input class="form-check-input reason-radio" type="radio" name="reason_id"
                               value="<?= $r['id'] ?>" id="reason<?= $r['id'] ?>">
                        <label class="form-check-label" for="reason<?= $r['id'] ?>">
                            <?= htmlspecialchars($r['reason_name']) ?>
                        </label>
                    </div>
                    <?php endwhile; ?>
                </div>
            </div>
            <div class="modal-footer">
                <button class="btn btn-secondary" id="backToParts">Back</button>
                <button class="btn btn-danger" id="submitNok">Submit</button>
            </div>
        </div>
    </div>
</div>

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

<!-- Schedule Break Modal -->
<div class="modal fade" id="scheduleBreakModal" tabindex="-1">
    <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="number" id="breakDuration" class="form-control" placeholder="Auto-filled" readonly min="1" max="600">
                </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>
                <input type="hidden" id="break_table_id" value="">
                <input type="hidden" id="break_pu_id" value="">
            </div>
            <div class="modal-footer justify-content-center" style="gap:15px;">
                <button class="btn btn-secondary btn-lg" data-dismiss="modal">
                    <i class="fas fa-times mr-1"></i> Cancel
                </button>
                <button class="btn btn-warning btn-lg" id="submitScheduleBreak">
                    <i class="fas fa-play mr-1"></i> Start Break
                </button>
            </div>
        </div>
    </div>
</div>

<!-- Details Modal -->
<div class="modal fade" id="detailsModal" tabindex="-1" role="dialog" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content">
            <div class="modal-header bg-primary text-white">
                <h5 class="modal-title"><i class="fas fa-info-circle mr-2"></i>Order Details - Table <span id="detailsTableId"></span></h5>
                <button type="button" class="close" data-dismiss="modal"><span>&times;</span></button>
            </div>
            <div class="modal-body">
                <?php foreach ([
                    'detailsPartNumber'=>'Part Number','detailsDescription'=>'Description',
                    'detailsWorkOrder'=>'Work Order','detailsStartDate'=>'Start Date',
                    'detailsEndDate'=>'End Date','detailsQtyReq'=>'Quantity Required',
                    'detailsOkCount'=>'OK Count','detailsNokCount'=>'NOK Count',
                    'detailsQuarCount'=>'Quarantine Count','detailsTargetUph'=>'Target UPH',
                    'detailsActualUph'=>'Actual UPH','detailsStatus'=>'Status',
                ] as $id => $label): ?>
                <div class="row mb-2"><div class="col-6"><strong><?= $label ?>:</strong></div><div class="col-6" id="<?= $id ?>"></div></div>
                <?php endforeach; ?>
                <div class="row mb-2">
                    <div class="col-6"><strong>Document:</strong></div>
                    <div class="col-6">
                        <a href="#" id="detailsPdfLink" target="_blank" style="display:none;"><i class="fas fa-file-pdf text-danger mr-1"></i> View PDF</a>
                        <span id="detailsNoPdf" style="display:none;">No PDF available</span>
                    </div>
                </div>
            </div>
            <div class="modal-footer"><button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button></div>
        </div>
    </div>
</div>

<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"></script>
<script>
const frontEndURL        = "<?= $frontEndURL ?>";
const machine_id         = <?= $machine_id ?>;
const puMachineTableId   = <?= (int)$puMachineTableId ?>;
const tableOrdersByTable = <?= json_encode($tableOrdersJS) ?>;

let currentIndex = {};
for (let t in tableOrdersByTable) currentIndex[t] = 0;

let currentTableId = null, currentpuId = null, currentCountType = null;
let selectedNokPartIds = '', unselectedNokPartIds = '';

// ── Wall Clock ────────────────────────────────────────────────────────────────
(function tick() {
    const n = new Date();
    const str = [n.getHours(), n.getMinutes(), n.getSeconds()]
        .map(v => String(v).padStart(2,'0')).join(':');
    const el = document.getElementById('clock');
    if (el) el.textContent = str;
    setTimeout(tick, 1000);
})();

// ── Production Clock ──────────────────────────────────────────────────────────
let productionSeconds = <?= $storedSeconds ?>;

const machineStatusesClock = <?= json_encode($machineStatuses) ?>;

let lastReportedRunning = null;

function isMachineRunning() {
    return Object.values(machineStatusesClock).some(s => s === 'start');
}

function renderProductionClock() {
    const running  = isMachineRunning();
    const clockEl  = document.getElementById('productionClock');
    const badgeEl  = document.getElementById('clockStatusBadge');

    if (running) {
        productionSeconds++;
        if (clockEl) clockEl.style.color = '#28a745';
        if (badgeEl) { badgeEl.textContent = 'RUNNING'; badgeEl.style.background = '#28a745'; }
    } else {
        if (clockEl) clockEl.style.color = '#dc3545';
        if (badgeEl) { badgeEl.textContent = 'PAUSED';  badgeEl.style.background = '#dc3545'; }
    }

    const h = Math.floor(productionSeconds / 3600);
    const m = Math.floor((productionSeconds % 3600) / 60);
    const s = productionSeconds % 60;
    if (clockEl) {
        clockEl.textContent =
            String(h).padStart(2,'0') + ':' +
            String(m).padStart(2,'0') + ':' +
            String(s).padStart(2,'0');
    }

    if (lastReportedRunning !== running) {
        lastReportedRunning = running;
        persistClock(running);
    }
}

window._productionClockInterval = setInterval(renderProductionClock, 1000);

window._clockHeartbeatInterval = setInterval(function() {
    persistClock(isMachineRunning());
}, 30000);

window.addEventListener('beforeunload', function() {
    persistClock(isMachineRunning());
});

function persistClock(running) {
    fetch(frontEndURL + '/machine_tab/index?page=ajax_actions_pu&action=update_clock_pu', {
        method: 'POST',
        headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
        body: new URLSearchParams({
            machine_id:         machine_id,
            production_seconds: productionSeconds,
            is_running:         running ? 1 : 0,
            last_start_time:    running ? new Date().toISOString() : ''
        }),
        keepalive: true
    }).catch(function() {});
}

// ── Logout ────────────────────────────────────────────────────────────────────
document.getElementById('logoutBtn').addEventListener('click', function () {

    if (!confirm('Are you sure you want to log out?\n\nAll active tables will be paused automatically.')) {
        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...';

    // Stop clock ticking immediately
    clearInterval(window._productionClockInterval);
    clearInterval(window._clockHeartbeatInterval);

    // Collect running tables
    let allWorkOrders = [];
    for (let tableId in tableOrdersByTable) {
        const orders = tableOrdersByTable[tableId];
        if (!orders || !orders.length) continue;
        const order = orders[currentIndex[tableId] || 0];
        if (order.machine_status === 'start') {
            allWorkOrders.push({
                tableId:          tableId,
                workOrderId:      order.work_order_id,
                partId:           order.part_id,
                puMachineTableId: order.id,
                machineId:        machine_id
            });
        }
    }

    function doRedirect() {
        window.location.href = logoutRedirectUrl;
    }

    function destroySessionAndRedirect() {
        persistClock(false);
        fetch(frontEndURL + '/machine_tab/index?page=ajax_actions_pu&action=logout_pu', {
            method: 'POST', keepalive: true
        })
        .catch(() => {})
        .finally(() => doRedirect());
    }

    if (allWorkOrders.length === 0) {
        destroySessionAndRedirect();
        return;
    }

    fetch(frontEndURL + '/machine_tab/index?page=ajax_actions_pu&action=log_bulk_action_pu', {
        method:  'POST',
        headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
        body:    new URLSearchParams({
            action_type: 'pause',
            work_orders: JSON.stringify(allWorkOrders)
        }),
        keepalive: true
    })
    .then(res => res.json())
    .then(response => {
        if (!response.success) console.warn('Bulk pause warning:', response.message);
        destroySessionAndRedirect();
    })
    .catch(err => {
        console.error('Pause on logout failed:', err);
        destroySessionAndRedirect();
    });
});

function ajaxPost(action, data, cb) {
    $.ajax({
        url: frontEndURL + '/machine_tab/index?page=ajax_actions_pu&action=' + action,
        method: 'POST', data: data, dataType: 'json',
        success: cb,
        error: function(x,s,e) { alert('AJAX Error: ' + e); }
    });
}

function updateCountDisplay(tableId, type, newVal) {
    const classMap = { ok:'ok-count', nok:'nok-count', quarantine:'quar-count' };
    $(`#table-${tableId} .${classMap[type]}`).val(newVal);
    if (type === 'ok') $(`#table-${tableId} .qty_good`).text(newVal);
}

function reloadPage() { location.reload(); }

// ── First-Off ─────────────────────────────────────────────────────────────────
$(document).on('click', '.firstOffBtn', function() {
    currentTableId = $(this).data('table');
    currentpuId    = $(this).data('pu-id');
    $('#firstOffModal').modal('show');
});
$('#submitFirstOff').click(function() {
    const qcClockNo = $('#qc_clock_no').val().trim();
    if (!qcClockNo) { alert('Please enter QC clock number'); return; }
    const orders = tableOrdersByTable[currentTableId];
    const o = orders[currentIndex[currentTableId] || 0];
    ajaxPost('first_off_signoff_pu', {
        work_order_id: o.work_order_id, part_id: o.part_id,
        pu_machine_table_id: currentpuId, table_id: currentTableId,
        machine_id, qc_clock_no: qcClockNo, qc_comment: $('#qc_comment').val().trim()
    }, function(r) {
        if (r.success) { $('#firstOffModal').modal('hide'); reloadPage(); }
        else alert('❌ ' + r.message);
    });
});

// ── Changeover ────────────────────────────────────────────────────────────────
let activeChangeoverData = {};

$(document).on('click', '.changeoverBtn', function() {
    if ($(this).prop('disabled')) return;
    const tableId = $(this).data('table');
    if (activeChangeoverData[tableId]?.active) { alert('⚠ Changeover already in progress!'); return; }
    ajaxPost('check_active_changeover_pu', { machine_id, table_id: tableId }, function(r) {
        if (r.has_active_changeover && r.changeover_data) {
            showChangeoverInTable(tableId, r.changeover_data.start_time); return;
        }
        const clockNo = prompt('🔧 Enter employee clock number to start changeover:');
        if (clockNo?.trim()) startChangeover(tableId, clockNo.trim());
    });
});
function startChangeover(tableId, clockNo) {
    const btn = $(`#table-${tableId} .changeoverBtn`);
    btn.html('<i class="fas fa-spinner fa-spin"></i> Starting…').prop('disabled', true);
    ajaxPost('start_changeover_pu', { machine_id, table_id: tableId, clock_no: clockNo }, function(r) {
        if (r.success) { showChangeoverInTable(tableId, null); }
        else { btn.html('<i class="fas fa-exchange-alt"></i> Changeover').prop('disabled', false); alert('❌ ' + r.message); }
    });
}
function showChangeoverInTable(tableId, startTime) {
    if ($(`#changeover-overlay-${tableId}`).length) return;
    const tableDiv = $(`#table-${tableId}`);
    tableDiv.find('.changeoverBtn').css({ opacity:'.6' }).prop('disabled', true);
    tableDiv.append(`
        <div class="table-changeover-overlay" id="changeover-overlay-${tableId}">
            <button class="table-changeover-stop-btn" onclick="stopTableChangeover(${tableId})">
                <i class="fas fa-stop"></i> Stop Changeover
            </button>
            <div class="table-changeover-content">
                <h4><i class="fas fa-exchange-alt"></i> CHANGEOVER IN PROGRESS</h4>
                <div class="table-changeover-timer" id="changeover-timer-${tableId}">00:00:00</div>
                <div class="table-changeover-progress">
                    <div class="table-changeover-progress-bar" id="changeover-progress-${tableId}" style="width:0%"></div>
                </div>
                <div class="table-changeover-info" id="changeover-info-${tableId}"></div>
            </div>
        </div>`);
    const st = startTime ? new Date(startTime) : new Date();
    activeChangeoverData[tableId] = { active: true, startTime: st };
    $(`#changeover-info-${tableId}`).html(`Started at: ${st.toLocaleTimeString()}`);
    disableTableButtons(tableId, true);
    startTableChangeoverTimer(tableId);
}
function startTableChangeoverTimer(tableId) {
    clearInterval(window[`coInt_${tableId}`]);
    window[`coInt_${tableId}`] = setInterval(() => updateTableChangeoverTimer(tableId), 1000);
    updateTableChangeoverTimer(tableId);
}
function updateTableChangeoverTimer(tableId) {
    if (!$(`#changeover-overlay-${tableId}`).length) return;
    const el = activeChangeoverData[tableId]; if (!el) return;
    const sec = Math.floor((Date.now() - el.startTime) / 1000);
    $(`#changeover-timer-${tableId}`).text(
        [Math.floor(sec/3600), Math.floor((sec%3600)/60), sec%60].map(v=>String(v).padStart(2,'0')).join(':')
    );
    const pct = Math.min((sec / 7200) * 100, 100);
    $(`#changeover-progress-${tableId}`).css({ width: pct+'%',
        background: sec > 7200 ? '#dc3545' : sec > 3600 ? '#ffc107' : '#28a745' });
}
function stopTableChangeover(tableId) {
    if (!confirm(`Stop changeover for Table ${tableId}?`)) return;
    ajaxPost('end_changeover_pu', { machine_id, table_id: tableId }, function(r) {
        if (r.success) { removeChangeoverFromTable(tableId); reloadPage(); }
        else alert('❌ ' + r.message);
    });
}
function removeChangeoverFromTable(tableId) {
    $(`#changeover-overlay-${tableId}`).remove();
    clearInterval(window[`coInt_${tableId}`]);
    delete window[`coInt_${tableId}`];
    const tableDiv = $(`#table-${tableId}`);
    tableDiv.find('.changeoverBtn').css({ opacity:'1' }).prop('disabled', false);
    disableTableButtons(tableId, false);
    delete activeChangeoverData[tableId];
}
function disableTableButtons(tableId, disabled) {
    $(`#table-${tableId}`).find('.increment-btn,.decrement-btn,.machine-action,.finish-btn,.firstOffBtn').prop('disabled', disabled);
}
function checkActiveChangeovers() {
    ajaxPost('check_active_changeover_pu', { machine_id, table_id: null }, function(r) {
        if (!r.has_active_changeover) return;
        const data = r.changeover_data;
        (Array.isArray(data) ? data : [data]).forEach(co => {
            if (!$(`#changeover-overlay-${co.table_id}`).length)
                showChangeoverInTable(co.table_id, co.start_time);
        });
    });
}

// ── Live UPH: fetchUph / poll / global on-demand refresh ─────────────────────
// FIX (both parts below): the previous version of this IIFE early-returned
// for any table whose machine_status was in ['finish','pause','break',
// 'breakdown'] and just re-displayed the number computed at last PHP
// render -- frozen until something triggered location.reload(). That's
// most of a real shift for most tables. Every table now polls every
// cycle, period. fetchUph is also exposed as window.refreshUphForTable so
// the OK/decrement/NOK handlers below can trigger an immediate refresh
// right after a successful count action instead of waiting up to 30s for
// the next automatic cycle.
(function() {
    const POLL = 30000;
    function renderUph(tableId, liveUph, plannedUph) {
        const ok = plannedUph > 0 && liveUph >= plannedUph;
        const c  = ok ? '#28a745' : '#dc3545';
        const n  = document.getElementById('actual-uph-t'+tableId);
        if (n) { n.textContent = liveUph; n.style.color = c; }
        const b  = document.getElementById('uph-badge-t'+tableId);
        if (b) {
            b.className = 'uph-live-badge ' + (ok ? 'green' : 'red');
            b.querySelector('.uph-badge-label').textContent = ok ? 'on target' : 'below target';
        }
        const td = document.getElementById('table-'+tableId);
        if (td) {
            td.style.borderColor = ok ? 'green' : 'red';
            td.classList.toggle('border-success', ok);
            td.classList.toggle('border-danger', !ok);
        }
    }
    function fetchUph(tableId) {
        const orders = tableOrdersByTable[tableId]; if (!orders?.length) return;
        const o = orders[0];
        fetch(frontEndURL+'/machine_tab/index?page=ajax_actions_pu&action=get_live_uph_pu', {
            method:'POST', headers:{'Content-Type':'application/x-www-form-urlencoded'},
            body: new URLSearchParams({ work_order_id:o.work_order_id, part_id:o.part_id,
                pu_machine_table_id:o.id, table_id:tableId, window_minutes:60 })
        }).then(r=>r.json()).then(d=>{ if(d.success) renderUph(tableId, d.live_uph, d.planned_uph); }).catch(()=>{});
    }
    function poll() { for (let t in tableOrdersByTable) fetchUph(t); }
    poll();
    setInterval(poll, POLL);

    window.refreshUphForTable = fetchUph;
})();

// ── Increment ─────────────────────────────────────────────────────────────────
$(document).on('click', '.increment-btn', function() {
    const type = $(this).data('type'), tableId = $(this).data('table'), puId = $(this).data('pu-id');
    const flashMap = { ok:'do-flash-ok', nok:'do-flash-nok', quarantine:'do-flash-quarantine' };
    const $btn = $(this);
    $btn.removeClass('do-flash-ok do-flash-nok do-flash-quarantine');
    void $btn[0].offsetWidth;
    $btn.addClass(flashMap[type]);
    currentTableId = tableId; currentpuId = puId; currentCountType = type;
    const orders = tableOrdersByTable[tableId];
    if (!orders?.length) return;
    const o = orders[currentIndex[tableId] || 0];
    if (type === 'ok') {
        ajaxPost('log_count_pu', {
            work_order_id: o.work_order_id, part_id: o.part_id,
            table_id: tableId, pu_machine_table_id: puId,
            type, setId: o.set_id || 0, quantity: 1
        }, function(r) {
            if (r.success) {
                const newVal = parseInt($(`#table-${tableId} .ok-count`).val() || 0) + 1;
                updateCountDisplay(tableId, 'ok', newVal);
                // FIX: refresh Actual UPH immediately instead of waiting
                // for the next 30s poll cycle.
                if (window.refreshUphForTable) window.refreshUphForTable(tableId);
            } else alert('Error: ' + r.message);
        });
    } else {
        const needsPartSelection = populatePartSelection(tableId);
        if (needsPartSelection) {
            $('#partSelectionModal').modal('show');
        } else {
            $('#reasonModal').modal('show');
        }
    }
});

// ── Decrement ─────────────────────────────────────────────────────────────────
$(document).on('click', '.decrement-btn', function() {
    const type = $(this).data('type'), tableId = $(this).data('table'), puId = $(this).data('pu-id');
    const classMap = { ok:'ok-count', nok:'nok-count', quarantine:'quar-count' };
    const currentCount = parseInt($(`#table-${tableId} .${classMap[type]}`).val() || 0);
    if (currentCount <= 0) { alert('⚠ Count is already 0.'); return; }
    if (!confirm(`Undo last ${type.toUpperCase()} entry?`)) return;
    const o = (tableOrdersByTable[tableId] || [])[currentIndex[tableId] || 0];
    if (!o) return;
    ajaxPost('log_count_pu', {
        work_order_id: o.work_order_id, part_id: o.part_id,
        table_id: tableId, pu_machine_table_id: puId,
        type, setId: o.set_id || 0, quantity: -1
    }, function(r) {
        if (r.success) {
            updateCountDisplay(tableId, type, currentCount - 1);
            // FIX: refresh Actual UPH immediately.
            if (window.refreshUphForTable) window.refreshUphForTable(tableId);
        } else alert('❌ ' + r.message);
    });
});

// ── Part / Reason selection ───────────────────────────────────────────────────
function buildExpandedParts(partNumbers) {
    let expanded = [];
    partNumbers.forEach(p => {
        for (let i = 0; i < (parseInt(p.ratio)||1); i++)
            expanded.push({ id:p.id, part_number:p.part_number, unit_index:i+1, uid:`${p.id}_${i}` });
    });
    return expanded;
}
function populatePartSelection(tableId) {
    const orders = tableOrdersByTable[tableId];
    if (!orders?.length) return false;
    const o = orders[currentIndex[tableId] || 0];
    const partNumbers = o.part_numbers || [];
    const expanded = buildExpandedParts(partNumbers);

    // No set or single part — skip part selection, go straight to reason
    if (expanded.length <= 1) {
        selectedNokPartIds   = expanded.length ? String(expanded[0].id) : String(o.part_id);
        unselectedNokPartIds = '';
        return false;  // caller should show reason modal directly
    }

    // Multiple parts — populate and show part selection modal
    const sel = document.getElementById('partSelection');
    sel.innerHTML = '';
    expanded.forEach(item => {
        const siblings = expanded.filter(e => e.id === item.id);
        const label    = siblings.length > 1 ? `${item.part_number} — unit ${item.unit_index}` : item.part_number;
        const d = document.createElement('div');
        d.className = 'part-checkbox';
        d.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>`;
        d.addEventListener('click', e => { if (e.target.tagName !== 'INPUT') d.querySelector('input').click(); });
        sel.appendChild(d);
    });
    return true;  // caller should show part selection modal
}
$('#proceedToReason').click(function() {
    const checked = [], unchecked = [];
    document.querySelectorAll('.part-check').forEach(cb => (cb.checked ? checked : unchecked).push(cb.value));
    if (!checked.length) { alert('⚠ Select at least one part.'); return; }
    selectedNokPartIds   = checked.join(',');
    unselectedNokPartIds = unchecked.join(',');
    $('#partSelectionModal').modal('hide');
    $('#reasonModal').modal('show');
});
$('#backToParts').click(function() { $('#reasonModal').modal('hide'); $('#partSelectionModal').modal('show'); });
$('#submitNok').click(function() {
    const reason = $('.reason-radio:checked').val();
    if (!reason) { alert('⚠ Please select a reason.'); return; }
    const o = (tableOrdersByTable[currentTableId] || [])[currentIndex[currentTableId] || 0];
    if (!o) return;
    ajaxPost('log_count_pu', {
        work_order_id: o.work_order_id, part_id: o.part_id,
        table_id: currentTableId, pu_machine_table_id: currentpuId,
        reason_id: reason, part_ids: selectedNokPartIds,
        nok_q_scrap_part_ids_part_ids: selectedNokPartIds,
        nok_q_ok_part_ids: unselectedNokPartIds,
        type: currentCountType, setId: o.set_id || 0, quantity: 1
    }, function(r) {
        if (r.success) {
            $('#reasonModal').modal('hide');
            $('.reason-radio').prop('checked', false);
            selectedNokPartIds = unselectedNokPartIds = '';
            const cls = currentCountType === 'nok' ? 'nok-count' : 'quar-count';
            const newVal = parseInt($(`#table-${currentTableId} .${cls}`).val() || 0) + 1;
            updateCountDisplay(currentTableId, currentCountType, newVal);
            // FIX: refresh Actual UPH immediately. NOK/quarantine counts
            // don't feed the 'ok'-only UPH calculation directly, but
            // triggering the refresh here too keeps behaviour consistent
            // and costs nothing extra.
            if (window.refreshUphForTable) window.refreshUphForTable(currentTableId);
        } else alert('Error: ' + r.message);
    });
});

// ── Machine action ────────────────────────────────────────────────────────────
$(document).on('click', '.machine-action', function() {
    const tableId  = $(this).data('table');
    const curAct   = $(this).data('action');
    const puId     = $(this).data('pu-id');
    const newAct   = curAct === 'start' ? 'pause' : 'start';
    const o = (tableOrdersByTable[tableId] || [])[currentIndex[tableId] || 0];
    if (!o) return;
    ajaxPost('log_action_pu', {
        machine_id, work_order_id: o.work_order_id, table_id: tableId,
        pu_machine_table_id: puId, part_id: o.part_id, action_type: newAct
    }, function(r) {
        if (r.success) reloadPage(); else alert('Error: ' + r.message);
    });
});

// ── Finish ────────────────────────────────────────────────────────────────────
$(document).on('click', '.finish-btn', function() {
    const tableId  = $(this).data('table'), puId = $(this).data('pu-id');
    const o = (tableOrdersByTable[tableId] || [])[currentIndex[tableId] || 0];
    if (!o) return;
    if (parseInt(o.ok) < parseInt(o.qty_req)) {
        if (!confirm(`OK Count: ${o.ok}\nRequired: ${o.qty_req}\n\nAre you sure you want to finish this order?`)) return;
    }
    if (!confirm('Mark this order as finished?')) return;
    ajaxPost('log_action_pu', {
        work_order_id: o.work_order_id, part_id: o.part_id, table_id: tableId,
        pu_machine_table_id: puId, machine_id, action_type: 'finish'
    }, function(r) {
        if (r.success) {
            disableTableAfterFinish(tableId); // ← disable immediately, no reload needed
        } else {
            alert('Error: ' + r.message);
        }
    });
});

function disableTableAfterFinish(tableId) {
    const $table = $('#table-' + tableId);

    // Disable count and action buttons
    $table.find('.increment-btn, .decrement-btn, .machine-action, .finish-btn')
          .prop('disabled', true)
          .css('opacity', '0.4');

    // Hide First-Off button if present
    $table.find('.firstOffBtn').hide();

    // Show finished banner if not already there
    if ($table.find('.finished-banner').length === 0) {
        $table.find('.table-body').prepend(
            '<div class="finished-banner alert alert-success text-center py-2 mb-3">' +
            '<i class="fas fa-check-circle"></i> ' +
            'Order Finished — Complete changeover to remove from dashboard' +
            '</div>'
        );
    }

    // Keep Changeover and Details enabled
    $table.find('.changeoverBtn, .details-btn').prop('disabled', false).css('opacity', '1');
}

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

// ── Breakdown ─────────────────────────────────────────────────────────────────
$('#breakdownAllBtn').click(function() {
    $('#breakdown_table_id').val(''); $('#breakdown_pu_id').val('');
    $('#breakdownModal').modal('show');
});
$('#submitBreakdown').click(function() {
    const duration = parseFloat($('#breakdown_duration').val());
    const reason   = $('#breakdown_reason').val();
    if (!duration || duration < 0.5 || duration > 24) { alert('⚠ Invalid duration.'); return; }
    const puIds = [];
    for (let t in tableOrdersByTable) {
        const orders = tableOrdersByTable[t]; if (!orders?.length) continue;
        const o = orders[currentIndex[t]||0];
        puIds.push({ pu_machine_table_id:o.id, table_id:t, work_order_id:o.work_order_id, part_id:o.part_id, machine_id:o.machine_id });
    }
    if (!puIds.length) { alert('No active tables.'); return; }
    ajaxPost('log_breakdown_pu', {
        machine_id, action_type:'breakdown', breakdown_reason:reason,
        breakdown_duration:duration, pu_table_ids:JSON.stringify(puIds)
    }, function(r) {
        if (r.success) { $('#breakdownModal').modal('hide'); reloadPage(); }
        else alert('❌ ' + r.message);
    });
});
$('#breakdownOverBtn').on('click', function() {
    ajaxPost('end_breakdown_pu', { machine_id:$(this).data('machine') }, function(r) {
        if (r.success) reloadPage();
    });
});

// ── Schedule Break ────────────────────────────────────────────────────────────
$('#scheduleBreakAll').click(function() {
    $('#break_table_id,#break_pu_id').val('');
    $('#breakType').val('');
    $('#breakDuration').val('').prop('readonly', true);
    $('#breakRemarks').val('');
    $('#scheduleBreakModal').modal('show');
});

$('#scheduleBreakModal').on('hidden.bs.modal', function() {
    $('#breakType').val('');
    $('#breakDuration').val('').prop('readonly', true);
    $('#breakRemarks').val('');
    // Restore button in case it was left in loading state
    const btn = document.getElementById('submitScheduleBreak');
    btn.disabled = false;
    btn.innerHTML = '<i class="fas fa-play mr-1"></i> Start Break';
});

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

// ── submitScheduleBreak ───────────────────────────────────────────────────────
document.getElementById('submitScheduleBreak').addEventListener('click', function() {
    const type            = document.getElementById('breakType').value;
    const durationRaw     = document.getElementById('breakDuration').value;
    const remarks         = document.getElementById('breakRemarks').value.trim();
    const tableId         = document.getElementById('break_table_id').value;
    const puId            = document.getElementById('break_pu_id').value;

    if (!type) { alert('Please select break type'); return; }
    const durationMinutes = parseFloat(durationRaw);
    if (isNaN(durationMinutes) || durationMinutes <= 0) {
        alert('Enter a valid duration'); return;
    }
    if (type === 'custom' && durationMinutes > 600) {
        alert('Duration cannot exceed 600 minutes'); return;
    }

    const durationHours = durationMinutes / 60;

    const breakReason = type === '20' ? 'EARLY BREAK'
                      : type === '30' ? 'LUNCH BREAK'
                      : (remarks || 'OTHER');

    const btn = this;
    btn.disabled = true;
    btn.innerHTML = '<i class="fas fa-spinner fa-spin mr-1"></i> Processing…';

    function restoreBtn() {
        btn.disabled = false;
        btn.innerHTML = '<i class="fas fa-play mr-1"></i> Start Break';
    }

    const allTables  = [];
    const runningWOs = [];

    for (let t in tableOrdersByTable) {
        const o = (tableOrdersByTable[t] || [])[currentIndex[t] || 0];
        if (!o) continue;
        allTables.push({
            table_id:            t,
            work_order_id:       o.work_order_id,
            part_id:             o.part_id,
            pu_machine_table_id: o.id,
            machine_id:          machine_id
        });
        if (o.machine_status === 'start') {
            runningWOs.push({
                tableId:          t,
                workOrderId:      o.work_order_id,
                partId:           o.part_id,
                puMachineTableId: o.id,
                machineId:        machine_id
            });
        }
    }

    if (!allTables.length) {
        alert('⚠ No active orders.');
        restoreBtn();
        return;
    }

    function scheduleBreak() {
        if (!tableId) {
            ajaxPost('schedule_break_all_tables_pu', {
                tables:    JSON.stringify(allTables),
                duration:  durationMinutes,
                reason:    breakReason,
                machine_id: machine_id
            }, function(r) {
                if (r.success) {
                    $('#scheduleBreakModal').modal('hide');
                    reloadPage();
                } else {
                    alert('❌ ' + r.message);
                    restoreBtn();
                }
            });
        } else {
            const o = (tableOrdersByTable[tableId] || [])[currentIndex[tableId] || 0];
            if (!o) { restoreBtn(); return; }
            ajaxPost('log_action_pu', {
                work_order_id:       o.work_order_id,
                part_id:             o.part_id,
                table_id:            tableId,
                pu_machine_table_id: puId || o.id,
                machine_id:          machine_id,
                action_type:         'break',
                break_duration:      durationHours,
                break_reason:        breakReason
            }, function(r) {
                if (r.success) {
                    $('#scheduleBreakModal').modal('hide');
                    reloadPage();
                } else {
                    alert('❌ ' + r.message);
                    restoreBtn();
                }
            });
        }
    }

    if (runningWOs.length === 0) {
        scheduleBreak();
        return;
    }

    ajaxPost('log_bulk_action_pu', {
        action_type:  'pause',
        work_orders:  JSON.stringify(runningWOs)
    }, function(r) {
        if (!r.success) {
            alert('❌ Could not pause tables before break: ' + (r.message || 'Unknown error'));
            restoreBtn();
            return;
        }
        scheduleBreak();
    });
});

// ── Toggle All ────────────────────────────────────────────────────────────────
$('#toggleAllBtn').click(function() {
    let anyRunning = false;
    for (let t in tableOrdersByTable) {
        const s = (tableOrdersByTable[t]||[])[currentIndex[t]||0]?.machine_status;
        if (s && !['pause','finish'].includes(s)) { anyRunning = true; break; }
    }
    const actionType = anyRunning ? 'pause' : 'start';
    if (!confirm(`${actionType.charAt(0).toUpperCase()+actionType.slice(1)} all tables?`)) return;
    const allWO = [];
    for (let t in tableOrdersByTable) {
        const o = (tableOrdersByTable[t]||[])[currentIndex[t]||0]; if (!o) continue;
        allWO.push({ tableId:t, workOrderId:o.work_order_id, partId:o.part_id,
                     puMachineTableId:o.id, machineId:machine_id });
    }
    ajaxPost('log_bulk_action_pu', { action_type:actionType, work_orders:JSON.stringify(allWO) }, function(r) {
        if (r.success) reloadPage(); else alert('Error: ' + r.message);
    });
});

// ── Modal resets ──────────────────────────────────────────────────────────────
$('#breakdownModal').on('hidden.bs.modal', function() {
    $('#breakdown_duration').val('1'); $('#breakdown_reason').val('');
});
$('#firstOffModal').on('hidden.bs.modal', function() {
    $('#qc_clock_no,#qc_comment').val('');
});

// ── Init ──────────────────────────────────────────────────────────────────────
$(document).ready(function() {
    checkActiveChangeovers();
});
setInterval(function () {
    $.get('keep_alive.php');
}, 300000);
</script>