<?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'];

if ($action == 'edit_transfer_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 transfer_orders set supplier='$supplier', supplier_address='$supplier_address', delivery_location='$delivery_location', delivery_address='$delivery_address', supplier_memo='$memo', user_id='$user_id' ,user_name='$user_name' where purchase_order_no='$purchase_id';";
        $rsinsert = mysql_query($query_insert, $courier) or die(mysql_error());

        $resultItems = mysql_query("SELECT * FROM $table WHERE $item_id_use='$id' ") 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_type'];
        $price = $arrayItems['price'];
        $alternate_lookup = $arrayItems['alternate_lookup'];

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

        if ($totalRows > 0) {
            $item_qty = $arrayItems['qty'] + 1;
            $query_insert = "update transfer_order_details set qty='$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'] . ' 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 !';

            $query_insert = "INSERT INTO `transfer_order_details` (`purchase_order_no`, `item_id`, `ins_item_code`, `item`, `service_type`, `qty`, `price`, `item_order_status`) VALUES ('$purchase_id', '$item_id',  '$ins_item_code', '$item', '$service', '$item_qty', '$price', '$item_order_status');";
            $rsinsert = mysql_query($query_insert, $courier) or die(mysql_error());
            $insert_id = mysql_insert_id();
            mysql_query("UPDATE transfer_order_details SET id_from_branch='$insert_id' WHERE id='$insert_id'");
        }
    }

    echo $status . '@@@' . $message . '@@@';
    include('list_of_added_items.php');
}


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

if ($action == 'add_new_transfer_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 = "Not Saved";

    $query_insert = "INSERT INTO `transfer_orders` (`supplier`, `date_of_order`, `order_status`, `user_ipaddress`, `user_id`, `user_name`, `branch_id`) VALUES ('" . $_SESSION['branch_id'] . "', NOW(), '$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 transfer_orders SET purchase_order_no = '$id',id_from_branch='$id2' WHERE id = '$id2'");
    include 'edit_transfer_order.php';
}

if ($action == 'up_transfer_order_details') {
    $queryItems = "SELECT * FROM transfer_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'] + 1;
        $query_insert = "update transfer_order_details set qty='$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'] . " to $item_qty - " . strtoupper($item);
        echo $status . '@@@' . $message . '@@@';
    }
    include('list_of_added_items.php');
}


if ($action == 'down_transfer_order_details') {
    $queryItems = "SELECT * FROM transfer_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'] > 1)) {
        $item_qty = $arrayItems['qty'] - 1;
        $query_insert = "update transfer_order_details set qty='$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'] . " to $item_qty - " . strtoupper($item);
        echo $status . '@@@' . $message . '@@@';
    }
    include('list_of_added_items.php');
}

if ($action == 'save_transfer_order') {
    $rsupdate_records = mysql_query("update transfer_orders set order_status='Unapproved', supplier='$supplier', supplier_address='$supplier_address', supplier_memo='$memo', delivery_location='$delivery_location', delivery_address='$delivery_address' where purchase_order_no='$id'") or die(mysql_error());
    if ($rsupdate_records == TRUE) {
        mysql_query("INSERT INTO transfer_activities_status (branch_id,purchase_order_no,previous_id,departure,arrival,status_time,transfer_status,user_id,status) VALUES('$branch_id','$id','0','$supplier','$delivery_location',now(),'Order Created','" . $_SESSION['myMM_Userid'] . "','closed')");
        mysql_query("INSERT INTO transfer_activities_status (branch_id,purchase_order_no,previous_id,departure,arrival,status_time,transfer_status,user_id) VALUES('$branch_id','$id','" . mysql_insert_id() . "','$supplier','$delivery_location',now(),'Unapproved','" . $_SESSION['myMM_Userid'] . "')");
        echo 'Success! Transfer Order Details Saved Successfully. Awaiting Approval.@@@success@@@';
    } else {
        echo 'Oops! Failed to Save Transfer Order Details.@@@error@@@';
    }
    $idd2 = 'Unapproved';
    include 'list_transfer_orders.php';
}

if ($action == 'approve_transfer_order') {
    $user_id = $_SESSION['myMM_Userid'];
    $user_name = $_SESSION['myMM_Fullname'];
    
    $rsupdate_records = mysql_query("update transfer_orders set order_status='Approved',approved_by='$user_id',approved_by_user_name='$user_name',approved_date=now() where purchase_order_no='$id'") or die(mysql_error());
    if ($rsupdate_records == TRUE) {
        $status_info = mysql_fetch_assoc(mysql_query("SELECT * FROM transfer_activities_status WHERE purchase_order_no='$id' ORDER BY id DESC LIMIT 1"));
        mysql_query("UPDATE transfer_activities_status SET status='closed' WHERE id='" . $status_info['id'] . "'");
        mysql_query("INSERT INTO transfer_activities_status (branch_id,purchase_order_no,previous_id,departure,arrival,status_time,transfer_status,user_id) VALUES('$branch_id','$id','" . $status_info['id'] . "','$supplier','$delivery_location',now(),'Approved','" . $_SESSION['myMM_Userid'] . "')");
        echo 'Success! Transfer Order Details Approved Successfully. Awaiting Supply.@@@success@@@';
    } else {
        echo 'Oops! Failed to Approve Transfer Order Details.@@@error@@@';
    }
    $idd2 = 'Approved';
    include 'list_transfer_orders.php';
}

if ($action == 'save_supply_transfer_order') {
    $delivery_memo = $_POST['delivery_memo'];
    $supplier_id = $_POST['supplier_id'];
    $user_id = $_SESSION['myMM_Userid'];
    $user_name = $_SESSION['myMM_Fullname'];
    // $branch_type_info = mysql_fetch_assoc(mysql_query("SELECT type FROM branches WHERE id='$branch_id'"));
    // $branch_type = $branch_type_info['type'];
    // if ($branch_type == 'branch') {
    //     $table = 'service_items';
    //     $item_id_use = 'id';
    // } else {
        $table = 'stock_items';
        $item_id_use = 'item_id';
    // }

    $i = 0;
    $stock_info = mysql_query("SELECT * FROM transfer_order_details WHERE purchase_order_no='$id' AND order_status='not supplied' 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, quantity_available FROM $table WHERE $item_id_use = '$item_id'"));

        if ($item_info['quantity_available'] >= $row['qty'] || ($row['qty'] >= $item_info['quantity_available'] && $item_info['quantity_available'] > 0)) {
            if ($item_info['quantity_available'] >= $row['qty']) {
                $qty_supplied = $row['qty'];
            } else if ($row['qty'] >= $item_info['quantity_available'] && $item_info['quantity_available'] > 0) {
                $qty_supplied = $item_info['quantity_available'];
            }

            $quantity_available = $item_info['quantity_available'] - $qty_supplied;
            $insert = mysql_query("UPDATE transfer_order_details SET order_status='supplied',qty='$qty_supplied' WHERE purchase_order_no='$id' AND item_id = '$item_id'");
            $update = mysql_query("UPDATE $table SET quantity_available = '$quantity_available' WHERE id = '" . $item_info['id'] . "'");
            $i++;
        } else if ($row['qty'] >= $item_info['quantity_available'] && $item_info['quantity_available'] <= 0) {
            $insert = mysql_query("UPDATE transfer_order_details SET order_status='out of stock' WHERE purchase_order_no='$id' AND item_id = '$item_id'");
        }
    }
    if ($i > 0) {
        $rsupdate_records = mysql_query("update transfer_orders set order_status='In-Transit', supplied_date=now(), delivery_memo='$delivery_memo',supplied_by='$user_id',supplied_by_user_name='$user_name' where purchase_order_no='$id'") or die(mysql_error());
        $status_info = mysql_fetch_assoc(mysql_query("SELECT * FROM transfer_activities_status WHERE purchase_order_no='$id' ORDER BY id DESC LIMIT 1"));
        mysql_query("UPDATE transfer_activities_status SET status='closed' WHERE id='" . $status_info['id'] . "'");
        mysql_query("INSERT INTO transfer_activities_status (branch_id,purchase_order_no,previous_id,departure,arrival,status_time,transfer_status,status,user_id) VALUES('$branch_id','$id','" . $status_info['id'] . "','" . $status_info['departure'] . "','" . $status_info['arrival'] . "',now(),'Supplied', 'closed','" . $_SESSION['myMM_Userid'] . "')");
        mysql_query("INSERT INTO transfer_activities_status (branch_id,purchase_order_no,previous_id,departure,arrival,status_time,transfer_status,user_id) VALUES('$branch_id','$id','" . mysql_insert_id() . "','" . $status_info['departure'] . "','" . $status_info['arrival'] . "',now(),'In-Transit','" . $_SESSION['myMM_Userid'] . "')");
    }

    if ($rsupdate_records == TRUE) {
        echo 'Success! Transfer Order Supplied Successfully.@@@success@@@';
    } else {
        echo 'Oops! Failed to Supply Transfer Order.@@@error@@@';
    }

    $idd2 = 'Approved';
    include 'list_transfer_orders.php';
}

if ($action == 'initiate_stock_reimbursement') {
    $item_transfers = $_POST['item_check_box'];
    foreach ($item_transfers as $item_transfer) {
        $item_info = mysql_query("SELECT quantity_available FROM service_items WHERE id = '$item_transfer'");
        if (mysql_num_rows($item_info) > 0) {
            
        }
    }
}

if ($action == 'updateqty_transfer_order_details_actual') {
    $value = $_POST["value"];
    $queryItems = "SELECT * FROM transfer_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'];

    $resultItems2 = mysql_query("SELECT item FROM stock_items WHERE item_id='" . $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 transfer_order_details set qty='$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=="supplier_address_transfer"){
$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'];
}

if($action=="delete_transfer_order"){
        $status = mysql_fetch_assoc(mysql_query("SELECT order_status FROM transfer_orders WHERE purchase_order_no='$id'"));
	$del_purchase_details = mysql_query("DELETE FROM transfer_order_details where purchase_order_no='$id'")or die ("Could not delete".mysql_error());
	$del_purchase_order = mysql_query("DELETE FROM transfer_orders where purchase_order_no='$id'")or die ("Could not delete".mysql_error());
        $idd2=$status['order_status'];
	include("list_transfer_orders.php");
}

if ($action == 'receive_transfer_order') {
    $user_id = $_SESSION['myMM_Userid'];
    $user_name = $_SESSION['myMM_Fullname'];

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

    $qty_aval_text = 'quantity_available_'.$_SESSION['name_code'];
    $i = 0;
    $stock_info = mysql_query("SELECT * FROM transfer_order_details WHERE purchase_order_no='$id' AND order_status='supplied' 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'"));
        $qty_supplied = $row['qty'];
        $quantity_available = $item_info[$qty_aval_text] + $qty_supplied;
        $insert = mysql_query("UPDATE transfer_order_details SET order_status='received' WHERE purchase_order_no='$id' AND item_id = '$item_id'");
        $update = mysql_query("UPDATE $table SET $qty_aval_text = '$quantity_available' WHERE id = '" . $item_info['id'] . "'");
        $i++;
    }
    $rsupdate_records = mysql_query("update transfer_orders set order_status='Received',accepted_by='$user_id',accepted_by_username='$user_name',accepted_date=now() where purchase_order_no='$id'") or die(mysql_error());
    $status_info = mysql_fetch_assoc(mysql_query("SELECT * FROM transfer_activities_status WHERE purchase_order_no='$id' ORDER BY id DESC LIMIT 1"));
    mysql_query("UPDATE transfer_activities_status SET status='closed' WHERE id='" . $status_info['id'] . "'");
    mysql_query("INSERT INTO transfer_activities_status (branch_id,purchase_order_no,previous_id,departure,arrival,status_time,transfer_status,status,user_id) VALUES('$branch_id','$id','" . $status_info['id'] . "','" . $status_info['departure'] . "','" . $status_info['arrival'] . "',now(),'Received', 'closed','" . $_SESSION['myMM_Userid'] . "')");

    if ($rsupdate_records == TRUE) {
        echo 'Success! Transfer Order Received Successfully.@@@success@@@';
    } else {
        echo 'Oops! Failed to Received Transfer Order.@@@error@@@';
    }

    $idd2 = 'Received';
    include 'list_transfer_orders.php';
}


if($action == 'Stock_Reimbursement'){
    $itemss = $_POST['item_check_box'];
    foreach($itemss AS $items){
        list($id, $item, $branch_id) = explode("@@@", $items);
        $item_qty_balance =  getStockAvail($item);
        
    }
}

