<?php

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

    $data['br_name'] =$row[0];
    $data['branch_ref'] =$row[1];
    $data['tax_id'] =$row[2];
    $data['curr_code'] =$row[3];
    $data['sales_type_id'] =$row[4];
    $data['payment_terms_id'] =$row[5];
    $data['phone'] =$row[6];
    $data['mail'] =$row[7];
    $data['tax_group_id'] =$row[8];
    $data['sales_account'] =$row[9];
    $data['sales_discount_account'] =$row[10];
    $data['receivables_account'] =$row[11];
    $data['payment_discount_account'] =$row[12];
    $data['bank_account'] =$row[13];
    $data['br_address'] =$row[14];

    $data['debtor_no'] ='';
    $data['area'] =$row[15];
    $data['salesman'] =$row[16];
    $data['credit_status'] =$row[17];
    $data['default_location'] ='';
    $data['br_post_address'] =$row[14];
    $data['notes'] ='';

    $check_empty =array('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_debtors_master($row[1],'Short name')){
        array_push($row, $error);
        array_push($unknown, $row);
        return false;
    }
    $check_empty =array('Payment terms'=>$row[5],'Tax Group'=>$row[8]);
    if($error=check_empty($check_empty)){
        array_push($row, $error);
        array_push($unknown, $row);
        return false;
    }
    if(!$data['curr_abrev'] =get_curr_abrev($row[3])){
        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[5])){
        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;
    } 
    if(!$data['area'] =get_area_code($data['area'])){
        array_push($row,"There is no area is defined in this system ");
        array_push($unknown, $row);
        return false;
    } 
    if(!$data['salesman'] =get_sales_person_id($data['salesman'])){
        array_push($row,"Incorrect salesman or there is no salesman in this system ");
        array_push($unknown, $row);
        return false;
    }
    if(!$data['credit_status'] =get_credit_status_id($data['credit_status'])){
        array_push($row,"Incorrect credit status or there is no credit status in this system ");
        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'];
    $data['debtor_no']=Insert('debtors_master',
        array(
            'name'=>$data['br_name'],
            'debtor_ref'=>$data['branch_ref'],
            'user_id'=>0,
            'address'=>$data['br_address'],
            'tax_id'=>$data['tax_id'],
            'curr_code'=>$data['curr_code'],
            'sales_type'=>$data['sales_type_id'],
            'credit_status'=>$data['credit_status'],
            'payment_terms'=>$data['payment_terms_id'],
            'discount'=>0,
            'pymt_discount'=>0
        ));
    return $data;
}
function import_customers($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_customers($row);   
	            if(!$data){
	                cancel_transaction();
	            }else{
	                $data['branch_code'] =Insert('cust_branch',
	                    array(
	                        'debtor_no'=>$data['debtor_no'],
	                        'br_name'=>$data['br_name'],
	                        'branch_ref'=>$data['branch_ref'],
	                        'br_address'=>$data['br_address'],
	                        'area'=>$data['area'],
	                        'salesman'=>$data['salesman'],
	                        'default_location'=>$data['default_location'],
	                        'tax_group_id'=>$data['tax_group_id'],
	                        'sales_account'=>$data['sales_account'],
	                        'sales_discount_account'=>$data['sales_discount_account'],
	                        'receivables_account'=>$data['receivables_account'],
	                        'payment_discount_account'=>$data['payment_discount_account'],
	                        'br_post_address'=>$data['br_post_address'],
	                        'notes'=>$data['notes'],
	                        'bank_account'=>$data['bank_account']
	                    )
	                );


                     $ph_no = explode(array(',','&'), $data['phone']);
	                $data['person_id']=Insert('crm_persons',
	                    array(
	                        'ref'=>$data['branch_ref'],
	                        'name'=>$data['br_name'],
	                        'address'=>$data['br_address'],
	                        'phone'=>$ph_no[0],
                            'phone2'=>$ph_no[1],
	                        'email'=>$data['mail']
	                    )
	                );
	                $result1=Insert('crm_contacts',
	                    array(
	                        'person_id'=>$data['person_id'],
	                        'type'=>'cust_branch',
	                        'action'=>'general',
	                        'entity_id'=>$data['branch_code']
	                    )
	                );
	                $result2=Insert('crm_contacts',
	                    array(
	                        'person_id'=>$data['person_id'],
	                        'type'=>'customer',
	                        'action'=>'general',
	                        'entity_id'=>$data['debtor_no']
	                    )
	                );    
	                if($result1 && $result2 ){
	                    commit_transaction();
	                }else{
	                    cancel_transaction();
	                }
	            }
            }else{
                 array_push($for_next,$row);
            }
        }else {
            $check_array =array('Name','Short Name' ,'Tax ID','Currency','Sales Type','Payment Terms','Phone','Email','Tax Group','Sales Account','Sales Discount','Receivables','Payment Discount','Bank Account','Address','Area','Sales person','Credit Status');
            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_customers(){
     global $path_to_root;
   $export_customers =array();
   $export_customers []=array('Name','Short Name' ,'Tax ID','Currency','Sales Type','Payment Terms','Phone',    'Email','Tax Group','Sales Account','Sales Discount','Receivables','Payment Discount','Bank Account','Address','Area','Sales person','Credit Status');

   $customers = GetDataJoin('debtors_master AS debtors_master', array( 
                    0 => array('join' => 'LEFT', 'table_name' => 'crm_contacts AS crm_contacts', 'conditions' => '`debtors_master`.`debtor_no` = `crm_contacts`.`entity_id` AND crm_contacts.type ="customer"'),

                    1=> array('join' => 'LEFT', 'table_name' => 'crm_persons AS crm_persons', 'conditions' => '`crm_contacts`.`person_id` = `crm_persons`.`id`AND crm_contacts.type ="customer" AND crm_contacts.entity_id ="debtors_master.debtor_no"'),

                    2=> array('join' => 'LEFT', 'table_name' => 'cust_branch AS cust_branch', 'conditions' => '`debtors_master`.`debtor_no` = `cust_branch`.`debtor_no`'), 

                    3 => array('join' => 'LEFT', 'table_name' => 'payment_terms AS payment_terms', 'conditions' => '`debtors_master`.`payment_terms` =`payment_terms`.`terms_indicator`'), 

                    4 => array('join' => 'LEFT', 'table_name' => 'sales_types AS sales_types', 'conditions' => '`debtors_master`.`sales_type` = `sales_types`.`id`'),
                    5 => array('join' => 'LEFT', 'table_name' => 'tax_groups AS tax_groups', 'conditions' => '`cust_branch`.`tax_group_id` = `tax_groups`.`id`'),
                    6 => array('join' => 'LEFT', 'table_name' => 'areas AS areas', 'conditions' => '`cust_branch`.`area` = `areas`.`area_code`'),
                    7 => array('join' => 'LEFT', 'table_name' => 'salesman AS salesman', 'conditions' => '`cust_branch`.`salesman` = `salesman`.`salesman_code`'),
                    8=> array('join' => 'LEFT', 'table_name' => 'credit_status AS credit_status', 'conditions' => '`debtors_master`.`credit_status` = `credit_status`.`id`')
                ), 
            array('debtors_master.*','sales_types.sales_type AS sales_type','payment_terms.terms AS payment_term','crm_persons.email AS email','crm_persons.phone AS phone','tax_groups.name AS tax_group'
            ,'cust_branch.sales_account AS sales_account','cust_branch.sales_discount_account AS sales_discount_account','cust_branch.receivables_account AS receivables_account','cust_branch.payment_discount_account AS payment_discount_account','cust_branch.bank_account AS bank_account','areas.description AS area','salesman.salesman_name AS salesman','credit_status.reason_description AS credit_status'));
    if(!empty($customers)){
        foreach ($customers as  $customer) {
           $export_customers []=array($customer['name'],$customer['debtor_ref'],$customer['tax_id'],$customer['curr_code'],$customer['sales_type'],$customer['payment_term'],$customer['phone'],$customer['email'],$customer['tax_group'],$customer['sales_account'],$customer['sales_discount_account'],$customer['receivables_account'],$customer['payment_discount_account'],$customer['bank_account'],$customer['address'],$customer['area'],$customer['salesman'],$customer['credit_status']);
        }

        export_csv($export_customers,'customers');

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