<?php

function upload_asset_verification_count_details_import_file(&$Mode) {
    if ($Mode == 'ADD_ITEM' && (!isset($_FILES['filename']) || $_FILES['filename']['size'] == 0)){
        display_error(_("Select attachment file."));
        return;
    }
    
    $tmpname = $_FILES['filename']['tmp_name'];

    $dir =  company_path()."/import_files";
    if (! file_exists($dir)) {
        mkdir ($dir,0777);
        $index_file = "<?php\nheader(\"Location: ../index.php\");\n?>";
        $fp = fopen($dir."/index.php", "w");
        fwrite($fp, $index_file);
        fclose($fp);
    }

    $dir =  company_path()."/import_files/asset_verification_counts";
    if (!file_exists($dir)) {
        mkdir ($dir,0777);
        $index_file = "<?php\nheader(\"Location: ../index.php\");\n?>";
        $fp = fopen($dir."/index.php", "w");
        fwrite($fp, $index_file);
        fclose($fp);
    }

    $filename = basename($_FILES['filename']['name']);
    $file_name = "Import_Asset_Verification_Count";

    if ($filename && file_exists($dir."/".$file_name)){
        unlink($dir."/".$file_name);
    }

    move_uploaded_file($tmpname, $dir."/".$file_name);

	$Mode = 'RESET';
}


function display_asset_verification_import_file_data() {
    $file_data = get_session_variable('import_asset_verification_count');
        if ($file_data == '') {
            $file_data = read_asset_verification_count_import_file();
        }

        set_session_variable('import_asset_verification_count', $file_data);
}
    
function read_insert_asset_verification_count_details_import_file_data() {
    $file_name = "Import_Asset_Verification_Count";
    $file_path_name = company_path()."/import_files/asset_verification_counts/".$file_name;
        
        if (file_exists($file_path_name)) {
            $file_handle = fopen($file_path_name, "r");
        } else {
            return array();
        }
        
        $header_line = true;
        if ($file_handle) {            
            while (! feof($file_handle)) {
                $line = fgetcsv($file_handle, 1024);
                
                if ($header_line || (! is_array($line))) {
                    $header_line = false;
                    continue;
                } 
                
                read_asset_verification_count_details_import_file_data($line);
            } 
            
            fclose($file_handle);
        } 
}

function display_import_asset_verification_count_details_file_data() {  
    global $stock_counting_statuses;
    
    start_table(TABLESTYLE, "width=80%");    
    
        $th = array("ID", "Asset Verification Count No", "Status", "Sheet No", "Asset Code", "Good Qty", "Damaged Qty", "Message" );                  
        table_header($th);
    
        $k = 0;
        $result = get_import_asset_verification_count_details_with_asset_verification_count_header();
            while($row = db_fetch($result)){
                alt_table_row_color($k);

                    label_cell($row['id'], 'align=center');
                    if (key_exists($row['avch_status_id'], $stock_counting_statuses)) {
                        label_cell($row['asset_verification_count_no'], 'align=center');
                        label_cell($stock_counting_statuses[$row['avch_status_id']]);
                    } else {
                        label_cell($row['asset_verification_count_no'].' (Wrong Header No)', 'align=center style=color:red');
                        label_cell('Unknown', "style=color:red");
                    }
                    label_cell($row['sheet_no']);
                    label_cell($row['asset_id']);
                    label_cell($row['good_qty']);
                    label_cell($row['damaged_qty']);
                    label_cell($row['message']);

                end_row();
            }
  
    end_table(2);
}

function read_asset_verification_count_details_import_file_data($line) {
    $asset_verification_count_no = str_replace('"', '', $line[0]);
    $sheet_no = str_replace('"', '', $line[1]);
    $asset_id = str_replace('"', '', $line[2]);                    
    $good_qty = str_replace('"', '', $line[3]);
    $damaged_qty = str_replace('"', '', $line[4]);
    $message = str_replace('"', '', $line[5]);        
   
    save_import_asset_verification_count_details($asset_verification_count_no, $sheet_no, $asset_id, $good_qty, $damaged_qty, $message);
}

function import_asset_verification_count_details() {
    global $stock_counting_statuses;
    
    $import_error = 0;
    
    $imp_sc_res = get_importing_asset_verification_counts();
    $m = db_num_rows($imp_sc_res);
        if ($m > 1) {
            display_error("Multiple asset verification count numbers found in the importing data.");
            return false;
        }
    
    $imp_sc = db_fetch($imp_sc_res);
        if (! (isset($imp_sc['asset_verification_count_no']) && $imp_sc['asset_verification_count_no'] > 0)) {
            display_error("No valid asset verification count number found in the importing data.");
            return false;
        }
        
    $asset_verification_count_no = $imp_sc['asset_verification_count_no'];
    
    $stock_count_h = get_asset_verification_count_header_record($asset_verification_count_no);
        if (! is_array($stock_count_h)) {
            display_error("No defined asset verification count found for the importing asset verification count number $asset_verification_count_no.");
            return false;
        }
    
    if ($stock_count_h['status_id'] != SC_COUNTING){
        display_error(_('Only asset verification count with status "'.$stock_counting_statuses[SC_COUNTING].'" allow importing counted details.')); 
        return false;
    }

    $result = get_import_asset_verification_count_details();
        while ($myrow = db_fetch($result)) {
            $import_error = 0;
            $data = array();

            $data['header_status_id'] = $stock_count_h['status_id'];
            $data['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_asset_verification_details_count_data($myrow, $data) === true) {
                if (can_process_asset_verification_count_data($data) === true) {
                    save_asset_verification_count_data($data);
                }
            }
        }
}

function check_import_asset_verification_details_count_data($myrow, &$data) {

    $id = $myrow['id'];
    $data['id'] = $myrow['id'];

        $cscn = check_asset_verification_count_number($myrow['asset_verification_count_no']);
            if ($cscn['passed'] == true) {
                $data['asset_verification_count_no'] = $cscn['message'];
            } else {
                update_import_asset_verification_count_detail_record($id, $cscn['message']);
                return false;
            }
        
        $csn = check_import_asset_verification_count_sheet_number($myrow['sheet_no']);
            if ($csn['passed'] == true) {
                $data['sheet_no'] = $csn['message'];
            } else {
                update_import_asset_verification_count_detail_record($id, $csn['message']);
                return false;
            }
        
        $msg = check_import_asset_verification_count_asset_id($myrow['asset_id']);
            if ($msg['passed'] == true) {
                $data['asset_id'] = $msg['message'];    
            } else {
                update_import_asset_verification_count_detail_record($id, $msg['message']);
                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_import_asset_verification_count_detail_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_import_asset_verification_count_detail_record($id, $msg);
            return false;
        }
        
        $asset_row = get_asset($myrow['asset_id']);
        if ($asset_row['multiple_items'] == 0) {
            $asset_counted_qty = $myrow['good_qty'] + $myrow['damaged_qty'];
                if ($asset_counted_qty > 1) {
                    $msg = (_("Total counted quantity cannot be higher than one for single item assets."));
                    update_import_asset_verification_count_detail_record($id, $msg);
                    return false;
                }
        }
        
        return true;
}

function can_process_asset_verification_count_data(&$data) {
    $avc_item = check_asset_verification_count_item_exists($data['asset_verification_count_no'], $data['asset_id']);
        if (is_array($avc_item)) {
            if ($data['sheet_no'] != $avc_item['sheet_no']){
                $msg = "Selected asset already entered in sheet number ".$avc_item['sheet_no'];
                update_import_asset_verification_count_detail_record($data['id'], $msg);
                return false;
            }
        }
    
    return true;
}

function save_asset_verification_count_data($data) {
    $avc_item = array();
    
    build_asset_verification_count_detail_import_array($avc_item, $data);
    
    $scsi = get_asset_verification_count_sheet_item($data['asset_verification_count_no'], $data['sheet_no'], $data['asset_id']);
        if (is_array($scsi)) {
            $avc_item['selected_id'] = $scsi['id'];
        } else {
            $avc_item['selected_id'] = -1;
        }
    
    $msg = save_asset_verification_count_detail_item($avc_item);
        if ($avc_item['selected_id'] > 0) {    
            if ($msg['success'] !== true) {        
                update_asset_verification_count_import_record($data['id'], $msg['message']);
            } else {
                update_asset_verification_count_import_record($data['id'], "Record Updated");
            }
        } else {
            if ($msg['success'] !== true) {        
                update_asset_verification_count_import_record($data['id'], $msg['message']);
            } else {
                update_asset_verification_count_import_record($data['id'], "Record Inserted");
            }  
        }
}

function build_asset_verification_count_detail_import_array(&$avc_item, $data) {
    $avc_item['asset_verification_count_no'] = $data['asset_verification_count_no'];
    $avc_item['asset_id'] = $data['asset_id'];
    
    $avc_item['good_qty'] = $data['good_qty'];
    $avc_item['damaged_qty'] = $data['damaged_qty'];
    
    $avc_item['sheet_no'] = $data['sheet_no'];
    $avc_item['line_sheet_no'] = $data['sheet_no'];
    
    $avc_item['status_id'] = $data['status_id'];
    $avc_item['header_status_id'] = $data['status_id'];
    $avc_item['loc_code'] = $data['loc_code'];
    $avc_item['tran_date'] = $data['tran_date'];
}

?>