<?php

function can_insert_suppliers($row) {
    global $unknown;
    $error='';
    $data=array();

    $data['supplier_name'] =$row[0];
    $data['supp_ref'] =$row[1];
    $data['contact'] =$row[2];
    $data['email'] =$row[3];
    $data['gst_no'] =$row[4];
    $data['curr_code'] =$row[5];
    $data['payment_terms_id'] =$row[6];
    $data['tax_included'] =$row[7];
    $data['tax_group_id'] =$row[8];
    $data['purchase_account'] =$row[9];
    $data['payable_account'] =$row[10];
    $data['payment_discount_account'] =$row[11];
    $data['address'] =$row[12];
    $data['bank_account']="";


    $check_empty =array('Supplier Name Column'=>$row[0],'Short name Column'=>$row[1]);
    if($error=check_empty($check_empty)){
        array_push($row, $error);
        array_push($unknown, $row);
        return false;
    }
    if($error=value_exists_suppliers($row[1],'Short name')){
        array_push($row, $error);
        array_push($unknown, $row);
        return false;
    }
    // $check_empty =array('Phone'=>$row[2],'Email'=>$row[3],'Tax included'=>$row[7]);
    // $check_empty =array('Tax included'=>$row[7]);
    if($error=check_empty($check_empty)){
        array_push($row, $error);
        array_push($unknown, $row);
        return false;
    }
    if(!$data['curr_code'] =get_curr_abrev($row[5])){
        array_push($row,"Incorrect curency value");
        array_push($unknown, $row);
        cancel_transaction();
        return false;
    } 
    // $data['sales_type_id']=get_sales_type_id($row[4]);
    if(!$data['payment_terms_id']=get_payment_terms_id($row[6])){
        array_push($row,"Incorrect Payment terms");
        array_push($unknown, $row);
        return false;
    }  
    if(!$data['tax_group_id'] =get_tax_group_id_two($row[8])){
        array_push($row,"Incorrect tax group ");
        array_push($unknown, $row);
        return false;
    } 
    // $data['sales_discount_account']=get_sys_defaults ($row[10],'default_sales_discount_act');
    // $data['receivables_account']=get_sys_defaults ($row[11],'debtors_act');
    // $data['payment_discount_account']=get_sys_defaults ($row[11],'default_prompt_payment_act');
    // $locations =GetRow('locations');
    // $data['default_location'] =$locations['loc_code'];
    if($data['tax_included'] !='' && strtolower($data['tax_included'])!='yes' && strtolower($data['tax_included'])!='no'){
        array_push($row,"Tax included Column must be 'Yes' or 'No'");
        array_push($unknown, $row);
        return false;

    }

    if(strtolower($data['tax_included'])=='yes'){
        $data['tax_included']=1;
    }else{
         $data['tax_included']=0;
    }
    $data['supplier_id']=Insert('suppliers',
        array(
            'supp_name'=>$data['supplier_name'],
            'supp_ref'=>$data['supp_ref'],
            'contact'=>$data['contact'],      
            'gst_no'=>$data['gst_no'] ,
            'curr_code'=>$data['curr_code'] ,
            'payment_terms'=>$data['payment_terms_id'] ,
            'tax_included'=>$data['tax_included'] ,
            'tax_group_id'=>$data['tax_group_id'] ,
            'purchase_account'=>$data['purchase_account'] ,
            'payable_account'=>$data['payable_account'] ,
            'payment_discount_account'=>$data['payment_discount_account'] ,
            'bank_account'=>$data['bank_account'] ,
            'address'=>$data['address'] ,
        ));
    return $data;
}



function import_suppliers($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"]){
	            begin_transaction();
	            $data=can_insert_suppliers($row);   
	            if(!$data){
	                cancel_transaction();
	            }else{
	                $data['person_id']=Insert('crm_persons',
	                    array(
	                        'ref'=>$data['supp_ref'],
	                        'name'=>$data['supplier_name'],
	                        'address'=>$data['address'],
	                        'phone'=>$data['contact'],
	                        'email'=>$data['email']
	                    )
	                );
	                $result1=Insert('crm_contacts',
	                    array(
	                        'person_id'=>$data['person_id'],
	                        'type'=>'supplier',
	                        'action'=>'general',
	                        'entity_id'=>$data['supplier_id']
	                    )
	                ); 
	                if($result1){
	                    commit_transaction();
	                }else{
	                    cancel_transaction();
	                }
	            }
            }else{
                array_push($for_next,$row);
            }
        }else {
            $check_array =array('Supplier Name','Short Name' ,'Phone','Email','GST No','Currency Code',' Payment Term','Tax Included','Tax Group','Purchase Account','Payable Account','Discount','Address');
            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_suppliers(){
    global $path_to_root;
    $export_suppliers =array();
    $export_suppliers []=array('Supplier Name','Short Name' ,'Phone','Email','GST No','Currency Code',' Payment Term','Tax Included','Tax Group','Purchase Account','Payable Account','Discount','Address');


    $suppliers = GetDataJoin('suppliers AS suppliers', array( 
                    0 => array('join' => 'LEFT', 'table_name' => 'crm_contacts AS crm_contacts', 'conditions' => '`suppliers`.`supplier_id` = `crm_contacts`.`entity_id`AND crm_contacts.type ="supplier"'),

                    1=> array('join' => 'LEFT', 'table_name' => 'crm_persons AS crm_persons', 'conditions' => '`crm_contacts`.`person_id` = `crm_persons`.`id`'),

                    2=> array('join' => 'LEFT', 'table_name' => 'payment_terms AS payment_terms', 'conditions' => '`suppliers`.`payment_terms` =`payment_terms`.`terms_indicator`'), 
                    3=> array('join' => 'LEFT', 'table_name' => 'tax_groups AS tax_groups', 'conditions' => '`suppliers`.`tax_group_id` = `tax_groups`.`id`')
                ), 
            array('suppliers.*','payment_terms.terms AS payment_term','crm_persons.email AS email','crm_persons.phone AS phone','tax_groups.name AS tax_group'));

    if(!empty($suppliers)){

        foreach ($suppliers as  $supplier) {

           $export_suppliers []=array($supplier['supp_name'],$supplier['supp_ref'],$supplier['contact'],$supplier['email'],$supplier['gst_no'],$supplier['curr_code'],$supplier['payment_term'],($supplier['tax_included'])?'Yes':'No',$supplier['tax_group'],$supplier['purchase_account'],$supplier['payable_account'],$supplier['payment_discount_account'],$supplier['address']);
        }

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


?>
