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

$quote_no_res = $db->query("quotes", "SELECT * FROM quotes WHERE 1 ORDER BY record_id DESC LIMIT 1");
if ($quote_no_res->num_rows == 0) {
    $quote_no = 1;
} else {
    $quote_no = $quote_no_res->fetch_assoc();
    $quote_no = $quote_no['quote_number'] + 1;
}

$quote_id = $db->query("quotes", "INSERT INTO quotes (`client_id`,`order_type`,`user_id`,`status`,`subject`,`notes`,`terms`,`area`,`quote_number`,`additional_delivery_details`) VALUES ('{$_POST['client_id']}','{$_POST['order_type']}','{$_SESSION['user_id']}','OPENED','$subject','$note','$terms','$area',$quote_no,'$additional_delivery_details')");

$stock_code = $_POST['stock_code'];
$index = 0;
foreach ($stock_code 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'];
    $db->query("quote_list", "INSERT INTO quote_list (`quote_id`,`stock_id`,`qty`,`price`,`size_m`,`pannels`) VALUES ('$quote_id', '$item_id','{$_POST['qty'][$index]}','" . preg_replace('/[^\d\.\-]/', '', $_POST['price'][$index]) . "','{$_POST['size_m'][$index]}','{$_POST['pannels'][$index]}')");
    $index++;
}
header("location:home.php");