<?php 
// ------------------------------------------------------
// HELPER FUNCTIONS — defined first before any usage
// ------------------------------------------------------
include_once("work_order_function.inc.php");
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 (!function_exists('getWorkOrderDataForEdit')) {
    function getWorkOrderDataForEdit($work_order_id, $conn) {
        $orderData    = [];
        $setorderData = [];

        $work_order_id = (int)$work_order_id;

        $orderQuery  = "SELECT product_id, quantity FROM work_order_customer_ref_mapping WHERE work_order_id = $work_order_id";
        $orderResult = mysqli_query($conn, $orderQuery);
        if ($orderResult) {
            while ($orderRow = mysqli_fetch_assoc($orderResult)) {
                $orderData[] = [
                    'groupItemId' => $orderRow['product_id'],
                    'quantity'    => (int)$orderRow['quantity']
                ];
            }
        }

        $setQuery  = "SELECT set_product_ids, set_ids FROM work_order WHERE id = $work_order_id";
        $setResult = mysqli_query($conn, $setQuery);
        if ($setResult && $setRow = mysqli_fetch_assoc($setResult)) {
            $set_product_ids = array_values(array_filter(explode(',', $setRow['set_product_ids'])));
            $set_ids         = array_values(array_filter(explode(',', $setRow['set_ids'])));
            foreach ($set_product_ids as $index => $product_id) {
                if (isset($set_ids[$index])) {
                    $setorderData[] = [
                        'setItemId' => trim($product_id),
                        'setId'     => trim($set_ids[$index])
                    ];
                }
            }
        }

        return [
            'orderData'    => $orderData,
            'setorderData' => $setorderData
        ];
    }
}

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])) continue;

            $working_days_subtracted++;
        }

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

// ------------------------------------------------------
// INCLUDES
// ------------------------------------------------------
include("includes/FCKeditor/fckeditor.php");

$file_name      = "index?page=view";
$form_action    = "insert";
$button_value   = "Add";
$table_name     = "work_order";
$id             = "";
$page_name      = "Edit Work Order";
$from           = $_REQUEST['from'] ?? "";

// ------------------------------------------------------
// INSERT ACTION (holiday — kept as original)
// ------------------------------------------------------
if (isset($_REQUEST['action']) && $_REQUEST['action'] == 'insert') {
    utility::addslashesOnAllInput(array("query_string", "engineer_id"));
    $holiday_name    = $_REQUEST['holiday_name'];
    $from_date       = utility::setFormatedDate($_REQUEST['from_date']);
    $to_date         = utility::setFormatedDate($_REQUEST['to_date']);
    $holiday_type_id = $_REQUEST['holiday_type_id'];
    $engineer_id     = implode(",", $_REQUEST['engineer_id']);
    $created_by      = $_SESSION['user_id'];
    $created_on      = date("Y-m-d H:i:s");
    $updated_by      = $_SESSION['user_id'];

    $sql = "holiday_name = '" . $holiday_name . "', from_date = '" . $from_date . "', to_date = '" . $to_date . "', holiday_type_id = '" . $holiday_type_id . "', engineer_id = '" . $engineer_id . "', created_on = '" . $created_on . "', created_by = '" . $created_by . "', updated_by = '" . $updated_by . "'";
    $sql = "INSERT INTO $table_name SET " . $sql;
    mysqli_query($conn, $sql);
    $holiday_id = mysqli_insert_id($conn);

    if (count($_REQUEST['engineer_id']) > 0) {
        foreach ($_REQUEST['engineer_id'] as $engineer_id) {
            $sql_engineertype_insert = "INSERT INTO engineer_type_mapping (holiday_id, engineer_id, created_by, created_on, updated_by) VALUES('$holiday_id', '$engineer_id', '$created_by', '$created_on', '$updated_by')";
            mysqli_query($conn, $sql_engineertype_insert);
        }
    }

    $_SESSION['info_message'] = "Holiday added successfully";
    header("Location: $file_name");
    exit();
}

// ------------------------------------------------------
// EDIT ACTION — load existing data into form
// ------------------------------------------------------
if (isset($_REQUEST['action']) && $_REQUEST['action'] == 'edit') {
    $id           = $_REQUEST['id'];
    $form_action  = "update";
    $button_value = "Update";
    $page_name    = "Edit Work Order";
    $query_string = (isset($_POST['query_string'])) ? $_POST['query_string'] : $_SERVER['QUERY_STRING'];

    $sql         = "SELECT * FROM $table_name WHERE id = $id";
    $result_edit = mysqli_query($conn, $sql);
    $row_edit    = mysqli_fetch_array($result_edit);
    $row_edit    = utility::validate_crypt_data($row_edit);

    $customer_id    = $row_edit['customer_id'];
    $product_id     = $row_edit['product_id'];
    $order_quantity = $row_edit['order_quantity'];
    $required_date  = $row_edit['require_date'];
    $shift_id       = explode(",", $row_edit['shift_ids']);
}

// =============================================
// UPDATE ACTION
// =============================================
// =============================================
// UPDATE ACTION
// =============================================
if (isset($_REQUEST['action']) && $_REQUEST['action'] == 'update') {

    $work_order_id = (int)$_REQUEST['id'];

    // STEP 0: Collect Inputs
    $product_ids      = array_values((array)$_REQUEST['product_id']);
    $order_quantities = array_values((array)$_REQUEST['order_quantity']);
    $require_datee    = utility::setFormatedDate($_REQUEST['required_date']);
    $updated_by       = $_SESSION['user_id'];

    // STEP 1: Prepare shifts
    $shift_ids = [];
    $res = $conn->query("SELECT id FROM working_hours");
    while ($r = $res->fetch_assoc()) {
        $shift_ids[] = $r['id'];
    }
    $shift_idss = implode(",", $shift_ids);

    // STEP 2: Calculate required start date (2 working days before delivery)
    $required_date = getPreviousWorkingDate($require_datee, $shift_ids, $conn, 2);

    // STEP 3: Update work_order main table
    mysqli_query($conn, "
        UPDATE work_order 
        SET require_date = '$require_datee',
            updated_by   = '$updated_by'
        WHERE id = '$work_order_id'
    ");

    // STEP 4: PRODUCTION PLANNING ADJUSTMENT (DELTA)
    foreach ($product_ids as $index => $product_id) {

        $partId = (int)$product_id;
        $newQty = (float)($order_quantities[$index] ?? 0);

        $oldRes = mysqli_query($conn, "
            SELECT quantity 
            FROM work_order_customer_ref_mapping
            WHERE work_order_id = '$work_order_id'
            AND product_id = '$partId'
            LIMIT 1
        ");
        $oldRow = mysqli_fetch_assoc($oldRes);
        $oldQty = (float)($oldRow['quantity'] ?? 0);
        $diff   = $newQty - $oldQty;

        // INCREASE
        if ($diff > 0) {
            $remainingQty = $diff;
            $result = mysqli_query($conn, "
                SELECT id, req_qty, produce_qty, status
                FROM production_planning
                WHERE part_id = $partId
                AND (status = 0 OR (status = 2 AND work_order_id IS NULL))
                ORDER BY status DESC, req_date ASC, id ASC
            ");
            while ($record = mysqli_fetch_assoc($result)) {
                if ($remainingQty <= 0) break;
                $pendingQty = (float)$record['req_qty'] - (float)$record['produce_qty'];
                if ($pendingQty <= 0) continue;
                if ($remainingQty >= $pendingQty) {
                    $producedQty   = $pendingQty;
                    $remainingQty -= $pendingQty;
                    mysqli_query($conn, "
                        UPDATE production_planning 
                        SET status = 1, produce_qty = produce_qty + $producedQty, work_order_id = '$work_order_id'
                        WHERE id = {$record['id']}
                    ");
                } else {
                    $producedQty  = $remainingQty;
                    $remainingQty = 0;
                    mysqli_query($conn, "
                        UPDATE production_planning 
                        SET status = 2, produce_qty = produce_qty + $producedQty, work_order_id = '$work_order_id'
                        WHERE id = {$record['id']}
                    ");
                }
            }

        // DECREASE
        } elseif ($diff < 0) {
            $reduceQty = abs($diff);
            $result = mysqli_query($conn, "
                SELECT id, produce_qty
                FROM production_planning
                WHERE work_order_id = '$work_order_id' AND part_id = $partId
                ORDER BY req_date DESC, id DESC
            ");
            while ($row = mysqli_fetch_assoc($result)) {
                if ($reduceQty <= 0) break;
                $produced = (float)$row['produce_qty'];
                if ($produced <= $reduceQty) {
                    mysqli_query($conn, "
                        UPDATE production_planning
                        SET produce_qty = 0, status = 0, work_order_id = NULL
                        WHERE id = {$row['id']}
                    ");
                    $reduceQty -= $produced;
                } else {
                    mysqli_query($conn, "
                        UPDATE production_planning
                        SET produce_qty = produce_qty - $reduceQty, status = 2
                        WHERE id = {$row['id']}
                    ");
                    $reduceQty = 0;
                }
            }
        }
    }

    // STEP 5: Update mapping quantities
    foreach ($product_ids as $index => $product_id) {
        $qty = (float)($order_quantities[$index] ?? 0);
        mysqli_query($conn, "
            UPDATE work_order_customer_ref_mapping 
            SET quantity = '$qty'
            WHERE work_order_id = '$work_order_id' AND product_id = '$product_id'
        ");
    }

    // STEP 6: Clear old scheduling
    $conn->query("DELETE FROM work_order_detail            WHERE work_order_id = $work_order_id");
    $conn->query("DELETE FROM manufacture_machine_table    WHERE work_order_id = $work_order_id");
    $conn->query("DELETE FROM manufacture_machine_children WHERE work_order_id = $work_order_id");
    $conn->query("DELETE FROM work_order_name              WHERE work_order_id = $work_order_id");
    $conn->query("DELETE FROM work_order_raw_matrial       WHERE work_order_id = $work_order_id");

    // STEP 7: Rebuild scheduling
    $workOrderData   = getWorkOrderDataForEdit($work_order_id, $conn);
    $setorderData    = $workOrderData['setorderData'];

    // Prepare set variables (needed by insert blocks below)
    if (!empty($setorderData)) {
        $set_check           = 1;
        $setproduct_ids_str  = implode(",", array_column($setorderData, 'setItemId'));
        $set_ids_str         = implode(",", array_column($setorderData, 'setId'));
    } else {
        $set_check           = 0;
        $setproduct_ids_str  = '';
        $set_ids_str         = '';
    }

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

    // STEP 8: Insert work_order_detail rows (process types 6, 4, 12, 21)
    global $operations;
    $grouped_operations = [];
    foreach ($operations as $operation) {
        $grouped_operations[$operation['product_code']][] = $operation;
    }

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

    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'];

                $conn->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'
                    )
                ");
            }
        }
    }

    // STEP 9: Apply set IDs to work_order_detail
    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'
            ");
        }
    }

    // STEP 10: Backfill set_id onto process_type = 4 children
    $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()) {
        $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']}'
                ");
            }
        }
    }

    // STEP 11: Insert into manufacture_machine_table (process_type = 6)
    $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,
                'description'   => $description,
                'product_ids'   => [],
                'highest_qty'   => (float)$row_p['quantity'],
                'data_row'      => $row_p,
            ];
        }
        $grouped_data[$key]['product_ids'][] = $row_p['product_id'];
        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;
            $grouped_data[$key]['description'] = $description;
        }
    }

    foreach ($grouped_data as $data) {
        $row_p       = $data['data_row'];
        $description = $data['description'];

        $shift_names = '';
        if (!empty($row_p['shift_idss'])) {
            $shiftRes    = $conn->query("SELECT GROUP_CONCAT(shift_name) AS shift_names FROM working_hours WHERE FIND_IN_SET(id, '{$row_p['shift_idss']}')");
            $shift_names = $shiftRes->fetch_assoc()['shift_names'];
        }

        $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($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')
        ");
    }

    // STEP 12: Insert into work_order_raw_matrial (process_type = 4)
    $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 {
            $grouped["row_" . $row['id']] = $row;
        }
    }
    foreach ($grouped as $data) {
        $set_id   = (int)$data['set_id'];
        $quantity = ($set_id > 0) ? ceil((float)$data['quantity']) : (float)$data['quantity'];
        $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']}',
                '" . $conn->real_escape_string($data['product_name']) . "',
                '" . $conn->real_escape_string($data['operation_description']) . "',
                '$quantity',
                '$quantity',
                '{$data['required_date']}'
            )
        ");
    }

    $_SESSION['info_message'] = "Work Order updated successfully";
    header("Location: index?page=view");
    exit();
}
// --- END UPDATE ---
?>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/flatpickr/dist/flatpickr.min.css">
<script src="https://cdn.jsdelivr.net/npm/flatpickr"></script>

<style>
em { color: red; font-size: 20px; position: absolute; }
.product-row { background: #f9f9f9; border: 1px solid #ddd; padding: 10px; margin-bottom: 10px; border-radius: 8px; }
.remove-btn { float: right; color: red; cursor: pointer; font-weight: bold; }
</style>

<section class="content-header">
    <div class="container-fluid">
        <div class="row mb-2">
            <div class="col-sm-6">
                <h1><?= $page_name; ?></h1>
            </div>
            <div class="col-sm-6">
                <?php
                $query_string = (isset($_POST['query_string'])) ? $_POST['query_string'] : $_SERVER['QUERY_STRING'];
                if (isset($from) && $from == "view_holiday_details") {
                    $query_string = str_ireplace("page=add", "page=view_holiday_details", $query_string);
                } else {
                    $query_string = str_ireplace("page=edit_work_order", "page=view", $query_string);
                }
                ?>
                <button type="button" id="back" class="btn btn-success"
                    style="float:right; margin-right:5px; margin-bottom:8px;"
                    onclick="window.location.href = 'index?<?= $query_string; ?>'">
                    Back
                </button>
            </div>
        </div>
    </div>
</section>

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

            <?php if (isset($_SESSION['info_message'])) { ?>
                <div class="alert alert-info alert-dismissable">
                    <button type="button" class="close" data-dismiss="alert" aria-hidden="true">&times;</button>
                    <?php echo $_SESSION['info_message'];
                    unset($_SESSION['info_message']); ?>
                </div>
            <?php } ?>

            <div class="card">
                <form method="post" name="form1" id="form1"
                    action="index?page=edit_work_order&action=<?= $form_action; ?>"
                    enctype="multipart/form-data">

                    <div class="card-body">
                        <div class="row">
                            <div class="col-lg-12 col-sm-12">

                                <div class="form-group">
                                    <label>Customer <em>*</em></label>
                                    <?php $gsi->getCustomerList("customer_id_display", $customer_id, "100%", false, "form-control select2 customer_id", "disabled"); ?>
                                    <input type="hidden" name="customer_id" value="<?= $customer_id ?>">
                                </div>

                                <h5 class="mt-3 mb-2">Products</h5>
                                <div id="productContainer">
                                    <?php
                                    $workOrderData = getWorkOrderDataForEdit($id, $conn);
                                    $orderData     = $workOrderData['orderData'];

                                    if (!empty($orderData)) {
                                        foreach ($orderData as $index => $item) {
                                            $productId = $item['groupItemId'];
                                            $quantity  = $item['quantity'];
                                    ?>
                                    <div class="product-row">
                                        <span class="remove-btn" onclick="this.parentNode.remove();">&times;</span>
                                        <div class="form-group">
                                            <label>Product ID <em>*</em></label>
                                            <?php
                                            $gsi->getworkItemList(
                                                "product_id_display[]",
                                                $productId,
                                                "100%",
                                                false,
                                                "form-control select2 product_id",
                                                "disabled"
                                            );
                                            ?>
                                            <input type="hidden" name="product_id[]" value="<?= $productId ?>">
                                        </div>
                                        <div class="form-group">
                                            <label>Order Quantity <em>*</em></label>
                                            <input type="number"
                                                class="form-control"
                                                name="order_quantity[]"
                                                value="<?= $quantity; ?>"
                                                placeholder="Order Quantity"
                                                autocomplete="off">
                                        </div>
                                    </div>
                                    <?php
                                        }
                                    } else {
                                    ?>
                                    <div class="product-row">
                                        <span class="remove-btn" onclick="this.parentNode.remove();">&times;</span>
                                        <div class="form-group">
                                            <label>Product ID <em>*</em></label>
                                            <?php
                                            $gsi->getworkItemList(
                                                "product_id[]",
                                                "",
                                                "100%",
                                                false,
                                                "form-control select2 product_id",
                                                ""
                                            );
                                            ?>
                                        </div>
                                        <div class="form-group">
                                            <label>Order Quantity <em>*</em></label>
                                            <input type="number"
                                                class="form-control"
                                                name="order_quantity[]"
                                                value=""
                                                placeholder="Order Quantity"
                                                autocomplete="off">
                                        </div>
                                    </div>
                                    <?php } ?>
                                </div>

                                <div class="form-group">
                                    <label class="control-label" for="required_date">Required Date</label>
                                    <div>
                                        <input type="text"
                                            class="form-control datepicker"
                                            id="required_date"
                                            name="required_date"
                                            value="<?php echo (isset($required_date) && $required_date != "")
                                                ? utility::getFormatedDate($required_date)
                                                : ""; ?>"
                                            placeholder="DD-MM-YYYY"
                                            autocomplete="off">
                                    </div>
                                </div>

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

                    <div class="card-footer">
                        <input type="hidden" name="id"           value="<?= $id; ?>">
                        <input type="hidden" name="from"         value="<?= $from; ?>">
                        <input type="hidden" name="query_string" value="<?= $query_string; ?>">
                        <button type="submit" class="btn btn-primary">
                            <?= $button_value; ?>
                            <i class="fas fa-sync-alt fa-spin" style="display:none;" id="page_load_div"></i>
                        </button>
                    </div>

                </form>
            </div>

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

<script>
document.getElementById('addProductRow').addEventListener('click', function () {
    const container = document.getElementById('productContainer');
    const newRow    = container.firstElementChild.cloneNode(true);
    newRow.querySelectorAll('input').forEach(i => i.value = '');
    container.appendChild(newRow);
});
</script>