<?php
/* Credit Administration class
 * REQUIRES: Database connection
 */
class CreditAdminister {
	public $cusid, $cusfname, $cuslname;
	private $creationstart = 1100000000;
	private $range = array('start'=>0, 'end'=>0, 'no'=>0);
	private $ranging = array('start'=>0, 'end'=>0, 'no'=>0);
	private $ranger = array(
			"0",
			array("1100000001","2000000000"),
			array("2100000001","3000000000"),
			array("3100000001","4000000000"),
			array("4100000001","5000000000"),
			array("5100000001","6000000000"),
			array("6100000001","7000000000"),
			array("7100000001","8000000000"),
			array("8100000001","9000000000"),
			array("9100000001","999999999999")
		);
		
	function __construct($cusid, $cusfname, $cuslname){//hook to a customer (user)
		$this->cusid = $cusid; $this->cusfname = $cusfname; $this->cuslname = $cuslname;
	}
	function setRange($creditid){
		$p=(int) substr($creditid,0,1);
		$this->range['start']=$this->ranger[$p][0]; $this->range['end']=$this->ranger[$p][1];
	}
	function createPinQuantity($quantity){
		if($quantity<=1000){
			$sqlsuccess = false; $this->ranging['no']=0; $this->ranging['start']=0; $this->ranging['end']=0;
			$res = mysql_query("select max(creditid) as maxserial from warehouse where category='new'");
			if($res){ $row = mysql_fetch_array($res); $maxserial = $row["maxserial"]; }
			if($maxserial=="") $maxserial = $this->creationstart;
			$number = $quantity; $ser = $maxserial ;
			
			while($number>0){
				$ser = $ser+1; $this->setRange($ser);
				if($ser < $this->range['start']){//outside new format range so start with the new startpoint
					$ser = $this->creationstart;
				}
				$number--; $this->ranging['no']++; if($this->ranging['start']==0){ $this->ranging['start']=$ser; } $this->ranging['end']=$ser;
				
				$res = mysql_query("insert into warehouse (creditid, pinno, uniqueid, officer, datecreated, category, status) values ('{$ser}', '".$this->newPin()."', '{$_SESSION['uid']}', '{$_SESSION['uname']}', NOW(), 'new', 'new')");
				if($res){ $sqlsuccess = true; }
			};
			if($sqlsuccess && $this->ranging['no']>0){//green light
				$rs='{';
				$rs.='"opsstat":0,';
				$rs.='"opsstatinfo":"'.$this->ranging["no"].' Pin(s) Created",';
				$rs.='"officer":"'.$_SESSION["uname"].'",';
				$rs.='"start":'.$this->ranging["start"].',';
				$rs.='"end":'.$this->ranging["end"].',';
				$rs.='"quantity":'.$this->ranging["no"].',';
				$rs.='"datecreated":"Today"';
				$rs.='}';
				//save to history
				mysql_query("insert into pincreationhistory (uniqueid, officer, serialstart, serialend, quantity, datecreated) values ('{$_SESSION['uid']}', '{$_SESSION['uname']}', '{$this->ranging['start']}', '{$this->ranging['end']}', '{$this->ranging['no']}', NOW())");
				
			}else{ $rs = '{"opsstat":1,"opsstatinfo":"Sorry\nThe operation was not successful"}'; }
			return $rs;
		}else{
			return '{"opsstat":1,"opsstatinfo":"Sorry\nQuantity too large. Should be at most 1,000 Pins at a time."}';
		}
	}
	
	function copyQuantity($quantity, $category){
		$c = 0; $serialstart=""; $serialend="";
		if($quantity==0){
			return '{"opsstat":1,"opsstatinfo":"Sorry\nInvalid quantity entered (0)"}';
		}else if($quantity<=1000){
			$sqlsuccess = false; $rs = '{"opsstat":1,"opsstatinfo":"Sorry\nThe operation was not successful"}';
			$res = mysql_query("select * from warehouse where category='{$category}' and status='new' order by creditid limit {$quantity}");
			if($res){
				if(mysql_num_rows($res)<$quantity){//full amount not available
					$rs = '{"opsstat":1,"opsstatinfo":"Sorry\nThere are less than '.$quantity.' uncopied '.$category.' Pin(s) in the warehouse.\nYou may refresh the page to view the current statistic"}';
				}else{
					while($row = mysql_fetch_array($res)){
						$serialend=$row['creditid']; if($c==0){ $serialstart = $serialend; } $c++; 
						mysql_query("begin");
						$res2 = mysql_query("insert into store (creditid, pinno, status, datecopied) values ('{$row['creditid']}','{$row['pinno']}','unassigned', NOW())");
						if($res2) $res2 = mysql_query("update warehouse set status='copied' where creditid='{$row['creditid']}'");
						if($res2){ mysql_query("commit"); $sqlsuccess = true; }
					}
				}
			}
			if($sqlsuccess){//green light
				$rs='{';
				$rs.='"opsstat":0,';
				$rs.='"serialstart":"'.$serialstart.'",';
				$rs.='"serialend":"'.$serialend.'",';
				$rs.='"quantity":'.$quantity;
				$rs.='}';
			}
			return $rs;
		}else{
			return '{"opsstat":1,"opsstatinfo":"Sorry\nQuantity too large. Should be at most 1,000 Pins at a time."}';
		}
	}
	function copyRange($start, $end){
		$c = 0; $serialstart=""; $serialend=""; $quantity = ((double) $end) - ((double) $start)+1; $quantitycopied = 0;
		if($quantity<=1000){
			$sqlsuccess = false; $rs = '{"opsstat":1,"opsstatinfo":"Sorry\nThe operation was not successful"}';
			$res = mysql_query("select * from warehouse where creditid>='{$start}' and creditid<='{$end}' and status='new' order by creditid");
			if($res){
				$quantitycopied = mysql_num_rows($res);
				if($quantitycopied<1){//range not available
					$rs = '{"opsstat":1,"opsstatinfo":"Sorry\nSerial range ( '.$start.' - '.$end.' ) is not available.\nPlease check and try again"}';
				}else{
					while($row = mysql_fetch_array($res)){
						$serialend=$row['creditid']; if($c==0){ $serialstart = $serialend; } $c++;
						mysql_query("begin");
						$res2 = mysql_query("insert into store (creditid, pinno, status, datecopied) values ('{$row['creditid']}','{$row['pinno']}','unassigned', NOW())");
						if($res2) $res2 = mysql_query("update warehouse set status='copied' where creditid='{$row['creditid']}'");
						if($res2){ mysql_query("commit"); $sqlsuccess = true; }
					}
				}
			}
			if($sqlsuccess){//green light
				$rs='{';
				$rs.='"opsstat":0,';
				$rs.='"serialstart":"'.$serialstart.'",';
				$rs.='"serialend":"'.$serialend.'",';
				$rs.='"quantity":"'.$quantity.'",';
				$rs.='"quantitycopied":'.$quantitycopied;
				$rs.='}';
			}
			return $rs;
		}else{
			return '{"opsstat":1,"opsstatinfo":"Sorry\nRange too wide. Should be at most 1,000 Pins at a time."}';
		}
	}
	
	function getPinRange($quantity){
		if($quantity<=1000){
			$this->ranging['no']=0; $this->ranging['start']=0; $this->ranging['end']=0;
			$res = mysql_query("select max(creditid) as maxserial from warehouse where category='new'");
			if($res){ $row = mysql_fetch_array($res); $maxserial = $row["maxserial"]; }
			if($maxserial=="") $maxserial=$this->creationstart;
			$number = $quantity; $ser = $maxserial ;
			
			while($number>0){
				$ser = $ser+1; $this->setRange($ser);
				if($ser < $this->range['start']){//outside new format range so start with the new startpoint
					$ser = $this->creationstart;
				}
				$number--; $this->ranging['no']++; if($this->ranging['start']==0){ $this->ranging['start']=$ser; } $this->ranging['end']=$ser;
			};
			if($this->ranging['no']>0){//green light
				$rs='{';
				$rs.='"opsstat":0,';
				$rs.='"start":'.$this->ranging["start"].',';
				$rs.='"end":'.$this->ranging["end"].',';
				$rs.='"quantity":'.$this->ranging["no"];
				$rs.='}';
			}else{ $rs = '{"opsstat":1,"opsstatinfo":"Sorry\nThe operation was not successful"}'; }
			return $rs;
		}else{
			return '{"opsstat":1,"opsstatinfo":"Sorry\nQuantity too large. Should be at most 1,000 Pins at a time."}';
		}
	}
	
	function newPin(){ $pinno = ""; for($i=0; $i<15; $i++){ $pinno .= mt_rand(0,9); } return $pinno; }
	
	function savePins($uid,$name,$selection){
		$success = false; $k=0; $stringified = $selection;
		$toret = '{"opsstat":1,"opsstatinfo":"SORRY !\nThe operation was aborted because one or more products\nfailed to be saved."}';
		$selection = json_decode($selection,true);
		//save to DB
		foreach($selection as $S=>$L){
			$k++; mysql_query("begin");
			$res = mysql_query("update store set dutylimit='{$L[limit]}', vendor='{$uid}', datetovendor=NOW(), status='assigned' where creditid='{$S}' and status='unassigned'");
			if($res && mysql_affected_rows()>0){ $res = mysql_query("update warehouse set status='assigned' where creditid='{$S}'"); }
			if($res && mysql_affected_rows()>0){ $success = true; }
			if(!$success) break;
		}
		if($success){
			$res = mysql_query("commit");
			if($res){
				$toret = '{"opsstat":0,"opsstatinfo":"DONE\nAll products were successfully saved and are now\npending activation.","date":"'.date('M d, Y').'"}';
				mysql_query("insert into pendingpintransactions (vendor,vendorname,quantity,commencer,datecommenced,stringifiedobject,display) values ('{$uid}','{$name}','{$k} Card(s)','{$_SESSION['uname']}',NOW(),'{$stringified}','1')");
			}
		}else{ mysql_query("rollback");	}
		return $toret;
	}
	function unassignPins($id,$selection){
		$success = false;
		$toret = '{"opsstat":1,"opsstatinfo":"SORRY !\nThe operation was aborted because one or more products\nwould fail to be unassigned."}';
		$selection = json_decode($selection,true);
		//save to DB
		foreach($selection as $S=>$L){
			mysql_query("begin");
			$res = mysql_query("update store set dutylimit='0', vendor='', datetovendor='', status='unassigned' where creditid='{$S}' and (status='assigned' or status='activated')");
			if($res && mysql_affected_rows()>0){ $res = mysql_query("update warehouse set status='copied' where creditid='{$S}'"); }
			if($res && mysql_affected_rows()>0){ $success = true; }
			if(!$success) break;
		}
		if($success){
			$res = mysql_query("commit");
			mysql_query("delete from pendingpintransactions where id='{$id}'");
			if($res){ $toret = '{"opsstat":0,"opsstatinfo":"DONE\nAll products have been successfully unassigned."}';}
		}else{ mysql_query("rollback");	}
		return $toret;
	}
	function activatePins($id,$selection){
		$success = false;
		$toret = '{"opsstat":1,"opsstatinfo":"SORRY !\nActivation failed."}';
		$selection = json_decode($selection,true);//print_r($selection);
		//save to DB
		foreach($selection as $S=>$L){
			mysql_query("begin");
			$res = mysql_query("update store set activatedby='{$_SESSION['uid']}', dateactivated=NOW(), status='activated' where creditid='{$S}'");
			if($res && mysql_affected_rows()>0){ $res = mysql_query("update warehouse set status='activated' where creditid='{$S}'"); }
			if($res && mysql_affected_rows()>0){ $success = true; }
			if(!$success) break;
		}
		if($success){
			$res = mysql_query("commit");
			mysql_query("update pendingpintransactions set display='0' where id='{$id}'");
			if($res){ $toret = '{"opsstat":0,"opsstatinfo":"DONE\nAll products were successfully activated."}';}
		}else{ mysql_query("rollback");	}
		return $toret;
	}
}
?>