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

// var_dump($_POST);
$html = new html();
$db = new db_safeguard();
$call = new call_functions();
$dev = 0;
$date = date('Y-m-d H:i', strtotime("+2 hours"));
$counter = $_POST['counter'];
$order_id = $_POST['order_id'];
$order_res = $db->query("orders", "SELECT * FROM orders WHERE record_id = $order_id");
$order = $order_res->fetch_assoc();
$q_counter = $_POST['q_counter'];

// insert into a stock receiving batches
$receiving_id = $db->query("receiving_batches", "INSERT INTO receiving_batches (`po_number`,`user_id`) VALUES ('{$order['po_number']}','{$_SESSION['user_id']}')");

?>
<?php
$index = 0;
$q_index = 0;
$quantity_total = 0;
$actual_total = 0;
$order_items_id = "";
while ($index < $counter) {
    if ($_POST["actual_amount_$index"] > 0) {
        $stock_id = $_POST["stock_id_$index"];
        $actual_amount = $_POST["actual_amount_$index"];
        $name = $_POST["name_$index"];
        $stock_id . "<br>";
        $actual_amount . "<br>";
        $serial_numbers = $_POST["serial_numbers_$index"];
        $order_items_id = $_POST["order_item_id_$index"];
        $non_stock_barcode = $_POST["barcode_non_$index"];
        if (isset($_POST["serial_numbers_$index"])) {
            $serial_numbers = explode(",", $serial_numbers);
            $sub_index = 1;
            // var_dump($serial_numbers);
            while ($sub_index <= $actual_amount) {
                // echo "SERIAL NUMBERS";
                $array_index = $sub_index - 1;
                $s_n_s = explode("~", $serial_numbers[$array_index]);
                // var_dump($s_n_s);
                $s_n = $s_n_s[0];
                $barcode = $s_n_s[1];
                $sub_index++;
                $items_for_email .= "<tr><td>$name</td><td>1</td><td>$barcode</td><td>$s_n</td></tr>";
                $unit_stock_id = $db->query("units_stock", "INSERT INTO `units_stock` (`order_items_id`, `serial_number`, `description`,`barcode`) VALUES ($order_items_id,'$s_n','$name','$barcode')");
                $db->query("order_trans", "INSERT INTO `order_trans` ( `stock_id`,`non_stock_id`,`amount`, `date_time`,`order_id`,`user_id`,`units_stock_id`,`receiving_batch_id`) VALUES ($stock_id,'0','1','$date',$order_id,'{$_SESSION['user_id']}',$unit_stock_id,$receiving_id)");
            }

        } else if (isset($non_stock_barcode)) {
            if (strlen($non_stock_barcode) > 5) {
                $items_for_email .= "<tr><td>$name</td><td>$actual_amount</td><td>$non_stock_barcode</td></tr>";
                $non_stock_id = $db->query("non_stock", "INSERT INTO `non_stock` ( `barcode`, `amount_received`,`stock_id`) VALUES ('$non_stock_barcode','$actual_amount','$stock_id')");
                $db->query("order_trans", "INSERT INTO `order_trans` ( `stock_id`,`non_stock_id`,`amount`, `date_time`,`order_id`,`user_id`,`units_stock_id`,`receiving_batch_id`) VALUES ($stock_id,'$non_stock_id','$actual_amount','$date',$order_id,'{$_SESSION['user_id']}',0,$receiving_id)");
            } else {
                $items_for_email .= "<tr><td>$name (NOT CAPTURED ON SYSTEM, NO BARCODE PROVIDED)</td><td>$actual_amount</td><td>$non_stock_barcode</td></tr>";
            }
        } else {
            $quantity_total += $_POST["quantity_$index"];
            $actual_total += $_POST["actual_amount_$index"];
            $items_for_email .= "<tr><td>$name</td><td>$actual_amount</td><td>$non_stock_barcode</td></tr>";

            $db->query("order_trans", "INSERT INTO `order_trans`( `stock_id`, `non_stock_id`, `amount`, `date_time`, `order_id`, `user_id`,`units_stock_id`,`receiving_batch_id`) VALUES ($stock_id,'0','$actual_amount','$date',$order_id,'{$_SESSION['user_id']}',0,$receiving_id)");

            // update stock item price from the order
            $db->query("stock", "UPDATE stock SET `cost_price` = {$_POST["price_$index"]} WHERE record_id = $stock_id");

        }



    } else {
        $quantity_total += $_POST["quantity_$index"];

    }
    $index++;
}
$emails = [];
$names = [];
if ($order['job_card_account_id'] != "") {
    $tool_account_res = $db->query("job_card_accounts", "SELECT * FROM job_card_accounts WHERE record_id = {$order['job_card_account_id']}");
    $tool_account = $tool_account_res->fetch_assoc();
    $tool = "   <p>Job Card Account: " . $tool_account['name'] . "</p>";
    // $names[] = 'Chanay';
    // $emails[] = 'chanay@midrandac.co.za';

} else {
    $tool = "";
}

// check if job card is on project job card:
$job_card_project_res = $db->query("job_cards", "SELECT * FROM job_cards WHERE jc_number = '{$order['jc_number']}'");
$job_card_tech_res = $db->query("job_cards_tech", "SELECT * FROM job_cards_tech WHERE jc_number ='{$order['jc_number']}'");
$job_card_acc_res = $db->query("job_card_accounts", "SELECT * FROM job_card_accounts WHERE `name` = '{$order['jc_number']}'");
if ($job_card_project_res->num_rows > 0) {
    $job_card = $job_card_project_res->fetch_assoc();
    $job_card_name = $job_card["project_name"];
    $jc_number_text = "<p> Job Card Number: " . $order['jc_number'] . "</p>" . "<p> Job Card Name : " . $job_card['project_name'] . "</p>";
} else if ($job_card_tech_res->num_rows > 0) {
    $job_card = $job_card_tech_res->fetch_assoc();
    $job_card_name = $job_card["company_name"];
    $jc_number_text = "<p> Job Card Number: " . $order['jc_number'] . "</p><p> Job Card Name : " . $job_card['company_name'] . "</p>";
} else if ($job_card_acc_res->num_rows > 0) {
    $job_card = $job_card_acc_res->fetch_assoc();
    $job_card_name = $job_card["description"];
    $jc_number_text = "<p> Job Account:" . $job_card['name'] . "</p><p>  Description : " . $job_card['description'] . "</p>";
} else {
    $job_card_name = "N/A";
    $account_manager = "N/A";
}


if ($order['job_card_account_id'] != 0) {
    $job_card_res = $db->query("job_card_accounts", "SELECT * FROM job_card_accounts WHERE record_id = {$order['job_card_account_id']}");
    $job_card = $job_card_res->fetch_assoc();
    $job_card_name = $job_card['name'];
    $jc_number_text = "<p> Job Account:" . $job_card['name'] . "</p><p>  Description :" . $job_card['description'] . "</p>";
}

if (strlen($items_for_email) > 5) {
    $email_html = "
            <html>
                <body>
                    <h5>ORDER RECEIVED</h5>
                    <p>Received by: " . $call->get_username($_SESSION['user_id']) . "</p>
                    <p>PO Number: " . $order['po_number'] . "</p>
                    <p>Supplier Name: " . $call->get_supplier_name($order['supplier_id']) . "</p>
                    $jc_number_text
                    $tool
                    <p>Order By: " . $call->get_username($order['user_created']) . "</p>
                    <p>Order For: " . $call->get_username($order['user_id']) . "</p>
                  <table style='width:100%; text-align:center;border:1px solid black'>
                    <tr style='border:1px solid black'>
                        <th style='width:50%'>Item</th>
                        <th style='width:10%'>Amount</th>
                        <th style='width:20%'>Barcode</th>
                        <th style='width:20%'>Serial Number</th>
                    </tr>
                    " . $items_for_email . "
                  </table>
                      <a href='https://mas.elegantwork.co.za/app/stock_control/receiving_pdf.php?receiving_id=$receiving_id' style='color:blue;font-size:40px'>PRINT</a>
                </body>
            </html>
            ";

    $user_res = $db->query("users", "SELECT * FROM users WHERE record_id = {$order['user_created']}");
    $user = $user_res->fetch_assoc();
    $emails[] = $user['email'];
    $names[] = $user['username'];
    $user_res = $db->query("users", "SELECT * FROM users WHERE record_id = {$order['user_id']}");
    $user = $user_res->fetch_assoc();
    $emails[] = $user['email'];
    $names[] = $user['username'];
    $emails[] = "anton@midrandac.co.za";
    $names[] = "Anton";
    $emails[] = "frans@midrandac.co.za";
    $names[] = "frans";
    $emails[] = "stores@midrandac.co.za";
    $names[] = "stores";
    $emails[] = "chris@elegantwork.co.za";
    $names[] = "chris";
    $call = new call_functions();
    $call->send_for_email($emails, $names, $order['po_number'], $email_html);
}
$completed = 1;
// check if all are received
$over_all_quantity = 0;
$over_all_received = 0;

$order_items_res = $db->query("order_items", "SELECT * FROM order_items WHERE order_id = $order_id");
while ($order_items = $order_items_res->fetch_assoc()) {



    $stock_id = $order_items['stock_id'];
    $amount = $order_items['quantity'];

    // count in order trans for quantities

    $order_trans_res = $db->query("order_trans", "SELECT SUM(amount) as total FROM order_trans WHERE stock_id = $stock_id AND order_id = $order_id");

    $order_trans = $order_trans_res->fetch_assoc();

    $over_all_quantity += $amount;
    $over_all_received += $order_trans['total'];



}

$emails = [];
$names = [];

// echo $over_all_quantity . " : " . $over_all_received;
if ($over_all_quantity == $over_all_received) {
    // close order


    $db->query("orders", "UPDATE orders SET `status` = 1 WHERE record_id = $order_id");


}

// header("location: stock_control.php");

echo "<script>window.location.href='stock_control.php';</script>";