<?php
include "../root.class.php";

$db = new db_safeguard();

// Get the latest order_id to inspect
$order_ids_res = $db->query("order_items", "SELECT DISTINCT order_id FROM order_items WHERE 1 ORDER BY record_id DESC");

while ($order_ids = $order_ids_res->fetch_assoc()) {
    $order_id = $order_ids['order_id'];

    $roder_res = $db->query("orders","SELECT * FROM orders WHERE record_id = '$order_id'");
    $order = $roder_res->fetch_assoc();

    // Query to find duplicate stock_ids within THIS specific order
    $dupe_query = "SELECT stock_id, COUNT(*) as qty ,`name`
                   FROM order_items 
                   WHERE order_id = '$order_id' AND stock_type = 2
                   GROUP BY stock_id 
                   HAVING COUNT(*) > 1";

    $dupe_res = $db->query("order_items", $dupe_query);

    if ($dupe_res->num_rows > 0) {
        echo "<h3>ORDER ID: " . $order_id . " - " . $order['po_number'] . "</h3>";
        echo "<ul>";
        while ($dupe = $dupe_res->fetch_assoc()) {
            echo "<li>Duplicate Stock ID: <strong>" . $dupe['stock_id'] . "</strong> (Found " . $dupe['qty'] . " times) as " . $dupe['name'] . "</li>";
        }
        echo "</ul>";
    } else {
        // echo "No duplicate stock IDs found for this order.<br>";
    }
}