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


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


function getActualStartDate($conn, $workOrderId) {
    $sql = "SELECT created_at FROM machine_activity_log 
            WHERE work_order_id = $workOrderId 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) {
    $sql = "SELECT created_at FROM machine_activity_log 
            WHERE work_order_id = $workOrderId 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;
}

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

    $actualStartDate = getActualStartDate($conn, $workOrderId);
    $actualFinishDate = getActualFinishDate($conn, $workOrderId);
}
?>
<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;
}
</style>
<?php
$plannedUph =45;
$actualUph  = 9; 
$borderClass = ($actualUph > $plannedUph) ? "border-success" : "border-danger";
?>
<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 <?= $borderClass ?>" style="border:5px solid;">
        <?php if ($workOrderId): ?>
            <?php
            $detailSql = "SELECT * FROM vac_machine_table 
                          WHERE id = $workOrderId 
                          AND machine_id = $machine_id";
            $detailRes = $conn->query($detailSql);
            if ($detailRes->num_rows > 0) {
                $detail = $detailRes->fetch_assoc();
                
                $partId = $detail['part_id'];

       
                if (!empty($detail['set_id']) && $detail['set_id'] != 0) {
     
                    $mapSql = "SELECT part_id FROM set_mangmnt_mapping WHERE set_id = " . intval($detail['set_id']);
                    $mapRes = $conn->query($mapSql);
                    $parts = [];
                    while ($row = $mapRes->fetch_assoc()) {
                        $parts[] = $row['part_id'];
                    }

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

                        // Fetch part_numbers for these part_ids
                        $itemSql = "SELECT part_number FROM item_management WHERE id IN ($partIds)";
                        $itemRes = $conn->query($itemSql);

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

                        $partId = implode(",", $partNumbers); 
                    }
                } else {
                    $partId = $detail['product_name'];
                }

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

             
                if (!$lastStatus) {
                    $stmt = $conn->prepare("INSERT INTO machine_activity_log (work_order_id,machine_id,engineer_id,action_type) VALUES (?,?,?,?)");
                    $start = "start";
                    $stmt->bind_param("iiis",$workOrderId,$machine_id,$engineer_id,$start);
                    $stmt->execute();
                    $lastStatus = "start";
                    $actualStartDate = date('Y-m-d H:i:s');
                }

              
                $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 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 btn-sm action-btn" data-action="pause">
										<i class="fas fa-pause-circle me-1"></i> Pause
									</button>
								<?php endif; ?>
								<button class="btn btn-info btn-sm action-btn" data-action="pdf">
									<i class="fas fa-file-pdf me-1"></i> SER PDF
								</button>
							</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-header bg-light py-2 hide">
                                        <h6 class="mb-0"><i class="fas fa-cube mr-2"></i>Part Information</h6>
                                    </div>
                                    <div class="card-body partinfoBox">
                                        <div class="row">
                                            <!-- Left Column -->
                                            <div class="col-md-6">
                                                <div class="mb-2">
                                                    <strong>Part Number:</strong> <?= htmlspecialchars($detail['product_name']); ?>
                                                </div>
                                                <div class="mb-2">
                                                    <strong>Description:</strong> <?= htmlspecialchars($detail['product_name']); ?>
                                                </div>
                                                <!--<div class="mb-2">
                                                    <strong>Part(s):</strong> <?= $partId; ?>
                                                </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>

                                            <!-- Right Column -->
                                            <div class="col-md-6">
                                                <div class="mb-2">
                                                    <strong>Qty to Make:</strong> <?= $detail['quantity']; ?>
                                                </div>
                                                <div class="mb-2">
                                                    <strong>UPH:</strong> <?= $detail['efficiency']; ?>
                                                </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><strong>Total Made:</strong></td>
									  <td><span class="h5 mb-0" id="total-made"><?= $totalMade ?></span>/<?= $detail['quantity']; ?></td>
									</tr>
									<tr>
									  <td><strong>Actual UPH:</strong></td>
									  <td class="green"><span class="h5 mb-0" id="total-made"><?= $totalMade ?></span>/<?= $detail['quantity']; ?></td>
									</tr>
								  </table>
								<!--<div class=" col-md-12 card border-0 bg-light">
                                    <div class="card-body text-center py-3">
                                        <strong>Total Made:</strong> <span class="h5 mb-0" id="total-made"><?= $totalMade ?></span>/<?= $detail['quantity']; ?>
                                    </div>
                                </div>
                                <div class=" col-md-12 card border-0 bg-light">
                                    <div class="card-body text-center py-3">
                                        <strong>Actual UPH:</strong> <span class="h5 mb-0 text-success">9</span>
                                    </div>
                                </div>-->
                            </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-6 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-6 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 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-bs-dismiss="modal">Cancel</button>
                                        <button type="button" class="btn btn-danger" id="submitBreakdown">Submit</button>
                                    </div>
                                </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 vac_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>
    
    <!-- Part Selection Modal -->
    <div class="modal fade" id="partModal" tabindex="-1" role="dialog" aria-hidden="true">
        <div class="modal-dialog modal-dialog-centered">
            <div class="modal-content">
                <div class="modal-header bg-danger text-white">
                    <h5 class="modal-title"><i class="fas fa-cube mr-2"></i>Select Part(s)</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 id="partSelection" class="mb-3">
                        <?php 
                        $parts = explode(",", $partId); 
                        foreach ($parts as $p): ?>
                            <div class="form-check mb-2">
                                <input class="form-check-input part-checkbox" type="checkbox" value="<?= $p ?>" id="part<?= $p ?>">
                                <label class="form-check-label" for="part<?= $p ?>">Part <?= $p ?></label>
                            </div>
                        <?php endforeach; ?>
                    </div>
                </div>
                <div class="modal-footer">
                    <button class="btn btn-secondary" data-dismiss="modal">Cancel</button>
                    <button class="btn btn-danger" id="submitParts">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">
                    <!-- Reason Codes -->
                    <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>
	</div>
</section>

<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
$(function(){
    let selectedParts = [];
    let nokType = ''; 

    $(".increment-btn").click(function(){
        const type = $(this).data("type");
        
        if (type === "ok") {
			//alert("hi");
            $.ajax({
                url: site_url + "/modules/machine_tab/index.php?page=ajax_actions&action=log_count",
                method: "POST",
                data: {
                    work_order_id: <?= $workOrderId ?>,
                    engineer_id: <?= $engineer_id ?>,
                    machine_id: <?= $machine_id ?>,
                    type: type,
                    quantity: 1
                },
                dataType: "json",
                success: function(response){
                    if(response.success){
                        // Update the count display
                        const currentCount = parseInt($(`#${type}_count`).val());
                        $(`#${type}_count`).val(currentCount + 1);
                        
                        // Update total made
                        const totalMade = parseInt($("#total-made").text());
                        $("#total-made").text(totalMade + 1);
                        
                        // Check if work order is completed
                        checkWorkOrderCompletion();
                    } else {
                        alert("Error: " + response.message);
                    }
                },
                error: function(xhr, status, error){
                    alert("AJAX Error: " + error);
                }
            });
        } else {
            nokType = type;
            
            const partIds = "<?= $partId ?>";
            const parts = partIds.split(",");
            
            if (parts.length > 1) {
                $("#partModal").modal("show");
            } else {
                selectedParts = [parts[0]];
                $("#reasonModal").modal("show");
            }
        }
    });


    $(".decrement-btn").click(function(){
        const type = $(this).data("type");
        const currentCount = parseInt($(`#${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",
                method: "POST",
                data: {
                    work_order_id: <?= $workOrderId ?>,
                    engineer_id: <?= $engineer_id ?>,
                    machine_id: <?= $machine_id ?>,
                    type: type,
                    quantity: -1
                },
                dataType: "json",
                success: function(response){
                    if(response.success){
                        $(`#${type}_count`).val(currentCount - 1);
                        const totalMade = parseInt($("#total-made").text());
                        $("#total-made").text(totalMade - 1);
                    } else {
                        alert("Error: " + response.message);
                    }
                },
                error: function(xhr, status, error){
                    alert("AJAX Error: " + error);
                }
            });
        }
    });

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


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

    $("#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",
            method: "POST",
            data: {
                work_order_id: <?= $workOrderId ?>,
                engineer_id: <?= $engineer_id ?>,
                machine_id: <?= $machine_id ?>,
                part_ids: selectedParts.join(","),
                reason_id: reason,
                quantity: 1,
                type: nokType
            },
            dataType: "json",
            success: function(response){
                if(response.success){
                    $("#reasonModal").modal("hide");
                    
                    const currentCount = parseInt($(`#${nokType}_count`).val());
                    $(`#${nokType}_count`).val(currentCount + 1);
                    
                    const totalMade = parseInt($("#total-made").text());
                    $("#total-made").text(totalMade + 1);
                    
                    checkWorkOrderCompletion();
                } else {
                    alert("Error: " + response.message);
                }
            },
            error: function(xhr, status, error){
                alert("AJAX Error: " + error);
            }
        });
    });

    function checkWorkOrderCompletion() {
        const totalMade = parseInt($("#total-made").text());
        const plannedQuantity = <?= $detail['quantity'] ?>;
        
        if (totalMade >= plannedQuantity) {
            $.ajax({
                url: site_url + "/modules/machine_tab/index.php?page=ajax_actions&action=log_action",
                method: "POST",
                data: {
                    work_order_id: <?= $workOrderId ?>,
                    action_type: "finish"
                },
                dataType: "json",
                success: function(response){
                    if(response.success){
                        alert("Work order completed! Total made: " + totalMade);
                        location.reload();
                    } else {
                        alert("Error logging finish action: " + response.message);
                    }
                },
                error: function(xhr, status, error){
                    alert("AJAX Error: " + error);
                }
            });
        }
    }

    $(".action-btn").click(function(){
        let action = $(this).data("action");
        let breakdownReason = $("#breakdown_reason").val(); // get dropdown value
		//alert(breakdownReason);

        if (confirm("Are you sure you want to set this work order to " + action + "?")) {
            $.ajax({
                url: site_url + "/modules/machine_tab/index.php?page=ajax_actions&action=log_action",
                method: "POST",
                data: {
                    work_order_id: <?= $workOrderId ?>,
                    action_type: action,
                    breakdown_reason: breakdownReason 
                },
                dataType: "json",
                success: function(response){
                    if(response.success){
                        location.reload(); 
                    } else {
                        alert("Error: " + response.message);
                    }
                },
                error: function(xhr, status, error){
                    alert("AJAX Error: " + error);
                }
            });
        }
    });
    
 
    $("#breakdownBtn").click(function () {
		//alert("hii");
        $("#breakdownModal").modal("show");
    });

    $("#submitBreakdown").click(function () {
        let reason = $("#breakdown_reason").val();
		//alert(reason);
        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",
                method: "POST",
                data: {
                    work_order_id: <?= $workOrderId ?>,
                    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>

