<?php
include "../../root.class.php";

$db = new db_safeguard();
var_dump($_POST);
$cost_id = $_POST['record_id'];
$job_card_account_id = (isset($_POST['job_card_account_id']) && strlen($_POST['job_card_account_id']) > 0) ? $_POST['job_card_account_id'] : 0;
$name = $_POST['name'];
$jc_number = $_POST['jc_number'];
$order_date = str_replace("T", " ", $_POST['order_date']);

$update = "UPDATE `costs` SET `name`='$name',`jc_number`='$jc_number',`date_time_created`='$order_date',`user_id`={$_SESSION['user_id']},`job_card_account_id`='$job_card_account_id',`include_vat`='{$_POST['include_vat']}' WHERE record_id = $cost_id";
$db->query("costs", $update);

$index = 0;
$db->query("cost_items", "DELETE FROM cost_items WHERE cost_id = $cost_id");
while ($index < $_POST['counter']) {
    if (strlen($_POST['item_description' . $index]) >= 1) {
        $description = $_POST['item_description' . $index];
        $quantity = $_POST['quantity' . $index];
        $cost_price = $_POST['cost_price' . $index];
        $db->query("cost_items", "INSERT INTO `cost_items`(`name`, `quantity`, `purchase_price_ex`, `cost_id`, `user_id_created`) VALUES ('$description','$quantity','$cost_price','$cost_id','{$_SESSION['user_id']}')");
    }
    $index++;
}

echo "<script>location.href = 'edit_cost.php?record_id=$cost_id';</script>";