<?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++;
}



if ($job_card_account_id != 0) {
    $call = new call_functions();
    $tool_res = $db->query("job_card_accounts", "SELECT * FROM `job_card_accounts` WHERE `record_id` = '$job_card_account_id'");
    $tool = $tool_res->fetch_assoc();
    if ((strpos($tool['name'], "ST-") !== false || strpos($tool['name'], "TA-") !== false) && count($order_items_array) > 0 && strlen($tool['name']) > 0) {
       $call->send_for_email(['chanay@midrandac.co.za'], ['Chanay'], "Tool Account Order : " . $tool['name'], "
        <html>
        <body>
        <h1>Tool Account Order : " . $tool['name'] . "</h1>
        <p>PO Number : " . $_POST['po_number'] . "</p>
        <p>JC Number : " . $_POST['jc_number'] . "</p>
        <p>Supplier : " . $call->get_supplier_name($supplier_id ) . "</p>
        <p>Order Date : " . $_POST['order_date'] . "</p>
        <p>Ordered For : " . $_POST['ordered_for'] . "</p><table style='width:100%'><th>Item</th><th>Quantity</th><th>Cost Price</th>" . implode("", $order_items_array) . "</table>
        </body>
        </html>
        ");
    }
}

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