<?php
include "../../classes/autoload.php";

$invoice_id = $_GET['record_id'];


// get invoice list and break up into suppliers
$suppliers_res = $db->query("invoice_list", "SELECT DISTINCT s.supplier_id FROM invoice_list as il LEFT join stock as s on s.record_id=il.stock_id WHERE il.invoice_id=$invoice_id");
while ($supplier_chooser = $suppliers_res->fetch_assoc()) {
    // check if order exists with invoice
    $duplicate_check_res = $db->query("supplier_orders", "SELECT * FROM supplier_orders WHERE invoice_id = '$invoice_id' AND supplier_id = '{$supplier_chooser['supplier_id']}'");
    if ($duplicate_check_res->num_rows < 1) {

        $supplier_details_res = $db->query("suppliers", "SELECT * FROM suppliers WHERE record_id = {$supplier_chooser['supplier_id']}");
        $supplier_details = $supplier_details_res->fetch_assoc();
        // create order number
        $order_no = $db->query("supplier_orders", "SELECT * FROM supplier_orders WHERE supplier_id = '{$supplier_chooser['supplier_id']}' ORDER BY record_id DESC LIMIT 1");
        if ($order_no->num_rows > 0) {
            $order_no = $order_no->fetch_assoc();
            $supplier_order_no = $supplier_details['code'] . '-' . ((int) str_replace($supplier_details['code'] . '-', '', $order_no['supplier_order_no']) + 1);
        } else {
            $supplier_order_no = $supplier_details['code'] . '-' . 1;
        }
        // create order
        $supplier_order_id = $db->query("supplier_orders", "INSERT INTO supplier_orders (`supplier_order_no`, `supplier_id`, `invoice_id`) VALUES ('$supplier_order_no', '{$supplier_chooser['supplier_id']}', '$invoice_id')");
    } else {
        $supplier_order_id = $duplicate_check_res->fetch_assoc()['record_id'];
    }
    $db->query("supplier_order_list", "DELETE FROM supplier_order_list WHERE supplier_order_id = '$supplier_order_id'");
    $db->query("supplier_order_list", "INSERT INTO supplier_order_list (stock_id, qty, supplier_order_id, size_m, price, pannels) SELECT i.stock_id, i.qty, '$supplier_order_id', i.size_m, s.cost, i.pannels FROM invoice_list i JOIN stock s ON s.record_id = i.stock_id WHERE i.invoice_id = '$invoice_id' AND s.supplier_id = '{$supplier_chooser['supplier_id']}';");
}
header("location:../supplier_orders/home.php");