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

$subject = str_replace('"', '', $_POST['subject']);
$note = str_replace('"', '', $_POST['note']);
$terms = str_replace('"', '', $_POST['terms']);
$area = str_replace('"', '', $_POST['area']);
$subject = str_replace("'", '', $subject);
$note = str_replace("'", '', $note);
$terms = str_replace("'", '', $terms);
$area = str_replace("'", '', $area);
$additional_delivery_details = str_replace("'", '', $_POST['additional_delivery_details']);
$db->query("invoices", "UPDATE invoices SET `client_id` = '{$_POST['client_id']}', `order_type` = '{$_POST['order_type']}', `user_id` = '{$_SESSION['user_id']}', `status` = 'OPENED', `subject` = '$subject', `notes` = '$note', `terms` = '$terms',`area`='$area',`additional_delivery_details`='$additional_delivery_details' WHERE record_id = '{$_POST['record_id']}'");
$invoice_id = $_POST['record_id'];
$db->query("invoice_list", "DELETE FROM invoice_list WHERE `invoice_id` = '$invoice_id'");
$stokc_items_arr = $_POST['stock_code'];
$index = 0;
foreach ($stokc_items_arr as $item_name) {
    if (empty($item_name)) {
        continue;
    }
    $stock_res = $db->query("stock", "SELECT * FROM stock WHERE `code` = '$item_name'");
    $stock = $stock_res->fetch_assoc();
    @$item_id = $stock['record_id'];
    $db->query("invoice_list", "INSERT INTO invoice_list (`invoice_id`,`stock_id`,`qty`,`price`,`size_m`,`pannels`) VALUES ('$invoice_id', '$item_id','{$_POST['qty'][$index]}','" . preg_replace('/[^\d\.\-]/', '', $_POST['price'][$index]) . "','{$_POST['size_m'][$index]}','{$_POST['pannels'][$index]}')");
    $index++;
}
header("location:home.php");