<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Admin extends MY_Controller { 
    function __construct() {error_reporting(0);
        parent::__construct();
		$this->load->library("upload");
		$this->load->library("email");
		
        if(!$this->session->userdata("admin")){redirect("home/admin");}
        //error_reporting(0);
		//redirect("home");
    }

	public function ajax_addtrade(){
		parse_str($_POST['formdata'],$_POST);
		//print_r($_POST);exit;
		$this->db->insert("user_trades",$_POST);
		$lid=$this->db->insert_id();
		$prol=$_POST['profit_loss'];
		$this->db->order_by("trid","desc");
				$chk=$this->db->get_where("user_trans",array("userid"=>$_POST['userid']))->row();
				
				//print_r($l);
				$wallet=$chk->left_amt;
				
					$newbal=$wallet+$prol;
				
				if($prol>0){
				$typ="Trade Credit";	
				}else{
				$typ="Trade Debit";	
				}
				$this->db->insert("user_trans",array("buysell_id"=>$lid,"tr_amt"=>$prol,"tr_type"=>$typ,"tr_date"=>date("Y-m-d"),"left_amt"=>$newbal,"userid"=>$_POST['userid']));
				;
				echo "Order Added Successfully";
	}
	
	public function ajax_upi_delete(){
 		$this->db->update("admin",array("qr_code"=>""));
	}

	public function user_loan(){
		$this->db->where("loan_id",$_POST['id']);
		$this->db->update("loans",array("loan_amt"=>$_POST['amt']));
	}
	
	public function userenable(){
		$pchange="";
		if($_POST['st']=="Disable"){

			$st="Disable";	
			$pchange="yes";

		}else{$st="";}

		$this->db->where("id",$_POST['id']);
		$this->db->update("users",array("admin_approve"=>$st,"pchange"=>$pchange));
		
		$chk=$this->db->get_where("users",array("id"=>$_POST['id']))->row();
		//if($st==''){
			$data['user']=$chk;
			$message = $this->load->view("new_welcome",$data,true);
			$this->email->set_newline("\r\n");
			$this->email->set_mailtype("html");
			$this->email->to($chk->email);//
			$this->email->from("info@aurofxmarket.in");
			$this->email->subject('AuroFx Market Account Activation');
			$this->email->message($message);
			$result = $this->email->send();
	}
	
	public function index()
	{
	    //$this->db->select("id,first_name,last_name");
		//$data['users']=$this->db->get("users")->result();
		//$data['livedata']=$this->db->get("metals")->result();
		$data=array();
		$this->template['middle'] = $this->load->view ($this->middle = 'admin/ndashboard',$data,true);
		$this->adminlayout(); 
	}

	public function  bonus()
	{
	    //$this->db->select("id,first_name,last_name");
		//$data['users']=$this->db->get("users")->result();
		//$data['livedata']=$this->db->get("metals")->result();
		$data=array();
		$this->template['middle'] = $this->load->view ($this->middle = 'admin/bonus',$data,true);
		$this->adminlayout(); 
	}

	
	public function add_paylist(){		
		if(!empty($_FILES["pay_img"]["name"])){
			$config['upload_path'] = './assets/';
			$config['allowed_types'] = 'gif|jpg|png|jpeg|svg';
			$config['max_size']	= '1000000';
			$this->upload->initialize($config);
			if (!$this->upload->do_upload('pay_img'))
			{
			echo $this->upload->display_errors();
			}
			else
			{	
			$pic = $this->upload->data();
			$file=$pic['file_name'];
			}
		}
			
		$this->db->insert("paylist",array("pay_img"=>$pay_img,"min_depo"=>$_POST['min_depo'],"pay_upi"=>$_POST['pay_upi'],"pay_type"=>$_POST['pay_type']));
		redirect("admin");
	}



	public function update_qr(){
		$file=$_POST['oldfile'];
		if(!empty($_FILES["file"]["name"])){
		$config['upload_path'] = './eassets/';
		$config['allowed_types'] = 'gif|jpg|png|jpeg|svg';
		$config['max_size']	= '1000000';
		$this->upload->initialize($config);
		if (!$this->upload->do_upload('file'))
		{
		echo $this->upload->display_errors();
		}
		else
		{	
		$pic = $this->upload->data();
		$file=$pic['file_name'];
		}}
		
		$this->db->update("admin",array("qr_code"=>$file,"upi_id"=>$_POST['upi_id'],"exchg_rate"=>$_POST['exchg_rate']));
		redirect("admin");
	}


	
	public function change_pass2(){
		parse_str($_POST['formdata'],$form);
		if($this->session->userdata("type")=="admin"){
			$this->db->where("id",1);
			if($this->db->update("admin",array("password"=>md5($form['npass'])))){echo "Password Changed Successfully.";}
		}else{
			$this->db->where("subadmin_id",$this->session->userdata("userid"));
			if($this->db->update("subadmins",array("subadmin_pass"=>md5($form['npass'])))){echo "Password Changed Successfully.";}	
		}
	}
	
	public function ajax_subadmin_delete(){
		$this->db->delete("subadmins",array("subadmin_id"=>$_POST['id']));
	}
	
	public function ajax_update_subadmin_password(){
		parse_str($_POST['formdata'],$form);
		//print_r($form);exit;
		$this->db->where("subadmin_id",$form['emp_id']);
		if($this->db->update("subadmins",array("subadmin_pass"=>md5($form['pass'])))==true){
			echo "Password Changed Successfully.";
		}else{
			echo "Password couldnot be changed.";
		}
	}
	public function subadmin_enable(){
		if($_POST['st']=="Disable"){$st="Disable";}else{$st="";}
		$this->db->where("subadmin_id",$_POST['id']);
		$this->db->update("subadmins",array("subadmin_status"=>$st));	
	}
	
	public function add_subadmin(){
		if($this->db->insert("subadmins",array("subadmin_username"=>$_POST['subadmin_username'],"subadmin_name"=>$_POST['subadmin_name'],"subadmin_pass"=>md5($_POST['subadmin_pass']),"subadmin_phone"=>$_POST['subadmin_phone'],"subadmin_email"=>$_POST['subadmin_email']))==true){
			$this->session->set_flashdata('msg', '<div class="alert alert-success">Subadmin Added Successfully.</div>');	
		}else{
			 $this->session->set_flashdata('msg', '<div class="alert alert-success">Subadmin couldnot be added.</div>');	
		}redirect("admin/subadmins");
	}
	
	public function update_subadmin(){
		$this->db->where("subadmin_id",$_POST['subadmin_id']);
		if($this->db->update("subadmins",array("subadmin_username"=>$_POST['subadmin_username'],"subadmin_name"=>$_POST['subadmin_name'],"subadmin_phone"=>$_POST['subadmin_phone'],"subadmin_email"=>$_POST['subadmin_email']))==true){
			$this->session->set_flashdata('msg', '<div class="alert alert-success">Subadmin Updated Successfully.</div>');	
		}else{
			 $this->session->set_flashdata('msg', '<div class="alert alert-success">Subadmin couldnot be Updated.</div>');	
		}redirect("admin/subadmins");
	}
	
	public function subadmins($brid=false){
		if($brid==true){
			$this->db->select("*");
			$this->db->from("subadmins");
			//$this->db->join("branches","branches.br_id=agents.brid");
			$this->db->where("subadmin_id",$brid);
			$data['edit']=$this->db->get()->row();
		}
		$this->db->select("*");
		$this->db->from("subadmins");
		//$this->db->join("states","states.state_id=emps.emp_state","left");
		//$this->db->order_by("agents.ag_id","desc");
		$data['emps']=$this->db->get()->result();
		
		$this->template['middle'] = $this->load->view ($this->middle = 'admin/subadmins',$data,true);
		$this->adminlayout();
	}
	
	public function admin_banking(){
		$query=$this->db->insert("banks",array("bank_name"=>$_POST['bank_name'],"acc_name"=>$_POST['acc_holder'],"acc_number"=>$_POST['acc_no'],"ifsc_code"=>$_POST['ifsc'],"acc_type"=>$_POST['acc_type']));
		if($query==true){$this->session->set_flashdata('msg', '<div class="alert alert-success">Bank Details Updated Successfully.</div>');
				}else{
	$this->session->set_flashdata('msg', '<div class="alert alert-danger">Bank Details Could not be Updated. Please try later.</div>');					 				}redirect('mcxadmin/settings');
	}
	
	public function edit_user(){
		$data['user']=$this->db->get_where("users",array("id"=>$_GET['id']))->row();
		$this->template['middle'] = $this->load->view ($this->middle = 'admin/edit_user',$data,true);
		$this->adminlayout(); 	
	}
	
	public function update_profile(){
		$profile_url=$_POST['old_profile_url'];
			//echo "<pre>";print_r($_FILES);
			if(!empty($_FILES["profile_url"]["name"])){
				$config['upload_path'] = './eassets/img/';
				$config['allowed_types'] = 'gif|jpg|png|jpeg|svg';
				$config['max_size']	= '1000000';
				$this->upload->initialize($config);
				if (!$this->upload->do_upload('profile_url'))
				{
				echo $this->upload->display_errors();
				}
				else
				{	
				$pic = $this->upload->data();
				$profile_url=$pic['file_name'];
				}
			}
		  	$this->db->where("id",$_POST['uid']);
			$query=$this->db->update("users",array("profile_url"=>$profile_url,"mobile"=>$_POST['mobile'],"email"=>$_POST['email'],"city"=>$_POST['city'],"zipcode"=>$_POST['zipcode']));
		if($query==true){$this->session->set_flashdata('msg', '<div class="alert alert-success">Profile Details Updated Successfully.</div>');
				}else{
	$this->session->set_flashdata('msg', '<div class="alert alert-danger">Profile Details Could not be Updated. Please try later.</div>');					 				}redirect('admin/edit_user?id='.$_POST['uid']);
	}
	
	public function update_banking(){
		  	$this->db->where("id",$_POST['uid']);
			if($this->db->update("users",array("bank_name"=>$_POST['bank_name'],"acc_holder"=>$_POST['acc_holder'],"ifsc"=>$_POST['ifsc'],"acc_type"=>$_POST['acc_type'],"acc_no"=>$_POST['acc_no']))==true){
			$this->session->set_flashdata('msg', '<div class="alert alert-success">Bank Details Updated Successfully.</div>');
				}else{
	$this->session->set_flashdata('msg', '<div class="alert alert-danger">Bank Details Could not be Updated. Please try later.</div>');					 				}redirect('admin/edit_user?id='.$_POST['uid']);
	  }
	  
	  public function update_kyc(){
		 	$aadhar=$_POST['old_aadhar_doc'];
			$pan=$_POST['old_pan_doc'];
			
			if(!empty($_FILES["aadhar_doc"]["name"])){
				$config['upload_path'] = './eassets/docs/';
				$config['allowed_types'] = 'gif|jpg|png|jpeg|svg';
				$config['max_size']	= '1000000';
				$this->upload->initialize($config);
				if (!$this->upload->do_upload('aadhar_doc'))
				{
				echo $this->upload->display_errors();
				}
				else
				{	
				$pic = $this->upload->data();
				$aadhar=$pic['file_name'];
				}
			}if(!empty($_FILES["pan_doc"]["name"])){
				$config['upload_path'] = './eassets/docs/';
				$config['allowed_types'] = 'gif|jpg|png|jpeg|svg';
				$config['max_size']	= '1000000';
				$this->upload->initialize($config);
				if (!$this->upload->do_upload('pan_doc'))
				{
				echo $this->upload->display_errors();
				}
				else
				{	
				$pic = $this->upload->data();
				$pan=$pic['file_name'];
				}
			} 
			$this->db->where("id",$_POST['uid']);
			if($this->db->update("users",array("pan_doc"=>$pan,"aadhar_doc"=>$aadhar,"aadhar"=>$_POST['aadhar_number'],"pan_no"=>$_POST['pan_number']))==true){
			$this->session->set_flashdata('msg', '<div class="alert alert-success">KYC Details Updated Successfully.</div>');
				}else{
			$this->session->set_flashdata('msg', '<div class="alert alert-danger">KYC Details Could not be Updated. Please try later.</div>');					 				
			}	    redirect('admin/edit_user?id='.$_POST['uid']);
	  }
	
	public function add_user(){
		//echo "<pre>";print_r($this->session->all_userdata());exit;
		$chk=$this->db->get_where("users",array("mobile"=>$_POST['mobile']));
		$chk2=$this->db->get_where("users",array("email"=>$_POST['email']));
		$chk3=$this->db->get_where("users",array("username"=>$_POST['username']));
		if($chk->num_rows()>0){
			$this->session->set_flashdata("msg","<div class='alert alert-danger'>Mobile Number Already Registered");
		}else if($chk2->num_rows()>0){
			$this->session->set_flashdata("msg","<div class='alert alert-danger'>Email id Already Registered");
		}else if($chk3->num_rows()>0){
			$this->session->set_flashdata("msg","<div class='alert alert-danger'>Username id Already Registered");
		}else{
			
			$aadhar=$pan='';
			
			if(!empty($_FILES["aadhar"]["name"])){
				$config['upload_path'] = './eassets/docs/';
				$config['allowed_types'] = 'gif|jpg|png|jpeg|svg';
				$config['max_size']	= '1000000';
				$this->upload->initialize($config);
				if (!$this->upload->do_upload('aadhar'))
				{
				echo $this->upload->display_errors();
				}
				else
				{	
				$pic = $this->upload->data();
				$aadhar=$pic['file_name'];
				}
			}if(!empty($_FILES["pan"]["name"])){
				$config['upload_path'] = './eassets/docs/';
				$config['allowed_types'] = 'gif|jpg|png|jpeg|svg';
				$config['max_size']	= '1000000';
				$this->upload->initialize($config);
				if (!$this->upload->do_upload('pan'))
				{
				echo $this->upload->display_errors();
				}
				else
				{	
				$pic = $this->upload->data();
				$pan=$pic['file_name'];
				}
			}
			$this->db->insert("users",array("subad_id"=>$this->session->userdata("userid"),"profile_url"=>"user.png","aadhar_number"=>$_POST['aadhar_number'],"pan_number"=>$_POST['pan_number'],"first_name"=>$_POST['name'],"mobile"=>$_POST['mobile'],"email"=>$_POST['email'],"username"=>$_POST['username'],"password"=>md5($_POST['password']),"aadhar_doc"=>$aadhar,"pan_doc"=>$pan,"created"=>date("Y-m-d")));
			$this->session->set_flashdata("msg","<div class='alert alert-success'>Client Account Created Successfully.");
		}redirect("admin/users");
	}
  
	public function check_trade(){
		$this->db->update("admin",array("trade_enable"=>$_POST['st']));	
	}
	public function bonus_form_submit(){
		parse_str($_POST['formdata'],$form);
		$this->db->update("admin",$form);
		echo "Updated";	
	}
	
	
	public function mega_trade(){
	$this->db->where("id",$_POST['id']);
	$this->db->update("users",array("mega_lot"=>$_POST['v']));  
  }
	
	public function invoice($id){
		$this->db->select("*");
		$this->db->from("orders");
		$this->db->where("oid",$id);
		$data['order']=$this->db->get('orders')->row();
		$this->load->view("admin/invoice",$data);	
	}
	
	public function total_trades(){error_reporting(0);error_reporting(0);
		$this->db->select("*");
		$this->db->from("buysell");
		$this->db->where("status !=","EXIT");
		echo $this->db->get()->num_rows();
		
	}
	public function reset_mrate(){
		$this->db->update("metals",array("mstatus"=>""));	
	}
	public function trade_refresh(){
		$this->db->delete("user_trans",array("buysell_id"=>$_POST['id']));
		$this->db->where("bsid",$_POST['id']);
		$this->db->update("buysell",array("status"=>"start","last_live"=>$_POST['href']));
		$this->db->close();
	}
	
	public function live_rates(){
		$met=explode("_",$_POST['id']);
		$this->db->select("metal,rate");
		$metal=$this->db->get_where("metals",array("metal"=>$met[1]))->row();
		echo $metal->rate;
		$this->db->close();
	}
	

	
	public function update_live_rates(){
		//print_r($_POST);exit;
		$this->db->where("metal",$_POST['metal']);
		if($this->db->update("metals",array("rate"=>$_POST['rate']))==true){
		echo 1;
		}else{
		echo 0;
		} 
		$this->db->close();
	}
	
	
	public function exit_positions(){
		$this->db->select("*");
		$this->db->from("buysell");
		$this->db->join("users","users.id=buysell.uid");
		$this->db->where("buysell.status","EXIT");
		$this->db->where("buysell.type","BUY");
		if(isset($_GET['date'])){
		$this->db->where("buysell.bsday",$_GET['date']);	
		}else{
		$this->db->where("buysell.bsday",date("Y-m-d"));	
		}
		$this->db->order_by("buysell.bsid","desc");
		$data['bexit']=$this->db->get()->result();
		
		$this->db->select("*");
		$this->db->from("buysell");
		$this->db->join("users","users.id=buysell.uid");
		$this->db->where("buysell.status","EXIT");
		$this->db->where("buysell.type","SELL");
		if(isset($_GET['date'])){
		$this->db->where("buysell.bsday",$_GET['date']);	
		}else{
		$this->db->where("buysell.bsday",date("Y-m-d"));	
		}
		$this->db->order_by("buysell.bsid","desc");
		$data['sexit']=$this->db->get()->result();
		
		$this->template['middle'] = $this->load->view($this->middle = 'admin/exit',$data,true);
		$this->adminlayout(); 	
		$this->db->close();
	}
	
    public function bankdetails(){
		$user=$this->db->get_where("users",array("id"=>$_POST['id']))->row();
		$this->db->order_by("trid","desc");
							  $chk=$this->db->get_where("user_trans",array("userid"=>$_POST['id']));
								if($chk->num_rows()>0){
									$l=$chk->row();
									//print_r($l);
									 $wallet=$l->left_amt;}else{ $wallet=0;}echo 'Wallet Balance '.$wallet.'<br/>';
		if($user->bank_name!=""){?>
        <table class="table table-condensed table-bordered">
        	<tr><th>Bank Name</th><td><?php echo $user->bank_name;?></td></tr>
        	<tr><th>A/c Holder</th><td><?php echo $user->acc_holder;?></td></tr>
        	<tr><th>A/c Number</th><td><?php echo $user->acc_no;?></td></tr>
        	<tr><th>IFSC Code</th><td><?php echo $user->ifsc;?></td></tr>
        	<tr><th>A/c Type</th><td><?php echo $user->acc_type;?></td></tr>
        </table> 
        <?php 	}else{echo '<h3 class="text-danger">Bank Details Not Updated</h3>';}
	}
	
	public function agent_change_pass(){
		parse_str($_POST['formdata'],$form);
		
		//print_r($form);exit;
		if($form['npass']!=$form['cpass'])
		{
			echo "Your Passwords Doesnot match";exit;
		}else{
		$this->db->where("id",$form['agentid']);
		if($this->db->update("users",array("pchange"=>"yes","password"=>md5($form['npass'])))){echo "Password Changed Successfully.<br/>";}
		}
		
	}
	public function add_money_submit(){
		parse_str($_POST['formdata'],$form);
		$this->db->order_by("trid","desc");
		$chk=$this->db->get_where("user_trans",array("userid"=>$form['user']));
			if($chk->num_rows()>0){
				$l=$chk->row();
				//print_r($l);
				$wallet=$l->left_amt;}else{$wallet=0;}
				// if($form['type']=="Credit"){
				// 	$newbal=$wallet+$form['usdamt'];
				// }else{
				// 	$newbal=$wallet-$form['usdamt'];
				// }




				if($form['type']=="Credit"){

					$newbal=$wallet+$form['usdamt'];
					$tr_type="Credit";
					$remark="Fund Credit";

				}else if($form['type']=="Bonus"){

					$newbal=$wallet+$form['usdamt'];
					$tr_type="Credit";
					$remark="Bonus Credit";

				}else if($form['type']=="Loan Credit"){

					$newbal=$wallet+$form['usdamt'];
					$tr_type="Credit";
					$remark="Loan Credit";

					$this->db->insert("loans",array("loan_amt"=>$form['usdamt'],"loan_user"=>$form['user'],
					"loan_date"=>date("Y-m-d"),"loan_remark"=>$form['remarks']));

				}else if($form['type']=="Loan Debit"){

					$newbal=$wallet-$form['usdamt'];
					$tr_type="Debit";
					$remark="Loan Debit";

				}else{

					$newbal=$wallet-$form['usdamt'];
					$tr_type="Debit";
					$remark="Fund Debit";

				}

				if($this->db->insert("user_trans",array("tr_amt"=>$form['usdamt'],"tr_type"=>$tr_type,"tr_date"=>date("Y-m-d"),"left_amt"=>$newbal,"tr_desc"=>$remark,"userid"=>$form['user']))==true){echo "Balance Updated";}else{echo "Balance Could not be updated.";}
	}
	
	public function userdelete(){
	if($this->db->delete("users",array("id"=>$_POST['id']))){
		$this->db->delete("buysell",array("uid"=>$_POST['id']));
		$this->db->delete("deposites",array("userid"=>$_POST['id']));
		$this->db->delete("user_trans",array("userid"=>$_POST['id']));
		$this->db->delete("withdrawls",array("uid"=>$_POST['id']));
	}
   }
   
   public function userdelete2(){
		$this->db->delete("user_trans",array("trid"=>$_POST['id']));  
		$this->db->delete("user_trades",array("trade_id"=>$_POST['bsid']));  
   }
   public function bankdelete(){
		$this->db->delete("banks",array("bid"=>$_POST['id']));  
   }
public function loan_delete(){
		$this->db->delete("loans",array("loan_id"=>$_POST['id']));  
   }
   
   
   
   public function depdelete(){
	$this->db->delete("deposites",array("depid"=>$_POST['id']));
   }
   public function wdelete(){
	$this->db->delete("withdrawls",array("wid"=>$_POST['id']));
   }
   public function trade_delete(){
		$this->db->delete("buysell",array("bsid"=>$_POST['id']));
		$this->db->delete("user_trans",array("buysell_id"=>$_POST['id']));   
   }

   
  public function loans(){

	$this->db->select("*");

  $this->db->from("loans");

  $this->db->join("users","users.id=loans.loan_user");

//   if($this->session->userdata("type")=='subadmin'){

// 	$this->db->where("users.uadmin_id",$this->session->userdata("userid"));
// }
  $this->db->order_by("loans.loan_id","desc");

	$data['loans']=$this->db->get()->result();

  $this->template['middle'] = $this->load->view ($this->middle = 'admin/loans',$data,true);

  $this->adminlayout(); 

}

   
	 public function trade_limit_form_submit(){
	  	parse_str($_POST['formdata'], $form);
		//echo "<pre>";print_r($form);exit;
		$this->db->where("id",$form['userid']);
		$this->db->update("users",array("umargin"=>$form['umargin'],"trade_limit"=>$form['amt'],"brokarage"=>$form['brokarage'],"max_lot"=>$form['max_lot']));
     }
	 
	public function livedata_rates1(){//echo "Afd";exit;
		$data=array();
		$ub=$this->db->get_where("buysell",array("status"=>"start"))->result();
		//print_r($ub);exit;
		foreach($ub as $u){
			  $p=0;$l=0;
			  $this->db->select_sum('tr_amt');  
			  $this->db->where("userid",$u->uid);
			  $this->db->where("tr_type","Credit");
			  $this->db->where("buysell_id",$u->bsid);
			  $profit=$this->db->get('transaction');
			  if($profit->num_rows()>0){$pro=$profit->row();$p=$pro->tr_amt;}	
			  //loss
			  $this->db->select_sum('tr_amt');  
			  $this->db->where("userid",$u->uid);
			  $this->db->where("tr_type","Debit");
			  $this->db->where("buysell_id",$u->bsid);
			  $loss=$this->db->get('transaction');
			  if($loss->num_rows()>0){$loo=$loss->row();$l=$loo->tr_amt;}
			  if($p>$l){$pll=$p-$l;$color="green";}else{$pll=$l-$p;$color="red";}
			  $prr= $pll.'-'.$u->metal.'-'.$u->metal.$u->bsid.'-'.$color;
			//  $prr= $p-$l.'-'.$u->metal.'-'.$u->metal.$u->bsid;
			  array_push($data,$prr);
		} 	  echo $res=implode("=",$data);
	 }
	
	
	 public function orderbook(){
		$this->db->select("*");
		$this->db->from("buysell");
		$this->db->join("users","users.id=buysell.uid");
		$this->db->where("buysell.status !=","EXIT");
		$this->db->where("buysell.type","BUY");
		$this->db->order_by("buysell.bsid","desc");
		$data['buy']=$this->db->get()->result();
		
		$this->db->select("*");
		$this->db->from("buysell");
		$this->db->join("users","users.id=buysell.uid");
		$this->db->where("buysell.status !=","EXIT");
		$this->db->where("buysell.type","SELL");
		$this->db->order_by("buysell.bsid","desc");
		$data['sell']=$this->db->get()->result();
		
		
		
		$this->template['middle'] = $this->load->view ($this->middle = 'admin/orderbook',$data,true);
   		$this->adminlayout(); 
	 }
	
	public function add_question(){
		//echo "<pre>";print_r($_POST);
		$ans=implode("|",$_POST['ans']);
		$this->db->insert("survey",array("survey"=>$_POST['survey'],"question"=>$_POST['que'],"answers"=>$ans));	
	}
	
	public function add_policy(){
		//echo "<pre>";print_r($_POST);
		$bens=implode("|",$_POST['bens']);
		$this->db->insert("policies",array("name"=>$_POST['title'],"price"=>$_POST['price'],"sdesc"=>$_POST['sdesc'],"ben_details"=>$_POST['ben_desc'],"benefits"=>$bens));	
		redirect("admin/policies");
	}
	
	public function survey(){
		$data['questions']=$this->db->get("survey")->result();
		$this->template['middle'] = $this->load->view ($this->middle = 'admin/survey',$data,true);
		$this->adminlayout();
		redirect("admin/survey");
	}
	
	public function policies(){
		$data['policies']=$this->db->get("policies")->result();
		$this->template['middle'] = $this->load->view ($this->middle = 'admin/policies',$data,true);
		$this->adminlayout();
	}
	
	public function catdelete(){
	if($this->db->delete("category",array("cid"=>$_POST['id'])) && $_POST['img']!="default.png"){
		unlink(base_url()."assets/images/category/".$_POST['img']);		
	}
  }
  
  public function showallf(){
	  //echo "asdf";exit;
		$data['f']=$this->db->get_where("fields",array("sid"=>$_POST['id']))->result();
		$this->load->view("admin/ajax_fields",$data);
  }
  
  public function add_fields(){
	  parse_str($_POST['formdata'],$form);
	  //echo $_POST['id'];exit;
	  $this->db->insert("fields",array("f_title"=>$form['label'],"f_type"=>$form['type'],"f_values"=>$form['vals'],"sid"=>$form['sid']));
	  $data['f']=$this->db->get_where("fields",array("sid"=>$form['sid']))->result();
		$this->load->view("admin/ajax_fields",$data);
  }
  
  public function remove_f(){
	  $this->db->delete("fields",array("fid"=>$_POST['id']));
  }
  //Manage Category Add/Edit
  public function Category($id=false){
		if($id==true){
			$data['editcat']=$this->db->get_where("category",array("cid"=>$id))->row();
		}
		$data['cats']=$this->db->get("category")->result();  
		$this->load->view ($this->middle = 'admin/category',$data,true);
      	$this->adminlayout();
  }
  
  public function in_trend(){
	$this->db->where("sid",$_POST['id']);
	$this->db->update("subcategory",array("in_trend"=>$_POST['v']));  
  }
  public function in_feat(){
	$this->db->where("aid",$_POST['id']);
	$this->db->update("ads",array("feat"=>$_POST['v']));  
  }
  public function ad_status(){
	$this->db->where("aid",$_POST['id']);
	$this->db->update("ads",array("ad_status"=>$_POST['v']));  
  }
  
  
  //Add/Edit Category
  public function add_category($id=false){
	  	if($id==true){
		$img=$this->input->post("oldimg");
		if(!empty($_FILES["img"]["name"])){
				$config['upload_path'] = './assets/images/category/';
				$config['allowed_types'] = 'gif|jpg|png|jpeg|svg';
				$config['max_size']	= '1000000';
				$this->upload->initialize($config);
				if (!$this->upload->do_upload('img'))
				{
				echo $this->upload->display_errors();
				}
				else
				{	
				$pic = $this->upload->data();
				$img=$pic['file_name'];
				}
		}  
			$data=array("cat_name"=>$this->input->post("cat"),"cat_image"=>$img);
			$this->db->where("cid",$id);
			if($this->db->update("category",$data)==true){
				$this->session->set_flashdata("msg","<div class='alert alert-success'>Category Updated Successfully");
			}else{
				$this->session->set_flashdata("msg","<div class='alert alert-warning'>Category Couldnot be Updated");
			}	
		}else{
		$img="default.png";
		if(!empty($_FILES["img"]["name"])){
				$config['upload_path'] = './assets/images/category/';
				$config['allowed_types'] = 'gif|jpg|png|jpeg|svg';
				$config['max_size']	= '1000000';
				$this->upload->initialize($config);
				if (!$this->upload->do_upload('img'))
				{
				echo $this->upload->display_errors();
				}
				else
				{	
				$pic = $this->upload->data();
				$img=$pic['file_name'];
				}
		}  
			$data=array("cat_name"=>$this->input->post("cat"),"cat_image"=>$img);
			if($this->db->insert("category",$data)==true){
				$this->session->set_flashdata("msg","<div class='alert alert-success'>Category Added Successfully");
			}else{
				$this->session->set_flashdata("msg","<div class='alert alert-warning'>Category Couldnot be Added");
			}
		}
		redirect("admin/category");
  }
  
  //Remove Subcategory
  public function subcatdelete(){
	if($this->db->delete("subcategory",array("sid"=>$_POST['id'])) && $_POST['img']!="default.png"){
		 unlink(base_url()."assets/images/category/".$_POST['img']);	
	}
  }
  //Manage Category Add/Edit
  public function Subcategory(){
	  	$this->load->library('pagination');

		$config['base_url'] = 'http://localhost/22kstreet/';
		$config['total_rows'] = $this->db->get("subcategory")->num_rows();
		$config['per_page'] = 1; 
		
		$this->pagination->initialize($config); 

	  	$data['cats']=$this->db->get("category")->result();  
		$data['subcats']=$this->db->get("subcategory")->result();  
		$this->load->view ($this->middle = 'admin/subcategory',$data,true);
      	$this->adminlayout();
  }
  //Add/Edit Category
  public function add_subcategory(){
		$img="default.png";
		if(!empty($_FILES["img"]["name"])){
				$config['upload_path'] = './assets/images/category/';
				$config['allowed_types'] = 'gif|jpg|png|jpeg|svg';
				$config['max_size']	= '1000000';
				$this->upload->initialize($config);
				if (!$this->upload->do_upload('img'))
				{
				echo $this->upload->display_errors();
				}
				else
				{	
				$pic = $this->upload->data();
				$img=$pic['file_name'];
				}
		}  
			$data=array("cid"=>$this->input->post("cat"),"subcat_name"=>$this->input->post("subcat"),"subcat_image"=>$img,"subcat_name"=>$this->input->post("subcat"),"service"=>$this->input->post("desc"),"feature"=>$this->input->post("feature"),"monthly"=>$this->input->post("mon"),"quarterly"=>$this->input->post("quar"),"half"=>$this->input->post("half"),"yearly"=>$this->input->post("year"));
			if($this->db->insert("subcategory",$data)==true){
				$this->session->set_flashdata("msg","<div class='alert alert-success'>SubCategory Added Successfully");
			}else{
				$this->session->set_flashdata("msg","<div class='alert alert-warning'>SubCategory Couldnot be Added");
			}
		redirect("admin/subcategory");
  }
  //Ajax Show subcategory to update in modal box
  public function ajax_showsubcat(){
		$sub=$this->db->get_where("subcategory",array("sid"=>$_POST['id']))->row();
		echo json_encode($sub);  
  }
  public function update_subcategory(){
	//print_r($_POST);
		
			$data=array("subcat_name"=>$this->input->post("subcat"),"cid"=>$_POST['cat'],"service"=>$this->input->post("desc"),"feature"=>$this->input->post("feature"),"monthly"=>$this->input->post("mon"),"quarterly"=>$this->input->post("quar"),"half"=>$this->input->post("half"),"yearly"=>$this->input->post("year"));
			$this->db->where("sid",$_POST['sid']);
			if($this->db->update("subcategory",$data)==true){
				$sub=$this->db->get_where("subcategory",array("sid"=>$_POST['sid']))->row();
				echo json_encode($sub);
				//$this->session->set_flashdata("msg","<div class='alert alert-success'>Category Updated Successfully");
			}else{
				//$this->session->set_flashdata("msg","<div class='alert alert-warning'>Category Couldnot be Updated");
			}  
  }
	
	public function offerusers(){
		  $data['ad']=$this->db->get_where("ads",array("aid"=>$_POST['aid']))->row();
		  $data['users']=$this->db->get_where("offers",array("aid",$_POST['aid']))->result();
		  $this->load->view('admin/offer_users',$data);
	  }
	  
	public function userchat(){
		$offer= $this->db->get_where("offers",array("oid"=>$_POST['oid']))->row();  
		echo '  <h3 class="text-success">Offer Amount AED '.$offer->offer_amt.'</h3><hr/><div class="friend-msg-wrap">
                 <img class="user-img img-circle block pull-left" src="'.base_url().'assets/images/author/img-08.jpg" alt="user">
                                                   
													<div class="msg pull-left">'.$offer->msg.'
                                                        <div class="msg-per-detail mt-5">
                                                            <span class="msg-per-name txt-success">'.$offer->rname.'</span>
                                                            <span class="msg-time txt-grey">'.date('d M Y',strtotime($offer->rdate)).'</span>
                                                        </div>
                                                    </div>
                                                    <div class="clearfix"></div>
                                                </div>';
	  }  
	
	public function ads($user=false){
		$this->db->select("*");
		$this->db->from('ads');
		$this->db->join("category","ads.cid=category.cid");
		$this->db->join("subcategory","ads.sid=subcategory.sid");
		$this->db->order_by("ads.aid","desc");
		if($user==true){
		$this->db->where("uid",$user);	
		}
		$data['ads']=$this->db->get()->result();
		$this->load->view ($this->middle = 'admin/ads',$data,true);
      	$this->adminlayout();
	}
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	public function manage_expense_fields(){
		$data['types']=$this->db->get("expense_types")->result();
		$this->template['middle'] = $this->load->view ($this->middle = 'admin/manage_expense_fields',$data,true);
		$this->adminlayout(); 
	
	}
	
	public function ad_delete(){
		$this->db->delete("ads",array("aid"=>$_POST['id']));
	}
	public function delete_users(){
	$this->db->delete("users",array("id"=>$_POST['id']));
	$this->db->delete("ads",array("uid"=>$_POST['id']));
	}
	
	
	public function exp_fields(){
	$f=$this->db->get_where("fields",array("expid"=>$_POST['id']))->result();
	foreach($f as $ff){
		if($ff->ftype=="textarea"){?>
        <div class="form-group label-floating">
            <label class="control-label"><?php echo $ff->fname;?></label>
            <textarea rows="4" class="form-control" name="<?php echo str_replace(" ","_",$ff->fname);?>"></textarea>
        </div>
        <?php 	}else if($ff->ftype=="selecte"){
			$em=$this->db->get("employees")->result();?>
        <div class="form-group label-floating">
            <select class="form-control" name="employees">
            	<option value="">Select Employee</option>
                <?php foreach($em as $emp){?>
                <option value="<?php echo $emp->id;?>"><?php echo $emp->ename;?></option>
                <?php }?>
            </select>
        </div>
        <?php 	}else if($ff->ftype=="selects"){
			$em=$this->db->get("suppliers")->result();?>
        <div class="form-group label-floating">
            <select class="form-control" name="suppliers">
            	<option value="">Select Suppliers</option>
                <?php foreach($em as $emp){?>
                <option value="<?php echo $emp->sid;?>"><?php echo $emp->sname;?></option>
                <?php }?>
            </select>
        </div>
        <?php 	}if($ff->ftype=="selectv"){
			$em=$this->db->get("vehicles")->result();?>
        <div class="form-group label-floating">
            <select class="form-control" name="vehicles">
            	<option value="">Select Vehicle</option>
                <?php foreach($em as $emp){?>
                <option value="<?php echo $emp->vid;?>"><?php echo $emp->make." ".$emp->model." ".$emp->vnumber;?></option>
                <?php }?>
            </select>
        </div>
        <?php 	}else if($ff->ftype=="number"){?>
        <div class="form-group label-floating">
            <label class="control-label"><?php echo $ff->fname;?></label>
            <input type="number" name="<?php echo $ff->fname;?>" class="form-control">
        </div>
        <?php 	}else if($ff->ftype=="text"){?>
        <div class="form-group label-floating">
            <label class="control-label"><?php echo $ff->fname;?></label>
            <input type="text" name="<?php echo $ff->fname;?>" class="form-control">
        </div>
        <?php }
	}
	}
	
	
	
  
    public function login(){//print_r($_POST);
	$this->form_validation->set_rules('username', 'Username', 'required');
	$this->form_validation->set_rules('password', 'Password', 'required');  
	if($this->form_validation->run() == FALSE)
		{
			redirect("admin");
		}
		else
		{		
			$chk=$this->db->get_where("admin",array("username"=>$this->input->post("username"),"password"=>md5($this->input->post("password"))));
			if($chk->num_rows()>0)
			{
				$data=array("admin"=>"true",
							"user"=>"admin","userid"=>0);
							$this->session->set_userdata($data);
							redirect("admin");
			}
			else
			{
			$chk=$this->db->get_where("employees",array("eemail"=>$this->input->post("username"),"epass"=>md5($this->input->post("password"))));
			if($chk->num_rows()>0)
			{
				$u=$chk->row();
				$data=array("admin"=>"true",
							"user"=>"user","userid"=>$u->id,"username"=>$u->ename);
							$this->session->set_userdata($data);
							redirect("admin");
			}else{
			$this->session->set_flashdata('msg', 'Invalid Username or Password.');	
			redirect("admin");
			}}
		}
  }
  
  public function usercom($id){
		$data['cdata']=array();//$this->db->get_where("campaigns",array("id"=>$cid))->row();	
		$this->template['middle'] = $this->load->view($this->middle = 'admin/usercom',$data,true);
		$this->adminlayout();
  } 
  
  public function logout(){
	$this->session->sess_destroy();
	redirect("admin");
  }
  public function approve_form_submit(){
	  	parse_str($_POST['formdata'], $form);
		$this->db->where("depid",$form['depid']);
		$this->db->update("deposites",array("dep_status"=>$form['status'],"dep_remarks"=>$form['remarks'],"status_date"=>date("Y-m-d")));
		if($form['status']=="Approved"){
		$this->db->order_by("trid","desc");
		$chk=$this->db->get_where("user_trans",array("userid"=>$form['uid']));
  		if($chk->num_rows()>0){
			$l=$chk->row();
			$last_bal=$l->left_amt;
		    $newbal=$last_bal+$form['amt'];//exit;
			$this->db->insert("user_trans",array("tr_amt"=>$form['amt'],"tr_type"=>"Credit","tr_date"=>date("Y-m-d"),"left_amt"=>$newbal,"userid"=>$form['uid']));
		}else{
			$this->db->insert("user_trans",array("tr_amt"=>$form['amt'],"tr_type"=>"Credit","tr_date"=>date("Y-m-d"),"left_amt"=>$form['amt'],"userid"=>$form['uid']));
		}
		}
  }

  public function wapprove_form_submit(){
	  	parse_str($_POST['formdata'], $form);
		$this->db->where("wid",$form['wid']);
		$this->db->update("withdrawls",array("req_status"=>$form['status'],"remarks"=>$form['remarks'],"req_date"=>date("Y-m-d")));
		if($form['status']=="Approved"){//
		$this->db->order_by("trid","desc");
		$chk=$this->db->get_where("user_trans",array("userid"=>$form['uid']));
  		if($chk->num_rows()>0){
			$l=$chk->row();
			$last_bal=$l->left_amt;
		    $newbal=$last_bal-$form['amt'];//exit;
			$this->db->insert("user_trans",array("tr_amt"=>$form['amt'],"tr_type"=>"Debit","tr_date"=>date("Y-m-d"),"left_amt"=>$newbal,"userid"=>$form['uid']));
		}else{
			$this->db->insert("user_trans",array("tr_amt"=>$form['amt'],"tr_type"=>"Debit","tr_date"=>date("Y-m-d"),"left_amt"=>$form['amt'],"userid"=>$form['uid']));
		}
		}
  }  
  
  public function users(){
	    $this->db->select("*");
		$this->db->from("users");
		//$this->db->join("subadmins","subadmins.subadmin_id=users.subad_id","left");
	    $this->db->order_by("users.id","desc");
		//if($this->session->userdata("type")=="subadmin"){
//			$this->db->where("users.subad_id",$this->session->userdata("userid"));
//		}
	  	$data['users']=$this->db->get()->result();
		$this->template['middle'] = $this->load->view ($this->middle = 'admin/users',$data,true);
		$this->adminlayout(); 
  }
  
  public function user_report($id){
	    $this->db->select("*");
		$this->db->from("user_trans");
		$this->db->join("user_trades","user_trans.buysell_id=user_trades.trade_id","left");
		$this->db->order_by("user_trans.trid","desc");
		$this->db->where("user_trans.userid",$id);
		$data['report']=$this->db->get()->result();
		$this->template['middle'] = $this->load->view ($this->middle = 'admin/ureport',$data,true);
		$this->adminlayout(); 
  }
  
  public function deposites($type=""){
	  	$this->db->select("*");
		$this->db->from("deposites");
		$this->db->join("users","users.id=deposites.userid");
		$this->db->where("deposites.dep_status",$type);
		if($this->session->userdata("type")=="subadmin"){
			$this->db->where("users.subad_id",$this->session->userdata("userid"));
		}
	    $this->db->order_by("deposites.dep_submit_date","desc");
	  	$data['deposites']=$this->db->get()->result();
		//echo "<pre>";print_r($data);exit;
		$this->template['middle'] = $this->load->view ($this->middle = 'admin/deposites',$data,true);
		$this->adminlayout(); 
  }
  
  public function withdrawls($type=""){
	  	$this->db->select("*");
		$this->db->from("withdrawls");
		$this->db->join("users","users.id=withdrawls.uid");
		$this->db->where("withdrawls.req_status",$type);
		if($this->session->userdata("type")=="subadmin"){
			$this->db->where("users.subad_id",$this->session->userdata("userid"));
		}
	    $this->db->order_by("withdrawls.wid","desc");
	  	$data['withdrawls']=$this->db->get()->result();
		$this->template['middle'] = $this->load->view ($this->middle = 'admin/withdrawls',$data,true);
		$this->adminlayout(); 
  }

  
  public function transactions(){
	  	$this->db->order_by("trid","desc");
	  	$this->db->where("tr_from",$_POST['id']);
		$this->db->or_where("tr_to",$_POST['id']);
		$data['trns']=$this->db->get("transactions")->result();
		$bal=0;
		$this->db->order_by("trid","desc");
		$this->db->where("tr_from",$_POST['id']);
		$this->db->or_where("tr_to",$_POST['id']);
		$chk=$this->db->get("transactions");
		if($chk->num_rows()>0){$t=$chk->row();$bal=$t->tr_bal;}
		$data['bal']=$bal;
		$this->load->view("transactions",$data);
  }
  
  public function userview(){
		$data['user']=$this->db->get_where("users",array("id"=>$_POST['uid']))->row();
		$this->load->view("userview",$data);  
  }
  
  public function trans_delete(){
	$this->db->delete("transactions",array("trid"=>$_POST['trid']));  
  }
  
  public function add_money(){
	  	$this->db->order_by("trid","desc");
	  	parse_str($_POST['formdata'],$form);
		//print_r($form);exit;
	  	$bal=0;
		$this->db->where("tr_from",$form['uid']);
		$this->db->or_where("tr_to",$form['uid']);
		$chk=$this->db->get("transactions");
		if($chk->num_rows()>0){$t=$chk->row();$bal=$t->tr_bal;}
		$bal=$bal+$form['amt'];
		$data['bal']=$bal;
		$this->db->insert("transactions",array("tr_type"=>"Credit","tr_bal"=>$bal,"tr_amt"=>$form['amt'],"tr_from"=>0,"tr_to"=>$form['uid'],"tr_date"=>date("Y-m-d")));  
		$this->db->order_by("trid","desc");
		$this->db->where("tr_from",$form['uid']);
		$this->db->or_where("tr_to",$form['uid']);
		$data['trns']=$this->db->get("transactions")->result();
		$this->load->view("transactions",$data);
  }
 
	public function ContactEnquiries(){
		$data['contacts']=$this->db->get("contact")->result();
		$this->template['middle'] = $this->load->view($this->middle = 'admin/contacts',$data,true);
		$this->adminlayout(); 	
	}

	public function notifications(){
		$this->db->select("*");
		$this->db->from("notifs");
		$this->db->join("users","users.id=notifs.nuser","left");

		$this->db->order_by("notifs.nid","desc");
		$data['list']=$this->db->get()->result();
		$this->template['middle'] = $this->load->view($this->middle = 'admin/notifs',$data,true);
		$this->adminlayout(); 	
	}

	public function deletecon(){
		$this->db->delete("contact",array("cn_id"=>$_POST['id']));	
	}
	public function ndelete(){
		$this->db->delete("notifs",array("nid"=>$_POST['id']));	
	}
	

	public function sendn(){
		//if($_POST['users']=='All'){

		//}else{
			$this->db->insert("notifs",array("ntitle"=>$_POST['ntitle'],"ndesc"=>$_POST['ndesc'],"nuser"=>$_POST['nuser'],"ndatetime"=>date("Y-m-d h:i:s")));
		//}
		redirect("admin/notifications");
	}
	
	public function change_pass(){
		parse_str($_POST['formdata'],$form);
		if($form['npass']!=$form['cpass'])
		{
			echo "Your Passwords Doesnot match";exit;
		}
		
		$chk=$this->db->get_where("admin",array("id"=>1,"password"=>md5($form['opass'])));
		if($chk->num_rows()>0)
			{
				$this->db->where("id",1);
				if($this->db->update("admin",array("password"=>md5($form['npass'])))){echo "Password Changed Successfully.";}
			}
			else{
				echo "Incorrect Password";
			}
		
	}
	
	
	
	
  
  public function deleteAd($id){
	$this->db->delete("campaigns",array("id"=>$id));
	$this->db->delete("tasks",array("taskid"=>$id));
	$this->session->set_flashdata('msg', 'Ad deleted Successfully.');	
	redirect("admin/allCampaigns");
  }
  
  
}
?>