<?php
session_start();
if (!isset($_SESSION['engineer_id'])) {
    header("Location: login.php");
    exit();
}

$engineer_id = $_SESSION['engineer_id'];

echo$query = "SELECT wo.id, wo.work_order_id, wo.customer_id, 
    (SELECT id FROM work_logs WHERE engineer_id = $engineer_id AND work_assign_id = wo.id AND end_time IS NULL LIMIT 1) AS active_log,  
	(SELECT id FROM work_logs WHERE engineer_id = $engineer_id AND work_assign_id = wo.id ORDER BY id DESC LIMIT 1) AS work_log_id,  (SELECT start_time FROM work_logs WHERE engineer_id = $engineer_id AND work_assign_id = wo.id AND end_time IS NULL LIMIT 1) AS start_time, 
    (SELECT SUM(quantity_made) FROM work_logs WHERE engineer_id = $engineer_id AND work_assign_id = wo.id) AS already_worked
          FROM work_order_assign wo 
          WHERE wo.engineer_id = $engineer_id";


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

?>


<style>/* Table Styling */
table {
    width: 100%;
    border-collapse: collapse;
    background: #ffffff;
    border-radius: 10px;
    overflow: hidden;
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

th, td {
    padding: 14px;
    text-align: left;
    border-bottom: 1px solid #ddd;
}

th {
    background: #6e7373;
    color: white;
    font-weight: bold;
    text-transform: uppercase;
}

tr:nth-child(even) {
    background: #f8f9fa;
}

tr:hover {
    background: #e9ecef;
    transition: 0.3s ease-in-out;
}

/* Button Styling */
button {
    padding: 8px 16px;
    font-size: 14px;
    font-weight: bold;
    border: none;
    cursor: pointer;
    border-radius: 5px;
    transition: all 0.3s ease;
}

.logon-btn {
    background: #28a745;
    color: white;
}

.logon-btn:hover {
    background: #218838;
}

.logoff-btn {
    background: #dc3545;
    color: white;
}

.logoff-btn:hover {
    background: #c82333;
}
/* Modal Overlay (Dark Background) */
.modal-overlay {
    display: none;
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background: rgba(0, 0, 0, 0.6);
    z-index: 999;
}

/* Modal Box */
.modal-container {
    display: none;
    position: fixed;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    background: white;
    padding: 20px;
    width: 400px;
    box-shadow: 0px 0px 10px rgba(0, 0, 0, 0.3);
    border-radius: 8px;
    z-index: 1000;
}

/* Modal Header */
.modal-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    font-size: 18px;
    font-weight: bold;
    margin-bottom: 10px;
}

/* Close Button */
.close-modal {
    cursor: pointer;
    font-size: 20px;
    color: red;
}

/* Modal Form Fields */
.modal-container label {
    display: block;
    font-weight: bold;
    margin-top: 8px;
}

.modal-container input,
.modal-container textarea {
    width: 100%;
    padding: 8px;
    margin-top: 5px;
    border: 1px solid #ccc;
    border-radius: 4px;
}

/* Buttons */
.modal-container button {
    margin-top: 15px;
    padding: 10px;
    border: none;
    cursor: pointer;
    font-size: 16px;
    border-radius: 5px;
}

.submit-btn {
    background: #28a745;
    color: white;
}

.cancel-modal {
    background: #dc3545;
    color: white;
}
/* Modal Structure */
.modal-container {
    background: white;
    padding: 20px;
    border-radius: 8px;
    width: 600px;
    margin: auto;
}

/* Two Sections in One Row */
.form-grid {
    display: grid;
    grid-template-columns: 1fr 1fr;
    gap: 20px;
}

/* Inputs in Each Section */
.quantity-section,
.quality-section {
    background: rgba(255, 255, 255, 0.6);
    padding: 10px;
    border-radius: 8px;
}

/* Input Group for Quantity Made */
.input-group {
    display: flex;
    gap: 10px;
}

.input-group input {
    flex: 1;
}

/* Progress Notes Below */
.progress-section {
    margin-top: 15px;
    display: flex;
    flex-direction: column;
}

.progress-section textarea {
    width: 100%;
    height: 80px;
}




</style>


<div class="table-responsive container-fluid">
<h2 class="text-center mt-2">Engineer Dashboard</h2>
<table id="example1" class="table table-bordered table-striped">
    <tr>
        
        <th>Customer Name</th>
        <th>Assign Jobs</th>
        <th>Already Worked</th>
        <th>Remaining Quantity</th>
        <th> Job Started</th>
		<th>Action</th>
    </tr>
    <?php while ($row = mysqli_fetch_assoc($sql)) {
	  $order_quantity = utility::getTableFieldById("work_order","order_quantity","id",$row['work_order_id']);?>
    <tr>
        <td><?= $gsi->getCustomerById($row['customer_id']) ?></td>
        <td><?= $gsi->getworkOrderNewById($row['work_order_id']) ?></td>
       <td><?= $row['already_worked'] ?? 0 ?></td>
        <td><?= ($order_quantity - $row['already_worked']) ?></td>
        
		<td><?= !empty($row['start_time']) ? date('d-m-Y H:i:s', strtotime($row['start_time'])) : '' ?></td>

        <td>
            <button class="logon-btn btn-primary border-0" data-id="<?= $row['id'] ?>" <?= ($row['active_log']) ? 'style="display:none;"' : '' ?>>Log On</button>
            <button class="logoff-btn btn-danger border-0" data-id="<?= $row['id'] ?>"data-id2="<?= $row['work_log_id'] ?>" <?= ($row['active_log']) ? '' : 'style="display:none;"' ?>>Log Off</button>
        </td>
		
    </tr>
    <?php }; ?>
</table>
</div>
<!-- Log Off Modal -->
<div class="modal-overlay"></div>

<div id="logoffModal" class="modal-container">
    <div class="modal-header">
        <h3 id="workOrderIdShow">Log Off Work Order </h3>
        <span class="close-modal">&times;</span>
    </div>

    <form id="logoffForm">
        <input type="hidden" name="work_logs_id" id="work_logs_id">

        <div class="form-grid">
            <div class="quantity-section">
                <h5 >Quantity Made</h5>
                <label>Already Worked</label>
              <input type="text" name="already_worked" id="already_worked" value="0" readonly>

                <label>Quantity Remaining</label>
                <input type="text" name="quantity_remaining" id='quantity_remaining' value="0" readonly>

                <label>Quantity Made</label>
                <div class="input-group">
                    <input type="number" name="quantity_made" required>
                </div>
            </div>

            <div class="quality-section">
                <h5>Quality Issues</h5>
                <label>Scrapped</label>
                <input type="number" name="scrap" value="0 EACH">

                <label>To Rework</label>
                <input type="number" name="rework" value="0 EACH">

                <label>At Risk</label>
                <input type="number" name="at_risk" value="0 EACH">
            </div>
        </div>

        <!-- Progress Notes Below -->
        <div class="progress-section">
            <label>Progress Notes:</label>
            <textarea name="progress_notes"></textarea>
        </div>

        <button type="submit" class="submit-btn">Submit</button>
        <button type="button" class="cancel-modal">Cancel</button>
    </form>
</div>


<script>
  $(document).ready(function() {
    $(".logon-btn").click(function() {
        var workOrderId = $(this).data("id");
        var button = $(this);
        
        $.post(site_url+"/modules/clockin_clockout/index.php?page=ajax_actions&action=logon",
        { work_assign_id: workOrderId }, function(response) {
            if (response == "success") {
                button.hide();
                button.siblings(".logoff-btn").show();
                location.reload();
            } else {
                alert("Log On Failed!");
            }
        });
    });

		$(".logoff-btn").click(function () {
			let workAssignId = $(this).data("id");
			let work_logs_id = $(this).data("id2");

			$.ajax({
				url: site_url+"/modules/clockin_clockout/index.php?page=ajax_actions&action=fetch_made_qty",
				type: "POST",
				data: { work_assign_id: workAssignId },
				success: function (response) {
					let data = JSON.parse(response);
					$("#work_logs_id").val(work_logs_id);
					$("#already_worked").val(data.already_worked);
					$("#quantity_remaining").val(data.remaining_quantity);
					$("#workOrderIdShow").html('Log Off Work Order : <span style="color: red;">' + data.work_order_name + '</span>');

					$("#logoffModal").fadeIn();
					$(".modal-overlay").fadeIn();
				}
			});
		});

    $(".close-modal, .cancel-modal, .modal-overlay").click(function() {
        $("#logoffModal").fadeOut();
        $(".modal-overlay").fadeOut();
    });

      $("#logoffForm").submit(function (e) {
        e.preventDefault();

        $.ajax({
            url: site_url+"/modules/clockin_clockout/index.php?page=ajax_actions&action=loggoff",
            type: "POST",
            data: $(this).serialize(),
            dataType: "json",
            success: function (response) {
                if (response.status === "success") {
                    alert("Logged Off Successfully!");
					location.reload();
                } else {
                    alert("Log Off Failed! " + response.message);
                }
            },
            error: function () {
                alert("Error in submitting data!");
            }
        });
    }); 
});


</script>

</body>
</html>
