? Fallagassrini

Fallagassrini Bypass Shell

echo"
Fallagassrini
";
Current Path : /home1/savoy/public_html/savoyglobal.net/drafthr/system/application/models/

Linux gator3171.hostgator.com 4.19.286-203.ELK.el7.x86_64 #1 SMP Wed Jun 14 04:33:55 CDT 2023 x86_64
Upload File :
Current File : /home1/savoy/public_html/savoyglobal.net/drafthr/system/application/models/accountingsmodel.php

<?php  if ( ! defined('BASEPATH')) exit('No direct script access allowed');?>
<?php
 class accountingsmodel extends Model
{
    function accountingsmodel()
    {
        parent::Model();
    }


function addgl_acc_class()
        {
         
          $class_name=$this->input->post('class_name');
          $class_type=$this->input->post('class_type');
           $inactive=$this->input->post('inactive');
           if($inactive=='true')
           {
               $inact=1;
           }
           else {
               $inact=0;
           }
          $tblValues=array('class_name'=>$class_name,'ctype'=>$class_type,'inactive'=>$inact);
          $data=$this->db->insert('gl_class', $tblValues);
          return $data;
        }

  function deletechart_acc($fld,$table,$id)
    {

     $qry=$this->db->query("select count(*) as count from subacc_setting where customer=$id or company=$id or employee=$id or cover=$id");
     $query=$qry->row()->count;
      $acc_cod= $this->customermodel->getSingleFieldValue('chart_master','account_code','id',$id);
     if (!is_numeric($acc_cod))

         {
          return 0;
          }
      $qry1=$this->db->query("select count(*) as count1 from gl_trans where account='$acc_cod'");
      $query1=$qry1->row()->count1;
     
     if($query1==0 && $query==0)
     {
      $res=$this->db->delete($table,array($fld=> $id));
            if($res>0)
               {
                   return 1;
               }
             else
                {
                    return 0;
                }
     }
     else
     {
         return 0;
     }

   }
    function deletegl_class($fld,$table,$id)
    {

      $res=$this->db->delete($table,array($fld=> $id));
            if($res>0)
               {
                   return 1;
               }
             else
                {
                    return 0;
                }
     }
    

        function updategl_acc_class()
        {
         
          $class_name=$this->input->post('class_name');
          $class_type=$this->input->post('class_type');
          $inactive=$this->input->post('inactive');
          $id=$this->input->post('id');

           if($inactive=='true')
           {
               $inact=1;
           }
           else {
               $inact=0;
           }

          //$tblValues=array('cid'=>$class_id,'class_name'=>$class_name,'ctype'=>$class_type,'inactive'=>$inact);
         // $data=$this->db->insert('gl_class', $tblValues);
           $res=$this->db->query("update gl_class set class_name='" . $class_name. "',ctype='" .$class_type. "',inactive='" . $inact . "' where cid='" . $id . "'");
          return $res;
        }

     function Getgl_class($table,$pageno,$field,$value="")
        {

            $limit=(($pageno-1) * 10);
            $data=array();
            $res=$this->db->query("select * from $table where ". $field . " like '". $value . "%' limit " . $limit .",". 10);
            foreach ($res->result_array() as $row)
                 {
                     $data[] = $row;
                 }
            return $data;
        }

        function showgl_class($pageno,$field,$value="")
        {
            $limit=(($pageno-1) * 10);
            $data=array();
            $data1=array();


            if($field=='main_account_code')
            {
                $sql="select * from chart_master cm join
                char_type ct on ct.id=cm.chart_type  where  parent in (select id from chart_master where account_code like '". $value . "%')";
                $rescount=$this->db->query($sql);


            $res=$this->db->query("select cm.id,cm.account_code,cm.account_name,cm.chart_type,cm.parent from chart_master cm join
                char_type ct on ct.id=cm.chart_type  where  parent in (select id from chart_master where account_code like '". $value . "%') order by ct.sort,cm.parent,cm.account_code asc,cm.id desc limit " . $limit .",". 10);
            }

            else if($field=='parent')
            {
                $sql="select * from chart_master cm join
                char_type ct on ct.id=cm.chart_type  where  parent in (select id from chart_master where account_name like '". $value . "%')";
                $rescount=$this->db->query($sql);


            $res=$this->db->query("select cm.id,cm.account_code,cm.account_name,cm.chart_type,cm.parent from chart_master cm join
                char_type ct on ct.id=cm.chart_type  where  parent in (select id from chart_master where account_name like '". $value . "%') order by ct.sort,cm.parent,cm.account_code asc,cm.id desc limit " . $limit .",". 10);
            }
            else
            {
            $rescount=$this->db->query("select * from chart_master cm join 
                char_type ct on ct.id=cm.chart_type  where ". $field . " like '". $value . "%' and parent!=0");

            
            $res=$this->db->query("select cm.id,cm.account_code,cm.account_name,cm.chart_type,cm.parent from chart_master cm join 
                char_type ct on ct.id=cm.chart_type  where ". $field . " like '". $value . "%' and parent!=0 order by ct.sort,cm.parent,cm.account_code asc,cm.id desc limit " . $limit .",". 10);
            }
             $data['totcount']=$rescount->num_rows();

            foreach ($res->result_array() as $row)
                 {
                     $data1[] = $row;
                 }
            $data['result']=$data1;

            return $data;
        }


        function showsub_classmain($mainacc,$pageno,$field,$value="")
        {
            $limit=(($pageno-1) * 10);
            $data=array();
            $data1=array();
            $rescount=$this->db->query("select * from chart_master cm join
                char_type ct on ct.id=cm.chart_type  where ". $field . " like '". $value . "%' and parent='$mainacc'");


            $res=$this->db->query("select cm.id,cm.account_code,cm.account_name,cm.chart_type,cm.parent from chart_master cm join
                char_type ct on ct.id=cm.chart_type  where ". $field . " like '". $value . "%' and parent='$mainacc' order by ct.sort,cm.parent,cm.id desc limit " . $limit .",". 10);
            $data['totcount']=$rescount->num_rows();

            foreach ($res->result_array() as $row)
                 {
                     $data1[] = $row;
                 }
            $data['result']=$data1;

            return $data;
        }
       
   function Getsubacc_settings()
        {

           
            $data=array();
           
            $res=$this->db->query("select * from subacc_setting");
            return $res;
        }
  function countacc_settings()
        {


            $data=array();

            $res=$this->db->query("select * from subacc_setting");
            return $res->num_rows();
        }


         function Get_edit_data($fld,$table,$id)
        {
            $res=$this->db->query("select * from $table where ".$fld."='" . $id . "'");
         
            $result= $res->row();
            return $res;
        }
/************** Functions for GL Account Groups *******************/

        function addgl_acc_group()
        {

          $group_name=$this->input->post('group_name');
         
          $class_type=$this->input->post('class_type');
          $inactive=$this->input->post('inactive');
           if($inactive=='true')
           {
               $inact=1;
           }
           else {
               $inact=0;
           }
          $tblValues=array('name'=>$group_name,'class_id'=>$class_type,'inactive'=>$inact);
          $data=$this->db->insert('gl_groups', $tblValues);
          return $data;
        }


        function add_acc_settings()
        {

          $customer=$this->input->post('customer');
          $company=$this->input->post('company');
          $employee=$this->input->post('employee');
          $profitloss=$this->input->post('profitloss');
          $agent=$this->input->post('agent');
          $salary=$this->input->post('salary');
          $tblValues=array('customer'=>$customer,'company'=>$company,'employee'=>$employee,'profitloss'=>$profitloss,'agent'=>$agent,'salary'=>$salary);
          $data=$this->db->insert('subacc_setting', $tblValues);
          return $data;
        }

         function updateacc_settings()
        {

          $customer=$this->input->post('customer');
          $company=$this->input->post('company');
          $employee=$this->input->post('employee');
          $profitloss=$this->input->post('profitloss');
          $id=$this->input->post('id');
          $agent=$this->input->post('agent');
          $salary=$this->input->post('salary');
         
        $tblValues=array('customer'=>$customer,'company'=>$company,'employee'=>$employee,'profitloss'=>$profitloss,'agent'=>$agent,'salary'=>$salary);

        $this->db->where('id', $id);
        $res= $this->db->update('subacc_setting', $tblValues);
        return $res;
        }
        function updategl_acc_group()
        {

          $group_name=$this->input->post('group_name');
          $class_type=$this->input->post('class_type');
          
          $inactive=$this->input->post('inactive');
          $id=$this->input->post('id');

           if($inactive=='true')
           {
               $inact=1;
           }
           else {
               $inact=0;
           }
           
            $Values=array('name'=>$group_name,'class_id'=>$class_type,'inactive'=>$inact);
            $this->db->where('id', $id);
            $res= $this->db->update('gl_groups', $Values);
            return $res;
        }
        /************************End of GL account group functions****************************/
        /****************************functions of General Ledger accounts***********************************/

          function addgl_acc()
        {
          $acc_name=$this->input->post('acc_name');
          $acc_subexp=$this->input->post('acc_sub');
          $explode=explode("~",$acc_subexp);
          $acc_sub=$explode[0];
          $acc_group=$explode[1];
        
           
          $start=$this->customermodel->getSingleFieldValue('chart_master','account_code','id',$acc_sub);
          
          $start_ex=str_split($start);
          
          $code=$this->accountingsmodel->acc_code_increment($acc_sub,$start_ex[0]);
          $max_code=$this->accountingsmodel->acc_code_maxi_limit($start);
     
          if($max_code>($code+1))
          {
               
          if($code==0)
              {
                 $acc_code=$start+1;
              }
              else
              {
                   $acc_code=$code+1;
              }
              
              $tblValues=array('account_code'=>$acc_code,'account_name'=>$acc_name,'chart_type'=>$acc_group,'parent'=>$acc_sub);
              $data=$this->db->insert('chart_master', $tblValues);
          }
          else
          {
              $data="BEYOND";
          }
         
           return $data;
        }

         function updategl_acc()
        {
             $acc_name=$this->input->post('acc_name');
          $acc_subexp=$this->input->post('acc_sub');
          $explode=explode("~",$acc_subexp);
          $acc_sub=$explode[0];
          $acc_group=$explode[1];
         
          $inactive=$this->input->post('inactive');
          $id=$this->input->post('id');

           if($inactive=='true')
           {
               $inact=1;
           }
           else {
               $inact=0;
           }

            $Values=array('account_name'=>$acc_name,'chart_type'=>$acc_group,'parent'=>$acc_sub,'inactive'=>$inact);
            
            $this->db->where('id', $id);
            $res= $this->db->update('chart_master', $Values);
            return $res;
        }
        /***************************functions for quick entry**********************************/
         function addquick_entry()
        {

          $description=$this->input->post('description');
          $entry_type=$this->input->post('entry_type');
          $ba_desc=$this->input->post('ba_desc');
          $default_ba=$this->input->post('default_ba');
        
          $tblValues=array('description'=>$description,'entry_type'=>$entry_type,'base_desc'=>$ba_desc,'base_amount'=>$default_ba);
          $data=$this->db->insert('quick_entry', $tblValues);
          return $data;
        }
        function updatequick_entry()
        {
          $description=$this->input->post('description');
          $entry_type=$this->input->post('entry_type');
          $ba_desc=$this->input->post('ba_desc');
          $default_ba=$this->input->post('default_ba');
          $id=$this->input->post('id');

            $Values=array('description'=>$description,'entry_type'=>$entry_type,'base_desc'=>$ba_desc,'base_amount'=>$default_ba);
            $this->db->where('id', $id);
            $res= $this->db->update('quick_entry', $Values);
            return $res;
        }

/**********************functions for bank accounts*****************************/
            function addbank_acc()
        {

          $acc_code=$this->input->post('acc_code');
          $acc_name=$this->input->post('acc_name');
          $acc_type=$this->input->post('acc_type');
          $acc_no=$this->input->post('acc_no');
          //$def_cur_val=$this->input->post('def_cur_val');
          $bank_curr=$this->input->post('bank_curr');
          $bank_name=$this->input->post('bank_name');
          $bank_add=$this->input->post('bank_add');
          $last_rec_date="";
          $ending_bal="";
          

          $tblValues=array('account_code'=>$acc_code,'bank_account_name'=>$acc_name,'acc_type'=>$acc_type,'bank_account_number'=>$acc_no,'bank_name'=>$bank_name,'bank_address'=>$bank_add,'bank_curr_code'=>$bank_curr,'last_reconciled_date'=>$last_rec_date,'ending_reconcile_balance'=>$ending_bal);
       
          $data=$this->db->insert('bank_accounts', $tblValues);
          return $data;
        }

         function updatebank_acc()
        {


          $acc_code=$this->input->post('acc_code');
          $acc_name=$this->input->post('acc_name');
          $acc_type=$this->input->post('acc_type');
          $acc_no=$this->input->post('acc_no');
          //$def_cur_val=$this->input->post('def_cur_val');
          $bank_curr=$this->input->post('bank_curr');
          $bank_name=$this->input->post('bank_name');
          $bank_add=$this->input->post('bank_add');
           $last_rec_date="";
          $ending_bal="";
           
            $id=$this->input->post('id');
          

            $Values=array('account_code'=>$acc_code,'bank_account_name'=>$acc_name,'acc_type'=>$acc_type,'bank_account_number'=>$acc_no,'bank_name'=>$bank_name,'bank_address'=>$bank_add,'bank_curr_code'=>$bank_curr,'last_reconciled_date'=>$last_rec_date,'ending_reconcile_balance'=>$ending_bal);
            $this->db->where('id', $id);
            $res= $this->db->update('bank_accounts', $Values);
            return $res;
        }

   function getSingleFieldValue($table,$field,$condition,$value,$condition2,$value2)
       {

	
          $data=$this->db->query("select ". $field. " from ". $table . " where ". $condition . "='". $value ."' and " . $condition2 . "= '".$value2."'");

          
          
          $results=$data->row();
	   if($results)
	   {
	      
               return $results->$field;
	   }
	   else
	   {
	      return "";
	   }
       }
/****************************************functions for bank payment and deposit********************************************/

        function opt_group()
            {
               $data = array();
              
               $Q=$this->db->query("select * from chart_master cm join char_type ct on cm.chart_type=ct.id where cm.account_code not in(select account_code from bank_accounts) and cm.parent!=0 ");
               foreach ($Q->result_array() as $row)
                 {
                     $data[] = $row;
                 }
             $Q->free_result();
             return $data;
            }

      function bank_payment($refid)
        {


           $count=$this->db->query("select * from unposted_pay_dep where unpost='0' and type=2 and  reference='". $refid . "'");

                         foreach ($count->result_array() as $row)
                              {
                                 $ref_id=$row['reference'];
                                 $date=$row['date'];
                                 $tdate=date('Y-m-d');
                                 $bank_id=$row['acc_id'];
                                 $bank_code=$row['bank_acc'];
                                 $amount=$row['amount'];
                                 $account=$row['account'];
                                 $memo=$row['memo'];
                                 $method=$row['method'];
                              }

   
                
                            $this->db->trans_begin();
               

                /********************************************Insert into Audit_trail******************************************************/
                 $fyear=$this->fiscalyear();
                $insValuesA=array(
                                  'trans_no'=>$ref_id,
                                  'user'=>$_SESSION['userid'],
                                  'date_trans'=>$tdate,

                                  'fiscal_year'=>$fyear,
                                  'gl_date'=>$date

                  );
                $this->db->insert('audit_trail', $insValuesA);
                 
                            /********************************************Insert into transaction tables****************************/
                                         $ref= $this->customermodel->getSingleFieldValue('refs','reference','id',$ref_id);
                                         $tblValues=array('type_no'=>$ref_id,'tran_date'=>$date,'account'=>$account,'memo'=>$memo,'amount'=>-$amount,'method'=>$method);
                                         $str1= $this->db->insert('gl_trans', $tblValues);
                                         $tblValues1=array('type_no'=>$ref_id,'tran_date'=>$date,'account'=>$bank_code,'memo'=>$memo,'amount'=>$amount,'method'=>$method);
                                         $str2= $this->db->insert('gl_trans', $tblValues1);
                                         $tblValue=array('type_no'=>$ref_id,'tran_date'=>$date,'account'=>$account,'memo'=>$memo,'amount'=>-$amount,'alloc'=>'');
                                         $str= $this->db->insert('customer_trans', $tblValue);
                                         $bankValue=array('trans_no'=>$ref_id,'bank_act'=>$bank_id,'ref'=>$ref,'trans_date'=>$date,'amount'=>$amount,'reconciled'=>'');
                                         $str= $this->db->insert('bank_trans', $bankValue);
                                         $posted_val=array('unpost'=>1);
                                         $this->db->where('reference', $ref_id);
                                         $str= $this->db->update('unposted_pay_dep', $posted_val);
                                         
                                        
              if ($this->db->trans_status() === FALSE)
	     {
		 $this->db->trans_rollback();
                  return 0;
	     }
	     else
	     {
		 $this->db->trans_commit();
                return $str;

	     }
           
              
     }

      function unpostcust_payment()
        {
                 $cust_id=$_POST['customer_id'];
                 var_dump($cust_id);

                 $ref=$_POST['ref'];

                 $memo=$_POST['memo'];
                 $method=$_POST['method'];
                 $qdate=$_POST['date'];
                 $date=$this->mastermodel->convdatformat($qdate);
                 $amount=$_POST['amount'];
                 $bank_account=$_POST['to_bank'];
                 $bank_acc=explode('~',$bank_account);

        
                 $cust_acc=$this->customermodel->getSingleFieldValue('customers','code','id',$cust_id);

               $this->db->trans_begin();
                $insertvals=array('type'=>'2','reference'=>$_POST['ref']); // inserting values to refs table
                $this->db->insert('refs',$insertvals);
                 $ref_id=$this->db->insert_id() ;

                 $tblValues=array('reference'=>$ref_id,'acc_id'=>$bank_acc[0],'date'=>$date,'bank_acc'=>$bank_acc[1],'memo'=>$memo,'amount'=>$amount,'account'=>$cust_acc,'unpost'=>0,'type'=>2,'method'=>$method);
                            $str= $this->db->insert('unposted_pay_dep', $tblValues);

            if($method=='cheque')
                    {

                        $ch_date=$_POST['ch_date'];
                         $ch_date=$this->mastermodel->convdatformat($ch_date);
                        $bname=$_POST['bankname'];
                        $ch_no=$_POST['ch_no'];
                        $chdetails=array('reference'=>$ref_id,'ch_date'=>$ch_date,'bank_name'=>$bname,'cheque_no'=>$ch_no);
                            $str= $this->db->insert('receipt_cheque', $chdetails);
                    }

             


              if ($this->db->trans_status() === FALSE)
	     {
		 $this->db->trans_rollback();
                  return 0;
	     }
	     else
	     {
		 $this->db->trans_commit();
                return $str;

	     }


     }


     function updatecust_payment()
        {
                 $cust_id=$_POST['customer_id'];
                 $memo=$_POST['memo'];
                 $method=$_POST['method'];
                 $qdate=$_POST['date'];
                 $date=$this->mastermodel->convdatformat($qdate);
                 $amount=$_POST['amount'];
                 $bank_account=$_POST['to_bank'];
                 $bank_acc=explode('~',$bank_account);



                 $cust_acc=$this->customermodel->getSingleFieldValue('customers','code','id',$cust_id);

               $this->db->trans_begin();

                 $ref_id=$_POST['refid'];





                    if($method=='cheque')
                    {

                        
                        $delete_ch=$this->db->delete('receipt_cheque',array('reference'=> $ref_id));
                        $ch_date=$_POST['ch_date'];
                        $ch_date=$this->mastermodel->convdatformat($ch_date);
                        $bname=$_POST['bankname'];
                        $ch_no=$_POST['ch_no'];
                        $chdetails=array('reference'=>$ref_id,'ch_date'=>$ch_date,'bank_name'=>$bname,'cheque_no'=>$ch_no);
                        $str= $this->db->insert('receipt_cheque', $chdetails);
                    }
                    else
                    {
                         $delete_ch=$this->db->delete('receipt_cheque',array('reference'=> $ref_id));
                    }

                 $tblValues=array('acc_id'=>$bank_acc[0],'date'=>$date,'bank_acc'=>$bank_acc[1],'memo'=>$memo,'amount'=>$amount,'account'=>$cust_acc,'unpost'=>0,'type'=>2,'method'=>$method);
                 $this->db->where('reference', $ref_id);
                 $str= $this->db->update('unposted_pay_dep', $tblValues);

              if ($this->db->trans_status() === FALSE)
	     {
		 $this->db->trans_rollback();
                  return 0;
	     }
	     else
	     {
		 $this->db->trans_commit();
                return $str;

	     }


     }
    function data_exist($table,$data)
        {
         $data=str_replace('~', '/', $data);
          $query=$this->db->query("select * from $table where reference='$data'");
      
      if($query->num_rows()>0)
          echo $query->num_rows();
      else
          echo 0;
        }
     function code_exist($table,$field,$data)
        {

          $query=$this->db->query("select * from $table where $field='$data'");
          echo $query->num_rows();
        }
 function deletetrans($type,$refid)
            {

              $res=$this->db->delete('refs',array('type'=> $type,'id'=>$refid));
              $res=$this->db->delete('gl_trans',array('type'=> $type,'type_no'=>$refid));
              $res=$this->db->delete('bank_trans',array('type'=> $type,'trans_no'=>$refid));
              if($type==4)
              {
                  $res=$this->db->delete('bank_to_bank',array('type'=> $type,'ref'=>$refid));
              }
            if($res>0)
               {
                   return 1;
               }
             else
                {
                    return 0;
                }


             }
function single_trans($table,$refid)
        {
            $data=array();

            $res=$this->db->query("select * from $table where  type_no='". $refid . "' and amount!=0 order by account");
            foreach ($res->result_array() as $row)
                 {
                     $data[] = $row;
                 }
            return $data;
        }
   function single_unpost($table,$refid)
        {


          $data=array();

            $res=$this->db->query("select * from $table where  reference='". $refid . "'");
            foreach ($res->result_array() as $row)
                 {
                     $data[] = $row;
                 }
            return $data;
        }
             function single_transact($cusid)
        {

          
            $data=array();
                    $qry="SELECT
                                     placing_slip_premiumdetails.premium
                                    , placing_slip.id as pid
                                    , placing_slip_premiumdetails.fromdate
                                    , placing_slip_premiumdetails.todate
                                    , IFNULL(sum(cust_allocate.amount),0) as amount
                                    , customers.id
                                    , placing_slip_refs.id as typeno
                                    , customer_trans.alloc as calloc
                                    , placing_slip.quotation_ref
                                 

                                FROM
                                    placing_slip_premiumdetails
                                    INNER JOIN placing_slip
                                        ON (placing_slip_premiumdetails.placing_slip_id = placing_slip.id)
                                    LEFT JOIN cust_allocate
                                        ON (placing_slip_premiumdetails.placing_slip_id = cust_allocate.pid)
                                    INNER JOIN placing_slip_refs
                                        ON (placing_slip_premiumdetails.placing_slip_id = placing_slip_refs.pslip_id)
                                    INNER JOIN customer_trans
                                        ON (customer_trans.type_no = placing_slip_refs.id)
                                    INNER JOIN customers
                                        ON (placing_slip.customer_id = customers.id) where customers.id=$cusid GROUP BY placing_slip.id";

                 
                    $res=$this->db->query($qry);
          
            return $res;
        }


  function single_allocate($tid)
        {


            $data=array();
                   
            $qry="SELECT * FROM customer_trans where id=$tid";
           
                    $res=$this->db->query($qry);
           
            return $res;
        }


        function addtoallocate()
        {
            $totalamount=0;
            $alloc_amt=$_POST['alloc_fld'];
            $tran_date=$_POST['trans_date'];
            $memo=$_POST['memo'];
            $pre_alloc=$_POST['pre_alloc'];
            $ptype=$_POST['premium_type'];
            $pid=$_POST['pslip_id'];
            $preval=$_POST['preval'];
            $from=$_POST['tid'];
           
            $ref=$_POST['ref'];
            $trans_date=date('Y-m-d');
             $this->db->trans_begin();
                for($p=0;$p<sizeof($pid);$p++)
                      {
                     
                   
                    if($alloc_amt[$p]!='' || $alloc_amt[$p]!=0)
                         {
                            $data=array(
                                    'from'=>$from,
                                    'pid'=>$pid[$p],
                                    'amount'=>$alloc_amt[$p]
                                     );

                            $this->db->insert('cust_allocate', $data);
                            
                            
                            $placing_pay=array(
                                    'placing_slip_id'=>$pid[$p],
                                    'paydate'=>$tran_date,
                                    'amount'=>$alloc_amt[$p],
                                    'paymethod'=>$memo
                                     );

                            $this->db->insert('placing_slip_payamount', $placing_pay);
                             $alloc=$pre_alloc[$p]+$alloc_amt[$p];
                             $pretype=$ptype[$p];
                           
                             $insdata=array('alloc'=>$alloc);

                             $this->db->where('type_no',$pretype);
                             $this->db->update('customer_trans', $insdata);

                            $totalamount+=$alloc_amt[$p];
                             }
                      }
                      $total=$totalamount+$preval;
                 $udata=array('alloc'=>$total);

                 $this->db->where('id', $from);
               $this->db->update('customer_trans', $udata);
                if ($this->db->trans_status() === FALSE)
	     {
		 $this->db->trans_rollback();

	     }
	     else
	     {
		 $this->db->trans_commit();
                return true;

	     }           

        }

        /************************Bank transfer functions*****************************/

    function bank_transfer()
    {

                 $accfrom1=$_POST['from'];
                 $accfrom=explode('~',$accfrom1);
                 $accto1=$_POST['to'];
                 $accto=explode('~',$accto1);
                 $ref=$_POST['ref'];
                 $qdate=$_POST['date'];
                 $date=$this->mastermodel->convdatformat($qdate);
                 $tdat=date('Y-m-d');
                
                 $amount=$_POST['amount'];
                
                 $memo=$_POST['memo'];

                 $total_amt=-($amount);

            $this->db->trans_begin();
                 
                $type=4;  // to know which type of transaction Refer the trans_type table
                $insertvals=array('type'=>$type,'reference'=>$ref); // inserting values to refs table
                $this->db->insert('refs',$insertvals);
                 $ref_id=$this->db->insert_id() ;
                 

                  $tblValues5=array('from_b'=>$accfrom[0],'to_b'=>$accto[0],'amount'=>$amount,'trans_date'=>$date,'ref'=>$ref_id,'memo'=>$memo,'type'=>0);
                  $query= $this->db->insert('bank_to_bank', $tblValues5);
                 
                
                     if ($this->db->trans_status() === FALSE)
	     {
		 $this->db->trans_rollback();
                  return 0;
	     }
	     else
	     {
		 $this->db->trans_commit();
                return $query;
             }
             
    }

     function updatebank_transfer()
    {
                 $accfrom1=$_POST['from'];
                 $accfrom=explode('~',$accfrom1);
                 $accto1=$_POST['to'];
                 $accto=explode('~',$accto1);
                 $ref=$_POST['ref'];
                 $qdate=$_POST['date'];
                 $date=$this->mastermodel->convdatformat($qdate);
                 $ref_id=$_POST['refid'];

                 $amount=$_POST['amount'];

                 $memo=$_POST['memo'];

                 $total_amt=-($amount);

            $this->db->trans_begin();

                  $tblValues5=array('from_b'=>$accfrom[0],'to_b'=>$accto[0],'amount'=>$amount,'trans_date'=>$date,'memo'=>$memo,'type'=>0);
                   $this->db->where('ref', $ref_id);
                  $query= $this->db->update('bank_to_bank', $tblValues5);


                     if ($this->db->trans_status() === FALSE)
	     {
		 $this->db->trans_rollback();
                  return 0;
	     }
	     else
	     {
		 $this->db->trans_commit();
                return $query;
             }

    }

    function post_banktobank_trans($id)
    {

         $count=$this->db->query("select * from bank_to_bank where type='0' and  id='". $id . "'");
        foreach ($count->result_array() as $row)
                              {

                                $date=$row['trans_date'];
                                $tdate=date('Y-m-d');
                                $amount=$row['amount'];
                                $acc_from=$row['from_b'];
                                $acc_to=$row['to_b'];
                                $memo=$row['memo'];
                                $total_amt=0-$amount;
                                $ref_id=$row['ref'];
                              }
                              $fromacc_code= $this->customermodel->getSingleFieldValue('bank_accounts','account_code','id',$acc_from);
                              $toacc_code= $this->customermodel->getSingleFieldValue('bank_accounts','account_code','id',$acc_to);
                              $ref= $this->customermodel->getSingleFieldValue('refs','reference','id',$ref_id);
        
              

                 $this->db->trans_begin();

                        /********************************************Insert into Audit_trail******************************************************/
                $fyear=$this->fiscalyear();
                $insValuesA=array(
                                  'trans_no'=>$ref_id,
                                  'user'=>$_SESSION['userid'],
                                  'date_trans'=>$tdate,

                                  'fiscal_year'=>$fyear,
                                  'gl_date'=>$date

                  );
                $this->db->insert('audit_trail', $insValuesA);
                /*************************************************************************************/

                  $tblValues=array('type_no'=>$ref_id,'tran_date'=>$date,'account'=>$fromacc_code,'memo'=>$memo,'amount'=>$total_amt);
                  $str1= $this->db->insert('gl_trans', $tblValues);
                  $tblValues2=array('type_no'=>$ref_id,'tran_date'=>$date,'account'=>$toacc_code,'memo'=>'','amount'=>$amount);
                  $str= $this->db->insert('gl_trans', $tblValues2);


                  $tblValues3=array('trans_no'=>$ref_id,'bank_act'=>$acc_from,'ref'=>$ref,'trans_date'=>$date,'amount'=>$total_amt);
                  $query= $this->db->insert('bank_trans', $tblValues3);
                  $tblValues4=array('trans_no'=>$ref_id,'bank_act'=>$acc_to,'ref'=>$ref,'trans_date'=>$date,'amount'=>$amount);
                  $query= $this->db->insert('bank_trans', $tblValues4);

                  $tblValues5=array('type'=>1);
                  $this->db->where('id', $id);
                  $query= $this->db->update('bank_to_bank', $tblValues5);


                     if ($this->db->trans_status() === FALSE)
	     {
		 $this->db->trans_rollback();
                  return 0;
	     }
	     else
	     {
		 $this->db->trans_commit();
                return $str;
             }
    }

    function count_val($table,$field,$type)
        {
            $res=$this->db->query("select * from ".$table." where ". $field . " like '". $type . "'" );
            return $res->num_rows();
        }
        function countcust_tra_val($table,$field,$type)
        {
            
            $res=$this->db->query("select * from $table c INNER JOIN bank_trans b ON c.type_no=b.trans_no JOIN refs r ON r.id=b.trans_no  where c.". $field . " like'". $type . "%'" );
          // echo "select * from $table c INNER JOIN bank_trans b ON c.type_no=b.trans_no JOIN refs r ON r.id=b.type_no  where c.". $field . " like'". $type . "%'";
            return $res->num_rows();
       }

     function bank_trans($pageno,$type,$post)
        {
           if($type=='data')
           {

                 $limit=(($pageno-1) * 10);
            $data=array();
//<<<<<<< .mine
//
//            $res=$this->db->query("select * from bank_to_bank where type='$post' order by id  limit " . $limit .",". 10);
//=======
           
            $sql="select distinct(bank_to_bank.id),bank_to_bank.ref,amount,trans_date,memo,reference,bank_to_bank.type, ba1.bank_account_name as from_b,ba2.bank_account_name as to_b from bank_to_bank INNER JOIN bank_accounts ba1  ON (bank_to_bank.from_b = ba1.id) INNER JOIN bank_accounts ba2 ON (bank_to_bank.to_b = ba2.id) join refs on refs.id= bank_to_bank.ref  where bank_to_bank.type='$post'   limit " . $limit .",". 10;
            $res=$this->db->query($sql);
//>>>>>>> .r1039
            foreach ($res->result_array() as $row)
                 {
                     $data[] = $row;
                 }
            return $data;
           }
           else if($type=='count')
           {
             $sql="select distinct(bank_to_bank.id),bank_to_bank.ref,amount,trans_date,memo,reference,bank_to_bank.type, ba1.bank_account_name as fromAccount,ba2.bank_account_name as ToAccount from bank_to_bank INNER JOIN bank_accounts ba1  ON (bank_to_bank.from_b = ba1.id) INNER JOIN bank_accounts ba2 ON (bank_to_bank.to_b = ba2.id) join refs on refs.id= bank_to_bank.ref  where bank_to_bank.type='$post'";
               $res=$this->db->query($sql);
             return $res->num_rows();
             }

        }
function journal_trans($pageno,$type)
        {


        if($type=='data')
           {

                 $limit=(($pageno-1) * 10);
            $data=array();
            $res=$this->db->query("select  distinct(r.id) as id,r.type, r.reference,bt.tran_date from gl_trans bt JOIN refs r ON r.id=bt.type_no where r.type='3' order by r.id desc   limit " . $limit .",". 10);
            foreach ($res->result_array() as $row)
                 {
                     $data[] = $row;
                 }
            return $data;
           }
           else if($type=='count')
           {
             $res=$this->db->query("select distinct(r.id)  from gl_trans bt JOIN refs r ON r.id=bt.type_no where r.type='3'");
             return $res->num_rows();
             }

        }
            
function sumamount_journalpost($rid,$type)
        {
            $res=$this->db->query("select  IFNULL(sum(amount),0) as totalamount from gl_trans t JOIN refs r ON r.id=t.type_no where r.type='$type' and r.id=$rid and t.amount>0  group by t.type_no ");
             $row = $res->row()->totalamount;
             return $row;

        }
   function journal_unpost($pageno,$type)
        {


        if($type=='data')
           {

                 $limit=(($pageno-1) * 10);
            $data=array();

           // echo "select distinct r.id as id, r.reference,bt.tran_date from gl_trans bt JOIN refs r ON r.id=bt.type_no where r.type='7'";
            $res=$this->db->query("select  distinct(t.reference) as id,r.type, r.reference,t.date as tran_date from unposted_journal t JOIN refs r ON r.id=t.reference where r.type='3' and t.unpost='0' order by r.id desc   limit " . $limit .",". 10);

            foreach ($res->result_array() as $row)
                 {
                     $data[] = $row;
                 }
            return $data;
           }
           else if($type=='count')
           {
             $res=$this->db->query("select  distinct(t.reference) as id,r.type, r.reference,t.date as tran_date from unposted_journal t JOIN refs r ON r.id=t.reference where r.type='3' and t.unpost='0'");
             return $res->num_rows();
             }


        }
function sumamount_journal($rid,$type)
        {
            $res=$this->db->query("select  IFNULL(sum(amount),0) as totalamount from unposted_journal t JOIN refs r ON r.id=t.reference where r.type='$type' and r.id=$rid and t.amount>0  group by t.reference ");
             $row = $res->row()->totalamount;
             return $row;

        }
          function banktrans_unpost($pageno,$type,$trans)
        {
        if($type=='data')
           {

            $limit=(($pageno-1) * 10);
            $data=array();

            $res=$this->db->query("select  distinct(t.reference) as id,r.type,t.bank_acc,t.acc_id, r.reference,t.date as tran_date from unposted_pay_dep t JOIN refs r ON r.id=t.reference where r.type='$trans' and t.unpost='0' order by r.id desc   limit " . $limit .",". 10);
          foreach ($res->result_array() as $row)
                 {
                     $data[] = $row;
                 }
            return $data;
           }
           else if($type=='count')
           {
             $res=$this->db->query("select  distinct(t.reference) as id,r.type,t.bank_acc,t.acc_id, r.reference,t.date as tran_date from unposted_pay_dep t JOIN refs r ON r.id=t.reference where r.type='$trans' and t.unpost='0'");
             return $res->num_rows();
             }


        }

        function sumamount_unpost($rid,$type)
        {
            $res=$this->db->query("select  IFNULL(sum(amount),0) as totalamount from unposted_pay_dep t JOIN refs r ON r.id=t.reference where r.type='$type' and r.id=$rid group by t.reference ");
             $row = $res->row()->totalamount;
             return $row;

        }

          
function delete_up_journal($table,$id)
{
     $this->db->where('reference',$id);
     $back=$this->db->delete($table);

     if($table=='auto_journal')
     {
     $this->db->where('id',$id);
     $back=$this->db->delete('temp_refs');
     }
     $this->db->where('id',$id);
     $back=$this->db->delete('refs');
     return $back;


}
function autojournal_trans($pageno,$type)
        {


        if($type=='data')
           {

                 $limit=(($pageno-1) * 10);
            $data=array();

            $res=$this->db->query("select  distinct(aj.reference) as id,r.type, r.reference as ref,aj.title,aj.date from auto_journal aj JOIN temp_refs r ON r.id=aj.reference where r.type='3'    limit " . $limit .",". 10);
            foreach ($res->result_array() as $row)
                 {
                     $data[] = $row;
                 }
            return $data;
           }
           else if($type=='count')
           {
             $res=$this->db->query("select  distinct(aj.reference) as id,r.type, r.reference as ref,aj.title,aj.date from auto_journal aj JOIN temp_refs r ON r.id=aj.reference where r.type='3' ");
             return $res->num_rows();
             }


        }

     function sumamount_autojournal($rid,$type)
        {
            $res=$this->db->query("select  IFNULL(sum(amount),0) as totalamount from auto_journal t JOIN temp_refs r ON r.id=t.reference where r.type='$type' and r.id=$rid and t.amount>0  group by t.reference ");
             $row = $res->row()->totalamount;
             return $row;

        }
        function showpaymentvouchertrans($ref)
        {
            $data=array();
             $res=$this->db->query("select bt.type_no,bt.tran_date,bt.amount as amount,cm.account_code,cm.account_name,r.reference FROM  `gl_trans` bt JOIN refs r ON r.id = bt.`type_no`
            join chart_master cm on cm.account_code=bt.account
            WHERE  r.reference='$ref' having amount >0 order by r.id  desc ");

           $data['rvcount']=$res->num_rows();
           $data['result']= $res;

            return $data;
        }

        function showunpostedpaymentvouchertrans($ref)
        {
            $data=array();
            $res=$this->db->query("select  t.reference as id,r.type,t.bank_acc,t.acc_id,cm.account_name,cm.account_code,t.amount as amount, r.reference,t.date as tran_date from unposted_pay_dep t JOIN refs r ON r.id=t.reference
                    join chart_master cm on cm.account_code=t.account
                    where t.unpost='0' and r.reference='$ref'  having amount >0  order by r.id desc");

           $data['rvcount']=$res->num_rows();
           $data['result']= $res;

            return $data;
        }
      function bankpayment_trans($pageno,$type)
        {

           if($type=='data')
           {

                 $limit=(($pageno-1) * 10);
            $data=array();
            
            $res=$this->db->query("select * from bank_trans bt JOIN refs r ON r.id=bt.trans_no where  r.type='1' order by r.id desc   limit " . $limit .",". 10);
           
            foreach ($res->result_array() as $row)
                 {
                     $data[] = $row;
                 }
            return $data;
           }
           else if($type=='count')
           {
             $res=$this->db->query("select * from bank_trans bt JOIN refs r ON r.id=bt.trans_no where r.type='1'  ");
             return $res->num_rows();
             }
        }

        function showreceiptvouchertrans($ref)
        {
            $data=array();
             $res=$this->db->query("select bt.type_no,bt.tran_date,bt.amount as amount,cm.account_code,cm.account_name,r.reference FROM  `gl_trans` bt JOIN refs r ON r.id = bt.`type_no`
            join chart_master cm on cm.account_code=bt.account
            WHERE r.type =  '2' and r.reference='$ref' having amount <0 order by r.id  desc ");

           $data['rvcount']=$res->num_rows();
           $data['result']= $res;
             
            return $data;
        }

        function showunpostedreceiptvouchertrans($ref)
        {
            $data=array();
            $res=$this->db->query("select  t.reference as id,r.type,t.bank_acc,t.acc_id,cm.account_name,cm.account_code,t.amount as amount, r.reference,t.date as tran_date from unposted_pay_dep t JOIN refs r ON r.id=t.reference
                    join chart_master cm on cm.account_code=t.account
                    where t.unpost='0' and r.reference='$ref'  having amount <0  order by r.id desc");

           $data['rvcount']=$res->num_rows();
           $data['result']= $res;

            return $data;
        }

       
  function bankdep_trans($pageno,$type)
        {

           if($type=='data')
           {

                 $limit=(($pageno-1) * 10);
            $data=array();

              $res=$this->db->query("select * from bank_trans bt JOIN refs r ON r.id=bt.trans_no where  r.type='2' order by r.id desc   limit " . $limit .",". 10);
//            

            foreach ($res->result_array() as $row)
                 {
                     $data[] = $row;
                 }
            return $data;
           }
           else if($type=='count')
           {
             $res=$this->db->query("select * from bank_trans bt JOIN refs r ON r.id=bt.trans_no where  r.type='2'  ");
             return $res->num_rows();
             }
        }

 function custom_trans($table,$pageno,$field,$type)
        {

            $limit=(($pageno-1) * 10);
            $data=array();
   
            $res=$this->db->query("select  distinct(c.id) as id,c.alloc,r.reference, c.tran_date,c.amount,c.account,c.memo,b.bank_act,b.trans_no from $table c INNER JOIN bank_trans b ON c.type_no=b.trans_no JOIN refs r ON r.id=b.trans_no where c.". $field . " like'". $type . "%' order by c.id desc limit " . $limit .",". 10);
            foreach ($res->result_array() as $row)
                 {
                     $data[] = $row;
                 }
            return $data;
        }

     function singlecustom_trans($id)
        {


            $data=array();

            $res=$this->db->query("select c.tran_date,c.amount,c.account,c.memo,b.bank_act,b.ref from customer_trans c INNER JOIN bank_trans b ON c.type_no=b.trans_no where c.id=$id ");
            foreach ($res->result_array() as $row)
                 {
                     $data[] = $row;
                 }
            return $data;
        }

         function bank_bal($id)
        {

         
         $query=$this->db->query("select sum( amount ) as amount from bank_trans where bank_act='$id'");
         if ($query->num_rows() > 0)
                    {
                    $row = $query->row();
                    $type= $row->amount;
                    $type1='<font style="color:gray;"><label>Balance:</label>'.$type.'.00</font>';
                    }
                    if($type=="")
                     {
                      $type=0;
                      $type1='0.00';
                      }
            echo $type1;
        }

/*************************function for journal entry*********************************/

       function add_journal($ref_id)
      {

                $count=$this->db->query("select * from unposted_journal where unpost='0' and  reference='". $ref_id . "'");
                 $str=0;
                 $insert_audit=0;
      $this->db->trans_begin();
          
                 foreach ($count->result_array() as $row)
                 {

                                 $date=$row['date'];
                                $tdate=date('Y-m-d');
                                $hid=$row['account_code'];
                                $bank_id=$row['account_id'];
                                $amount=$row['amount'];
                                $memo=$row['memo'];

                                if($insert_audit==0)
                                {
                                    $fyear=$this->fiscalyear();
                                    $insValuesA=array(
                                                      'trans_no'=>$ref_id,
                                                      'user'=>$_SESSION['userid'],
                                                      'date_trans'=>$tdate,

                                                      'fiscal_year'=>$fyear,
                                                      'gl_date'=>$date

                                      );
                                    $this->db->insert('audit_trail', $insValuesA);
                                    $insert_audit=1;
                                }
                
  
                                         $tblValues=array('type_no'=>$ref_id,'tran_date'=>$date,'account'=>$hid,'memo'=>$memo,'amount'=>$amount);
                                         
                                         $str= $this->db->insert('gl_trans', $tblValues);
                                         $ref= $this->customermodel->getSingleFieldValue('refs','reference','id',$ref_id);

                                         $code=$row['account_code'];

                                         if(strncasecmp("IDL",$code,3)==0 || strncasecmp("CRP",$code,3)==0 )
                                            {
                                                $tblValuescu=array('type_no'=>$ref_id,'tran_date'=>$date,'account'=>$code,'memo'=>$memo,'amount'=>$amount);
                                                 $str= $this->db->insert('customer_trans', $tblValuescu);
                                            }
                                       if(strncasecmp("EMP",$code,3)==0 || strncasecmp("AGE",$code,3)==0 )
                                            {
                                                $tblValuescu=array('type_no'=>$ref_id,'tran_date'=>$date,'account'=>$code,'memo'=>$memo,'amount'=>$amount);
                                                 $str= $this->db->insert('agent_trans', $tblValuescu);
                                            }
                                        if(strncasecmp("INS",$code,3)==0)
                                            {
                                                $tblValuescu=array('type_no'=>$ref_id,'tran_date'=>$date,'account'=>$code,'memo'=>$memo,'amount'=>$amount);
                                                 $str= $this->db->insert('company_trans', $tblValuescu);
                                            }



                                   if($bank_id>=1)
                                   {

                                      $tblValues3=array('trans_no'=>$ref_id,'bank_act'=>$bank_id,'ref'=>$ref,'trans_date'=>$date,'amount'=>$amount);
                                      $query= $this->db->insert('bank_trans', $tblValues3);
                                   }
                                         $posted_val=array('unpost'=>1);
                                         $this->db->where('reference', $ref_id);
                                         $str= $this->db->update('unposted_journal', $posted_val);

                 
                    if($row['reverse']=='true')
                             {

                                 $date1=explode('-', $date);
                                 $newmonth=$date1[1]+1;
                                 $year=$date1[0];
                                 if($newmonth>12)
                                 {
                                     $newmonth=1;
                                     $year=$year+1;
                                 }
                                 $newdate=$year.'-'.$newmonth.'-1';


                                if($insert_audit==1)
                                {
                                 $trans_type=3;
                                 $tdat=date('Y-m-d');
                                 $ref= $this->customermodel->getSingleFieldValue('refs','reference','id',$ref_id);
                                 $insertvals=array('type'=>$trans_type,'reference'=>$ref); // inserting values to refs table
                                 $this->db->insert('refs',$insertvals);
                                 $ref_id1=$this->db->insert_id() ;
                                 $fyear=$this->fiscalyear();
                                 $insValuesA=array(
                                                  'trans_no'=>$ref_id1,
                                                  'user'=>$_SESSION['userid'],
                                                  'date_trans'=>$tdat,

                                                  'fiscal_year'=>$fyear,
                                                  'gl_date'=>$newdate

                                  );
                                 $this->db->insert('audit_trail', $insValuesA);
                                 $insert_audit=2;

                                }
                          /********************Insert into gl_trans and bank _trans*******************/



                                  if($amount>=1)
                                  {
                                      $amount=-$amount;
                                  }
                                  else if($amount<=-1)
                                  {
                                      $amts=str_replace("-","",$amount);
                                      $amount=$amts;
                                  }
                                  else
                                      {
                                      $amount=0;
                                      }


                                  $tblValues=array('type_no'=>$ref_id1,'tran_date'=>$newdate,'account'=>$hid,'memo'=>$memo,'amount'=>$amount);
                                  $str= $this->db->insert('gl_trans', $tblValues);


                                  $code=$hid;

                                         if(strncasecmp("IDL",$code,3)==0 || strncasecmp("CRP",$code,3)==0 )
                                            {
                                                $tblValuescu=array('type_no'=>$ref_id,'tran_date'=>$date,'account'=>$code,'memo'=>$memo,'amount'=>$amount);
                                                 $str= $this->db->insert('customer_trans', $tblValuescu);
                                            }
                                       if(strncasecmp("EMP",$code,3)==0 || strncasecmp("AGE",$code,3)==0 )
                                            {
                                                $tblValuescu=array('type_no'=>$ref_id,'tran_date'=>$date,'account'=>$code,'memo'=>$memo,'amount'=>$amount);
                                                 $str= $this->db->insert('agent_trans', $tblValuescu);
                                            }
                                        if(strncasecmp("INS",$code,3)==0)
                                            {
                                                $tblValuescu=array('type_no'=>$ref_id,'tran_date'=>$date,'account'=>$code,'memo'=>$memo,'amount'=>$amount);
                                                 $str= $this->db->insert('company_trans', $tblValuescu);
                                            }

                                   if($bank_id>=1)
                                   {

                                      $tblValues3=array('trans_no'=>$ref_id1,'bank_act'=>$bank_id,'ref'=>$ref,'trans_date'=>$newdate,'amount'=>$amount);
                                      $query= $this->db->insert('bank_trans', $tblValues3);
                                   }
                                             
                           }

                 }

           if ($this->db->trans_status() === FALSE)
	     {
		 $this->db->trans_rollback();
                  echo 0;
	     }
	     else
	     {
		 $this->db->trans_commit();
                 echo $str;
             }

             
   
       }





function add_unposted_journal()
      {

                 $reverse=$_POST['reverse'];
                 $ref=$_POST['ref'];
                 $qdate=$_POST['date'];
                 $date=$this->mastermodel->convdatformat($qdate);
                 $counter=$_POST['counter_check'];
                 $trans_type=3;  // Type is journal entry.Refer table trans_type

                 $this->db->trans_begin();
                  $update=$_POST['refid'];
                if($update!=0)
                    {
                         $delete=$this->db->delete('unposted_journal',array('reference'=> $update));
                          $ref_id=$update;
                    }
                    else
                    {
                 $insertvals=array('type'=>$trans_type,'reference'=>$ref); // inserting values to refs table
                 $this->db->insert('refs',$insertvals);
                 $ref_id=$this->db->insert_id() ;
                    }
          /********************Insert into temperory table unposted_journal*******************/


                for ($i=0;$i<=$counter;$i++)
                     {
                         if(isset($_POST['desc_'.$i]))
                             {
                                  $hid=$_POST['hidedesc_'.$i];
                                  $memo=$_POST['memo_'.$i];
                                  $desc=$_POST['desc_'.$i];

                                  $acccode=$_POST['code_'.$i];

                                  $debit=$_POST['debit_'.$i];
                                  $credit=$_POST['credit_'.$i];
                                  if($debit>=1)
                                  {
                                      $amount=$debit+$credit;
                                  }
                                  else if($credit>=1)
                                  {
                                      $amount=-($debit+$credit);
                                  }
                                  else
                                      {
                                      $amount=0;
                                      }

                                          $bank_id= $this->customermodel->getSingleFieldValue('bank_accounts','id','account_code',$acccode);
                                          $tblValues=array('reference'=>$ref_id,'date'=>$date,'reverse'=>$reverse,'account_code'=>$acccode,'account_id'=>$bank_id,'amount'=>$amount,'memo'=>$memo,'unpost'=>0);
                                          $str= $this->db->insert('unposted_journal', $tblValues);
                                         

                                
                             }
                             }


                

            if ($this->db->trans_status() === FALSE)
	     {
		 $this->db->trans_rollback();
                  return 0;
	     }
	     else
	     {
		 $this->db->trans_commit();
                 return $str;
             }

       }


       function add_autojournal($temp_id,$qdate)
      {

                 $count=$this->db->query("select * from auto_journal where  reference='". $temp_id . "'");
                 //$ref=$this->customermodel->getSingleFieldValue('temp_refs','reference','id',$temp_id);

                 $tra_cod= $this->customermodel->getSingleFieldValue('transaction_code','code','trans',3);
                      if($tra_cod!='')
                      {
                           $next_ref= $this->accountingsmodel->get_reference_code(3);
                          $ref=$tra_cod.'/'.date('Y').'/'.$next_ref;
                      }
                      else
                      {
                          $ref="0";
                      }
                 $str=0;
                 $insert_audit=0;
                 $date=$this->mastermodel->convdatformat($qdate);
                 $tdat=date('Y-m-d');
                 $this->db->trans_begin();
                 foreach ($count->result_array() as $row)
                 {

                                
                                $hid=$row['account_code'];
                                $bank_id=$row['account_id'];
                                $amount=$row['amount'];
                                $memo=$row['memo'];

                                if($insert_audit==0)
                                {

                                    $trans_type=3;  // Type is journal entry.Refer table trans_type
                                    $insertvals=array('type'=>$trans_type,'reference'=>$ref); // inserting values to refs table
                                    $this->db->insert('refs',$insertvals);
                                    $ref_id=$this->db->insert_id();
                                    $fyear=$this->fiscalyear();
                                    $insValuesA=array(
                                                      'trans_no'=>$ref_id,
                                                      'user'=>$_SESSION['userid'],
                                                      'date_trans'=>$tdat,

                                                      'fiscal_year'=>$fyear,
                                                      'gl_date'=>$date

                                      );
                                    $this->db->insert('audit_trail', $insValuesA);
                                    $insert_audit=1;
                                }


                                         $tblValues=array('type_no'=>$ref_id,'tran_date'=>$date,'account'=>$hid,'memo'=>$memo,'amount'=>$amount);
                                        
                                         $str= $this->db->insert('gl_trans', $tblValues);
                                         $ref= $this->customermodel->getSingleFieldValue('refs','reference','id',$ref_id);

                                   if($bank_id>=1)
                                   {

                                      $tblValues3=array('trans_no'=>$ref_id,'bank_act'=>$bank_id,'ref'=>$ref,'trans_date'=>$date,'amount'=>$amount);
                                      $query= $this->db->insert('bank_trans', $tblValues3);
                                   }
                                         $posted_val=array('unpost'=>1);
                                         $this->db->where('reference', $ref_id);
                                         $str= $this->db->update('unposted_journal', $posted_val);

                 }

              if ($this->db->trans_status() === FALSE)
	     {
		 $this->db->trans_rollback();
                  return 0;
	     }
	     else
	     {
		 $this->db->trans_commit();
                 echo $str;
             }

       }

       /***********************Get customer account id from cust_id***************************/
     
 function get_acc_id($table,$tfield,$value)
       {
           
$field='account_code';
	   $data=$this->db->query("select chart_master.account_code from chart_master inner join $table on $table.$tfield=chart_master.account_code where $table.id= ". $value );
	   $result= $data->row();
	   if($result)
	   {
	      return $result->$field;
	   }
	   else
	   {
	      return "";
	   }
       }

    function getbank_acc($type)
    {

          if($type==1)
          {
              $qry="select employeeid as code,name as name,id as id,'$type' as type from staffpersonaldetails";
              $data=$this->db->query($qry);

          }
          else if($type==2)
          {
              $qry="select id as id, company_code as code,company_name as name,'$type' as type from insurance_company";
              $data=$this->db->query($qry);

          }
          return $data;

    }


        function get_acc_sub($type)
    {

            
          if($type==1)
          {
              $qry="select employeeid as code,name as name,id as id,'$type' as type from staffpersonaldetails";
              $data=$this->db->query($qry);

          }
          else if($type==2)
          {
              $qry="select id as id, company_code as code,company_name as name,'$type' as type from insurance_company";
              $data=$this->db->query($qry);

          }
          else if($type==3)
          {
              $qry="select c.id as id, c.code as code,IFNULL(cp.insured,cc.insured)  as name,'$type' as type  from customers c LEFT JOIN customer_corp_info cc ON c.id = cc.customer_id LEFT JOIN customer_personal_ind cp ON c.id = cp.customer_id ";
              $data=$this->db->query($qry);

          }
          return $data;

    }
    function getpayment_list($val)
    {
      
        $dat= explode("~",$val);
        
       if($dat[0]==1)
       {
           $acid= $this->customermodel->getSingleFieldValue('staffpersonaldetails','id','employeeid',$dat[1]);
        $qry="select 
           ps.quotation_ref
           , pspd.placing_slip_id as pid
           , ct.type_no as tno
           , ct.amount as tamount
           ,ct.alloc,pspd.premium
          
           ,pspd.brokerage
           ,pssh.percentage
           ,policynote.policyno
           from placing_slip_stakeholders pssh
           join placing_slip_premiumdetails pspd on pspd.placing_slip_id=pssh.placing_slip_id
            INNER JOIN placing_slip ps on pspd.placing_slip_id=ps.id
           INNER JOIN placing_slip_refs psr ON psr.pslip_id= pspd.placing_slip_id
           INNER JOIN agent_trans ct ON (ct.type_no=psr.id and ct.account= '$dat[1]')
          
           left join policynote on ps.quotation_ref=policynote.quotation_ref
           where pssh.staffid=$acid group by ps.id";

        $data=$this->db->query($qry);
       }
       else if($dat[0]==2)
       {
          $acid= $this->customermodel->getSingleFieldValue('insurance_company','id','company_code',$dat[1]);
        $qry="select ps.quotation_ref
           , pspd.placing_slip_id as pid
           , ct.type_no as tno
           , ct.amount as tamount
           ,ct.alloc, pspd.premium
           
           ,pspd.brokerage
            ,policynote.policyno
           from  placing_slip_premiumdetails pspd
           INNER JOIN placing_slip ps on pspd.placing_slip_id=ps.id
           INNER JOIN placing_slip_refs psr ON psr.pslip_id= pspd.placing_slip_id
           INNER JOIN company_trans ct ON ct.type_no=psr.id
         
           left join policynote on ps.quotation_ref=policynote.quotation_ref
           where pspd.insurance_company_id=$acid group by ps.id";

        $data=$this->db->query($qry);
       }


         return $data;
    }

function bankaccount_unpostpayment()
        {
           
           

              $transact_type=$_POST['bank_trans_type'];

                 $acccode1=$_POST['bankacc'];
                    $acccode=explode('~',$acccode1);
                    $qdate=$_POST['date'];
                    $date=$this->mastermodel->convdatformat($qdate);
                    $ref=$_POST['ref'];
                    $this->db->trans_begin();
                    $type=explode('~',$acccode1);
                    $trans_type=$_POST['pay_n_dep'];
                    $str=0;
                     $counter=$_POST['counter_check'];
                     $update=$_POST['refid'];
                     if(isset($_POST['method']))
                     {
                     $method=$_POST['method'];
                     }
                     else
                     {
                       $method='';
                     }
                if($update!=0)
                    {
                         $delete=$this->db->delete('unposted_pay_dep',array('reference'=> $update));
                         $delete_ch=$this->db->delete('receipt_cheque',array('reference'=> $update));
                         $ref_id=$update;
                    }
                   
                    else
                    {
                    $insertvals=array('type'=>$trans_type,'reference'=>$_POST['ref']); // inserting values to refs table
                    $this->db->insert('refs',$insertvals);
                    $ref_id=$this->db->insert_id() ;
                    }
                     /*****************************************************************************************/
                    for ($i=0;$i<=$counter;$i++)
                    {
                        if(isset($_POST['amount_'.$i]))
                        {
                            $hid=$_POST['hidedesc_'.$i];
                            $memo=$_POST['memo_'.$i];
                            $code=$_POST['code_'.$i];
                            if($trans_type==1)   // For Bank Payment
                            {
                                $cre_amo=$_POST['amount_'.$i];
                                $amount=$cre_amo;
                                $sumamount=$_POST['sumamount'];
                                //$pay_to=$_POST['payment_to'];

                                if(ISSET($_POST['to_bank']))
                                {
                                 $pay_to=$_POST['to_bank'];
                                }
                                else
                                {
                                  $pay_to=0;
                                }
                            }
                            else if($trans_type==2)   // For Bank Deposit
                            {
                                $cre_amo=$_POST['amount_'.$i];
                                 $amount=0-$cre_amo;
                                $sumamount=-($_POST['sumamount']);
                                $pay_to=0;
                            }
                            $tblValues=array('reference'=>$ref_id,'acc_id'=>$acccode[0],'date'=>$date,'bank_acc'=>$acccode[1],'memo'=>$memo,'amount'=>$amount,'account'=>$code,'unpost'=>0,'type'=>$trans_type,'pay_to'=>$pay_to,'method'=>$method);
                            $str= $this->db->insert('unposted_pay_dep', $tblValues);
                           
                         }
                    }



                    if($method=='cheque')
                    {

                        $ch_date=$_POST['ch_date'];
                         $ch_date=$this->mastermodel->convdatformat($ch_date);
                        $bname=$_POST['bankname'];
                        $ch_no=$_POST['ch_no'];
                      $chdetails=array('reference'=>$ref_id,'ch_date'=>$ch_date,'bank_name'=>$bname,'cheque_no'=>$ch_no);
                            $str= $this->db->insert('receipt_cheque', $chdetails);
                    }
                     if ($this->db->trans_status() === FALSE)
                         {
                             $this->db->trans_rollback();
                              return 0;
                         }
                         else
                         {
                             $this->db->trans_commit();
                             return $str;
                         }
        }
    function bankaccount_payment($ref_id)
        {

            $count=$this->db->query("select * from unposted_pay_dep where unpost='0' and  reference='". $ref_id . "'");
                 $str=0;
                 $insert_audit=0;
             $this->db->trans_begin();

                            $transact_type='other';
                         if( $transact_type=='other')
                         {

                                $str=0;

                                $sumamount=0;
                              
                            foreach ($count->result_array() as $row)
                              {

                                $date=$row['date'];
                                $tdate=date('Y-m-d');
                                $acccode=$row['bank_acc'];
                                $accid=$row['acc_id'];
                                $amount=$row['amount'];
                                $code=$row['account'];
                                $memo=$row['memo'];
                                $type=$row['type'];
                                $method=$row['method'];

                            $this->db->trans_begin();

                      /********************************************Insert into Audit_trail******************************************************/
                   
                    if($insert_audit==0)
                                {
                                    $fyear=$this->fiscalyear();
                                    $insValuesA=array(
                                                      'trans_no'=>$ref_id,
                                                      'user'=>$_SESSION['userid'],
                                                      'date_trans'=>$tdate,

                                                      'fiscal_year'=>$fyear,
                                                      'gl_date'=>$date

                                      );
                                    $this->db->insert('audit_trail', $insValuesA);
                                    $insert_audit=1;
                                }

                    /*****************************************************************************************/
                    
                       
                          
                            $tblValues=array('type_no'=>$ref_id,'tran_date'=>$date,'account'=>$code,'memo'=>$memo,'amount'=>$amount,'method'=>$method);
                            $str= $this->db->insert('gl_trans', $tblValues);


                            if(strncasecmp("IDL",$code,3)==0 || strncasecmp("CRP",$code,3)==0 )
                            {
                                $tblValuescu=array('type_no'=>$ref_id,'tran_date'=>$date,'account'=>$code,'memo'=>$memo,'amount'=>$amount);
                                 $str= $this->db->insert('customer_trans', $tblValuescu);
                            }
                             if(strncasecmp("EMP",$code,3)==0 || strncasecmp("AGE",$code,3)==0 )
                            {
                                $tblValuescu=array('type_no'=>$ref_id,'tran_date'=>$date,'account'=>$code,'memo'=>$memo,'amount'=>$amount);
                                 $str= $this->db->insert('agent_trans', $tblValuescu);
                            }
                            if(strncasecmp("INS",$code,3)==0)
                            {
                                $tblValuescu=array('type_no'=>$ref_id,'tran_date'=>$date,'account'=>$code,'memo'=>$memo,'amount'=>$amount);
                                 $str= $this->db->insert('company_trans', $tblValuescu);
                            }

                            $sumamount+=$amount;
                              }
                              $insamount=0-$sumamount;
                            $ref= $this->customermodel->getSingleFieldValue('refs','reference','id',$ref_id);
                            $tblValues1=array('type_no'=>$ref_id,'tran_date'=>$date,'account'=>$acccode,'memo'=>$memo,'amount'=>$insamount,'method'=>$method);
                            $str= $this->db->insert('gl_trans', $tblValues1);
                            $tblValues3=array('trans_no'=>$ref_id,'bank_act'=>$accid,'ref'=>$ref,'trans_date'=>$date,'amount'=>$insamount,'reconciled'=>'');
                            $query= $this->db->insert('bank_trans', $tblValues3);

                            

                                   $posted_val=array('unpost'=>1);
                                         $this->db->where('reference', $ref_id);
                                         $str= $this->db->update('unposted_pay_dep', $posted_val);
                    if ($this->db->trans_status() === FALSE)
                         {
                             $this->db->trans_rollback();
                              return 0;
                         }
                         else
                         {
                             $this->db->trans_commit();
                             return $query;
                         }
                }

                else
                {
                   
                     $pay_amt=$_POST['pay_amt'];
                     $memo1=$_POST['memo1'];                   
                     $type_no=$_POST['t_no'];
                     $pid=$_POST['p_id'];
                     $to_acc=$_POST['to_bank'];
                     $prev_amt=$_POST['prev_amt'];
                     $bank_details=explode('~',$to_acc);
                     $acc_code=$bank_details[2];
                     $sum_amount=0;
                       if($bank_details[0]==1)
                           {
                              $table='agent_allocate';
                              $table1='agent_trans';
                           }
                       else if($bank_details[0]==2)
                           {
                              $table='company_allocate';
                              $table1='company_trans';
                           }

                    $insertvals=array('type'=>'2','reference'=>$_POST['ref']); // inserting values to refs table
                    $this->db->insert('refs',$insertvals);
                    $ref_id=$this->db->insert_id() ;





                      /********************************************Insert into Audit_trail******************************************************/
                      $fyear=$this->fiscalyear();
                $insValuesA=array(
                                  'trans_no'=>$ref_id,
                                  'user'=>$_SESSION['userid'],
                                  'date_trans'=>$tdat,

                                  'fiscal_year'=>$fyear,
                                  'gl_date'=>$date

                  );
                $this->db->insert('audit_trail', $insValuesA);
                    /*****************************************************************************************/


                         for($p=0;$p<sizeof($type_no);$p++)
                      {
                         if($pay_amt[$p]!='' || $pay_amt[$p]!=0)
                         {


                              $insertdata=array(        'type_no'=>$ref_id,
                                                        'tran_date'=>$date,
                                                        'account'=>$acc_code,
                                                        'memo'=>$memo1[$p],
                                                        'amount'=>$pay_amt[$p],
                                                        'alloc'=>$pay_amt[$p]
                                                );
                              
                                   $this->db->insert($table1, $insertdata);
                                   $fromac=$this->db->insert_id() ;

                             $data=array(
                                    'from'=>$fromac,
                                    'pid'=>$pid[$p],
                                    'amount'=>$pay_amt[$p]
                                     );
                                     
                                     $this->db->insert($table, $data);
                                    
                                     

                             $alloc=$prev_amt[$p]+$pay_amt[$p];
                             
//
//                             
                               $this->db->query("update $table1 set alloc=$alloc where type_no='$type_no[$p]' and account='$acc_code'");
                               $sum_amount+=$pay_amt[$p];
                            
                             }
                      }



                     

                     $Tabledata=array(                  'type_no'=>$ref_id,
                                                        'tran_date'=>$date,
                                                        'account'=>$acc_code,
                                                        'memo'=>'',
                                                        'amount'=>$sum_amount
                                                );
                      $this->db->insert('gl_trans', $Tabledata);

                     $Tabledata1=array(                  'type_no'=>$ref_id,
                                                        'tran_date'=>$date,
                                                        'account'=>$acccode[1],
                                                        'memo'=>'',
                                                        'amount'=>-$sum_amount
                                                );
                      $this->db->insert('gl_trans', $Tabledata1);
                       $bankdata=array(                  'trans_no'=>$ref_id,
                                                         'bank_act'=>$acccode[0],
                                                         'ref'=>$ref,
                                                         'trans_date'=>$date,
                                                         'amount'=>-$sum_amount,
                                                         'reconciled'=>''
                                                );
                                   $data=$this->db->insert('bank_trans', $bankdata);

                  
                       if ($this->db->trans_status() === FALSE)
                         {
                             $this->db->trans_rollback();
                              return 0;
                         }
                         else
                         {
                             $this->db->trans_commit();
                             return $data;
                         }

                   }
        }


          function fiscalyear()
       {
            

	   $data=$this->db->query("select fyear from mycompany ");
	   $result= $data->row();
	   if($result)
	   {
	      return $result->fyear;
	   }
	   else
	   {
	      return "";
	   }
       }

       /*******************function to add auto journal********************/

 function add_auto_journal()
      {

                // $reverse=$_POST['reverse'];
                // $ref=$_POST['ref'];
                 $title=$_POST['title'];
                 $date=date('Y-m-d');
                 $counter=$_POST['counter_check'];
                 $trans_type=3;  // Type is journal entry.Refer table trans_type

                 $this->db->trans_begin();
                 $update=$_POST['refid'];
                if($update!=0)
                    {
                         $delete=$this->db->delete('auto_journal',array('reference'=> $update));
                          $ref_id=$update;
                    }
                    else
                    {
                 $insertvals=array('type'=>$trans_type,'reference'=>$title); // inserting values to refs table
                 $this->db->insert('temp_refs',$insertvals);
                 $ref_id=$this->db->insert_id() ;
                    }
          /********************Insert into temperory table unposted_journal*******************/


                for ($i=0;$i<=$counter;$i++)
                     {
                         if(isset($_POST['desc_'.$i]))
                             {
                                  $hid=$_POST['hidedesc_'.$i];
                                  $memo=$_POST['memo_'.$i];
                                  $desc=$_POST['desc_'.$i];



                                  $debit=$_POST['debit_'.$i];
                                  $credit=$_POST['credit_'.$i];
                                  if($debit>=1)
                                  {
                                      $amount=$debit+$credit;
                                  }
                                  else if($credit>=1)
                                  {
                                      $amount=-($debit+$credit);
                                  }
                                  else
                                      {
                                      $amount=0;
                                      }

                                          $bank_id= $this->customermodel->getSingleFieldValue('bank_accounts','id','account_code',$hid);
                                          $tblValues=array('reference'=>$ref_id,'date'=>$date,'title'=>$title,'account_code'=>$hid,'account_id'=>$bank_id,'amount'=>$amount,'memo'=>$memo);
                                          $str= $this->db->insert('auto_journal', $tblValues);

                             }
                             }

             if ($this->db->trans_status() === FALSE)
	     {
		 $this->db->trans_rollback();
                  return 0;
	     }
	     else
	     {
		 $this->db->trans_commit();
                 return $str;
             }

       }

function get_transtype_count($type,$refid)
   {
        $res=$this->db->query("select count(*) as count from refs where refs.type= $type and refs.id <= $refid ");
     
           $cnt= ($res->row()->count);
           return $cnt;
	  
   }
 function checkaccountisset($account,$table)
     {
        
        $query=$this->db->query('select * from '.$table.' t join fiscal_year fy ON t.fyear=fy.id where fy.closed=0');
         $res=$query->row();
         if(!isset($res->$account))
                 $baccount=0;
         else
                 $baccount=$res->$account;
         return $baccount;

     }
 function checkaccountsetting()
     {

        $query=$this->db->query('select * from subacc_setting');

         $res=$query->num_rows();
         return $res;


     }
 function get_subaccount_setting($field)
     {

       
         $query=$this->db->query("select $field from subacc_setting ");
         $res=$query->row()->$field;
         return $res;


     }
     
      function get_mainaccount_setting($field)
     {

       
         $query=$this->db->query("select $field from mainacc_setting ");
         $res=$query->row()->$field;
         return $res;


     }


     /*************Report Functions*******************/
 function get_chart_report()
     {

     $sql="select IFNULL(sum(g.amount),0) as amount,cg.chart_group,cg.chart_type as ctype,ct.id as cid,c.account_name,c.account_code,ct.chart_types as chart_type from chart_master c INNER JOIN char_type ct ON ct.id=c.chart_type LEFT JOIN gl_trans
          g ON g.account=c.account_code join chart_group cg ON cg.chart_type=ct.id group by c.account_code,cg.chart_type order by ct.id";
     $Q=$this->db->query($sql);

        if ($Q->num_rows() > 0)
         {
             foreach ($Q->result_array() as $row)
             {
                 $data[] = $row;
             }
         }
         $Q->free_result();
         return $data;
     }
 function get_journal_report($date1='',$date2='')
         {

            $data=array();
            $date1 = $this->mastermodel->convdatformat($date1);
            $date2 = $this->mastermodel->convdatformat($date2);
            $sql="select * from gl_trans g INNER JOIN refs r ON r.id=g.type_no where r.type=3 and g.tran_date between '$date1' and '$date2' order by g.type_no";
            $Q=$this->db->query($sql);

                if ($Q->num_rows() > 0)
                 {
                     foreach ($Q->result_array() as $row)
                     {
                         $data[] = $row;
                     }
                 }
             $Q->free_result();
             return $data;
         }
   function get_customer_balance($cus_id,$date1,$date2)
         {

            $data=array();
            $date1 = $this->mastermodel->convdatformat($date1);
            $date2 = $this->mastermodel->convdatformat($date2);
            if($cus_id=='all')
                $condition="where";
                else
                   $condition=" where customers.id=$cus_id and "  ;



             $sql="SELECT
                             placing_slip_premiumdetails.premium
                            , placing_slip.id as pid
                            , IFNULL(sum(cust_allocate.amount),0) as amount
                            , customers.id
                            , placing_slip_refs.id as typeno
                            , customer_trans.alloc as calloc
                            , placing_slip.quotation_ref
                            , refs.reference
                            , customer_trans.tran_date
                            , customer_trans.account


                        FROM
                            placing_slip_premiumdetails
                            INNER JOIN placing_slip
                                ON (placing_slip_premiumdetails.placing_slip_id = placing_slip.id)
                            LEFT JOIN cust_allocate
                                ON (placing_slip_premiumdetails.placing_slip_id = cust_allocate.pid)
                            INNER JOIN placing_slip_refs
                                ON (placing_slip_premiumdetails.placing_slip_id = placing_slip_refs.pslip_id)
                            INNER JOIN refs
                                ON (placing_slip_refs.id = refs.id)
                            INNER JOIN customer_trans
                                ON (customer_trans.type_no = placing_slip_refs.id)
                            INNER JOIN customers
                                ON (placing_slip.customer_id = customers.id)  $condition customer_trans.tran_date between '$date1' and '$date2' GROUP BY placing_slip.id ORDER by customer_trans.account";



            $Q=$this->db->query($sql);

                if ($Q->num_rows() > 0)
                 {
                     foreach ($Q->result_array() as $row)
                     {
                         $data[] = $row;
                     }
                 }
             $Q->free_result();
             return $data;
         }



  function get_cust_allocate_bal($cus_code,$date1,$date2)
        {

            $data=array();
            $date1 = $this->mastermodel->convdatformat($date1);
            $date2 = $this->mastermodel->convdatformat($date2);
             if($cus_code=='all')
                $condition="where";
                else
                   $condition=" where account='$cus_code' and "  ;

            $qry="SELECT sum(amount) as all_amount,sum(alloc) as bal_amount, account FROM customer_trans $condition amount <0 and customer_trans.tran_date between '$date1' and '$date2' GROUP by customer_trans.account ORDER by customer_trans.account";

                    $res=$this->db->query($qry);

            if ($res->num_rows() > 0)
                 {
                     foreach ($res->result_array() as $row)
                     {
                         $data[] = $row;
                     }
                 }
             $res->free_result();
             return $data;
        }


     function customer_list_rep()
     {


         $qry="SELECT IFNULL(cp.insured,cc.insured) as name , c.id,c.code FROM customers c LEFT JOIN customer_personal_ind cp ON c.id=cp.customer_id  LEFT JOIN customer_corp_info cc ON c.id=cc.customer_id  ";

                    $res=$this->db->query($qry);

            if ($res->num_rows() > 0)
                 {
                     foreach ($res->result_array() as $row)
                     {
                         $data[] = $row;
                     }
                 }
             $res->free_result();
             return $data;
     }

  function get_customer_name($cus_code)
  {

        $data="SELECT IFNULL(cp.insured,cc.insured) as name , c.id,c.code FROM customers c LEFT JOIN customer_personal_ind cp ON c.id=cp.customer_id  LEFT JOIN customer_corp_info cc ON c.id=cc.customer_id where c.code='$cus_code' ";
         $res=$this->db->query($data);
     
        $result= $res->row();
	   if($result)
	   {
	      return $result->name;
	   }
	   else
	   {
	      return "";
	   }
  }

   function bankname_list()
     {


         $qry="SELECT * from bank_accounts ";

                    $res=$this->db->query($qry);

            if ($res->num_rows() > 0)
                 {
                     foreach ($res->result_array() as $row)
                     {
                         $data[] = $row;
                     }
                 }
             $res->free_result();
             return $data;
     }
 function get_bank_statement($bankid,$date1,$date2)
        {

            $data=array();
            $date1 = $this->mastermodel->convdatformat($date1);
            $date2 = $this->mastermodel->convdatformat($date2);

            $qry="SELECT bt.trans_no, bt.trans_date,bt.amount,r.reference,tt.transaction FROM bank_trans bt LEFT JOIN refs r ON r.id=bt.trans_no LEFT JOIN transaction_types tt ON tt.id=r.type where bank_act=$bankid and  trans_date between '$date1' and '$date2' ORDER BY bt.trans_no ";
         
            $res=$this->db->query($qry);

            if ($res->num_rows() > 0)
                 {
                     foreach ($res->result_array() as $row)
                     {
                         $data[] = $row;
                     }
                 }
             $res->free_result();
             return $data;
        }

     function get_chart_trans_report($acc,$date1='',$date2='')
         {

            $data=array();
            $date1 = $this->mastermodel->convdatformat($date1);
            $date2 = $this->mastermodel->convdatformat($date2);
            $sql="SELECT gt.type_no, gt.tran_date,gt.amount,r.reference,tt.transaction_type FROM gl_trans gt LEFT JOIN refs r ON r.id=gt.type_no LEFT JOIN transaction_types tt ON tt.id=r.type where gt.account='$acc' and  gt.tran_date between '$date1' and '$date2' ORDER BY gt.type_no ";
           
            $Q=$this->db->query($sql);

                if ($Q->num_rows() > 0)
                 {
                     foreach ($Q->result_array() as $row)
                     {
                         $data[] = $row;
                     }
                 }
             $Q->free_result();
             return $data;
         }
         /*******************Report end*******************/

  function acc_code_increment($where,$like)
  {

        $data="SELECT IFNULL(max(account_code),0) as code FROM chart_master where parent=$where and account_code like '".$like."%'";
       
        $res=$this->db->query($data);
        return $res->row()->code;
                 
        
	   
  }

  function acc_code_maxi_limit($value)
  {

        $data="SELECT account_code FROM chart_master where account_code>$value and parent=0 order by account_code ASC limit 0,1";
        
        $res=$this->db->query($data);
        if ($res->num_rows() > 0)
                 {
                    return $res->row()->account_code;
                 }
         else
                 {
                     return 99999999999999999999;
                 }

  }

 function Getchart_group($table,$pageno,$field,$value="")
        {

            $limit=(($pageno-1) * 10);
            $data=array();
           if($field=='chart_type')
           {
             
               $res=$this->db->query("select * from $table t join char_type ct on ct.id=t.chart_type where ct.chart_types like '". $value . "%' order by t.id limit " . $limit .",". 10);
           }
           else 
           {
            $res=$this->db->query("select * from $table where ". $field . " like '". $value . "%' order by id limit " . $limit .",". 10);

           }
           foreach ($res->result_array() as $row)
                 {
                     $data[] = $row;
                 }
            return $data;
        }

function showchart_group($pageno,$field,$value="")
        {
            $limit=(($pageno-1) * 10);
            $data=array();
            $data1=array();
            $rescount=$this->db->query("select * from chart_master  where ". $field . " like '". $value . "%' and parent=0");

              if($field=='chart_type')
           {

               $res=$this->db->query("select * from chart_master t join char_type ct on ct.id=t.chart_type where ct.chart_types like '". $value . "%' and parent=0 order by t.id limit " . $limit .",". 10);
           }
           else
           {

            $res=$this->db->query("select cg.account_code,cg.account_name,cg.id,cg.chart_type from  chart_master cg join char_type ct on ct.id=cg.chart_type
                where ". $field . " like '". $value . "%' and parent=0 order by ct.sort,cg.account_code asc,cg.id desc limit " . $limit .",". 10);
          

           }

             $data['totcount']=$rescount->num_rows();

            foreach ($res->result_array() as $row)
                 {
                     $data1[] = $row;
                 }
            $data['result']=$data1;

            return $data;
        }

    function addchart_group()
        {

        
          $acc_name=$this->input->post('acc_name');
          $parent=$this->input->post('parent');
          $acc_group=$this->input->post('acc_group');
          $account_code=$this->input->post('account_code');
        

              
              $tblValues=array('account_code'=>$account_code,'chart_type'=>$acc_group,'parent'=>$parent,'account_name'=>$acc_name);
          
              $data=$this->db->insert('chart_master', $tblValues);
              

           return $data;
        }

    function addtransaction_code()
        {


          $code=$this->input->post('code');
          $codefor=$this->input->post('codefor');
          $type=$this->input->post('type');
          
          $tblValues=array('code'=>$code,'type'=>$type,'trans'=>$codefor);
          $data=$this->db->insert('transaction_code', $tblValues);
          return $data;
        }

    function countchart_group($table,$field,$value="")
        {

        if($field=='chart_type')
           {

               $res=$this->db->query("select * from $table t join char_type ct on ct.id=t.chart_type where ct.chart_types like '". $value . "%'  ");
           }
           else
           {

                  $res=$this->db->query("select * from ".$table." where ". $field . " like '". $value . "%'" );

           }
           return $res->num_rows();
       }


        function updatechart_group()
        {

              $acc_name=$this->input->post('acc_name');
              $parent=$this->input->post('parent');
              $acc_group=$this->input->post('acc_group');
              $account_code=$this->input->post('account_code');
              $id=$this->input->post('id');


            $tblValues=array('account_code'=>$account_code,'chart_type'=>$acc_group,'parent'=>$parent,'account_name'=>$acc_name);

            $this->db->where('id', $id);
            $res= $this->db->update('chart_master', $tblValues);
            return $res;
        }

        function updatetrans_code()
        {

          $id=$this->input->post('id');
          $code=$this->input->post('code');
          $codefor=$this->input->post('codefor');
          $type=$this->input->post('type');
       
          $this->db->where('id', $id);
          $tblValues=array('code'=>$code,'type'=>$type,'trans'=>$codefor);
          $res= $this->db->update('transaction_code', $tblValues);
            return $res;
        }


  function deletechart_group($fld,$table,$id)
    {

       $qry=$this->db->query("select count(*) as count from chart_master where parent='$id'");
       $query=$qry->row()->count;
       
         if($query==0 )
         {
          $res=$this->db->delete($table,array($fld=> $id));
                if($res>0)
                   {
                       return 1;
                   }
                 else
                    {
                        return 0;
                    }
         }
         else
         {
             return 0;
         }

   }
   function unpost_customerpayment($pageno,$type,$post)
        {



           if($type=='data')
           {

                 $limit=(($pageno-1) * 10);
            $data=array();

            $res=$this->db->query("select * from bank_to_bank where type='$post'   limit " . $limit .",". 10);
            foreach ($res->result_array() as $row)
                 {
                     $data[] = $row;
                 }
            return $data;
           }
           else if($type=='count')
           {

               $res=$this->db->query("select * from bank_to_bank ");
             return $res->num_rows();
             }


        }
   function checktrans_codeset($val)
     {
     
        $query=$this->db->query("select * from transaction_code  where trans=$val");

         $res=$query->num_rows();
         return $res;


     }

   function get_reference_code($val)
   {
     $inval=str_replace('-', ',', $val);
     $query=$this->db->query("select max(id) as id from refs where type in($inval) ");
     $id=$query->row()->id;
     $ref=$this->customermodel->getSingleFieldValue('refs','reference','id',$id);

     $reference=explode('/',$ref);
     $cnt=count($reference);
     $cnt=$cnt-1;
     $ref_val=$reference[$cnt];
    

     $array=str_split($reference[$cnt]);
     $count=count($array);

     $f="";
     $m="";
     $e="";
     $isNum=0;
     $pre=0;
     $current=0;

     $a=$count;

     for($i=$count-1;$i>=0;$i--)
     {

         if(is_numeric($array[$i]))
         {
            if($current==0)
            {
                $current=1;
                $isNum++;
            }
         }
         else
         {
            if($current==1)
            {
                $current=0;
                $isNum++;
            }
         }


         if($isNum==0)
            $e=$array[$i].$e;
         else if($isNum==1)
            $m=$array[$i].$m;
         else
            $f=$array[$i].$f;
     }


      $m=$m+1;
      $output=$f.$m.$e;
     return $output;
   }


   function add_reverse_posted_journal()
      {
                 $str=0;
                 $reverse=$_POST['reverse'];
                 $ref=$_POST['ref'];
                 $qdate=$_POST['date'];
                 $date=$this->mastermodel->convdatformat($qdate);
                 $counter=$_POST['counter_check'];
                 $trans_type=3;  // Type is journal entry.Refer table trans_type
                   
                     $this->db->trans_begin();
                      if($reverse=='true')
                    {

                     $insertvals=array('type'=>$trans_type,'reference'=>$ref); // inserting values to refs table
                     $this->db->insert('refs',$insertvals);
                     $ref_id=$this->db->insert_id() ;

          /********************Insert into temperory table unposted_journal*******************/


                for ($i=0;$i<=$counter;$i++)
                     {
                         if(isset($_POST['desc_'.$i]))
                             {
                                  $hid=$_POST['hidedesc_'.$i];
                                  $memo=$_POST['memo_'.$i];
                                  $desc=$_POST['desc_'.$i];



                                  $debit=$_POST['debit_'.$i];
                                  $credit=$_POST['credit_'.$i];
                                  if($debit>=1)
                                  {
                                      $amount=0-($debit+$credit);
                                  }
                                  else if($credit>=1)
                                  {
                                      $amount=$debit+$credit;
                                  }
                                  else
                                      {
                                      $amount=0;
                                      }

                                          $bank_id= $this->customermodel->getSingleFieldValue('bank_accounts','id','account_code',$hid);
                                          $tblValues=array('reference'=>$ref_id,'date'=>$date,'reverse'=>'false','account_code'=>$hid,'account_id'=>$bank_id,'amount'=>$amount,'memo'=>$memo,'unpost'=>0);
                                          $str= $this->db->insert('unposted_journal', $tblValues);



                             }
                             }


                    }

            if ($this->db->trans_status() === FALSE)
	     {
		 $this->db->trans_rollback();
                  return 0;
	     }
	     else
	     {
		 $this->db->trans_commit();
                 return $str;
             }

       }
       function get_emp_paid_amount($val,$table)
       {
            $query=$this->db->query("select  amount from $table  where id='$val'");

         $res=$query->row()->amount;
         return $res;
       }
       function get_emp_alloc_amount($val,$table)
       {
           $query=$this->db->query("select  alloc from $table  where id='$val'");
         // echo "select  alloc from $table  where id='$val'";
         $res=$query->row()->alloc;
         return $res;
       }


   function addemployeeallocate()
        {
           
            $ptype=$_POST['t_no'];
            $pid=$_POST['p_id'];
            $alloc_amt=$_POST['pay_amt'];
            $pre_alloc=$_POST['prev_amt'];
            $account_code=$_POST['account_code'];
            $from=$_POST['fromid'];
            $allocate=$_POST['alloc_table'];
            $trans=$_POST['trans_table'];
            $bal_allocate=$_POST['bal_allocate'];
             $this->db->trans_begin();
                for($p=0;$p<sizeof($pid);$p++)
                      {


                    if($alloc_amt[$p]!='' || $alloc_amt[$p]!=0)
                         {
                            $data=array(
                                    'from'=>$from,
                                    'pid'=>$pid[$p],
                                    'amount'=>$alloc_amt[$p]
                                     );

                            $this->db->insert($allocate, $data);


                           
                            $bal_allocate+=$alloc_amt[$p];



                             $alloc=$pre_alloc[$p]+$alloc_amt[$p];
                             $pretype=$ptype[$p];

                             $insdata=array('alloc'=>$alloc);

                             $this->db->where('type_no',$pretype);
                             $this->db->where('account',$account_code);
                             $this->db->update($trans, $insdata);

                            //   $this->db->query("update $trans set alloc=$alloc where type_no=$pretype and account='$account_code'");
                          
                             }
                      }


                     $insalloc=array('alloc'=>$bal_allocate);

                             $this->db->where('id',$from);
                             $this->db->update($trans, $insalloc);

                      
                if ($this->db->trans_status() === FALSE)
	     {
		 $this->db->trans_rollback();

	     }
	     else
	     {
		 $this->db->trans_commit();
                return true;

	     }






        }
        function search_autojournal($searchopt,$searchtext="",$page="",$per_page="",$count)
        {
             $data = array();
             if($page)
                $start = ($page-1)*$per_page;
             else
                 $start=0;
            if($count=='true')
            {
              $sql="select  distinct(aj.reference) as id, r.reference as ref,aj.title,aj.date from auto_journal aj JOIN temp_refs r ON r.id=aj.reference  where r.type='7' and  $searchopt like '$searchtext%'" ;
               $data['results']= $this->db->query($sql);
               return $data['results']->num_rows();
            }
            else
            {
               $sql="select distinct(aj.reference) as id, r.reference as ref,aj.title,aj.date from auto_journal aj JOIN temp_refs r ON r.id=aj.reference  where r.type='7' and  $searchopt like '$searchtext%'  limit $start,$per_page";
               $res=$this->db->query($sql);
               foreach ($res->result_array() as $row)
               {
                    $data[] = $row;
               }
               return $data;
            }
        }
        function search_unposted_journal($searchopt,$searchtext="",$page="",$per_page="",$count)
        {
            $data = array();
             if($page)
                $start = ($page-1)*$per_page;
             else
                 $start=0;
            if($count=='true')
            {
               $sql="select  distinct(t.reference) as id, r.reference,t.date as tran_date from unposted_journal t JOIN refs r ON r.id=t.reference where r.type='7' and t.unpost='0' and $searchopt like '$searchtext%'" ;
               $data['results']= $this->db->query($sql);
               return $data['results']->num_rows();
            }
            else
            {
               $sql="select  distinct(t.reference) as id, r.reference,t.date as tran_date from unposted_journal t JOIN refs r ON r.id=t.reference where r.type='7' and t.unpost='0' and $searchopt like '$searchtext%'  limit $start,$per_page";
               $res=$this->db->query($sql);
               foreach ($res->result_array() as $row)
               {
                    $data[] = $row;
               }
               return $data;
            }
        }
        function search_posted_journal($searchopt,$searchtext="",$page="",$per_page="",$count)
        {
            $data = array();
             if($page)
                $start = ($page-1)*$per_page;
             else
                 $start=0;
            if($count=='true')
            {
               $sql="select distinct(r.id)  from gl_trans bt JOIN refs r ON r.id=bt.type_no where r.type='7' and $searchopt like '$searchtext%'" ;
               $data['results']= $this->db->query($sql);
               return $data['results']->num_rows();
            }
            else
            {
               $sql="select  distinct(r.id) as id, r.reference,bt.tran_date from gl_trans bt JOIN refs r ON r.id=bt.type_no where r.type='7' and $searchopt like '$searchtext%'  limit $start,$per_page";
               $res=$this->db->query($sql);
               foreach ($res->result_array() as $row)
               {
                    $data[] = $row;
               }
               return $data;
            }
        }
        function search_bank_transfer($searchopt,$searchtext="",$page="",$per_page="",$count="",$post="")
        {
            $data = array();
             if($page)
                $start = ($page-1)*$per_page;
             else
                 $start=0;
            if($count=='true')
            {
               $sql="select distinct(bank_to_bank.id),bank_to_bank.ref,amount,trans_date,memo,reference,bank_to_bank.type, ba1.bank_account_name as from_b,ba2.bank_account_name as to_b from bank_to_bank INNER JOIN bank_accounts ba1  ON (bank_to_bank.from_b = ba1.id) INNER JOIN bank_accounts ba2 ON (bank_to_bank.to_b = ba2.id) join refs on refs.id= bank_to_bank.ref  where bank_to_bank.type='$post' and $searchopt like '$searchtext%'" ;
               $data['results']= $this->db->query($sql);
               return $data['results']->num_rows();
            }
            else
            {
            $sql="select distinct(bank_to_bank.id),bank_to_bank.ref,amount,trans_date,memo,reference,bank_to_bank.type, ba1.bank_account_name as from_b,ba2.bank_account_name as to_b from bank_to_bank INNER JOIN bank_accounts ba1  ON (bank_to_bank.from_b = ba1.id) INNER JOIN bank_accounts ba2 ON (bank_to_bank.to_b = ba2.id) join refs on refs.id= bank_to_bank.ref  where bank_to_bank.type='$post' and $searchopt like '$searchtext%'  limit $start,$per_page";
               $res=$this->db->query($sql);
               foreach ($res->result_array() as $row)
               {
                    $data[] = $row;
               }
               return $data;
            }
        }
        function search_posted_bank_deposit($searchopt,$searchtext="",$page="",$per_page="",$count="")
        {
            $data = array();
             if($page)
                $start = ($page-1)*$per_page;
             else
                 $start=0;


             if($searchopt=='tran_date')
             {
               $searchtext=$this->mastermodel->convdatformat($searchtext);
             }
             else if($searchopt=='amount')
             {
               $searchtext=0-$searchtext;
             }

            if($count=='true')
            {
              $sql="select r.reference, bt.type_no as trans_no,bt.tran_date as trans_date,bt.amount as amount,cm.account_code,cm.account_name FROM  `gl_trans` bt JOIN refs r ON r.id = bt.`type_no`
             join chart_master cm on cm.account_code=bt.account
             WHERE r.type =  '2' and $searchopt like '$searchtext%' group by r.reference having amount <0 ";
           
               $data['results']= $this->db->query($sql);
               return $data['results']->num_rows();
            }
            else
            {
             $sql="select r.reference, bt.type_no as trans_no,bt.tran_date as trans_date,bt.amount as amount,cm.account_code,cm.account_name FROM  `gl_trans` bt JOIN refs r ON r.id = bt.`type_no`
             join chart_master cm on cm.account_code=bt.account
             WHERE r.type =  '2' and $searchopt like '$searchtext%' group by r.reference having amount <0 order by r.id  desc limit $start,$per_page";

           
            

               $res=$this->db->query($sql);
               foreach ($res->result_array() as $row)
               {
                    $data[] = $row;
               }
               return $data;
            }
        }
        function search_unposted_bank_deposit($searchopt,$searchtext="",$page="",$per_page="",$count="")
        {
            $data = array();
             if($page)
                $start = ($page-1)*$per_page;
             else
                 $start=0;

             if($searchopt=='date')
             {
               $searchtext=$this->mastermodel->convdatformat($searchtext);
             }
             else if($searchopt=='amount')
             {
               $searchtext=0-$searchtext;
             }

            if($count=='true')
            {
              $sql="select  t.reference as id,r.type,t.bank_acc,t.acc_id,cm.account_name,cm.account_code,t.amount as amount, r.reference,t.date as tran_date from unposted_pay_dep t JOIN refs r ON r.id=t.reference
                    join chart_master cm on cm.account_code=t.account
                    where r.type='2' and t.unpost='0' and $searchopt like '$searchtext%' group by r.reference   having amount <0  ";

           
               $data['results']= $this->db->query($sql);
               return $data['results']->num_rows();
            }
            else
            {

                $sql="select  t.reference as id,r.type,t.bank_acc,t.acc_id,cm.account_name,cm.account_code,t.amount as amount, r.reference,t.date as tran_date from unposted_pay_dep t JOIN refs r ON r.id=t.reference
                    join chart_master cm on cm.account_code=t.account
                    where r.type='2' and t.unpost='0' and $searchopt like '$searchtext%' group by r.reference  having amount <0  order by r.id desc limit $start,$per_page";

               // echo $sql;

         
            $res=$this->db->query($sql);
               foreach ($res->result_array() as $row)
               {
                    $data[] = $row;
               }
               return $data;
            }
        }
        function search_posted_bank_payment($searchopt,$searchtext="",$page="",$per_page="",$count="")
        {
            
            $data = array();
             if($page)
                $start = ($page-1)*$per_page;
             else
                 $start=0;


             if($searchopt=='tran_date')
             {
               $searchtext=$this->mastermodel->convdatformat($searchtext);
             }
            
             
              if($count=='true')
            {
              $sql="select r.reference, bt.type_no as trans_no,bt.tran_date as trans_date,bt.amount as amount,cm.account_code,cm.account_name FROM  `gl_trans` bt JOIN refs r ON r.id = bt.`type_no`
             join chart_master cm on cm.account_code=bt.account
             WHERE r.type =  '1' and $searchopt like '$searchtext%' group by r.reference having amount >0 ";

               $data['results']= $this->db->query($sql);
               return $data['results']->num_rows();
            }
            else
            {
             $sql="select r.reference, bt.type_no as trans_no,bt.tran_date as trans_date,bt.amount as amount,cm.account_code,cm.account_name FROM  `gl_trans` bt JOIN refs r ON r.id = bt.`type_no`
             join chart_master cm on cm.account_code=bt.account
             WHERE r.type =  '1' and $searchopt like '$searchtext%' group by r.reference having amount >0 order by r.id  desc limit $start,$per_page";




               $res=$this->db->query($sql);
               foreach ($res->result_array() as $row)
               {
                    $data[] = $row;
               }
               return $data;
            }
             
            
        }
         function search_unposted_bank_payment($searchopt,$searchtext="",$page="",$per_page="",$count="")
        {
            $data = array();
             if($page)
                $start = ($page-1)*$per_page;
             else
                 $start=0;

             if($searchopt=='date')
             {
               $searchtext=$this->mastermodel->convdatformat($searchtext);
             }

            if($count=='true')
            {
              $sql="select  t.reference as id,r.type,t.bank_acc,t.acc_id,cm.account_name,cm.account_code,t.amount as amount, r.reference,t.date as tran_date from unposted_pay_dep t JOIN refs r ON r.id=t.reference
                    join chart_master cm on cm.account_code=t.account
                    where r.type='1' and t.unpost='0' and $searchopt like '$searchtext%' group by r.reference   having amount >0  ";


               $data['results']= $this->db->query($sql);
               return $data['results']->num_rows();
            }
            else
            {

                $sql="select  t.reference as id,r.type,t.bank_acc,t.acc_id,cm.account_name,cm.account_code,t.amount as amount, r.reference,t.date as tran_date from unposted_pay_dep t JOIN refs r ON r.id=t.reference
                    join chart_master cm on cm.account_code=t.account
                    where r.type='1' and t.unpost='0' and $searchopt like '$searchtext%' group by r.reference  having amount >0  order by r.id desc limit $start,$per_page";

               // echo $sql;


            $res=$this->db->query($sql);
               foreach ($res->result_array() as $row)
               {
                    $data[] = $row;
               }
               return $data;
            }
        }
function search_unposted_customer_payment($searchopt,$searchtext="",$page="",$per_page="",$count="")
        {
            $data = array();
             if($page)
                $start = ($page-1)*$per_page;
             else
                 $start=0;
            if($count=='true')
            {
              $sql="select  distinct(t.reference) as id,t.bank_acc,t.acc_id, r.reference,t.date as tran_date from unposted_pay_dep t JOIN refs r ON r.id=t.reference where r.type='2' and t.unpost='0' and $searchopt like '$searchtext%'" ;
               $data['results']= $this->db->query($sql);
               return $data['results']->num_rows();
            }
            else
            {
            $sql="select  distinct(t.reference) as id,t.bank_acc,t.acc_id, r.reference,t.date as tran_date from unposted_pay_dep t JOIN refs r ON r.id=t.reference where r.type='2' and t.unpost='0' and $searchopt like '$searchtext%'  limit $start,$per_page";
               $res=$this->db->query($sql);
               foreach ($res->result_array() as $row)
               {
                    $data[] = $row;
               }
               return $data;
            }
        }
        function search_posted_customer_payment($searchopt,$searchtext="",$page="",$per_page="",$count="")
        {
            $data = array();
             if($page)
                $start = ($page-1)*$per_page;
             else
                 $start=0;
            if($count=='true')
            {
          $sql="select * from customer_trans c INNER JOIN bank_trans b ON c.type_no=b.trans_no where c.amount like'-%' and $searchopt like '$searchtext%'" ;
               $data['results']= $this->db->query($sql);
               return $data['results']->num_rows();
            }
            else
            {
         $sql="select distinct(c.id) as id,c.tran_date,c.amount,c.account,c.memo from customer_trans c INNER JOIN bank_trans b ON c.type_no=b.trans_no where c.amount like'-%' and $searchopt like '$searchtext%'  limit $start,$per_page";
               $res=$this->db->query($sql);
               foreach ($res->result_array() as $row)
               {
                    $data[] = $row;
               }
               return $data;
            }
        }



    function custom_allocat($table,$pageno,$field,$type)
        {

            $limit=(($pageno-1) * 10);
            $data=array();
          //echo "select distinct(c.id) as id,c.tran_date,c.amount,c.account,c.memo,b.bank_act from $table c INNER JOIN bank_trans b ON c.type_no=b.trans_no where c.alloc<>c.amount and c.". $field . " like'". $type . "%' ";
            $res=$this->db->query("select distinct(c.id) as id,c.alloc,c.tran_date,c.amount,c.account,c.memo,b.bank_act from $table c INNER JOIN bank_trans b ON c.type_no=b.trans_no where c.alloc<>-c.amount and c.". $field . " like'". $type . "%' order by c.id desc limit " . $limit .",". 10);
            foreach ($res->result_array() as $row)
                 {
                     $data[] = $row;
                 }
            return $data;
        }
        function countcust_alloc_val($table,$field,$type)
        {
            
            $res=$this->db->query("select * from $table c INNER JOIN bank_trans b ON c.type_no=b.trans_no where c.alloc<>-c.amount and c.". $field . " like'". $type . "%'" );
            return $res->num_rows();
       }

       function emplo_allocat($table,$pageno,$field,$type)
        {

            $limit=(($pageno-1) * 10);
            $data=array();

            $res=$this->db->query("select  id,a.alloc,a.tran_date,a.amount,a.account,a.memo from $table a  where a.alloc<>a.amount and a.". $field  . " >0 order by a.id desc limit " . $limit .",". 10);
            foreach ($res->result_array() as $row)
                 {
                     $data[] = $row;
                 }
            return $data;
        }
        function countemp_alloc_val($table,$field,$type)
        {

            $res=$this->db->query("select * from $table a  where a.alloc<>a.amount and a.". $field . " >0" );
            return $res->num_rows();
       }



function get_receipt_voucher($id)
  {

        $data=array();
          $sql = "
     SELECT  cv.cover
    , cc.address
    , cc.postbox
    , c.type
    , ca.amount as alloc_amt
    , c.id as cid
    , cty.cityname
    , ctry.countryname
    , ctry.currencyname
    , ctry.currencycode
    , pspd.fromdate
    , pspd.todate
    , ic.company_name
    , gt.method
    , ct.type_no

FROM
    customer_trans ct
        JOIN cust_allocate ca ON ct.id=ca.from
        JOIN gl_trans gt ON gt.type_no=ct.type_no
        INNER JOIN placing_slip ps ON ps.id=ca.pid
        JOIN placing_slip_premiumdetails  pspd ON pspd.placing_slip_id=ps.id
        JOIN insurance_company ic ON ic.id=pspd.insurance_company_id
        LEFT JOIN covers cv ON cv.id=ps.cover_id
        JOIN customers c ON c.id=ps.customer_id
        JOIN customer_contact cc ON cc.customer_id=c.id
        JOIN city cty ON cty.id=cc.city
        JOIN country ctry ON ctry.id=cc.country

        where ct.id='$id' and ct.account=gt.account";

          //  echo $sql;



          //

         $Q=$this->db->query($sql);

        if ($Q->num_rows() > 0)
         {
             foreach ($Q->result_array() as $row)
             {
                 $data[] = $row;
             }
         }
         $Q->free_result();
         return $data;


   }
function generate_rv($rid)
{
   $res=$this->db->query("SELECT * FROM gl_trans gt JOIN refs r   ON r.id=gt.type_no WHERE amount<0 and  gt.type_no=$rid" );
            return $res->result_array();
}
function generate_pv($rid)
{   
    $res=$this->db->query("SELECT * FROM gl_trans gt JOIN refs r   ON r.id=gt.type_no WHERE amount>0 and  gt.type_no=$rid" );
            return $res->result_array();
}
function show_trans_pslip($refid)
{

   
    $res=$this->db->query("SELECT * FROM placing_slip_refs p JOIN gl_trans  gt ON p.id=gt.type_no JOIN refs r ON p.id=r.id WHERE r.id='$refid'" );
    return $res->result_array();

}


function get_ref_pslip($pid,$type)
{
     $res=$this->db->query("SELECT r.id FROM placing_slip_refs p JOIN refs r ON p.id=r.id  WHERE r.type='$type' and p.pslip_id='$pid' "  );
     return $res->row()->id;

}

function search_trans($pageno,$type,$ref,$rtype,$from,$to)
        {

if($rtype!='all')
{
    $where="r.type=$rtype and";
}
else
{
    $where='';
}
$from = $this->mastermodel->convdatformat($from);
$to = $this->mastermodel->convdatformat($to);
//echo "select sum(gt.amount) as amount , gt.type_no as id,tt.transaction,r.type, r.reference as ref,gt.tran_date from gl_trans gt JOIN refs r ON r.id=gt.type_no  JOIN transaction_types tt ON tt.id=r.type where $where r.reference like '$ref%' and gt.tran_date between '$from' and '$to' and r.type!=6 and gt.amount>0 group by gt.type_no    ";

if($type=='data')
           {

                 $limit=(($pageno-1) * 10);
            $data=array();

            $res=$this->db->query("select fy.closed, sum(gt.amount) as amount,gt.memo,tt.transaction,  gt.type_no as id,r.type, r.reference as ref,gt.tran_date
                                  from gl_trans gt JOIN refs r ON r.id=gt.type_no JOIN transaction_types tt ON tt.id=r.type
                                  JOIN audit_trail au ON au.trans_no=gt.type_no JOIN fiscal_year fy ON fy.id=au.fiscal_year
                                  where $where r.reference like '$ref%' and gt.tran_date between '$from' and '$to'  and gt.amount>0  group by gt.type_no order by gt.type_no desc   limit " . $limit .",". 10);
            foreach ($res->result_array() as $row)
                 {
                     $data[] = $row;
                 }
            return $data;
           }
           else if($type=='count')
           {
             $res=$this->db->query("select fy.closed, sum(gt.amount) as amount,gt.memo,tt.transaction , gt.type_no as id,r.type,
                                    r.reference as ref,gt.tran_date from gl_trans gt JOIN refs r ON r.id=gt.type_no
                                    JOIN transaction_types tt ON tt.id=r.type JOIN audit_trail au ON au.trans_no=gt.type_no JOIN fiscal_year fy ON fy.id=au.fiscal_year
                     where $where r.reference like '$ref%' and gt.tran_date between '$from' and '$to'
                                    and gt.amount>0 group by gt.type_no   ");
             return $res->num_rows();
             }


        }

         function get_main_trail_balance($date1,$date2)
        {

            $data=array();


            $date1=$this->mastermodel->convdatformat($date1);
            $date2=$this->mastermodel->convdatformat($date2);

//            $qry="SELECT sum(if(gt.tran_date>='$date1' and gt.tran_date <='$date2',if(gt.amount<0,gt.amount,0),if(glt.tran_date>='$date1' and glt.tran_date <='$date2',if(glt.amount<0,glt.amount,0),0)))as credit,
//                sum(if(gt.tran_date>='$date1' and gt.tran_date <='$date2',if(gt.amount>0,gt.amount,0),if(glt.tran_date>='$date1' and glt.tran_date <='$date2',if(glt.amount>0,glt.amount,0),0)))as debit,
//                sum(if(gt.tran_date< '$date1',if(gt.amount<0,gt.amount,0),if(glt.tran_date< '$date1',if(glt.amount<0,glt.amount,0),0))) as opencredit,
//                sum(if(gt.tran_date< '$date1',if(gt.amount>0,gt.amount,0),if(glt.tran_date< '$date1',if(glt.amount>0,glt.amount,0),0))) as opendebit,
//                cm.account_name ,cm.account_code as account,cm.id as cgid FROM chart_master cm left join chart_master cp on cp.parent=cm.id
//                left join gl_trans gt ON gt.account=cp.account_code
//                left join gl_trans glt ON glt.account=cm.account_code
//                join char_type ct on ct.id=cm.chart_type
//                where cm.parent=0 group by cgid order by ct.sort,cm.account_code asc";
            
            
                     $qry="SELECT sum(if(gt.amount<0,gt.amount,if(glt.amount<0,glt.amount,0)))as credit,
                sum(if(gt.amount>0,gt.amount,if(glt.amount>0,glt.amount,0)))as debit,
                sum(if(gt.tran_date< '$date1',if(gt.amount<0,gt.amount,0),if(glt.tran_date< '$date1',if(glt.amount<0,glt.amount,0),0))) as opencredit,
                sum(if(gt.tran_date< '$date1',if(gt.amount>0,gt.amount,0),if(glt.tran_date< '$date1',if(glt.amount>0,glt.amount,0),0))) as opendebit,
                cm.account_name ,cm.account_code as account,cm.id as cgid FROM chart_master cm left join chart_master cp on cp.parent=cm.id
                left join gl_trans gt ON gt.account=cp.account_code
                left join gl_trans glt ON glt.account=cm.account_code
                join char_type ct on ct.id=cm.chart_type
                where cm.parent=0 and (gt.tran_date between '$date1' and '$date2' or glt.tran_date between '$date1' and '$date2') group by cgid order by ct.sort,cm.account_code asc";


            
//            $qry="SELECT sum(if(gt.tran_date>='$date1' and gt.tran_date <='$date2',if(gt.amount<0,amount,0),0))as credit,
//
//                sum(if(gt.tran_date>='$date1' and gt.tran_date <='$date2',if(gt.amount>0,amount,0),0))as debit,
//                sum(if(gt.tran_date< '$date1',if(gt.amount<0,gt.amount,0),0)) as opencredit, sum(if(gt.tran_date< '$date1',if(gt.amount>0,gt.amount,0),0)) as opendebit,
//                cm.account_name ,cm.account_code as account,cm.id as cgid FROM chart_master cm inner join chart_master cp on cp.parent=cm.id left join gl_trans gt ON gt.account=cp.account_code
//                join char_type ct on ct.id=cp.chart_type where cm.parent=0 group by cgid order by ct.sort";
          //  echo $qry;
            $res=$this->db->query($qry);

            if ($res->num_rows() > 0)
                 {
                     foreach ($res->result_array() as $row)
                     {
                         $data[] = $row;
                     }
                 }
             $res->free_result();
             return $data;

    }



         function get_trail_balance($date1,$date2,$mainacc="",$rangefrom="",$rangeto="")
        {

            $data=array();
          
           
            $date1=$this->mastermodel->convdatformat($date1);
            $date2=$this->mastermodel->convdatformat($date2);

            $cust="";

            if(!empty($mainacc) && !empty($rangefrom) && !empty($rangeto))
            {
              $cust="where cm.parent='$mainacc' and cm.account_code between '$rangefrom' and '$rangeto'";
            }
            if(!empty($mainacc) && empty($rangefrom) && empty($rangeto))
            {
              $cust="where cm.parent='$mainacc'";
            }
            
            if(!empty($rangefrom) && !empty($rangeto))
            {
                 $cust="where cm.account_code between '$rangefrom' and '$rangeto'";
            }
            
            $qry="SELECT sum(if(gt.tran_date>='$date1' and gt.tran_date <='$date2',if(gt.amount<0,amount,0),0))as credit,

                sum(if(gt.tran_date>='$date1' and gt.tran_date <='$date2',if(gt.amount>0,amount,0),0))as debit,
                sum(if(gt.tran_date< '$date1',if(gt.amount<0,gt.amount,0),0)) as opencredit, sum(if(gt.tran_date< '$date1',if(gt.amount>0,gt.amount,0),0)) as opendebit,
                cm.account_code as account,cm.account_name FROM chart_master cm left join gl_trans gt ON gt.account=cm.account_code 
                $cust group by cm.account_code";
            //echo $qry;
         
            $res=$this->db->query($qry);

            if ($res->num_rows() > 0)
                 {
                     foreach ($res->result_array() as $row)
                     {
                         $data[] = $row;
                     }
                 }
             $res->free_result();
             return $data;

    }


        function get_sub_gl($from,$to,$mainacc,$rangefrom,$rangeto)
        {
             $data=array();


             $date1=$this->mastermodel->convdatformat($from);
             $date2=$this->mastermodel->convdatformat($to);

           
             

            $cust="";

            if(!empty($mainacc) && !empty($rangefrom) && !empty($rangeto))
            {
              $cust="where cm.parent='$mainacc' and cm.account_code between '$rangefrom' and '$rangeto'";
            }
            if(!empty($mainacc) && empty($rangefrom) && empty($rangeto))
            {
              $cust="where cm.parent='$mainacc'";
            }

            if(!empty($rangefrom) && !empty($rangeto))
            {
                 $cust="where cm.account_code between '$rangefrom' and '$rangeto'";
            }

            $qry1="SELECT if(gt.tran_date>='$date1' and gt.tran_date <='$date2',if(gt.amount<0,gt.amount,0),if(glt.tran_date>='$date1' and glt.tran_date <='$date2',if(glt.amount<0,glt.amount,0),0))as credit,
                if(gt.tran_date>='$date1' and gt.tran_date <='$date2',if(gt.amount>0,gt.amount,0),if(glt.tran_date>='$date1' and glt.tran_date <='$date2',if(glt.amount>0,glt.amount,0),0))as debit,
                ifnull(gt.tran_date,glt.tran_date) as tran_date,
                ifnull(gt.memo,glt.memo) as memo,
                ifnull(r1.reference,r2.reference) as reference,
                cm.account_name ,cm.account_code as account,cm.id as cgid FROM chart_master cm
                left join chart_master cp on cp.parent=cm.id
                left join gl_trans gt ON gt.account=cp.account_code
                left join gl_trans glt ON glt.account=cm.account_code
                left join refs r1 on  r1.id= gt.type_no
                left join refs r2 on  r2.id= glt.type_no
                join char_type ct on ct.id=cm.chart_type
                $cust  having reference!=''   order by ct.sort,cm.account_code,tran_date,LEFT(r1.reference,2),LEFT(r2.reference,2),RIGHT(r1.reference ,2),RIGHT(r2.reference,2),reference asc";

//             $qry1="SELECT if(gt.amount<0,amount,0)as credit,
//
//                if(gt.amount>0,amount,0)as debit,gt.tran_date,gt.memo,
//
//                cm.account_code as account,refs.reference,cm.account_name FROM chart_master cm left join gl_trans gt ON gt.account=cm.account_code join refs on refs.id=gt.type_no
//                $cust  and gt.tran_date between '$date1' and '$date2' order by cm.account_code asc";

            // echo $qry1;


             $res=$this->db->query($qry1);

             $data['transdet']=$res->result_array();

             return $data;
            


            
        }

        function get_main_gl($rangefrom,$rangeto,$fromdate,$todate)
        {
             $data=array();


             $date1=$this->mastermodel->convdatformat($fromdate);
             $date2=$this->mastermodel->convdatformat($todate);


             

             $qry1="SELECT if(gt.tran_date>='$date1' and gt.tran_date <='$date2',if(gt.amount<0,sum(gt.amount),0),if(glt.tran_date>='$date1' and glt.tran_date <='$date2',if(glt.amount<0,sum(glt.amount),0),0))as credit,
                if(gt.tran_date>='$date1' and gt.tran_date <='$date2',if(gt.amount>0,sum(gt.amount),0),if(glt.tran_date>='$date1' and glt.tran_date <='$date2',if(glt.amount>0,sum(glt.amount),0),0))as debit,
                ifnull(gt.tran_date,glt.tran_date) as tran_date,
                ifnull(gt.memo,glt.memo) as memo,
                ifnull(r1.reference,r2.reference) as reference,
                cm.account_name ,cm.account_code as account,cm.id as cgid FROM chart_master cm
                left join chart_master cp on cp.parent=cm.id
                left join gl_trans gt ON gt.account=cp.account_code
                left join gl_trans glt ON glt.account=cm.account_code
                left join refs r1 on  r1.id= gt.type_no
                left join refs r2 on  r2.id= glt.type_no
                join char_type ct on ct.id=cm.chart_type
                where cm.parent=0 and cm.account_code between '$rangefrom' and '$rangeto' group by reference order by ct.sort,cm.account_code,tran_date,LEFT(r1.reference,2),LEFT(r2.reference,2),RIGHT(r1.reference ,2),RIGHT(r2.reference,2),reference asc";

                //echo $qry1;

//             $qry1="SELECT if(gt.amount<0,amount,0)as credit,
//
//                if(gt.amount>0,amount,0)as debit,gt.tran_date,gt.memo,
//
//                cm.account_code as account,refs.reference,cm.account_name FROM chart_master cm left join gl_trans gt ON
//                gt.account=cm.account_code join refs on refs.id=gt.type_no
//                where cm.id='$mainacc'  and gt.tran_date between '$date1' and '$date2' ";

             //echo $qry1;


             $res=$this->db->query($qry1);

             $data['transdet']=$res->result_array();

             return $data;




        }

        function get_ageing_report($date,$accval,$type,$cid)
        {
             $data=array();
             
             $acccode=$accval;
             $acctype=$type;


             
             $date=$this->mastermodel->convdatformat($date);
             

             
             $mindate=$this->mintransdate($acccode,$acctype);

              $table='gl_trans';
            
               if($acctype==3)
               {
                  
                   

                   $qry="select customers.code,customers.type,customer_contact.address
    , customer_contact.postbox,country.countryname
    , city.cityname FROM customers
    INNER JOIN  customer_contact ON (customer_contact.customer_id = customers.id)
    INNER JOIN  country
        ON (country.id = customer_contact.country)
    INNER JOIN  city
        ON (city.id = customer_contact.city)  where customers.id='$cid' ";

                  $cdet= $this->db->query($qry);
                  $data['accdet']=$cdet->row();

           //   $table=
            $qry="SELECT
    customers.code
                    
    , gl_trans.account
    , gl_trans.tran_date
    , gl_trans.amount
   
    , placing_slip.cover_id
    , placing_slip.quotation_ref,
      IFNULL(placing_slip.id,0) as placingid
    , covers.cover
    , insurance_company.company_name
   
    , gl_trans.memo
    , gl_trans.account
    , refs.reference,
       psr.type,psr.pslip_id as qid,plcn.policyno
     FROM
     customers
    INNER JOIN  gl_trans
        ON (customers.code = gl_trans.account)
    INNER JOIN refs
        ON (refs.id = gl_trans.type_no)
    left join placing_slip_refs psr on psr.id=refs.id
    LEFT JOIN  placing_slip
        ON (psr.pslip_id = placing_slip.id)
    LEFT JOIN  covers
        ON (placing_slip.cover_id = covers.id)
    left join policynote plcn
           on plcn.quotation_ref=placing_slip.quotation_ref
    LEFT JOIN  placing_slip_premiumdetails
        ON (placing_slip_premiumdetails.placing_slip_id = placing_slip.id)
    LEFT JOIN  insurance_company
        ON (insurance_company.id = placing_slip_premiumdetails.insurance_company_id)
   

              where gl_trans.tran_date between '$mindate' and '$date' and customers.id='$cid' order by gl_trans.tran_date ";
            //echo $qry;
               }

               else if($acctype==1)
               {
                  
                 

                 $qry="Select spd.employeeid as code,spd.name
                , spa.address
                , spa.pobox as postbox
                , country.countryname
                , city.cityname
                from staffpersonaldetails spd
                LEFT JOIN staffpermaddress spa ON spd.id=spa.staffid
                LEFT JOIN  country
                          ON (country.id = spa.country)
                LEFT JOIN  city
                          ON (city.id = spa.city)
               where spd.id='$cid' ";
               
                $cdet= $this->db->query($qry);
                $data['accdet']=$cdet->row();


            $qry="Select

                    spd.employeeid as code
                     
                
                
                , at.tran_date
                , at.amount
               
                , ps.cover_id
                , ps.quotation_ref,
                 IFNULL(ps.id,0) as placingid
                , c.cover
                , ic.company_name
                
                , at.memo
                , at.account
                , r.reference,
                 psr.type,psr.pslip_id as qid,plcn.policyno
                
                   from staffpersonaldetails spd
                LEFT JOIN staffpermaddress spa ON spd.id=spa.staffid
                   INNER JOIN  gl_trans at
                             ON (spd.employeeid = at.account)
                   INNER JOIN refs r
                              ON (r.id = at.type_no)
                    left join placing_slip_refs psr on psr.id=r.id
                    LEFT JOIN  placing_slip ps
                               ON (psr.pslip_id = ps.id)
                 
                    LEFT JOIN  covers c
                             ON (ps.cover_id = c.id)
                left join policynote plcn
                on plcn.quotation_ref=ps.quotation_ref
                  LEFT JOIN  placing_slip_premiumdetails pspd
                          ON (pspd.placing_slip_id = ps.id)
                    LEFT JOIN  insurance_company ic
                                  ON (ic.id = pspd.insurance_company_id)
                
              where at.tran_date  between '$mindate' and '$date'  and spd.id='$cid' order by at.tran_date ";
           
               }

                else if($acctype==2)
               {
                   
                  

                   $qry="select ic.company_code as code
                      
                        , ic.company_name as name
                , ic.address
                , ic.po_box as postbox
                , country.countryname
                , city.cityname
                from insurance_company ic
                   LEFT JOIN  country
                          ON (country.id = ic.country_id)
                LEFT JOIN  city
                          ON (city.id = ic.city_id)
              where ic.id='$cid'  ";

                   $cdet= $this->db->query($qry);
                $data['accdet']=$cdet->row();

            $qry="Select

                                ic.company_code as code
                              
                , ct.account
                , ct.tran_date
                , ct.amount
                
                , ps.cover_id
                , ps.quotation_ref,
                  IFNULL(ps.id,0) as placingid
                , c.cover

                
                
                , ct.memo
                , ct.account
                , r.reference,
                 psr.type,psr.pslip_id as qid,plcn.policyno
                   from insurance_company ic

                   INNER JOIN gl_trans ct
                             ON (ic.company_code = ct.account)
                   INNER JOIN refs r
                              ON (r.id = ct.type_no)
                left join placing_slip_refs psr on psr.id=r.id
                    LEFT JOIN  placing_slip ps
                               ON (psr.pslip_id = ps.id)
                    LEFT JOIN  covers c
                             ON (ps.cover_id = c.id)
                left join policynote plcn
                on plcn.quotation_ref=ps.quotation_ref
                  LEFT JOIN  placing_slip_premiumdetails pspd
                          ON (pspd.placing_slip_id = ps.id)
                   
                LEFT JOIN  country
                          ON (country.id = ic.country_id)
                LEFT JOIN  city
                          ON (city.id = ic.city_id)
              where ct.tran_date  between '$mindate' and '$date' and ic.id='$cid' order by ct.tran_date  ";
           
               }


           $res=$this->db->query($qry);

           $data['transdet']=$res->result_array();



            $query=$this->db->query("select if(SUM(amount)<0,concat(format(abs(sum(amount)),2),' Cr'),concat(format(abs(sum(amount)),2),' Dr')) as amount from $table cr join refs on refs.id=cr.type_no where tran_date <='$date' and account='$acccode'");

           
            
             $bal=$query->row();
             $data['balance']=$bal->amount;

             $curdate=date('Y-m-d');
             $query=$this->db->query("select if(SUM(amount)<0,concat(format(abs(sum(amount)),2),' Cr'),concat(format(abs(sum(amount)),2),' Dr'))  as amount from $table cr join refs on refs.id=cr.type_no where tran_date <='$curdate' and account='$acccode'");

             $bal=$query->row();
             $data['current']=$bal->amount;


             $newdate = strtotime ( '-30 day' , strtotime ( $date ) ) ;
             $newdate = date ( 'Y-m-j' , $newdate );

             $query=$this->db->query("select if(SUM(amount)<0,concat(format(abs(sum(amount)),2),' Cr'),concat(format(abs(sum(amount)),2),' Dr'))  as amount from $table cr join refs on refs.id=cr.type_no where tran_date <='$newdate' and account='$acccode'");
             
             $bal=$query->row();
             $data['lthirty']=$bal->amount;

             $newdate = strtotime ( '-90 day' , strtotime ( $date ) ) ;
             $newdate = date ( 'Y-m-j' , $newdate );

             $query=$this->db->query("select if(SUM(amount)<0,concat(format(abs(sum(amount)),2),' Cr'),concat(format(abs(sum(amount)),2),' Dr'))  as amount from $table cr join refs on refs.id=cr.type_no where tran_date <='$newdate' and account='$acccode'");

             $bal=$query->row();
             $data['lninty']=$bal->amount;

             $newdate = strtotime ( '-180 day' , strtotime ( $date ) ) ;
             $newdate = date ( 'Y-m-j' , $newdate );

             $query=$this->db->query("select if(SUM(amount)<0,concat(format(abs(sum(amount)),2),' Cr'),concat(format(abs(sum(amount)),2),' Dr')) as amount from $table cr join refs on refs.id=cr.type_no where tran_date <='$newdate' and account='$acccode'");
             
             $bal=$query->row();
             $data['loneeighty']=$bal->amount;

             $newdate = strtotime ( '-270 day' , strtotime ( $date ) ) ;
             $newdate = date ( 'Y-m-j' , $newdate );

             $query=$this->db->query("select if(SUM(amount)<0,concat(format(abs(sum(amount)),2),' Cr'),concat(format(abs(sum(amount)),2),' Dr'))  as amount from $table cr join refs on refs.id=cr.type_no where tran_date <='$newdate' and account='$acccode'");

             $bal=$query->row();
             $data['ltseventy']=$bal->amount;

             $newdate = strtotime ( '-365 day' , strtotime ( $date ) ) ;
             $newdate = date ( 'Y-m-j' , $newdate );

             $query=$this->db->query("select if(SUM(amount)<0,concat(format(abs(sum(amount)),2),' Cr'),concat(format(abs(sum(amount)),2),' Dr'))  as amount from $table cr join refs on refs.id=cr.type_no where tran_date <='$newdate' and account='$acccode'");

             $bal=$query->row();
             $data['ltsixty']=$bal->amount;
            
             return $data;
             
        }

               function get_ageingsummary_report($date,$accval,$empid="")
        {
             $data=array();
             $date=$this->mastermodel->convdatformat($date);



             $curdate=date('Y-m-d');



             $newdate = strtotime ( '-30 day' , strtotime ( $date ) ) ;
             $t3date = date ( 'Y-m-j' , $newdate );


             $newdate = strtotime ( '-90 day' , strtotime ( $date ) ) ;
             $t9date = date ( 'Y-m-j' , $newdate );



             $newdate = strtotime ( '-180 day' , strtotime ( $date ) ) ;
             $t180date = date ( 'Y-m-j' , $newdate );



             $newdate = strtotime ( '-270 day' , strtotime ( $date ) ) ;
             $t270date = date ( 'Y-m-j' , $newdate );



             $newdate = strtotime ( '-365 day' , strtotime ( $date ) ) ;
             $t365date = date ( 'Y-m-j' , $newdate );




             $mixedqry="sum(if(ct.tran_date <= '$date',ct.amount,0)) as amount1,
                        sum(if(ct.tran_date <= '$curdate',ct.amount,0)) as amount2,
                        sum(if(ct.tran_date <= '$t3date',ct.amount,0)) as amount3,
                        sum(if(ct.tran_date <= '$t9date',ct.amount,0)) as amount4,
                        sum(if(ct.tran_date <= '$t180date',ct.amount,0)) as amount5,
                        sum(if(ct.tran_date <= '$t270date',ct.amount,0)) as amount6,
                        sum(if(ct.tran_date <= '$t365date',ct.amount,0)) as amount7";

             
               if($accval==1)
               {

               $qry="Select spd.employeeid as code,spd.name
                , spa.address
                , spa.pobox as postbox
                , country.countryname
                , city.cityname
                from staffpersonaldetails spd
                LEFT JOIN staffpermaddress spa ON spd.id=spa.staffid
                LEFT JOIN  country
                          ON (country.id = spa.country)
                LEFT JOIN  city
                          ON (city.id = spa.city)
               where spd.id='$empid' ";

                $cdet= $this->db->query($qry);
                $data['accdet']=$cdet->row();
                  
               $qry="SELECT code,ct.account,c.type,c.id,
                 @cstaff := (select staffid from staffcustomer where customerid = c.id and date <= ct.tran_date order by date desc limit 1) as cStaff,
                 if(@cstaff='$empid', NULL,0) as isStaff,
                sum(if(@cstaff='$empid', if(ct.tran_date <= '$date', ct.amount,0),0)) as amount1,
                sum(if(@cstaff='$empid', if(ct.tran_date <= '$curdate', ct.amount,0),0)) as amount2,
                sum(if(@cstaff='$empid', if(ct.tran_date <= '$t3date', ct.amount,0),0)) as amount3,
                sum(if(@cstaff='$empid', if(ct.tran_date <= '$t9date', ct.amount,0),0)) as amount4,
                sum(if(@cstaff='$empid', if(ct.tran_date <= '$t180date', ct.amount,0),0)) as amount5,
                sum(if(@cstaff='$empid', if(ct.tran_date <= '$t270date', ct.amount,0),0)) as amount6,
                sum(if(@cstaff='$empid', if(ct.tran_date <= '$t365date', ct.amount,0),0)) as amount7,
                ct.tran_date FROM customers c  join gl_trans ct on ct.account=c.code,(select @cstaff:=-1 ) t
                group by code,cStaff  having isStaff IS NULL order by code desc";
                   

//                $qry="Select spd.employeeid as code ,ct.account,spd.name as name,
//
//                    $mixedqry
//
//
//                    from staffpersonaldetails spd
//                    LEFT JOIN staffpermaddress spa ON spd.id=spa.staffid
//                    inner JOIN  gl_trans ct
//                             ON (spd.employeeid = ct.account)
//                    inner join refs on refs.id=ct.type_no
//
//                    group by code ";
                

               }
               else if($accval==2)
               {
                 $data['accdet']="";
                $qry="Select ic.company_code as code ,ic.company_name as name, ct.account,

                    $mixedqry

                    from insurance_company ic
                    inner JOIN gl_trans ct ON (ic.company_code = ct.account)
                    inner join refs on refs.id=ct.type_no
                    group by code ";

               }
               else if($accval==3)
               {
                 $data['accdet']="";
                $qry="Select customers.code, ct.account,customers.type,customers.id,

                     $mixedqry

                     FROM customers
                     inner JOIN  gl_trans ct
                     ON (customers.code = ct.account)
                     inner join refs on refs.id=ct.type_no
                     group by code ";

               }
               
               $res=$this->db->query($qry);
//echo $qry;
               $data['transdet']=$res->result_array();
               return $data;

        }

        function opening_trail_balance($code,$date1,$date2)
        {

            $data=array();
            $date1=$this->mastermodel->convdatformat($date1);
            $qry="SELECT IFNULL(SUM(if(gt.amount<0,gt.amount,0)),0) as opencredit, IFNULL(SUM(if(gt.amount>0,gt.amount,0)),0) as opendebit FROM gl_trans gt  where  gt.account='$code' and  gt.tran_date < '$date1' ";
           
            $res=$this->db->query($qry);
            $data=$res->row() ;
            return $data;
        }

        function opening_maintrail_balance($code,$date1,$date2)
        {

            $data=array();
            $date1=$this->mastermodel->convdatformat($date1);

            $qry="select sum(if(gt.tran_date< '$date1',if(gt.amount<0,gt.amount,0),if(glt.tran_date< '$date1',if(glt.amount<0,glt.amount,0),0))) as opencredit,
                sum(if(gt.tran_date< '$date1',if(gt.amount>0,gt.amount,0),if(glt.tran_date< '$date1',if(glt.amount>0,glt.amount,0),0))) as opendebit
                FROM chart_master cm
                left join chart_master cp on cp.parent=cm.id
                left join gl_trans gt ON gt.account=cp.account_code
                left join gl_trans glt ON glt.account=cm.account_code
                 where  cm.account_code='$code'";



          //  $qry="SELECT IFNULL(SUM(if(gt.amount<0,gt.amount,0)),0) as opencredit, IFNULL(SUM(if(gt.amount>0,gt.amount,0)),0) as opendebit FROM gl_trans gt  where  gt.account='$code' and  gt.tran_date < '$date1' ";
          //echo $qry;
            $res=$this->db->query($qry);
            $data=$res->row() ;
            return $data;
        }

              function get_statement_account($value,$type,$cid,$date1,$date2)
        {

            $data=array();


              $date1=$this->mastermodel->convdatformat($date1);
              $date2=$this->mastermodel->convdatformat($date2);

               
               if($type==3)
               {
                  
           //   $table=

                    $qry="select customers.code,customers.type,customer_contact.address
    , customer_contact.postbox,country.countryname
    , city.cityname FROM customers
    INNER JOIN  customer_contact ON (customer_contact.customer_id = customers.id)
    INNER JOIN  country
        ON (country.id = customer_contact.country)
    INNER JOIN  city
        ON (city.id = customer_contact.city)  where customers.id='$cid' ";

                  $cdet= $this->db->query($qry);
                  $data['accdet']=$cdet->row();
            $qry="SELECT
    customers.code
                   
    , customers.type
    , customer_contact.address
    , customer_contact.postbox
    , gl_trans.account
    , gl_trans.tran_date
    , gl_trans.id as lsid
    , gl_trans.amount
    , placing_slip.cover_id
    , placing_slip.quotation_ref,
      IFNULL(placing_slip.id,0) as placingid,
      placing_slip.currencytype
    , covers.cover
    , insurance_company.company_name
    , country.countryname
    , city.cityname
    , gl_trans.memo
    , refs.reference,
     psr.type,psr.pslip_id as qid,
     plcn.policyno
     FROM
     customers
    INNER JOIN  gl_trans
        ON (customers.code = gl_trans.account)
    INNER JOIN refs
        ON (refs.id = gl_trans.type_no)
    left join placing_slip_refs psr on psr.id=refs.id
    LEFT JOIN  placing_slip
        ON (psr.pslip_id = placing_slip.id)
    LEFT JOIN  customer_contact
        ON (customer_contact.customer_id = customers.id)
    LEFT JOIN  covers
        ON (placing_slip.cover_id = covers.id)
    LEFT JOIN  placing_slip_premiumdetails
        ON (placing_slip_premiumdetails.placing_slip_id = placing_slip.id)
    left join policynote plcn
           on plcn.quotation_ref=placing_slip.quotation_ref
    LEFT JOIN  insurance_company
        ON (insurance_company.id = placing_slip_premiumdetails.insurance_company_id)
    left JOIN  country
        ON (country.id = customer_contact.country)
    left JOIN  city
        ON (city.id = customer_contact.city)

              where gl_trans.tran_date between '$date1' and '$date2' and customers.id='$cid' order by gl_trans.tran_date,lsid";
       //    echo $qry;
               }

               else if($type==1)
               {
                   
                    $qry="Select spd.employeeid as code,spd.name
                , spa.address
                , spa.pobox as postbox
                , country.countryname
                , city.cityname
                from staffpersonaldetails spd
                LEFT JOIN staffpermaddress spa ON spd.id=spa.staffid
                LEFT JOIN  country
                          ON (country.id = spa.country)
                LEFT JOIN  city
                          ON (city.id = spa.city)
               where spd.id='$cid' ";

                $cdet= $this->db->query($qry);
                $data['accdet']=$cdet->row();

            $qry="Select

                    spd.employeeid as code
                     
    , spd.name
    , spa.address
    , spa.pobox as postbox
    , at.account
    , at.tran_date
    , at.amount
    , at.id as lsid
    , ps.cover_id
    , ps.quotation_ref,
      IFNULL(ps.id,0) as placingid,
      ps.currencytype
    , c.cover
    , ic.company_name
    , country.countryname
    , city.cityname
    
    , at.memo
    , at.account
    , r.reference,
     psr.type,psr.pslip_id as qid ,
     plcn.policyno
                   from staffpersonaldetails spd
                LEFT JOIN staffpermaddress spa ON spd.id=spa.staffid
                   INNER JOIN  gl_trans at
                             ON (spd.employeeid = at.account)
                   INNER JOIN refs r
                              ON (r.id = at.type_no)
                 left join placing_slip_refs psr on psr.id=r.id
                    LEFT JOIN  placing_slip ps
                               ON (psr.pslip_id = ps.id)
                    LEFT JOIN  covers c
                             ON (ps.cover_id = c.id)
                  LEFT JOIN  placing_slip_premiumdetails pspd
                          ON (pspd.placing_slip_id = ps.id)
                left join policynote plcn
             on plcn.quotation_ref=ps.quotation_ref
                    LEFT JOIN  insurance_company ic
                                  ON (ic.id = pspd.insurance_company_id)
                LEFT JOIN  country
                          ON (country.id = spa.country)
                LEFT JOIN  city
                          ON (city.id = spa.city)
              where at.tran_date between '$date1' and '$date2' and spd.id='$cid' order by at.tran_date,lsid ";
           //echo $qry;
               }

                else if($type==2)
               {
                   

                    $qry="select ic.company_code as code
                      
                        , ic.company_name as name
                , ic.address
                , ic.po_box as postbox
                , country.countryname
                , city.cityname
                from insurance_company ic
                   LEFT JOIN  country
                          ON (country.id = ic.country_id)
                LEFT JOIN  city
                          ON (city.id = ic.city_id)
              where ic.id='$cid'  ";

                   $cdet= $this->db->query($qry);
                $data['accdet']=$cdet->row();

            $qry="Select

                    ic.company_code as code
                  
    , ic.company_name as name
    , ic.address
    , ic.po_box as postbox
    , ct.account
    , ct.tran_date
    , ct.amount
    , ct.id as lsid
    , ps.cover_id
    , ps.quotation_ref,
      IFNULL(ps.id,0) as placingid,
      ps.currencytype
    , c.cover
    
    , country.countryname
    , city.cityname
    
    , ct.memo
    , ct.account
    , r.reference,
     psr.type,psr.pslip_id as qid,
     plcn.policyno
                   from insurance_company ic
              
                   INNER JOIN gl_trans ct
                             ON (ic.company_code = ct.account)
                   INNER JOIN refs r
                              ON (r.id = ct.type_no)
                   left join placing_slip_refs psr on psr.id=r.id
                    LEFT JOIN  placing_slip ps
                               ON (psr.pslip_id = ps.id)
                    LEFT JOIN  covers c
                             ON (ps.cover_id = c.id)
                  LEFT JOIN  placing_slip_premiumdetails pspd
                          ON (pspd.placing_slip_id = ps.id)
                   left join policynote plcn
           on plcn.quotation_ref=ps.quotation_ref
                    
                LEFT JOIN  country
                          ON (country.id = ic.country_id)
                LEFT JOIN  city
                          ON (city.id = ic.city_id)
              where ct.tran_date between '$date1' and '$date2' and ic.id='$cid' order by ct.tran_date ,lsid";
          
               }


              $res=$this->db->query($qry);

           $data['transdet']=$res->result_array();



             return $data;
    }

 function opening_bal_statementacc($date1,$code,$table)
        {
     
            $data=array();
            
            $qry="SELECT SUM(IF(ct.amount<0,ct.amount,0)) as credit, SUM(IF(ct.amount>0,ct.amount,0)) as debit,cm.account_name  FROM $table ct join chart_master cm ON ct.account=cm.account_code
              where ct.account='$code' and tran_date <'$date1'  group by ct.account ";
              
          
            $res=$this->db->query($qry);
           
            return $res;
        }

  function opening_bal_bankstatementacc($date1,$code,$table)
        {

            $data=array();
            $date1=$this->mastermodel->convdatformat($date1);
            $qry="SELECT SUM(IF(ct.amount<0,ct.amount,0)) as credit, SUM(IF(ct.amount>0,ct.amount,0)) as debit,ba.bank_account_name as account_name  FROM $table ct JOIN bank_accounts ba ON ba.id=ct.bank_act 
              where ba.account_code='$code' and trans_date <'$date1'  group by ba.account_code ";


            $res=$this->db->query($qry);

            return $res;
        }
   function monthdays($someMonth, $someYear)
        {
        return date("t", strtotime($someYear . "-" . $someMonth . "-01"));
        }

        function get_pslip_transno($id,$type)
        {

            $data=array();
            $qry="SELECT reference as ref  FROM placing_slip_refs psr join refs r ON r.id=psr.id  where  psr.pslip_id='$id' and r.type='$type'";
            $res=$this->db->query($qry);
            $data=$res->row()->ref ;
            return $data;
        }
       function fiscaldate_check($date)
       {

            $data=array();
            $date=$this->mastermodel->convdatformat($date);
            $qry="SELECT count(*) as count  FROM mycompany mc JOIn  fiscal_year fy ON fy.id=mc.fyear where '$date' between fy.begin and fy.end and fy.closed=0";
            $res=$this->db->query($qry);
            $data=$res->row()->count ;
            return $data;
       }

       function mintransdate($acccode,$val)
       {

        
           if($val==3)
               {
                 
           $qery="Select  min(tran_date) as tran_date from customer_trans where (abs(amount)!=alloc)
               and account='$acccode' ";
               }
           else if($val==2)
               {

                   $qery="Select  min(tran_date) as tran_date from company_trans where (abs(amount)!=alloc)
                   and account='$acccode'";

               }
           else if($val==1)
               {
                 $qery="Select  min(tran_date) as tran_date from agent_trans where (abs(amount)!=alloc)
                   and account='$acccode'";

               }

           
            $query=$this->db->query($qery);
            $querydate=$query->row();
            $mindate=$querydate->tran_date;
            return $mindate;
       }


       function checkcustomer_trans($refid)
       {
            $qry="SELECT count(*) as count  FROM customer_trans where type_no='$refid'";
            $res=$this->db->query($qry);
            $data=$res->row()->count ;
            return $data;
       }

       function checkemployee_trans($refid)
       {
            $qry="SELECT count(*) as count  FROM agent_trans where type_no='$refid'";
            $res=$this->db->query($qry);
            $data=$res->row()->count ;
            return $data;
       }

       function findaccountbyno($code)
         {
           $res=$this->db->query("SELECT chart_master.account_code,chart_master.account_name FROM `chart_master` where chart_master.account_code='$code'");
          $result=$res->row();

           if($res->num_rows() > 0)
           {
             $accountno= $result->account_code;
             //$accountname_id=$result->id;
             $account_name=$result->account_name;

             $resultset=$accountno.'~'.$account_name;
           }
           else
           {
               $resultset="";
           }

           return $resultset;
           var_dump($resultset);die();

         }
}
?>

bypass 1.0, Devloped By El Moujahidin (the source has been moved and devloped)
Email: contact@elmoujehidin.net