<?php


function import_stock_balances()
{
    $header['date'] = Today();
    
    clear_all_messages();
    
    create_new_cart_for_import_stock_balances($header);
    
    //create_new_cart_for_import_stock_balances();
    $sb = $_SESSION['import_stock_balances_items'];
    
    $import_error = 0;

  //  $sb = $_SESSION['import_stock_balances_items'];
    
   // $import_error = 0;
    $data_array = array();
    $sql="SELECT * FROM item_balances_import WHERE item_code <> 'HEADER_RECORD'";
    $result = db_query($sql,"Import item records could not be retrieved");
    while ($myrow = db_fetch($result))
    {
        $import_table_data_array[] = $myrow;
    }

    $all_validations_successful = true;
    
    db_query("DELETE FROM item_balances_import WHERE item_code = 'HEADER_RECORD'");
    db_query("INSERT INTO `item_balances_import` (`id`, `item_code`, `quantity`, `cost`, `task`, `site`, `message`) VALUES (NULL, 'HEADER_RECORD', '0', '0', '', '', '')");
    
    $header_validation_rec_id = db_insert_id();
    if(!fill_header_data($header_validation_rec_id, $sb)){
        return array("success" => false, "tran_no" => 0, "message" => "Header information has some errors. No record imported.");
    }
    
    foreach ($import_table_data_array as $import_table_row){
        $line_data = "";
        if(validate_import_stock_balances_raw_data($import_table_row, $line_data,$sb) ==  true){
            if(check_import_stock_balance_item_data($sb,$line_data) == true){
                add_to_import_stock_balances_order($sb,$line_data);
            }
            else{
                $all_validations_successful = false;
                update_import_stock_balance_record($line_data['id'],$line_data['message']);
            }
        }
        else{
            $all_validations_successful = false;
        }
    }
    
    if(!$all_validations_successful){
        update_import_record($header_validation_rec_id,"Some items have errors. No record imported.");
        return array("success" => false, "tran_no" => 0, "message" => "Some items have errors. No record imported.");
    }
    else{
            //$header_data["StockLocation"] = "Main Stores";
            
        if(can_process_import_stock_balances_data($sb, $line_data, $header_validation_rec_id) == false){
            //update_import_record($header_validation_rec_id,$data['message']);
            $all_validations_successful == false;
        }
    }
    
    if($all_validations_successful){
        clear_all_messages(); // SET message = ''
        $asa_msg = $asa_msg = add_stock_adjustment($sb->line_items,
		$sb->location, $sb->tran_date,  $sb->increase,
		$sb->ref, $sb->memo, $sb->movement_type,$sb->project_id, 0, $sb->sample_items, 
                ST_INVADJUST, $sb->linked_field_type,$sb->linked_field_id);

        if($asa_msg['success'] === true){
            return array("success" => true, "tran_no" => $asa_msg["tran_no"], "message" => "Stock balances imported.");
        }
        else{
            update_import_record($header_validation_rec_id,$asa_msg['message']);
            return array("success" => false, "tran_no" => 0, "message" => "Could not import stock balances. Log is written in the table.");
        }
    }
    
    $sb->clear_items();
}

function clear_all_messages()
{
    $sql="UPDATE item_balances_import SET message = '' ";
    db_query($sql);
}

function fill_header_data($hid, &$sb)
{
    global $Refs;
            $header_data["reference"] ="ef123";// $Refs->get_next(ST_INVADJUST);
            $header_data["tran_date"] = today();
            $header_data["location_name"] = "City School Outlet";
            $header_data['movement_type_name'] = "Inventory Increase"; 
            $header_data['project_id'] = "SAW/30/28/15/INT/ELE/1"; 
            $header_data['increase'] = 1;
            $header_data['memo_'] = "";
            $header_data["movement_type"] = "Stock Balances Import";
            $header_data["linked_field_id"] = 0;
            $header_data["linked_field_type"] = 0;
             $header_data["task_description"] = "eeeeee";
            
            $sb->increase = $header_data['increase'];
            $sb->memo = $header_data['memo_'];
            $sb->movement_type = $header_data["movement_type"];
            $sb->linked_field_id = $header_data["linked_field_id"];
            $sb->linked_field_type = $header_data["linked_field_type"];
            $sb->ref = $header_data["reference"];
            $sb->tran_date =  $header_data["tran_date"];
            $sb->sample_items = false;
            //$sb->location = $header_data["location_name"];
            $sb->transfer_type = $header_data['movement_type_name'];
            $sb->project_id =  $header_data['project_id'];
            
            $sb->task_description=$header_data["task_description"];
            
            $glc_msg = get_location_code($header_data["location_name"]);
            if($glc_msg["passed"] == true){
                $sb->location = $glc_msg["message"];
            }
            else{
                update_import_stock_balance_record($hid, "Location name is invalid.");
                return false;
            }
            
            $gmti_msg = get_movement_type_id($header_data["movement_type_name"]);
            if($gmti_msg["passed"] == true){
                $sb->transfer_type = $gmti_msg["message"];
            }
            else{
                update_import_stock_balance_record($hid, "Movement type name is invalid.");
                return false;
            }
            
            $prj_msg = get_project_id($header_data["project_id"]);
            if($prj_msg["passed"] == true){
                $sb->project_id = $prj_msg["message"];
            }
            else{
                update_import_stock_balance_record($hid, "Project name is invalid.");
                return false;
            }
            
            return true;
}


function add_to_import_stock_balances_order($order, $line_data)
{


    $item_info = get_stock_item_edit_info($line_data['stock_id']);
    $alternate_unit = get_convertion_factor($line_data['tran_unit'], $line_data['stock_id']);
    $convertion_factor = $alternate_unit['convertion_factor'];

    $standard_cost = $item_info['standard_cost'];

    $order->add_to_cart (count($order->line_items), $line_data['stock_id'], $line_data['tran_qty'] * $line_data['convertion_factor'], $standard_cost, null, null,null,
                     null, 0, 0, 0, 0, 0, null, 0,null, null,null, null, null,$line_data['tran_unit'], $line_data['tran_qty'], 
                     $line_data['convertion_factor']);

//add_to_cart($line_no, $stock_id, $qty, 
//                    $standard_cost, $comment = null, $description=null, $required_date = null, 
//                    $line_comment=null, $row_id = 0, $issued_qty = 0, $requested_qty = 0,
//                    $stock_category_id = 0, $price = 0, $requesting_location = null, $status_id = 0,
//                    $required_from_date = null, $required_to_date = null, $issuing_date=null, $asset_id=null, 
//                    $check=null, $tran_unit = null, $tran_qty = null, $convertion_factor = null);


    //$item_info = get_stock_item_edit_info($line_data['stock_id']);
            
    $current_element = (count($order->line_items)-1);
//    $adj->line_items[$current_element]->requested_qty = $_POST['qty'];
    $order->line_items[$current_element]->high_value_item = $item_info["high_value_item"];
    $order->line_items[$current_element]->sample_item = $item_info["sample_item"];
    $order->line_items[$current_element]->reference_cost = $item_info["reference_cost"];
    $order->line_items[$current_element]->stock_control_method = $item_info["stock_control_method"];
	
    $order->line_items[$current_element]->site_id = $line_data['site_id'];
    $order->line_items[$current_element]->task_id = $line_data['task_id'];
}


function validate_import_stock_balances_raw_data($myrow,&$data,$sb)
{
    //$category = "";
        
        $id = $myrow['id'];
        $data['id'] = $myrow['id'];
        $data['stock_id']  = '';
        $data['tran_qty'] = 0;
        $data['std_cost'] = 0;
        $data['task_id'] = "";
        $data['site_id'] = "";
        $data['message'] = "";
        
        $giei = get_item_edit_info($myrow['item_code']);
        if($giei){
            $data['stock_id']  = $myrow['item_code'];
        }
        else{
            update_import_stock_balance_record($id,"Invalid item code.");
            return false;
        }
        
        $gtu_msg = get_units_code($myrow['unit_name']);
        if($gtu_msg["passed"] == true){
            $data['tran_unit'] = $gtu_msg['message'];
        }
        else{
            update_import_stock_balance_record($id,"Transaction unit not found.");
            return false;
        }
        
        
        $gt = get_task($myrow['task_name'],$sb->project_id,$sb->task_description);
        if($gt['passed'] == true){
            $data['task_id'] = $gt['message'];
        }
        else{
            update_import_stock_balance_record($id,$gt['message']);
            return false;
        }
        
        $gs = get_site($myrow['site_name']);
        if($gs['passed'] == true){
            $data['site_id'] = $gs['message'];
        }
        else{
            update_import_stock_balance_record($id,$gs['message']);
            return false;
        }
        

        $gn = get_numeric($myrow['quantity']);
        if($data['tran_qty']==""){
            $data['tran_qty'] = $gn['message'];
        }
        else{
            update_import_stock_balance_record($id,$gn['message']);
            return false;
        }  
        
        $ct = get_numeric($myrow['cost']);
        if($data['std_cost']==""){
            $data['std_cost'] = $ct['message'];
        }
         else{
            update_import_stock_balance_record($id,$ct['message']);
            return false;
        } 
      //  $data['manual_entry'] = false;
        
        $alternate_unit = get_convertion_factor($data['tran_unit'], $data['stock_id']);
        if($alternate_unit){
            $data['convertion_factor'] = $alternate_unit['convertion_factor'];
        }
         else{
            update_import_stock_balance_record($id,"No unit conversion record found.");
            return false;
        } 
        return true;
        
    
}

function can_process_import_stock_balances_data(&$adj, $lines, $id)
{
    global $Refs;

	//$adj = &$_SESSION['import_stock_balances_items'];
        
        
        
	if (count($adj->line_items) == 0)	{
		$message = ("You must enter at least one non empty item line.");
		update_import_stock_balance_record($id,$message);
                return false;
	}
               
	if (!$Refs->is_valid($adj->ref)) 
	{
		$msg = "You must enter a reference.";
		update_import_stock_balance_record($id,$msg);
                return false;
	}
        

	if (!is_new_reference($adj->ref, ST_INVADJUST)) 
	{
		$message =("The entered reference is already in use.");
		update_import_stock_balance_record($id,$message);
		return false;
	}
        
      //  $adj->reference = $lines['ref'];
                
      //  
        
	if (!is_date($adj->tran_date)) 
	{
		$message =("The entered date for the adjustment is invalid.");
		update_import_stock_balance_record($id,$gn['message']);
		return false;
	} 
	elseif (!is_date_in_fiscalyear($adj->tran_date)) 
	{
		$message =("The entered date is not in fiscal year.");
		update_import_stock_balance_record($id,$message);
		return false;
	} 
        
        if (!is_movement_type($adj->transfer_type)) 
	{
		$message =("Please select a movement type.");
		update_import_stock_balance_record($id,$message);
		return false;
	} 
	
      
        
        else{
             // $adj->trans_type = $lines['type'];
		$failed_item = $adj->check_qoh($adj->location, $adj->tran_date,$adj->increase);
		if ($failed_item >= 0) 
		{
			$line = $adj->line_items[$failed_item];
                        display_error(_("The adjustment cannot be processed because an adjustment item would cause a negative inventory balance :") .
    			" " . $line->stock_id . " - " .  $line->item_description);
			$_POST['Edit'.$failed_item] = 1; // enter edit mode
			unset($_POST['Process']);
		return false;
		}
	}
     
    if (input_num('project_id') == -1) 
    {
            display_error( _('Select a project.'));
            set_focus('project_id');
            return false;
    }
    
    return true;
//
//    
//    $vtqd_msg = validate_transaction_quantity_details($adj);
//    if ($vtqd_msg['success'] !== true) 
//    {
//        display_error($vtqd_msg['message']);
//        return false;
//    }
//	return true;
    
}

function check_import_stock_balance_item_data(&$order, &$line_data_row)
{
    $id = $line_data_row["id"];
    
    if($order->sample_items == true){
                $item = get_item($line_data_row['stock_id']);
                if($item['sample_item'] != 1)
                {
                    update_import_stock_balance_record($id,"Selected item is not a sample item");
                    return false;
                }
    }
    else{
                $item = get_item($line_data_row['stock_id']);
                if($item['sample_item'] != 0)
                {
                    update_import_stock_balance_record($id,"Selected item is a sample item");
                    return false;
                }    
    }      

    if (!is_numeric($line_data_row['tran_qty']))
    {
            update_import_stock_balance_record($id,"The quantity entered is invalid.");
            return false;
    }

    if (!is_numeric($line_data_row['std_cost']))
    {
            update_import_stock_balance_record($id,"The entered cost is invalid.");
            return false;
    }

    if(!$line_data_row['std_cost'] > 0){
            update_import_stock_balance_record($id,"The entered cost is negative.");
            return false;
    }

   	return true;
}


//-----------------------------------------------------------------------------------------------

function create_new_cart_for_import_stock_balances($header)
{
	if (isset($_SESSION['import_stock_balances_items']))
	{
		$_SESSION['import_stock_balances_items']->clear_items();
		unset ($_SESSION['import_stock_balances_items']);
	}

    $_SESSION['import_stock_balances_items'] = new items_cart(ST_INVADJUST);
	if (!is_date_in_fiscalyear($header['date']))
		$header['date'] = end_fiscalyear();
	$_SESSION['import_stock_balances_items']->tran_date = $header['date'];	
}



function update_import_stock_balance_record($id, $message)
{
    $sql = "UPDATE item_balances_import SET message = ".db_escape($message)." WHERE id = ".$id;
    db_query($sql);
}
?>