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

$invoice_res = $db->query('invoices', "SELECT * FROM invoices WHERE 1 ORDER BY record_id DESC");
if ($invoice_res->num_rows == 0) {
    $invoice_number = 19133;
} else {
    $invoice = $invoice_res->fetch_assoc();
    $invoice_number = $invoice['invoice_number'] + 1;
}
$quote_id = $db->query("invoices", "INSERT INTO invoices (`client_id`,`order_type`,`user_id`,`status`,`subject`,`notes`,`terms`,`area`,`invoice_number`,`quote_id`,`additional_delivery_details`) VALUES ('{$_POST['client_id']}','{$_POST['order_type']}','{$_SESSION['user_id']}','OPENED','$subject','$note','$terms','$area',$invoice_number,0,'$additional_delivery_details')");

$stokc_items_arr = $_POST['stock_code'];
$index = 0;
foreach ($stokc_items_arr as $item_name) {
    $stock_res = $db->query("stock", "SELECT * FROM stock WHERE `code` = '$item_name'");
    $stock = $stock_res->fetch_assoc();
    $item_id = $stock['record_id'];
    // echo  "INSERT INTO invoice_list (`invoice_id`,`stock_id`,`qty`,`price`,`size_m`,`pannels`) VALUES ('$quote_id', '$item_id','{$_POST['qty'][$index]}','" . $function->number_to_save($_POST['price'][$index]) . "','{$_POST['size_m'][$index]}','{$_POST['pannels'][$index]}')";
    $db->query("invoice_list", "INSERT INTO invoice_list (`invoice_id`,`stock_id`,`qty`,`price`,`size_m`,`pannels`) VALUES ('$quote_id', '$item_id','{$_POST['qty'][$index]}','" . $function->number_to_save($_POST['price'][$index]) . "','{$_POST['size_m'][$index]}','{$_POST['pannels'][$index]}')");

    $index++;
}
header("location:home.php");