<?php
include("../../../include/startup.php");
include("stand_alone_work_order_function.inc.php");

ini_set('display_errors', '0');
ini_set('log_errors', '1');
ini_set('error_log', __DIR__ . '/manual_wo_errors.log');
error_reporting(E_ALL);

if(isset($_REQUEST['action']) && $_REQUEST['action']=='fetch_part_meta'){

    $part_id = $_POST['part_id'] ?? '';

    if ($part_id === '' || !is_numeric($part_id)) {
        echo json_encode(['group_type' => 'none', 'has_set' => false]);
        die;
    }
    $part_id = intval($part_id);

    $group_type = 'none';
    $group_query = "SELECT DISTINCT gm.group_type
                     FROM group_mangmnt_mapping gmm
                     JOIN group_mangmnt gm ON gmm.group_id = gm.id
                     WHERE gmm.part_id = $part_id";
    $group_result = mysqli_query($conn, $group_query);
    if ($group_result && mysqli_num_rows($group_result) > 0) {
        $has_mandatory = false;
        while ($row = mysqli_fetch_assoc($group_result)) {
            if ($row['group_type'] == 'mandatory') { $has_mandatory = true; }
        }
        $group_type = $has_mandatory ? 'mandatory' : 'optional';
    }

    function mw_hasSetInBom($conn, $part_id, &$visited = []) {
        if (in_array($part_id, $visited)) return false;
        $visited[] = $part_id;

        $check_query = "SELECT 1 FROM set_mangmnt_mapping WHERE part_id = $part_id LIMIT 1";
        $check_result = mysqli_query($conn, $check_query);
        if ($check_result && mysqli_num_rows($check_result) > 0) {
            return true;
        }

        $bom_query = "SELECT sub_part_id FROM bom WHERE main_product_id = $part_id";
        $bom_result = mysqli_query($conn, $bom_query);
        while ($bom_result && $row = mysqli_fetch_assoc($bom_result)) {
            if (mw_hasSetInBom($conn, $row['sub_part_id'], $visited)) {
                return true;
            }
        }

        return false;
    }

    $visited = [];
    $has_set = mw_hasSetInBom($conn, $part_id, $visited);

    echo json_encode([
        'group_type' => $group_type,
        'has_set'    => $has_set
    ]);
    die;

}else if(isset($_REQUEST['action']) && $_REQUEST['action']=='check_group_type'){
    $part_id = $_POST['part_id'] ?? '';
    if ($part_id === '' || !is_numeric($part_id)) {
        echo json_encode(['group_type' => 'none']);
        die;
    }
    $part_id = intval($part_id);

    $query = "SELECT DISTINCT gmm.group_id, gm.group_type, gm.group_number
              FROM group_mangmnt_mapping gmm
              JOIN group_mangmnt gm ON gmm.group_id = gm.id
              WHERE gmm.part_id = $part_id";

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

    if(mysqli_num_rows($result) > 0) {
        $groups = [];
        while($row = mysqli_fetch_assoc($result)) {
            $groups[] = [
                'group_id'     => $row['group_id'],
                'group_type'   => $row['group_type'],
                'group_number' => $row['group_number']
            ];
        }

        $mandatory_groups = array_filter($groups, function($g) { return $g['group_type'] === 'mandatory'; });
        $mandatory_groups = array_values($mandatory_groups);

        if (count($mandatory_groups) === 1) {
            echo json_encode([
                'group_id'   => $mandatory_groups[0]['group_id'],
                'group_type' => 'mandatory'
            ]);
        } elseif (count($mandatory_groups) > 1) {
            echo json_encode([
                'group_type' => 'mandatory_multiple',
                'groups'     => $mandatory_groups
            ]);
        } else {
            echo json_encode([
                'group_id'   => $groups[0]['group_id'],
                'group_type' => $groups[0]['group_type']
            ]);
        }
    } else {
        echo json_encode(['group_type' => 'none']);
    }
    die;

}else if(isset($_REQUEST['action']) && $_REQUEST['action']=='fetch_group_items'){
    // NOTE: unlike the production_planning version of this action, there is
    // no cross-check against production_planning here — manual entries have
    // nothing to match against, so the "Not In List" column is dropped.
    $part_id   = $_POST['part_id'];
    $order_qty = $_POST['order_qty'];

    $query = "SELECT DISTINCT gmm.group_id, gm.group_number, gm.group_type
              FROM group_mangmnt_mapping gmm
              JOIN group_mangmnt gm ON gmm.group_id = gm.id
              WHERE gmm.part_id = $part_id";

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

    if(mysqli_num_rows($result) > 0) {
        $output = '<table class="table">
                        <tr><th>Group Number</th><th>Part Numbers</th><th>Type</th></tr>';

        while ($row = mysqli_fetch_assoc($result)) {
            $group_id     = $row['group_id'];
            $group_number = $row['group_number'];
            $group_type   = $row['group_type'];

            $part_query  = "SELECT part_id FROM group_mangmnt_mapping WHERE group_id = $group_id";
            $part_result = mysqli_query($conn, $part_query);

            $part_names = [];
            while ($part_row = mysqli_fetch_assoc($part_result)) {
                $loop_part_id = $part_row['part_id'];
                $part_names[] = utility::getTableFieldById("item_management", "part_number", "id", $loop_part_id);
            }

            $part_names_list = implode(', ', $part_names);

            $type_badge = ($group_type == 'mandatory')
                ? '<span class="badge badge-danger">Mandatory</span>'
                : '<span class="badge badge-warning">Optional</span>';

            $output .= '<tr class="group-item-row_1" data-group-id="' . $group_id . '" data-orderqty-id="' . $order_qty . '" data-part-id="' . $part_id . '" style="cursor:pointer;">
                            <td>' . $group_number . '</td>
                            <td>' . $part_names_list . '</td>
                            <td>' . $type_badge . '</td>
                        </tr>';
        }

        $output .= '</table>';
        echo $output;
    } else {
        echo '<div class="alert alert-info">No groups found for this part.</div>';
    }
    die;

}else if(isset($_REQUEST['action']) && $_REQUEST['action']=='fetch_group_details'){
    $group_id  = $_POST['group_id'];
    $part_id   = $_POST['part_id'];
    $order_qty = !empty($_POST['order_qty']) ? $_POST['order_qty'] : 1;

    $group_type_query  = "SELECT group_type FROM group_mangmnt WHERE id = $group_id";
    $group_type_result = mysqli_query($conn, $group_type_query);
    $group_type_row    = mysqli_fetch_assoc($group_type_result);
    $group_type        = $group_type_row['group_type'] ?? 'optional';

    $query  = "SELECT part_id FROM group_mangmnt_mapping WHERE group_id = $group_id";
    $result = mysqli_query($conn, $query);

    $part_number = utility::getTableFieldById("item_management","part_number","id",$part_id);

    $output = '<div class="alert alert-primary" style="background-color: #007bff; color: white; font-weight: bold; text-align: center;">';
    $output .= '<h5 style="margin: 0;">Main Part Number: ' . htmlspecialchars($part_number) . '</h5>';
    $output .= '</div>';

    $type_display = ($group_type == 'mandatory')
        ? '<div class="alert alert-info"><strong>Mandatory Group:</strong> All items must be produced together</div>'
        : '<div class="alert alert-warning"><strong>Optional Group:</strong> You can choose to produce these items together</div>';

    $output .= $type_display;
    $output .= '<table class="table">
                    <tr><th>Part Number</th><th>Quantity</th></tr>';

    while ($row = mysqli_fetch_assoc($result)) {
        $current_part_id = $row['part_id'];
        $qty_value = ($group_type === 'mandatory') ? $order_qty : (($part_id == $current_part_id) ? $order_qty : 1);

        $part_name = utility::getTableFieldById("item_management", "part_number", "id", $current_part_id);

        $output .= '<tr class="group-item-row" data-group-item-id="' . $current_part_id . '">
                        <td>' . $part_name . '</td>
                        <td><input type="number" class="group-item-qty form-control" min="0" value="' . $qty_value . '"></td>
                    </tr>';
    }

    $output .= '</table>';
    $output .= '<div class="text-center">';
    $output .= '<button id="submitGroupOrder" class="btn btn-success">Continue</button>';
    $output .= '</div>';

    echo $output;
    die;

}else if (isset($_REQUEST['action']) && $_REQUEST['action'] == 'fetch_set_items') {

    $orderData = json_decode($_POST['orderData'], true);

    $product_ids = [];
    foreach ($orderData as $item) {
        $product_ids[] = $item['groupItemId'];
    }

    $operations_ids = [];

    function processOrderHybridforset_manual($product_ids, $conn, $depth = 0, $max_depth = 10)
    {
        global $operations_ids;

        foreach ($product_ids as $product_id) {
            $operations_ids[] = [
                'product_id' => $product_id,
            ];

            $query     = "SELECT sub_part_id FROM bom WHERE main_product_id = $product_id";
            $bom_parts = $conn->query($query);

            if ($bom_parts && $bom_parts->num_rows > 0 && $depth < $max_depth) {
                while ($bom = $bom_parts->fetch_assoc()) {
                    $sub_part_id = $bom['sub_part_id'];
                    $operations_ids[] = [
                        'product_id' => $sub_part_id,
                        'parent_ids' => [$product_id]
                    ];
                    processOrderHybridforset_manual([$sub_part_id], $conn, $depth + 1, $max_depth);
                }
            }
        }

        return true;
    }

    processOrderHybridforset_manual($product_ids, $conn);

    $productIds = [];
    foreach ($operations_ids as $operation) {
        $productIds[$operation['product_id']] = true;
    }
    $productIds = array_keys($productIds);

    $productDetails = [];

    foreach ($productIds as $productId) {
        $sqlMapping = "
        SELECT
            sm.set_id,
            sm.part_id,
            sm.ratio,
            smm.description,
            smm.set_number
        FROM
            set_mangmnt_mapping sm
        INNER JOIN
            set_mangmnt smm
        ON
            sm.set_id = smm.id
        WHERE
            sm.part_id = '$productId'
            AND smm.preferred_set = 0
        ";
        $result = mysqli_query($conn, $sqlMapping);

        if ($result && mysqli_num_rows($result) > 0) {
            while ($row = mysqli_fetch_assoc($result)) {
                $row['part_name'] = utility::getTableFieldById("item_management", "part_number", "id", $row['part_id']);
                $productDetails[] = $row;
            }
        }
    }

    $groupedSets = [];
    foreach ($productDetails as $item) {
        $setId = $item['set_id'];

        if (!isset($groupedSets[$setId])) {
            $groupedSets[$setId] = [
                'set_number' => $item['set_number'],
                'description' => $item['description'],
                'set_id' => $item['set_id'],
                'parts' => []
            ];
        }

        $exists = false;
        foreach ($groupedSets[$setId]['parts'] as $existingPart) {
            if ($existingPart['part_id'] == $item['part_id']) {
                $exists = true;
                break;
            }
        }

        if (!$exists) {
            $groupedSets[$setId]['parts'][] = [
                'part_id' => $item['part_id'],
                'part_name' => $item['part_name'],
                'ratio' => $item['ratio']
            ];
        }
    }

    $output = '<table class="table table-bordered table-striped" style="font-size:12px;">
                <thead>
                    <tr>
                        <th style="width:35%">Part Numbers</th>
                        <th style="width:20%">Set Number</th>
                        <th style="width:35%">Description</th>
                        <th style="width:10%">Select</th>
                    </tr>
                </thead><tbody>';

    if (empty($groupedSets)) {
        $output .= '<tr><td colspan="4" class="text-center">No set items found.</td></tr>';
    } else {
        foreach ($groupedSets as $set) {
            $part_names = array_column($set['parts'], 'part_name');
            $part_names_string = implode(', ', $part_names);

            $description_display = $set['description'];
            $description_short = strlen($description_display) > 50 ? substr($description_display, 0, 50) . '...' : $description_display;

            $part_ids = array_column($set['parts'], 'part_id');
            $part_ids_string = implode(',', $part_ids);

            $output .= '
                <tr class="set-item-row"
                    data-set-id="' . htmlspecialchars($set['set_id']) . '"
                    data-part-ids="' . htmlspecialchars($part_ids_string) . '">
                    <td style="text-align:left;">
                        ' . htmlspecialchars($part_names_string) . '
                        <span class="badge badge-info" style="margin-left:5px;">' . count($set['parts']) . ' parts</span>
                    </td>
                    <td>' . htmlspecialchars($set['set_number']) . '</td>
                    <td style="text-align:left;" title="' . htmlspecialchars($set['description']) . '">' . htmlspecialchars($description_short) . '</td>
                    <td>
                        <input type="checkbox" class="set-group-checkbox" checked>
                    </td>
                </tr>';
        }
    }

    $output .= '</tbody></table>';
    $output .= '<div class="text-center"><button id="submitSetOrder" class="btn btn-success mt-2">Continue</button></div>';

    echo $output;
    exit;

}else if (isset($_REQUEST['action']) && $_REQUEST['action'] == 'create_manual_work_order') {
header('Content-Type: application/json');
    $orderData     = json_decode($_REQUEST['orderData'] ?? '', true);
    $setorderData  = json_decode($_REQUEST['setorderData'] ?? '', true);
    if (!is_array($orderData))    { $orderData = []; }
    if (!is_array($setorderData)) { $setorderData = []; }
    $group_id      = intval($_REQUEST['group_id'] ?? 0);
    $customer      = $_REQUEST['customer'] ?? '';
    $required_date = $_REQUEST['required_date'] ?? '';

    // Remove zero quantity items
    $orderData = array_filter($orderData, function($item){
        return isset($item['quantity']) && floatval($item['quantity']) > 0;
    });
    $orderData = array_values($orderData);

    if (empty($orderData) || empty($customer) || empty($required_date)) {
        echo json_encode(['status' => 'failure', 'message' => 'Missing required fields.']);
        die;
    }

    $product_ids       = array_column($orderData, 'groupItemId');
    $order_quantities  = array_column($orderData, 'quantity');

    if (!empty($setorderData)) {
        $set_check = 1;
        $setproduct_ids = array_column($setorderData, 'setItemId');
        $set_ids = array_column($setorderData, 'setId');
        $setproduct_ids_str = implode(",", $setproduct_ids);
        $set_ids_str = implode(",", $set_ids);
    } else {
        $set_check = 0;
        $setproduct_ids_str = '';
        $set_ids_str = '';
    }

    $shift_ids = [];
    $result = $conn->query("SELECT id FROM working_hours");
    while ($row = $result->fetch_assoc()) {
        $shift_ids[] = $row['id'];
    }
    $shift_idss = implode(",", $shift_ids);

    $selectedReqDate      = $required_date;
    $selectedCustomerReff = $customer;

    if (!function_exists('getPreviousWorkingDate')) {
    function getPreviousWorkingDate($targetDate, $shift_ids, $conn, $days_to_subtract = 2)
    {
        $working_hours = calculateShiftHours($shift_ids, $conn);

        $holidays = [];
        $result = $conn->query("SELECT holiday_date FROM admin_holidays");
        while ($row = $result->fetch_assoc()) {
            $holidays[$row['holiday_date']] = true;
        }

        $date = new DateTime($targetDate);
        $working_days_subtracted = 0;

        while ($working_days_subtracted < $days_to_subtract) {
            $date->modify('-1 day');
            $day_index = (int)$date->format('w');
            $date_str = $date->format('Y-m-d');
            if (isset($holidays[$date_str])) continue;
            if (empty($working_hours[$day_index]) || $working_hours[$day_index] <= 0) continue;
            $working_days_subtracted++;
        }

        return $date->format('Y-m-d');
    }
    }

    $required_date_offset = getPreviousWorkingDate($selectedReqDate, $shift_ids, $conn, 2);

    $rr_row = $conn->query("SELECT IFNULL(MAX(CAST(SUBSTRING(work_order_no, 5) AS UNSIGNED)), 0) + 1 AS new_order FROM work_order_customer_ref_mapping")->fetch_assoc();
    $work_order_name = 'order-' . str_pad($rr_row['new_order'], 3, '0', STR_PAD_LEFT);

    $created_by = $_SESSION['user_id'] ?? 0;
    $created_on = date('Y-m-d H:i:s');

    $query_work_order = "
        INSERT INTO work_order
        (customer_id, work_order_no, product_id, order_quantity, require_date, set_product_ids, set_ids, shift_ids, group_id, is_manual, created_by, created_on)
        VALUES (
            '$selectedCustomerReff',
            '$work_order_name',
            '" . implode(",", $product_ids) . "',
            '" . implode(",", $order_quantities) . "',
            '$selectedReqDate',
            '$setproduct_ids_str',
            '$set_ids_str',
            '$shift_idss',
            '$group_id',
            1,
            '$created_by',
            '$created_on'
        )";
    $conn->query($query_work_order);
    $work_order_id = $conn->insert_id;

    foreach ($product_ids as $index => $product_id) {
        $rr_row = $conn->query("SELECT IFNULL(MAX(CAST(SUBSTRING(work_order_no, 5) AS UNSIGNED)), 0) + 1 AS new_enq FROM work_order_customer_ref_mapping")->fetch_assoc();
        $work_order_no = 'CCO-' . str_pad($rr_row['new_enq'], 3, '0', STR_PAD_LEFT);
        $quantity = $order_quantities[$index];
        $conn->query("INSERT INTO work_order_customer_ref_mapping (work_order_no, work_order_id, quantity, product_id) VALUES ('$work_order_no', '$work_order_id', '$quantity', '$product_id')");
    }

    $flag = 1;
    processOrderHybrid($product_ids, $order_quantities, $shift_ids, $conn, $required_date_offset, $work_order_id, $flag, $setorderData);

    global $operations;
    $grouped_operations = [];
    foreach ($operations as $operation) {
        $grouped_operations[$operation['product_code']][] = $operation;
    }

    foreach ($grouped_operations as $ops) {
        foreach ($ops as $op) {
            if (in_array($op['process_type'], [6, 4, 12, 21])) {
                $parent_ids = is_array($op['parent_ids']) ? implode(',', $op['parent_ids']) : $op['parent_ids'];

                $query = "
                    INSERT INTO work_order_detail
                    (work_order_id, product_code, product_name, operation_description, product_id, quantity, required_date, process_type, parent_ids, machine, shift_idss, total_time, created_on, created_by)
                    VALUES (
                        '$work_order_id',
                        '{$op['product_code']}',
                        '{$op['product_name']}',
                        '{$op['operation']}',
                        '{$op['product_id']}',
                        '{$op['qty']}',
                        '{$op['required_date']}',
                        '{$op['process_type']}',
                        '$parent_ids',
                        '{$op['machine']}',
                        '$shift_idss',
                        '{$op['total_time']}',
                        '$created_on',
                        '$created_by'
                    )";
                $conn->query($query);
            }
        }
    }

    if (!function_exists('normalizeParentIds')) {
    function normalizeParentIds($parent_ids) {
        if (empty($parent_ids)) return [];
        $parent_ids = str_replace('Array,', '', $parent_ids);
        $ids = array_map('trim', explode(',', $parent_ids));
        return array_filter($ids, 'is_numeric');
    }
    }

    if ($set_check == 1) {
        foreach ($setorderData as $setitem) {
            $conn->query("
                UPDATE work_order_detail
                SET set_id = '{$setitem['setId']}'
                WHERE product_id = '{$setitem['setItemId']}'
                  AND work_order_id = '$work_order_id'
            ");
        }
    }

    $result_p = $conn->query("
        SELECT
            product_id,
            quantity,
            required_date,
            machine,
            shift_idss,
            parent_ids,
            set_id,
            product_name,
            total_time
        FROM work_order_detail
        WHERE process_type = 6
          AND work_order_id = $work_order_id
    ");

    $grouped_data = [];

    while ($row_p = $result_p->fetch_assoc()) {

        $set_id = (int)$row_p['set_id'];
        $product_id = (int)$row_p['product_id'];
        $set_number = '';
        $description = '';

        if ($set_id > 0) {
            $setRes = $conn->query("
                SELECT description, set_number
                FROM set_mangmnt
                WHERE id = $set_id
                LIMIT 1
            ");

            if ($setRes && $setRes->num_rows > 0) {
                $setRow = $setRes->fetch_assoc();
                $set_number = $setRow['set_number'];
                $description = $setRow['description'];
            }

        } else {
            $itemRes = $conn->query("
                SELECT part_number, product_description
                FROM item_management
                WHERE id = $product_id
                LIMIT 1
            ");

            if ($itemRes && $itemRes->num_rows > 0) {
                $itemRow = $itemRes->fetch_assoc();
                $description = $itemRow['product_description'];
            }
        }

        $key = ($set_id > 0) ? "set_$set_id" : "product_{$row_p['product_id']}";

        if (!isset($grouped_data[$key])) {
            $grouped_data[$key] = [
                'work_order_id' => $work_order_id,
                'set_id'        => $set_id,
                'set_number'    => $set_number,
                'product_ids'   => [],
                'highest_qty'   => (float)$row_p['quantity'],
                'data_row'      => $row_p
            ];
        }

        $grouped_data[$key]['product_ids'][] = $row_p['product_id'];
        $grouped_data[$key]['description'] = $description;

        if ((float)$row_p['quantity'] > $grouped_data[$key]['highest_qty']) {
            $grouped_data[$key]['highest_qty'] = (float)$row_p['quantity'];
            $grouped_data[$key]['data_row'] = $row_p;
        }
    }

    foreach ($grouped_data as $data) {

        $row_p = $data['data_row'];

        $parentIds = normalizeParentIds($row_p['parent_ids']);
        $parent_ids_str = implode(',', $parentIds);

        $product_name_to_store = ($data['set_id'] > 0)
            ? 'Set-' . $data['set_number']
            : $row_p['product_name'];

        $conn->query("
            INSERT INTO manufacture_machine_table (
                work_order_id,
                part_id,
                end_date,
                quantity,
                machine_id,
                parent_ids,
                product_name,
                description,
                set_id,
                total_hours
            ) VALUES (
                '{$work_order_id}',
                '{$row_p['product_id']}',
                '{$row_p['required_date']}',
                '{$row_p['quantity']}',
                '{$row_p['machine']}',
                '{$parent_ids_str}',
                '{$product_name_to_store}',
                '" . $conn->real_escape_string($data['description']) . "',
                '{$row_p['set_id']}',
                '{$row_p['total_time']}'
            )
        ");

        foreach ($parentIds as $parent_id) {
            $conn->query("
                INSERT INTO manufacture_machine_children (
                    work_order_id,
                    part_id,
                    child_part_id
                ) VALUES (
                    '{$work_order_id}',
                    '{$parent_id}',
                    '{$row_p['product_id']}'
                )
            ");
        }

        $rr_row = $conn->query("
            SELECT IFNULL(MAX(CAST(SUBSTRING(work_order_name, 4) AS UNSIGNED)), 0) + 1 AS new_enq
            FROM work_order_name
        ")->fetch_assoc();

        $new_work_order_name = 'WO-' . str_pad($rr_row['new_enq'], 3, '0', STR_PAD_LEFT);

        $conn->query("
            INSERT INTO work_order_name (
                work_order_id,
                part_id,
                work_order_name
            ) VALUES (
                '{$work_order_id}',
                '{$row_p['product_id']}',
                '{$new_work_order_name}'
            )
        ");
    }

    $result_child = $conn->query("
        SELECT
            id,
            product_id,
            parent_ids
        FROM work_order_detail
        WHERE process_type = 4
          AND work_order_id = $work_order_id
    ");

    while ($child = $result_child->fetch_assoc()) {

        $child_id = $child['id'];
        $parentIds = normalizeParentIds($child['parent_ids']);

        if (!empty($parentIds)) {

            $parent_ids_str = implode(",", $parentIds);

            $parentRes = $conn->query("
                SELECT set_id
                FROM work_order_detail
                WHERE product_id IN ($parent_ids_str)
                  AND process_type = 6
                  AND work_order_id = $work_order_id
                LIMIT 1
            ");

            if ($parentRes && $parentRes->num_rows > 0) {
                $parentRow = $parentRes->fetch_assoc();
                $parent_set_id = $parentRow['set_id'];

                $conn->query("
                    UPDATE work_order_detail
                    SET set_id = '$parent_set_id'
                    WHERE id = '$child_id'
                ");
            }
        }
    }

    $result_pt4 = $conn->query("
        SELECT
            id,
            set_id,
            product_id,
            product_name,
            operation_description,
            quantity,
            required_date
        FROM work_order_detail
        WHERE process_type = 4
          AND work_order_id = $work_order_id
    ");

    $grouped = [];

    while ($row = $result_pt4->fetch_assoc()) {

        $set_id = (int)$row['set_id'];

        if ($set_id > 0) {
            $key = "set_" . $set_id . "_" . $row['product_id'];

            if (!isset($grouped[$key])) {
                $grouped[$key] = $row;
                $grouped[$key]['quantity'] = 0;
            }

            $grouped[$key]['quantity'] += (float)$row['quantity'];

            if ($row['required_date'] < $grouped[$key]['required_date']) {
                $grouped[$key]['required_date'] = $row['required_date'];
            }

        } else {
            $key = "row_" . $row['id'];
            $grouped[$key] = $row;
        }
    }

    foreach ($grouped as $data) {

        $set_id = (int)$data['set_id'];
        $quantity = (float)$data['quantity'];

        if ($set_id > 0) {
            $quantity = ceil($quantity);
        }

        $product_name = $conn->real_escape_string($data['product_name']);
        $operation_description = $conn->real_escape_string($data['operation_description']);

        $conn->query("
            INSERT INTO work_order_raw_matrial (
                work_order_id,
                set_id,
                product_id,
                product_name,
                operation_description,
                quantity,
                quantity_produce,
                required_date
            ) VALUES (
                '$work_order_id',
                '$set_id',
                '{$data['product_id']}',
                '$product_name',
                '$operation_description',
                '$quantity',
                '$quantity',
                '{$data['required_date']}'
            )
        ");
    }

    echo json_encode(['status' => 'success', 'message' => "Manual work order {$work_order_name} created successfully!", 'work_order_id' => $work_order_id]);
    die;
}
?>