<?php
global $unknown;
function can_insert_journal($row) {
    global $Refs,$unknown;
    $error='';
    $data=array();

    $data['source_reference'] =$row[0];
    $data['date'] =$row[1];
    $data['memo'] =$row[2];
    $data['amount'] =$row[3];
    $data['accountcode'] =$row[4];
    $data['person_type'] =$row[5];
    $data['person_name'] =$row[6];
    $data['dimension_id'] =$row[7];
    $data['dimension2_id'] =$row[8];
    $data['person_type_id'] ="";
    $data['person_id'] ="";
    
    if (!$data['date'] = date_create_from_format("Y-m-d",$data['date'])) {
        array_push($row, "Ivalid date format");
        array_push($unknown, $row);
        return false;
    }else{
        $data['date']= sql2date(date_format($data['date'],"Y-m-d"));
    }

    if (!is_date_in_fiscalyear($data['date'])) {
        array_push($row, "date not in fiscal year");
        array_push($unknown, $row);
        return false;
    }

    if (get_gl_account($data['accountcode']) == null) {
        array_push($row, "Could not find the account code");
        array_push($unknown, $row);
        return false;
    }
    
    if($data['person_type']){
        if(strtolower($data['person_type']) =="customer"){
            $data['person_type_id']=PT_CUSTOMER;
            if(! $data['person_id']=GetSingleValue('debtors_master','debtor_no',array('debtor_ref'=>$data['person_name']))){
                array_push($row, "The customer reference not found !");
                array_push($unknown, $row);
                return false;
            }
        }elseif(strtolower($data['person_type']) =="supplier"){
            $data['person_type_id']=PT_SUPPLIER;
            if(! $data['person_id']=GetSingleValue('suppliers','supplier_id',array('supp_ref'=>$data['person_name']))){
                array_push($row, "The supplier reference not found !");
                array_push($unknown, $row);
                return false;
            }
        }else{
            array_push($row, "Person type must be either customer or supplier. Leave this empty for default.");
            array_push($unknown, $row);
            return false;
        }
        
    }
    
    return $data;
}

function import_journal($file_name){
    global $unknown  ;
    $file =fopen($file_name, 'r');
    $counter =-1;
    $result='';
    $for_next =array();
    $unformatted_csv=false;

    $curr_journal=array();
    $journal_entires=array();
    $journal_amount =0;
    // create_journal_cart();
    while ($row=fgetcsv($file)) {

        if($counter!=-1){
            $counter++;
            $journal_amount +=$row[3];
            if(true){
                $data= can_insert_journal($row);   
                if(!$data){
                    // break;
                }else{
                    $curr_journal[]=$data;
                    if($journal_amount !=0){
                        if($curr_journal[0]['date'] !=$data['date']){

                            display_error('Incorrect journal entries ');
                            break;
                        }
                    }
                    if($journal_amount==0){
                        $journal_entires[] =$curr_journal;
                        $curr_journal=array();
                    }
                }
            }else{
                array_push($for_next,$row);
            }
        }else {
            $check_array =array('Source Reference','Date' ,'Memo','Amount','Account code','Person type','Person Name','Cost Center','Branch');
            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 && $journal_amount==0){
            foreach ($journal_entires as $journal_entires_key => $journal_entires_value) {
                //for create journal cart
                global $Refs;

                if (isset($_SESSION['journal_items']))
                {
                    unset($_SESSION['journal_items']);
                }
                $type=$trans_no=0;
                check_is_closed($type, $trans_no);
                $cart = new items_cart($type);
                $cart->order_id = $trans_no;
                $cart->tran_date = $cart->doc_date = $cart->event_date = $journal_entires_value[0]['date'];
                $cart->reference =$Refs->get_next(ST_JOURNAL, null, $journal_entires_value[0]['date']);

                $cart->source_ref = $journal_entires_value[0]['source_reference'];

                

                $cart->memo_=get_comments_string(ST_UNDEFINED, $trans_no);
                // $cart->tran_date = $cart->doc_date = $cart->event_date == sql2date($bank_trans['trans_date']);

                if (isset($cart->tax_info['net_amount']) || (!$trans_no && get_company_pref('default_gl_vat')))
                    $_POST['taxable_trans'] = true;
                $_SESSION['journal_items'] = &$cart;

                // for add journal items
                foreach ($journal_entires_value as $myrow) {
                    $amount = $myrow['amount'];
                    $_SESSION['journal_items']->add_gl_item($myrow['accountcode'], $myrow['dimension_id'],
                        $myrow['dimension2_id'], $amount, $myrow['memo'], '', $myrow['person_id']!=""?$myrow['person_id']:null);
                }
                //for add journal entries
                begin_transaction();
                // display_error('yes');
                $cart = &$_SESSION['journal_items'];
                $new = $cart->order_id == 0;

                $cart->tax_info = false;
                $trans_no = write_journal_entries($cart);

                    // retain the reconciled status if desired by user
                    if (isset($_POST['reconciled'])
                        && $_POST['reconciled'] == 1) {
                        $sql = "UPDATE ".TB_PREF."bank_trans SET reconciled=".db_escape($_POST['reconciled_date'])
                            ." WHERE type=" . ST_JOURNAL . " AND trans_no=".db_escape($trans_no);

                        db_query($sql, "Can't change reconciliation status");
                    }

                commit_transaction();
                $cart->clear_items();
            }
            display_notification($counter-$error_rows-$remaining_rows.' rows are inserted');
        }else{  
            if($error_rows ==0 && $remaining_rows ==0 && $journal_amount!=0){
                display_error('Incorrect journal entries');

            }else{
                put_csv($unknown);
               display_error('Cannot import journal entry.<br>'.$error_rows.' row are having errors while uploading <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.');


                // 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 get_counter_party_type($person_type_id){
    if($person_type_id ==PT_CUSTOMER){
        return "customer";
    }elseif($person_type_id ==PT_SUPPLIER){
        return "supplier";
    }else{
        return "";
    }
}
function get_counter_party($person_type_id,$person_id){
        if($person_type_id ==PT_CUSTOMER){
            $data['person_type_id']=PT_CUSTOMER;
            if($counter_party =GetSingleValue('debtors_master','debtor_ref',array('debtor_no'=>$person_id))){
                return $counter_party;
            }
            return "";
        }elseif($person_type_id ==PT_SUPPLIER){
            if($counter_party =GetSingleValue('suppliers','supp_ref',array('supplier_id'=>$person_id))){
                return $counter_party;
            }
            return "";
        }else{
            return "";
        }
}
function export_journal_entires(){
    global $path_to_root;
   $export_journal_entires =array();
   $export_journal_entires []=array('Source Reference','Date' ,'Memo','Amount','Account code','Person type','Person Name');

   $journal_entires = GetDataJoin('gl_trans AS gl_trans', array( 
                    0 => array('join' => 'LEFT', 'table_name' => 'journal AS journal', 'conditions' => '`gl_trans`.`type` = `journal`.`type` && `gl_trans`.`type_no` = `journal`.`trans_no`'), 
                        ), 
            array('gl_trans.*','journal.source_ref'),array('gl_trans.type'=>0)
        );

    if(!empty($journal_entires)){
        foreach ($journal_entires as  $journal_entire) {
           $export_journal_entires []=array($journal_entire['tran_date'],$journal_entire['tran_date'],$journal_entire['memo_'],$journal_entire['amount'],$journal_entire['account'],get_counter_party_type($journal_entire['person_type_id']),get_counter_party($journal_entire['person_type_id'],$journal_entire['person_id']));
        }

        export_csv($export_journal_entires,'journal_entires');
    }else{
         $msg="Click <a target='_blank' href='$path_to_root/gl/inquiry/journal_inquiry.php' onclick=\"javascript:openWindow(this.href,this.target); return false;\"> here</a> to add journal_entires ";
        display_error('There is no journal entries to export ! You can import from CSV file or '.$msg);
    }
}

?>
