<?php
include('../config/config.php');
include('../config/session_check.php'); 
$branch_id = $_SESSION['branch_id'];

// Fetch Active Customers
$result = $conn->query("SELECT 
                        op.id, 
                        op.batch_date, 
                        o.order_no, 
                        v.reg_no AS truck_number, 
                        d.name AS driver_name, 
                        op.ordered_quantity, 
                        op.production_quantity, 
                        op.created_at 
                    FROM order_processing op
                    JOIN orders o ON op.order_id = o.id
                    JOIN vehicles v ON op.truck_id = v.id
                    JOIN drivers d ON op.driver_id = d.id
                    WHERE op.status='active'&& op.branch_id='$branch_id' order by op.id DESC");

?>

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="utf-8">
  <meta content="width=device-width, initial-scale=1.0" name="viewport">

  <title>Customer Master</title>
  <meta content="" name="description">
  <meta content="" name="keywords">

  <!-- Favicons -->
  <link href="../assets/img/favicon.png" rel="icon">
  <link href="../assets/img/apple-touch-icon.png" rel="apple-touch-icon">

  <!-- Google Fonts -->
  <link href="https://fonts.gstatic.com" rel="preconnect">
  <link href="https://fonts.googleapis.com/css?family=Open+Sans:300,300i,400,400i,600,600i,700,700i|Nunito:300,300i,400,400i,600,600i,700,700i|Poppins:300,300i,400,400i,500,500i,600,600i,700,700i" rel="stylesheet">

  <!-- Vendor CSS Files -->
  <link href="../assets/vendor/bootstrap/css/bootstrap.min.css" rel="stylesheet">
  <link href="../assets/vendor/bootstrap-icons/bootstrap-icons.css" rel="stylesheet">
  <link href="../assets/vendor/boxicons/css/boxicons.min.css" rel="stylesheet">
  <link href="../assets/vendor/quill/quill.snow.css" rel="stylesheet">
  <link href="../assets/vendor/quill/quill.bubble.css" rel="stylesheet">
  <link href="../assets/vendor/remixicon/remixicon.css" rel="stylesheet">
  <link href="../assets/vendor/simple-datatables/style.css" rel="stylesheet">

  <!-- Template Main CSS File -->
  <link href="../assets/css/style.css" rel="stylesheet">
  <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <style>
    @media (max-width: 768px) {
        table thead { display: none; }
        table tbody tr { display: block; margin-bottom: 1rem; border: 1px solid #ccc; padding: 1rem; border-radius: 8px; background-color: #f9f9f9; }
        table tbody td { display: block; padding: 0.5rem 0; }
        table tbody td::before { content: attr(data-label); font-weight: bold; display: inline-block; width: 120px; }
    }
    </style>

</head>

<body>

  <!-- ======= Header ======= -->
<?php include('../config/header.php'); ?> // Include the header

  <!-- ======= Sidebar ======= -->

<?php include('../config/sidebar.php'); ?>
  <main id="main" class="main">

  

    <section class="section">
      <div class="row">
        <div class="col-lg-12">

          <div class="card">
            <div class="card-body">
                
               
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Order Processing Master</title>
    <link href="../assets/vendor/bootstrap/css/bootstrap.min.css" rel="stylesheet">
    <script src="../assets/vendor/bootstrap/js/bootstrap.bundle.min.js"></script>
</head>
<body>
<div class="container mt-5">
    <h2>Order Processing Master</h2>
    <button type="button" class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#addOrderProcessingModal">Order Processing </button>
     <table class="table datatable">
       <thead>
        <tr>
            <th>Date</th>
            <th>Order No</th>
            <th>Truck</th>
            <th>Driver</th>
            <th>Order Qty (m³)</th>
            <th>Process Qty (m³)</th>
            <th>Created Time</th>
            <th>Actions</th>
        </tr>
    </thead>
    <tbody>
        <?php while ($row = $result->fetch_assoc()): ?>
        <tr>
    <td data-label="Batch Date"><?= htmlspecialchars($row['batch_date']); ?></td>
    <td data-label="Order No"><?= htmlspecialchars($row['order_no']); ?></td>
    <td data-label="Truck Number"><?= htmlspecialchars($row['truck_number']); ?></td>
    <td data-label="Driver Name"><?= htmlspecialchars($row['driver_name']); ?></td>
    <td data-label="Ordered Qty"><?= htmlspecialchars($row['ordered_quantity']); ?> m³</td>
    <td data-label="Produced Qty"><?= htmlspecialchars($row['production_quantity']); ?> m³</td>
    <td data-label="Created At"><?= htmlspecialchars($row['created_at']); ?></td>
    <td data-label="Actions">
        <button onclick="viewOrderProcessing(<?= $row['id']; ?>)" class="btn btn-info btn-sm">View</button>
        <button onclick="editOrderProcessing(<?= $row['id']; ?>)" class="btn btn-warning btn-sm">Edit</button>
        <button onclick="deleteOrderProcessing(<?= $row['id']; ?>)" class="btn btn-danger btn-sm">Delete</button>
        <button onclick="generateBatchReport(<?= $row['id']; ?>)" class="btn btn-primary btn-sm">Batch Report</button>
    </td>
</tr>

        <?php endwhile; ?>
    </tbody>
    </table>
</div>

<!-- Add Order Processing Modal -->
<div class="modal fade" id="addOrderProcessingModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">Add Order Processing</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <form id="addOrderProcessingForm">
                    <div class="mb-3">
                        <label for="order_id" class="form-label">Order</label>
                        <select class="form-control" id="order_id" name="order_id" required>
                            <option value="">Select Order</option>
                            <?php 
                            $orders = $conn->query("SELECT id, order_no FROM orders WHERE status='active' AND (order_quantity_m3 - process_qty) > 0");
                            while ($row = $orders->fetch_assoc()): ?>
                                <option value="<?= $row['id'] ?>"><?= htmlspecialchars($row['order_no']) ?></option>
                            <?php endwhile; ?>
                        </select>
                    </div>

                    <div class="mb-3">
                        <label for="truck_id" class="form-label">Truck</label>
                        <select class="form-control" id="truck_id" name="truck_id" required>
                            <option value="">Select Truck</option>
                            <?php 
                            $trucks = $conn->query("SELECT id, reg_no FROM vehicles WHERE status='active'");
                            while ($row = $trucks->fetch_assoc()): ?>
                                <option value="<?= $row['id'] ?>"><?= htmlspecialchars($row['reg_no']) ?></option>
                            <?php endwhile; ?>
                        </select>
                    </div>

                    <div class="mb-3">
                        <label for="driver_id" class="form-label">Driver</label>
                        <select class="form-control" id="driver_id" name="driver_id" required>
                            <option value="">Select Driver</option>
                            <?php 
                            $drivers = $conn->query("SELECT id, name FROM drivers WHERE status='active'");
                            while ($row = $drivers->fetch_assoc()): ?>
                                <option value="<?= $row['id'] ?>"><?= htmlspecialchars($row['name']) ?></option>
                            <?php endwhile; ?>
                        </select>
                    </div>

                    <div class="mb-3">
                        <label for="recipe_id" class="form-label">Recipe</label>
                        <select class="form-control" id="recipe_id" name="recipe_id" required>
                            <option value="">Select Recipe</option>
                            <?php 
                            $recipes = $conn->query("SELECT id, recipe_name FROM recipes WHERE status='active'");
                            while ($row = $recipes->fetch_assoc()): ?>
                                <option value="<?= $row['id'] ?>"><?= htmlspecialchars($row['recipe_name']) ?></option>
                            <?php endwhile; ?>
                        </select>
                    </div>

                    <div class="mb-3">
                        <label for="batch_date" class="form-label">Batch Date</label>
                        <input type="date" class="form-control" id="batch_date" name="batch_date" required>
                    </div>

                    <div class="mb-3">
                        <label for="batch_start_time" class="form-label">Batch Start Time</label>
                        <input type="datetime-local" class="form-control" id="batch_start_time" name="batch_start_time" required>
                    </div>

                    <div class="mb-3">
                        <label for="batch_end_time" class="form-label">Batch End Time</label>
                        <input type="datetime-local" class="form-control" id="batch_end_time" name="batch_end_time" required>
                    </div>
                    
                    <div class="mb-3">
                        <label for="Order_qty" class="form-label">Order Quantity (m³)</label>
                        <input type="text" class="form-control" id="order_qty" name="order_qty" readonly>
                    </div>

                    <div class="mb-3">
                        <label for="remaining_qty" class="form-label">Remaining Quantity (m³)</label>
                        <input type="text" class="form-control" id="remaining_qty" name="remaining_qty" readonly>
                    </div>

                    <div class="mb-3">
                        <label for="batch_number" class="form-label">Batch Number</label>
                        <input type="text" class="form-control" id="batch_number" name="batch_number" readonly>
                    </div>

                    <div class="mb-3">
                        <label for="process_quantity" class="form-label">Processing Quantity (m³)</label>
                        <input type="number" class="form-control" id="process_quantity" name="process_quantity" step="0.01" required>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
                <button class="btn btn-primary" onclick="submitOrderProcessingForm()">Save</button>
            </div>
        </div>
    </div>
</div>





<!-- View Order Processing Modal -->
<div class="modal fade" id="viewOrderProcessingModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">Order Processing Details</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <p><strong>Order No:</strong> <span id="viewOrderNo"></span></p>
                <p><strong>Truck:</strong> <span id="viewTruck"></span></p>
                <p><strong>Driver:</strong> <span id="viewDriver"></span></p>
                <p><strong>Order Quantity:</strong> <span id="viewOrderQty"></span> m³</p>
                <p><strong>Processed Quantity:</strong> <span id="viewProcessQty"></span> m³</p>
                <p><strong>Batch Date:</strong> <span id="viewBatchDate"></span></p>
                <p><strong>Batch Start Time:</strong> <span id="viewBatchStart"></span></p>
                <p><strong>Batch End Time:</strong> <span id="viewBatchEnd"></span></p>
                <p><strong>Batch Number:</strong> <span id="viewBatchNo"></span></p>
            </div>
            <div class="modal-footer">
                <button class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
            </div>
        </div>
    </div>
</div>

<!-- Edit Order Processing Modal -->
<div class="modal fade" id="editOrderProcessingModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">Edit Order Processing</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <form id="editOrderProcessingForm">
                    <input type="hidden" id="edit_order_id" name="edit_order_id">

                    <!-- Order Number Dropdown -->
                    <div class="mb-3">
                        <label for="edit_order_no" class="form-label">Order Number</label>
                        <select class="form-control" id="edit_order_no" name="edit_order_no" required>
                            <option value="">Select Order</option>
                        </select>
                    </div>

                    <!-- Batch Details -->
                    <div class="mb-3">
                        <label for="edit_batch_number" class="form-label">Batch Number</label>
                        <input type="text" class="form-control" id="edit_batch_number" name="edit_batch_number" readonly>
                    </div>

                    <div class="mb-3">
                        <label for="edit_batch_date" class="form-label">Batch Date</label>
                        <input type="date" class="form-control" id="edit_batch_date" name="edit_batch_date" required>
                    </div>

                    <div class="mb-3">
                        <label for="edit_batch_start_time" class="form-label">Batch Start Time</label>
                        <input type="datetime-local" class="form-control" id="edit_batch_start_time" name="edit_batch_start_time" required>
                    </div>

                    <div class="mb-3">
                        <label for="edit_batch_end_time" class="form-label">Batch End Time</label>
                        <input type="datetime-local" class="form-control" id="edit_batch_end_time" name="edit_batch_end_time" required>
                    </div>

                    <!-- Truck Dropdown -->
                    <div class="mb-3">
                        <label for="edit_truck_id" class="form-label">Truck</label>
                        <select class="form-control" id="edit_truck_id" name="edit_truck_id" required>
                            <option value="">Select Truck</option>
                        </select>
                    </div>

                    <!-- Driver Dropdown -->
                    <div class="mb-3">
                        <label for="edit_driver_id" class="form-label">Driver</label>
                        <select class="form-control" id="edit_driver_id" name="edit_driver_id" required>
                            <option value="">Select Driver</option>
                        </select>
                    </div>

                    <!-- Recipe Dropdown -->
                    <div class="mb-3">
                        <label for="edit_recipe_id" class="form-label">Recipe</label>
                        <select class="form-control" id="edit_recipe_id" name="edit_recipe_id" required>
                            <option value="">Select Recipe</option>
                        </select>
                    </div>

                    <!-- Processing Quantities -->
                    <div class="mb-3">
                        <label for="edit_ordered_quantity" class="form-label">Ordered Quantity (m³)</label>
                        <input type="number" class="form-control" id="edit_ordered_quantity" name="edit_ordered_quantity" readonly>
                    </div>

                    <div class="mb-3">
                        <label for="edit_process_quantity" class="form-label">Processing Quantity (m³)</label>
                        <input type="number" class="form-control" id="edit_process_quantity" name="edit_process_quantity" step="0.01" required>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
                <button class="btn btn-primary" onclick="updateOrderProcessing()">Save Changes</button>
            </div>
        </div>
    </div>
</div>






            </div>  
          </div>

        </div>
      </div>
    </section>

  </main><!-- End #main -->
  
  
  
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
  <script>
  
function getOrderDetails() {
    var orderId = document.getElementById("order_id").value;
    if (!orderId) {
        alert("Please select an order.");
        return;
    }

    var formData = new FormData();
    formData.append("action", "get_order_details");
    formData.append("order_id", orderId);

    fetch("order_processing_actions.php", {
        method: "POST",
        body: formData
    })
    .then(response => response.json())
    .then(data => {
        console.log("Server Response:", data); // Debugging

        if (data.error) {
            alert("Error: " + data.error);
            return;
        }

        // Update form fields with order details
        document.getElementById("order_qty").value = data.order_quantity_m3;
        
        document.getElementById("remaining_qty").value = data.remaining_qty;
        document.getElementById("batch_number").value = data.next_batch_number;
    })
    .catch(error => {
        console.error("Fetch Error:", error);
        alert("Failed to load order details. Check the console.");
    });
}

// Attach the function to the `onchange` event of the order dropdown
document.getElementById("order_id").addEventListener("change", getOrderDetails);





function submitOrderProcessingForm() {
    var formData = new FormData(document.getElementById("addOrderProcessingForm"));
    formData.append("action", "add");

    var xhr = new XMLHttpRequest();
    xhr.open("POST", "order_processing_actions.php", true);

    xhr.onload = function () {
        alert(xhr.responseText);
        location.reload();
    };

    xhr.send(formData);
}

function deleteOrderProcessing(id) {
    if (confirm("Are you sure you want to delete this order processing record?")) {
        var formData = new FormData();
        formData.append("id", id);
        formData.append("action", "delete");

        var xhr = new XMLHttpRequest();
        xhr.open("POST", "order_processing_actions.php", true);
        xhr.onload = function () {
            alert(xhr.responseText);
            location.reload();
        };
        xhr.send(formData);
    }
}

function generateBatchReport(orderId) {
    window.open("lib/generate_batch_report.php?order_id=" + orderId, "_blank");
}


function submitEditOrderProcessingForm() {
    var formData = new FormData(document.getElementById("editOrderProcessingForm"));
    formData.append("action", "edit");

    var xhr = new XMLHttpRequest();
    xhr.open("POST", "order_processing_actions.php", true);

    xhr.onload = function () {
        alert(xhr.responseText);
        location.reload();
    };

    xhr.send(formData);
}

function viewOrderProcessing(id) {
    var xhr = new XMLHttpRequest();
    xhr.open("GET", "order_processing_actions.php?id=" + id, true);

    xhr.onload = function () {
        if (xhr.status === 200) {
            try {
                var data = JSON.parse(xhr.responseText);

                if (data.error) {
                    alert("Error: " + data.error);
                    return;
                }

                // Ensure elements exist before modifying them
                if (document.getElementById("viewOrderNo")) {
                    document.getElementById("viewOrderNo").innerText = data.order_no;
                    document.getElementById("viewTruck").innerText = data.truck_no;
                    document.getElementById("viewDriver").innerText = data.driver_name;
                    document.getElementById("viewOrderQty").innerText = data.ordered_quantity;
                    document.getElementById("viewProcessQty").innerText = data.process_quantity;
                    document.getElementById("viewBatchDate").innerText = data.batch_date;
                    document.getElementById("viewBatchStart").innerText = data.batch_start_time;
                    document.getElementById("viewBatchEnd").innerText = data.batch_end_time;
                    document.getElementById("viewBatchNo").innerText = data.batch_number;

                    var modal = new bootstrap.Modal(document.getElementById("viewOrderProcessingModal"));
                    modal.show();
                } else {
                    console.error("View modal elements not found.");
                }
            } catch (error) {
                console.error("Error parsing JSON: ", error);
                alert("Failed to load order details.");
            }
        } else {
            alert("Error loading data.");
        }
    };

    xhr.send();
}

function editOrderProcessing(id) {
    var formData = new FormData();
    formData.append("action", "get_order_processing");
    formData.append("id", id);

    fetch("order_processing_actions.php", {
        method: "POST",
        body: formData
    })
    .then(response => response.json())
    .then(data => {
        if (data.error) {
            alert("Error: " + data.error);
            return;
        }

        if (document.getElementById("edit_order_id")) {
            document.getElementById("edit_order_id").value = data.id;

            // Load Order No Dropdown
            fetch("order_processing_actions.php?action=get_orders")
                .then(response => response.json())
                .then(orderData => {
                    var orderDropdown = document.getElementById("edit_order_no");
                    orderDropdown.innerHTML = "";
                    orderData.forEach(order => {
                        var option = document.createElement("option");
                        option.value = order.id;
                        option.textContent = order.order_no;
                        if (order.id == data.order_id) {
                            option.selected = true;
                        }
                        orderDropdown.appendChild(option);
                    });
                });

            document.getElementById("edit_batch_number").value = data.batch_number;
            document.getElementById("edit_batch_date").value = data.batch_date;
            document.getElementById("edit_batch_start_time").value = data.batch_start_time;
            document.getElementById("edit_batch_end_time").value = data.batch_end_time;

            document.getElementById("edit_truck_id").value = data.truck_id;
            document.getElementById("edit_driver_id").value = data.driver_id;
            document.getElementById("edit_recipe_id").value = data.recipe_id;

            document.getElementById("edit_ordered_quantity").value = data.ordered_quantity;
            document.getElementById("edit_process_quantity").value = data.process_quantity;

            var modal = new bootstrap.Modal(document.getElementById("editOrderProcessingModal"));
            modal.show();
        } else {
            console.error("Edit modal elements not found.");
        }
    })
    .catch(error => {
        console.error("Fetch Error:", error);
        alert("Failed to load order details.");
    });
}





</script>
  <!-- ======= Footer ======= -->
  <?php include '../config/footer.php'; ?>

  <a href="#" class="back-to-top d-flex align-items-center justify-content-center"><i class="bi bi-arrow-up-short"></i></a>

  <!-- Vendor JS Files -->
  <script src="../assets/vendor/apexcharts/apexcharts.min.js"></script>
  <script src="../assets/vendor/bootstrap/js/bootstrap.bundle.min.js"></script>
  <script src="../assets/vendor/chart.js/chart.umd.js"></script>
  <script src="../assets/vendor/echarts/echarts.min.js"></script>
  <script src="../assets/vendor/quill/quill.js"></script>
  <script src="../assets/vendor/simple-datatables/simple-datatables.js"></script>
  <script src="../assets/vendor/tinymce/tinymce.min.js"></script>
  <script src="../assets/vendor/php-email-form/validate.js"></script>

  <!-- Template Main JS File -->
  <script src="../assets/js/main.js"></script>

</body>

</html>