<?php

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

// invoice data
$invoice_res = $db->query("invoices", 'SELECT * FROM `invoices` WHERE `record_id` = ' . $_GET['record_id']);
$invoice = $invoice_res->fetch_assoc();

// check if order_exist
$order_res = $db->query("orders", 'SELECT * FROM `orders` WHERE `invoice_id` = ' . $_GET['record_id']);
if ($order_res->num_rows > 0) {
    $order = $order_res->fetch_assoc();
    $order_id = $order['record_id'];
} else {
    // create order
    $db->query('orders', "INSERT INTO `orders`(`order_date`, `date_created`, `invoice_id`, `description`,`user_id`) VALUES ('',NOW(),'{$invoice['record_id']}','',{$_SESSION['user_id']})");
    $order_id = $db->query('orders', "SELECT record_id FROM orders WHERE invoice_id = '{$invoice['record_id']}' ORDER BY record_id DESC LIMIT 1")->fetch_assoc()['record_id'];
}

// insert into order_list
$invoice_list_res = $db->query('invoice_list', "SELECT * FROM invoice_list WHERE invoice_id = {$invoice['record_id']}");
$db->query("order_list", "DELETE FROM `order_list` WHERE `order_id` = $order_id");
while ($invoice_list = $invoice_list_res->fetch_assoc()) {
    $db->query("order_list", "INSERT INTO `order_list`(`order_id`, `stock_id`, `qty`, `size_m`) VALUES ('$order_id','{$invoice_list['stock_id']}','{$invoice_list['qty']}','{$invoice_list['size_m']}')");
}

header("location: ../work_schedule/edit_work_schedule.php?record_id=$order_id");