<?php
session_start();
include('accesscheck2.php');
require_once('Connections/courier.php');
require_once('functions/functions.php');

$action = $_POST["act"];
$id = $_POST['id'];

$supplier = $_POST['supplier'];
$supplier_address = $_POST['supplier_address'];
$memo = $_POST['memo'];
$delivery_location = $_POST['delivery_location'];
$delivery_address = $_POST['delivery_address'];
$expected_date = $_POST['expected_date'];
$user_id = $_SESSION['myMM_Userid'];
$user_name = $_SESSION['myMM_Fullname'];
$purchase_id = $_POST['purchase_order_id'];
$branch_id = $_SESSION['branch_id'];
$branch_id_user = $_SESSION['branch_id_user'];

if ($action == 'edit_requisition_details') {
    $branch_type = mysql_fetch_assoc(mysql_query("SELECT type FROM branches WHERE id='$branch_id'"));
    if ($branch_type['type'] == 'branch') {
        $table = 'service_items';
        $item_id_use = 'id';
    } else {
        $table = 'stock_items';
        $item_id_use = 'item_id';
    }

    if ($id > 0) {

        $query_insert = "UPDATE requisition_orders set supplier='$supplier', supplier_address='$supplier_address', delivery_location='$delivery_location', delivery_address='$delivery_address', expected_date='$expected_date', memo='$memo', supplier_opening_balance='$supplier_opening_balance', user_id='$user_id' ,user_name='$user_name' where purchase_order_no='$purchase_id';";
        $rsinsert = mysql_query($query_insert, $courier) or die(mysql_error());

        $queryItems = "SELECT * FROM $table WHERE $item_id_use='$id'";
        $resultItems = mysql_query($queryItems) or die(mysql_error());
        $arrayItems = mysql_fetch_assoc($resultItems);
        $totalRows = mysql_num_rows($resultItems);

        $item_id = $arrayItems[$item_id_use];
        $ins_item_code = $arrayItems['ins_item_code'];
        $item = $arrayItems['item'];
        $service = $arrayItems['service'];
        $alternate_lookup = $arrayItems['alternate_lookup'];
        $cost_price_before_tax = $arrayItems['purchase_price'];

        $queryItems = "SELECT * FROM requisition_order_details WHERE purchase_order_no='$purchase_id' and item_id='$item_id' and pack_size=1";
        $resultItems = mysql_query($queryItems) or die(mysql_error());
        $arrayItems = mysql_fetch_assoc($resultItems);
        $totalRows = mysql_num_rows($resultItems);


        if ($totalRows > 0) {
            $item_qty = $arrayItems['qty_expected'] + 1;
            $total_price = $item_qty * $cost_price_before_tax;

            $query_insert = "update requisition_order_details set qty_expected='$item_qty' where purchase_order_no='$purchase_id' and item_id='$id'";
            $rsinsert = mysql_query($query_insert, $courier) or die(mysql_error());

            $status = 'success';
            $message = 'Quantity has been increased from ' . $arrayItems['qty_expected'] . ' to ' . $item_qty . ' - ' . strtoupper($item);
        } else {
            $item_qty = 1;
            $item_order_status = 'Added';

            $status = 'success';
            $message = strtoupper($item) . ' has been added to the list Successfully !';
            $pack_size_qty = 1;

            $query_insert = "INSERT INTO `requisition_order_details` (`id`, `purchase_order_no`, `item_id`, `ins_item_code`, `item`, `service`, `qty_expected`, `qty_received`, `cost_price_before_tax`, `date_expected`, `datetime_received`, `item_order_status`, `pack_size`) VALUES (NULL, '$purchase_id', '$item_id',  '$ins_item_code', '$item', '$service', '$item_qty', '$qty_received', '$cost_price_before_tax', '$expected_date', '$datetime_received', '$item_order_status', '$pack_size_qty');";
            $rsinsert = mysql_query($query_insert, $courier) or die(mysql_error());
            $insert_id = mysql_insert_id();
            mysql_query("UPDATE requisition_order_details SET id_from_branch='$insert_id' WHERE id = '$insert_id'");
        }
    }
    echo $status . '@@@' . $message . '@@@';
    include('list_of_added_items.php');
}


if ($action == 'del_requisition_order_details') {
    $query_insert = "delete from requisition_order_details where id='$id';";
    $rsinsert = mysql_query($query_insert, $courier) or die(mysql_error());
    include('list_of_added_items.php');
}

if ($action == 'up_requisition_order_details') {
    $queryItems = "SELECT * FROM requisition_order_details WHERE id='$id' ";
    $resultItems = mysql_query($queryItems) or die(mysql_error());
    $arrayItems = mysql_fetch_assoc($resultItems);
    $totalRows = mysql_num_rows($resultItems);

    $branch_type = mysql_fetch_assoc(mysql_query("SELECT type FROM branches WHERE id='$branch_id'"));
    if ($branch_type['type'] == 'branch') {
        $table = 'service_items';
        $item_id_use = 'id';
    } else {
        $table = 'stock_items';
        $item_id_use = 'item_id';
    }

    $resultItems2 = mysql_query("SELECT item FROM $table WHERE $item_id_use='" . $arrayItems['item_id'] . "'") or die(mysql_error());
    $arrayItems2 = mysql_fetch_assoc($resultItems2);
    $item = $arrayItems2['item'];

    if ($totalRows > 0) {
        $item_qty = $arrayItems['qty_expected'] + 1;
        $total_claim = $item_qty * $arrayItems['item_unit_price'];

        $query_insert = "update requisition_order_details set qty_expected='$item_qty' where id='$id'";
        $rsinsert = mysql_query($query_insert, $courier) or die(mysql_error());

        $status = 'success';
        $message = "Quantity has been Increased from " . $arrayItems['qty_expected'] . " to $item_qty - " . strtoupper($item);
        echo $status . '@@@' . $message . '@@@';
    }
    include('list_of_added_items.php');
}


if ($action == 'down_requisition_order_details') {
    $queryItems = "SELECT * FROM requisition_order_details WHERE id='$id' ";
    $resultItems = mysql_query($queryItems) or die(mysql_error());
    $arrayItems = mysql_fetch_assoc($resultItems);
    $totalRows = mysql_num_rows($resultItems);
    
    $branch_type = mysql_fetch_assoc(mysql_query("SELECT type FROM branches WHERE id='$branch_id'"));
    if ($branch_type['type'] == 'branch') {
        $table = 'service_items';
        $item_id_use = 'id';
    } else {
        $table = 'stock_items';
        $item_id_use = 'item_id';
    }

    $resultItems2 = mysql_query("SELECT item FROM $table WHERE $item_id_use='" . $arrayItems['item_id'] . "'") or die(mysql_error());
    $arrayItems2 = mysql_fetch_assoc($resultItems2);
    $item = $arrayItems2['item'];

    if (($totalRows > 0) && ($arrayItems['qty_expected'] > 1)) {
        $item_qty = $arrayItems['qty_expected'] - 1;
        $total_claim = $item_qty * $arrayItems['item_unit_price'];

        $query_insert = "update requisition_order_details set qty_expected='$item_qty' where id='$id'";
        $rsinsert = mysql_query($query_insert, $courier) or die(mysql_error());

        $status = 'success';
        $message = "Quantity has been Decreased from " . $arrayItems['qty_expected'] . " to $item_qty - " . strtoupper($item);
        echo $status . '@@@' . $message . '@@@';
    }
    include('list_of_added_items.php');
}

if ($action == 'updateqty_requisition_order_details') {
    $value = $_POST["value"];
    $queryItems = "SELECT * FROM requisition_order_details WHERE id='$id' ";
    $resultItems = mysql_query($queryItems) or die(mysql_error());
    $arrayItems = mysql_fetch_assoc($resultItems);
    $totalRows = mysql_num_rows($resultItems);
    $unit_price = $arrayItems['qty_expected'];
    
    $branch_type = mysql_fetch_assoc(mysql_query("SELECT type FROM branches WHERE id='$branch_id'"));
    if ($branch_type['type'] == 'branch') {
        $table = 'service_items';
        $item_id_use = 'id';
    } else {
        $table = 'stock_items';
        $item_id_use = 'item_id';
    }

    $resultItems2 = mysql_query("SELECT item FROM $table WHERE $item_id_use='" . $arrayItems['item_id'] . "'") or die(mysql_error());
    $arrayItems2 = mysql_fetch_assoc($resultItems2);
    $item = $arrayItems2['item'];

    if ($totalRows > 0) {
        $item_qty = $value;
        $total_claim = $item_qty * $arrayItems['item_unit_price'];
        $query_insert = "update requisition_order_details set qty_expected='$item_qty' where id='$id'";
        $rsinsert = mysql_query($query_insert, $courier) or die(mysql_error());

        if ($value > $unit_price) {
            $status = 'success';
            $message = "Quantity has been Increased from $unit_price to $value - " . strtoupper($item);
        } else if ($value < $unit_price) {
            $status = 'success';
            $message = "Quantity has been Decreased from $unit_price to $value - " . strtoupper($item);
        }
        echo $status . '@@@' . $message . '@@@';
    }
    include('list_of_added_items.php');
}

if($action=="delete_requisition_order"){
	$del_purchase_details = mysql_query("DELETE FROM requisition_order_details where purchase_order_no='$id'")or die ("could not del purchase items".mysql_error());
	$del_purchase_order = mysql_query("DELETE FROM requisition_orders where purchase_order_no='$id'")or die ("could not delete purchase_order".mysql_error());
	include("list_requisition_orders.php");
}

if ($action == 'save_requisition_order') {
    $rsupdate_records = mysql_query("update requisition_orders set order_status_from='Approved',order_status='Awaiting', supplier='$supplier', supplier_address='$supplier_address', memo='$memo', delivery_location='$delivery_location', delivery_address='$delivery_address', expected_date='$expected_date' where purchase_order_no='$id'") or die(mysql_error());
    if ($rsupdate_records == TRUE) {
        echo 'Success! Requisition Order Details Saved Successfully.@@@success@@@';
    } else {
        echo 'Oops! Failed to Save Requisition Order Details.@@@error@@@';
    }
    include 'list_requisition_orders.php';
}

if ($action == 'approve_requisition_order_supply') {
    $user_id = $_SESSION['myMM_Userid'];
    $user_name = $_SESSION['myMM_Fullname'];
    $date = date('Y-m-d h:s:i');
    $rsupdate_records = mysql_query("update requisition_orders set order_status='Approved',approved_by='$user_id',approved_by_user_name='$user_name',approved_date='$date' where purchase_order_no='$id'") or die(mysql_error());
    if ($rsupdate_records == TRUE) {
        echo 'Success! Requisition Approved Successfully for Supply.@@@success@@@';
    } else {
        echo 'Oops! Failed to Approve Requisition Supply.@@@error@@@';
    }
    $idd='Approved';
    include 'list_requisition_orders.php';
}

if ($action == 'approve_requisition_order_from') {
    $user_id = $_SESSION['myMM_Userid'];
    $user_name = $_SESSION['myMM_Fullname'];
    $date = date('Y-m-d h:s:i');
    $rsupdate_records = mysql_query("update requisition_orders set order_status_from='Approved',approved_by_from='$user_id',approved_by_user_name_from='$user_name',approved_date_from='$date', supplier='$supplier', supplier_address='$supplier_address', memo='$memo', delivery_location='$delivery_location', delivery_address='$delivery_address', expected_date='$expected_date' where purchase_order_no='$id'") or die(mysql_error());
    if ($rsupdate_records == TRUE) {
        echo 'Success! Requisition Order Details Approved Successfully.@@@success@@@';
    } else {
        echo 'Oops! Failed to Approve Requisition Order Details.@@@error@@@';
    }
    include 'list_requisition_orders.php';
}

if ($action == 'forward_requisition_order_for_approval') {
    $delivery_memo = $_POST['delivery_memo'];
    $user_id = $_SESSION['myMM_Userid'];
    $user_name = $_SESSION['myMM_Fullname'];
    $date = date('Y-m-d h:s:i');
    $rsupdate_records = mysql_query("update requisition_orders set order_status='Unapproved', delivery_memo='$delivery_memo' where purchase_order_no='$id'") or die(mysql_error());
    if ($rsupdate_records == TRUE) {
        echo 'Success! Requisition Order Forwarded for Approval.@@@success@@@';
    } else {
        echo 'Oops! Failed to Forward Requisition Order.@@@error@@@';
    }
    include 'list_requisition_orders.php';
}

if($action=="supplier_address_requisition"){
    $query_rspics = "select * FROM branches where id='$id'";
    $rspics = mysql_query($query_rspics, $courier) or die(mysql_error()); 
    $row_rspics=mysql_fetch_assoc($rspics);
    echo $row_rspics['postal_address'].' '.$row_rspics['location'];
}

if($action=="delivery_address_requisition"){
    $query_rspics = "select * FROM branches where id='$id'";
    $rspics = mysql_query($query_rspics, $courier) or die(mysql_error()); 
    $row_rspics=mysql_fetch_assoc($rspics);
    echo $row_rspics['postal_address'].' - '. $row_rspics['location'];
}

if ($action == 'add_new_requisition_order') {
    $query_ipaddress = "select SUBSTRING_INDEX(host,':',1) as 'ip' from information_schema.processlist where ID=connection_id();";
    $rsipaddress = mysql_query($query_ipaddress, $courier) or die(mysql_error());
    $row_rsipaddress = mysql_fetch_assoc($rsipaddress);

    $user_ipaddress = $row_rsipaddress['ip'];
    $user_id = $_SESSION['myMM_Userid'];
    $user_name = $_SESSION['myMM_Fullname'];
    $order_status = "Awaiting";

    $query_insert = "INSERT INTO `requisition_orders` (`purchase_order_no`, `supplier`, `supplier_address`, `date_of_order`, `delivery_location`, `delivery_address`, `expected_date`,  `supplier_message`, `memo`, `supplier_opening_balance`, `order_status_from`, `user_ipaddress`, `user_id`, `user_name`, `branch_id`) VALUES (NULL, '$supplier', '$supplier_address', NOW(), '$delivery_location', '$delivery_address', '$expected_date', '$supplier_message', '$memo', '$supplier_opening_balance', '$order_status', '$user_ipaddress', '$user_id', '$user_name','" . $_SESSION['branch_id'] . "');";
    $rsinsert = mysql_query($query_insert, $courier) or die(mysql_error());
    $id2 = mysql_insert_id();
    $id = $_SESSION['branch_code'].$id2;
    $update_records = mysql_query("UPDATE requisition_orders SET purchase_order_no = '$id',id_from_branch='$id2' WHERE id = '$id2'");

    include 'edit_requisition_order.php';
}

if ($action == 'updateqty_requisition_order_details_actual') {
    $value = $_POST["value"];
    $queryItems = "SELECT * FROM requisition_order_details WHERE id='$id' ";
    $resultItems = mysql_query($queryItems) or die(mysql_error());
    $arrayItems = mysql_fetch_assoc($resultItems);
    $totalRows = mysql_num_rows($resultItems);
    $unit_price = $arrayItems['qty_received'];
    $qty_expected1 = $arrayItems['qty_expected'];

    $branch_type = mysql_fetch_assoc(mysql_query("SELECT type FROM branches WHERE id='$branch_id_user'"));
    if ($branch_type['type'] == 'branch') {
        $table = 'service_items';
        $item_id_use = 'id';
        $branchQty = '_'.$_SESSION['name_code'];
    } else {
        $table = 'stock_items';
        $item_id_use = 'item_id';
        $branchQty = '';
    }


    $resultItems2 = mysql_query("SELECT * FROM $table WHERE $item_id_use='" . $arrayItems['item_id'] . "'") or die(mysql_error());
    $arrayItems2 = mysql_fetch_assoc($resultItems2);
    $item = $arrayItems2['item'];
    $quantity_available = $arrayItems2['quantity_available'.$branchQty];

if($value > $qty_expected1){
$status = 'error';
$message = "Supply quantity cannot be more than requested quantity";
echo $status . '@@@' . $message . '@@@';
}else if ($value > $quantity_available) {
 $status = 'error';
$message = "Supply quantity cannot be more than available quantity";
echo $status . '@@@' . $message . '@@@';
}else{
    if ($totalRows > 0) {
        $item_qty = $value;
        $total_claim = $item_qty * $arrayItems['item_unit_price'];
        $query_insert = "update requisition_order_details set qty_received='$item_qty' where id='$id'";
        $rsinsert = mysql_query($query_insert, $courier) or die(mysql_error());

        if ($value > $unit_price) {
            $status = 'success';
            $message = "Actual Quantity has been Increased from $unit_price to $value - " . strtoupper($item);
        } else if ($value < $unit_price) {
            $status = 'success';
            $message = "Actual Quantity has been Decreased from $unit_price to $value - " . strtoupper($item);
        }
        echo $status . '@@@' . $message . '@@@';
    }
}
    include('list_approved_requisitions_items.php');
}

if ($action == 'save_supply_requisition_order') {
    $bill_ref = $_POST['bill_ref'];
    $supplied_date = $_POST['supplied_date'];
    $delivery_memo = $_POST['delivery_memo'];
    $supplier_id = $_POST['supplier_id'];
    $user_id = $_SESSION['myMM_Userid'];
    $user_name = $_SESSION['myMM_Fullname'];

    $supplier_location_info = mysql_fetch_assoc(mysql_query("SELECT supplier FROM requisition_orders WHERE purchase_order_no='$id'"));
    $branch_id = $supplier_location_info['supplier'];
    $branch_type = mysql_fetch_assoc(mysql_query("SELECT type,name_code FROM branches WHERE id='$branch_id'"));
    if ($branch_type['type'] == 'branch') {
        $table = 'service_items';
        $item_id_use = 'id';
        $qty_aval_text = 'quantity_available_'.$branch_type['name_code'];
    } else {
        $table = 'stock_items';
        $item_id_use = 'item_id';
        $qty_aval_text = 'quantity_available';
    }

    $rsupdate_records = mysql_query("update requisition_orders set order_status='In-Transit', bill_ref='$bill_ref', supplied_date='$supplied_date', delivery_memo='$delivery_memo',supplied_by='$user_id',supplied_by_user_name='$user_name',supplied_date=now() where purchase_order_no='$id'") or die(mysql_error());
    $stock_info = mysql_query("SELECT * FROM requisition_order_details WHERE purchase_order_no='$id' order by id desc;");
    while ($row = mysql_fetch_assoc($stock_info)) {
        $item_id = $row['item_id'];
        $item_info = mysql_fetch_assoc(mysql_query("SELECT id, $qty_aval_text FROM $table WHERE $item_id_use = '$item_id'"));
        if ($item_info[$qty_aval_text] >= $row['qty_received']) {
            $quantity_available = $item_info[$qty_aval_text] - $row['qty_received'];
            $update = mysql_query("UPDATE $table SET $qty_aval_text = '$quantity_available' WHERE id = '" . $item_info['id'] . "'");
            mysql_query("UPDATE requisition_order_details SET item_order_status='supplied' WHERE purchase_order_no='$id' AND item_id = '$item_id'");
        }
    }

    if ($rsupdate_records == TRUE) {
        mysql_query("UPDATE requisition_orders SET order_status='Approved' WHERE id = '$id' AND order_status='Awaiting'");
        echo 'Success! Requisition Order Supplied Successfully.@@@success@@@';
    } else {
        echo 'Oops! Failed to Supply Requisition Order.@@@error@@@';
    }
    $idd2 = 'In-Transit';
    include 'list_requisition_orders.php';
}


if ($action == 'accept_supply_requisition_order') {
    $user_id = $_SESSION['myMM_Userid'];
    $user_name = $_SESSION['myMM_Fullname'];
    $total_items = $_POST['total_items'];
    $order_status = 'Accepted With No Rejections';
    
    $branch_type = mysql_fetch_assoc(mysql_query("SELECT type,name_code FROM branches WHERE id='$branch_id'"));
    if ($branch_type['type'] == 'branch') {
        $table = 'service_items';
        $item_id_use = 'id';
        $qty_aval_text = 'quantity_available_'.$branch_type['name_code'];
        $price_text = 'price_'.$branch_type['name_code'];
    } else {
        $table = 'stock_items';
        $item_id_use = 'item_id';
        $qty_aval_text = 'quantity_available';
         $price_text = 'price';
    }

    for ($i = 1; $i <= $total_items; $i++) {
        $action_taken = $_POST['action_taken_' . $id . '_' . $i];
        $reason = $_POST['reason_' . $id . '_' . $i];
        $item_id = $_POST['item_details_id_' . $id . '_' . $i];

        $stock_info = mysql_query("SELECT * FROM requisition_order_details WHERE purchase_order_no='$id' AND id = '$item_id' order by id desc;");
        $stock_info_row = mysql_fetch_assoc($stock_info);
        $item_info = mysql_fetch_assoc(mysql_query("SELECT id, $qty_aval_text, $price_text FROM $table WHERE $item_id_use = '" . $stock_info_row['item_id'] . "'"));


        $item_info1 = mysql_fetch_assoc(mysql_query("SELECT id, price FROM stock_items WHERE item_id = '" . $stock_info_row['item_id'] . "'"));
        $item_price = $item_info1['price'];

        $quantity_available = $item_info[$qty_aval_text] + $stock_info_row['qty_received'];
        if ($action_taken == 'Accepted') {
            $update = mysql_query("UPDATE $table SET $qty_aval_text = '$quantity_available', $price_text = '$item_price' WHERE id = '" . $item_info['id'] . "'");
        }

        if ($action_taken == 'Rejected') {
            $order_status = 'Accepted With Rejections';
        }

        $update = mysql_query("UPDATE requisition_order_details SET item_order_status = '$action_taken', reason='$reason' WHERE id = '$item_id'");
    }

    $rsupdate_records = mysql_query("update requisition_orders set order_status_from='$order_status', order_status='Sent/Received', accepted_date=now(),accepted_by='$user_id',accepted_by_username='$user_name' where purchase_order_no='$id'") or die(mysql_error());

    if ($rsupdate_records == TRUE) {
        echo 'Success! Requisition Order Accepted Successfully.@@@success@@@';
    } else {
        echo 'Oops! Failed to Accept Requisition Order.@@@error@@@';
    }
    $idd2 = 'In-Transit';
    include 'list_requisition_orders.php';
}


////////////////////////////////////// Prosper ///////////////////////////////////////////////////////



if ($action == 'return_to_stores') {
    $query_ipaddress = "select SUBSTRING_INDEX(host,':',1) as 'ip' from information_schema.processlist where ID=connection_id();";
    $rsipaddress = mysql_query($query_ipaddress, $courier) or die(mysql_error());
    $row_rsipaddress = mysql_fetch_assoc($rsipaddress);

    $user_ipaddress = $row_rsipaddress['ip'];
    $user_id = $_SESSION['myMM_Userid'];
    $user_name = $_SESSION['myMM_Fullname'];
    $order_status = "Return to Store";

    $query_insert = "INSERT INTO `return_orders` (`purchase_order_no`, `supplier`, `supplier_address`, `date_of_order`, `delivery_location`, `delivery_address`, `expected_date`,  `supplier_message`, `memo`, `supplier_opening_balance`, `order_status_from`, `user_ipaddress`, `user_id`, `user_name`, `branch_id`) VALUES (NULL, '$supplier', '$supplier_address', NOW(), '$delivery_location', '$delivery_address', '$expected_date', '$supplier_message', '$memo', '$supplier_opening_balance', '$order_status', '$user_ipaddress', '$user_id', '$user_name','" . $_SESSION['branch_id'] . "');";
    $rsinsert = mysql_query($query_insert, $courier) or die(mysql_error());
    $id2 = mysql_insert_id();
    $id = $_SESSION['branch_code'].$id2;
    $update_records = mysql_query("UPDATE return_orders SET purchase_order_no = '$id',id_from_branch='$id2' WHERE id = '$id2'");

    include 'return/edit_return_to_store.php';
}


if ($action == 'list_store_return_orders') {
    $branch_type = mysql_fetch_assoc(mysql_query("SELECT type FROM branches WHERE id='$branch_id'"));
    if ($branch_type['type'] == 'branch') {
        $table = 'service_items';
        $item_id_use = 'id';
    } else {
        $table = 'stock_items';
        $item_id_use = 'item_id';
    }

    if ($id > 0) {

        $query_insert = "UPDATE requisition_orders set supplier='$supplier', supplier_address='$supplier_address', delivery_location='$delivery_location', delivery_address='$delivery_address', expected_date='$expected_date', memo='$memo', supplier_opening_balance='$supplier_opening_balance', user_id='$user_id' ,user_name='$user_name' where purchase_order_no='$purchase_id';";
        $rsinsert = mysql_query($query_insert, $courier) or die(mysql_error());

        $queryItems = "SELECT * FROM $table WHERE $item_id_use='$id'";
        $resultItems = mysql_query($queryItems) or die(mysql_error());
        $arrayItems = mysql_fetch_assoc($resultItems);
        $totalRows = mysql_num_rows($resultItems);

        $item_id = $arrayItems[$item_id_use];
        $ins_item_code = $arrayItems['ins_item_code'];
        $item = $arrayItems['item'];
        $service = $arrayItems['service'];
        $alternate_lookup = $arrayItems['alternate_lookup'];
        $cost_price_before_tax = $arrayItems['purchase_price'];

        $queryItems = "SELECT * FROM requisition_order_details WHERE purchase_order_no='$purchase_id' and item_id='$item_id' and pack_size=1";
        $resultItems = mysql_query($queryItems) or die(mysql_error());
        $arrayItems = mysql_fetch_assoc($resultItems);
        $totalRows = mysql_num_rows($resultItems);


        if ($totalRows > 0) {
            $item_qty = $arrayItems['qty_expected'] + 1;
            $total_price = $item_qty * $cost_price_before_tax;

            $query_insert = "update requisition_order_details set qty_expected='$item_qty' where purchase_order_no='$purchase_id' and item_id='$id'";
            $rsinsert = mysql_query($query_insert, $courier) or die(mysql_error());

            $status = 'success';
            $message = 'Quantity has been increased from ' . $arrayItems['qty_expected'] . ' to ' . $item_qty . ' - ' . strtoupper($item);
        } else {
            $item_qty = 1;
            $item_order_status = 'Added';

            $status = 'success';
            $message = strtoupper($item) . ' has been added to the list Successfully !';
            $pack_size_qty = 1;

            $query_insert = "INSERT INTO `requisition_order_details` (`id`, `purchase_order_no`, `item_id`, `ins_item_code`, `item`, `service`, `qty_expected`, `qty_received`, `cost_price_before_tax`, `date_expected`, `datetime_received`, `item_order_status`, `pack_size`) VALUES (NULL, '$purchase_id', '$item_id',  '$ins_item_code', '$item', '$service', '$item_qty', '$qty_received', '$cost_price_before_tax', '$expected_date', '$datetime_received', '$item_order_status', '$pack_size_qty');";
            $rsinsert = mysql_query($query_insert, $courier) or die(mysql_error());
            $insert_id = mysql_insert_id();
            mysql_query("UPDATE requisition_order_details SET id_from_branch='$insert_id' WHERE id = '$insert_id'");
        }
    }
    echo $status . '@@@' . $message . '@@@';
    include('return/list_of_added_items_return.php');
}


if ($action == 'edit_requisition_details_return') {
    $branch_type = mysql_fetch_assoc(mysql_query("SELECT type FROM branches WHERE id='$branch_id'"));
    if ($branch_type['type'] == 'branch') {
        $table = 'service_items';
        $item_id_use = 'id';

    } else {
        $table = 'stock_items';
        $item_id_use = 'item_id';
    }

    $branchfieldQty = 'quantity_available_'.$_SESSION['name_code'];

    if ($id > 0) {
         $query_insert = "UPDATE return_orders set supplier='$supplier', supplier_address='$supplier_address', delivery_location='$delivery_location', delivery_address='$delivery_address', expected_date='$expected_date', memo='$memo', supplier_opening_balance='$supplier_opening_balance', user_id='$user_id',user_name='$user_name' where purchase_order_no='$purchase_id'";
        $rsinsert = mysql_query($query_insert, $courier) or die(mysql_error());

        $queryItems = "SELECT * FROM $table WHERE $item_id_use='$id'";
        $resultItems = mysql_query($queryItems) or die(mysql_error());
        $arrayItems = mysql_fetch_assoc($resultItems);
        $totalRows = mysql_num_rows($resultItems);

        $item_id = $arrayItems[$item_id_use];
        $ins_item_code = $arrayItems['ins_item_code'];
        $item = $arrayItems['item'];
        $service = $arrayItems['service'];
        $alternate_lookup = $arrayItems['alternate_lookup'];
        $cost_price_before_tax = $arrayItems['purchase_price'];

        $qtyFromReturnBranch = $arrayItems[$branchfieldQty];

        $queryItems = "SELECT * FROM return_order_details WHERE item_id='$item_id' AND purchase_order_no='$purchase_id'";
        $resultItems = mysql_query($queryItems) or die(mysql_error());
        $arrayItems = mysql_fetch_assoc($resultItems);
        $totalRows = mysql_num_rows($resultItems);


        if ($totalRows > 0) {
            $item_qty = $arrayItems['qty_expected'] + 1;
            $total_price = $item_qty * $cost_price_before_tax;
            $query_insert = "update return_order_details set qty_expected='$item_qty' where purchase_order_no='$purchase_id' and item_id='$id'";
            $rsinsert = mysql_query($query_insert, $courier) or die(mysql_error());

            $NewqtyFromReturnBranch = $qtyFromReturnBranch - $item_qty;
            $status = 'success';
            $message = 'Quantity has been increased from ' . $arrayItems['qty_expected'] . ' to ' . $item_qty . ' - ' . strtoupper($item);
        } else {
            $item_qty = 1;
            $item_order_status = 'Added';
            $NewqtyFromReturnBranch = $qtyFromReturnBranch - $item_qty;
            if ($item_qty > $qtyFromReturnBranch) {
             $status = 'error';
             $message = 'You cannot return more than quantity available !';
         }else{
            $status = 'success';
            $message = strtoupper($item) . 'has been added to the list Successfully !';
            $pack_size_qty = 1;

            $query_insert = "INSERT INTO `return_order_details` (`id`, `purchase_order_no`, `item_id`, `ins_item_code`, `item`, `service`, `qty_expected`, `qty_received`, `cost_price_before_tax`, `date_expected`, `datetime_received`, `item_order_status`, `pack_size`) VALUES (NULL, '$purchase_id', '$item_id',  '$ins_item_code', '$item', '$service', '$item_qty', '$qty_received', '$cost_price_before_tax', '$expected_date', '$datetime_received', '$item_order_status', '$pack_size_qty');";
            $rsinsert = mysql_query($query_insert, $courier) or die(mysql_error());
            $insert_id = mysql_insert_id();
            mysql_query("UPDATE return_order_details SET id_from_branch='$insert_id' WHERE id = '$insert_id'");

        }

    }
}
echo $status . '@@@' . $message . '@@@';
include('return/list_of_added_items_return.php');
}

if ($action == 'updateqty_requisition_order_details_return') {
 $value = $_POST["value"];
 $queryItems = "SELECT * FROM return_order_details WHERE id='$id' AND item_order_status <> 'Received'";
 $resultItems = mysql_query($queryItems) or die(mysql_error());
 $arrayItems = mysql_fetch_assoc($resultItems);
 $totalRows = mysql_num_rows($resultItems);
 $unit_price = $arrayItems['qty_expected'];

 $branch_type = mysql_fetch_assoc(mysql_query("SELECT type FROM branches WHERE id='$branch_id'"));
 if ($branch_type['type'] == 'branch') {
    $table = 'service_items';
    $item_id_use = 'id';
} else {
    $table = 'stock_items';
    $item_id_use = 'item_id';
}

$resultItems2 = mysql_query("SELECT item FROM $table WHERE $item_id_use='" . $arrayItems['item_id'] . "'") or die(mysql_error());
$arrayItems2 = mysql_fetch_assoc($resultItems2);
$item = $arrayItems2['item'];

if ($totalRows > 0) {
    $item_qty = $value;
    $total_claim = $item_qty * $arrayItems['item_unit_price'];
    $query_insert = "update return_order_details set qty_expected='$item_qty' where id='$id'";
    $rsinsert = mysql_query($query_insert, $courier) or die(mysql_error());

    if ($value > $unit_price) {
        $status = 'success';
        $message = "Quantity has been Increased from $unit_price to $value - " . strtoupper($item);
    } else if ($value < $unit_price) {
        $status = 'success';
        $message = "Quantity has been Decreased from $unit_price to $value - " . strtoupper($item);
    }
    echo $status . '@@@' . $message . '@@@';
}
include('return/list_of_added_items_return.php');
}


if ($action == "save_requisition_order_return") {
    $purchase_order_no = $_POST['id'];
    $branchfieldQty = 'quantity_available_'.$_SESSION['name_code'];
    $rodest = mysql_query("UPDATE return_orders SET order_status='In-Transit' WHERE purchase_order_no = '$id'");
    $rodest = mysql_query("SELECT * FROM return_order_details WHERE purchase_order_no = '$id'");
    $table = 'service_items';
    while($row = mysql_fetch_assoc($rodest)){
        $item_id = $row['item_id'];
        $retunedQty = $row['qty_expected'];
        $existingqty = mysql_fetch_assoc(mysql_query("SELECT * FROM $table WHERE id = $item_id"));
        $existing_qty = $existingqty[$branchfieldQty]; 
        $newReturnedQty = $existing_qty - $retunedQty;
        $updateServiceItems = mysql_query("UPDATE $table SET $branchfieldQty = '$newReturnedQty' WHERE id = '$item_id'");
    }
    include('return/list_return_orders.php');
}

if ($action == "del_requisition_order_details_return") {
    $deleteid = $_POST['id'];
    mysql_query("DELETE FROM return_order_details WHERE id = '$deleteid'");
    include('return/list_of_added_items_return.php');
}

if ($action == "receive_requisition_order_return") {
 $purchase_order_no = $_POST['id'];
 $branchfieldQty = 'quantity_available_'.$_SESSION['name_code'];
 $rodest = mysql_query("SELECT * FROM return_order_details WHERE purchase_order_no = '$id'");
 $table = 'stock_items';
 while($row = mysql_fetch_assoc($rodest)){
    $item_id = $row['item_id'];
    $retunedQty = $row['qty_expected'];
    $existingqty = mysql_fetch_assoc(mysql_query("SELECT * FROM $table WHERE item_id = $item_id"));
    $existing_qty = $existingqty['quantity_available'];
    $newReturnedQty = $existing_qty + $retunedQty;
    $updateServiceItems = mysql_query("UPDATE $table SET quantity_available = '$newReturnedQty' WHERE item_id = '$item_id'"); 

    mysql_query("UPDATE return_order_details SET item_order_status = 'Received' WHERE purchase_order_no = '$id'");
    $updateReturn = mysql_query("UPDATE return_orders SET order_status = 'Received' WHERE purchase_order_no = '$id'");
}
include('return/list_return_orders.php');
}


if ($action == 'up_return_order_details') {
    $queryItems = "SELECT * FROM return_order_details WHERE id='$id' AND item_order_status <> 'Received'";
    $resultItems = mysql_query($queryItems) or die(mysql_error());
    $arrayItems = mysql_fetch_assoc($resultItems);
    $totalRows = mysql_num_rows($resultItems);

    $branch_type = mysql_fetch_assoc(mysql_query("SELECT type FROM branches WHERE id='$branch_id'"));
    if ($branch_type['type'] == 'branch') {
        $table = 'service_items';
        $item_id_use = 'id';
    } else {
        $table = 'stock_items';
        $item_id_use = 'item_id';
    }

    $resultItems2 = mysql_query("SELECT item FROM $table WHERE $item_id_use='" . $arrayItems['item_id'] . "'") or die(mysql_error());
    $arrayItems2 = mysql_fetch_assoc($resultItems2);
    $item = $arrayItems2['item'];

    if ($totalRows > 0) {
        $item_qty = $arrayItems['qty_expected'] + 1;
        $total_claim = $item_qty * $arrayItems['item_unit_price'];

        $query_insert = "update return_order_details set qty_expected='$item_qty' where id='$id'";
        $rsinsert = mysql_query($query_insert, $courier) or die(mysql_error());

        $status = 'success';
        $message = "Quantity has been Increased from " . $arrayItems['qty_expected'] . " to $item_qty - " . strtoupper($item);
        echo $status . '@@@' . $message . '@@@';
    }
    include('return/list_of_added_items_return.php');
}


if ($action == 'down_return_order_details') {
    $queryItems = "SELECT * FROM return_order_details WHERE id='$id' AND item_order_status <> 'Received'";
    $resultItems = mysql_query($queryItems) or die(mysql_error());
    $arrayItems = mysql_fetch_assoc($resultItems);
    $totalRows = mysql_num_rows($resultItems);
    
    $branch_type = mysql_fetch_assoc(mysql_query("SELECT type FROM branches WHERE id='$branch_id'"));
    if ($branch_type['type'] == 'branch') {
        $table = 'service_items';
        $item_id_use = 'id';
    } else {
        $table = 'stock_items';
        $item_id_use = 'item_id';
    }

    $resultItems2 = mysql_query("SELECT item FROM $table WHERE $item_id_use='" . $arrayItems['item_id'] . "'") or die(mysql_error());
    $arrayItems2 = mysql_fetch_assoc($resultItems2);
    $item = $arrayItems2['item'];

    if (($totalRows > 0) && ($arrayItems['qty_expected'] > 1)) {
        $item_qty = $arrayItems['qty_expected'] - 1;
        $total_claim = $item_qty * $arrayItems['item_unit_price'];

        $query_insert = "update return_order_details set qty_expected='$item_qty' where id='$id'";
        $rsinsert = mysql_query($query_insert, $courier) or die(mysql_error());

        $status = 'success';
        $message = "Quantity has been Decreased from " . $arrayItems['qty_expected'] . " to $item_qty - " . strtoupper($item);
        echo $status . '@@@' . $message . '@@@';
    }
    include('return/list_of_added_items_return.php');
}

if ($action == "delete_return_order") {
       $deleteid = $_POST['id'];
    mysql_query("DELETE FROM return_orders WHERE purchase_order_no = '$deleteid'");
    mysql_query("DELETE FROM return_order_details WHERE purchase_order_no = '$deleteid'");
    include('return/list_return_orders.php');
}