<?php
session_start();
include "config.php"; 

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

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

// ------------------------------------------------
// Utility functions
// ------------------------------------------------
function getTotalCounts($conn, $workOrderId, $partId, $type) {
    $sql = "SELECT SUM(quantity) as total FROM part_count_log 
            WHERE work_order_id = $workOrderId 
            AND part_id = $partId 
            AND type = '$type'";
    $result = $conn->query($sql);
    $row = $result->fetch_assoc();
    return $row['total'] ? $row['total'] : 0;
}

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

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

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

function calculateAndStoreActualUPH($conn, $workOrderId, $partId, $machine_id, $engineer_id = null) {
    // Get total counts
    $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;

    // Get activity timestamps
    $activitySql = "SELECT 
                    MIN(CASE WHEN action_type = 'start' THEN created_at END) as first_start,
                    MAX(CASE WHEN action_type = 'finish' THEN created_at END) as last_finish
                    FROM 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) {
                // Work order is finished - calculate from start to finish
                $startTime = strtotime($firstStart);
                $finishTime = strtotime($lastFinish);
                $totalSeconds = $finishTime - $startTime;
            } else {
                // Work order is still ongoing - calculate from start to now
                $startTime = strtotime($firstStart);
                $totalSeconds = time() - $startTime;
            }
            
            $totalHours = $totalSeconds / 3600;
            $actualUph = ($totalHours > 0) ? round($totalMade / $totalHours, 2) : 0;
        }
    }

    // ✅ FIXED: Always update UPH regardless of finish status
    // This ensures consistent UPH display whether work is ongoing or completed
    $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;
}

// ------------------------------------------------
// Calculate Planned and Actual UPH
// ------------------------------------------------
$plannedUph = 0;
$actualUph = 0;
$borderClass = "";
$actualStartDate = "";
$actualFinishDate = "";
$partId = 0;
$setId = 0;
$partNumbers = [];

if ($workOrderId) {
    $detailSql = "SELECT * FROM assbly_machine_table 
                  WHERE id = $workOrderId AND machine_id = $machine_id";
    $detailRes = $conn->query($detailSql);
    if ($detailRes && $detailRes->num_rows > 0) {
        $detail = $detailRes->fetch_assoc();
        $partId = intval($detail['part_id']);
        $setId = isset($detail['set_id']) ? intval($detail['set_id']) : 0;

        $partNumbers = getPartNumbersFromSet($conn, $setId, $partId);

        $plannedUph = ($detail['total_hours'] > 0) 
            ? round($detail['quantity'] / $detail['total_hours'], 2) 
            : 0;

        $okCount = getTotalCounts($conn, $workOrderId, $partId, 'ok');
        $nokCount = getTotalCounts($conn, $workOrderId, $partId, 'nok');
        $quarantineCount = getTotalCounts($conn, $workOrderId, $partId, 'quarantine');
        $totalMade = $okCount + $nokCount + $quarantineCount;

        $actualStartDate = getActualStartDate($conn, $workOrderId, $partId);
        $actualFinishDate = getActualFinishDate($conn, $workOrderId, $partId);

        $actualUph = calculateAndStoreActualUPH($conn, $workOrderId, $partId, $machine_id, $engineer_id);

        if ($plannedUph > 0 && $actualUph > 0) {
            $borderClass = ($actualUph >= $plannedUph) ? "border-success" : "border-danger";
        }
    }
}

?>

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

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

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

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

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

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

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

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

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

.part-checkbox * {
    transition: all 0.2s ease;
}
</style>

<section class="content" style="margin-top:5vh;">
    <div class="container-fluid d-flex justify-content-center">
        <div class="p-3 rounded shadow-sm w-100 <?= $workOrderId ? $borderClass : '' ?>" 
             style="<?= $workOrderId ? 'border:9px solid;' : '' ?>">
        <?php if ($workOrderId): ?>
            <?php
            $detailSql = "SELECT * FROM assbly_machine_table 
                          WHERE id = $workOrderId 
                          AND machine_id = $machine_id 
                          AND part_id = $partId";
            $detailRes = $conn->query($detailSql);
            if ($detailRes->num_rows > 0) {
                $detail = $detailRes->fetch_assoc();
                $partId = $detail['part_id'];
                $setId = isset($detail['set_id']) ? intval($detail['set_id']) : 0;

                $statusSql = "SELECT action_type 
                              FROM machine_activity_log 
                              WHERE work_order_id = $workOrderId 
                              AND part_id = $partId 
                              ORDER BY created_at DESC LIMIT 1";

                $statusRes = $conn->query($statusSql);
                $lastStatus = $statusRes->num_rows > 0 ? $statusRes->fetch_assoc()['action_type'] : null;

                if (!$lastStatus) {
                    $createdOn = date('Y-m-d H:i:s');
                    $start = "start";

                    $insertSql = "
                        INSERT INTO machine_activity_log 
                        (work_order_id, part_id, machine_id, engineer_id, action_type, created_at)
                        VALUES ($workOrderId, $partId, $machine_id, $engineer_id, '$start', '$createdOn')
                    ";

                    $conn->query($insertSql);

                    $lastStatus = "start";
                    $actualStartDate = $createdOn;
                }

                $badgeClass = [
                    "start" => "badge bg-success",
                    "pause" => "badge bg-warning",
                    "break" => "badge bg-info",
                    "breakdown" => "badge bg-danger",
                    "finish" => "badge bg-primary"
                ];
           
            ?>
                <div class="card shadow-sm">
					<div class="card">
						<div class="card-header w-100 d-flex justify-content-between align-items-center py-3">
							<a href="index?page=dashboard" class="btn btn-secondary btn-sm">
								<i class="fas fa-arrow-left mr-1"></i> Back
							</a>
							<span class="<?= $badgeClass[$lastStatus] ?? 'badge bg-secondary'; ?> px-3 py-2 mx-auto">
								<i class="fas fa-circle mr-1"></i> <?= ucfirst($lastStatus); ?>
							</span>
							<div>
								<?php if (!in_array($lastStatus, ["pause", "break", "breakdown", "finish"])): ?>
									<button class="btn btn-warning  py-3 btn-sm action-btn" data-action="pause" style="min-width:140px;">
										<i class="fas fa-pause-circle me-1"></i> Pause
									</button>
								<?php endif; ?>
								<button class="btn btn-info btn-sm py-3 action-btn" data-action="pdf" style="min-width:140px;">
									<i class="fas fa-file-pdf me-1"></i> SER PDF
								</button>
								<?php  
                                if (!empty($setId) && $setId != 0) {
                                    $sql = "SELECT document_upload FROM set_route_details WHERE set_id = '$setId'";
                                } else {
                                    $sql = "SELECT document_upload FROM route_details WHERE item_id = '$partId'";
                                }

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

                                if ($result_edit && mysqli_num_rows($result_edit) > 0) {
                                    $row_edit = mysqli_fetch_assoc($result_edit);
                                    $document_upload = $row_edit['document_upload'];
                                } else {
                                    $document_upload = "";
                                }
                                ?>
							<?php
                            $dir = "../admin/route_documents/";    
                            $ext = strtolower(pathinfo($document_upload, PATHINFO_EXTENSION));

                            if ($ext == 'pdf') {
                                $image_path = '<a href="'.$dir.$document_upload.'" target="_blank">
                                                  <span class="primary text-primary" 
                                                        title="'.$document_upload.'">'
                                              .utility::ellipsis($document_upload, 20).'</span></a>';
                            } else {
                                $image_path = '<img style="width:100px;border:1px solid #777" src="'.$dir.'no-image.gif">';
                            }
                            ?>
							</div>
						</div>
					</div>

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

                        <div class="row mb-1">
                            <div class="col-12">
                                <div class="card h-80 border-0 shadow-sm">
                                    <div class="card-body partinfoBox" style="color:black;">
                                        <div class="row">
                                            <div class="col-md-6">
                                                <div class="mb-2">
                                                    <strong>Part Number:</strong> 
                                                    <?php 
                                                    if (!empty($partNumbers)) {
                                                        $partDisplay = implode(", ", array_column($partNumbers, 'part_number'));
                                                        echo htmlspecialchars($partDisplay);
                                                    } else {
                                                        echo htmlspecialchars($detail['product_name']);
                                                    }
                                                    ?>
                                                </div>
                                                <div class="mb-2">
                                                    <strong>Description:</strong> <?= htmlspecialchars($detail['product_name']); ?>
                                                </div>
                                                <div class="mb-2">
                                                    <strong>Planned Start:</strong> <?= $detail['start_date']; ?>
                                                </div>
                                                <div class="mb-2">
                                                    <strong>Actual Start:</strong> <?= $actualStartDate ? $actualStartDate : 'Not started yet'; ?>
                                                </div>
                                            </div>

                                            <div class="col-md-6">
                                                <div class="mb-2">
                                                    <strong>Qty to Make:</strong> <?= $detail['quantity']; ?>
                                                </div>
                                                <div class="mb-2">
                                                    <strong>Planned UPH:</strong> <?= $plannedUph; ?>
                                                </div>
                                                <div class="mb-2">
                                                    <strong>Planned Finish:</strong> <?= $detail['end_date']; ?>
                                                </div>
                                                <div class="mb-2">
                                                    <strong>Actual Finish:</strong> <?= $actualFinishDate ? $actualFinishDate : 'Not finished yet'; ?>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <div class="row ">
                            <div class="col-md-12 mb-2">
                                <div class="count-controls">
                                   <button type="button" class="btn btn-success count-btn increment-btn w-50 br-0 f-w-b" data-type="ok"><i class=""></i> OK</button>
										<input type="number" id="ok_count" value="<?= $okCount ?>"  class="form-control w-40 text-center br-0" readonly>
									<button type="button" class="btn undoBtn count-btn decrement-btn w-10 br-0 f-w-b" data-type="ok">
                                        <i class="">Undo</i>
                                    </button>
                                </div>
                            </div>
                            <div class="col-md-12 mb-2">
                                <div class="count-controls">
                                    <button type="button" class="btn btn-danger count-btn increment-btn w-50 br-0 f-w-b" data-type="nok" id="nokBtn">
                                        <i class="">NOK</i>
                                    </button>
                                    <input type="number" id="nok_count" value="<?= $nokCount ?>" class="form-control w-40 text-center br-0" readonly>
                                    <button type="button" class="btn undoBtn count-btn decrement-btn br-0 f-w-b" data-type="nok">
                                        <i class="">Undo</i>
                                    </button>
                                </div>
                            </div>
                            
                            <div class="col-md-12 mb-2">
                                <div class="count-controls">
                                    <button type="button" class="btn btn-warning count-btn increment-btn w-50 br-0 f-w-b" data-type="quarantine" id="quarantineBtn">
                                        <i class="">Quarantine</i>
                                    </button>
                                    <input type="number" id="quarantine_count" value="<?= $quarantineCount ?>" class="form-control w-40 text-center br-0" readonly>
                                    <button type="button" class="btn undoBtn count-btn decrement-btn br-0 f-w-b" data-type="quarantine">
                                        <i class="">Undo</i>
                                    </button>
                                </div>
                            </div>
                        </div>

                        <div class="row mb-2">
                            <div class="col-md-6 mb-3 mb-md-0">
                                <table class="status-table">
									<tr>
									  <td style="color:black;"><strong>Total Made:</strong></td>
									  <td style="color:black;"><span class="h5 mb-0" id="total-made"><?= $totalMade ?></span>/<?= $detail['quantity']; ?></td>
									</tr>
									<tr>
									  <td style="color:black;"><strong>Actual UPH:</strong></td>
									  <td class="<?= ($actualUph >= $plannedUph) ? 'text-success' : 'text-danger' ?>">
										<span class="h5 mb-0"><?= $actualUph ?></span>
									  </td>
									</tr>
								  </table>
                            </div>
                            <div class="col-md-6">
                                <div class="row">
                                    <?php if ($lastStatus === "finish"): ?>
                                        <div class="col-12 mb-2">
                                            <button class="btn btn-primary w-100 py-3" disabled>
                                                <i class="fas fa-check-circle mr-2"></i> Work Order Completed
                                            </button>
                                        </div>
                                    <?php elseif (in_array($lastStatus, ["pause", "break", "breakdown"])): ?>
                                        <div class="col-12 mb-2">
                                            <button class="btn btn-success w-100 py-3 action-btn" data-action="start">
                                                <i class="fas fa-play-circle mr-2"></i> Resume Work
                                            </button>
                                        </div>
                                    <?php else: ?>
                                          <div class="col-md-4 mb-2">
        <button class="btn btn-primary w-100 py-3 action-btn" data-action="finish">
            <i class="fas fa-check-circle mr-2"></i> Finish<br>Work Order
        </button>
    </div>
    
    <div class="col-md-4 mb-2">
        <button class="btn btn-info w-100 py-3 action-btn" data-action="break">
            <i class="fas fa-coffee mr-2"></i> Schedule<br>Break
        </button>
    </div>
    
    <div class="col-md-4 mb-2">
        <button id="breakdownBtn" class="btn btn-danger w-100 py-3">
            <i class="fas fa-exclamation-triangle mr-2"></i> Machine<br>Breakdown
        </button>
    </div>
                                    <?php endif; ?>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            <?php
            } else {
                echo "<p class='text-danger'>Work order not found.</p>";
            }
            ?>
        <?php else: ?>
            <?php
            $sql = "SELECT id, part_id, product_name, start_date, quantity, end_date 
                    FROM assbly_machine_table
                    WHERE machine_id = $machine_id
                    ORDER BY start_date ASC";
            $res = $conn->query($sql);
            ?>
            <div class="card shadow-sm">
               <div class="card-header bg-purple text-white py-3">
                    <h5 class="mb-0"><i class="fas fa-list-alt me-2"></i>Upcoming Work Orders</h5>
                </div>

                <div class="card-body p-0">
                    <div class="table-responsive">
                        <table class="table table-hover table-bordered mb-0">
                            <thead class="thead-light">
                                <tr>
                                    <th>Product Name</th>
                                    <th>Description</th>
                                    <th>Quantity</th>
                                    <th>Start Date</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php if ($res->num_rows > 0): ?>
                                    <?php while ($row = $res->fetch_assoc()): ?>
                                        <tr onclick="window.location.href='index?page=dashboard&work_order_id=<?= $row['id']; ?>'" style="cursor:pointer;">
                                            <td><?= htmlspecialchars($row['product_name']); ?></td>
                                            <td><?= $part_name = utility::getTableFieldById("item_management", "product_description", "id", $row['part_id']); ?></td>
                                            <td><?= $row['quantity']; ?></td>
                                            <td><?= $row['start_date']; ?></td>
                                        </tr>
                                    <?php endwhile; ?>
                                <?php else: ?>
                                    <tr><td colspan="5" class="text-center py-4">No upcoming work orders found.</td></tr>
                                <?php endif; ?>
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        <?php endif; ?>
    </div>
</section>

<!-- Part Selection Modal -->
<div class="modal fade" id="partSelectionModal" tabindex="-1" role="dialog" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content">
            <div class="modal-header bg-warning text-white">
                <h5 class="modal-title"><i class="fas fa-cogs mr-2"></i>Select Part Number</h5>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>
            <div class="modal-body">
                <h6 class="mb-3">Please select the part number(s):</h6>
                <div id="partSelection" style="max-height: 200px; overflow-y: auto;">
                    <!-- Part checkboxes will be inserted here dynamically -->
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-dismiss="modal">Cancel</button>
                <button type="button" class="btn btn-warning" id="proceedToReason">Next</button>
            </div>
        </div>
    </div>
</div>

<!-- Reason Selection Modal -->
<div class="modal fade" id="reasonModal" tabindex="-1" role="dialog" aria-hidden="true">
    <div class="modal-dialog modal-lg modal-dialog-centered">
        <div class="modal-content">
            <div class="modal-header bg-danger text-white">
                <h5 class="modal-title"><i class="fas fa-exclamation-circle mr-2"></i>Select Reason</h5>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>
            <div class="modal-body">
                <h6 class="mb-3">Select Reason</h6>
                <div id="reasonSelection" style="max-height: 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>

<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>
$(function(){
    let selectedParts = [];
    let currentCountType = null;
    let partNumbers = <?php echo json_encode($partNumbers); ?>;
    const requiredQuantity = <?= $detail['quantity'] ?? 0 ?>;

    // Function to populate part selection modal (CNC-style)
    function populatePartSelection() {
        const partSelection = document.getElementById("partSelection");
        partSelection.innerHTML = '';
        
        // If only one part or no part numbers, skip to reason modal
        if (!partNumbers || partNumbers.length <= 1) {
            selectedParts = ["<?= $partId ?>"];
            $("#reasonModal").modal("show");
            return false;
        }
        
        // Multiple parts - show selection modal
        if (partNumbers && partNumbers.length > 1) {
            partNumbers.forEach(part => {
                const partDiv = document.createElement('div');
                partDiv.className = 'part-checkbox';
                partDiv.innerHTML = `
                    <div class="form-check">
                        <input class="form-check-input part-check" 
                               type="checkbox" 
                               value="${part.id}" 
                               id="part${part.id}">
                        <label class="form-check-label" for="part${part.id}">
                            ${part.part_number}
                        </label>
                    </div>
                `;
                
                // Make the entire div clickable (CNC-style interaction)
                partDiv.addEventListener('click', function(e) {
                    if (e.target.tagName !== 'INPUT') {
                        const checkbox = this.querySelector('input[type="checkbox"]');
                        checkbox.checked = !checkbox.checked;
                    }
                });
                
                partSelection.appendChild(partDiv);
            });
        }
        return true;
    }

    $(".increment-btn").click(function(){
        const type = $(this).data("type");
        currentCountType = type;
        
        if (type === "ok") {
            $.ajax({
                url: site_url + "/modules/machine_tab/index.php?page=ajax_actions&action=log_count_assambly",
                method: "POST",
                data: {
                    work_order_id: <?= $workOrderId ?>,
                    engineer_id: <?= $engineer_id ?>,
                    machine_id: <?= $machine_id ?>,
                    part_id: <?= $partId ?>,
                    type: type,
                    quantity: 1
                },
                dataType: "json",
                success: function(response){
                    if(response.success){
                        const currentCount = parseInt($(`#${type}_count`).val());
                        $(`#${type}_count`).val(currentCount + 1);
                        
                        const totalMade = parseInt($("#total-made").text());
                        $("#total-made").text(totalMade + 1);
                        
                        location.reload();
                    } else {
                        alert("Error: " + response.message);
                    }
                },
                error: function(xhr, status, error){
                    alert("AJAX Error: " + error);
                }
            });
        } else {
            // For NOK and Quarantine, check if part selection is needed
            const hasPartSelection = populatePartSelection();
            
            if (hasPartSelection) {
                $("#partSelectionModal").modal("show");
            }
        }
    });

    // Proceed from part selection to reason selection
    $("#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");
    });

    // Back button from reason to part selection
    $("#backToParts").click(function() {
        $("#reasonModal").modal("hide");
        $("#partSelectionModal").modal("show");
    });

    // Submit NOK / Quarantine log with part selection
    $("#submitNok").click(function() {
        let reason = $(".reason-radio:checked").val();

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

        $.ajax({
            url: site_url + "/modules/machine_tab/index.php?page=ajax_actions&action=log_count_assambly",
            method: "POST",
            data: {
                work_order_id: <?= $workOrderId ?>,
                engineer_id: <?= $engineer_id ?>,
                machine_id: <?= $machine_id ?>,
                part_id: <?= $partId ?>,
                reason_id: reason,
                part_ids: selectedParts.join(","),
                type: currentCountType,
                quantity: 1
            },
            dataType: "json",
            success: function(response) {
                if (response.success) {
                    $("#reasonModal").modal("hide");
                    
                    const currentCount = parseInt($(`#${currentCountType}_count`).val());
                    $(`#${currentCountType}_count`).val(currentCount + 1);
                    
                    const totalMade = parseInt($("#total-made").text());
                    $("#total-made").text(totalMade + 1);
                    
                    location.reload();
                    
                    // Reset modal selections
                    $(".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);
            }
        });
    });

    // ✅ IMPROVED: Decrement button - handles most recent entry
    $(".decrement-btn").click(function(){
        const type = $(this).data("type");
        const currentCount = parseInt($(`#${type}_count`).val());
        
        if (currentCount <= 0) {
            alert("⚠ Count is already 0. Nothing to undo.");
            return;
        }
        
        if (confirm("Are you sure you want to undo the last " + type.toUpperCase() + " entry?")) {
            $.ajax({
                url: site_url + "/modules/machine_tab/index.php?page=ajax_actions&action=log_count_assambly",
                method: "POST",
                data: {
                    work_order_id: <?= $workOrderId ?>,
                    engineer_id: <?= $engineer_id ?>,
                    machine_id: <?= $machine_id ?>,
                    part_id: <?= $partId ?>,
                    type: type,
                    quantity: -1  // Negative to indicate decrement
                },
                dataType: "json",
                success: function(response){
                    if(response.success){
                        $(`#${type}_count`).val(currentCount - 1);
                        const totalMade = parseInt($("#total-made").text());
                        $("#total-made").text(totalMade - 1);
                        location.reload();
                    } else {
                        alert("❌ Error: " + response.message);
                    }
                },
                error: function(xhr, status, error){
                    alert("AJAX Error: " + error);
                }
            });
        }
    });

    // ✅ IMPROVED: Action button with finish validation
    $(".action-btn").click(function(){
        let action = $(this).data("action");
        
        if(action === "pdf"){
            let pdfFile = "<?= $document_upload ?>";
            let dir = "<?= $dir ?>";

            if(pdfFile){
                window.location.href = dir + pdfFile;
            } else {
                alert("No PDF file available!");
            }
            return;
        }

        // ✅ Validate OK count before allowing finish
        if (action === "finish") {
            const okCount = parseInt($("#ok_count").val());
            const requiredQty = <?= $detail['quantity'] ?? 0 ?>;
            
            if (okCount < requiredQty) {
                alert(`❌ Cannot finish work order!\n\nOK Count: ${okCount}\nRequired: ${requiredQty}\n\nYou need ${requiredQty - okCount} more OK parts to complete this work order.`);
                return;
            }
            
            if (!confirm(`✅ Ready to finish work order?\n\nOK Count: ${okCount}\nRequired: ${requiredQty}\n\nThis action cannot be undone.`)) {
                return;
            }
        } else if (!confirm("Are you sure you want to set this work order to " + action + "?")) {
            return;
        }

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

    $("#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_assambly",
                method: "POST",
                data: {
                    work_order_id: <?= $workOrderId ?>,
                    part_id: <?= $partId ?>,
                    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);
                }
            });
        }
    });
});
</script>