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

$note = str_replace('"', '', $_POST['note']);
$note = str_replace("'", '', $note);

$db->query("delivery_note", "UPDATE delivery_note SET `quote_id` = '{$_POST['invoice_id']}', `note` = '$note' WHERE `record_id` = '{$_POST['record_id']}'");

$db->query("delivery_note_list", "DELETE FROM delivery_note_list WHERE delivery_note_id = '{$_POST['record_id']}'");

$index = 0;
foreach ($_POST['stock_code'] as $raw_code) {
    // code field datalist format: CODE~Description~UOM~Price — take first part only
    $stock_code  = explode('~', $raw_code)[0];

    // description field datalist format: Description~CODE~UOM~Price — take first part only
    $raw_desc    = $_POST['description'][$index];
    $description = str_replace("'", '', explode('~', $raw_desc)[0]);

    $size_m      = $_POST['size_m'][$index];
    $pannels     = $_POST['pannels'][$index];

    $db->query("delivery_note_list", "INSERT INTO delivery_note_list (`delivery_note_id`, `stock_code`, `description`, `size_m`, `pannels`) VALUES ('{$_POST['record_id']}', '$stock_code', '$description', '$size_m', '$pannels')");
    $index++;
}

header("location:home.php");