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

$quote_id = $_GET['record_id'];
// check if quote is already converted to invoice
$res = $db->query("invoices", "SELECT * FROM `invoices` WHERE `quote_id` = '$quote_id'");
if ($res->num_rows > 0) {
    $invoice = $res->fetch_assoc();
    header("Location: ../invoices/edit_invoices.php?record_id={$invoice['record_id']}");
} else {
    // get invoice number
    $invoice_number = $db->query("invoices", "SELECT * FROM `invoices` WHERE 1 ORDER BY `record_id` DESC LIMIT 1");
    if ($invoice_number->num_rows > 0) {
        $invoice_number = $invoice_number->fetch_assoc();
        $invoice_number = $invoice_number['invoice_number'] + 1;
    } else {
        $invoice_number = 1;
    }
    // get quote data
    $quote_data_res = $db->query("quotes", "SELECT * FROM `quotes` WHERE `record_id` = '$quote_id'");
    $quote_data = $quote_data_res->fetch_assoc();
    // insert into invoices
    $invoice_no = $db->query("invoices", "INSERT INTO `invoices`(`client_id`, `order_type`, `user_id`, `status`, `date_time_created`, `terms`, `subject`, `notes`, `area`, `quote_id`, `invoice_number`,`additional_delivery_details`) VALUES ('{$quote_data['client_id']}','{$quote_data['order_type']}','{$_SESSION['user_id']}','PENDING PAYMENT',NOW(), '{$quote_data['terms']}','
    PLEASE ALLOW TWO WEEK FOR DELIVERY OF STOCK AFTER DEPOSIT IS DONE
    ','
    THANK YOU FOR THE SUPPORT!
PAYMENT OPTIONS:  EFT Transfer, CREDIT CARD OR CASH.
    ','{$quote_data['area']}','$quote_id','{$invoice_number}','{$quote_data['additional_delivery_details']}')");
    // load quote_lsit into invoice_list
    $quote_list_res = $db->query("quote_list", "SELECT * FROM `quote_list` WHERE `quote_id` = '$quote_id'");
    while ($quote_list = $quote_list_res->fetch_assoc()) {
        $db->query("invoice_list", "INSERT INTO `invoice_list`(`stock_id`, `qty`, `price`, `invoice_id`, `size_m`, `pannels`) VALUES ('{$quote_list['stock_id']}','{$quote_list['qty']}','" . preg_replace('/[^\d\.\-]/', '', str_replace(',', '.', $quote_list['price'])) . "','{$invoice_no}','{$quote_list['size_m']}','{$quote_list['pannels']}')");
    }
    header("Location: ../invoices/edit_invoices.php?record_id=$invoice_no");
}