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

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

$delivery_note_id = $db->query("delivery_note", "INSERT INTO delivery_note (`quote_id`, `note`) VALUES ('{$_POST['invoice_id']}', '$note')");

$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 ('$delivery_note_id', '$stock_code', '$description', '$size_m', '$pannels')");
    $index++;
}

header("location:home.php");