<?php
error_reporting(0);
class User extends CI_Controller {

public function __construct(){

        parent::__construct();
           $this->load->model('page_model');
  			$this->load->helper('url');
  	 		$this->load->model('user_model');
        $this->load->library('session');
        $this->load->model('department_model');
        $this->load->helper(array('form', 'url'));
         $this->load->library('table');
       $this->load->library('pagination');
       $this->load->helper('Login');
       is_logged_in();
      $this->load->database();

}

public function index()
{
  $user_id=$this->session->userdata('user_id');   
 if($user_id){
      redirect('user/dash', 'refresh');
 }
    else{
       $this->load->view("login.php"); 
    }

}
      public function forgot(){
    $email=$this->input->post('forgotemail');
    $pass=$this->input->post('forgotpass');
          $code=$this->input->post('code');
    $userid=$this->user_model->forgotten_user($code);
        $data=array('user_password'=>md5($pass), );
       if($userid){
            $this -> db -> where('user_id', $userid );
        $this -> db -> update('user',$data);
             redirect('user/login_view', 'refresh');
       }
        else{
             $this->session->set_flashdata('error_msg', 'Wrong code  number');
            $this->load->view("login.php");
        }
    }
     public function forgotpass(){
         
    $email=$this->input->post('email');
    $email_check=$this->user_model->forgot_email_check($email);
    
     }
public function register_user(){

      $user=array(
      'first_name'=>$this->input->post('fname'),
      'last_name'=>$this->input->post('fname'),
      'user_email'=>$this->input->post('email'),
      'user_password'=>md5($this->input->post('user_password')),
   
      'buisness_type'=>$this->input->post('buisness_type')
        );
        

$email_check=$this->user_model->email_check($user['user_email']);

if($email_check){
  $this->user_model->register_user($user);
  $this->session->set_flashdata('success_msg', 'Registered successfully.Now login to your account.');
  redirect('user/login_view');

}
else{

  $this->session->set_flashdata('This email  already exists.');
  redirect('user');


}

}

public function login_view(){

$this->load->view("login.php");

}



function login_user(){
  $user_login=array(

  'user_email'=>$this->input->post('user_email'),
  'user_password'=>md5($this->input->post('user_password'))

    );

    $data=$this->user_model->login_user($user_login['user_email'],$user_login['user_password']);
      if($data)
      {
        $this->session->set_userdata('user_id',$data['user_id']);
        $this->session->set_userdata('user_email',$data['user_email']);
        $this->session->set_userdata('first_name',$data['first_name']);
          $this->session->set_userdata('last_name',$data['last_name']);
        

        $this->load->view('user_profile.php');

      }
      else{
        $this->session->set_flashdata('error_msg', 'Error occured,Try again.');
        $this->load->view("login.php");

      }


}

function user_profile(){

$this->load->view('user_profile.php');

}
public function logout(){

  $this->session->sess_destroy();
  redirect('user/login_view', 'refresh');
}

     public function changeprofile(){
         $id= $this->input->post('id');
      
           $profile=$this->user_model->profile($id);
        foreach($profile as $key=>$item)
          $c_email= $this->input->post('c_email');
          $file= $this->input->post('file');
        $n_email= $this->input->post('n_email');
         $c_pass= $this->input->post('c_pass');
        $n_pass= $this->input->post('n_pass');
        $old_pass= md5($this->input->post('old'));
       
          $c_pass= $this->input->post('c_pass');
        if($this->input->post('n_email') == $this->input->post('c_email') and $n_email and $c_email ){
            $n_email= $this->input->post('n_email');
        }
        else{
            $n_email=$item->user_email;
           
        }
       if($this->input->post('n_pass') == $this->input->post('c_pass') and $n_pass and $c_pass and $old_pass== $item->user_password and $old_pass and $old_pass==$item->user_password ){
            $n_pass= md5($this->input->post('n_pass')); 
            
        }
        else{
            $n_pass=$item->user_password;
            
            $result=array('oldpass'=>$old_pass,);
              echo json_encode($result);
           
        }
        if($this->input->post('file') and $file){
            $file= $this->input->post('file');
            
             
        }
        else{
            $file=$item->logo;
        }
        
     
        $fname= $this->input->post('fname');
         $lname= $this->input->post('lname');
        $email= $this->input->post('email');
    
       
         $pass= $this->input->post('pass');
       
       
        
      
        $data=array(
             
                'user_password'=>($n_pass),
            );
   if($this->input->post('n_pass') == $this->input->post('c_pass') and $n_pass and $c_pass and $old_pass== $item->user_password and $old_pass and $old_pass==$item->user_password  ){
          $this -> db -> where('user_id', $id );
        $this -> db -> update('user',$data); 
        $result=array('oldpass'=>$old_pass,);
              echo json_encode($result);
   }
    else if ($n_email==$c_email and $n_email and $c_email){
        $newdata=array(
           
                'user_email'=>$n_email,);
        $this -> db -> where('user_id', $id );
        $this -> db -> update('user',$newdata); 
        
    }    
     else{
         $userdata=array('first_name'=>$fname,
                'last_name'=>$lname,
                'logo'=>$file,);
             $this -> db -> where('user_id', $id );
        $this -> db -> update('user',$userdata);
        
     }   
            
     
    }
                
    public function profileupdate(){
         $config['upload_path'] = FCPATH.'/uploads/';
        $config['allowed_types'] = '*';
        $config['max_filename'] = '255';
        $config['encrypt_name'] = TRUE;
        $config['max_size'] = '10000000'; //1 MB

     $target_path = $config['upload_path'];
    $ext = explode('.',( $_FILES['file']['name']));
    $target_path = $target_path  .( $_FILES['file']['name']);
    if(move_uploaded_file($_FILES['file']['tmp_name'], $target_path)) {
        echo json_encode ("The file has been uploaded successfully <br />");
    } else{
        echo json_encode ("There was an error uploading the file, please try again! <br />");
    }
    }
    
    public function profile(){
        $id=$this->session->userdata('user_id');
$data['profile']=$this->user_model->profile($id);
      $profile=$this->user_model->profile($id);
       
$this->load->view("profile.php",$data);

}
    public function activesalepagination(){
        $b_type=$this->department_model->get_buisness_type();
         $tabid=$this->input->post('saletabid');
        $page=$this->input->post('salepage');
        $pagination=$this->db->query("select * from pagination where page='$page' and buisness_id='$b_type' ");
          foreach ($pagination->result() as $key => $value)
              $value=$value->page;
        $data=array('page'=>$page,
                   'active'=>$tabid,
                   'buisness_id'=>$b_type,);
        if($value){
           
            $this -> db -> where('page', $page );
        $this -> db -> update('pagination',$data);
        }
        else{
           $this -> db ->insert('pagination',$data); 
        }
    
     
        $result=array('success'=>$tabid,
                    );
        echo json_encode($result);
	
		/* $page = ($this->uri->segment(4)) ? ($this->uri->segment(4) - 1) : 0;
					 $data['tabpagi'] = $active;
		
		    $config['base_url'] = base_url().'user/search/'.$active;
		$config['total_rows'] = $getTotalCustomers;
		$config['per_page'] = $perPage;
		$config['uri_segment'] = 4;
		$config['use_page_numbers'] = true;
		
		
		//Pagination Container tag
		$config['full_tag_open'] = '<div style="margin:50px 30%;">';
		$config['full_tag_close'] = '</div>';
		
		//First and last Link Text
		$config['first_link'] = 'First';
		$config['last_link'] = 'Last';
		
		//First tag 
		$config['first_tag_open'] = '<span class="pagination-first-tag">';
		$config['first_tag_close'] = '</span>';
		
		//Last tag 
		$config['last_tag_open'] = '<span class="pagination-last-tag">';
		$config['last_tag_close'] = '</span>';
		
		
		//Next and Prev Link
		$config['next_link'] = 'Next';
		$config['prev_link'] = 'Prev';
		
		
		//Next and Prev Link Styling
		$config['next_tag_open'] = '<span class="pagination-next-tag">';
		$config['next_tag_close'] = '</span>';
		
		$config['prev_tag_open'] = '<span class="pagination-prev-tag">';
		$config['prev_tag_close'] = '</span>';
		
		
		//Current page tag
		$config['cur_tag_open'] = '<strong class="pagination-current-tag">';
		$config['cur_tag_close'] = '</strong>';

		
		$config['num_tag_open'] = '<span class="pagination-number">';
		$config['num_tag_close'] = '</span>';



		$this->pagination->initialize($config);
	
		
		$page =  $this->pagination->create_links();
        $result=array('pagi'=>$page,
                     'id'=>$tabid,);
        echo json_encode($result);*/
    }
    public function activepagination(){
         $b_type=$this->department_model->get_buisness_type();
        $tabid=$this->input->post('tabid');
        $page=$this->input->post('page');
        
        $pagination=$this->db->query("select * from pagination where page='$page' and buisness_id='$b_type' ");
          foreach ($pagination->result() as $key => $value)
              $value=$value->page;
        $data=array('page'=>$page,
                   'active'=>$tabid,
                   'buisness_id'=>$b_type,);
        if($value){
            $this -> db -> where('page', $page );
        $this -> db -> update('pagination',$data);
        }
        else{
           $this -> db ->insert('pagination',$data); 
        }
       $result=array('tabid'=>$tabid);
         echo json_encode($result);
    /*  $active = $this->page_model->activepage();
      $getTotalCustomers = $this->page_model->getTotalresult($tabid);
         $limit=$this->db->query("select page_limit from page_limit where page='dash' ");
          foreach ($limit->result() as $key => $value)
              $value=$value->page_limit;
          
        if($value){
          $perPage = $value;  
        }
        else{
          $perPage = 2;  
        }
		
		 $page = ($this->uri->segment(4)) ? ($this->uri->segment(4) - 1) : 0;
					 $data['tabpagi'] = $active;
		
		    $config['base_url'] = base_url().'user/dash/'.$active;
		$config['total_rows'] = $getTotalCustomers;
		$config['per_page'] = $perPage;
		$config['uri_segment'] = 4;
		$config['use_page_numbers'] = true;
		
		
		//Pagination Container tag
		$config['full_tag_open'] = '<div style="margin:50px 30%;">';
		$config['full_tag_close'] = '</div>';
		
		//First and last Link Text
		$config['first_link'] = 'First';
		$config['last_link'] = 'Last';
		
		//First tag 
		$config['first_tag_open'] = '<span class="pagination-first-tag">';
		$config['first_tag_close'] = '</span>';
		
		//Last tag 
		$config['last_tag_open'] = '<span class="pagination-last-tag">';
		$config['last_tag_close'] = '</span>';
		
		
		//Next and Prev Link
		$config['next_link'] = 'Next';
		$config['prev_link'] = 'Prev';
		
		
		//Next and Prev Link Styling
		$config['next_tag_open'] = '<span class="pagination-next-tag">';
		$config['next_tag_close'] = '</span>';
		
		$config['prev_tag_open'] = '<span class="pagination-prev-tag">';
		$config['prev_tag_close'] = '</span>';
		
		
		//Current page tag
		$config['cur_tag_open'] = '<strong class="pagination-current-tag">';
		$config['cur_tag_close'] = '</strong>';

		
		$config['num_tag_open'] = '<span class="pagination-number">';
		$config['num_tag_close'] = '</span>';



		$this->pagination->initialize($config);
	
		
		$page =  $this->pagination->create_links();
        $result=array('page'=>$page,
                     'id'=>$tabid,);
        echo json_encode($result);*/
    }
    public function yearfilter(){
        $year=$this->input->post('year');
        $data['graphdata']=$this->department_model->graph($year);
        echo json_encode($data['graphdata']);exit;
    }
    public function dash(){
       
        
      $b_type=$this->department_model->get_buisness_type();
      

       $trbank=$this->department_model->tr_bank();
       $cashbank=$this->department_model->cash_bank();
     
        $data['from']=$this->input->post('from');
        
        $data['to']=$this->input->post('to');
        $data['b_type']=$this->department_model->get_buisness_type();
        $data['calculate']=$this->department_model->get_amount_details();
        
        $data['bankamount']=$this->department_model->get_bankamount();
        //print_r($data);exit;
        $data['allbankamount']=$this->department_model->get_bankamount_mark('bankamount');
        //print_r($data['markbank']);
         //print_r($data);exit;
        $data['bankcash']=$this->department_model->get_cashbankamount($cashbank);
        $data['banktr']=$this->department_model->get_trbankamount($trbank);
        
         $data['totalloan']=$this->department_model->get_totalloanamount();
        
        $data['unpaidpurchases']=$this->department_model->get_unpaidpurchasesbankamount();
        //print_r($data);exit;
         $data['unpaidwholesale']=$this->department_model->get_unpaidwholesalebankamount();
        
         $data['payloan']=$this->department_model->get_totalpayloanamount();
        $data['totalprofit']=$this->department_model->get_totalprofitamount();
        $data['graphdata']=$this->department_model->graph();
        //print_r($data);exit;
         if($this->input->post('tabid')!=null)
        $data['tabid'] = $this->input->post('tabid');

      $this->load->view("dash.php",$data);
    }
    
    public function ajax_sale_purchases()
{
    $bank_id = $this->input->post('bank_id');
    $b_type=$this->department_model->get_buisness_type();
    $buisness_id = $b_type;
    $start   = $this->input->post('start');
    $length  = $this->input->post('length');
    $search  = $this->input->post('search')['value'];
    $from    = $this->input->post('from');
    $to      = $this->input->post('to');
    $this->db->from('sale_purchases');
    $this->db->where('bank_id', $bank_id);
      if (!empty($from)) {
        $fromDate = DateTime::createFromFormat('d/m/Y', $from)->format('Y-m-d');
        $this->db->where('date >=', $fromDate);
    }
    if (!empty($to)) {
        $toDate = DateTime::createFromFormat('d/m/Y', $to)->format('Y-m-d');
        $this->db->where('date <=', $toDate);
    }   
    $this->db->where('status', 1);
    $this->db->where('buisness_id', $buisness_id);
    if (!empty($search)) {
        $this->db->group_start();
        $this->db->like('type', $search);
        $this->db->group_end();
    }
    $recordsTotal = $this->db->count_all_results('', FALSE);
    $this->db->limit($length, $start);
    $data = $this->db->get()->result();

    $balance = 0;
    $result = [];
    foreach ($data as $row) {
        $balance += ($row->amount - $row->pur_amount);
        $result[] = [
            date('d F Y', strtotime($row->date)),
            ucfirst($row->type),
            number_format($row->pur_amount, 2).' €',
            number_format($row->amount, 2).' €',
            number_format($balance, 2).' €'
        ];
    }

    echo json_encode([
        "draw" => intval($this->input->post('draw')),
        "recordsTotal" => $recordsTotal,
        "recordsFiltered" => $recordsTotal,
        "data" => $result
    ]);
}

    public function getTransactions($bank_id, $start, $length, $search, $from, $to) {
        $this->db->select("date, type, pur_amount, amount");
        $this->db->from("sale_purchases");
        $this->db->where("bank_id", $bank_id);
        $this->db->where("status", 1);

        if (!empty($from)) {
            $fromDate = DateTime::createFromFormat('d/m/Y', $from)->format('Y-m-d');
            $this->db->where("date >=", $fromDate);
        }
        if (!empty($to)) {
            $toDate = DateTime::createFromFormat('d/m/Y', $to)->format('Y-m-d');
            $this->db->where("date <=", $toDate);
        }
        if (!empty($search)) {
            $this->db->group_start()
                     ->like("type", $search)
                     ->group_end();
        }

        $recordsTotal = $this->db->count_all_results('', FALSE);

        if ($length != -1) {
            $this->db->limit($length, $start);
        }

        $data = $this->db->get()->result_array();
        return [$data, $recordsTotal];
    }
    public function ajax_transactions() {
    $bank_id = $this->input->post('bank_id');
    $from    = $this->input->post('from');
    $to      = $this->input->post('to');
    $start   = $this->input->post('start');
    $length  = $this->input->post('length');
    $search  = $this->input->post('search')['value'];
    $draw    = $this->input->post('draw');

    $this->load->model('Transactions_model');
    list($data, $recordsTotal) = $this->getTransactions(
        $bank_id, $start, $length, $search, $from, $to
    );

    $balance = 0;
    $formatted = [];
    foreach ($data as $row) {
        $balance += ($row['amount'] - $row['pur_amount']);
        $formatted[] = [
            date('d F Y', strtotime($row['date'])),
            ucfirst($row['type']),
            number_format($row['pur_amount'], 2) . ' €',
            number_format($row['amount'], 2) . ' €',
            number_format($balance, 2) . ' €'
        ];
    }

    echo json_encode([
        "draw" => intval($draw),
        "recordsTotal" => $recordsTotal,
        "recordsFiltered" => $recordsTotal,
        "data" => $formatted
    ]);
}

      public function alltrans(){
      $b_type=$this->department_model->get_buisness_type();
      

       $trbank=$this->department_model->tr_bank();
       $cashbank=$this->department_model->cash_bank();
     
        $data['from']=$this->input->post('from');
        $data['to']=$this->input->post('to');
        $data['b_type']=$this->department_model->get_buisness_type();
        $data['calculate']=$this->department_model->get_amount_details();
        $data['bankamount']=$this->department_model->get_bankamount();
        $data['markbank']=$this->department_model->get_bankamount_mark();
        $data['bankcash']=$this->department_model->get_cashbankamount($cashbank);
        $data['banktr']=$this->department_model->get_trbankamount($trbank);
         $data['unpaidpurchases']=$this->department_model->get_unpaidpurchasesbankamount();
         $data['unpaidwholesale']=$this->department_model->get_unpaidwholesalebankamount();
        $data['totalprofit']=$this->department_model->get_totalprofitamount();
         if($this->input->post('tabid')!=null)
        $data['tabid'] = $this->input->post('tabid');

      $this->load->view("alltrans.php",$data);
    }
public function value(){
     
    $b_type=$this->department_model->get_buisness_type();
    $bankrowvalue=$this->department_model->bank_row();
 
    $edit_id=$this->input->post('edit_id');
    $date=$this->input->post('date');
   // $date=date('Y-m-d');
     $data_bank =  $this->input->post('select_bank');
      $data_value = $this->input->post('bank_card');
   $cash=$this->input->post('cash');
   $date=$this->input->post('date');
    $bank=$this->input->post('bank_select');
     $saletype=$this->department_model->get_tab_type($this->input->post('select'));
   $checked=$this->input->post('checked');
    $bankcount=$this->department_model->get_bankcount();
   
    $salevalue=array();
       //echo $this->input->post('total');exit;
      
      $a=(serialize($data_value));
      if($data_bank and !$edit_id ){
      $datasale = array(
  //'user_id' => $this->input->post('id'),
   //'date' => date("Y-m-d H:i:s"),
   'date' => $date,
   'type' => $this->input->post('select'),
    'bank_info' => $a,
    'total' => $this->input->post('total'),
    'status' => 1,
    'buisness_type' => $b_type,
  );  
     
 
    $this->db->insert('sale',$datasale);
    $saleid=$this->db->insert_id();
    
      
    foreach ($data_value as $bank_id => $bank_value){
               
     if ($bank_value >0 ){
        $this->db->set('record',1,false);
        $this -> db -> where('id', $bank_id );
        $this -> db -> update('bank_name'); 
              
                   $saleall_detail =array(
                   'date' => $date,
                   'type' => $saletype,
                   'sale_id' =>$saleid,
                   'sale_type' =>'bank',
                   'bank_id'=>$bank_id,
                   'amount'=>$bank_value,
                   'status'=>1,
                  'buisness_id'=>$b_type,
               );
          
        
          
          $this->db->insert('sale_details',$saleall_detail); 
         $this->db->insert('sale_purchases',$saleall_detail); 
          
         }
             
            
        }
                 
               redirect('user/search', 'refresh');
         }
 
   if($data_bank  and $edit_id ){
     
           $data = array(
          
          'date' => $this->input->post('date'),
          'type' => $this->input->post('select'),
          'bank_info' => $a,
           'total' => $this->input->post('total'),
            'status'=>1,  
             
            'buisness_type'=>$b_type,
                );
           $this -> db -> where('id', $edit_id);
           $this->db->update('sale',$data);
 
       $value=array();
        $sale_detail=array();
      
       if($data_bank ){
            
    foreach ($data_value as $bankup_id => $bankup_value){
               
     if ($bankup_value>0){
         
        $this->db->set('record',1,false);
        $this -> db -> where('id', $bank_id );
        $this -> db -> update('bank_name'); 
           
        
              
              $saleup_detail[] =array(
                   'date' => $date,
                   'type' => $saletype,
                   'sale_id' =>$edit_id,
                   'sale_type' =>'bank',
                   'bank_id'=>$bankup_id,
                   'amount'=>$bankup_value,
                   'status'=>1,
                  'buisness_id'=>$b_type,
               );
  
        
         }
                 
        $this -> db -> where('sale_id', $edit_id);
        $this -> db -> delete('sale_purchases');   
          
        }
    
          if($saleup_detail){
            $this->db->insert_batch('sale_purchases',$saleup_detail);  
          }
           
        
       }  
       
       
           $url = 'user/search';
            echo'<script>
            window.location.href = "'.base_url().$url.'";
            </script>';
  
               redirect('user/search', 'refresh');
         }
 
      redirect('user/search', 'refresh');
    }
   
        public function  dashtabfilter(){
             $tabid=$this->input->post('tabid');
            $text=$this->input->post('text');
            
            
             $calculate=$this->department_model->get_tab_total($tabid,$text);
             echo json_encode($calculate);
      
        }
    public function totalsale(){
        
        $filter=$this->input->post('uristring');
        $tab=$this->input->post('activetab');
       $calculate=$this->department_model->get_sale_total($filter,$tab);
       echo json_encode($calculate);
}

    public function search($offset = 0){
        $b_type=$this->department_model->get_buisness_type();
        $active = $this->uri->segment(3);
        $filterac=$this->input->post('tabsearchpagi');
       
      
        if($filterac){
          $active=$filterac;  
        }
       
        if(!$active and  !$filterac){
            $active=0;
            
        }
     
           $getTotalsale = $this->page_model->getTotalsale($active); 
    
        
        
                         $data['cash']=0.0;
                          $data['tr']=0.0;
                          $data['card']=0.0;
                          $data['total']=0.0;
    
  
		
      
         $pagelimit=$this->db->query("select * from page_limit where page='search' and buisness_id='$b_type' ");
          foreach ($pagelimit->result() as $key => $pagevalue)
               $limited=$pagevalue->page_limit;
       
        if($limited){
          $perPage = $limited;  
        }
        else{
          $perPage = 2;  
        }
		
		 $page = ($this->uri->segment(4)) ? ($this->uri->segment(4) - 1) : 0;
					 $data['tabpagi'] = $active;
		//$data["page_results"] = $this->page_model->getCustomersByLimit($perPage, $page*$perPage);
		
		
		
		//Basic configuration 
		    $config['base_url'] = base_url().'user/search/'.$active;
		$config['total_rows'] = $getTotalsale;
		$config['per_page'] = $perPage;
		$config['uri_segment'] = 4;
		$config['use_page_numbers'] = true;
		
		
		//Pagination Container tag
		


		$this->pagination->initialize($config);
	
		
	 $data["pagination_link"] =  $this->pagination->create_links();

        $data['deptlist'] = $this->department_model->get_department_list($perPage, $page*$perPage,$active);           
        $data['saletype'] = $this->department_model->get_saletype_list();     

       $data['id']='';
        $data ['id']=$this->uri->segment(3);
         $data['id_post'] = $this->input->post('uristring');
        $data['from']='';
        $data['to']='';
         
         $data['limit']=$perPage;
         $data['start']=$page*$perPage;
        $data['from']=$this->input->post('from');
        $data['to']=$this->input->post('to');
     
        $data['pagination'] = $this->pagination->create_links(); 
      
        $data['tabsearch']=$this->input->post('tabsearch');
        $data['tabtype'] = $this->department_model->get_tab_type($active);   
        
        $data['bb']=$this->input->post('from');
        $this->load->view("dashboard.php",$data);
       
        
    }
    public function delete(){

 
        $id_post = $this->input->post('uristring'); 
        if($id_post){
          $this->db->set('status',0,false);
        $this -> db -> where('id', $id_post);
        $this -> db -> update('sale');
         
                 $this->db->set('status',0,false);
        $this -> db -> where('sale_id', $id_post);
        $this -> db -> update('sale_details');
          
            
                 $this->db->set('status',0,false);
        $this -> db -> where('sale_id', $id_post);
        $this -> db -> update('sale_purchases');
            
        }
        
        
    $b_type= $this->department_model->get_buisness_type();
       
       $status=1;
        $type='';
            $cash_sale=0.0;
            $bank_card=0.0;
            $ticket=0.0;
            $total=0.0;
        $limit=0;
          $bank[1]=0;
        $bank[2]=0;
        $bank[3]=0;
        $bank[4]=0;
        $bank[5]=0;
        $bank[6]=0;
        $limit=$this->db->query("select page_limit from page_limit");
          foreach ($limit->result() as $key => $value)
            $value=$value->page_limit;  
        $limit=$value-1;
         $id_post = $this->input->post('uristring'); 
        
        $id_post1 = $this->input->post('type');
        
        $query = $this->db->query("SELECT * FROM bank_name where status=1 and record=1 and buisness_id='$b_type' ");
        $row= $query->num_rows();
 
       for ($i = 1; $i <=$row; ++$i) {
            $type1=$this->db->query("select * from sale_purchases   where status=1 and bank_id='$i' and  sale_id  order by id   limit ".$limit." ",false);
          foreach ($type1->result() as $key => $value1){
           
              $bank[$i]+=$value1->amount;
              $total+=$value1->amount;
              
          }
            
        }
         /* $type1=$this->db->query("select * from sale_purchases   where status=1 and bank_id=1 and  sale_id  ");
          foreach ($type1->result() as $key => $value1){
           
              $bank1+=$value1->amount;
              
          }
        $type2=$this->db->query("select * from sale_purchases   where status=1 and bank_id=2 and  sale_id  ");
          foreach ($type2->result() as $key => $value2){
           
              $bank2+=$value2->amount;
              
          }
        $type3=$this->db->query("select * from sale_purchases   where status=1 and bank_id=3 and  sale_id  ");
          foreach ($type3->result() as $key => $value3){
           
              $bank3+=$value3->amount;
              
          }
        $type4=$this->db->query("select * from sale_purchases   where status=1 and bank_id=4 and  sale_id  ");
          foreach ($type4->result() as $key => $value4){
           
              $bank4+=$value4->amount;
              
          }
        $type5=$this->db->query("select * from sale_purchases   where status=1 and bank_id=5 and  sale_id  ");
          foreach ($type5->result() as $key => $value5){
           
              $bank5+=$value5->amount;
              
          }
        $type6=$this->db->query("select * from sale_purchases   where status=1 and bank_id=6 and  sale_id  ");
          foreach ($type6->result() as $key => $value6){
           
              $bank6+=$value6->amount;
              
          }*/
          $result = array(
            'type' => $type,
              'bank' => $bank,
             
              'id'=>$id_post,
              'total'=>$total,
              
        );
     
  echo json_encode($result);
         
    
 
    }
  
    public function update(){
        $id_post=$this->input->post('value_id');
        $data = array(
  'user_id' => $this->input->post('id'),
   'date' => $this->input->post('date'),
   'type' => $this->input->post('type'),
   'cash_sale' => $this->input->post('cash'),
   'bank_card' => $this->input->post('bank'),
   'ticket' => $this->input->post('ticket'),
   'total' => $this->input->post('total'),
  );
         $this -> db -> where('id', $id_post);
        $this -> db -> update('sale',$data);
        redirect('user/search', 'refresh');
    }
    public function type(){
        $config['upload_path'] = FCPATH.'/uploads/';
		$config['allowed_types'] = 'gif|jpg|png';
		

		$this->load->library('upload', $config);
        $data = array('upload_data' => $this->upload->data());
         $data = array(
  'type' => $this->input->post('type'),
   'address' => $this->input->post('adress'),
   'number' => $this->input->post('number'),
  
  );
  $this->db->insert('type', $data);
redirect('user/search', 'refresh');
    }
   public function mypag(){
    $this->load->view("mypag.php");
    }
       public function setting(){
        $page['page']=$this->uri->segment(3);
       $this->load->view("seting.php",$page); 
    }
    public function pagelimit(){
        $b_type= $this->department_model->get_buisness_type();
       $page= $this->input->post('limit');
        $limit=$this->db->query("select * from page_limit where page='$page' and buisness_id='$b_type'");
          foreach ($limit->result() as $key => $value)
              $pagelimit=$value->page_limit;
        $result=array('limit'=>$pagelimit);
        echo json_encode($result);
    }
      public function page_set(){
           $b_type= $this->department_model->get_buisness_type();
            $page=$this->input->post('page');
         
          $data = array(
              'page_limit' => $this->input->post('seting'),
              'page'=>$page,
              'buisness_id'=>$b_type,
              );
           $limit=$this->db->query("select * from page_limit where page='$page' and buisness_id='$b_type'");
          foreach ($limit->result() as $key => $value)
              $url=$value->page;
          if($url){
             $this -> db -> where('page', $page);
             $this -> db -> update('page_limit',$data);  
          }
         else{
            $this -> db -> insert('page_limit',$data); 
         }
          
          
          if($page=='dash'){
              redirect('user/dash', 'refresh'); 
          }
          else if($page=='search'){
              redirect('user/search', 'refresh'); 
          }
       else if($page=='home'){
              redirect('purchases/home', 'refresh'); 
          }
          else if($page=='whome'){
              redirect('worker/home', 'refresh'); 
          }
          else if($page=='expense'){
              redirect('expense/search', 'refresh'); 
          }
          else if($page=='wholesale'){
              redirect('sale/wholesale', 'refresh'); 
          }
          else if($page=='transfer'){
              redirect('balance/transfer', 'refresh'); 
          }
           else if($page=='loan'){
              redirect('loan/create', 'refresh'); 
          }
            else if($page=='payloan'){
              redirect('pay_loan/create', 'refresh'); 
          }
      }
    
    public function bu_edit(){
         $id_post = $this->input->post('uristring');
        
        $buisnesstype=$this->department_model->get_buisness_name($id_post);
        
        $result=array(
        'type'=>$buisnesstype);
        echo json_encode($result);
    }
     public function bu_delete(){
         
               
         $id_post = $this->input->post('uristring');
         $this -> db -> where('buisness_id', $id_post);
        $this -> db -> delete('sale_details');
         $this -> db -> where('buisness_id', $id_post);
        $this -> db -> delete('sale_purchases');
         $this -> db -> where('buisness_id', $id_post);
        $this -> db -> delete('purchases_details');
         $this -> db -> where('buisness_type', $id_post);
        $this -> db -> delete('sale');
         $this -> db -> where('buisness_type', $id_post);
         $this -> db -> delete('sale_type');
         $this -> db -> where('buisness_type', $id_post);
         $this -> db -> delete('purchases');
          $this -> db -> where('buisness_type', $id_post);
         $this -> db -> delete('purchases_type');
          $this -> db -> where('buisness_type', $id_post);
          $this -> db -> delete('expense');
          $this -> db -> where('buisness_type', $id_post);
           $this -> db -> delete('expense_type');
          $this -> db -> where('buisness_type', $id_post);
         $this -> db -> delete('wholesale');
          $this -> db -> where('buisness_type', $id_post);
         $this -> db -> delete('wholesale_category');
          $this -> db -> where('buisness_type', $id_post);
          $this -> db -> delete('worker');
         $this -> db -> where('buisness_type', $id_post);
         $this -> db -> delete('worker_name');
          $this -> db -> where('buisness_id', $id_post);
        $this -> db -> delete('buisness_type'); 
          $this -> db -> where('id', $id_post);
        $this -> db -> delete('type');
        /*  $this -> db -> where('id', $id_post);
        $this -> db -> delete('pagination');*/
          $this -> db -> where('buisness_id', $id_post);
        $this -> db -> delete('page_limit');
         $this -> db -> where('buisness_id', $id_post);
        $this -> db -> delete('bank_name');
         $this -> db -> where('buisness_id', $id_post);
         $this -> db -> delete('address_setting');
         $this -> db -> where('buisness_id', $id_post);
          $this -> db -> delete('invoice');
         $this -> db -> where('buisness_type', $id_post);
          $this -> db -> delete('transfer');
         $this -> db -> where('buisness_type', $id_post);
          
    }
    public function buisness_type(){
        $this->load->library('session');
        $user_id=$this->session->userdata('user_id');
         $data1=$this->uri->segment(3);
        $bid=$this->uri->segment(4);
        $type = str_replace('%20', ' ', $data1);
        
         $b_type= $this->department_model->get_buisness_type();
     
    $data2 = array(
         'type' => $type,
        'buisness_id'=>$this->uri->segment(4)
  );
    $data = array(
   'user_id' => $user_id,
   'type' => $type,
    'buisness_id'=>$this->uri->segment(4)
  
  );
        
       
        if($b_type){
               $this->db->where("(user_id=$user_id  )");
             
               $this->db->update('buisness_type',$data2);  
               redirect('user/search', 'refresh');
        }
        else{
            
             $this -> db -> insert('buisness_type',$data);
        redirect('user/search', 'refresh'); 
        }
        
       
        
    }
     public function do_upload(){
   
       $user_id=$this->session->userdata('user_id');
         $pass=$this->input->post('buis_pass');
         $b_type= $this->input->post('bu_edit');
         $type= $this->input->post('type');
     
        $data2 = array(
  
       'type' => $type
         );
       $data3 = array(
       'user_id'=>$user_id,
       'type' => $type,
        'status'=>1,
        );
      
       
        if($b_type and $type){
              
               $this -> db -> where('id',  $b_type);
               $this->db->update('type',$data2);
          
               
        }
         else if(!$b_type and $type){
            $this->db->insert('type',$data3);
            
         }
           
        $url = 'user/dash';
        echo'<script>window.location.href = "'.base_url().$url.'";
           </script>';
           
    }
    public function category(){
        

 $this->load->database(); //load library database


//$num_rows=$this->db->count_all("users");


      
       $b_type= $this->department_model->get_buisness_type();
       $query = $this->db->query("SELECT * FROM sale_type where status=1 and buisness_type='$b_type' ");
       $row= $query->num_rows();
  
          $perPage = 20;  
      
		
		 $page = ($this->uri->segment(3)) ? ($this->uri->segment(3) - 1) : 0;
					
		//Basic configuration 
		    $config['base_url'] = base_url().'user/category';
		$config['total_rows'] = $row;
		$config['per_page'] = $perPage;
		$config['uri_segment'] = 3;
		$config['use_page_numbers'] = true;
		
		
		



		$this->pagination->initialize($config);
	

       
        $data['deptlist'] = $this->department_model->get_sale_type($perPage, $page*$perPage); 
                   

        $data['pagination'] = $this->pagination->create_links();

        $this->load->view('sale_category',$data);
    }
     public function cat_value(){
        $b_type= $this->department_model->get_buisness_type();
         $type=$this->input->post('cat');
          $data = array(
        'user_id' =>$this->session->userdata('user_id'),
   
         'type' =>$type,
              
              'buisness_type'=>$b_type,
              'status' =>1,
  
       );
          $value='';
          $p_type=$this->db->query("select type from sale_type where type='$type' and buisness_type='$b_type' and status=1");
          foreach ($p_type->result() as $key => $value)
              $value=$value->type;
          if($value){
             
          
             echo '<script>alert("Type Already exit!");</script>';
   
        }   
        else{
          $this->db->insert('sale_type', $data);  
        }
         
        
         
        redirect('user/category', 'refresh');
    }
    public function type_delete(){
      $id_post = $this->input->post('uristring'); 
        $this->db->set('status',0,false);
        $this -> db -> where('id', $id_post);
        $this -> db -> update('sale_type');
       
 
    }
    public function cat_update(){
         $id_post='';
         $id_post=$this->input->post('id');
        
        $data = array(
 'user_id' =>$this->session->userdata('user_id'),
   
   'type' => $this->input->post('cat'),
   
  );
         $pretype=  $this->page_model->get_presaletype($id_post);
         $this -> db -> where('id', $id_post);
        $this -> db -> update('sale_type',$data);
        redirect('user/category', 'refresh');
    }
     public function cat_edit(){
         $id ['id']=$this->uri->segment(3);
        $this->load->view('sale_type_edit',$id);
    }
  public function trash(){
      
 $this->load->database(); //load library database

    $b_type=$this->department_model->get_buisness_type();
        
       
        $active = $this->uri->segment(3);
       
        if(!$active){
            $active=0;
            
        }
     
           $getTotalsale = $this->page_model->getTotalsaletrash($active); 
    
          
        
                          $data['cash']=0.0;
                          $data['tr']=0.0;
                          $data['card']=0.0;
                          $data['total']=0.0;
    
  
		
      
         $pagelimit=$this->db->query("select * from page_limit where page='search' and buisness_id='$b_type' ");
          foreach ($pagelimit->result() as $key => $pagevalue)
               $limited=$pagevalue->page_limit;
       
        if($limited){
          $perPage = $limited;  
        }
        else{
          $perPage = 20;  
        }
		
		 $page = ($this->uri->segment(4)) ? ($this->uri->segment(4) - 1) : 0;
          $data['tabpagi'] = $active;
		
       $config['base_url'] = base_url().'user/trash/'.$active;
		$config['total_rows'] = $getTotalsale;
		$config['per_page'] = $perPage;
		$config['uri_segment'] = 4;
		$config['use_page_numbers'] = true;
		
		



		$this->pagination->initialize($config);
	


        //call the model function to get the department data
        $data['deptlist'] = $this->department_model->get_trash($perPage, $page*$perPage,$active);           
           $data["pagination_link"] =  $this->pagination->create_links();
       
        $data['from']='';
        $data['to']='';
        $data['from']=$this->input->post('from');
        $data['tabsearch']=$active;
        $data['to']=$this->input->post('to');
       $this->load->view('trash',$data);
  }
      public function trash_delete(){
           $id_post = $this->input->post('uristring'); 
        $this -> db -> where('id', $id_post);
        $this -> db -> delete('sale');
       if($id_post) {
            $this -> db -> where('sale_id', $id_post);
        $this -> db -> delete('sale_details');
           
          
                 
        $this -> db -> where('sale_id', $id_post);
        $this -> db -> delete('sale_purchases');
           
       }    
       
         
          
         $b_type= $this->department_model->get_buisness_type();
       
            $status=0;
            $type='';
            $cash_sale=0.0;
            $bank_card=0.0;
            $ticket=0.0;
            $total=0.0;
        $limit=0;
             $limit=$this->db->query("select page_limit from page_limit");
          foreach ($limit->result() as $key => $value){
              $value=$value->page_limit;  
          }
        
        $limit=$value-1;
        
         $id_post = $this->input->post('uristring'); 
        
        $id_post1 = $this->input->post('type');
        
          $type=$this->db->query("select * from sale   where  buisness_type='$b_type'   order by id   limit ".$limit." ",false);
          foreach ($type->result() as $key => $value){
           
             
              $cash_sale+=$value->cash_sale;
              $bank_card+=$value->bank_card;
              $ticket+=$value->ticket;
              $total+=$value->total;
              
          }
          $result = array(
            'type' => $type,
              'cash' => $cash_sale,
              'bank' => $bank_card,
              'ticket' => $ticket,
              'total' => $total,
              'id'=>$id_post,
              
        );
     
   echo json_encode($result);
         
      }
     public function trashalldelete(){
           $id_post = $this->input->post('uristring'); 
        $this -> db -> where('id', $id_post);
        $this -> db -> delete('sale');
      }
    public function trash_recover(){
          $id_post = $this->input->post('uristring'); 
        $this->db->set('status',1,false);
        $this -> db -> where('id', $id_post);
        $this -> db -> update('sale');
        
        
        if($id_post){
          $this->db->set('status',1,false);
        $this -> db -> where('id', $id_post);
        $this -> db -> update('sale');
            
                 $this->db->set('status',1,false);
        $this -> db -> where('sale_id', $id_post);
        $this -> db -> update('sale_details');
         
       
                 $this->db->set('status',1,false);
        $this -> db -> where('sale_id', $id_post);
        $this -> db -> update('sale_purchases');
          
        
    }
    }
        public function show(){
            $totalbank=0.0;
       
       $b_type= $this->department_model->get_buisness_type();
            
            $bank=$this->db->query("select * from bank_name  where   status=1 
                                     and record=1 and buisness_id='$b_type'");
             $row= $bank->num_rows();
       
        $type='';
           
            $cash_sale='';
            $bank_card='';
            $ticket='';
            $total='';
            $totalbank=0.0;
            
         $id_post = $this->input->post('uristring'); 
        
        $id_post1 = $this->input->post('type');
        $html=''; 
             
          $type=$this->db->query("select * from sale b  where b.id  = '$id_post' and buisness_type='$b_type' and status=1 ",false);
          foreach ($type->result() as $key => $value){
            $date= date("Y-m-d",strtotime($value->date));
              $type=$value->type;
             $total=$value->total;
              $ticket=$value->ticket;
              $cash_sale=$value->cash_sale;
            $bank_card=(unserialize($value->bank_info));
             
                                    foreach ($bank->result() as $key => $bank){
                                         if(!isset($bank_card[$bank->id])) {
                                       $bank_card[$bank->id] = 0;
                                         }
                                    $totalbank+=$bank_card[$bank->id];
                                    if( ($bank_card[$bank->id])){
                                                $chk="checked";
                                               $style="";
                                            }
                                            else{
                                              $chk="";
                                                $style="display:none";
                                                
                                            }
                                           
                                    
                                    
                                     $html.= '<div id="checkboxdiv"  class="checkboxdivedit" style="display:inline-block;vertical-align:top;max-width:100px"><input  type="checkbox" id="myCheck'.$bank->id.'" name="select_bank['.$bank->id.']" onclick="bankFunction('.$bank->id.')" value="'.$bank->id.'" '.$chk.'>'.$bank->type.' </br>
                                        <input id="text'.$bank->id.'"  style="'.$style.'" type="text" name="bank_card['.$bank->id.']" class="banktext class" value="'.$bank_card[$bank->id].'"  onKeyPress="bbankcalculate()" onKeyUp="bbankcalculate()""></br></div>
                                    ';
                                              
                                      
                                       
        
                                 
                                        
                                    }
              
             // $total=$value->total;
              
          }
            /* $saletype=$this->db->query("select * from sale_type b  where type  = '$type' and buisness_type='$b_type' and status=1 ",false);
          foreach ($saletype->result() as $key => $saletype){
              $saletype=$saletype->id;
          }*/
          $result = array(
              'date'=>$date,
              'saletype'=>$type,
          
             'totalbank'=>number_format($totalbank,2),
              'cash' => $cash_sale,
              'bank' => $html,
              'ticket' => $ticket,
              'total' => $total,
              'id'=>$id_post,
              
        );
     
   echo json_encode($result);
         
       
    }
    public function update_result(){
            $b_type= $this->department_model->get_buisness_type();
       
        $type='';
            $cash_sale='';
            $bank_card='';
            $ticket='';
            $total='';
            $limit=0;
         $id_post = $this->input->post('uristring'); 
        
        $id_post1 = $this->input->post('type');
        
          $type=$this->db->query("select * from sale b  where b.id  = '$id_post' and buisness_type='$b_type' ",false);
          foreach ($type->result() as $key => $value){
           
              $type=$value->type;
              $cash_sale+=$value->cash_sale;
              $bank_card+=$value->bank_card;
              $ticket+=$value->ticket;
              $total+=$value->total;
              
          }
          $result = array(
            'type' => $type,
              'cash' => $cash_sale,
              'bank' => $bank_card,
              'ticket' => $ticket,
              'total' => $total,
              'id'=>$id_post,
              
        );
     
   echo json_encode($result);
         
    
    	
}
    public function saleedit(){
          
        $b_type= $this->department_model->get_buisness_type();
       
        $type='';
           
            
         $id_post = $this->input->post('uristring'); 
        
        $id_post1 = $this->input->post('type');
        
          $type=$this->db->query("select * from sale_type b  where b.id  = '$id_post' and buisness_type='$b_type' ",false);
          foreach ($type->result() as $key => $value){
           
              $type=$value->type;
              
              
          }
          $result = array(
            'type' => $type,
              
              'id'=>$id_post,
              
        );
     
   echo json_encode($result);
         
    }
    public function newcheck(){
        $b_type= $this->department_model->get_buisness_type();
        $date=date("Y-m-d");
        $type=$this->db->query("select * from bank_name  where  status=1 and buisness_id='$b_type'
                                      ");
                                    $data='';
                                     $html='';
                                    foreach ($type->result() as $key => $type){
                                        $html.= '<div id="checkboxdiv" class="checkboxdiv" style="display:inline-block;vertical-align:top;max-width:130px"><input  type="checkbox" id="myCheck'.$type->id.'" name="select_bank['.$type->id.']" onclick="bankFunction('.$type->id.')" value="'.$type->id.'"  >'.$type->type.' </br>
                                        <input id="text'.$type->id.'" type="text" name="bank_card['.$type->id.']" class="banktext class" style="display:none; width:100%" onKeyPress="bbankcalculate()" onKeyUp="bbankcalculate()""></br></div>';

                                   
                                    }
        $result=array(
        'date'=>$date,
        'html'=>$html,
        'checked'=>11);
         echo json_encode($result);
    }

}
