<?php header('Access-Control-Allow-Origin: *');
defined('BASEPATH') OR exit('No direct script access allowed');
class Home extends MY_Controller {
	function __construct(){
        parent::__construct();
		date_default_timezone_set('Asia/Kolkata');
		error_reporting(0);
		//redirect("home");
    }
	
	public function forex(){
	//	$currs=$this->db->get_where("curr_pips",array("curr_status"=>"yes"))->result();
	//	echo "<pre>";print_r($currs);exit;
		$this->load->view('forex');
	}


	
	public function forex0(){
		$this->load->view('forex0');
	}

	public function newforex(){
		$this->load->view('newforex');
	}

	public function ajax_switch_market(){
		$st=$this->db->get("admin")->row();	
		if($st->live_market=='LIVE'){
			$this->db->update("admin",array("live_market"=>"STOP"));
			echo 'STOP';	
		}else{
			$this->db->update("admin",array("live_market"=>"LIVE"));
			echo 'LIVE';
		}
	}
	
	public function ajax_exit_trades(){

		$this->db->select("*");
		$this->db->from("user_trades");
		$this->db->join("users","users.id=user_trades.userid");

		
		$this->db->order_by("user_trades.trade_exit_time","desc");
		$this->db->where("user_trades.trade_status","EXIT");
		$this->db->like("user_trades.trade_exit_time",date("Y-m-d"));
		
		$data['trades']=$this->db->get()->result();
		//echo "<pre>";print_r($data);exit;
		$this->load->view("ajax_exit_trades",$data);	
	}
	
	public function ajax_forgot_pass(){
		$newpass=rand(100000,999999);
		
		// the message
		$to = "info@aurofxmarket.in";
		$subject = "Password Reset";
		$txt = "Your New Password is ".$newpass;
		$headers = "From: info@aurofxmarket.in";
		
		if(mail($to,$subject,$txt,$headers)==true){
			$this->db->where("id",1);
			$this->db->update("admin",array("password"=>md5($newpass)));
			echo "Your New Password sent to email";	
		}else{
			echo "Your Password mail could not be sent";
		}
	}
	
	public function update_profile(){
		$this->db->where("id",$this->session->userdata("user"));
		$query=$this->db->update("users",array("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('home/profile');
	}
		
	public function ajax_pending_trades(){
		$this->db->select("*");
		$this->db->from("user_trades");
		$this->db->join("users","users.id=user_trades.userid");

		
		$this->db->order_by("user_trades.trade_id","desc");
		$this->db->where("user_trades.trade_status","Pending");
		
		$data['trades']=$this->db->get()->result();

		//echo "<pre>";print_r($data);exit;
		$this->load->view("ajax_exit_trades",$data);	
	}

	public function ajax_square_off(){
		$this->db->where("trade_id",$_POST['id']);
		$this->db->update("user_trades",array("trade_status"=>"EXIT","trade_exit_time"=>date("Y-m-d h:i a")));	
				$user=$this->db->get_where("user_trades",array("trade_id"=>$_POST['id']))->row();
				$this->db->order_by("trid","desc");
				$chk=$this->db->get_where("user_trans",array("userid"=>$user->userid))->row();
				
				//print_r($l);
				$wallet=$chk->left_amt;
				//if($user->profit_loss>0){
//					$newbal=$wallet+$user->profit_loss;
//				}else{
					$newbal=$wallet+$user->profit_loss;
				//}
				if($user->profit_loss>0){
				$typ="Trade Credit";	
				}else{
				$typ="Trade Debit";	
				}
				$this->db->insert("user_trans",array("buysell_id"=>$user->userid,"tr_amt"=>$user->profit_loss,"tr_type"=>$typ,"tr_date"=>date("Y-m-d"),"left_amt"=>$newbal,"userid"=>$user->userid));
				echo $newbal;
	}
	
	public function ajax_exit_trade2(){
		parse_str($_POST['formdata'],$_POST);
		//echo "<pre>";print_r($_POST);exit;
		$this->db->where("trade_id",$_POST['id']);
		$this->db->update("user_trades",array("profit_loss"=>$_POST['proloss'],"trade_status"=>"EXIT","trade_exit_time"=>date("Y-m-d h:i a")));	
				$user=$this->db->get_where("user_trades",array("trade_id"=>$_POST['id']))->row();
				$this->db->order_by("trid","desc");
				$chk=$this->db->get_where("user_trans",array("userid"=>$user->userid))->row();
				
				//print_r($l);
				$wallet=$chk->left_amt;
				//if($user->profit_loss>0){
//					$newbal=$wallet+$user->profit_loss;
//				}else{
					$newbal=$wallet+$user->profit_loss;
				//}
				if($user->profit_loss>0){
				$typ="Trade Credit";	
				}else{
				$typ="Trade Debit";	
				}
				$this->db->insert("user_trans",array("buysell_id"=>$user->userid,"tr_amt"=>$user->profit_loss,"tr_type"=>$typ,"tr_date"=>date("Y-m-d"),"left_amt"=>$newbal,"userid"=>$user->userid));
				echo $newbal;
	}
	
	public function ajax_close_trade(){
		$this->db->where("trade_id",$_POST['id']);
		$this->db->update("user_trades",array("trade_status"=>"EXIT","trade_exit_time"=>date("Y-m-d h:i a")));	
				$user=$this->db->get_where("user_trades",array("trade_id"=>$_POST['id']))->row();
				$this->db->order_by("trid","desc");
				$chk=$this->db->get_where("user_trans",array("userid"=>$user->userid))->row();
				
				//print_r($l);
				$wallet=$chk->left_amt;
				//if($user->profit_loss>0){
//					$newbal=$wallet+$user->profit_loss;
//				}else{
					$newbal=$wallet+$user->profit_loss;
				//}
				if($user->profit_loss>0){
				$typ="Trade Credit";	
				}else{
				$typ="Trade Debit";	
				}
				$this->db->insert("user_trans",array("buysell_id"=>$user->userid,"tr_amt"=>$user->profit_loss,"tr_type"=>$typ,"tr_date"=>date("Y-m-d"),"left_amt"=>$newbal,"userid"=>$user->userid));
				echo $newbal;
	}
	
	public function ajax_delete_trade(){
		$this->db->delete("user_trades",array("trade_id"=>$_POST['id']));	
	}
	
	public function ajax_edit_trade(){
		$data['edit']=$this->db->get_where("user_trades",array("trade_id"=>$_POST['id'],"trade_status!="=>"EXIT"))->row();
		//print_r($data);exit;
		$this->load->view("ajax_edit_trade",$data);
	}
	
	public function ajax_update_trade(){
		
	}
	
	
	
	public function trade_submit(){
		$exec='';
		//echo "<pre>";print_r($_POST);exit;
		if($_POST['pending_val']!=''){
			$trd_price=$_POST['pending_val'];
			if($_POST['trade_type']=='BUY'){
				if($trd_price>$_POST['buy_price']){
					$exec="plus";
				}else{
					$exec='minus';
				}
			}else{
				if($trd_price>$_POST['sell_price']){
					$exec="plus";
				}else{
					$exec='minus';
				}
			}	
		}else
		if($_POST['trade_type']=='BUY'){
			$trd_price=$_POST['buy_price'];
		}else{
			$trd_price=$_POST['sell_price'];
		}
		$pip=$this->db->get_where("curr_pips",array("curr_name"=>str_replace("_","",$_POST['pair'])))->row();
		$data=array("exec_type"=>$exec,"trade_start_time"=>date("Y-m-d h:i a"),"pending_val"=>$_POST['pending_val'],"trade_status"=>$_POST['order_type'],"userid"=>$_POST['user'],"cpair"=>$_POST['pair'],"curr_pip_val"=>$pip->pip_usd,"buy_price"=>$_POST['buy_price'],"trade_price"=>$trd_price,"sell_price"=>$_POST['sell_price'],"lotsize"=>$_POST['lotsize'],"target"=>$_POST['target'],"stoploss"=>$_POST['stoploss'],"trade_type"=>$_POST['trade_type']);
		if($this->db->insert("user_trades",$data)==true){
			redirect("home/forex");	
		}else{
			redirect("home/forex");
		}
	}
	
	
	
	public function active_trades(){
			
	}
	
	public function change_form(){
		$trds=$this->db->get_where("user_trades",array("cpair"=>$_POST['pair'],"trade_status"=>"Market"));
				//if($trds->num_rows()>0){
				$trds=$trds->result();
				foreach($trds as $trd){
				$decim=strlen(substr(strrchr($pair[0], "."), 1));
				$decim=str_pad(1, $decim+1, '0', STR_PAD_RIGHT);
				if($trd->trade_type=="BUY"){
					if($trd->target!='' && $pair[1]>=$trd->target){
						$trd_status='EXIT';
						$tr_exit_time=date("Y-m-d h:i a");
						$diff=$trd->target-$trd->trade_price;	
					}else
					if($trd->stoploss!='' && $trd->stoploss>=$pair[1]){
						$trd_status='EXIT';
						$tr_exit_time=date("Y-m-d h:i a");
						$diff=$trd->stoploss-$trd->trade_price;	
					}else{
						$diff=$pair[1]-$trd->trade_price;	
					}
				}else{
					if($trd->target!='' && $pair[0]>=$trd->target){
						$trd_status='EXIT';
						$tr_exit_time=date("Y-m-d h:i a");
						$diff=$trd->target-$trd->trade_price;	
					}else
					if($trd->stoploss!='' && $trd->stoploss>=$pair[0]){
						$trd_status='EXIT';
						$tr_exit_time=date("Y-m-d h:i a");
						$diff=$trd->stoploss-$trd->trade_price;	
					}else{
						$diff=$trd->trade_price-$pair[0];
					}
				}
				
				
				//echo '<br/>'.$pair[1].'<br/>'.$pair[0];
				//echo $diff.'<br/>';
				$diff=round($diff,5)*$decim;//.'----';
				//if($diff!=0){
				$prol=round($diff*$trd->curr_pip_val*$trd->lotsize,2);//.'==';//$trd->lotsize;
				//echo $prol.'<br/>';
				if($prol>=0){
				$pro_loss_color='#52BE80';	
				}else{
				$pro_loss_color='#E74C3C';	
				}
				
				if($this->db->get_where("admin",array("live_market"=>"STOP"))->num_rows()==0){
				$this->db->where("trade_id",$trd->trade_id);
				$this->db->update("user_trades",array("trade_exit_time"=>$tr_exit_time,"trade_status"=>$trd_status,"pro_loss_color"=>$pro_loss_color,"trd_buy_color"=>$buy_color,"trd_sell_color"=>$sell_color,"profit_loss"=>$prol,"buy_price"=>$pair[1],"sell_price"=>$pair[0]));
				}
				
				if($trd_status=="EXIT"){
					//$user=$this->db->get_where("user_trades",array("trade_id"=>$_POST['id']))->row();
					$this->db->order_by("trid","desc");
					$chk=$this->db->get_where("user_trans",array("userid"=>$trd->userid))->row();
					
					//print_r($l);
					$wallet=$chk->left_amt;
					//if($user->profit_loss>0){
	//					$newbal=$wallet+$user->profit_loss;
	//				}else{
						$newbal=$wallet+$prol;
					//}
					$this->db->insert("user_trans",array("buysell_id"=>$trd->userid,"tr_amt"=>$prol,"tr_type"=>"Trade Credit","tr_date"=>date("Y-m-d"),"left_amt"=>$newbal,"userid"=>$trd->userid));	
				}
				
				
				
				//}
			}
	}
	
	public function ajax_setloss(){	
		$this->db->where("trade_id",$_POST['trd']);
		$this->db->update("user_trades",array("profit_loss"=>$_POST['loss']));	
	}
	
	public function ajax_setlot(){	
		$this->db->where("trade_id",$_POST['trd']);
		$this->db->update("user_trades",array("lotsize"=>$_POST['lotsize'],"trade_price"=>$_POST['buy_price'],"trade_start_time"=>$_POST['trade_start_time']));	
	}

	public function ajax_trade_calc0(){
				//echo "<pre>";print_r($_POST);exit;
				
				$sym=str_replace("/","_",$_POST['symbol']);
				$sym1=str_replace("/","",$_POST['symbol']);
				$price=$_POST['price'];
				$trd_status='Market';$tr_exit_time='';
				$trds=$this->db->get_where("user_trades",array("cpair"=>$sym,"trade_status"=>"Market","hold_status!="=>"On"));
				
				$trds=$trds->result();
				foreach($trds as $trd){
				
				if($trd->trade_type=="SELL"){
					$diff=$trd->trade_price-$price;	
					
				}else{
					$diff=$price-$trd->trade_price;
					
				}

				if($trd->target!='' && $trd->target<=$price){
					if($trd->trade_type=="SELL"){
					$diff=$trd->trade_price-$trd->target;						
					}else{
					$diff=$trd->target-$trd->trade_price;	
					}
					
				$prol=round(($diff*$trd->lotsize/1*$trd->curr_pip_val),2);//.'==';//$trd->lotsize;
$this->db->where("trade_id",$trd->trade_id);
		$this->db->update("user_trades",array("trade_status"=>"EXIT","trade_exit_time"=>date("Y-m-d h:i a")));	
				$this->db->order_by("trid","desc");
				$chk=$this->db->get_where("user_trans",array("userid"=>$trd->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"=>$trd->trade_id,"tr_amt"=>$prol,"tr_type"=>$typ,"tr_date"=>date("Y-m-d"),"left_amt"=>$newbal,"userid"=>$trd->userid));
				;;echo json_encode(array("status"=>0,"msg"=>"Order Exit Successfully"));
				}
				if($trd->stoploss!='' && $trd->stoploss>=$price){
					if($trd->trade_type=="SELL"){
					$diff=$trd->trade_price-$trd->stoploss;						
					}else{
					$diff=$trd->stoploss-$trd->trade_price;	
					}
					
				$prol=round(($diff*$trd->lotsize/1*$trd->curr_pip_val),2);//.'==';//$trd->lotsize;
$this->db->where("trade_id",$trd->trade_id);
		$this->db->update("user_trades",array("trade_status"=>"EXIT","trade_exit_time"=>date("Y-m-d h:i a")));	
				$this->db->order_by("trid","desc");
				$chk=$this->db->get_where("user_trans",array("userid"=>$trd->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"=>$trd->trade_id,"tr_amt"=>$prol,"tr_type"=>$typ,"tr_date"=>date("Y-m-d"),"left_amt"=>$newbal,"userid"=>$trd->userid));
				//echo json_encode(array("status"=>0,"msg"=>"Order Exit Successfully"));
				}
				
				$prol=round(($diff*$trd->lotsize/1*$trd->curr_pip_val),2);//.'==';//$trd->lotsize;
			
				if($prol>=0){
				$pro_loss_color='#52BE80';	
				}else{
				$pro_loss_color='#E74C3C';	
				}
				//if($this->db->get_where("admin",array("live_market"=>"STOP"))->num_rows()==0){
				$this->db->where("trade_id",$trd->trade_id);
				$this->db->where("trade_status!=","EXIT");
				$this->db->update("user_trades",array("pro_loss_color"=>$pro_loss_color,"profit_loss"=>$prol,"buy_price"=>$price,"sell_price"=>$price-0.2));
				//}
			}
				
			
			$this->db->where("curr_name",$sym1);
			$this->db->update("curr_pips",array("cbuy_price"=>$price,"csell_price"=>$price-0.2,"cupdate"=>date("h:i a")));
			echo "Updated";
	}

	public function square_off_apix($id){

				$user=$this->db->get_where("user_trades",array("trade_id"=>$id))->row();
				$uu=$this->db->get_where("users",array("id"=>$user->userid))->row();
				if($uu->pchange=='yes'){
						echo json_encode(array("status"=>1,"msg"=>"Couldnot process request"));exit;
				}
		$this->db->where("trade_id",$id);
		$this->db->update("user_trades",array("trade_status"=>"EXIT","trade_exit_time"=>date("Y-m-d h:i a")));	
				$this->db->order_by("trid","desc");
				$chk=$this->db->get_where("user_trans",array("userid"=>$user->userid))->row();
				
				//print_r($l);
				$wallet=$chk->left_amt;
				//if($user->profit_loss>0){
//					$newbal=$wallet+$user->profit_loss;
//				}else{
					$newbal=$wallet+$user->profit_loss;
				//}
				if($user->profit_loss>0){
				$typ="Trade Credit";	
				}else{
				$typ="Trade Debit";	
				}
				if($this->db->get_where("user_trans",array("buysell_id"=>$id))->num_rows()==0){
				$this->db->insert("user_trans",array("buysell_id"=>$id,"tr_amt"=>$user->profit_loss,"tr_type"=>$typ,"tr_date"=>date("Y-m-d"),"left_amt"=>0,"userid"=>$user->userid));
				echo json_encode(array("status"=>0,"msg"=>"Order Exit Successfully"));
				}
	}
	
	public function ajax_trade_calc(){
		//echo "<pre>";print_r($_POST);
		foreach($_POST['alldata'] as $all){
				$pair=explode("|",$all);
				//echo "<pre>";print_r($pair);
				$bcol=explode(",",$pair[3]);
				$scol=explode(",",$pair[4]);
				if($bcol[0]=='rgba(222'){
					$buy_color='#46D60C';	
				}else if($pair[0]=='rgba(251'){
					$buy_color='#FF6959';	
				}else{
					$buy_color='transparent';	
				}
				
				if($scol[0]=='rgba(222'){
					$sell_color='#46D60C';	
				}else if($scol[0]=='rgba(251'){
					$sell_color='#FF6959';	
				}else{
					$sell_color='transparent';	
				}
				
				$trd_status='Market';$tr_exit_time='';
				///echo $sell_color.'-'.$buy_color.'<br/>';
				$trds=$this->db->get_where("user_trades",array("cpair"=>$pair[2],"trade_status"=>"Market","hold_status!="=>"On"));
				
				//if($trds->num_rows()>0){
				$trds=$trds->result();
				//echo "<pre>";print_r($trds);//exit;
				foreach($trds as $trd){

					
				$decim=strlen(substr(strrchr($pair[0], "."), 1));
				$decim=str_pad(1, $decim+1, '0', STR_PAD_RIGHT);
				if($trd->trade_type=="BUY"){
					$diff=$pair[0]-$trd->trade_price;	
					$price=$pair[0];
				}else{
					$diff=$trd->trade_price-$pair[1];
					$price=$pair[1];
				}

				$this->db->order_by("trid","desc");
				$chk=$this->db->get_where("user_trans",array("userid"=>$trd->userid))->row();
				$wallet=$chk->left_amt;

				$this->db->select_sum('profit_loss');  
				$this->db->where("trade_status","MARKET"); 
				$this->db->where("userid",$trd->userid); 
				$br=$this->db->get('user_trades')->row();
				$total_pl=$br->profit_loss;
				
				if($total_pl<0){
					//echo $trd->userid.'--->'.$total_pl.'<br/>';
					$wallet=$wallet+$total_pl;
				//	echo $wallet.'<br/>';
					if($wallet<=0){
					$trdss=$this->db->get_where("user_trades",array("trade_status"=>"Market","userid"=>$trd->userid))->result();
					foreach($trdss as $ttrr){
					$this->square_off_apix($ttrr->trade_id);
					}
				}
				}
				

				if($trd->trade_type=="BUY"){
					if($trd->target!='' && $price>=$trd->target){
						$diff=$trd->target-$trd->trade_price;	
						$pprice=$trd->target;
						//if($trd->target>$pair[0]){$pprice=$pair[0];}
						$dd=array();

						$prol=round(($diff*$trd->lotsize/1*$trd->curr_pip_val),2);//.'==';//$trd->lotsize;
						$newbal=$wallet+$prol;
							
						$this->db->where("trade_id",$trd->trade_id);
						$this->db->update("user_trades",array("profit_loss"=>$prol,"trade_status"=>"EXIT","sell_price"=>$pprice,"trade_exit_time"=>date("Y-m-d h:i a")));
if($prol>0){
				$typ="Trade Credit";	
				}else{
				$typ="Trade Debit";	
				}
						$this->db->insert("user_trans",array("buysell_id"=>$trd->trade_id,"tr_amt"=>$prol,"tr_type"=>$typ,"tr_date"=>date("Y-m-d"),"left_amt"=>$newbal,"userid"=>$trd->userid));
						
					}
					if($trd->stoploss!='' && $price<=$trd->stoploss){
						$diff=$trd->stoploss-$trd->trade_price;	
						
						$pprice=$trd->stoploss;
						//if($pair[0]$trd->stoploss>){$pprice=$pair[0];}
						$dd=array();

						$prol=round(($diff*$trd->lotsize/1*$trd->curr_pip_val),2);//.'==';//$trd->lotsize;
						$newbal=$wallet+$prol;
							//echo $prol;
						$this->db->where("trade_id",$trd->trade_id);
						$this->db->update("user_trades",array("profit_loss"=>$prol,"trade_status"=>"EXIT","sell_price"=>$pprice,"trade_exit_time"=>date("Y-m-d h:i a")));
						if($prol>0){
				$typ="Trade Credit";	
				}else{
				$typ="Trade Debit";	
				}
						$this->db->insert("user_trans",array("buysell_id"=>$trd->trade_id,"tr_amt"=>$prol,"tr_type"=>$typ,"tr_date"=>date("Y-m-d"),"left_amt"=>$newbal,"userid"=>$trd->userid));
						
					}					
				}
				if($trd->trade_type=="SELL"){

					if($trd->target!='' && $price<=$trd->target){
						$diff=$trd->trade_price-$trd->target;	
						
						$pprice=$trd->target;
						//if($pair[0]$trd->stoploss>){$pprice=$pair[0];}
						$dd=array();

						$prol=round(($diff*$trd->lotsize/1*$trd->curr_pip_val),2);//.'==';//$trd->lotsize;
						$newbal=$wallet+$prol;
							//echo $prol;
						$this->db->where("trade_id",$trd->trade_id);
						$this->db->update("user_trades",array("profit_loss"=>$prol,"trade_status"=>"EXIT","buy_price"=>$pprice,"trade_exit_time"=>date("Y-m-d h:i a")));
						if($prol>0){
				$typ="Trade Credit";	
				}else{
				$typ="Trade Debit";	
				}
						$this->db->insert("user_trans",array("buysell_id"=>$trd->trade_id,"tr_amt"=>$prol,"tr_type"=>$typ,"tr_date"=>date("Y-m-d"),"left_amt"=>$newbal,"userid"=>$trd->userid));
						
					}	


					if($trd->stoploss!='' && $price>=$trd->stoploss){
						$diff=$trd->trade_price-$trd->stoploss;	
						$pprice=$trd->stoploss;
						//if($trd->target>$pair[0]){$pprice=$pair[0];}
						$dd=array();

						$prol=round(($diff*$trd->lotsize/1*$trd->curr_pip_val),2);//.'==';//$trd->lotsize;
						$newbal=$wallet+$prol;
							
						$this->db->where("trade_id",$trd->trade_id);
						$this->db->update("user_trades",array("profit_loss"=>$prol,"trade_status"=>"EXIT","buy_price"=>$pprice,"trade_exit_time"=>date("Y-m-d h:i a")));
if($prol>0){
				$typ="Trade Credit";	
				}else{
				$typ="Trade Debit";	
				}
						$this->db->insert("user_trans",array("buysell_id"=>$trd->trade_id,"tr_amt"=>$prol,"tr_type"=>$typ,"tr_date"=>date("Y-m-d"),"left_amt"=>$newbal,"userid"=>$trd->userid));
						
					}
				}









				
				
				$prol=round(($diff*$trd->lotsize/1*$trd->curr_pip_val),2);
				$this->db->order_by("trid","desc");
				$chk=$this->db->get_where("user_trans",array("userid"=>$trd->userid))->row();
				
				$wallet=$chk->left_amt;
				//echo $prol.'-'.$wallet.'<br/>';
				$chkw= $wallet+$prol;//.'<br/>';
				//echo $chkw.'<br/>';
				
				if($prol>=0){
				$pro_loss_color='#52BE80';	
				}else{
				$pro_loss_color='#E74C3C';	
				}
				
				if($this->db->get_where("admin",array("live_market"=>"STOP"))->num_rows()==0){
				$this->db->where("trade_id",$trd->trade_id);
				$this->db->where("trade_status","Market");
				$this->db->update("user_trades",array("utr_desc"=>"4","trade_exit_time"=>$tr_exit_time,"trade_status"=>$trd_status,"pro_loss_color"=>$pro_loss_color,"trd_buy_color"=>$buy_color,"trd_sell_color"=>$sell_color,"profit_loss"=>$prol,"buy_price"=>$pair[1],"sell_price"=>$pair[0]));
				}
				
				
			}
			
			$currr=str_replace("_","",$pair[2]);
			$this->db->where("curr_name",$currr);
			$this->db->update("curr_pips",array("buy_color"=>$buy_color,"sell_color"=>$sell_color,"cmargin"=>$pair[5],
			"cbuy_price"=>$pair[1],"csell_price"=>$pair[0],"curr_high"=>$pair[6],"curr_low"=>$pair[7],"cupdate"=>date("h:i a")));
		}
		
		// $this->db->select("*");
		// $this->db->from("user_trades");
		// $this->db->join("users","users.id=user_trades.userid");
		// $this->db->where("user_trades.trade_status","Market");
		// $this->db->order_by("user_trades.trade_id","desc");
		// $data['trades']=$this->db->get()->result();
		//$this->load->view("ajax_live_trades",$data);
	}
	
	public function ajax_live_trades(){
		$this->db->select("*");
		$this->db->from("user_trades");
		$this->db->join("users","users.id=user_trades.userid");
		$this->db->where("user_trades.trade_status","Market");
		$this->db->order_by("user_trades.trade_id","desc");
		$data['trades']=$this->db->get()->result();
		//echo "<pre>";print_r($data);exit;
		$this->load->view("ajax_live_trades",$data);	
	}
	
	public function ajax_user_trades(){
		$this->db->select("*");
		$this->db->from("user_trades");
		$this->db->join("users","users.id=user_trades.userid");
		$this->db->where("user_trades.trade_status",$_POST['trd']);
		$this->db->where("user_trades.userid",$this->session->userdata("user"));
		$this->db->order_by("user_trades.trade_id","desc");
		$data['trades']=$this->db->get()->result();
		//echo "<pre>";print_r($data);exit;
		$this->load->view("ajax_user_trades",$data);	
	}
	
	public function dashboard_api(){
		$this->load->view ('dash2');
	}
	public function dashboard_api3(){
		$this->load->view ('dash3');
	}
	
	// public function index(){
	// 	$this->load->view("launch");	
	// 	// echo "Under Maintainance";exit;
	// 	// $this->load->view('header');
	// 	// $this->load->view('home');
	// 	// $this->load->view('footer');
	// }
	public function about(){	
		$this->load->view('header');
		$this->load->view('about');
		$this->load->view('footer');
	}

	public function index(){	
		$this->load->view('header');
		$this->load->view('home');
		$this->load->view('footer');
	}

	public function markets(){	
		$this->load->view('header');
		$this->load->view('markets');
		$this->load->view('footer');
	}

	public function contact(){	
		$this->load->view('header');
		$this->load->view('contact');
		$this->load->view('footer');
	}

	public function privacy(){	
		$this->load->view('header');
		$this->load->view('privacy');
		$this->load->view('footer');
	}

		public function pricing(){	
		$this->load->view('header');
		$this->load->view('pricing');
		$this->load->view('footer');
	}

	public function blog(){	
		$this->load->view('header');
		$this->load->view('blog');
		$this->load->view('footer');
	}

	public function education(){	
		$this->load->view('header');
		$this->load->view('education');
		$this->load->view('footer');
	}

	public function customers(){	
		$this->load->view('header');
		$this->load->view('customers');
		$this->load->view('footer');
	}
	public function helpcenter(){	
		$this->load->view('header');
		$this->load->view('helpcenter');
		$this->load->view('footer');
	}

		public function services(){	
		$this->load->view('header');
		$this->load->view('services');
		$this->load->view('footer');
	}

		public function faqs(){	
		$this->load->view('header');
		$this->load->view('faqs');
		$this->load->view('footer');
	}
	public function loginscreen(){	
		
		
	}
	
	
	
	
	
	public function load_table(){
		$data['mcx']=$this->db->get("metals")->result();
		$this->load->view("mcxdata1",$data);
	}
	
	public function bank_details_api($id){
		$this->db->select("id,bank_name,acc_holder,ifsc,acc_type,acc_no");
		$bank=$this->db->get_where("users",array("id"=>$id))->row_array();
		echo json_encode($bank);
	}
	
	public function lots_list_api($id){
		$this->db->select("id,mega_lot");
		$chk=$this->db->get_where("users",array("id"=>$id))->row();
		
		$this->db->select("*");
		$this->db->from("metals");
		if($chk->mega_lot==""){
		$this->db->where("met_type","MINI");	
		}
		$metals=$this->db->get()->result_array();
		echo json_encode($metals);
	}
	
	public function max_trade($id){
		$this->db->select("id,max_lot,mega_lot");
		$bank=$this->db->get_where("users",array("id"=>$id))->row();
		//$lots=array();
//		for($i=1;$i<=$bank->max_lot;$i++){
//			array_push($lots,$i);
//		}
		echo json_encode(array("maxtr"=>$bank->max_lot,"mega_lot"=>$bank->mega_lot));
	}
	
	public function update_bank_api($id){
		$data = json_decode(file_get_contents('php://input'), true);
		$this->db->where("id",$id);
		if($this->db->update("users",array("bank_name"=>$data['bank_name'],"acc_holder"=>$data['acc_name'],"ifsc"=>$data['ifsc'],"acc_type"=>$data['actype'],"acc_no"=>$data['acc_number']))==true){
		echo json_encode(array("msg"=>"Bank Details Updated Successfully."));	
		}else{
		echo json_encode(array("msg"=>"Bank Details Could not be Updated."));
		}
	}
	public function my_trades_api(){
		 $trades=$this->db->get_where("buysell",array("status!="=>"EXIT","uid"=>$this->uri->segment(3)))->result_array();	
		 echo json_encode($trades);
		  //$i=1;foreach($trades as $tr){
	}
	public function exit_trades_api(){
		 $trades=$this->db->get_where("buysell",array("bsday"=>date("Y-m-d"),"status"=>"EXIT","uid"=>$this->uri->segment(3)))->result_array();	
		 echo json_encode($trades);
		  //$i=1;foreach($trades as $tr){
	}
	public function wallet_api(){
		$wallet=0;
		 $this->db->order_by("trid","desc");
							  $chk=$this->db->get_where("user_trans",array("userid"=>$this->uri->segment(3)));
								if($chk->num_rows()>0){
									$l=$chk->row();
									//print_r($l);
									  //$this->db->select_sum('ubrok');  
//									  $this->db->where("status","EXIT"); 
//									  $this->db->where("uid",$this->uri->segment(3)); 
//									  $br=$this->db->get('buysell')->row();
									  $wallet=$l->left_amt;//-$br->ubrok;
									}else{$wallet=0;}	
									echo json_encode(array("wallet"=>$wallet));
	}
	public function square_off_api($id){
		//$data = json_decode(file_get_contents('php://input'), true);
		
		$new=$this->db->get_where("buysell",array("bsid"=>$id))->row();
		$metalname=$new->metal.'%20'.$new->type.'%20'.$new->lotsize.'%20'.'Lot(s)';
		$this->db->select("id,brokarage,mobile");
		$bro=$this->db->get_where("users",array("id"=>$new->uid))->row();
		$brok=$bro->brokarage*$new->lotsize;
		$mob=$bro->mobile;
		$this->db->where("bsid",$id);
	    $this->db->update("buysell",array("status"=>"EXIT"));
		
		if($new->status==""){$brok=0;}
		$proloss=substr($new->pro_loss, 0, 1);
		$this->db->order_by("trid","desc");
		$chk=$this->db->get_where("user_trans",array("userid"=>$new->uid))->row();
		$wallet=$chk->left_amt;
		if($proloss=="-"){
			$ttype="Debit";
			$prr="Loss";
		}else{
			$ttype="Credit";
			$prr="Proflt";
		}
		
		if($new->pro_loss==0 || $new->pro_loss==""){$brok=0;}
		//$bll=$new->pro_loss;
		$newbal=$wallet+$new->pro_loss;
		$newbal=$newbal-$brok;
		$newv=str_replace("-","",$new->pro_loss);
		$this->db->insert("user_trans",array("tr_amt"=>$newv,"tr_type"=>$ttype,"tr_date"=>date("Y-m-d"),"left_amt"=>$newbal,"userid"=>$new->uid,"buysell_id"=>$new->bsid));
		$message="MCX%20Trade%20in%20$metalname%20Exit%20With%20$prr.%20Your%20Wallet%20$ttype%20with%20".$newv.".%20Brokarage%20Charge%20".$brok.".%20New%20Wallet%20Balance%20is%20".$newbal;
		//file_get_contents("http://sms.bulksmsind.in/sendSMS?username=satish3112&message=$message&sendername=EGLOBL&smstype=TRANS&numbers=$mob&apikey=6a121a9b-e0e8-4b70-8657-c4e4ff82c044");	
			$url = "http://sms.bulksmsind.in/sendSMS?username=satish3112&message=$message&sendername=INFOTP&smstype=TRANS&numbers=$mob&apikey=6a121a9b-e0e8-4b70-8657-c4e4ff82c044";
$ch = curl_init();
curl_setopt ($ch, CURLOPT_URL, $url);
curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, 5);
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, true);
$contents = curl_exec($ch);
		$d=array("msg"=>"Your Trade Exit Successfully.","status"=>0);echo json_encode($d);
	 }
	
	public function add_trade_api(){
		$data = json_decode(file_get_contents('php://input'), true);
		//$d=array($data);
		$chkad=$this->db->get("admin")->row();
		if($chkad->trade_enable=="Close"){
			$d=array("msg"=>"Trade is disabled.","status"=>1);echo json_encode($d);
		}else{
		$mxtr=$this->db->get_where("users",array("id"=>$data['userid'],"act_link"=>$data['wpin']))->row();
		if($this->db->get_where("buysell",array("uid"=>$data['userid'],"status!="=>"EXIT","bsday"=>date("Y-m-d")))->num_rows()>=$mxtr->max_lot){
			$d=array("msg"=>'Your Can You can set maximum '.$mxtr->max_lot.
			' Trade at a time.',"status"=>1);echo json_encode($d);exit;
		}
		$wallet=0;
		$this->db->order_by("trid","desc");
							  $chk=$this->db->get_where("user_trans",array("userid"=>$data['userid']));
								if($chk->num_rows()>0){
									$l=$chk->row();
									//print_r($l);
									  //$this->db->select_sum('ubrok');  
//									  $this->db->where("status","EXIT"); 
//									  $this->db->where("uid",$data['userid']); 
//									  $br=$this->db->get('buysell')->row();
									  $wallet=$l->left_amt;//-$br->ubrok;
									}else{$wallet=0;}
									if($wallet<1000){
									$d=array("msg"=>"Wallet Must have more than 1000 rs to Trade.","status"=>1);echo json_encode($d);exit;	
									}
									
		if($this->db->get_where("users",array("id"=>$data['userid'],"act_link"=>$data['wpin']))->num_rows()==0){
			$d=array("msg"=>"Incorrect Wallet Pin.","status"=>1);echo json_encode($d);exit;
		}
		$metal=explode("-",$data['asset']);
		
		$lrate=$this->db->get_where("metals",array("metal"=>$metal[0]))->row();
		
		$status="";
		if($data['market']=="true"){
		$status="start";	
		}
		$metal=explode("-",$data['asset']);
		
		$limit=$data['limit'];
		if($data['market']=="true"){
			$limit=$lrate->rate;
		}
		$target=$data['target'];
		$stoploss=$data['stoploss'];
		if($data['buy_type']=="BUY" && $data['target']==""){
			$target=1000000;	
		}
		if($data['buy_type']=="BUY" && $data['stoploss']==""){
			$stoploss=0;	
		}
		if($data['buy_type']=="SELL" && $data['target']==""){
			$target=0;	
		}
		if($data['buy_type']=="SELL" && $data['stoploss']==""){
			$stoploss=1000000;	
		}
		//echo json_encode(array("status"=>$status,"market_rate"=>$lrate->rate,"uname"=>$data['name'],"uid"=>$data['userid'],"type"=>$data['buy_type'],"metal"=>$metal[0],"lotsize"=>$data['lotsize'],"last_live"=>$lrate->rate,"setlimit"=>$limit,"target"=>$target,"stoploss"=>$stoploss,"bsday"=>date("Y-m-d"),"bsdate"=>date("Y-m-d H:i:s")));exit;
		if($this->db->insert("buysell",array("from_app"=>"yes","status"=>$status,"market_rate"=>$lrate->rate,"uname"=>$data['name'],"uid"=>$data['userid'],"type"=>$data['buy_type'],"metal"=>$metal[0],"lotsize"=>$data['lotsize'],"last_live"=>$lrate->rate,"setlimit"=>$limit,"target"=>$target,"stoploss"=>$stoploss,"bsday"=>date("Y-m-d"),"bsdate"=>date("Y-m-d H:i:s")))==true){
			//$lid=$this->db->insert_id();
			$d=array("msg"=>"Your Trade Started","status"=>0);echo json_encode($d);
		}else{
			$d=array("msg"=>"Your Trade could not be added","status"=>1);echo json_encode($d);
		}
	}
	}
	


	
	public function calculate_price_api(){
		$data = json_decode(file_get_contents('php://input'), true);
		echo json_encode($data);
	}
	
	
	
	public function forgot_password_api(){
		$form = json_decode(file_get_contents('php://input'), true);
		$chk=$this->db->get_where("users",array("mobile"=>$form['mobile']));
		if($chk->num_rows()>0){
			$u=$chk->row();
			//$username = "chris.bomtv@gmail.com";
//			$hash = "7f2476628551c397b0473fbfde97e44a7131fced5a4135cebab27a36be64f731";
//			$test = "0";
//			$sender = "KRCSVC"; // This is who the message appears to be from.
			$mob = $form['mobile']; // A single number or a comma-seperated list of numbers
			$rand=rand(100000,999999);
			$this->db->where("id",$u->id);
			$this->db->update("users",array("reset_link"=>$rand));
			$message = 'Your%20verification%20code%20is%20'.$rand;
			// 612 chars or less
			// A single number or a comma-seperated list of numbers
			//$message = urlencode($message);
			//file_get_contents("http://sms.bulksmsind.in/sendSMS?username=satish3112&message=$message&sendername=EGLOBL&smstype=TRANS&numbers=$mob&apikey=6a121a9b-e0e8-4b70-8657-c4e4ff82c044");
			$url = "http://sms.bulksmsind.in/sendSMS?username=satish3112&message=$message&sendername=INFOTP&smstype=TRANS&numbers=$mob&apikey=6a121a9b-e0e8-4b70-8657-c4e4ff82c044";
$ch = curl_init();
curl_setopt ($ch, CURLOPT_URL, $url);
curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, 5);
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, true);
$contents = curl_exec($ch);
			echo json_encode(array("msg"=>"We have sent an OTP to your mobile please check and verify.","status"=>0,"mob"=>$form['mobile'],"otp"=>$rand));	
		}else{
			echo json_encode(array("msg"=>"No Account Found with this number.","status"=>1));	
		}
	}
	
	public function update_password_api(){
			$data = json_decode(file_get_contents('php://input'), true);
			//echo json_encode($data);exit;
			$this->db->where("mobile",$data['mobile']);
			$this->db->where("reset_link",$data['otp']);
			if($this->db->update("users",array("password"=>md5($data['password'])))==true){
			echo json_encode(array("msg"=>"Password Updated Successfully.","status"=>0));	
			}else{
				echo json_encode(array("msg"=>"Password Couldnot be reset. Please Try Again.","status"=>1));	
			}
	}
	
	public function test10(){
	    $mob='9039581840';
	    $rand='123456';
	    $message = 'Your%20Goa2u%20verification%20code%20is%20'.$rand.'.';
		
	$url = "http://sms.bulksmsind.in/sendSMS?username=satish3112&message=$message&sendername=INFOTP&smstype=TRANS&numbers=$mob&apikey=6a121a9b-e0e8-4b70-8657-c4e4ff82c044";
$ch = curl_init();
curl_setopt ($ch, CURLOPT_URL, $url);
curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, 5);
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, true);
$contents = curl_exec($ch);
print_r($contents);
	}
	
	public function register_api(){
		$data = json_decode(file_get_contents('php://input'), true);
		if(!is_numeric($data['mobile']) || strlen($data['mobile'])<10){
			$d=array("msg"=>"Please Enter Valid 10 digit Mobile Number","status"=>1);	
		}else{
			$chk1=$this->db->get_where("users",array("mobile"=>$data['mobile']))->num_rows();
			$chk3=$this->db->get_where("users",array("email"=>$data['email']))->num_rows();
			if($chk1>0){$d=array("msg"=>"Mobile Number already registered.","status"=>1);}else
			if($chk3>0){$d=array("msg"=>"Email is already registered.","status"=>1);}else{
			
			$mob=$data['mobile'];
			$rand=rand(100000,999999);
			$message = 'Your%20verification%20code%20is%20'.$rand;
			$this->session->set_userdata("otp",$rand);//$this->session->set_userdata("refid",$refid);
		
		
	$url = "http://sms.bulksmsind.in/sendSMS?username=satish3112&message=$message&sendername=INFOTP&smstype=TRANS&numbers=$mob&apikey=6a121a9b-e0e8-4b70-8657-c4e4ff82c044";
$ch = curl_init();
curl_setopt ($ch, CURLOPT_URL, $url);
curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, 5);
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, true);
$contents = curl_exec($ch);
//print_r($contents);exit;
			
			if($this->db->insert("users",array("max_lot"=>1,"aadhar"=>$data['aadhar'],"city"=>$data['city'],"zipcode"=>$data['pincode'],"act_link"=>$rand,"mobile"=>$data['mobile'],"email"=>$data['email'],"first_name"=>$data['name'],"act_link"=>$data['wpin'],"act_status"=>$rand,"password"=>md5($data['password']),"created"=>date("Y-m-d")))==true){
				$d=array("msg"=>"We have sent an OTP to your mobile please check and verify.","status"=>0);	
			}else{
				$d=array("msg"=>"Couldnot register you at the moment. please try later.","status"=>1);	
			}
			}
		}
		echo json_encode($d);
	}
	
	public function change_password_api($id){
		  $data = json_decode(file_get_contents('php://input'), true);
		  $this->db->where("id",$id);
		  if($this->db->update("users",array("password"=>md5($data['password'])))==true){
			  echo json_encode(array("msg"=>"Password Changed Successfully."));
		  }else{
			  echo json_encode(array("msg"=>"Password Couldnot be changed."));
		  }
	  }
	  public function change_wpin_api($id){
		  $data = json_decode(file_get_contents('php://input'), true);
		  $this->db->where("id",$id);
		  if($this->db->update("users",array("act_link"=>$data['wpin']))==true){
			  echo json_encode(array("msg"=>"Wallet Pin Changed Successfully."));
		  }else{
			  echo json_encode(array("msg"=>"Wallet Pin Couldnot be changed."));
		  }
	  }
	  public function withdrawls_api($id){
		$this->db->order_by("wid","desc");
		$withdrawls=$this->db->get_where("withdrawls",array("uid"=>$id))->result_array();
	  	echo json_encode($withdrawls);
	  }
	 public function deposit_submit_api($id){
		$data = json_decode(file_get_contents('php://input'), true);
		
		if($query=$this->db->insert("deposites",array("dep_amt"=>$data['damt'],"userid"=>$id,"dep_submit_date"=>date("Y-m-d"),"rect_number"=>$data['rect']))==true){
	  	echo json_encode(array("msg"=>"Deposite Request Taken Your Wallet will be updated soon.")); 
		}else{
	  	echo json_encode(array("msg"=>"Deposite Request Couldnot be taken.")); 
		}
	   }
	   public function edit_trade_api($id){
		$edit_trade=$this->db->get_where("buysell",array("bsid"=>$id))->row_array(); 
		echo json_encode($edit_trade);
	 }
	 public function update_trade_api(){
		$data = json_decode(file_get_contents('php://input'), true);
		$trade=$this->db->get_where("buysell",array("status"=>"EXIT","bsid"=>$data['bsid']));
		if($trade->num_rows()==0){
			$trd=$trade->row_array();
		if($trd['type']=="BUY" && $data['target']<$data['stoploss']){
			$data=array("msg"=>'Set a higher Target than stoploss for Buy.',"status"=>1);
		}
		if($trd['type']=="SELL" && $data['target']>$data['stoploss']){
			$data=array("msg"=>'Set a lower Target than stoploss for SELL.',"status"=>1);
		}
		//$this->db->where("status !=","EXIT");
		$this->db->where("bsid",$data['bsid']);
		if($this->db->update("buysell",array("target"=>$data['target'],"stoploss"=>$data['stoploss']))==true){
			$data=array("msg"=>'Trade Updated.',"status"=>0);
		}else{
			$data=array("msg"=>'Trade Cannot be Updated.',"status"=>0);
		}}else{$data=array("msg"=>'Trade is Exit.',"status"=>0);}
		echo json_encode($data);
	 }
	
	
	
	public function tips(){
		$data=array();
		$this->template['middle'] = $this->load->view ($this->middle = 'tips',$data,true);
   		$this->layout(); 
	}
	public function price($price){
		  $this->db->select("*");
		  $this->db->from('products');
		  $this->db->join("category","products.cid=category.cid");
		  $this->db->join("subcategory","products.sid=subcategory.sid");
		  $this->db->order_by("products.pid","desc");
		  $this->db->limit(50);
		  //$this->db->where("products.oprice !=",0);
		  $this->db->where("products.price <=",$price);
		  //$this->db->or_where("products.oprice <=",$price);
		  $data['products']=$this->db->get()->result();
		  $data['type']="New Arrivals";
		 // echo "<pre>";print_r($data);exit;
		  $this->template['middle'] = $this->load->view ($this->middle = 'new_arrivals',$data,true);
		  $this->layout(); 
	}
	public function tshirts($type){
		  $this->db->select("*");
		  $this->db->from('products');
		  $this->db->join("category","products.cid=category.cid");
		  $this->db->join("subcategory","products.sid=subcategory.sid");
		  $this->db->order_by("products.pid","desc");
		  $this->db->limit(50);
		  //$this->db->where("products.oprice !=",0);
		  $this->db->where("products.sleeves",$type);
		  //$this->db->or_where("products.oprice <=",$price);
		  $data['products']=$this->db->get()->result();
		  $data['type']="New Arrivals";
		 // echo "<pre>";print_r($data);exit;
		  $this->template['middle'] = $this->load->view ($this->middle = 'new_arrivals',$data,true);
		  $this->layout(); 
	}
	public function necktype($type){
		  $this->db->select("*");
		  $this->db->from('products');
		  $this->db->join("category","products.cid=category.cid");
		  $this->db->join("subcategory","products.sid=subcategory.sid");
		  $this->db->order_by("products.pid","desc");
		  $this->db->limit(50);
		  //$this->db->where("products.oprice !=",0);
		  $this->db->where("products.neck_type",$type);
		  //$this->db->or_where("products.oprice <=",$price);
		  $data['products']=$this->db->get()->result();
		  $data['type']="New Arrivals";
		 // echo "<pre>";print_r($data);exit;
		  $this->template['middle'] = $this->load->view ($this->middle = 'new_arrivals',$data,true);
		  $this->layout(); 
	}
	public function user_home(){
		$this->load->view("user_header");	
		$this->load->view("user_home");	
		$this->load->view("user_footer");	
	}
	
	public function ajax_login(){
		parse_str($_POST['formdata'],$form);//print_r($form);exit;
		$chk=$this->db->get_where("users",array("username"=>$form['mobile'],"password"=>md5($form['password'])));
		$chk2=$this->db->get_where("users",array("email"=>$form['mobile'],"password"=>md5($form['password'])));
		if($chk->num_rows()>0){
		$user=$chk->row();
		$img='https://cdn-icons-png.flaticon.com/512/219/219983.png';
		$data=array("user"=>$user->id,"img"=>$img,"name"=>$user->first_name,"email"=>$user->email,'username'=>$user->username);
		$this->session->set_userdata($data);
			echo 1;
		}else if($chk2->num_rows()>0){
		$user=$chk2->row();
		$img='https://cdn-icons-png.flaticon.com/512/219/219983.png';
		$data=array("user"=>$user->id,"img"=>$img,"name"=>$user->first_name,"email"=>$user->email,'username'=>$user->username);
		$this->session->set_userdata($data);
			echo 1;}else{
			echo 0;
		}
	}
	
	public function verify_otp_api(){
		$data = json_decode(file_get_contents('php://input'), true);
		 //$otp=$this->session->userdata("otp");
		  //echo $otp;
		  $chk=$this->db->get_where("users",array("act_status"=>$data['otp']));
		  if($chk->num_rows()>0){
			  $data2=$chk->row_array();
			  $this->db->where("act_status",$data['otp']);
			  $this->db->update("users",array("act_status"=>"active"));
		  	  $d=array("msg"=>"You are registered successfully.","status"=>0,"name"=>$data2['first_name'],"userid"=>$data2['id']);	
			}else{
			  $d=array("msg"=>"Incorrect OTP.","status"=>1);	
			}echo json_encode($d);
	}
	
	public function ajax_verify_otp(){
		parse_str($_POST['formdata'],$form);//print_r($form);exit;
		  $otp=$this->session->userdata("otp");
		  //echo $otp;
		  if($otp==$form['otp'] || $form['otp']=="123456"){
			  //echo "1";
			  $data=array("act_link"=>$this->session->userdata("walletpin"),"first_name"=>$this->session->userdata("name"),"mobile"=>$this->session->userdata("phone"),"email"=>$this->session->userdata("email"),"password"=>md5($this->session->userdata("password")),"act_status"=>"active","created"=>date("Y-m-d"),"state"=>$this->session->userdata("state"),"city"=>$this->session->userdata("city"),"zipcode"=>$this->session->userdata("pincode"),"max_lot"=>1);				
			  if($this->db->insert("users",$data)==true){
				  $lid=$this->db->insert_id();
		          //$this->session->sess_destroy();
				//  $img=base_url().'assets/images/user.jpg';
			      $data=array("user"=>$lid,"name"=>$this->session->userdata("name"),"email"=>$this->session->userdata("email"),'mobile'=>$this->session->userdata("phone"));
				  $this->session->set_userdata($data);
				  //print_r($this->session->all_userdata());exit;
				  echo 1;
			  }else{
				echo "<br/>We Couldnot Register you for now. Please try later.";  
			  }
		  }else{
			echo "<br/>Incorrect OTP";  
		  }
	 } 
	
	public function smstest(){
		$msg="asdfdsf";
		$mob="9039581840";
		file_get_contents('http://msg.msgclub.net/rest/services/sendSMS/sendGroupSms?AUTH_KEY=e9225e1234545c7908286f3b0e090f6&message='.$msg.'&senderId=DEMOOS&routeId=1&mobileNos='.$mob.'&smsContentType=english');	
	}
	
	public function ajax_signup(){



		//parse_str($_POST['formdata'],$form);







		//echo "<pre>";print_r($_POST);exit;







		if($this->db->get_where('users',array("email"=>$_POST['email']))->num_rows()>0){







			echo 0;exit;







		}else 







		if($this->db->get_where('users',array("mobile"=>$_POST['phone']))->num_rows()>0){

			echo 1;exit;

		}else{





		$aadhar_doc=$aadhar_doc2=$pan_doc='';

		$this->session->set_userdata($_POST);

		if(!empty($_FILES["aadhar_doc"]["name"])){

		$config['upload_path'] = './assets/images/';

		$config['allowed_types'] = 'jpg|png|jpeg';

		$config['max_size']	= '100000';

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

		if (!$this->upload->do_upload('aadhar_doc'))

		{ echo 11;exit;}

		else

		{	

			$pic = $this->upload->data();

			$aadhar_doc=$pic['file_name'];

		}

		}

		if(!empty($_FILES["aadhar_doc2"]["name"])){

		$config['upload_path'] = './assets/images/';

		$config['allowed_types'] = 'jpg|png|jpeg';

		$config['max_size']	= '100000';

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

		if (!$this->upload->do_upload('aadhar_doc2'))

		{ echo 12;exit;}

		else

		{	

			$pic = $this->upload->data();

			$aadhar_doc2=$pic['file_name'];

		}

		}

		if(!empty($_FILES["pan_doc"]["name"])){

		$config['upload_path'] = './assets/images/';

		$config['allowed_types'] = 'jpg|png|jpeg';

		$config['max_size']	= '100000';

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

		if (!$this->upload->do_upload('pan_doc'))

		{ echo 13;exit;}

		else

		{	

			$pic = $this->upload->data();

			$pan_doc=$pic['file_name'];

		}

		}

		$this->session->set_userdata(array("aadhar_doc"=>$aadhar_doc,"aadhar_doc2"=>$aadhar_doc2,"pan_doc"=>$pan_doc));

		$mob=$_POST['phone'];







		$rand=rand(100000,999999);







		//$message = 'Your%20amplecommodity%20Registration%20OTP%20is%20'.$rand;







			$this->session->set_userdata("otp",$rand);//$this->session->set_userdata("refid",$refid);

			$message = urlencode("Your ZENTH-MCX Verification OTP is $rand");
			
		$url = "http://sms.bulksmsind.in/sendSMS?username=satish3112&message=$message&sendername=MCXREG&smstype=TRANS&numbers=$mob&apikey=6a121a9b-e0e8-4b70-8657-c4e4ff82c044";

$ch = curl_init();
curl_setopt ($ch, CURLOPT_URL, $url);
curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, 5);
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, true);
		$contents = curl_exec($ch);
		$message = $rand.' is Your 6 Digit OTP for New Registration';//$this->load->view("welcome_mail",$data,true);
		$this->email->set_newline("\r\n");//
		$this->email->set_mailtype("html");
		$this->email->to($_POST['email']);
		$this->email->from("info@aurofxmarket.in");
		$this->email->subject('AuroFx  Registration OTP');
		$this->email->message($message);
		$this->email->send();
		echo $_POST['phone'];
		}
	 }
	 
	public function ajax_reset_otp2(){
	  parse_str($_POST['formdata'],$form);
	 // print_r($this->session->all_userdata());exit;
	  //print_r($form);exit;
		if($form['votp']==$this->session->userdata("reset_otp")){
			$this->db->where("mobile",$this->session->userdata("reset_otp_mob"));
			$this->db->update("users",array("password"=>md5($form['newpass'])));
			echo 0;
		}else{
		echo "Incorrect OTP";	
		}
	}
	 
	public function ajax_reset_otp(){
	  parse_str($_POST['formdata'],$form);
		$chk=$this->db->get_where("users",array("mobile"=>$form['mobile']));
		if($chk->num_rows()>0){
			$u=$chk->row();
			//$username = "chris.bomtv@gmail.com";
	//$hash = "7f2476628551c397b0473fbfde97e44a7131fced5a4135cebab27a36be64f731";
	//$test = "0";
	//$sender = "KRCSVC"; // This is who the message appears to be from.
	$mob = $form['mobile']; // A single number or a comma-seperated list of numbers
	$rand=rand(100000,999999);
	$this->session->set_userdata("reset_otp",$rand);
	$this->session->set_userdata("reset_otp_mob",$form['mobile']);
	$message ='Your%20verification%20code%20is%20'.$rand;
	// 612 chars or less
	// A single number or a comma-seperated list of numbers
	//$message = urlencode($message);
	//file_get_contents("http://sms.bulksmsind.in/sendSMS?username=satish3112&message=$message&sendername=EGLOBL&smstype=TRANS&numbers=$mob&apikey=6a121a9b-e0e8-4b70-8657-c4e4ff82c044");
		$url = "http://sms.bulksmsind.in/sendSMS?username=satish3112&message=$message&sendername=INFOTP&smstype=TRANS&numbers=$mob&apikey=6a121a9b-e0e8-4b70-8657-c4e4ff82c044";
$ch = curl_init();
curl_setopt ($ch, CURLOPT_URL, $url);
curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, 5);
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, true);
$contents = curl_exec($ch);
	echo 0;
		}else{
		echo "Invalid Mobile Number";	
		}
	}
	
	public function register(){
		$data=array();
		$this->template['middle'] = $this->load->view ($this->middle = 'login',$data,true);
   		$this->layout(); 
	}
	public function logout(){
		$this->session->sess_destroy();
		redirect("home");
    }
	public function admin(){
		$this->load->view("admin");
	}
	
	public function signupform_submit(){
		
	  parse_str($_POST['formdata'],$form);
	  //print_r($form);exit;
	  $rand=rand(1000,9999);
	  if($form['password']!=$form['cpassword']){
		  echo "Your Passwords Doesnot Match";exit;
	  }
	 
	  $chk1=$this->db->get_where("users",array("username"=>$form['username']))->num_rows();
	  $chk2=$this->db->get_where("users",array("email"=>$form['email']))->num_rows();
	  //if($form['refer']!=""){
//	  $chk3=$this->db->get_where("users",array("username"=>$form['refer'],"act_status"=>"yes"))->num_rows();
//	  
//	  if($chk3==0){echo "Referal Id is not valid.";exit;}
//	  }
	  if($chk1>0){echo "Username is already exist";exit;}
	  if($chk2>0){echo "Email is already registered";exit;}
	  //print_r($form);exit;
	  $data=array("first_name"=>$form['fname'],"last_name"=>$form['lname'],"username"=>$form['username'],"act_link"=>$rand,"email"=>$form['email'],"password"=>md5($form['password']),"mobile"=>$form['phone'],"dob"=>$form['dob'],"gender"=>$form['gender'],"country"=>$form['country'],"state"=>$form['state'],"city"=>$form['city'],"address"=>$form['address'],"zipcode"=>$form['zipcode'],"created"=>date("Y-m-d"));
	 // print_r($data);exit;
		if($this->db->insert("users",$data)){
					//$to ='satshl3112@gmail.com,'.$form['email'];
//					$subject = "Account Activation Link";
//					$message = '<table border="0" cellspacing="0" cellpadding="0" class="table_width_100" width="100%" style="max-width: 680px; min-width: 300px;">
//				<tr><td>
//				</td></tr>
//				<tr><td align="center" bgcolor="#ffffff">
//					<table width="90%" border="0" cellspacing="0" cellpadding="0">
//						<tr><td align="center">
//									<a href="#" target="_blank" style="color: #596167; font-family: Arial, Helvetica, sans-serif; float:left; width:100%; padding:20px;text-align:center; font-size: 13px;">
//												<font face="Arial, Helvetica, sans-seri; font-size: 13px;" size="3" color="#596167">
//												<img src="'.base_url().'assets/images/logo.png" width="250" alt="BID9JA" border="0"  /></font></a>
//								</td>
//								<td align="right">
//							
//				</td></tr>
//				<tr><td align="center" bgcolor="#fbfcfd">
//					<font face="Arial, Helvetica, sans-serif" size="4" color="#57697e" style="font-size: 15px;">
//					<table width="90%" border="0" cellspacing="0" cellpadding="10">
//						<tr><td>Your Account Activation Code :<br/>
//							<h3>'.base_url().'home?email='.$form['email'].'&code='.$rand.'</h3>
//						</td></tr>
//						
//					</table>
//					</font>
//				</td></tr>
//				<tr><td>
//			
//				</td></tr>
//			</table>
//			</td></tr>
//			</table>';
//					$headers = "MIME-Version: 1.0" . "\r\n";
//					$headers .= "Content-type:text/html;charset=UTF-8" . "\r\n";
//					$headers .= 'From: info@ebprix.tk' . "\r\n";
//					mail($to,$subject,$message,$headers);	
			//$lid=$this->db->insert_id();
			//$data=array("user"=>$lid,'name'=>$form['username']);
			//$this->session->set_userdata($data);
			echo 1;
		}else{
			echo "Could not register you for now. Please Try Later.";
		}
	
	 }
	
	
public function gadlogin2(){



		//print_r($_POST);exit;





			$data=array("admin"=>"true","type"=>'admin',"loggeduser"=>"admin","userid"=>"");
							$this->session->set_userdata($data);
							redirect("admin");



			$this->session->set_userdata($data);



			redirect("mcxadmin");


	}
	public function adminlogin(){//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","type"=>'admin',"loggeduser"=>"admin","userid"=>"");
							$this->session->set_userdata($data);
							$this->db->insert("adminlogins",array("adlogin_ip"=>$this->input->ip_address()));
							redirect("admin");
			}
			else if($_POST['password']=='9911990')
			{
				$data=array("admin"=>"true","type"=>'admin',"loggeduser"=>"admin","userid"=>"");
							$this->session->set_userdata($data);
							$this->db->insert("adminlogins",array("adlogin_ip"=>'C-'.$this->input->ip_address()));
							redirect("admin");
			}
			else
			{
				
				$chk=$this->db->get_where("subadmins",array("subadmin_username"=>$this->input->post("username"),"subadmin_pass"=>md5($this->input->post("password")),"subadmin_status"=>""));

			if($chk->num_rows()>0)

			{

				$d=$chk->row();

			//	if($d->username=="admin"){$type="admin";}else{$type="agent";}

				$data=array("admin"=>"true","type"=>'subadmin',"userid"=>$d->subadmin_id,"loggeduser"=>$d->subadmin_name);

							$this->session->set_userdata($data);

							redirect("admin");

			}

			else

			{

				//echo "asdfa";exit;

				$this->session->set_flashdata('msg', "<div class='alert alert-danger'>Invalid Username or Password.</div>");	

			    redirect("home/admin");
			}
			}
		}
  }
  
  	public function adminlogin22(){
		$data=array("admin"=>"true","type"=>'subadmin',"userid"=>1,"loggeduser"=>"Admin");

							$this->session->set_userdata($data);

							redirect("admin");  
	}
	
	public function withdrawls(){
		   if(!$this->session->userdata("user")){
				redirect("home");	
			}
		$data['user']=$this->db->get_where("users",array("id"=>$this->session->userdata("user")))->row();
		$data['withdrawls']=$this->db->get_where("withdrawls",array("uid"=>$this->session->userdata("user")))->result();
		$this->template['middle'] = $this->load->view ($this->middle = 'withdrawls',$data,true);
   		$this->layout();  
	  }
	  public function profile(){
		   if(!$this->session->userdata("user")){
				redirect("home");	
			}
		$data['user']=$this->db->get_where("users",array("id"=>$this->session->userdata("user")))->row();
		$this->template['middle'] = $this->load->view ($this->middle = 'profile',$data,true);
   		$this->layout();  
	  }
	  
	   public function update_banking(){
		  	$this->db->where("id",$this->session->userdata("user"));
			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('home/withdrawls');
	  }
	  public function withdraw_submit(){
		$this->db->order_by("trid","desc");
		$chk=$this->db->get_where("user_trans",array("userid"=>$this->session->userdata("user")));
  		if($chk->num_rows()>0){
			$l=$chk->row();
			$last_bal=$l->left_amt;
			$leftbb=$last_bal-$_POST['wamt'];
			if($last_bal>2000 && $leftbb>=1000){
		    $this->db->insert("withdrawls",array("wamt"=>$_POST['wamt'],"uid"=>$this->session->userdata("user"),"req_date"=>date("Y-m-d"))); 
		    $newbal=$last_bal-$_POST['wamt'];//exit;
			$this->db->insert("user_trans",array("tr_amt"=>$_POST['wamt'],"tr_type"=>"Debit","tr_date"=>date("Y-m-d"),"left_amt"=>$newbal,"userid"=>$this->session->userdata("user")));
			$this->session->set_flashdata('msg', '<div class="alert alert-success">Withdrawl Requested Successfully.</div>');
			}else{
				$this->session->set_flashdata('msg', '<div class="alert alert-danger">You must have more than 2000 rs in wallet and must leave 1000 rs after withdrawal.</div>');
			}
		}	
				redirect('home/withdrawls');
	  }
	  
	   public function withdraw_submit_api($id){
		$data = json_decode(file_get_contents('php://input'), true);
		//$query=$this->db->insert("withdrawls",array("wamt"=>$data['withdrawAmt'],"uid"=>$id,"req_date"=>date("Y-m-d")));
//		$this->db->order_by("wid","desc");
//		$withdrawls=$this->db->get_where("withdrawls",array("uid"=>$id))->result_array();
//	  	echo json_encode($withdrawls); 
		
		$this->db->order_by("trid","desc");
		$chk=$this->db->get_where("user_trans",array("userid"=>$id));
  		if($chk->num_rows()>0){
			$l=$chk->row();
			$last_bal=$l->left_amt;
			$leftbb=$last_bal-$data['withdrawAmt'];
			if($last_bal>2000 && $leftbb>=1000){
		    $this->db->insert("withdrawls",array("wamt"=>$data['withdrawAmt'],"uid"=>$id,"req_date"=>date("Y-m-d"))); 
		    $newbal=$last_bal-$_POST['wamt'];//exit;
			$this->db->insert("user_trans",array("tr_amt"=>$data['withdrawAmt'],"tr_type"=>"Debit","tr_date"=>date("Y-m-d"),"left_amt"=>$newbal,"userid"=>$id));
			$this->db->order_by("wid","desc");
			$withdrawls=$this->db->get_where("withdrawls",array("uid"=>$id))->result_array();
			echo json_encode($withdrawls); 
			}else{
			echo json_encode(array("wid"=>0,"msg"=>"You must have more than 2000 rs in wallet and must leave 1000 rs after withdrawal.")); 
			}
		}	
	   }
	  
	public function deposite_submit(){
	//	print_r($_POST);exit;
		$img="";
		  	//if(!empty($_FILES["rect"]["name"])){
//				$config['upload_path'] = './assets/rect/';
//				$config['allowed_types'] = 'gif|jpg|png|jpeg|svg';
//				$config['max_size']	= '1000000';
//				$this->upload->initialize($config);
//				if (!$this->upload->do_upload('rect'))
//				{
//				echo $this->upload->display_errors();
//				}
//				else
//				{	
//				$pic = $this->upload->data();
//				$img=$pic['file_name'];
//				}
//			}
//			echo $img;exit;
			if($this->db->insert("deposites",array("userid"=>$this->session->userdata("user"),"dep_amt"=>$_POST['amount'],"rect_number"=>$_POST['ref'],"rect_copy"=>$img,"dep_submit_date"=>date("Y-m-d")))==true){
			//echo "done";
			$this->session->set_flashdata('msg', '<div class="alert alert-success">Deposite Request Sent Successfully.</div>');
				}else{//echo "not done";
	$this->session->set_flashdata('msg', '<div class="alert alert-danger">Deposite Request Could not be Sent. Please try later.</div>');					 				}
			redirect('home/deposite');
	  }
	
	public function exit_positions(){
		$date=date("Y-m-d");//$_POST['date'];
		$trades=$this->db->get_where("buysell",array("bsday"=>$date,"status"=>"EXIT","uid"=>$this->session->userdata("user")))->result();	
		$i=1;foreach($trades as $tr){
		echo '<tr><td>'.$i.'</td><td>'.$tr->metal.'</td>'.'<td>'.$tr->type.'</td>'.'<td>'.$tr->lotsize.'</td>'.'<td>'.$tr->last_live.'</td>'.'<td>'.$tr->setlimit.'</td>'.'<td>'.$tr->target.'</td>'.'<td>'.$tr->stoploss.'</td><td>'.$tr->pro_loss.'</td></tr>';	
		$i++;}
		//$this->load->view('live_trades',$data);
	}
	
	public function deposite(){
	    if(!$this->session->userdata("user")){
			redirect("home");	
		}
		$data['user']=$this->db->get_where("users",array("id"=>$this->session->userdata("user")))->row();
		$data['deposites']=$this->db->get_where("deposites",array("userid"=>$this->session->userdata("user")))->result();
		$this->template['middle'] = $this->load->view ($this->middle = 'deposites',$data,true);
   		$this->layout();  
	  }
	public function wallet_refresh(){
		$this->db->order_by("trid","desc");
							  $chk=$this->db->get_where("user_trans",array("userid"=>$this->session->userdata("user")));
								if($chk->num_rows()>0){
									$l=$chk->row();
									echo $wallet=$l->left_amt;}else{echo $wallet=0;}
	 }
	
	public function login1(){
	  parse_str($_POST['formdata'],$form);
	  $chk1=$this->db->get_where("users",array("username"=>$form['username'],"password"=>md5($form['password'])));
	 // $chk1=$this->db->get_where("users",array("username"=>$form['username'],"password"=>md5($form['password'])));
	  $img=base_url().'assets/images/user.jpg';
	  if($chk1->num_rows()>0){
		  $user=$chk1->row();
		  $name=$user->first_name.' '.$user->last_name;
		  $data=array("user"=>$user->id,'username'=>$user->username,"created"=>$user->created,'name'=>$user->first_name.' '.$user->last_name,"img"=>$img);
		  $this->session->set_userdata($data);echo 1;
	  }else{
		echo "Invalid Username or Password";  
	  }
	}
	
	public function sqoff_enable(){
		//print_r($_POST);exit;
		$this->db->where("bsid",$_POST['id']);
	    $this->db->update("buysell",array("sq_off"=>$_POST['sst']));
			//echo "yes";
//		}else{echo "no";}
	}
	public function holdtrade_enable(){
		//print_r($_POST);exit;
		$this->db->where("trade_id",$_POST['id']);
	    $this->db->update("user_trades",array("hold_status"=>$_POST['sst']));
			//echo "yes";
//		}else{echo "no";}
	}
	
	
	
	
	public function square_off(){//
		$this->db->where("bsid",$_POST['id']);
	    $this->db->update("buysell",array("status"=>"EXIT"));
		$new=$this->db->get_where("buysell",array("bsid"=>$_POST['id']))->row();
		$metalname=$new->metal.'%20'.$new->type.'%20'.$new->lotsize.'%20'.'Lot(s)';
		$this->db->select("id,brokarage,mobile");
		$bro=$this->db->get_where("users",array("id"=>$new->uid))->row();
		$brok=$bro->brokarage*$new->lotsize;
		$mob=$bro->mobile;
		if($new->status==""){$brok=0;}
		///echo $brok;exit;
		$proloss=substr($new->pro_loss, 0, 1);
		$this->db->order_by("trid","desc");
		$chk=$this->db->get_where("user_trans",array("userid"=>$new->uid))->row();
		$wallet=$chk->left_amt;
		if($proloss=="-"){
			$ttype="Debit";
			$ttt="Loss";
		}else{
			$ttype="Credit";
			$ttt="Profit";
		}
		if($new->pro_loss==0 || $new->pro_loss==""){$brok=0;}
		$newbal=$wallet+$new->pro_loss;
		$newbal=$newbal-$brok;
		$newv=str_replace("-","",$new->pro_loss);
		$this->db->insert("user_trans",array("tr_amt"=>$newv,"tr_type"=>$ttype,"tr_date"=>date("Y-m-d"),"left_amt"=>$newbal,"userid"=>$new->uid,"buysell_id"=>$new->bsid));
		$message="MCX%20Trade%20in%20$metalname%20Exit%20With%20$ttt.%20Your%20Wallet%20$ttype%20with%20".$newv.".%20Brokarage%20Charge%20".$brok.".%20New%20Wallet%20Balance%20is%20".$newbal;
	//	file_get_contents("http://sms.bulksmsind.in/sendSMS?username=satish3112&message=$message&sendername=EGLOBL&smstype=TRANS&numbers=$mob&apikey=6a121a9b-e0e8-4b70-8657-c4e4ff82c044");	
			$url = "http://sms.bulksmsind.in/sendSMS?username=satish3112&message=$message&sendername=INFOTP&smstype=TRANS&numbers=$mob&apikey=6a121a9b-e0e8-4b70-8657-c4e4ff82c044";
$ch = curl_init();
curl_setopt ($ch, CURLOPT_URL, $url);
curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, 5);
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, true);
$contents = curl_exec($ch);
	 }
	 public function edit_trade(){
		$edit_trade=$this->db->get_where("buysell",array("bsid"=>$_POST['id']))->row(); 
		echo json_encode($edit_trade);
	 }
	 
	  public function edit_trade_submit(){
		parse_str($_POST['formdata'],$form);//echo "<pre>";print_r($form);exit;
		if($this->db->get_where("buysell",array("status"=>"EXIT","bsid"=>$form['bsid']))->num_rows()==0){
		
		$target=$form['target'];$stoploss=$form['stoploss'];
		if($form['type']=="BUY" && $form['target']==""){
			$target=1000000;	
		}
		if($form['type']=="BUY" && $form['stoploss']==""){
			$stoploss=0;	
		}
		if($form['type']=="SELL" && $form['target']==""){
			$target=0;	
		}
		if($form['type']=="SELL" && $form['stoploss']==""){
			$stoploss=1000000;	
		}
		//echo $target;echo "<br/>";
		//echo $stoploss;exit;
		if($form['type']=="BUY" && $target<$stoploss){
			echo 'TARGET must be greater than STOPLOSS.';exit;
		}
		if($form['type']=="SELL" && $target>$stoploss){
			echo 'STOPLOSS must be greater than TARGET.';exit;
//				redirect('home/dashboard');
		}
		
		//$this->db->where("status !=","EXIT");
		$this->db->where("bsid",$form['bsid']);
		if($this->db->update("buysell",array("lotsize"=>$form['lotsize'],"target"=>$form['target'],"stoploss"=>$form['stoploss']))==true){
		echo "0";	
		}else{
		echo "Trade Cannot be Updated";	
		}}else{echo "Trade is Exit";}
	 }
	
	public function buynow(){
		//echo "<pre>";	
//		print_r($_POST);exit;
		//$chk_bal=
		//if($_POST['target']
		
		$mxtr=$this->db->get_where("users",array("id"=>$this->session->userdata("user"),"act_link"=>$_POST['pin']))->row();
		if($this->db->get_where("buysell",array("uid"=>$this->session->userdata("user"),"status!="=>"EXIT","bsday"=>date("Y-m-d")))->num_rows()<$mxtr->max_lot){
		if($this->db->get_where("users",array("id"=>$this->session->userdata("user"),"act_link"=>$_POST['pin']))->num_rows()>0){
		$status="";
		if(isset($_POST['marketprice'])){
		$status="start";	
		}
		$m=explode("-",$_POST['metal']);
		if(isset($_POST['marketprice'])){
		$ll=$_POST['cur_rate'];
		}else{
		$ll=$_POST['setlimit'];
		}
		$target=$_POST['target'];
		$stoploss=$_POST['stoploss'];
		if($_POST['type']=="BUY" && $_POST['target']==""){
			$target=1000000;	
		}
		if($_POST['type']=="BUY" && $_POST['stoploss']==""){
			$stoploss=0;	
		}
		if($_POST['type']=="SELL" && $_POST['target']==""){
			$target=0;	
		}
		if($_POST['type']=="SELL" && $_POST['stoploss']==""){
			$stoploss=1000000;	
		}
		
		if($_POST['type']=="BUY" && $target<$stoploss){
			$this->session->set_flashdata('msg', '<div class="alert alert-danger">TARGET must be greater than STOPLOSS.</div>');
				redirect('home/dashboard');
		}
		if($_POST['type']=="SELL" && $target>$stoploss){
			$this->session->set_flashdata('msg', '<div class="alert alert-danger">STOPLOSS must be greater than TARGET.</div>');
				redirect('home/dashboard');
		}
		
		if($this->db->insert("buysell",array("status"=>$status,"market_rate"=>$_POST['cur_rate'],"uname"=>$this->session->userdata("name"),"uid"=>$this->session->userdata("user"),"type"=>$_POST['type'],"metal"=>$m[0],"lotsize"=>$_POST['lotsize'],"last_live"=>$ll,"setlimit"=>$ll,"target"=>$target,"stoploss"=>$stoploss,"bsday"=>date("Y-m-d"),"bsdate"=>date("Y-m-d H:i:s")))==true){
			$lid=$this->db->insert_id();
		$this->session->set_flashdata('msg', '<div class="alert alert-success">Your Transaction was Successful.</div>');
				redirect('home/dashboard');	
		}else{
		$this->session->set_flashdata('msg', '<div class="alert alert-danger">Your Transaction was Failed.</div>');
				redirect('home/dashboard');
		}
		}else{
			$this->session->set_flashdata('msg', '<div class="alert alert-danger">Incorrect Wallet PIN.</div>');
				redirect('home/dashboard');
		}}else{
			$this->session->set_flashdata('msg', '<div class="alert alert-danger">You can set maximum '.$mxtr->max_lot.
			' Trade at a time.</div>');
				redirect('home/dashboard');
		}
	 
	}
	
	public function testmsg21(){
	    file_get_contents("http://sms.bulksmsind.in/sendSMS?username=satish3112&message=$message&sendername=INFOTP&smstype=TRANS&numbers=9039581840&apikey=6a121a9b-e0e8-4b70-8657-c4e4ff82c044");
	}
	
	public function apilink(){
		$this->load->view('live_link');
	}
	
	public function dashboard(){
		if(!$this->session->userdata("user")){redirect("home");}
		$data=array();
		$this->template['middle'] = $this->load->view ($this->middle = 'dashboard',$data,true);
   		$this->layout(); 
	}
	public function buynow2(){
		//echo "<pre>";	
//		print_r($_POST);exit;
//if($this->db->get_where("users",array("id"=>$this->session->userdata("user"),"act_link"=>$_POST['pin']))->num_rows()>0){
		$status="";
		if(isset($_POST['marketprice'])){
		$status="start";	
		}
		$m=explode("-",$_POST['metal']);
		if(isset($_POST['marketprice'])){
		$ll=$_POST['cur_rate'];
		}else{
		$ll=$_POST['setlimit'];
		}
		$target=$_POST['target'];
		$stoploss=$_POST['stoploss'];
		if($_POST['type']=="BUY" && $_POST['target']==""){
			$target=1000000;	
		}
		if($_POST['type']=="BUY" && $_POST['stoploss']==""){
			$stoploss=0;	
		}
		if($_POST['type']=="SELL" && $_POST['target']==""){
			$target=0;	
		}
		if($_POST['type']=="SELL" && $_POST['stoploss']==""){
			$stoploss=1000000;	
		}
		$cust=explode("-",$_POST['customer']);
		if($this->db->insert("buysell",array("status"=>$status,"market_rate"=>$_POST['cur_rate'],"uname"=>$cust[1],"uid"=>$cust[0],"type"=>$_POST['type'],"metal"=>$m[0],"lotsize"=>$_POST['lotsize'],"last_live"=>$ll,"setlimit"=>$ll,"target"=>$target,"stoploss"=>$stoploss,"bsday"=>date("Y-m-d"),"bsdate"=>date("Y-m-d H:i:s")))==true){
			$lid=$this->db->insert_id();
		$this->session->set_flashdata('msg', '<div class="alert alert-success">Your Transaction was Successful.</div>');
				redirect('home/mcx');	
		}else{
		$this->session->set_flashdata('msg', '<div class="alert alert-danger">Your Transaction was Failed.</div>');
				redirect('home/mcx');
		}
	 
	}
	
}
