<?php


function can_insert_items($row) {
    global $unknown;
    $error='';
    $data=array();
    $data['insert']=true;
    $data['stock_id']=$row[0];
    $data['description']=$row[1];
    $data['category_id']=$row[2];
    $data['units']=$row[3];
    $data['mb_flag']=$row[4];
    $data['sales_type_id']=$row[5];
    $data['curr_abrev']=$row[6];
    $data['price']=$row[7];
    $data['tax_type_id']=$row[8 ];
    $data['sales_account']=$row[9];
    $data['cogs_account']=$row[10];
    $data['inventory_account']=$row[11];
    $data['adjustment_account']=$row[12];
    $data['wip_account']=$row[13];
    $check_empty =array('Stock ID Column'=>$row[0],'Description Column'=>$row[1],'Category Column'=>$row[2]);
    if($error=check_empty($check_empty)){
        array_push($row, $error);
        array_push($unknown, $row);
        return false;
    }   
        // $data['units']=default_stock_cvalue($row[3],'dflt_units',$data['category_id']);
        // $data['mb_flag']=default_stock_cvalue($row[4],'dflt_mb_flag',$data['category_id']);
        // $data['tax_type_id']=default_stock_cvalue($row[8],'dflt_tax_type',$data['category_id']);
        // $data['sales_account']=default_stock_cvalue($row[9],'dflt_sales_act',$data['category_id']);
        // $data['cogs_account']=default_stock_cvalue($row[10],'dflt_cogs_act',$data['category_id']);
        // $data['inventory_account']=default_stock_cvalue($row[11],'dflt_inventory_act',$data['category_id']);
        // $data['adjustment_account']=default_stock_cvalue($row[12],'dflt_adjustment_act',$data['category_id']);
        // $data['wip_account']=default_stock_cvalue($row[13],'dflt_wip_act',$data['category_id']);

    $data['category_id']= GetSingleValue('stock_category','category_id',array('description'=>trim($row[2])));
    
    if(!$data['category_id']){
        $check_empty =array('Unit Column'=>$row[3],'Flag Column'=>$row[4],'Tax Type column'=>$row[8]);
        if($error=check_empty($check_empty)){
            array_push($row, $error);
            array_push($unknown, $row);
            return false;
        }
        $data['sales_account']=get_sys_defaults($row[9],'default_inv_sales_act');
        $data['cogs_account']=get_sys_defaults($row[10],'default_cogs_act');
        $data['inventory_account']=get_sys_defaults($row[11],'default_inventory_act');
        $data['adjustment_account']=get_sys_defaults($row[12],'default_adj_act');
        $data['wip_account']=get_sys_defaults($row[13],'default_wip_act');
        $data['tax_type_id']=get_tax_type_id($row[8]);
        $data['category_id']=Insert('stock_category',
            array('description'=>$row[2],
                'dflt_tax_type'=>$data['tax_type_id'],
                'dflt_units'=>$data['units'],
                'dflt_mb_flag'=>$data['mb_flag'],
                'dflt_sales_act'=>$data['sales_account'],
                'dflt_cogs_act'=>$data['cogs_account'],
                'dflt_inventory_act'=>$data['inventory_account'],
                'dflt_adjustment_act'=>$data['adjustment_account'],
                'dflt_wip_act'=>$data['wip_account'],
                'dflt_dim1'=>0,
                'dflt_dim2'=>0)
            );
    }else{
        $data['units']=default_stock_cvalue($row[3],'dflt_units',$data['category_id']);
        $data['mb_flag']=default_stock_cvalue($row[4],'dflt_mb_flag',$data['category_id']);
        $data['tax_type_id']=default_stock_cvalue($row[8],'dflt_tax_type',$data['category_id']);
        $data['sales_account']=default_stock_cvalue($row[9],'dflt_sales_act',$data['category_id']);
        $data['cogs_account']=default_stock_cvalue($row[10],'dflt_cogs_act',$data['category_id']);
        $data['inventory_account']=default_stock_cvalue($row[11],'dflt_inventory_act',$data['category_id']);
        $data['adjustment_account']=default_stock_cvalue($row[12],'dflt_adjustment_act',$data['category_id']);
        $data['wip_account']=default_stock_cvalue($row[13],'dflt_wip_act',$data['category_id']);
    }   
    $check_empty =array('Unit Column'=>$data['units'],'Flag Column'=>$data['mb_flag'],'Tax Type column'=>$data['tax_type_id'],'Sales Column'=>$data['sales_account'],'Cogs Column'=>$data['cogs_account'],'Inventory Column'=>$data['inventory_account'],'Adjustment Column'=>$data['adjustment_account'],'Wip Column'=>$data['wip_account']);
    if($data['price'] !=0 || $data['price'] !=''){
         $check_empty['Sales_type Column']=$data['sales_type_id'];
         $check_empty['Currency column']=$data['curr_abrev'];
    }
    if($error=check_empty($check_empty)){
        array_push($row, $error);
        array_push($unknown, $row);
        return false;
    }
    $data['tax_type_id']=get_tax_type_id($row[8]);
    $data['sales_type_id']=get_sales_type_id($row[5]);
    if(!$data['curr_abrev'] =get_curr_abrev($row[6])){
        array_push($row,"Incorrect curency value");
        display_error(json_encode($unknown));
        array_push($unknown, $row);
        cancel_transaction();
        return false;
    }

    if($error=value_exists_stock_master($row[0],'Stock id')){
        if(!GetSingleValue('prices','id',array('stock_id'=>$data['stock_id'],'sales_type_id'=>$data['sales_type_id'], 'curr_abrev'=>$data['curr_abrev']))){
            if($data['price'] !=0 || $data['price'] !=''){
                $prices =Insert('prices',
                    array('stock_id'=>$data['stock_id'],
                        'sales_type_id'=>$data['sales_type_id'],
                        'curr_abrev'=>$data['curr_abrev'], 'price'=>$data['price'])
                    );
                return false;
            }
            return false;
        }else{
            array_push($row, $error);
            array_push($unknown, $row);
            return false;
        }
    }
    return $data;
}

function import_items($file_name){
    global $unknown  ;
    $file =fopen($file_name, 'r');
    $counter =-1;
    $result='';
    $for_next =array();
    $unformatted_csv=false;
    while ($row=fgetcsv($file)) {
        if($counter!=-1){
            $counter++;
           	if($counter<=$_POST["max_rows"]){
	            $data= can_insert_items($row);   
                begin_transaction();
	            if(!$data){
	                cancel_transaction();
	            }else{
	                Insert('stock_master',
	                    array(
	                        'stock_id'=>$data['stock_id'],
	                        'description'=>$data['description'],
	                        'category_id'=>$data['category_id'],
	                        'units'=>$data['units'],
	                        'mb_flag'=>$data['mb_flag'],
	                        'tax_type_id'=>$data['tax_type_id'],
	                        'sales_account'=>$data['sales_account'],
	                        'cogs_account'=>$data['cogs_account'],
	                        'inventory_account'=>$data['inventory_account'],
	                        'adjustment_account'=>$data['adjustment_account'],
	                        'wip_account'=>$data['wip_account'],
	                        'dimension_id'=>0,
	                        'dimension2_id'=>0  
	                    )
	                );
	                $result1= db_num_affected_rows();
	                $result2 =Insert('item_codes',
	                    array(
	                        'item_code'=>$data['stock_id'],
	                        'stock_id'=>$data['stock_id'],
	                        'description'=>$data['description'],
	                        'category_id'=>$data['category_id'], 
	                        'quantity'=>1,
	                        'is_foreign'=>0
	                    )
	                );
	                
	                if($result1 && $result2){
	                    commit_transaction();
	                }else{
	                    cancel_transaction();
	                    array_push($row,'unknown error');
	                	array_push($unknown,$row);
	                }
	            }
	        }else{
	            array_push($for_next,$row);
	        }
        }else {
            $check_array =array('Stock ID','Description' ,'Category','Units','Flag','Sales Type','Currency', 'Price','Tax Type','Sales','Cogs','Inventory','Adjustment','Wip');
            if(array_diff($check_array,$row)){
                display_error('Cant import ! Unformatted CSV file ! You can download and edit sample file');
                $unformatted_csv=true;
                break;
            }
            array_push($row,'Memo');
            $unknown=array();
            array_push($unknown,$row);
            $counter++;
        } 
    }
    if(!$unformatted_csv){
        $error_rows=sizeof($unknown)-1;
        $remaining_rows =sizeof($for_next);
        foreach ($for_next as $value) {
            array_push($unknown, $value);
        }   
        if($error_rows ==0 && $remaining_rows ==0){
            display_notification($counter-$error_rows-$remaining_rows.' rows are inserted');
        }else{   
            put_csv($unknown);
            display_error($counter-$error_rows-$remaining_rows.' rows are inserted <br> '.$error_rows.' row are having errors while uploading <br> '.$remaining_rows.' rows are yet to be added <br><a href="'.$_SERVER['PHP_SELF'].'?dl='.$_FILES['file']['name'].'" > Click Here </a> Download the CSV File and reupload it again after correcting the errors if any to import the rest of the items');
        }
    }

}


function export_items(){
    global $path_to_root;
   $export_items =array();
   $export_items []=array('Stock ID','Description' ,'Category','Units','Flag','Sales Type','Currency',    'Price','Tax Type','Sales','Cogs','Inventory','Adjustment','Wip');

   $items = GetDataJoin('stock_master AS stock_master', array( 
                    0 => array('join' => 'LEFT', 'table_name' => 'stock_category AS stock_category', 'conditions' => '`stock_master`.`category_id` = `stock_category`.`category_id`'), 
                    1 => array('join' => 'LEFT', 'table_name' => 'item_tax_types AS item_tax_types', 'conditions' => '`stock_master`.`tax_type_id` = `item_tax_types`.`id`'),   
                    2 => array('join' => 'LEFT', 'table_name' => 'prices AS prices', 'conditions' => '`stock_master`.`stock_id` =`prices`.`stock_id`'), 
                    3 => array('join' => 'LEFT', 'table_name' => 'sales_types AS sales_types', 'conditions' => '`prices`.`sales_type_id` = `sales_types`.`id`')
                        ), 
            array('stock_master.*','stock_category.description AS category','item_tax_types.name AS tax_type','prices.curr_abrev AS currency','prices.price AS price','sales_types.sales_type AS sales_type'));

    if(!empty($items)){
        foreach ($items as  $item) {
           $export_items []=array($item['stock_id'],$item['description'],$item['category'],$item['units'],$item['mb_flag'],$item['sales_type'],$item['currency'],$item['price'],$item['tax_type'],$item['sales_account'],$item['cogs_account'],$item['inventory_account'],$item['adjustment_account'],$item['wip_account']);
        }

        export_csv($export_items,'items');
    }else{
         $msg="Click <a target='_blank' href='$path_to_root/inventory/manage/items.php?' onclick=\"javascript:openWindow(this.href,this.target); return false;\"> here</a> to add inventory items";
        display_error('There is no item(s) to export ! You can import from CSV file or '.$msg);
    }
}


?>
