<?php
/* Manages user credit top-up and adjustment, balance and switch-overs
 * REQUIRES: Database connection
 */
class CreditManager {
	public $cusid, $cusfname, $cuslname, $balance, $cinuse, $cinuse_src, $lastcreditid, $sqlerr;
	public $credittables = array("openingbalances","store","creditadjustments","ccadjustments");
	public $debittables = array("valuationhistory","creditdeductions","vehiclehistorychecks","expiredcredits");
	public $sourcesAbr = array("openingbalances"=>"ob", "store"=>"sto", "creditadjustments"=>"adj", "ccadjustments"=>"cc");
	public $sources = array("ob"=>"openingbalances", "sto"=>"store", "adj"=>"creditadjustments", "cc"=>"ccadjustments");
	
	function __construct($cusid, $cusfname, $cuslname){//hook to a customer (user)
		date_default_timezone_set("Africa/Accra");
		$this->cusid = $cusid; $this->cusfname = $cusfname; $this->cuslname = $cuslname;
		$res=mysql_query("select creditinuse, creditinusesrc, lastcreditid from users where uniqueid='{$this->cusid}'");
		if($res && mysql_num_rows($res)>0){
			$row=mysql_fetch_array($res);
			$this->cinuse = $row['creditinuse'];
			$this->cinuse_src = $row['creditinusesrc'];
			$this->lastcreditid = $row['lastcreditid'];
		}else{ echo mysql_error(); }
	}
	
	function getCINUseCount(){
		$usecount = 0;
		$rarr = $this->getCINInfo();
		if(sizeof($rarr)>0){
			foreach($this->debittables as $tbl){
				$res=mysql_query("select sum(debit) as usecount from {$tbl} where uniqueid='{$this->cusid}' and creditref='{$rarr['creditref']}'");
				if($res && mysql_num_rows($res)>0){
					$row = mysql_fetch_array($res);
					if($row['usecount']!==NULL) $usecount += $row['usecount'];
				}else{ $usecount = 0;}
			}
		}
		return $usecount;
	}
	
	function getBalance(){
		$balance = 0;
		if($this->cinuse != ""){
			$this->updateExpiry();
			
			//get the balance
			$socin = 0; $socout = 0;
			foreach($this->credittables as $tbl){
				switch($tbl){
					case "store":
					$qry="select SUM(dutylimit) as socin from store where uniqueid='{$this->cusid}' and (status='loaded' or status='used' or status='expired')";
					break;
					default:
					$qry="select SUM(credit) as socin from {$tbl} where uniqueid='{$this->cusid}'";
				}
				$R = mysql_query($qry);
				if($R && mysql_num_rows($R)>0){ $W=mysql_fetch_array($R); if($W['socin']!==NULL) $socin += $W['socin'];	}
			}
			foreach($this->debittables as $tbl){
				$qry="select SUM(debit) as socout from {$tbl} where uniqueid='{$this->cusid}'";
				$R = mysql_query($qry);
				if($R && mysql_num_rows($R)>0){ $W=mysql_fetch_array($R); if($W['socout']!==NULL) $socout += $W['socout']; }
			}
			$balance = ($socin - $socout);
		}
		$this->balance = $balance;
		return $balance;
	}
		
	function getQuantityOfCIN(){
		$qty = 0;
		foreach($this->credittables as $tbl){
			switch($tbl){
				case "store":
				$qry="select dutylimit as qty from store where uniqueid='{$this->cusid}' and creditid='{$this->cinuse}'";
				break;
				
				default:
				$qry="select credit as qty from {$tbl} where uniqueid='{$this->cusid}' and creditid='{$this->cinuse}'";
			}
			$res = mysql_query($qry);
			if($res && mysql_num_rows($res)>0){ $row=mysql_fetch_array($res);
				if($row['qty']!==NULL) $qty += $row['qty'];
			}
		}
		return $qty;
	}
	function getNumberOfUses($uniqueid, $creditref){
		$nouses = 0;
		$R = mysql_query("select sum(debit) as nouses from valuationhistory where uniqueid='{$uniqueid}' and creditref='{$creditref}'");
		if($R && mysql_num_rows($R)>0){
			$W = mysql_fetch_array($R);
			if($W['nouses']!==NULL){
				$nouses = $W['nouses'];
			}
		}
		return $nouses;
	}
	
	function updateExpiry(){
		/*switch($this->cinuse_src){
			case "ob":
			$res = mysql_query("select id, credit, expirydate from openingbalances where uniqueid='{$this->cusid}' and creditid='{$this->cinuse}' and creditstatus != 'completed' and expirydate<=NOW() limit 1");
			if($res && mysql_num_rows($res)>0){//this credit has expired
				$row = mysql_fetch_array($res);
				//find quantity expired
				$qexpired = $row['credit'] - $this->getNumberOfUses($this->cusid, $this->cinuse);
				
				$R2 = mysql_query("insert into expiredcredits (uniqueid, creditref, credit, debit, transactdate) values ('{$this->cusid}','{$this->cinuse}','{$row['credit']}','{$qexpired}','{$row['expirydate']}')");
				if($R2){
					mysql_query("update {$this->sources[$this->cinuse_src]} set creditstatus = 'completed' where (uniqueid = '{$this->cusid}' and creditid = '{$this->cinuse}')");
				}
			}
			break;
			
			case "adj":
			$res = mysql_query("select id, credit, duration + INTERVAL duration days as expirydate from creditadjustments where uniqueid='{$this->cusid}' and creditid='{$this->cinuse}' and creditstatus != 'completed' and (transactdate + INTERVAL duration days)<=NOW() limit 1");
			if($res && mysql_num_rows($res)>0){//this credit has expired
				$row = mysql_fetch_array($res);
				//find quantity expired
				$qexpired = $row['credit'] - $this->getNumberOfUses($this->cusid, $this->cinuse);
				
				$R2 = mysql_query("insert into expiredcredits (uniqueid, creditref, credit, debit, transactdate) values ('{$this->cusid}','{$this->cinuse}','{$row['credit']}','{$qexpired}','{$row['expirydate']}')");
				if($R2){
					mysql_query("update {$this->sources[$this->cinuse_src]} set creditstatus = 'completed' where (uniqueid = '{$this->cusid}' and creditid = '{$this->cinuse}')");
				}
			}
			break;
			
			case "sto":
			$res = mysql_query("select id, dutylimit as credit, expirydate from store where uniqueid='{$this->cusid}' and creditid='{$this->cinuse}' and creditstatus != 'completed' and expirydate<=NOW() limit 1");
			if($res && mysql_num_rows($res)>0){//this credit has expired
				$row = mysql_fetch_array($res);
				//find quantity expired
				$qexpired = $row['credit'] - $this->getNumberOfUses($this->cusid, $this->cinuse);
				
				$R2 = mysql_query("insert into expiredcredits (uniqueid, creditref, credit, debit, transactdate) values ('{$this->cusid}','{$this->cinuse}','{$row['credit']}','{$qexpired}','{$row['expirydate']}')");
				if($R2){
					mysql_query("update {$this->sources[$this->cinuse_src]} set creditstatus = 'completed' where (uniqueid = '{$this->cusid}' and creditid = '{$this->cinuse}')");
				}
			}
			break;
			
			case "cc":
			$res = mysql_query("select id, credit, expirydate from ccadjustments where uniqueid='{$this->cusid}' and creditid='{$this->cinuse}' and creditstatus != 'completed' and expirydate<=NOW() limit 1");
			if($res && mysql_num_rows($res)>0){//this credit has expired
				$row = mysql_fetch_array($res);
				//find quantity expired
				$qexpired = $row['credit'] - $this->getNumberOfUses($this->cusid, $this->cinuse);
				
				$R2 = mysql_query("insert into expiredcredits (uniqueid, creditref, credit, debit, transactdate) values ('{$this->cusid}','{$this->cinuse}','{$row['credit']}','{$qexpired}','{$row['expirydate']}')");
				if($R2){
					mysql_query("update {$this->sources[$this->cinuse_src]} set creditstatus = 'completed' where (uniqueid = '{$this->cusid}' and creditid = '{$this->cinuse}')");
				}
			}
			break;
		}*/
	}
	
	function activateNextCredit(){
		/*//set status of last credit to completed
		$res = mysql_query("update {$this->sources[$this->cinuse_src]} set creditstatus = 'completed' where (uniqueid = '{$this->cusid}' and creditid = '{$this->cinuse}')");
		if(!$res) echo mysql_error();
		//echo "inside activateNextCredit():<br />update {$this->sources[$this->cinuse_src]} set creditstatus = 'completed' where (uniqueid = '{$this->cusid}' and creditid = '{$this->cinuse}')";*/
		
		//find next credit available
		$nextcreditarr = array();
		$RR = mysql_query("(select
			store.creditid as creditref,
			store.dutylimit as credit,
			store.dateloaded as transactdate,
			store.dateloaded as validfrom,
			store.expirydate as validto,
			DATEDIFF(store.expirydate,store.dateloaded) as duration,
			'sto' as src,
			'' as details,
			store.creditstatus as status
			from store where store.uniqueid='{$this->cusid}' and store.creditstatus!='completed')
			
			UNION ALL
			
			(select
			creditadjustments.creditid as creditref,
			creditadjustments.credit as credit,
			creditadjustments.transactdate as transactdate,
			creditadjustments.transactdate as validfrom,
			creditadjustments.transactdate + INTERVAL creditadjustments.duration DAY as validto,
			creditadjustments.duration as duration,
			'adj' as src,
			'' as details,
			creditadjustments.creditstatus as status
			from creditadjustments where creditadjustments.uniqueid='{$this->cusid}' and creditadjustments.creditstatus!='completed')
			
			order by transactdate ASC limit 1");
		
		if($RR && mysql_num_rows($RR)>0){
			$WW = mysql_fetch_array($RR);
			
			//find and overwrite with the correct effective date range
			//$firstdateofuse = '';
			//$RC = mysql_query("select transactdate as firstdateofuse from valuationhistory where uniqueid='{$this->cusid}' and creditref='' and (transactdate>='{$validfrom}' and transactdate<='{$validto}') order by transactdate ASC limit 1 offset 0");
			
			$RC = mysql_query("select transactdate as validfrom, transactdate + INTERVAL {$WW['duration']} DAY as validto from valuationhistory where uniqueid='{$this->cusid}' and creditref='' and (transactdate>='{$WW['validfrom']}' and transactdate<='{$WW['validto']}') order by transactdate ASC limit 1 offset 0");
			if($RC && mysql_num_rows($RC)>0){
				$WC = mysql_fetch_array($RC);
				//echo "<br />New Validity Date = {$WW['validfrom']} - {$WW['validto']}";
				$WW['validfrom'] = $WC['validfrom'];
				$WW['validto'] = $WC['validto'];
				//echo "<br />New Validity Date = {$WW['validfrom']} - {$WW['validto']}";
			}
			$nextcreditarr = array('uniqueid'=>$this->cusid, 'creditref'=>$WW['creditref'], 'credit'=>$WW['credit'], 'validfrom'=>$WW['validfrom'], 'validto'=>$WW['validto'], 'src'=>$WW['src']);
			$rrs = mysql_query("update users set creditinuse = '{$WW['creditref']}', creditinusesrc = '{$WW['src']}' where uniqueid = '{$this->cusid}'");
			//update class variables
			if($rrs){
				$this->cinuse = $nextcreditarr['creditref'];
				$this->cinuse_src = $nextcreditarr['src'];
			}
		}
		//echo "<br />Next Activated Credit = ";print_r($nextcreditarr);
		return $nextcreditarr;
	}
	
	function adjustBy($amt, $com, $duration){
		$rs='{"opsstat":1,"opsstatinfo":"Operation was not successful !"}';
		$amt = (int) trim($amt); $ab_amt = abs($amt);
		if($amt!=0){
			$inscrip = " credit"; if($ab_amt>1) $inscrip = " credits";
			$bal = $this->getBalance();
			$creditid = $this->lastcreditid + 1;
			if($amt>0){ $acol = "credit"; $cin = $ab_amt; $cout = 0; } else{ $acol = "debit"; $cin = 0; $cout = $ab_amt; }
			$balnow = $bal + $amt;
			//check if it needs immediate activation
			if($this->balance<1){//yes
				$expdate = date("Y-m-d H:i:s",time()+(86400*$duration));
				if($amt<0){
					$ins = "";
					$sql = "insert into creditdeductions (uniqueid, officerid, officername, debit, comment, transactdate) values ('{$this->cusid}', '{$_SESSION['uid']}', '{$_SESSION['uname']}', '{$cout}', '{$com}', NOW())";
				}else{
					$ins = ", creditinuse='{$creditid}', creditinusesrc='adj'"; $this->cinuse=$creditid; $this->cinuse_src="adj";
					$sql =  "insert into creditadjustments (uniqueid, officerid, officername, creditid, credit, debit, duration, comment, transactdate, expirydate) values ('{$this->cusid}', '{$_SESSION['uid']}', '{$_SESSION['uname']}', '{$creditid}', '{$cin}', '{$cout}', '{$duration}', '{$com}', NOW(), '{$expdate}')";
				}
			}else{
				$ins = "";
				if($amt<0){
					$sql = "insert into creditdeductions (uniqueid, officerid, officername, debit, comment, transactdate) values ('{$this->cusid}', '{$_SESSION['uid']}', '{$_SESSION['uname']}', '{$cout}', '{$com}', NOW())";
				}else{
					$sql = "insert into creditadjustments (uniqueid, officerid, officername, creditid, credit, debit, duration, comment, transactdate) values ('{$this->cusid}', '{$_SESSION['uid']}', '{$_SESSION['uname']}', '{$creditid}', '{$cin}', '{$cout}', '{$duration}', '{$com}', NOW())";
				}
			}
			mysql_query("begin");
			$res = mysql_query($sql);
			if($res){
				if($amt<0){ $res = mysql_query("update users set {$acol}={$acol}+{$ab_amt} where uniqueid='{$this->cusid}'"); }
				else{ $res = mysql_query("update users set {$acol}={$acol}+{$ab_amt}, lastcreditid='{$creditid}'{$ins} where uniqueid='{$this->cusid}'"); }
				if($res){
					mysql_query("commit");
					if($amt<0){ $rs='{"opsstat":0,"opsstatinfo":"'.$ab_amt.$inscrip.' removed. '.$this->cusfname.' has '.$balnow.' now."}'; }
					else { $rs='{"opsstat":0,"opsstatinfo":"'.$ab_amt.$inscrip.' added. '.$this->cusfname.' has '.$balnow.' now."}'; }
				}else{ $this->sqlerr = mysql_error(); mysql_query("rollback"); }
			}else{ $this->sqlerr = mysql_error(); mysql_query("rollback"); }
		}
		return $rs;
	}
	
	function ccAdjustBy($amt, $mtd, $com, $duration){//positive adjustment only
		$rs='{"opsstat":1,"opsstatinfo":"Operation was not successful !"}';
		$amt = (int) trim($amt); $ab_amt = abs($amt);
		if($amt!=0){
			$inscrip = " credit"; if($ab_amt>1) $inscrip = " credits";
			$bal = $this->getBalance();
			$creditid = $this->lastcreditid + 1;
			$acol = "credit"; $cin = $ab_amt; $cout = 0;
			$balnow = $bal + $amt;
			//check if it needs immediate activation
			if($this->balance<1){//yes
				$expdate = date("Y-m-d H:i:s",time()+(86400*$duration));
				$ins = ", creditinuse='{$creditid}', creditinusesrc='cc'"; $this->cinuse=$creditid; $this->cinuse_src="cc";
				$sql =  "insert into ccadjustments (uniqueid, paymentmethod, creditid, credit, debit, duration, comment, transactdate, expirydate) values ('{$this->cusid}', '{$mtd}', '{$creditid}', '{$cin}', '{$cout}', '{$duration}', '{$com}', NOW(), '{$expdate}')";
			}else{
				$ins = "";
				$sql = "insert into ccadjustments (uniqueid, paymentmethod, creditid, credit, debit, duration, comment, transactdate) values ('{$this->cusid}', '{$mtd}', '{$creditid}', '{$cin}', '{$cout}', '{$duration}', '{$com}', NOW())";
			}
			mysql_query("begin");
			$res = mysql_query($sql);
			if($res){
				$res = mysql_query("update users set {$acol}={$acol}+{$ab_amt}, lastcreditid='{$creditid}'{$ins} where uniqueid='{$this->cusid}'");
				if($res){
					mysql_query("commit");
					$rs='{"opsstat":0,"opsstatinfo":"'.$ab_amt.$inscrip.' added. '.$this->cusfname.' has '.$balnow.' now."}';
				}else{ $this->sqlerr = mysql_error(); mysql_query("rollback"); }
			}else{ echo mysql_error(); $this->sqlerr = mysql_error(); mysql_query("rollback"); }
		}
		return $rs;
	}
	
	function topupWith($pinno){
		$goodtogo = false; $price = 0; $pricett = ""; $failreason="";
		$bal = $this->getBalance(); $creditid = $this->lastcreditid + 1; 
		//find the pincode
		$res = mysql_query("select * from store where pinno='{$pinno}' limit 1");
		if($res && mysql_num_rows($res)>0){//pinno found (unused)
			$row = mysql_fetch_array($res); $vendorid=$row['vendor']; $creditid=$row['creditid'];
			switch($row['status']){
				case 'activated':
				$creditid = $row['creditid']; $quantity = $row['dutylimit']; $disp_price="";
				
				switch($row['product']){
					case "S-CARD-C":
					case "S-CARD-O":
					case "E-PIN-GH":
					case "MTN-MM":
					case "TIGO-MM":
					case "AIRTEL-MM":
					$currency="GHS";
					$res = mysql_query("select cediprice from pintypeinfo where dutylimit='{$quantity}'");
					if($res){ $row = mysql_fetch_array($res); $price = $row['cediprice']; $disp_price = $price; }
					break;
					
					case "E-PIN-US":
					$currency="USD";
					$res = mysql_query("select dollarprice from pintypeinfo where dutylimit='{$quantity}'");
					if($res){ $row = mysql_fetch_array($res); $price = $row['dollarprice']; $dollarprice = $price; $disp_price = $price; }
					//get fxrate and apply
					$res=mysql_query("select rate from fxrates where symbol='USD'");
					if($res && mysql_num_rows($res)>0){ $row=mysql_fetch_array($res); $price = $price * (double) $row['rate']; }
					break;
					
					default:
					$currency="GHS";
					$res = mysql_query("select cediprice from pintypeinfo where dutylimit='{$quantity}'");
					if($res){ $row = mysql_fetch_array($res); $price = $row['cediprice']; $disp_price = $price; }
				}
				//get vendor commission
				$res = mysql_query("select commission as percentage from vendorinfo where vendorid='{$vendorid}' order by dateedited DESC limit 1");
				if($res){ $row = mysql_fetch_array($res); $percentage = $row['percentage']; }
				else{ $percentage=0; }
				
				//check if it would need immediate activation
				if($this->balance<1){//yes
					$res = mysql_query("select duration from pintypeinfo where dutylimit = '{$quantity}' limit 1");
					if($res){ $row = mysql_fetch_array($res); $duration = $row['duration']; }
					
					$expdate = date("Y-m-d H:i:s",time()+(86400*$duration));
					$ins = ", creditinuse='{$creditid}', creditinusesrc='sto'"; $this->cinuse=$creditid; $this->cinuse_src="sto";
					//store as cedis or dollars?
					switch($currency){
						case "GHS":
						$sql = "update store set uniqueid='{$this->cusid}', creditid='{$creditid}', dateloaded=NOW(), expirydate='{$expdate}'{$pricett}, status='loaded', price='{$price}', topay=(((100-{$percentage})/100)*{$price}), commission='{$percentage}' where creditid='{$creditid}' and status='activated'";
						break;
						
						case "USD":
						$sql = "update store set uniqueid='{$this->cusid}', creditid='{$creditid}', dateloaded=NOW(), expirydate='{$expdate}'{$pricett}, status='loaded', dollarprice='{$dollarprice}', topay=(((100-{$percentage})/100)*{$dollarprice}), commission='{$percentage}' where creditid='{$creditid}' and status='activated'";
						break;
					}
				}else{
					$ins = "";
					//cedis or dollars?
					switch($currency){
						case "GHS":
						$sql = "update store set uniqueid='{$this->cusid}', creditid='{$creditid}', dateloaded=NOW(), expirydate='{$expdate}'{$pricett}, status='loaded', price='{$price}', topay=(((100-{$percentage})/100)*{$price}), commission='{$percentage}' where creditid='{$creditid}' and status='activated'";
						break;
						
						case "USD":
						$sql = "update store set uniqueid='{$this->cusid}', creditid='{$creditid}', dateloaded=NOW(), expirydate='{$expdate}'{$pricett}, status='loaded', dollarprice='{$dollarprice}', topay=(((100-{$percentage})/100)*{$dollarprice}), commission='{$percentage}' where creditid='{$creditid}' and status='activated'";
						break;
					}
				}
				
				mysql_query('begin');
				$res = mysql_query($sql);
				if($res){ $res = mysql_query("update warehouse set status='loaded' where creditid='{$creditid}' and status='activated'");}
				if($res && mysql_affected_rows()>0){
					$r000 = mysql_query("update users set firstpurchasedate = NOW() where uniqueid='{$this->cusid}' and firstpurchasedate='0000-00-00'");
					$res = mysql_query("update users set credit=credit+{$quantity}, lastcreditid='{$creditid}'{$ins} where uniqueid='{$this->cusid}'");
					if($res && mysql_affected_rows()>0){ $goodtogo = true; }
				}
				if($goodtogo){
					//mysql_query("insert into topuphistory (userid,fullname,type,creditid,quantity,topupdate) values ('{$_SESSION['uid']}','{$_SESSION['uname']}','','{$creditid}','{$quantity}',NOW())");
					mysql_query('commit');
					$rs='{';
					$rs.='"opsstat":0,';
					$rs.='"opsstatinfo":"Topup was successful",';
					$rs.='"pinno":"'.$pinno.'",';
					$rs.='"price":"'.$price.'",';
					$rs.='"quantity":"'.$quantity.'",';
					$rs.='"balance":"'.($bal + $quantity).'",';
					
					$message = "<table style='background-color:#F0FBCB;' width='400px'><tr><td width='10px'><img src='images/success.png'></td><td width='300px'><b>Recharge was successful<b></td></tr><tr><td></td><td>{$currency} {$disp_price} ({$quantity} - Search)</td></tr></table>";
					$rs.='"message":"'.$message.'"';
					$rs.='}';
				}else{ 
					mysql_query('rollback');
					$rs='{';
					$rs.='"opsstat":1,';
					if($failreason=="") $rs.='"opsstatinfo":"SORRY, WE COULD NOT LOAD YOUR CREDIT\n\nPlease contact Automasters with the serial number of this card ( '.$creditid.' ) and we will resolve this immediately.\n\nThank you !",';
					else $rs.='"opsstatinfo":"'.$failreason.'",';
					$message = "<table style='background-color:#FFEFEF;' width='400px'><tr><td width='10px'><img src='images/fail.png'></td><td width='300px'><b>Could not recharge, please contact Automasters<b></td></tr><tr><td></td><td>({$pinno})</td></tr></table>";
					$rs.='"message":"'.$message.'"';
					$rs.='}';
				}
				break;
				
				case 'assigned':
				$rs='{"opsstat":1,"opsstatinfo":"SORRY, WE COULD NOT LOAD YOUR CREDIT\n\nPlease contact Automasters with the serial number of this card ( '.$creditid.' ) and we will resolve this immediately.\n\nThank you !"}';
				break;
				
				case 'unassigned':
				$rs='{"opsstat":1,"opsstatinfo":"SORRY, WE COULD NOT LOAD YOUR CREDIT\n\nPlease contact Automasters with the serial number of this card ( '.$creditid.' ) and we will resolve this immediately.\n\nThank you !"}';
				break;
				
				case 'loaded':
				case 'used':
				$rs='{"opsstat":1,"opsstatinfo":"THIS CARD HAS BEEN ALREADY USED\n\nPlease contact Automasters with the serial number of this card ( '.$creditid.' ) for futher clarification."}';
				break;
				
				case 'expired':
				$rs='{"opsstat":1,"opsstatinfo":"THIS CARD HAS EXPIRED\n\nPlease contact Automasters with the serial number of this card ( '.$creditid.' ) for futher clarification."}';
				break;
			}
		}else{
			$rs='{"opsstat":1,"opsstatinfo":"DOES NOT EXIST\n\nWe did not find the pin code you entered. Please contact Automasters with the serial number of this card if you believe this is a mistake."}';
		}
		return $rs;
	}
	
	function checkExhaustion($uniqueid, $creditref, $credit){
		$nouses = $this->getNumberOfUses($uniqueid, $creditref);
		if($nouses >= $credit){
			$this->activateNextCredit();
		}
	}
	
	function checkCINCompletion(){
		$info = $this->getCINInfo();
		//echo "Credit In Use = "; print_r($info);
		if(sizeof($info)>0){
			$useCount = $this->getCINUseCount(); $creditAmt = $info['credit'];
			//echo "<br />Used {$useCount} out of {$creditAmt}";
			if($useCount >= $creditAmt){
				//set status of last credit to completed
				$res = mysql_query("update {$this->sources[$this->cinuse_src]} set creditstatus = 'completed' where (uniqueid = '{$this->cusid}' and creditid = '{$this->cinuse}')");
				//echo "inside activateNextCredit():<br />update {$this->sources[$this->cinuse_src]} set creditstatus = 'completed' where (uniqueid = '{$this->cusid}' and creditid = '{$this->cinuse}')";
				$this->activateNextCredit();
			}
		}
	}
	
	function getCINInfo(){
		$info = array();
		//echo "this->cinuse_src = {$this->cinuse_src}";
		switch($this->cinuse_src){
			case "ob":
			$res = mysql_query("select creditid, credit from openingbalances where uniqueid='{$this->cusid}' and creditid='{$this->cinuse}'");//echo "select creditid, credit from openingbalances where uniqueid='{$this->cusid}' and creditid='{$this->cinuse}'";
			if($res && mysql_num_rows($res)>0){
				$row = mysql_fetch_array($res);
				$info = array("creditref"=>$row['creditid'], "credit"=>$row['credit'], "source"=>"openingbalances");
			}
			break;
			
			case "adj":
			$res = mysql_query("select creditid, credit from creditadjustments where uniqueid='{$this->cusid}' and creditid='{$this->cinuse}'");//echo "select creditid, credit from creditadjustments where uniqueid='{$this->cusid}' and creditid='{$this->cinuse}'";
			if($res && mysql_num_rows($res)>0){
				$row = mysql_fetch_array($res);
				$info = array("creditref"=>$row['creditid'], "credit"=>$row['credit'], "source"=>"creditadjustments");
			}
			break;
			
			case "sto":
			$res=mysql_query("select creditid, dutylimit as credit from store where uniqueid='{$this->cusid}' and creditid='{$this->cinuse}'");//echo "select creditid, dutylimit as credit from store where uniqueid='{$this->cusid}' and creditid='{$this->cinuse}'";
			if($res && mysql_num_rows($res)>0){
				$row = mysql_fetch_array($res);
				$info = array("creditref"=>$row['creditid'], "credit"=>$row['credit'], "source"=>"store");
			}
			
			case "cc":
			$res = mysql_query("select creditid, credit from ccadjustments where uniqueid='{$this->cusid}' and creditid='{$this->cinuse}'");//echo "select creditid, credit from ccadjustments where uniqueid='{$this->cusid}' and creditid='{$this->cinuse}'";
			if($res && mysql_num_rows($res)>0){
				$row = mysql_fetch_array($res);
				$info = array("creditref"=>$row['creditid'], "credit"=>$row['credit'], "source"=>"ccadjustments");
			}
			break;
		}
		return $info;
	}
	
	function checkDSStatus(){
		$toret = array();
		$res = mysql_query("select dsref from users where uniqueid='{$this->cusid}' and dsref!=''");
		if($res && mysql_num_rows($res)>0){
			$row = mysql_fetch_array($res);
			$dsref = $row['dsref'];
			
			$r = mysql_query("select * from dssetting where dsref='{$dsref}'");
			if($r && mysql_num_rows($r)>0){
				$w = mysql_fetch_array($r); $limitqty = (int) $w['limitqty'];
				
				$curdate = (int) date("Ymd"); $curhour = (int) date("H");
				
				$datefrom = (int) date("Ymd" ,strtotime($w['effdatefrom']));
				$dateto = (int) date("Ymd" ,strtotime($w['effdateto']));
				
				$hourfrom = (int) $w['effhourfrom'];
				$hourto = (int) $w['effhourto'];
				
				//echo "curdate = {$curdate}\ncurhour = {$curhour}\ndatefrom = {$datefrom}\ndateto = {$dateto}\nhourfrom = {$hourfrom}\nhourto = {$hourto}\n";
				
				if($curdate >= $datefrom && $curdate <= $dateto && $curhour >= $hourfrom && $curhour < $hourto){
					//in effect
					$r1 = mysql_query("select count(*) as ddone from valuationhistory where creditref = '{$dsref}'");
					if($r1){
						$w1 = mysql_fetch_array($r1);
						if($w1['ddone']!==NULL){
							$ddone = (int) $w1['ddone'];
							
							if($ddone < $limitqty){
								$toret = array("creditref"=>$dsref, "debit"=>0);
							}else{
								//used up, clear from user record
								mysql_query("update users set dsref = '' where uniqueid='{$this->cusid}'");
							}
						}
					}
				}else{
					//not in effect, clear from user record
					mysql_query("update users set dsref = '' where uniqueid='{$this->cusid}'");
				}
			}
		}
		return $toret;
	}
}
?>