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

$ordersByTable = [];
$sql = "SELECT * 
        FROM cnc_machine_table 
        WHERE finished = 0 
        AND machine_id = '" . $machine_id . "'
        ORDER BY table_id, priority ASC, start_date ASC";

$result = mysqli_query($conn, $sql);
while ($row = mysqli_fetch_assoc($result)) {

    // 🔹 Default part name
    $partDisplay = $row['product_name'];
    $partNumbers = []; // Initialize part numbers array

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

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

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

            // Get all part numbers for these part IDs
            $itemSql = "SELECT id, part_number FROM item_management WHERE id IN ($partIds)";
            $itemRes = $conn->query($itemSql);

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

            // Replace display part name with the joined part numbers
            $partDisplay = implode(", ", array_column($partNumbers, 'part_number'));
        }
    }

    // 🔹 Get document_upload based on set_id or part_id
    $document_upload = "";
    if (!empty($row['set_id']) && $row['set_id'] != 0) {
        // For set - get from set_route_details
        $docSql = "SELECT document_upload FROM set_route_details WHERE set_id = '" . $row['set_id'] . "'";
    } else {
        // For single part - get from route_details
        $docSql = "SELECT document_upload FROM route_details WHERE item_id = '" . $row['part_id'] . "'";
    }
    $docResult = mysqli_query($conn, $docSql);
    if ($docResult && mysqli_num_rows($docResult) > 0) {
        $docRow = mysqli_fetch_assoc($docResult);
        $document_upload = $docRow['document_upload'];
    }

    // 🔹 Replace product_name or part_id display with new combined partDisplay
    $row['product_name'] = $partDisplay;
    $row['part_numbers'] = $partNumbers; // Store part numbers array for later use
    $row['document_upload'] = $document_upload; // Store document path

    // 🔹 Add to structured array
    $ordersByTable[$row['table_id']][] = $row;
}

function getPartCount($conn, $workOrderId, $partId) {
    if (empty($workOrderId) || empty($partId)) {
        return ['ok' => 0, 'nok' => 0, 'quar' => 0, 'uph' => 0];
    }

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

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

function getMachineStatus($conn, $tableId, $machineId) {
    $sql = "SELECT action_type 
            FROM machine_activity_log 
            WHERE machine_id = $machineId AND table_id = $tableId 
            ORDER BY created_at DESC 
            LIMIT 1";

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

    if ($result && mysqli_num_rows($result) > 0) {
        $row = mysqli_fetch_assoc($result);
        return $row['action_type'];
    }

    return 'pause';
}

function calculateAndStoreActualUPH($conn, $workOrderId, $partId, $machine_id, $engineer_id = null) {
    $countSql = "SELECT 
                SUM(CASE WHEN type = 'ok' THEN quantity ELSE 0 END) AS ok,
                SUM(CASE WHEN type = 'nok' THEN quantity ELSE 0 END) AS nok,
                SUM(CASE WHEN type = 'quarantine' THEN quantity ELSE 0 END) AS quar
             FROM part_count_log 
             WHERE work_order_id = $workOrderId 
             AND part_id = '$partId'";
    $countResult = $conn->query($countSql);
    $countRow = $countResult->fetch_assoc();
    
    $okCount = $countRow['ok'] ?: 0;
    $nokCount = $countRow['nok'] ?: 0;
    $quarantineCount = $countRow['quar'] ?: 0;
    $totalMade = $okCount + $nokCount + $quarantineCount;

    $activitySql = "SELECT 
                    MIN(CASE WHEN action_type = 'start' THEN created_at END) as first_start,
                    MAX(CASE WHEN action_type = 'finish' THEN created_at END) as last_finish
                    FROM machine_activity_log 
                    WHERE work_order_id = $workOrderId 
                    AND part_id = '$partId'";
    $activityRes = $conn->query($activitySql);
    
    $actualUph = 0;
    
    if ($activityRes && $activityRes->num_rows > 0) {
        $activityRow = $activityRes->fetch_assoc();
        $firstStart = $activityRow['first_start'];
        $lastFinish = $activityRow['last_finish'];
        
        if ($firstStart) {
            if ($lastFinish) {
                $startTime = strtotime($firstStart);
                $finishTime = strtotime($lastFinish);
                $totalSeconds = $finishTime - $startTime;
            } else {
                $startTime = strtotime($firstStart);
                $totalSeconds = time() - $startTime;
            }
            
            $totalHours = $totalSeconds / 3600;
            $actualUph = ($totalHours > 0) ? round($totalMade / $totalHours, 2) : 0;
        }
    }

    $lastActionSql = "SELECT action_type 
                      FROM machine_activity_log 
                      WHERE work_order_id = $workOrderId 
                      AND part_id = '$partId' 
                      ORDER BY created_at DESC LIMIT 1";
    $lastActionResult = $conn->query($lastActionSql);
    $lastAction = '';
    if ($lastActionResult && $lastActionResult->num_rows > 0) {
        $lastAction = $lastActionResult->fetch_assoc()['action_type'];
    }
    
    if ($lastAction != 'finish') {
        $checkSql = "SELECT id FROM part_count_log 
                     WHERE work_order_id = $workOrderId 
                     AND machine_id = $machine_id 
                     AND part_id = '$partId' 
                     LIMIT 1";
        $checkResult = $conn->query($checkSql);
        
        if ($checkResult->num_rows > 0) {
            $updateUphSql = "UPDATE part_count_log 
                            SET uph = $actualUph 
                            WHERE work_order_id = $workOrderId 
                            AND machine_id = $machine_id 
                            AND part_id = '$partId'";
            
            if (!mysqli_query($conn, $updateUphSql)) {
                error_log("Failed to update UPH: " . mysqli_error($conn));
            }
        }
    }
    
    return $actualUph;
}

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

// Prepare JS data structure
$tableOrdersJS = [];
$machineStatuses = [];
$tableBorders = [];
$documentDir = "../admin/route_documents/"; // Define document directory

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

    foreach ($orders as $order) {
        $machineStatuses[$tableId] = getMachineStatus($conn, $tableId, $order['machine_id']);
        
        $actualUph = calculateAndStoreActualUPH($conn, $order['work_order_id'], $order['part_id'], $order['machine_id']);
        
        $counts = getPartCount($conn, $order['work_order_id'], $order['part_id']);

        $originalUph = $order['quantity'] / $order['total_hours']; 
        $loggedUph   = $counts['uph'];
        
        $borderColor = "green";
        if ($originalUph > 0 && $actualUph > 0) {
            $borderColor = ($actualUph >= $originalUph) ? "green" : "red";
        }
        
        $tableBorders[$tableId] = $borderColor;

        $tableOrdersJS[$tableId][] = [
            "part_id" => $order['part_id'],
            "set_id" => $order['set_id'],
            "machine_id" => $order['machine_id'],
            "product_name" => $order['product_name'],
            "qty_req" => $order['quantity'],
            "original_uph" => $originalUph,
            "ok" => $counts['ok'],
            "nok" => $counts['nok'],
            "quar" => $counts['quar'],
            "work_order_id" => $order['work_order_id'],
            "uph" => $loggedUph,
            "actual_uph" => $actualUph,
            "border" => $borderColor,
            "part_numbers" => $order['part_numbers'],
            "start_date" => $order['start_date'],
            "end_date" => $order['end_date'],
            "document_upload" => $order['document_upload']
        ];
    }
}
?>

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">
<style>
html, body {
    height: 100%;
    margin: 0;
    background-color: #c3e5eb !important;
}

h2, h3 {
    margin: 10px 0;
}

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

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

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

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

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

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

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

.order-controls {
    position: absolute;
    top: 15px;
    right: 15px;
    display: flex;
    gap: 10px;
}

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

.order-control:hover {
    background: #e0e0e0;
}

.count-controls {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin: 5px 0;
    background: white;
    border-radius: 5px;
    padding: 5px;
}

.count-btn {
    flex: 1;
    padding: 10px;
    margin: 0 2px;
    border: none;
    border-radius: 5px;
    color: white;
    font-weight: bold;
    cursor: pointer;
}

.increment-btn.ok { background: green; }
.increment-btn.nok { background: red; }
.increment-btn.quar { background: orange; }

.decrement-btn {
    background: #6c757d;
    color: white;
}

.count-input {
    width: 60px;
    text-align: center;
    margin: 0 5px;
    font-weight: bold;
    border: 1px solid #ccc;
    border-radius: 5px;
    padding: 5px;
}

.start { background: blue; color: white; }
.pause { background: darkred; color: white; }
.finished { background: lightblue; color: black; }

.colBox{
    padding:2;
}
.br-0{
    border-radius:0 !important;
}
.ai-n{
    align-items: normal !important;
}

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

/* Highlight selected items */
.part-checkbox input:checked ~ label {
    color: #007bff;
    font-weight: 600;
}

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

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

/* Make the entire checkbox area flex for better alignment */
.part-checkbox .form-check {
    display: flex;
    align-items: center;
    margin-bottom: 0;
}

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

.btn-darkred {
    background-color: darkred;
    color: white;
    border-color: darkred;
}

.btn-darkred:hover {
    background-color: #a10000;
    border-color: #a10000;
    color: white;
}
</style>

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

        <?php for ($t=1; $t <= $no_of_table; $t++): ?>
            <?php if (!empty($tableOrdersJS[$t])): 
                $first = $tableOrdersJS[$t][0]; 
                $machineStatus = $machineStatuses[$t];
                $borderColor = isset($tableBorders[$t]) ? $tableBorders[$t] : 'green';
            ?>
			<br>
            <div class="machine" id="table-<?= $t ?>" style="border:10px solid <?= $borderColor ?>;">
                <strong>   
                    <div class="row">
                        Table <?= $t ?> |
                        <span class="hide">Part No : <span class="part"><? echo $first["part_id"] ?></span></span>   
                        <span>Part No : <span class="part_name"><? echo $first["product_name"] ?></span></span> |	
                        <span>UPH: <span class="part_name"><? echo round($first["original_uph"], 2) ?></span></span> |
                        <span>Actual UPH: <span class="part_name"><? echo $first["actual_uph"] ?></span></span> |
                        <span>QTY Req : <span class="qty"><?= $first["qty_req"] ?></span></span> |
                        <span>QTY Good : <span class="qtygood"><?= $first["ok"] ?></span></span>
                    </div>
                </strong>
                
                <div class="row text-center ai-n">
                    <div class="col colBox">
                        <button type="button" class="btn btn-success w-100 increment-btn mb-2 py-3 br-0" data-type="ok" data-table="<?= $t ?>">OK</button>
                        <div class="row g-2">
                            <div class="col-6">
                                <input type="number" class="form-control text-center ok-count h-100 br-0" value="<?= $first['ok'] ?>" readonly>
                            </div>
                            <div class="col-6 p-0">
                                <button type="button" class="btn btn-outline-secondary w-100 h-100 decrement-btn br-0" data-type="ok" data-table="<?= $t ?>">Undo</button>
                            </div>
                        </div>
                    </div>

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

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

                    <div class="col d-flex flex-row gap-3 colBox">
                        <div class="btn <?= $machineStatus === 'pause' ? 'btn-success' : 'btn-darkred' ?> flex-fill py-5 machine-action br-0" 
                                data-table="<?= $t ?>" 
                                data-action="<?= $machineStatus === 'pause' ? 'pause' : 'start' ?>">
                            <?= $machineStatus === 'pause' ? 'Start' : 'Pause' ?>
                        </div>
                        <div class="btn btn-primary flex-fill py-5 finish-btn br-0" data-table="<?= $t ?>">Finished</div>
                        <div class="btn btn-dark flex-fill py-5 details-btn br-0" data-table="<?= $t ?>">Details</div>
                    </div>
                </div>
            <?php else: ?>
                <p>No orders scheduled for Table <?= $t ?></p>
            <?php endif; ?>
            </div>
        <?php endfor; ?>

        <div class="footer">
            <div class="col-md-4 mb-0">
                <button id="toggleAllBtn" class="btn btn-success w-100 py-4">
                    <i class="fas fa-pause mr-2"></i> Pause All
                </button>
            </div>	
            <div class="col-md-4 mb-0">
                <button id="schedule" class="btn schedule w-100 py-4">
                    <i class="fas fa-clock mr-2"></i> Scheduler Break
                </button>
            </div>
            <div class="col-md-4 mb-0">
                <button id="breakdownBtn" class="btn btn-danger w-100 py-4">
                    <i class="fas fa-exclamation-triangle mr-2"></i> Machine Breakdown
                </button>
            </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" data-dismiss="modal">Cancel</button>
                        <button type="button" class="btn btn-warning" id="proceedToReason">Next</button>
                    </div>
                </div>
            </div>
        </div>

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

        <!-- 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>Select Breakdown 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">
                        <?php 
                        echo Keycode::getKeycodeListValue(
                            "breakdown_reason",
                            $breakdown_reason,
                            "100%",
                            "Please Select",
                            "id",
                            "code",
                            "breakdown_reason",
                            "",
                            "form-control",
                            false,
                            "required"
                        ); 
                        ?>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-dismiss="modal">Cancel</button>
                        <button type="button" class="btn btn-danger" id="submitBreakdown">Submit</button>
                    </div>
                </div>
            </div>
        </div>

        <!-- Details Modal -->
		<div class="modal fade" id="detailsModal" tabindex="-1" role="dialog" aria-hidden="true">
			<div class="modal-dialog modal-dialog-centered" role="document">
				<div class="modal-content">
					<div class="modal-header bg-primary text-white">
						<h5 class="modal-title"><i class="fas fa-info-circle mr-2"></i>Order Details - Table <span id="detailsTableId"></span></h5>
						<button type="button" class="close" data-dismiss="modal" aria-label="Close">
						  <span aria-hidden="true">&times;</span>
						</button>
					</div>
					<div class="modal-body">
						<div class="row mb-2">
							<div class="col-6"><strong>Part Number:</strong></div>
							<div class="col-6" id="detailsPartNumber"></div>
						</div>
						<div class="row mb-2">
							<div class="col-6"><strong>Part Description:</strong></div>
							<div class="col-6" id="detailsPartDescription"></div>
						</div>
						<div class="row mb-2">
							<div class="col-6"><strong>Start Date:</strong></div>
							<div class="col-6" id="detailsStartDate"></div>
						</div>
						<div class="row mb-2">
							<div class="col-6"><strong>End Date:</strong></div>
							<div class="col-6" id="detailsEndDate"></div>
						</div>
						<div class="row mb-2">
							<div class="col-6"><strong>Quantity Required:</strong></div>
							<div class="col-6" id="detailsQtyReq"></div>
						</div>
						<div class="row mb-2">
							<div class="col-6"><strong>Quantity Made:</strong></div>
							<div class="col-6" id="detailsQtyMade"></div>
						</div>
						<div class="row mb-2">
							<div class="col-6"><strong>OK Count:</strong></div>
							<div class="col-6" id="detailsOkCount"></div>
						</div>
						<div class="row mb-2">
							<div class="col-6"><strong>NOK Count:</strong></div>
							<div class="col-6" id="detailsNokCount"></div>
						</div>
						<div class="row mb-2">
							<div class="col-6"><strong>Quarantine Count:</strong></div>
							<div class="col-6" id="detailsQuarCount"></div>
						</div>
						<div class="row mb-2">
							<div class="col-6"><strong>Document:</strong></div>
							<div class="col-6">
								<button type="button" class="btn btn-danger btn-sm" id="detailsPdfBtn" style="display:none;">
									<i class="fas fa-file-pdf mr-1"></i> View PDF
								</button>
								<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>
    </div>
</section>

<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 documentDir = "<?= $documentDir ?>";
    
    function updateClock() {
        const now = new Date();
        const hours = String(now.getHours()).padStart(2, '0');
        const minutes = String(now.getMinutes()).padStart(2, '0');
        const seconds = String(now.getSeconds()).padStart(2, '0');
        document.getElementById('clock').textContent = `${hours}:${minutes}:${seconds}`;
    }
   
    updateClock();
    setInterval(updateClock, 1000);

    let ordersByTable = <?php echo json_encode($tableOrdersJS); ?>;
    let currentIndex = {};
    for (let t in ordersByTable) currentIndex[t] = 0;

    let currentTableId = null;
    let currentCountType = null;
    let selectedParts = [];

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

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

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

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

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

    // Details button click handler
// Details button click handler
    $(document).on("click", ".details-btn", function() {
        const tableId = $(this).data("table");
        
        // Get the current order stored in the button's data
        let order = $(this).data('current-order');
        
        // Fallback: if no data stored, get from ordersByTable
        if (!order) {
            const orders = ordersByTable[tableId];
            if (!orders || orders.length === 0) {
                alert("No orders found for this table.");
                return;
            }
            const currentOrderIndex = currentIndex[tableId] || 0;
            order = orders[currentOrderIndex];
        }
        
        const totalMade = parseInt(order.ok || 0) + parseInt(order.nok || 0) + parseInt(order.quar || 0);
        
        console.log("Table ID:", tableId);
        console.log("Order Data:", order);
        console.log("Document:", order.document_upload);
        
        $("#detailsTableId").text(tableId);
        $("#detailsPartNumber").text(order.product_name || 'N/A');
        $("#detailsPartDescription").text(order.product_name || 'N/A');
        $("#detailsStartDate").text(order.start_date ? new Date(order.start_date).toLocaleString() : 'Not set');
        $("#detailsEndDate").text(order.end_date ? new Date(order.end_date).toLocaleString() : 'Not set');
        $("#detailsQtyReq").text(order.qty_req || 0);
        $("#detailsQtyMade").text(totalMade);
        $("#detailsOkCount").text(order.ok || 0);
        $("#detailsNokCount").text(order.nok || 0);
        $("#detailsQuarCount").text(order.quar || 0);
        
        // Handle PDF document
        if (order.document_upload && order.document_upload !== "" && order.document_upload !== null) {
            const ext = order.document_upload.split('.').pop().toLowerCase();
            console.log("File extension:", ext);
            
            if (ext === 'pdf') {
                const documentPath = documentDir + order.document_upload;
                console.log("Full PDF path:", documentPath);
                
                $("#detailsPdfBtn").show().off('click').on('click', function() {
                    console.log("Opening PDF:", documentPath);
                    window.open(documentPath, '_blank');
                });
                $("#detailsNoPdf").hide();
            } else {
                $("#detailsPdfBtn").hide();
                $("#detailsNoPdf").text("Document is not a PDF (." + ext + ")").show();
            }
        } else {
            console.log("No document found");
            $("#detailsPdfBtn").hide();
            $("#detailsNoPdf").text("No PDF available").show();
        }
        
        $("#detailsModal").modal("show");
    });

function populatePartSelection(tableId) {
    const orders = ordersByTable[tableId];
    const currentOrderIndex = currentIndex[tableId];
    const order = orders[currentOrderIndex];
    
    const partSelection = document.getElementById("partSelection");
    partSelection.innerHTML = '';
    
    if (order.part_numbers && order.part_numbers.length > 0) {
        order.part_numbers.forEach(part => {
            const partDiv = document.createElement('div');
            partDiv.className = 'part-checkbox';
            partDiv.innerHTML = `
                <div class="form-check">
                    <input class="form-check-input part-check" 
                           type="checkbox" 
                           value="${part.id}" 
                           id="part${part.id}">
                    <label class="form-check-label" for="part${part.id}">
                        ${part.part_number}
                    </label>
                </div>
            `;
            
            // Make the entire div clickable
            partDiv.addEventListener('click', function(e) {
                if (e.target.tagName !== 'INPUT') {
                    const checkbox = this.querySelector('input[type="checkbox"]');
                    checkbox.checked = !checkbox.checked;
                }
            });
            
            partSelection.appendChild(partDiv);
        });
    } else {
        selectedParts = [order.part_id.toString()];
        $("#reasonModal").modal("show");
        return false;
    }
    return true;
}

    $(document).on("click", ".increment-btn", function() {
        const type = $(this).data("type");
        const tableId = $(this).data("table");
        currentTableId = tableId;
        currentCountType = type;
        
        const orders = ordersByTable[tableId];
        const currentOrderIndex = currentIndex[tableId];
        const workOrderId = orders[currentOrderIndex].work_order_id;
        const partId = orders[currentOrderIndex].part_id;
        
        if (type === "ok") {
            $.ajax({
                url: site_url + "/modules/machine_tab/index.php?page=ajax_actions&action=log_count_cnc",
                method: "POST",
                data: {
                    work_order_id: workOrderId,
                    part_id: partId,
                    type: type,
                    quantity: 1
                },
                dataType: "json",
                success: function(response) {
                    if (response.success) {
                        const currentCount = parseInt($(`#table-${tableId} .${type}-count`).val());
                        $(`#table-${tableId} .${type}-count`).val(currentCount + 1);
                        ordersByTable[tableId][currentOrderIndex][type] = currentCount + 1;
                        $(`#table-${tableId} .qtygood`).text(ordersByTable[tableId][currentOrderIndex].ok);
						updateFinishButtonState(tableId);
                        location.reload();
                        checkWorkOrderCompletion(tableId);
                    } else {
                        alert("Error: " + response.message);
                    }
                },
                error: function(xhr, status, error) {
                    alert("AJAX Error: " + error);
                }
            });
        } else {
            const hasPartSelection = populatePartSelection(tableId);
            if (hasPartSelection) {
                $("#partSelectionModal").modal("show");
            }
        }
    });

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

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

    $("#submitNok").click(function() {
        let reason = $(".reason-radio:checked").val();

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

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

        $.ajax({
            url: site_url + "/modules/machine_tab/index.php?page=ajax_actions&action=log_count_cnc",
            method: "POST",
            data: {
                work_order_id: workOrderId,
                part_id: partId,
                reason_id: reason,
                part_ids: selectedParts.join(","),
                type: type,
                quantity: 1
            },
            dataType: "json",
            success: function(response) {
                if (response.success) {
                    $("#reasonModal").modal("hide");
                    const currentCount = parseInt($(`#table-${tableId} .${type}-count`).val());
                    $(`#table-${tableId} .${type}-count`).val(currentCount + 1);
                    ordersByTable[tableId][currentOrderIndex][type] = currentCount + 1;
                    location.reload();
                    $(".reason-radio").prop("checked", false);
                    $(".part-check").prop("checked", false);
                    selectedParts = [];
                } else {
                    alert("Error: " + response.message);
                }
            },
            error: function(xhr, status, error) {
                alert("AJAX Error: " + error);
            }
        });
    });

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

    $(document).on("click", ".machine-action", function() {
        const tableId = $(this).data("table");
        const currentAction = $(this).data("action");
        const newAction = currentAction === 'start' ? 'pause' : 'start';
        
        const orders = ordersByTable[tableId];
        const currentOrderIndex = currentIndex[tableId];
        const workOrderId = orders[currentOrderIndex].work_order_id;
        const partId = orders[currentOrderIndex].part_id;
        const machineId = orders[currentOrderIndex].machine_id;
        
        $.ajax({
            url: site_url + "/modules/machine_tab/index.php?page=ajax_actions&action=log_action_cnc",
            method: "POST",
            data: {
                machine_id: machineId, 
                work_order_id: workOrderId, 
                tableId: tableId,
                part_id: partId,
                action_type: newAction
            },
            dataType: "json",
            success: function(response) {
                if (response.success) {
                    const button = $(`#table-${tableId} .machine-action`);
                    button.removeClass('start pause').addClass(newAction);
                    button.text(newAction.charAt(0).toUpperCase() + newAction.slice(1));
                    button.data("action", newAction);
                    location.reload();
                } else {
                    alert("Error: " + response.message);
                }
            },
            error: function(xhr, status, error) {
                alert("AJAX Error: " + error);
            }
        });
    });

$(document).on("click", ".finish-btn", function() {
    const tableId = $(this).data("table");
    
    const orders = ordersByTable[tableId];
    const currentOrderIndex = currentIndex[tableId];
    const workOrderId = orders[currentOrderIndex].work_order_id;
    const partId = orders[currentOrderIndex].part_id;
    const qtyRequired = parseInt(orders[currentOrderIndex].qty_req);
    const qtyGood = parseInt(orders[currentOrderIndex].ok);
    
    // Check if quantity good meets the requirement
    if (qtyGood < qtyRequired) {
        alert(`Cannot finish! Quantity Good (${qtyGood}) must reach Quantity Required (${qtyRequired}) before finishing.\n\nRemaining: ${qtyRequired - qtyGood}`);
        return;
    }
    
    if (confirm("Are you sure you want to mark this order as finished?")) {
        $.ajax({
            url: site_url + "/modules/machine_tab/index.php?page=ajax_actions&action=log_action_cnc",
            method: "POST",
            data: {
                work_order_id: workOrderId,
                part_id: partId,
                action_type: "finish"
            },
            dataType: "json",
            success: function(response) {
                if (response.success) {
                    alert("Order marked as finished!");
                    if (orders.length > 1) {
                        showNextOrder(tableId);
                    }
                    location.reload();
                } else {
                    alert("Error: " + response.message);
                }
            },
            error: function(xhr, status, error) {
                alert("AJAX Error: " + error);
            }
        });
    }
});

function updateFinishButtonState(tableId) {
    const orders = ordersByTable[tableId];
    const currentOrderIndex = currentIndex[tableId];
    const qtyRequired = parseInt(orders[currentOrderIndex].qty_req);
    const qtyGood = parseInt(orders[currentOrderIndex].ok);
    
    const $finishBtn = $(`#table-${tableId} .finish-btn`);
    
    if (qtyGood < qtyRequired) {
        $finishBtn.addClass('disabled').css({
            'opacity': '0.6',
            'cursor': 'not-allowed'
        });
    } else {
        $finishBtn.removeClass('disabled').css({
            'opacity': '1',
            'cursor': 'pointer'
        });
    }
}

    let schedulerActive = false;

    $("#schedule").click(function() {
        const actionType = schedulerActive ? "scheduler_break_stop" : "scheduler_break_start";
        
        if (confirm(`Are you sure you want to ${schedulerActive ? "stop" : "start"} scheduler break?`)) {
            let allWorkOrders = [];

            for (let tableId in ordersByTable) {
                const orders = ordersByTable[tableId];
                if (orders && orders.length > 0) {
                    const currentOrderIndex = currentIndex[tableId];
                    allWorkOrders.push({
                        work_order_id: orders[currentOrderIndex].work_order_id,
                        part_id: orders[currentOrderIndex].part_id,
                        machine_id: orders[currentOrderIndex].machine_id,
                        tableId: tableId
                    });
                }
            }

            allWorkOrders.forEach((order) => {
                $.ajax({
                    url: site_url + "/modules/machine_tab/index.php?page=ajax_actions&action=log_action_cnc",
                    method: "POST",
                    data: {
                        work_order_id: order.work_order_id,
                        part_id: order.part_id,
                        machine_id: order.machine_id,
                        tableId: order.tableId,
                        action_type: actionType
                    },
                    dataType: "json",
                    success: function(response) {
                        if (response.success) {
                            console.log(`Scheduler ${actionType} logged for table ${order.tableId}`);
                        } else {
                            console.error("Error: " + response.message);
                        }
                    },
                    error: function(xhr, status, error) {
                        console.error("AJAX Error: " + error);
                    }
                });
            });

            schedulerActive = !schedulerActive;
            if (schedulerActive) {
                $("#schedule").removeClass("schedule").addClass("btn-darkred")
                    .html('<i class="fas fa-stop mr-2"></i> Stop Scheduler Break');
            } else {
                $("#schedule").removeClass("btn-darkred").addClass("schedule")
                    .html('<i class="fas fa-clock mr-2"></i> Scheduler Break');
            }
        }
    });

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

    $("#submitBreakdown").click(function () {
        let reason = $("#breakdown_reason").val();
        if (!reason) {
            alert("⚠ Please select a breakdown reason.");
            return;
        }

        if (confirm("Are you sure you want to log this breakdown?")) {
            $.ajax({
                url: site_url + "/modules/machine_tab/index.php?page=ajax_actions&action=log_action_cnc",
                method: "POST",
                data: {
                    action_type: "breakdown",
                    breakdown_reason: reason
                },
                dataType: "json",
                success: function (response) {
                    if (response.success) {
                        $("#breakdownModal").modal("hide");
                        location.reload();
                    } else {
                        alert("Error: " + response.message);
                    }
                },
                error: function (xhr, status, error) {
                    alert("AJAX Error: " + error);
                }
            });
        }
    });

    function checkWorkOrderCompletion(tableId) {
        const orders = ordersByTable[tableId];
        const currentOrderIndex = currentIndex[tableId];
        const totalMade = orders[currentOrderIndex].ok;
        const plannedQuantity = orders[currentOrderIndex].qty_req;
        
        if (totalMade >= plannedQuantity) {
            alert("Work order completed! Total made: " + totalMade);
        }
    }

     function checkAllMachinesState() {
        let allPaused = true;
        let allStarted = true;
        
        $(".machine-action").each(function() {
            const action = $(this).data("action");
            if (action === "start") {
                allPaused = false;
            } else {
                allStarted = false;
            }
        });
        
        return { allPaused, allStarted };
    }

   function updateToggleButton() {
        const state = checkAllMachinesState();
        const $toggleBtn = $("#toggleAllBtn");
        
        if (state.allPaused) {
            $toggleBtn.removeClass('btn-darkred').addClass('btn-success')
                .html('<i class="fas fa-play mr-2"></i> Start All');
        } else if (state.allStarted) {
            $toggleBtn.removeClass('btn-success').addClass('btn-darkred')
                .html('<i class="fas fa-pause mr-2"></i> Pause All');
        } else {
            $toggleBtn.removeClass('btn-success').addClass('btn-darkred')
                .html('<i class="fas fa-pause mr-2"></i> Pause All');
        }
    }

    $("#toggleAllBtn").click(function() {
        const state = checkAllMachinesState();
        const actionType = state.allPaused ? "start" : "pause";
        
        if (confirm(`Are you sure you want to ${actionType} all Tables?`)) {
            let allWorkOrders = [];
            
            for (let tableId in ordersByTable) {
                const orders = ordersByTable[tableId];
                if (orders && orders.length > 0) {
                    const currentOrderIndex = currentIndex[tableId];
                    const workOrderId = orders[currentOrderIndex].work_order_id;
                    const partId = orders[currentOrderIndex].part_id;
                    const machineId = orders[currentOrderIndex].machine_id;
                    
                    allWorkOrders.push({
                        tableId: tableId,
                        workOrderId: workOrderId,
                        partId: partId,
                        machineId: machineId
                    });
                }
            }
            
            if (allWorkOrders.length === 0) {
                alert("No active work orders found!");
                return;
            }
            
            $.ajax({
                url: site_url + "/modules/machine_tab/index.php?page=ajax_actions&action=log_bulk_action_cnc",
                method: "POST",
                data: {
                    action_type: actionType,
                    work_orders: JSON.stringify(allWorkOrders)
                },
                dataType: "json",
                success: function(response) {
                    if (response.success) {
                        alert(`All Tables have been ${actionType}ed successfully!`);
                        
                        $(".machine-action").each(function() {
                            const $this = $(this);
                            if (actionType === "pause") {
                                $this.removeClass('btn-success').addClass('btn-darkred')
                                    .text('Start').data("action", "start");
                            } else {
                                $this.removeClass('btn-darkred').addClass('btn-success')
                                    .text('Pause').data("action", "pause");
                            }
                        });
                        
                        updateToggleButton();
                        location.reload();
                    } else {
                        alert("Error: " + response.message);
                    }
                },
                error: function(xhr, status, error) {
                    alert("AJAX Error: " + error);
                }
            });
        }
    });

   $(document).ready(function() {
    updateToggleButton();
    for (let t in ordersByTable) {
        updateOrderDisplay(t);
        updateFinishButtonState(t); // Add this line
    }
});
</script>