<?php

include "../../root.class.php";
$db = new db_safeguard();

$scanned = $_GET['scanned'];

// check if scanned is a stock barcode

// check if its a unit with a serial number
$unit_res = $db->query("units_stock", "SELECT * FROM units_stock WHERE serial_number = '$scanned' OR barcode = '$scanned'");
if ($unit_res->num_rows > 0) {
    $unit = $unit_res->fetch_assoc();
    $order_trans_stock_res = $db->query("order_trans", "SELECT SUM(amount) AS amount,stock_id FROM order_trans WHERE units_stock_id = {$unit['record_id']}");
    $order_trans_stock = $order_trans_stock_res->fetch_assoc();
    if ($order_trans_stock['amount'] > 0) {
        // get the stock_id form stock
        $stock_res = $db->query("stock", "SELECT * FROM stock WHERE record_id = {$order_trans_stock['stock_id']}");
        $stock = $stock_res->fetch_assoc();
        $stock_amount_res = $db->query("order_trans", "SELECT SUM(amount) AS amount FROM order_trans WHERE units_stock_id = {$unit['record_id']}");
        $stock_amount = $stock_amount_res->fetch_assoc()['amount'];
        $description = trim(preg_replace('/\s+/', ' ', $stock['description']));
        echo $description . "|R~{$stock['record_id']}~RS~{$unit['serial_number']}~SA~$stock_amount~AB~{$unit['barcode']}~BT~{$stock['stock_type']}~T";
    }
} else {
    $stock_res = $db->query("stock", "SELECT * FROM stock WHERE barcode = '$scanned'");
    if ($stock_res->num_rows > 0) {
        $stock = $stock_res->fetch_assoc();
        $stock_amount_res = $db->query("order_trans", "SELECT SUM(amount) AS amount FROM order_trans WHERE stock_id = {$stock['record_id']}");
        $stock_amount = $stock_amount_res->fetch_assoc()['amount'];
        $description = trim(preg_replace('/\s+/', ' ', $stock['description']));
        echo $description . "|R~{$stock['record_id']}~RA~$stock_amount~AB~{$stock['barcode']}~BT~{$stock['stock_type']}~T";
    } else {
        $non_stock_res = $db->query("non_stock", "SELECT * FROM non_stock WHERE barcode = '$scanned'");
        if ($non_stock_res->num_rows > 0) {
            $non_stock = $non_stock_res->fetch_assoc();
            $non_stock_amount_res = $db->query("order_trans", "SELECT SUM(amount) AS amount FROM order_trans WHERE non_stock_id = {$non_stock['record_id']}");
            $non_stock_amount = $non_stock_amount_res->fetch_assoc()['amount'];

            // get descrtiption
            $stock_res = $db->query("stock", "SELECT * FROM stock WHERE record_id = {$non_stock['stock_id']}");
            $stock = $stock_res->fetch_assoc();
            $description = trim(preg_replace('/\s+/', ' ', $stock['description']));
            echo $description . "|R~{$non_stock['stock_id']}~RA~$non_stock_amount~AB~{$non_stock['barcode']}~BT~{$stock['stock_type']}~T";
        } else {
            echo 0;
        }
    }
}

