<?php

error_reporting(0);

class Sale  extends CI_Controller {



public function __construct(){



        parent::__construct();

  			$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->model('page_model');

 $this->load->library('pagination');



 $this->load->database();
   $user_id=$this->session->userdata('user_id');
   if(!$user_id){
     redirect('user/login_view', 'refresh');
     }


}







public function activepagination(){

     $b_type=$this->department_model->get_buisness_type();

         $tabid=$this->input->post('purchasestabid');

        $page=$this->input->post('purchasespage');

        $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);

    

}





    public function wholesale($offset = 0){

        $b_type=$this->department_model->get_buisness_type();

                          $data['cash']=0.0;

                          $data['tr']=0.0;

                          $data['card']=0.0;

                          $data['total']=0.0;

    

         //load library database

    $active = $this->uri->segment(3);

        $filterac=$this->input->post('tabsearchpagi');

       

      

        if($filterac){

          $active=$filterac;  

        }

       

        if(!$active and  !$filterac){

            $active=0;

            

        }

        $getTotalwholesale = $this->page_model->getTotalwholesale($active);

        $data['cash']=0.0;

                          $data['tr']=0.0;

                          $data['card']=0.0;

                          $data['total']=0.0;

  

         $pagelimited=$this->db->query("select page_limit from page_limit where page='wholesale' and buisness_id='$b_type' ");

          foreach ($pagelimited->result() as $key => $pagevalue)

              $value=$pagevalue->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().'sale/wholesale/'.$active;

		$config['total_rows'] = $getTotalwholesale;

		$config['per_page'] = $perPage;

		$config['uri_segment'] = 4;

		$config['use_page_numbers'] = true;



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


     

         $data['limit']=$perPage;

          $data['start']=$page*$perPage;

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

       $data['tabtype'] = $this->department_model->get_wholetab_type($active);

        $data['category'] = $this->department_model->get_wholesale_category(); 

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

      $data['tabsearch']=$this->input->post('tabsearch');

        

      $data['id']='';

        $data ['id']=$this->uri->segment(3);

         $data['id_post'] = $this->input->post('uristring');

        $data['from']='';

        $data['to']='';

        $data['from']=$this->input->post('from');

        $data['catmark']=$this->department_model->wholesaletabmark();

      

        $data['to']=$this->input->post('to');

        $data['bb']=$this->input->post('from');

        $this->load->view("wholesale.php",$data);

        //redirect('user/sale', 'refresh');

        

    }

     public function profit(){

         $profit=$this->input->post('uristring');

         $from=$this->input->post('from');

        $to=$this->input->post('to');

        $saleprofit= $this->department_model->get_sale_profit($profit,$from,$to);

         echo  json_encode($saleprofit);

     }

    

   public function total(){

        $filter=$this->input->post('uristring');
        $active=$this->input->get('active');
        $wholesaleprofit= $this->department_model->get_totalwholesale($filter,$active);

         echo  json_encode($wholesaleprofit); 

    }

    

    public function filterprofit(){

         $from=$this->input->post('from');

        $to=$this->input->post('to');

        $saleprofit= $this->department_model->get_sale_filterprofit($from,$to);

        //echo  json_encode($saleprofit);

     }

      public function expense(){

         $profit=$this->input->post('uristring');

          $from=$this->input->post('from');

        $to=$this->input->post('to');

        $expenseprofit= $this->department_model->get_expense_profit($profit,$from,$to);

         echo  json_encode($expenseprofit);

     }
    public function netexpense(){

         $profit=$this->input->post('uristring');

          $from=$this->input->post('from');

        $to=$this->input->post('to');

        $expenseprofit= $this->department_model->get_netexpense_profit($profit,$from,$to);

         echo  json_encode($expenseprofit);

     }

    public function category(){

         $data['category'] = $this->department_model->get_wholesale_category();           



        

     

    

         $this->load->view('wholesale_category',$data);

    }

  public function cat_value(){

       $b_type= $this->department_model->get_buisness_type();

        $type=$this->input->post('cat');

          $data = array(

              

   

              'category' =>  $type,

              'status' =>  1,

              'buisness_type' =>  $b_type,

              

  

       );

        $p_type='';

     $value='';

          $p_type=$this->db->query("select * from wholesale_category where category='$type' and buisness_type='$b_type' and status=1 ");

          foreach ($p_type->result() as $key => $value)

              $value=$value->category;

          if($value){

             

          

             echo '<script>alert("Category Already exit!");</script>';

   

        }   

        else{

           $this->db->insert('wholesale_category', $data);  

        }

        

         

       

        redirect('sale/category', 'refresh');

    }



    

    public function categoryedit (){

    

       $b_type= $this->department_model->get_buisness_type();

        $type='';

           

            

         $id_post = $this->input->post('uristring'); 

        

        $id_post1 = $this->input->post('type');

        

        

        $type=$this->department_model->get_wholesale_type($id_post,$b_type);

         

          $result = array(

            'type' => $type,

              

              'id'=>$id_post,

              

        );

     

   echo json_encode($result);

    }

    

     public function cat_update (){

          $id_post='';

         $id_post=$this->input->post('id');

        

        $data = array(



   

   'category' => $this->input->post('cat'),

   

  );

        $precat=  $this->page_model->get_prewholecat($id_post);

         $this -> db -> where('id', $id_post);

        $this -> db -> update('wholesale_category',$data);

        redirect('sale/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('wholesale_category');

       

 

    }

       public function newcheck(){

           $date=date("Y-m-d");

           $b_type=$this->department_model->get_buisness_type();

         $type=$this->db->query("select * from bank_name  where  status=1 and buisness_id='$b_type' ");

                 $html='';

                     foreach ($type->result() as $key => $type){

                      

                   $html.='<div id="checkboxdiv" style="display:inline-block;vertical-align:top;max-width:100px"><input  type="checkbox" id="myCheck'.$type->id.'" name="select_bank['.$type->id.']" onclick="pbankFunction('.$type->id.')" value="'.$type->id.'"  >'.$type->type.' </br>

                   

                      <input id="text'.$type->id.'" type="number" name="bank_card['.$type->id.']" class="banktext bankclass" style="display:none; width:100%" value="" onKeyPress="bankvalue('.$type->id.')" onKeyUp="bankvalue('.$type->id.')" step=any></br>

                       <input id="bank'.$type->id.'" type="hidden"  class="banktext class" style="display:none; width:100%" value="" ></br></div>    <input type="hidden" id="bankvalue'.$type->id.'">';

                      }

        $result=array(

            'date'=>$date,

        'html'=>$html,

        'checked'=>11);

         echo json_encode($result);

    }

    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 value(){

          $bankrowvalue=$this->department_model->bank_row();

        $data_bank =  $this->input->post('select_bank[]');

     $data1_card = $this->input->post('bank_card[]');

$b_type=$this->department_model->get_buisness_type();

$bankcount=$this->department_model->get_bankcount();
 $selected=$this->input->post('select');
$whtype=$this->department_model->get_wholesale_type($selected);
    

          $p_edit=$this->input->post('pur_edit');

      

         if($this->input->post('bank')!=null){

            $paytotal=$this->input->post('bank');

       }

       else{

          $paytotal=00; 

       }

        $value=array();

       

        foreach ($bankcount as $key => $bank){

               

         $value [$data_bank[$bank->id]]=$data1_card[$bank->id];

         }

        $a=(serialize($value));

        if($p_edit){

           

            

        $data = array(

 //'user_id' =>$this->session->userdata('user_id'),

   'date' => $this->input->post('date'),

   'type' => $this->input->post('select'),

   'pay_type' => $this->input->post('pay_type'),

   'pay_total' => $paytotal,

    'bank_info' => $a,

    'invoice_number' =>  $this->input->post('invoice'),

   'total_order' => $this->input->post('ticket'),

    'due_balance' => $this->input->post('total'),

     'status' => 1,

  );

        

    foreach ($data1_card as $bank_id => $bank_value){
            

     if ($bank_value >0 ){       

              $purchaseall_detail[] =array(

                  

                   'wholesale_id' =>$p_edit,

                   'sale_type' =>'bank',

                   'bank_id'=>$bank_id,

                   'amount'=>$bank_value,

                  'date'=>$this->input->post('date'),

                  'type'=>$whtype,

                   'status'=>1,

                  'buisness_id'=>$b_type,

               );
          

         }

             

          $this -> db -> where('wholesale_id', $p_edit);

        $this -> db -> delete('sale_purchases');

             

        }   

        

         $this -> db -> where('id', $p_edit);

        $this -> db -> update('wholesale',$data);

           if($purchaseall_detail){

                $this -> db -> insert_batch('sale_purchases', $purchaseall_detail);

            } 

          

          

           

          $url = 'sale/wholesale';

       echo'

           <script>

          window.location.href = "'.base_url().'/'.$url.'";

           </script>';

        

    }

     if (!$p_edit){  


          $value=array();
 

         for($i=0; $i<=count($data1_card);$i++){
              

        $this->db->set('record',1,false);

        $this -> db -> where('id', $data_bank[$i] );

        $this -> db -> update('bank_name'); 

             

             

           }

     

        

 

      $data = array(

  //'user_id' => $this->input->post('id'),

   'date' => $this->input->post('date'),

   'type' => $this->input->post('select'),

   'pay_type' => $this->input->post('pay_type'),

    'bank_info' => $a,

 'invoice_number' =>  $this->input->post('invoice'),

   'pay_total' => $paytotal,

   'total_order' => $this->input->post('ticket'),

    'due_balance' => $this->input->post('total'),

          'status' => 1,

          'buisness_type' => $b_type,

  );  

       $this->db->insert('wholesale', $data);

   

       $pur_id=$this->db->insert_id();

 


 foreach ($data1_card as $bank_id => $bank_value){

               

     if ($bank_value >0 ){

              $purchaseall_detail =array(

                   'wholesale_id' =>$pur_id,

                   'sale_type' =>'bank',

                  'date'=>$this->input->post('date'),

                  'type'=>$whtype,

                   'bank_id'=>$bank_id,

                   'amount'=>$bank_value,

                   'status'=>1,

                  'buisness_id'=>$b_type,

               );


           $this->db->insert('sale_purchases',$purchaseall_detail); 

          

         }

             

            

        }

        

redirect('sale/wholesale', 'refresh');

      }

    }

    

     public function show(){

       $b_type=$this->department_model->get_buisness_type();

       $type='';

        $pay_type='';

        $order=0.0;

        $t_order=0.0;

        $d_balance=0.0;

        $id_post = $this->input->post('category');

        

        $id_post1 = $this->input->post('type');

        

          $type=$this->db->query("select * from wholesale b  where b.type  = '$id_post' and buisness_type='$b_type' and status=1 ",false);

          foreach ($type->result() as $key => $value){

             $type=$value->pay_type;

              $id=$value->id;

              

              $order+=round($value->pay_total,2);

              $t_order+=round($value->total_order,2);

              

              $d_balance+=round($value->due_balance,2);

              

          }

        $due=($order)-($t_order);

          $result = array(

            

            'res' => round($order,2),

              'res1' => round($t_order,2),

              'res2' => round($due,2),

              'res3' => $id_post,

              'id'=>$id,

              'res5'=>$type,

              

        );

     

   echo json_encode($result);

         

       

    }

    

        public function pay(){

    $b_type=$this->department_model->get_buisness_type();

      $total=$this->input->post('totaldu');

        $bankcount=$this->department_model->get_bankcount();

            $bankval=$this->input->post('bank');

            $ticket=$this->input->post('ticket');

        

           //$due_total=$bank-$ticket; 

       $data_bank =  $this->input->post('select_bank[]');

     $data1_card = $this->input->post('bank_card[]');



        $selected=$this->input->post('select');
         $whtype=$this->department_model->get_wholesale_type($selected);
        $pay=$this->input->post('pay_type');

        

       $value=array();

       

          foreach ($bankcount as $key => $bank){

               

         $value [$data_bank[$bank->id]]=$data1_card[$bank->id];

             $this->db->set('record',1,false);

        $this -> db -> where('id', $data_bank[$bank->id] );

        $this -> db -> update('bank_name');

         }

     

          $a=(serialize($value));

        

       // $select = str_replace(' ', '', $selected);

       //$pay_type = str_replace(' ', '_', $pay);

     

      $data = array(

 // 'user_id' =>$this->session->userdata('user_id'),

   'date' => $this->input->post('date'),

   'type' => $selected,

   'pay_type' => $pay,

   'pay_total' => $bankval,

    'due_balance'=> $bankval,

   'bank_info' => $a,

    

          'buisness_type' => $b_type,

          'status' => 1,

          

          

       );

        

         $this->db->insert('wholesale', $data);

          $pur_id=$this->db->insert_id();
     foreach ($data1_card as $bank_id => $bank_value){

               

     if ($bank_value >0 ){


              $purchaseall_detail =array(

                   'wholesale_id' =>$pur_id,

                   'sale_type' =>'bank',

                  'date'=>$this->input->post('date'),

                  'type'=>$whtype,

                   'bank_id'=>$bank_id,

                   'amount'=>$bank_value,

                  'buisness_id' => $b_type,

                   'status'=>1,

               );

          

        

          

          $this->db->insert('sale_purchases',$purchaseall_detail); 

          

         }

             

            

        }

        

         

       

        redirect('sale/wholesale', 'refresh');

    }

         public function pur_edit(){

          

  $b_type=$this->department_model->get_buisness_type();

       $type='';

        $option='';

           $pay_total='';

           $total_order='';

            $due='';

            $total='';

            $html='';

         $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();

 

        $bankname=$this->db->query("select * from bank_name  where   status=1 

                                     and record=1 and buisness_id='$b_type' ");

         $type=$this->db->query("select * from wholesale   where id  = '$id_post' and buisness_type='$b_type' and status=1 ");

          foreach ($type->result() as $key => $value){

           

             // $type=$value->type;

             $total=$value->total;

              $ticket=$value->ticket;

              $cash_sale=$value->cash_sale;

               $pay_total=$value->pay_total;

              $total_order=$value->total_order;

              $due=$value->due_balance;

              $option=$value->type;

               $invoice=$value->invoice_number;

              $type= $value->pay_type;

               $date= date("Y-m-d",strtotime($value->date));

            $bank_card=(unserialize($value->bank_info));

             

                                     foreach ($bankname->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="checkboxdivedit"  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="pbankFunction('.$bank->id.')" value="'.$bank->id.'" '.$chk.'>'.$bank->type.' </br>

                                        <input id="text'.$bank->id.'"  style="'.$style.'" type="number" name="bank_card['.$bank->id.']" class="banktext bankclass" value="'.$bank_card[$bank->id].'"  onKeyPress="bankvalue()" onKeyUp="bankvalue()" step=any></br></div>

                                    ';

                                              

                                       

                                       

        

                                  

                                        

                                    }

             

            

              

          }

        

     /*$prtype=$this->db->query("select * from wholesale_category b  where category  = '$option' and buisness_type='$b_type' and status=1 ",false);

          foreach ($prtype->result() as $key => $prtype){

              $prtype=$prtype->id;

          }*/

       /* if($type=='No Pay'){

            $type='no';

        }*/

          $result = array(

            'date' => $date,

              //'cash' => $pay_type,

              'option'=>$option,

              'type'=>$type,

              'pay_total' => $pay_total,

              'total_order' => $total_order,

              'due' => $due,

              'id'=>$id_post,

              'html'=>$html,

              'invoice'=>$invoice,

              

        );

     

   echo json_encode($result);

         

       

    

    }

       public function value_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('wholesale');

        

          

          

                 $this->db->set('status',0,false);

        $this -> db -> where('wholesale_id', $id_post);

        $this -> db -> update('sale_purchases');

         

        

    }

            

            

        

       

        

    

    $b_type=$this->department_model->get_buisness_type();





       $status=1;

        $pay=0.0;

        $order=0.0;

        $due=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 wholesale   where status='$status' and buisness_type='$b_type'   order by id   limit ".$limit." ",false);

          foreach ($type->result() as $key => $value){

           

             

              $pay+=$value->pay_total;

              $order+=$value->total_order;

              $due+=$value->due_balance;

              

              

          }

          $result = array(

            'pay' => $pay,

              'order' => $order,

              'due' => $due,

             

              

        );

     

   echo json_encode($result);

         

        

    }

    

    public function trash(){

           $b_type=$this->department_model->get_buisness_type();

                          $data['cash']=0.0;

                          $data['tr']=0.0;

                          $data['card']=0.0;

                          $data['total']=0.0;

    

         //load library database

       $active = $this->uri->segment(3);

       

        $getTotalwholesale = $this->page_model->getTotalwholesaletrash($active);

                         $data['cash']=0.0;

                          $data['tr']=0.0;

                          $data['card']=0.0;

                          $data['total']=0.0;

    

  

		

      

         $pagelimited=$this->db->query("select page_limit from page_limit where page='wholesale' and buisness_id='$b_type' ");

          foreach ($pagelimited->result() as $key => $pagevalue)

              $value=$pagevalue->page_limit;

          

        if($value){

          $perPage = $value;  

        }

        else{

          $perPage = 20;  

        }

		

		 $page = ($this->uri->segment(4)) ? ($this->uri->segment(4) - 1) : 0;

        $data['tabpagi'] = $active;

		

		  $config['base_url'] = base_url().'sale/trash/'.$active;

		$config['total_rows'] = $getTotalwholesale;

		$config['per_page'] = $perPage;

		$config['uri_segment'] = 4;

		$config['use_page_numbers'] = true;




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



         $data['limit']=$perPage;

          $data['start']=$page*$perPage;

        

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



        $data['pagination'] = $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('wholesale_trash',$data);

    }

      public function trash_recover(){

          $id_post = $this->input->post('uristring'); 

        

        

 

        if($id_post){

             $this->db->set('status',1,false);

        $this -> db -> where('id', $id_post);

        $this -> db -> update('wholesale');

        

            

           

                 $this->db->set('status',1,false);

        $this -> db -> where('wholesale_id', $id_post);

        $this -> db -> update('sale_purchases');

           

            

        }

        

    }

    public function trash_delete(){

           $id_post = $this->input->post('uristring'); 



        if($id_post){

            

        $this -> db -> where('id', $id_post);

        $this -> db -> delete('wholesale');

               

        $this -> db -> where('wholesale_id', $id_post);

        $this -> db -> delete('sale_purchases');

           

            

        }

      }

}

