<?php

function check_item_code($item_code)
{
    $sql = "SELECT IFNULL((SELECT stock_id FROM ".TB_PREF."stock_master 
                                WHERE stock_id =".db_escape($item_code)."), '') as stock_id";
    
    $result = db_query($sql);
    $stock_id = db_fetch($result);
    
    if($stock_id['stock_id'] == ''){
        $msg = "Unknown itemcode";
        return array("passed" => false, "message" => $msg);
    }
    else {
           return array("passed" => true, "message" => $stock_id['stock_id']);
    }
}

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

function check_stock_count_number($stock_count_no)
{
    global $stock_counting_statuses;
    
    $sql = "SELECT IFNULL((SELECT status_id FROM ".TB_PREF."stock_counts 
                                WHERE stock_count_no =".db_escape($stock_count_no)." ), '') as status_id";
    
    $result = db_query($sql);
    $myrow = db_fetch($result);
    
    if($myrow['status_id'] == ''){
        $msg = "Unknown stock count number";
        return array("passed" => false, "message" => $msg);
    }
    else {
        if(!($myrow['status_id'] == SC_NEW || $myrow['status_id'] == SC_COUNTING)){
            $msg = "Can not import data for a Stock Count with status ".$stock_counting_statuses[$myrow['status_id']];
            return array("passed" => false, "message" => $msg);
        }
        else{
            return array("passed" => true, "message" => $stock_count_no);
        }
    }
}


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

function check_sheet_number($sheet_no)
{    
    if(!(is_numeric($sheet_no) && $sheet_no > 0)){
        $msg = "Stock count sheet number has to be numeric and greater than zero.";
        return array("passed" => false, "message" => $msg);
    }
    else {
        return array("passed" => true, "message" => $sheet_no);        
    }
}

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

function get_unit_abbr($unit_name)
{
    $sql = "SELECT IFNULL((SELECT abbr FROM ".TB_PREF."item_units 
                                WHERE name =".db_escape($unit_name)."), '') as abbr";
    
    $result = db_query($sql);
    $myrow = db_fetch($result);
    
    if($myrow['abbr'] == ''){
        $msg = "Unknown unit name";
        return array("passed" => false, "message" => $msg);
    }
    else {
           return array("passed" => true, "message" => $myrow['abbr']);
    }
}

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

function get_pos_price_record_id($data)
{
    $sql = "SELECT IFNULL((SELECT id FROM ".TB_PREF."pos_prices 
                           WHERE stock_id =".db_escape($data['stock_id'])." AND 
                                    sales_type_id =".db_escape($data['sales_type_id'])." AND 
                                    curr_abrev =".db_escape($data['curr_abrev'])." AND 
                                    pos_price =".db_escape($data['price'])." AND 
                                    effective_date =".db_escape($data['effective_date'])." AND 
                                    expiry_date =".db_escape($data['expiry_date'])."), 0) as id";
    
    $result = db_query($sql);
    $myrow = db_fetch($result);
    
    return $myrow['id'];

}


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


function check_import_stock_count_data($myrow,&$data)
{

        $id = $myrow['id'];
        $data['id'] = $myrow['id'];
        
        $cscn = check_stock_count_number($myrow['stock_count_no']);
        if($cscn['passed'] == true){
            $data['stock_count_no'] = $cscn['message'];
        }
        else{
            update_stock_count_import_record($id,$cscn['message']);
            return false;
        }
        
        
        $csn = check_sheet_number($myrow['sheet_no']);
        if($csn['passed'] == true){
            $data['sheet_no'] = $csn['message'];
        }
        else{
            update_stock_count_import_record($id,$csn['message']);
            return false;
        }
        
        
        $msg = check_item_code($myrow['stock_id']);
        if($msg['passed'] == true){
            $data['stock_id'] = $msg['message'];    
        }
        else{
            update_stock_count_import_record($id,$msg['message']);
            return false;
        }
        
        
        $msg = get_unit_abbr($myrow['unit_name']);
        if($msg['passed'] == true){
            $data['unit'] = $msg['message'];
        }
        else{
            update_stock_count_import_record($id,$msg['message']);
            return false;
        }
        
        $itm = get_item_edit_info($data['stock_id']);
        $data['base_unit'] = $itm['units'];
//        if(check_num2($myrow['good_qty'], 0.0000001) || check_num2($myrow['damaged_qty'], 0.0000001)){
//            
//        }
//        else{
//            $msg = "Either good qty or damaged qty should have a positive value.";
//            update_stock_count_import_record($id,$msg);
//            return false;
//        }
        
        if(check_num2($myrow['good_qty'], 0)){
            $data['good_qty'] = $myrow['good_qty'];
        }
        else{
            $msg = "Good qunatity entered should be zero or higher.";
            update_stock_count_import_record($id,$msg);
            return false;
        }
        
        if(check_num2($myrow['damaged_qty'], 0)){
            $data['damaged_qty'] = $myrow['damaged_qty'];
        }
        else{
            $msg = "Damaged qunatity entered should be zero or higher.";
            update_stock_count_import_record($id,$msg);
            return false;
        }
        
        return true;
        
}


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

function can_process_stock_count_data(&$data)
{
    $sc_item = check_stock_count_item_exists($data['stock_count_no'], $data['stock_id']);
    if(isset($sc_item['sheet_no'])){
        if($sc_item['sheet_no'] == $sc_item['sheet_no']){
            // The same line. Can update
        }
        else{
            $msg = "Selected item already entered in sheet number ".$sc_item['sheet_no'];
            update_stock_count_import_record($data['id'],$msg);
            return false;
        }
    }
    return true;
    
}

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


function import_stock_count_details($import=false)
{
    global $stock_counting_statuses;
    
    $import_error = 0;
    
    $imp_sc_res = get_importing_stock_counts();
    $m = db_num_rows($imp_sc_res);
    if($m > 1){
        display_error("Multiple stockcount numbers found in the importing data.");
        return false;
    }
    
    $imp_sc = db_fetch($imp_sc_res);
    if(!(isset($imp_sc['stock_count_no']) && $imp_sc['stock_count_no'] > 0)){
        display_error("No valid stockcount number found in the importing data.");
        return false;
    }
    
    $stock_count_h = get_stock_count_header_record($imp_sc['stock_count_no']);
    if(!(isset($stock_count_h['stock_count_no']) && $stock_count_h['stock_count_no'] > 0)){
        display_error("No defined stockcount found for the importing stockcount number ".$imp_sc['stock_count_no']);
        return false;
    }
    
    if ($stock_count_h['status_id'] != SC_COUNTING){
        display_error(_('Only stockcounts with status "'.$stock_counting_statuses[SC_COUNTING].'" allow importing counted details.')); 
        return false;
    }

    $result = get_stock_count_data();
    while ($myrow = db_fetch($result))
    {
        $import_error = 0;
        $data = array();
        
        $data['header_status_id'] = $stock_count_h['status_id'];
        $data['loc_code'] = $stock_count_h['loc_code'];
        $data['tran_date'] = $stock_count_h['tran_date'];
        if(check_import_stock_count_data($myrow, $data) ==  true){
            if(can_process_stock_count_data($data) == true){
                if($import){
                    save_stock_count_data($data);
                }
            }
        }
        //break;
    }
}
//----------------------------------------------------------------------------------

function build_stock_count_detail_import_array(&$sc_item, $data)
{

    $sc_item['stock_count_id'] = $data['stock_count_no'];
    $sc_item['stock_id'] = $data['stock_id'];
    $sc_item['tran_unit'] = $data['unit'];
    
    $sc_item['tran_unit_good_qty'] = $data['good_qty'];
    $sc_item['tran_unit_damaged_qty'] = $data['damaged_qty'];
    
    $sc_item['line_sheet_no'] = $data['sheet_no'];
    
    $sc_item['base_unit'] = $data['base_unit'];
    
    $sc_item['header_status_id'] = $data['header_status_id'];
    $sc_item['loc_code'] = $data['loc_code'];
    $sc_item['tran_date'] = $data['tran_date'];
    
    return true;
}


function save_stock_count_data($data)
{
    $sc_item = array();

    $scsi = get_stock_count_sheet_item($data['stock_count_no'], $data['sheet_no'], $data['stock_id']);
    
    build_stock_count_detail_import_array($sc_item, $data);
    
    if(isset($scsi['id']) && $scsi['id'] > 0){
        $sc_item['selected_id'] = $scsi['id'];
    }
    else{
        $sc_item['selected_id'] = -1;
    }
    
    
//    build_stock_count_detail_array($sc_item, $selected_id, $stock_count_id);
    
    $msg = save_stock_count_detail_item($sc_item);
    if($sc_item['selected_id'] > 0){    
        if($msg['success'] !== true){        
            update_stock_count_import_record($data['id'],$msg['message']);
        }
        else{
            update_stock_count_import_record($data['id'],"Record Updated");
        }
    }
    else{
        if($msg['success'] !== true){        
            update_stock_count_import_record($data['id'],$msg['message']);
        }
        else{
            update_stock_count_import_record($data['id'],"Record Updated");
        }  
    }
}

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


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

function update_stock_count_import_record($id, $message)
{
    $sql = "UPDATE  import_stock_count_details SET message = ".db_escape($message)." WHERE id = ".$id;
    db_query($sql);
}


?>