<?php
include $_SERVER['DOCUMENT_ROOT'] . '/classes/autoload.php';

// var_dump($_POST);

// echo "<br><br>";

$invoice_id = $_POST['invoice_id'];
$supplier_order_no = $_POST['supplier_order_no'];
$supplier_id = trim($_POST['supplier_id']);

// echo "UPDATE `supplier_orders` SET `supplier_order_no`='$supplier_order_no',`supplier_id`='$supplier_id',`invoice_id`='$invoice_id' WHERE record_id='{$_POST['record_id']}'";


$db->query("supplier_orders", "UPDATE `supplier_orders` SET `supplier_order_no`='$supplier_order_no',`supplier_id`='$supplier_id',`invoice_id`='$invoice_id' WHERE record_id='{$_POST['record_id']}'");

$supplier_orders_id = $_POST['record_id'];

// echo "DELETE FROM `supplier_order_list` WHERE supplier_order_id`='{$_POST['record_id']}'";

$delete_prev = $db->query("supplier_order_list", "DELETE FROM `supplier_order_list` WHERE supplier_order_id='{$_POST['record_id']}'");

$index = 0;
$stock_items_array = $_POST['stock_code'];

foreach ($stock_items_array as $order) {

    $stock_res = $db->query("stock", "SELECT * FROM stock WHERE `code` = '$order'");
    $stock = $stock_res->fetch_assoc();
    $stock_id = $stock['record_id'];

    // echo "<br><br>";

    // echo "INSERT INTO `supplier_order_list`(`stock_id`, `qty`, `price`, `supplier_order_id`, `size_m`, `pannels`) VALUES ('$stock_id','{$_POST['qty'][$index]}','" . $function->number_to_save($_POST['price'][$index]) . "','$supplier_orders_id','{$_POST['size_m'][$index]}','{$_POST['pannels'][$index]}')";

    // echo "<br><br>";

    $db->query("supplier_order_list", "INSERT INTO `supplier_order_list`(`stock_id`, `qty`, `price`, `supplier_order_id`, `size_m`, `pannels`) VALUES ('$stock_id','{$_POST['qty'][$index]}','" . $function->number_to_save($_POST['price'][$index]) . "','$supplier_orders_id','{$_POST['size_m'][$index]}','{$_POST['pannels'][$index]}')");

    $index++;
}

header("location:home.php");