Your IP : 216.73.216.40


Current Path : /var/www/html/mmishra/erp/views/
Upload File :
Current File : /var/www/html/mmishra/erp/views/z.php

<?php
	include("erp_view.php");

	echo $str;

?>
/*
		//alert on long admission
		$rs = mysql_query("select reg_no,adm_datetime,datediff(now(),date(adm_datetime)) as days from admissions where isnull(dr_id)");
		while ($o = mysql_fetch_object($rs)) {
			if ($o->days > 2) {
				//$days = floor((strtotime($o->expiry) - strtotime($o->dated)) / (60*60*24));
				echo "[RegNo.: $o->reg_no admitted on $o->adm_datetime not yet discharged.] ";
			}
		}

		//registration

		$regdate = $_REQUEST["regdate"];
		if (!$regdate) $regdate = date("Y-m-d");

		$patgroup = $_REQUEST["patgroup"];
		if (!$patgroup) $patgroup = 'Student';

		$patid = $_POST["patid"];
		$dependent = $_POST["dependent"];
		$drid = $_POST["drid"];
		if ($patid == 'RollNo of Student' || $patid == 'EmpNo of Employee' || $patid == 'Name of Worker') {
			$patid = '';
			$dependent = '';
		}
		if ($dependent == 'Parent/Dependent Name') $dependent = '';

		if ($_POST["submit"] == 'REGISTER' && $patid) {
			if (mysql_num_rows(mysql_query("select * from $tbl where reg_no=$regno"))) {
				mysql_query("update $tbl set pat_group='$patgroup',reg_date='$regdate',pat_id='$patid',dependent='$dependent',dr_id='$drid',
				login_id='$user' where reg_no=$regno");
				//$email = get_email($patgroup, $patid);
				//echo automailer($email, "iCure@IIITA - OPD Registration",registration_detail($regno)); 
			} else {
				mysql_query("insert into $tbl(pat_group,pat_id,dependent,reg_date,reg_time,dr_id,login_id) 
				values('$patgroup','$patid','$dependent','$regdate',current_time(),'$drid','$user')");

				$regno = mysql_insert_id();
				$email = get_email($patgroup, $patid);
				echo automailer($email, "iCure@IIITA - OPD Registration",registration_detail($regno)); 
				//Patient ID: $patid ($patgroup - P/d. $dependent)<br>
				//Doctor: ".doctor_detail($drid));
			}
		}

		if ($_GET["del"] == 1) {
			mysql_query("delete from $tbl where reg_no=$regno");
		}

		$dated1 = date('Y-m-d', strtotime($regdate .' -1 day'));
		$dated2 = date('Y-m-d', strtotime($regdate .' +1 day'));

		echo "<h3 align='left'>OPD Registration</h3>
		<div align='right'><a href='?pg=$pg&regdate=$dated1' title='Previous'>&lt;&lt;</a> 
		<font size='+1' color='red'>&nbsp;$regdate&nbsp;</font>
		";

		if ($regdate == date("Y-m-d")) echo "&gt;&gt;";
		else echo "<a href='?pg=$pg&regdate=$dated2' title='Next'>&gt;&gt;</a>";

		echo "</div>
		Patient group <b><font size='+1'>[</font>"; 

		foreach ($patgps as $pgp) {
			$i++;
			echo "<input type='radio' name='patgroup' value='$pgp'";
			if (!$regno) echo " onchange=\"javascript: document.location.href='?pg=$pg&regdate=$regdate&patgroup='+this.value\"";
			echo ($patgroup == $pgp ? ' checked' : ''). '>';
			echo ($patgroup == $pgp ? "<font size='+1' color='red'>$pgp</font>" : "$pgp");
		}
		echo "<font size='+1'> ]</font></b>
		<br>
		(For registration of parents/dependents, please provide RollNo. of student or EmpNo. of employee in the first text box and patient name in the second text box) 
		<br><font color='red'>System permits only one registration per patient per doctor per day.</font> <br>

		<div id='ajax'></div>";

		$ro = '';
		if ($patgroup == 'Student') {
			$lbl1 = 'RollNo of Student';
			$lbl2 = "Parent Name";
		} else if ($patgroup == 'Employee') {
			$lbl1 = 'Name of Employee';
			$lbl2 = "Dependent Name";
		} else if ($patgroup == 'AgencyStaff') {
			$lbl1 = 'Name of Worker';
			$lbl2 = 'No Dependent';
		} else {
			$lbl1 = 'Name of Guest';
			$lbl2 = 'Official Purpose';
		}

		if (!$drid) $drid = 'SOD';

		if ($regdate) {
			echo "<table border='1' width='100%' cellpadding='5pt'>
			<tr><th width='5%'>Sr</th><th width='10%'>RegistrationNo</th><th width='10%'>Date Time</th><th width='50%'>Patient Detail 
			(<a href='javascript:void(0);' onclick=\"popup('staff/students.php','Student List',600,700);\">Student</a>, 
			<a href='javascript:void(0);' onclick=\"popup('staff/employees.php','Employees List',600,700);\">Employee</a>,
			<a href='javascript:void(0);' onclick=\"popup('staff/agencystaffs.php','AgencyStaff List',600,700);\">AgencyStaff</a>)</th>
			<th>Doctor</th><th width='5%'>Staff</th></tr>";


			if (!$regno && $regdate == date("Y-m-d")) {
				echo "<tr><td align='center'>+</td>
				<td align='center'>Auto generated</td>
				<td align='center'>".date("Y-m-d H:i:s")."</td>
				<td>";
				if ($patgroup == 'Employee') echo employee_list('');
				else if ($patgroup == 'AgencyStaff') echo agencystaff_list('');
				else echo "<input type='text' name='patid' value='$lbl1' size='35' onblur=\"if(value=='') value='$lbl1'\" onfocus=\"if(value=='$lbl1') value=''\">";
				echo "<br><input type='text' name='dependent' value='$lbl2' size='35' onblur=\"if(value=='') value='$lbl2'\" onfocus=\"if(value=='$lbl2') value=''\"></td>
				<td>".doctor_list($drid)."</td><td>$user</td></tr>
				<tr><th colspan='6'><input type='submit' name='submit' value='REGISTER'></th></tr>";     
			} elseif ($regdate == date('Y-m-d')) { 
				echo "<tr><td colspan='6'><a href='?pg=$pg&patgroup=$patgroup&regdate=$regdate&regno='>+</a></td></tr>";
			}

			$i = 0;
			$rs = mysql_query("select * from $tbl where reg_date='$regdate' order by reg_no desc");
			while ($o = mysql_fetch_object($rs)) {
				$i++;
				echo "<tr><td align='center'><a name='$i'></a>$i</td>
				<th><a href='?pg=$pg&patgroup=$o->pat_group&regdate=$regdate&regno=$o->reg_no#$i'>
				<font size='+1'>$o->reg_no</font></a></th>
				<td align='center'>$o->reg_date $o->reg_time</td><td>";
				if ($regno == $o->reg_no) {
					if ($o->pat_group == 'Employee') echo employee_list($o->pat_id);
					//else if ($o->pat_group == 'AgencyStaff') echo agencystaff_list($o->pat_id);
					else echo "<input type='text' name='patid' value='$o->pat_id' size='35'>";
					echo "<br><input type='text' name='dependent' value='$o->dependent' size='35'></td>
						<td>".doctor_list($o->dr_id)."<input type='hidden' name='regno' value='$regno'></td>
						<td>$o->login_id</td></tr>
					<tr><th colspan='6'><input type='submit' name='submit' value='REGISTER'><!--<a href='?pg=$pg&del=1&regno=$regno'>x</a>--></th></tr>";
				} else {
					echo patient_name($o->reg_no);
			   
					$sr = mysql_query("select pat_id,count(reg_no) as no from $tbl where pat_id='$o->pat_id' group by pat_id");
					$q = mysql_fetch_object($sr);
						if ($q->no > 1) {
						$no = $q->no;
								echo "<div align='center'>[ 
						<a href='javascript:void(0);' onclick=\"popup('staff/patients.php?patid=$q->pat_id','Get Multiple Registrations',600,600);\">VISITS $no</a>
						] </div>";
								//echo "<a href='javascript:void(0);' onclick=\"ajax('patients.php?patid=$q->pat_id');\">Total $no</a>";
							}

					echo "</td><td>".doctor_detail($o->dr_id)."</td><td>$o->login_id</td></td>";	
				}
				echo "</tr>";
				if ($o->pat_group == 'Employee') $eno++;
				else if ($o->pat_group == 'Student') $sno++;
				//else if ($o->pat_group == 'AgencyStaff') $ano++;
				else $ono++;
			}
			echo "</table><br>
			<b>SUMMARY<br> [ Employees: $eno, Students: $sno, Others: $ono ]</b>";
			//<b>[ Employees: $eno, Students: $sno, AgencyStaff: $ano, Others: $ono ]</b>";
		}
	}


	
	public function ihcAdmission($action, $patientID) {
		$tbl = 'admissions';
		$regno = $_REQUEST["regno"];
		$admid = $_REQUEST["admid"];

		if ($_POST["submit"] == 'SAVE') {
			
			$diagnosis = $_POST["diagnosis"];
			$admdatetime = $_POST["admdatetime"];
			
			if (mysql_num_rows(mysql_query("select * from $tbl where adm_id=$admid"))) {
				mysql_query("update $tbl set reg_no='$regno',diagnosis='$diagnosis',adm_datetime='$admdatetime',
				login_id='$user' where adm_id=$admid");
			} else {
				mysql_query("insert into $tbl(reg_no,diagnosis,adm_datetime,login_id) 
				values($regno,'$diagnosis',now(),'$user')");
			}

			//automailer($email, "iCure@IIITA", "Medicine receipt");
		}

		if ($_GET["del"] == 1) {
			mysql_query("delete from $tbl where adm_id=$admid");
			$admid = 0;
		}

		echo "Registration No. <input type='text' name='regno' value='<?php echo $regno; ?>' size='10'>
		<input type='submit' name='submit' value='FIND'>
		<br>
		";

		if ($regno) {
			if (is_registration($regno)) {
				echo registration_detail($regno);

				echo "<table border='1' width='60%'>
				<tr><th>Sr</th><th>Diagnosis</th><th>Admission DateTime</th><td align='center'>Action</td></tr>";

				if (!$admid) {
					echo "<tr><td>+</td>
					<td align='center'><input type='text' name='diagnosis' value='' size='40'></td>
					<td align='center'>".date("Y-m-d H:i:s")."</td>
					<td align='center'><input type='submit' name='submit' value='SAVE'></td></tr>";
				} else {
					echo "<tr><td colspan='4'><a href='?pg=$pg&regno=$regno&admid='>+</a></td></tr>";
				}

				$rs = mysql_query("select * from $tbl where reg_no=$regno order by adm_id");
				while ($o = mysql_fetch_object($rs)) {
					$i++;
					echo "<tr><td><a href='?pg=$pg&regno=$regno&admid=$o->adm_id'>$i</a></td>";
					
				if ($admid == $o->adm_id) {
					echo "<td><input type='hidden' name='admid' value='$o->adm_id'>
					<input type='text' name='diagnosis' value='$o->diagnosis' size='40'></td>
					<td align='center'><input type='text' name='admdatetime' value='$o->adm_datetime' size='20'></td>
					<td align='center'><input type='submit' name='submit' value='SAVE'> 
					<a href='?pg=$pg&regno=$regno&del=1&admid=$o->adm_id'>x</a></td>";
				} else {
					echo "<td>$o->diagnosis</td><td align='center'>$o->adm_datetime</td>";
				}
				echo "</tr>";
				}
				echo "</table>";
			} else
				echo "No registration";
		} else {
			echo "<b>Past Admissions</b>";
			$sql = "select reg_no as RegNo,diagnosis,adm_datetime as dated,login_id as staff from $tbl order by adm_datetime desc";
			echo list_tabledata($sql);
		}
		
	}
	
	public function ihcBatch($action, $batchNo) {
		$tbl = 'batchnos';
		$batchID = $_REQUEST["batchID"];
			
		$medid = $_POST["medid"];
		$batchNo = $_POST["batchNo"];
		$dateExpiry = $_POST["dateExpiry"];
		$unitrate = $_POST["unitrate"];
		$qtyinhand = $_POST["qtyinhand"];
		$xqtyinhand = $_POST["xqtyinhand"];
		$qtyused = $_POST["qtyused"];
		$xqtyused = $_POST["xqtyused"];
		$dated = date("Y-m-d");

		if ($_POST["submit"] == 'SAVE') {
			if (mysql_num_rows(mysql_query("select * from $tbl where batchID=$batchID"))) {
				//mysql_query("update $tbl set batchNo='$batchNo',dateExpiry='$dateExpiry',unit_rate=$unitrate,
				//qty_inhand=qty_inhand+$qtyinhand-$xqtyinhand,qty_used=qty_used+$qty_used-$xqtyused,login_id='$user' 
				//where batchID=$batchID");
				
				//update medicine qty_inhand
				//mysql_query("update medicines set unit_rate=$unitrate,qty_inhand=qty_inhand+$qtyinhand-$xqtyinhand,
				//qty_used=qty_used+$qtyused-$xqtyused,login_id='$user' 
				//where med_id=$medid");
			} else {
				//mysql_query("insert into $tbl(med_id,batchNo,dateExpiry,unit_rate,qty_inhand,qty_used,login_id) 
				//values($medid,'$batchNo','$dateExpiry',$unitrate,$qtyinhand,$qtyused,'$user')");
				
				//update medicine qty_inhand
				//mysql_query("update medicines set unit_rate=$unitrate,qty_inhand=qty_inhand+$qtyinhand-$xqtyinhand,
				//qty_used=qty_used+$qtyused-$xqtyused,login_id='$user' 
				//where med_id=$medid");
			}
		} else if ($_GET["del"] == 1) {
			//mysql_query("delete from $tbl where batchID=$batchID");
			//update medicine qty_inhand
			//mysql_query("update medicines set qty_inhand=qty_inhand-$xqtyinhand,qty_used=qty_used-$xqtyused,login_id='$user' 
			//where med_id=$medid");
		}


		echo "<h3 align='left'>Medicine Batch</h3>
		<table border='1' width='80%'>
		<tr><th>Sr</th><th>Medicine Name</th><th>Batch No.</th><th>Expiry Date</th><th>Unit Rate</th>
		<th>Qty Inhand</th><th>Qty Used</th><th>LoginID</th><th>Dated</th></tr>";

		if (!$batchID) {
			echo "<tr><th>+</th><td>".medicine_list(0,'+')."</td>
			<td align='center'><input type='text' name='batchNo' value='' size='20'></td>	
			<td align='center'><input type='text' name='dateExpiry' value='$dated' size='10'></td>	
			<td align='center'>Rs. <input type='text' name='unitrate' value='0.00' size='6'></td>
			<td align='center'><input type='text' name='qtyinhand' value='0' size='5'></td>
			<td align='center'><input type='text' name='qtyused' value='0' size='5'></td>
			<td>$user</td>
			<td align='center'><input type='submit' name='submit' value='SAVE'></td></tr>";     
		} else {
			echo "<tr><td colspan='9'><a href='?pg=$pg&batchID='>+</a></td></tr>";
		}

		$i = $pgno;
		$rs = mysql_query("select * from $tbl order by med_id,batchNo");
		while ($o = mysql_fetch_object($rs)) {
			$i++;
				echo "<tr><th><a name='$i' href='?pg=$pg&batchID=$o->batchID#$i'>$i</a></th>";
			if ($batchID == $o->batchID) {
				echo "<td><input type='hidden' name='batchID' value='$o->batchID'>".medicine_list($o->med_id,'+')."</td>
				<td align='center'><input type='text' name='batchNo' value='$o->batchNo' size='20'></td>
				<td align='center'><input type='text' name='dateExpiry' value='$o->dateExpiry' size='10'></td>
				<td align='center'><input type='text' name='unitrate' value='$o->unit_rate' size='6'></td>
				<td align='right'>$o->qty_inhand</td><td align='right'>$o->qty_used</td>
				<td>$o->login_id</td>
				<td align='center'><input type='submit' name='submit' value='SAVE'> 
				<a href='?pg=$pg&del=1&batchID=$batchID'>x</a></td>";     
			} else {
				echo "<td>".medicine_detail($o->med_id)."</td><td align='center'>$o->batchNo</td>
				<td align='center'>$o->dateExpiry</td><td align='right'>Rs. $o->unit_rate</td>
				<td align='right'>$o->qty_inhand</td><td align='right'>$o->qty_used</td>
				<td>$o->login_id</td><td>$o->date_updation</td>";	
			}
			echo "</tr>";
		}

		echo "</table>";
	}

	public function ihcBHTest($action, $regno) {
		$tbl = 'bhtests';
		$bhtid = $_REQUEST["bhtid"];
		$regno = $_REQUEST["regno"];
		$bp = $_POST["bp"];
		$puls = $_POST["puls"];
		$temp = $_POST["temp"];

		if ($_POST["submit"] == 'SAVE' && $regno) {				
				if (mysql_num_rows(mysql_query("select * from $tbl where bht_id=$bhtid"))) {
						mysql_query("update $tbl set reg_no=$regno,bp='$bp',puls=$puls,temp=$temp,bht_datetime=now(),
						login_id='$user' where bht_id=$bhtid");
				} else {
						mysql_query("insert into $tbl(reg_no,bp,puls,temp,bht_datetime,login_id) 
						values($regno,'$bp',$puls,$temp,now(),'$user')");
				}
		}                       
								
		if ($_GET["del"] == 1) {
		//      mysql_query("delete from $tbl where reg_no=$regno");
		}
								

		echo "<h3 align='left'>Bed Head Test</h3>
		Registration No. <input type='text' name='regno' value='<?php echo $regno; ?>' size='10'>
		<input type='submit' name='submit' value='FIND'>
		<br>";

		if ($regno && is_registration($regno)) {
				echo registration_detail($regno);

				if (is_admission($regno)) {
					echo admission_detail($regno);
				
				echo "<table border='1' width='60%'>
					<tr><th>Sr</th><th>BP</th><th>Puls</th><th>Temp</th><th>Date Time</th><td align='center'>Action</td></tr>";


					if (!$bhtid) {
							echo "<tr><td>+</td>
							<td align='center'><input type='text' name='bp' value='0/0' size='10'></td>
							<td align='center'><input type='text' name='puls' value='0' size='5'></td>
							<td align='center'><input type='text' name='temp' value='0' size='5'></td>
							<td align='center'>".date("Y-m-d H:i:s")."</td>
							<td align='center'><input type='submit' name='submit' value='SAVE'></td></tr>";
					} else {
							echo "<tr><td colspan='6'><a href='?pg=$pg&regno=$regno&bhtid='>+</a></td></tr>";
					}

					$rs = mysql_query("select * from $tbl where reg_no=$regno order by bht_id");
					while ($o = mysql_fetch_object($rs)) {
							$i++;
							if ($bhtid == $o->bht_id) {
									echo "<tr><td>$i <input type='hidden' name='bhtid' value='$o->bht_id'></td>
									<td align='center'><input type='text' name='bp' value='$o->bp' size='10'></td>
									<td align='center'><input type='text' name='puls' value='$o->puls' size='5'></td>
									<td align='center'><input type='text' name='temp' value='$o->temp' size='5'></td>
									<td align='center'>$o->bht_datetime</td>
									<td nowrap align='center'><input type='submit' name='submit' value='SAVE'> 
						<a href='?pg=$pg&regno=$regno&bhtid=$o->bht_id'>x</a></td></tr>";
							} else {
									echo "<tr><td>$i</td>
									<td><a href='?pg=$pg&regno=$regno&bhtid=$o->bht_id'>$o->bp</a></td>
									<td align='center'>$o->puls</td>
									<td align='center'>$o->temp</td>
									<td align='center'>$o->bht_datetime</td>
									</tr>";
							}
					}
					echo "</table>";
			} else
				echo "<font color='red'>Above patient has not been admitted so far.</font>";
		}
	}
	
	public function ihcBill($action, $patientID) {
		$tbl = 'bills';
		$billno = $_REQUEST["billno"];
		$regno = $_REQUEST["regno"];

		if ($_POST["submit"] == 'SAVE') {
			$billamount = $_POST["billamount"];
			$billdatetime = $_POST["billdatetime"];

			if (mysql_num_rows(mysql_query("select * from $tbl where bill_no=$billno"))) {
				mysql_query("update $tbl set reg_no=$regno,bill_amount=$billamount,login_id='$user' where bill_no=$billno");
			} else {
				mysql_query("insert into $tbl(bill_no,reg_no,bill_amount,bill_date,login_id) 
				values($billno,$regno,$billamount,'$billdate','$user')");
			}
		}
		if ($_GET["del"] == 1) {
		//	mysql_query("delete from $tbl where bill_no=$billno");
		}

		echo "<h3 align='left'>Bill Receipt</h3>
		<table border='1' width='80%'>
		<tr><th>Sr</th><th>RegNo</th><th>BillNo</th><th>BillAmount</th><th>BillDate</th>
		<th>ShopName</th><td align='center'>Action</td></tr>";

		if (!$billno) {
			echo "<tr><td>+</td>
			<td><input type='text' name='regno' value='' size='20'></td>
			<td><input type='text' name='billno' value='' size='20'></td>
			<td><input type='text' name='billamount' value='0' size='10'></td>
			<td><input type='text' name='billdate' value='".date("Y-m-d")."' size='15'></td>
			<td><input type='text' name='shopname' value='' size='25'></td>
			<td align='center'><input type='submit' name='submit' value='SAVE'></td></tr>";     
		} else {
			echo "<tr><td colspan='7'><a href='?pg=$pg&regno=$regno&billno='>+</a></td></tr>";
		}

		$rs = mysql_query("select * from $tbl order by date_creation desc");
		while ($o = mysql_fetch_object($rs)) {
			$i++;
				echo "<tr><td>$i</td>";
			if ($billno == $o->bill_no) {
					echo "<td><input type='text' name='regno' value='$o->reg_no' size='20'></td>
					<td><input type='text' name='billno' value='$o->bill_no' size='20'></td>
					<td><input type='text' name='billamount' value='$o->bill_amount' size='10'></td>
					<td><input type='text' name='billdate' value='$o->bill_date' size='15'></td>
					<td><input type='text' name='shopname' value='$o->shop_name' size='25'></td>
				<td align='center'><input type='submit' name='submit' value='SAVE'></td>";     
			} else {
				echo "<td><a href='?pg=$pg&regno=$o->reg_no&billno=$o->bill_no'>$o->reg_no</td>
				<td><a href='?pg=$pg&regno=$o->reg_no&billno=$o->bill_no'>$o->bill_no</td>
				<td>$o->bill_amount</td>
				<td>$o->bill_date</td>	
				<td>$o->shop_name</td>";	
			}
			echo "</tr>";
			if (!$regno) $regno = $o->reg_no;
		}
		echo "</table>";
			
		echo registration_detail($regno);
	}

	public function ihcDailyMedicine($action, $dated) {
		$tbl = 'medications';
		$dated = $_REQUEST["dated"];

		if (!$dated) $dated = date("Y-m-d");

		$dated1 = date('Y-m-d', strtotime($dated .' -1 day'));
		$dated2 = date('Y-m-d', strtotime($dated .' +1 day'));

		echo "<h3 align='left'>Dated Medications</h3>
		<a href='?pg=$pg&dated=$dated1'>$dated1</a> 
		<font size='+1' color='red'>[ $dated ]</font>";

		if ($dated != date("Y-m-d")) echo "<a href='?pg=$pg&dated=$dated2'>$dated2</a>";

		$sql = "select med_name as medicine,reg_no,dis_datetime as dated,qty,a.login_id as staff 
		from $tbl as a, medicines as b 
		where a.med_id=b.med_id and dis_datetime like '$dated%' order by med_name";

		//echo list_tabledata($sql);

		$rs = mysql_query($sql);
						
		if (mysql_num_rows($rs)) {
				$colHeads = mysql_num_fields($rs);
				
				$str = "<table border='1' width='90%'><tr><th>Sr</th>";
				for ($i=0; $i < $colHeads; $i++) { // Header
						$str .= "<th>".ucwords(str_replace("_"," ",mysql_field_name($rs, $i)))."</th>";
				}
				$str .= "</tr>";
			$j = $pgno;                        
				while ($row = mysql_fetch_row($rs)) { //data
						$j++;
						$str .= "<tr><td>$j</td><td>".implode($row,'</td><td>')."</td></tr>";
				}
				$str .= "</table>";
		} else {
				$str = "---";
		}
		echo $str;
	}
	
	public function ihcDailyReceipt($action, $dated) {
		$tbl = 'receipts';
		$dated = $_REQUEST["dated"];

		if (!$dated) $dated = date("Y-m-d");

		$dated1 = date('Y-m-d', strtotime($dated .' -1 day'));
		$dated2 = date('Y-m-d', strtotime($dated .' +1 day'));

		echo "<a href='?pg=$pg&dated=$dated1'>&lt;&lt;</a> 
		<font size='+1' color='red'>[ $dated ]</font>";

		if ($dated != date("Y-m-d")) echo " <a href='?pg=$pg&dated=$dated2'>&gt;&gt;</a>";
		echo "<br>";
		$sql = "select med_name as medicine,b.batchNo,b.dateExpiry as expiry,b.qty_receipt as qty,rec_date as dated,a.login_id as staff from medicines as a,$tbl as b
		where a.med_id=b.med_id and rec_date='$dated' order by med_name";

		$rs = mysql_query($sql);
		if (mysql_num_rows($rs)) {
				$colHeads = mysql_num_fields($rs);
				
				$str = "<table border='1' width='90%'><tr><th>Sr</th>";
				for ($i=0; $i < $colHeads; $i++) { // Header
						$str .= "<th>".ucwords(str_replace("_"," ",mysql_field_name($rs, $i)))."</th>";
				}
				$str .= "</tr>";
			$j = $pgno;                        
				while ($row = mysql_fetch_row($rs)) { //data
						$j++;
						$str .= "<tr><td>$j</td><td>".implode($row,'</td><td>')."</td></tr>";
				}
				$str .= "</table>";
		} else {
				$str = "<b>Nothing.</b>";
		}
		echo $str;
	}
	
	public function ihcDailyRegistrations($action, $dated) {
		$dated = $_REQUEST["dated"];

		if (!$dated) $dated = date("Y-m-d");

		$dated1 = date('Y-m-d', strtotime($dated .' -1 day'));
		$dated2 = date('Y-m-d', strtotime($dated .' +1 day'));

		echo "<h3 align='left'>Dated Registrations</h3>
		<center>
		<table width='90%' border='1'>
		<tr valign='top'>
		<a href='?pg=$pg&dated=$dated1'>&lt;&lt;</a> 
		<font size='+1' color='red'>[ $dated ]</font>";

		if ($dated != date("Y-m-d")) echo " <a href='?pg=$pg&dated=$dated2'>&gt;&gt;</a>";


		$heads = array('Registration For','Registration By','Pathology Tests By','Patients','Batch','Course','Gender','Hostel','BG');

		$sqls = array("select concat(dr_name,', ',specialization) as doctor,count(reg_no) as patients 
			from registrations as a, doctors as b 
			where a.dr_id=b.dr_id and reg_date like '$dated%' group by a.dr_id",
			"select concat(ph_name,', ',specialization) as staff,count(reg_no) as patients 
			from registrations as a, staffs as b 
			where a.login_id=b.ph_id and reg_date like '$dated%' group by a.login_id",
				"select concat(ph_name,', ',specialization) as staff,count(distinct reg_no) as patients 
				from phresults as a, staffs as b    
				where a.login_id=b.ph_id and test_date like '$dated%' group by a.login_id",
			"select pat_group as Category,count(reg_no) as patients 
			from registrations 
			where reg_date like '$dated%' group by pat_group",
				"select year as batch,count(reg_no) as patients
				from students as a,registrations as b
				where a.roll_no=b.pat_id and reg_date like '$dated%' group by year",
			"select course_name,count(reg_no) as patients 
			from students as a,registrations as b
			where a.roll_no=b.pat_id and reg_date like '$dated%' group by course_name",
			"select gender,count(reg_no) as patients     
				from students as a,registrations as b
				where a.roll_no=b.pat_id and reg_date like '$dated%' group by gender",
			"select hostel_no,count(reg_no) as patients     
				from students as a,registrations as b
				where a.roll_no=b.pat_id and reg_date like '$dated%' group by hostel_no",
			"select bg as blood_group,count(reg_no) as patients     
				from students as a,registrations as b
				where a.roll_no=b.pat_id and reg_date like '$dated%' group by bg");

		$cols = 3;
		$colw = 100/$cols;
		$no = 0;
		foreach ($sqls as $sql) {
				echo "<td width='$colw%' align='center'><h3>".$heads[$no]."</h3>";
				$no++;
			$tno = 0;
				$rs = mysql_query($sql);
				if (mysql_num_rows($rs)) {
						$colHeads = mysql_num_fields($rs);

						echo "<table border='0' width='90%' align='center'>
				<tr>";
						for ($i=0; $i < $colHeads; $i++) { // Header
								echo "<th>".ucwords(str_replace("_"," ",mysql_field_name($rs, $i)))."</th>";
						}
						echo "</tr>";
						
				$j = 0;
						while ($row = mysql_fetch_row($rs)) { //data
								$j++;
								echo "<tr><td>".implode($row,'</td><td>')."</td></tr>\n";
							$tno = $tno + $row[1];
						}
						echo "<tr><th>Total</th><th>$tno</th></tr></table><br>";
				} else {
					echo "---";      	
			}
			echo "</td>";
				$k++;
				if ($k % $cols == 0) echo "</tr><tr valign='top'>";
		}
		echo "</tr></table>";
	}

	public function ihcDatedExpiry($action, $dated) {
		$tbl = 'expirys';
		$dated = $_REQUEST["dated"];

		if (!$dated) $dated = date("Y-m-d");

		$dated1 = date('Y-m-d', strtotime($dated .' -1 day'));
		$dated2 = date('Y-m-d', strtotime($dated .' +1 day'));

		echo "<h3 align='left'>Dated Expiry</h3>
		<a href='?pg=$pg&dated=$dated1'>&lt;&lt;</a> 
		<font size='+1' color='red'>[ $dated ]</font>";

		if ($dated != date("Y-m-d")) echo " <a href='?pg=$pg&dated=$dated2'>&gt;&gt;</a>";
		echo "<br>";
		$sql = "select med_name as medicine,b.qty_expired as qty,date_expiry as dated,a.login_id as staff from medicines as a,$tbl as b
		where a.med_id=b.med_id and date_expiry='$dated' order by med_name";

		$rs = mysql_query($sql);
		if (mysql_num_rows($rs)) {
				$colHeads = mysql_num_fields($rs);
				
				$str = "<table border='1' width='90%'><tr><th>Sr</th>";
				for ($i=0; $i < $colHeads; $i++) { // Header
						$str .= "<th>".ucwords(str_replace("_"," ",mysql_field_name($rs, $i)))."</th>";
				}
				$str .= "</tr>";
			$j = $pgno;                        
				while ($row = mysql_fetch_row($rs)) { //data
						$j++;
						$str .= "<tr><td>$j</td><td>".implode($row,'</td><td>')."</td></tr>";
				}
				$str .= "</table>";
		} else {
				$str = "<b>Nothing.</b>";
		}
		echo $str;
	}

	public function ihcDischarge($action, $regNo) {
		$tbl = 'admissions';
		$regno = $_REQUEST["regno"];
		$admid = $_REQUEST["admid"];

		if ($_POST["submit"] == 'SAVE') {
			
			$referral = $_POST["hosid"];
			$drid = $_POST["drid"];
			if (mysql_num_rows(mysql_query("select * from $tbl where adm_id=$admid"))) {
				mysql_query("update $tbl set referral='$referral',dr_id='$drid',dis_datetime=now(),login_id='$user' where reg_no=$regno");
			}
			//automailer($email, "iCure@IIITA", "Medicine receipt");
		}

		echo "<h3 align='left'>IPD Discharge</h3>
		Registration No. <input type='text' name='regno' value='<?php echo $regno; ?>' size='10'>
		<input type='submit' name='submit' value='FIND'>
		<br>";

		if ($regno && is_registration($regno)) {
				echo registration_detail($regno);

				if (is_admission($regno)) {
					echo admission_detail($regno);
			
				echo "<table border='1' width='90%'>
					<tr><th>Referral</th><th>Doctor</th><th>Discharge Date Time</th><th>Staff</th><td align='center'>Action</td></tr>";

					$rs = mysql_query("select * from $tbl where reg_no=$regno order by adm_id");
					while ($o = mysql_fetch_object($rs)) {
							echo "<tr>";
					if ($o->dis_datetime == "0000-00-00 00:00:00") {
								echo "<td><input type='hidden' name='admid' value='$o->adm_id'>
						".hospital_list($o->referral)."</td><td>
						".doctor_list($o->dr_id)."</td>
						<td align='center'>".date("Y-m-d H:i:s")."</td>
						<td align='center'>$user</td>
								<td align='center'><input type='submit' name='submit' value='SAVE'></td>";
					} else {
						echo "<td>".($o->referral ? $o->referral : '--')."</td>
						<td align='center'>".doctor_detail($o->dr_id)."</td>
						<td align='center'>$o->dis_datetime</td>
						<td align='center'>$o->login_id</td>";
					}
					echo "</tr>";
					}
					echo "</table>";
			} else
				echo "<font color='red'>Above patient has not been admitted so far.</font>";
		}
	}

	public function ihcDressing($action, $regNo) {
		$tbl = 'dressings';

		$regno = $_REQUEST["regno"];
		$disid = $_REQUEST["disid"];

		$medid = $_POST["medid"];
		$qty = ($_POST["qty"] ? $_POST["qty"] : 0);
		$xqty = ($_POST["xqty"] ? $_POST["xqty"] : 0);

		if ($_POST["submit"] == 'SAVE') {
			
			if (mysql_num_rows(mysql_query("select * from $tbl where dis_id=$disid"))) {
				mysql_query("update $tbl set reg_no=$regno,med_id=$medid,qty=$qty,dis_datetime=now(),
				date_updation=now(),login_id='$user' where dis_id=$disid");
				//update medicine inventory
				mysql_query("update medicines set qty_inhand=qty_inhand-$qty+$xqty,qty_used=qty_used+$qty-$xqty
				where med_id=$medid");
			} else {
				mysql_query("insert into $tbl(reg_no,med_id,qty,dis_datetime,date_creation,date_updation,login_id) 
				values($regno,$medid,$qty,now(),now(),now(),'$user')");
				//update medicine inventory
				mysql_query("update medicines set qty_inhand=qty_inhand-$qty,qty_used=qty_used+$qty
				where med_id=$medid");
			}

		}

		if ($_GET["del"] == 1) {
		//	mysql_query("delete from $tbl where dis_id=$disid");
			//update medicine inventory
		//	mysql_query("update medicines set qty_inhand=qty_inhand+$xqty,qty_used=qty_used-$xqty
		//	where med_id=$medid");

		}
		echo "<h3 align='left'>Dressing</h3>
		Registration No. <input type='text' name='regno' value='<?php echo $regno; ?>' size='10'>
		<input type='submit' name='submit' value='FIND'>
		<br>";

		if ($regno && is_registration($regno)) {
			echo registration_detail($regno);
			
			//if (is_prescription($regno)) {
			//	echo prescription_detail($regno);
				
				echo "<font color='red'><b>Stocks of red marked materials are below critical level.</b></font> 
				<table border='1' width='60%'>
				<tr><th>Sr</th><th>Material Name</th><th>Qty</th><th>Date Time</th><td align='center'>Action</td></tr>";

				if (!$disid) {
					echo "<tr><td>+</td>
					<td>".material_list('','-')."</td>
					<td align='center'><input type='text' name='qty' value='0' size='3'></td>
					<td align='center'><input type='text' name='disdatetime' value='".date("Y-m-d H:i:s")."' size='20'></td>
					<td align='center'><input type='submit' name='submit' value='SAVE'></td></tr>";     
				} else {
					echo "<tr><td colspan='5'><a href='?pg=$pg&regno=$regno&disid='>+</a></td></tr>";
				}

				$rs = mysql_query("select * from $tbl where reg_no=$regno order by med_id");
				while ($o = mysql_fetch_object($rs)) {
					$i++;
					echo "<tr><td>$i</td>";
					if ($disid == $o->dis_id) {
							echo "<td><input type='hidden' name='disid' value='$o->dis_id'>
						".material_list($o->med_id,'-')."<input type='hidden' name='xqty' value='$o->qty'></td>
							<td align='center'><input type='text' name='qty' value='$o->qty' size='3'></td>
							<td align='center'>$o->dis_datetime</td>
							<td nowrap align='center'><input type='submit' name='submit' value='SAVE'> 
						<a href='?pg=$pg&regno=$regno&disid=$o->dis_id'>x</a></td>";     
					} else {
						echo "<td><a href='?pg=$pg&regno=$regno&disid=$o->dis_id'>".material_detail($o->med_id)."</a></td>
						<td align='center'>$o->qty</td>
						<td align='center'>$o->dis_datetime</td>";	
					}
					echo "</tr>";
				}
				echo "</table>";
			//} else
			//	echo "No prescription";
		}
	}

	public function ihcDSchedule($action, $month) {
		$tbl = 'dschedules';
		$schid = $_REQUEST["schid"];
		$monthyear = $_REQUEST["monthyear"];
		if (!$monthyear) $monthyear = date("Y-m");

		if ($_POST["submit"] == 'SAVE') {
			
			$drid = $_POST["drid"];
			$dayweek = $_POST["dayweek"];
			$timing = $_POST["timing"];
			if (!$timing) {
				$ftime = $_POST["ftime"];
				$ttime = $_POST["ttime"];

				//if ($ftime < $ttime) 
				$timing = "$ftime - $ttime";
				//else echo "Wrong timing";
			}

			if (mysql_num_rows(mysql_query("select * from $tbl where sch_id=$schid"))) {
				mysql_query("update $tbl set dr_id='$drid',period='$monthyear',day_week='$dayweek',timing='$timing',
				login_id='$user' where sch_id=$schid");
			} else {
				mysql_query("insert into $tbl(dr_id,period,day_week,timing,login_id) 
				values('$drid','$monthyear','$dayweek','$timing','$user')");
			}

		} else if ($_POST["submit"] == 'DELETE') {
			mysql_query("update $tbl set dr_id='' where sch_id=$schid");

		}

		if ($_GET["cont"] == 1) {
			$pmonthyear = previous_month();
			$rs = mysql_query("select * from $tbl where period='$pmonthyear' order by sch_id");
			while ($o = mysql_fetch_object($rs)) {
				$i++;
				mysql_query("insert into $tbl(dr_id,period,day_week,timing,date_creation,date_updation,login_id) 
				values('$o->dr_id','$monthyear','$o->day_week','$o->timing',now(),now(),'$user')");
			}
		}

		echo "<h3 align='left'>Doctor Schedule</h3>
		Select month <select name='monthyear'>";
		
		$cal = explode("-", $monthyear);
		$m = $cal[1];
		$y = $cal[0];

		$rs = mysql_query("select distinct concat(year(reg_date),'-',month(reg_date)) as monthyear from registrations order by reg_date desc");
		while ($o = mysql_fetch_object($rs)) {
				if (strlen($o->monthyear) == 6) $myear = str_replace("-","-0",$o->monthyear);
				else $myear = $o->monthyear;
				echo "<option value='$myear'";
				if ($myear == $monthyear) echo " selected";
				echo ">$myear</option>";
		}

		echo "</select> <input type='submit' name='submit' value='OK'>

		<table border='1' width='80%'>
		<tr><th nowrap>Time Slots \ Day of Week</th>";

		$dayweeks = array('Monday','Tuesday','Wednesday','Thursday','Friday','Saturday','Sunday'); 

		foreach ($dayweeks as $dw) {
			echo "<th>$dw</th>";
		}

		echo "</tr>";

		$i = 0; $j = 0; $k = 0;

		$rs = mysql_query("select distinct timing from $tbl where period='$monthyear' order by sch_id");
		while ($o = mysql_fetch_object($rs)) {
			$i++;
			$timing = $o->timing;
			
			echo "<tr><th>$timing</th>";
				
			$j = 0;
			$sr = mysql_query("select * from $tbl where period='$monthyear' and timing='$timing' order by sch_id");
			while ($q = mysql_fetch_object($sr)) {
				$j++;
				echo "<td align='center'>";
				if ($schid == $q->sch_id) {
					echo doctor_list($q->dr_id) . "<input type='hidden' name='dayweek' value='$q->day_week'>
					<input type='hidden' name='timing' value='$q->timing'><input type='hidden' name='schid' value='$q->sch_id'>";
				} else if ($monthyear == $q->period) {
					echo "<a href='?pg=$pg&edit=1&schid=$q->sch_id'>".($q->dr_id ? $q->dr_id : 'x') ."</a>";
				} else {
					echo ($q->dr_id ? $q->dr_id : 'x');
				}
				echo "</td>";
				$did = $q->dr_id;
			}
			if ($j < 7 || ($j < 7 && $did == '')) {
				echo "<td>" . doctor_list($drid) . "<input type='hidden' name='dayweek' value='".$dayweeks[$j] . "'>
				<input type='hidden' name='timing' value='$timing'><input type='hidden' name='schid' value='$q->sch_id'></td>";
			} else $j = 0;

			echo "</tr>";
		}

		$edit = $_GET["edit"];
		$timings = explode(" - ", $timing);

		echo "<tr>";
		if ((!$i || !$j) && ($edit == 0)) {
			   echo "<th>";
			if ($timings[1]) {
				echo $timings[1] . "<input type='hidden' name='ftime' value='" . $timings[1] . "'>";
			} else {
				echo "<select name='ftime'>";
						
					for ($j = 0; $j < 24; $j++) {
							echo "<option value='$j'>$j</option>";
					}
						
					echo "</select>";
			}
			echo " - <select name='ttime'>";
						
				for ($j = 1; $j < 24; $j++) {
						echo "<option value='$j'>$j</option>";
				}
						
				echo "</select></th>
			<td>" . doctor_list($drid) . "<input type='hidden' name='dayweek' value='" . $dayweeks[0] . "'></td>";
		} else {
				echo "<th><a href='?pg=$pg&schid='>Next</a></th>";
		}
		echo "</tr>";

		if (!mysql_num_rows($rs)) {
			echo "<tr><td colspan='8'><a href='?pg=$pg&cont=1'>Continue with previous schedule</a></td></tr>";
		}

		echo "<tr><th colspan='8'>
		<input type='submit' name='submit' value='SAVE'> <input type='submit' name='submit' value='DELETE'>
		</th></tr>
		</table>";
	}

	public function ihcMaterials($action, $month) {
		$tbl = 'materials';

		$sql = "select med_name as material,unit_rate,qty_receipt,qty_inhand,qty_critical,qty_used,date_updation as dated,login_id as staff from $tbl order by qty_inhand,med_name";

		echo "<h3 align='left'>Materials</h3>" .list_tabledata($sql);
	}
	
	public function ihcMedication($action, $regNo) {
		$tbl = 'medications';

		$regno = $_REQUEST["regno"];
		$disids = $_REQUEST["disid"];

		$medid = $_POST["medid"];
		$qty = ($_POST["qty"] ? $_POST["qty"] : 0);
		$xqty = ($_POST["xqty"] ? $_POST["xqty"] : 0);
		$sqty = 0;
		$j = 0;

		if ($_POST["submit"] == 'SAVE') {
			foreach ($disids as $disid) {
				$sqty = 0;
				if ($qty[$j] > 50) {
					automailer('mmishra@iiita.ac.in', "Medication over 50", $med_id[$j] .' to '. $regno);
					$qty[$j] = 50;
				}
				//check dis qty, should not be more than the stock qty
				$rs = mysql_query("select * from medicines where med_id=$medid[$j]");
				if (mysql_num_rows($rs)) {
					$o = mysql_fetch_object($rs);
					$sqty = $o->qty_inhand;
				}
				//accedental over quantity to be reduced to available qty - 1 
				if ($qty[$j] > $sqty) $qty[$j] = $sqty - 1;
				if ($qty[$j]) {
					//maitain medication record	
					if (mysql_num_rows(mysql_query("select * from $tbl where dis_id=$disid"))) {
						mysql_query("update $tbl set reg_no=$regno,med_id=$medid[$j],qty=$qty[$j],dis_datetime=now(),
						login_id='$user' where dis_id=$disid");
						//update medicine inventory
						mysql_query("update medicines set qty_inhand=qty_inhand-$qty[$j]+$xqty[$j],qty_used=qty_used+$qty[$j]-$xqty[$j]
						where med_id=$medid[$j]");
					} else if($medid[$j]) {
						mysql_query("insert into $tbl(reg_no,med_id,qty,dis_datetime,login_id) 
						values($regno,$medid[$j],$qty[$j],now(),'$user')");
						//update medicine inventory
						mysql_query("update medicines set qty_inhand=qty_inhand-$qty[$j],qty_used=qty_used+$qty[$j]
						where med_id=$medid[$j]");
					}
				}
				$j++;
			}
			$rs = mysql_query("select * from registrations where reg_no=$regno");
			if (mysql_num_rows($rs)) {
				$o = mysql_fetch_object($rs);
				$patgroup = $o->pat_group;
				$patid = $o->pat_id;
				$email = get_email($patgroup, $patid);
				//$email = 'mmishra@iiita.ac.in';
			}
			$str = medication_detail($regno);
			if ($email) echo automailer($email, "iCure@IIITA - Medication", $str);
		} else if ($_POST["submit"] == 'DELETE') {
			foreach ($disids as $disid) {
				mysql_query("delete from $tbl where dis_id=$disid");
				//update medicine inventory
				mysql_query("update medicines set qty_inhand=qty_inhand+$xqty[$j],qty_used=qty_used-$xqty[$j]
				where med_id=$medid[$j]");
				$j++;
			}
		}

		echo "<h3 align='left'>Medication</h3>
		Registration No. <input type='text' name='regno' value='<?php echo $regno; ?>' size='10'>
		<input type='submit' name='submit' value='OK'>
		<br>";

		if ($regno) {
			if (is_registration($regno)) {
				echo registration_detail($regno);
				$rs = mysql_query("select * from registrations where reg_no=$regno");
				if (mysql_num_rows($rs)) {
					$o = mysql_fetch_object($rs);
					$regdate = $o->reg_date;
				}
				
				//issue medicine for today and yesterday
				$yday = date('Y-m-d', strtotime(date("Y-m-d") .' -1 day'));

					//if (is_prescription($regno)) {
				//	echo prescription_detail($regno);
				
					echo "<font color='red'>
					<b>Stocks of red marked medicines are under critical level. Quantity shown as (inhand/critical).</b>
					<br>
					Issued quantity should not exceed stock quantity.</font> 
					<table border='1' width='70%'>
					<tr><th>Sr</th><th>Medicine Name</th><th>Qty</th><th>Date Time</th><th>Staff</th></tr>";

					//$ddt = new datetime(date("Y-m-d"));
					//$dd = $ddt->format('Y-m-d');
					
					$rs = mysql_query("select * from $tbl where reg_no=$regno order by med_id");
					while ($o = mysql_fetch_object($rs)) {
						$i++;
						//$ddt1 = $o->dis_datetime;
						//$ddt = new datetime($ddt1);
						//$dd = $ddt->format('Y-m-d');
						$lid = $o->login_id;
				
						echo "<tr><td>$i</td>";
							
						if ($regdate >= $yday) {
							echo "<td><input type='hidden' name='disid[]' value='$o->dis_id'>
							".medicines_list($o->med_id,'-')."<input type='hidden' name='xqty[]' value='$o->qty'></td>
							<td align='center'><input type='text' name='qty[]' value='$o->qty' size='3' maxlength='2'></td>";
						} else {
							echo "<td>".medicine_detail($o->med_id)."</td><td align='center'>$o->qty</td>";
						}
						echo "<td align='center'>$o->dis_datetime</td><td>".staff_detail($o->login_id)."</td></tr>";
						$ddt1 = $o->dis_datetime;
					}
					if (is_admission($regno)) $mno = 20; else $mno = 8;
					
					if ($regdate >= $yday) {//date("Y-m-d")) {
						while ($i < $mno) {
							$i++;
							echo "<tr><td>$i</td>
							<td><input type='hidden' name='disid[]' value='0'>
							".medicines_list('', '-')."<input type='hidden' name='xqty[]' value='0'></td>
							<td align='center'><input type='text' name='qty[]' value='' size='3' maxlength='2'></td>
							<td align='center'>".date("Y-m-d H:i:s")."</td>
							<td>$user</td></tr>";
						}
						
						while ($i >= $mno && $i < $mno + 7) {
							$i++;
							echo "<tr><td>$i</td>
							<td><input type='hidden' name='disid[]' value='0'>
							".medicines_list('','-')."<input type='hidden' name='xqty[]' value='0'></td>
							<td align='center'><input type='text' name='qty[]' value='' size='3' maxlength='2'></td>
							<td align='center'>".date("Y-m-d H:i:s")."</td>
							<td>$user</td></tr>";
						}
						
						echo "<tr><th colspan='3'><input type='submit' name='submit' value='SAVE'></th>
						<th colspan='2'><input type='submit' name='submit' value='DELETE'></th></tr>";
					}
					echo "</table>";
				//} else
				//	echo "No prescription";
			} else
				echo "No registration";
		}
	}
	
	public function ihcMedicine($action, $medID) {
		$tbl = 'medicines';
		$medid = $_REQUEST["medid"];
		$dated = date("Y-m-d");

		if ($_POST["submit"] == 'SAVE') {
			$medname = $_POST["medname"];
			$dateExpiry = $_POST["dateExpiry"];	
			$unitrate = $_POST["unitrate"];
			$openingstock = $_POST["openingstock"];
			$qtyreceipt = $_POST["qtyreceipt"];
			$qtyused = $_POST["qtyused"];
			$qtyinhand = $_POST["qtyinhand"];
			$qtycritical = $_POST["qtycritical"];

			if (mysql_num_rows(mysql_query("select * from $tbl where med_id=$medid"))) {
				mysql_query("update $tbl set med_name='$medname',dateExpiry='$dateExpiry',unit_rate=$unitrate,
				qty_critical=$qtycritical,login_id='$user' where med_id=$medid");
			} else if ($medname) {
				// for new medicines $qtyinhand = $qtyreceipt
				mysql_query("insert into $tbl(med_name,dateExpiry,unit_rate,opening_stock,qty_receipt,qty_used,qty_inhand,qty_critical,login_id) 
				values('$medname','$dateExpiry',$unitrate,$openingstock,$qtyreceipt,$qtyused,$qtyreceipt,$qtycritical,'$user')");
			}
		} else if ($_GET["del"] == 1) {
			mysql_query("delete from $tbl where med_id=$medid");
		}

		echo "<h3 align='left'>Medicine Stock</h3>
		<font color='red'><b>Pink lines indicate out of stock medicines<br>
		For new medicines, quantity in hand equals receipt quantity at the time of entry.</b></font> 
		<table border='1' width='90%' cellpadding='3pt'>
		<tr><th>Sr</th><th>Medicine Name</th><th>Expiry Date</th><th>Unit Rate</th><th>Opening Stock</th>
		<th>Received Qty</th><th>Used Qty</th><th>Inhand Qty</th><th>Critical Level</th><th>LoginID</th><th>Dated</th></tr>
		";
		
		if (!$medid) {
			echo "<tr><th>+</th>
			<td><input type='text' name='medname' value='' size='30'></td>
			<td align='center'><input type='text' name='dateExpiry' value='$dated' size='10'></td>
			<td nowrap align='center'>Rs. <input type='text' name='unitrate' value='0.00' size='5'></td>
			<td align='center'><input type='text' name='openingstock' value='0' size='5'></td>
			<td align='center'><input type='text' name='qtyreceipt' value='0' size='5'></td>
			<td align='center'><input type='text' name='qtyused' value='0' size='5'></td>
			<td align='center'><input type='text' name='qtyinhand' value='0' size='5'></td>
			<td align='center'><input type='text' name='qtycritical' value='0' size='5'></td>
			<td>$user</td>
			<td align='center'><input type='submit' name='submit' value='SAVE'></td></tr>";     
		} else {
			echo "<tr><td colspan='11'><a href='?pg=$pg&medid='>+</a></td></tr>";
		}

		$rs = mysql_query("select * from $tbl order by med_name");
		while ($o = mysql_fetch_object($rs)) {
			$i++;
			echo "<tr bgcolor='".($o->qty_inhand == $o->qty_critical ? 'pink' : '')."'>
			<th><a name='$i' href='?pg=$pg&medid=$o->med_id#$i'>$i</a></th>";
			if ($medid == $o->med_id) {
				echo "<td><input type='hidden' name='medid' value='$o->med_id'>
				<input type='text' name='medname' value='$o->med_name' size='30'></td>
				<td align='center'><input type='text' name='dateExpiry' value='$o->dateExpiry' size='10'></td>
				<td nowrap align='center'>Rs. <input type='text' name='unitrate' value='$o->unit_rate' size='5'></td>
				<td align='center'><input type='text' name='openingstock' value='$o->opening_stock' size='5'></td>
				<td align='right'>$o->qty_receipt</td>
				<td align='right'>$o->qty_used</td>
				<td align='right'>$o->qty_inhand</td>
				<td align='center'><input type='text' name='qtycritical' value='$o->qty_critical' size='5'></td>
				<td>$o->login_id</td>
				<td align='center'><input type='submit' name='submit' value='SAVE'> 
				<a href='?pg=$pg&del=1&medid=$medid'>x</a></td>";     
			} else {
				echo "<td>$o->med_name</td><td align='right'>$o->dateExpiry</td>
				<td align='right'>Rs. $o->unit_rate</td><td align='right'>$o->opening_stock</td><td align='right'>$o->qty_receipt</td>
				<td align='right'>$o->qty_used</td><td align='right'>$o->qty_inhand</td><td align='right'>$o->qty_critical</td>
				<td>$o->login_id</td><td nowrap>$o->date_updation</td>";
			}
			echo "</tr>";	
		}
		echo "</table>";
	}
	
	public function ihcMonthlyMedication($action, $month) {
		$tbl = 'medicines';
		$monthyear = $_REQUEST["monthyear"];

		if (!$monthyear) $monthyear = date("Y-m");
		$cal = explode("-", $monthyear);
		$m = $cal[1];
		$y = $cal[0];

		echo "<h3 align='left'>Monthly Medications</h3>
		Select month <select name='monthyear' onchange=\"javascript: document.location.href='?pg=$pg&monthyear='+this.value\">
		<option value=''></option>";

		$rs = mysql_query("select distinct concat(year(dis_datetime),'-',month(dis_datetime)) as monthyear from medications order by dis_datetime desc");
		while ($o = mysql_fetch_object($rs)) {
			if (strlen($o->monthyear) == 6) $myear = str_replace("-","-0",$o->monthyear); 
			else $myear = $o->monthyear; 
			echo "<option value='$myear'";
			if ($myear == $monthyear) echo " selected";
			echo ">$myear</option>";
		}
		echo "</select> 
		<center>";

		$no = cal_days_in_month(CAL_GREGORIAN, $m, $y);
		echo "<table border='1' width='90%'>
		<tr><th rowspan='2'>Sr</th><th rowspan='2'>Dates =><br>Medicines v</th>
		<th rowspan='2'>Open<br>Qty</th><th colspan='$no'>Date-wise medicines used in the month $monthyear</th>
		<th rowspan='2'>Used<br>Qty</th><th rowspan='2'>Close<br>Qty</th></tr>
		<tr>";
		for ($i=1; $i <= $no; $i++) {
			echo "<th>".($i < 10 ? '0' : '')."$i</th>";
		}
		echo "</tr>";
		$sl = 0;
		$rs = mysql_query("select med_id,med_name from $tbl order by med_name");
		while ($o = mysql_fetch_object($rs)) {
			$sl++;
			$mid = $o->med_id;
			echo "<tr><td>$sl</td><td>$o->med_name</td>";
			//opening stock of the month
				//total received qty in the previous months
			$sr = mysql_query("select sum(qty_receipt) as rq from receipts where med_id=$mid and rec_date<'$monthyear-01' group by med_id");
				if (mysql_num_rows($sr)) {
					  $q = mysql_fetch_object($sr);
					  $rqty = $q->rq;
			} else $rqty = 0;
			//total medication qty in the previous months
				$sr = mysql_query("select sum(qty) as uq from medications where med_id=$mid and date(dis_datetime)<'$monthyear-01' group by med_id");
				if (mysql_num_rows($sr)) {
					  $q = mysql_fetch_object($sr);
					  $uqty = $q->uq;
				} else $uqty = 0;
			//opening qty = total received - total used
			$oqty = $rqty - $uqty;
				echo "<td>$oqty</td>";

			//this month medications (used qty)
			$tot = 0;
			for ($i=1; $i <= $no; $i++) {
				$d = ($i<10 ? '0'.$i : $i);
				$sr = mysql_query("select sum(qty) as iq from medications where med_id=$mid and date(dis_datetime)='$monthyear-$d' group by med_id");
				echo '<td>';
				if (mysql_num_rows($sr)) {
					$q = mysql_fetch_object($sr);
					$iqty = $q->iq;
					$tot += $iqty;
					echo $iqty;
				} else {
					echo '';
				}
				echo '</td>';
			}
			//total qty used this month
			echo "<td>$tot</td>";

			//closing stock of the month
			//total received qty till the end of this month
				$sr = mysql_query("select sum(qty_receipt) as rq from receipts where med_id=$mid and rec_date<='$monthyear-$no' group by med_id");
				if (mysql_num_rows($sr)) {
					  $q = mysql_fetch_object($sr);
					  $rqty = $q->rq;
				} else $rqty = 0;
			//closing stock = total received - total used
			$cqty = $rqty - ($uqty + $tot);
			echo "<td>$cqty</td></tr>";
		}
		echo "</table>";
	}
	
	public function ihcMonthlyReceipt($action, $month) {
		$tbl = 'medicines';
		$monthyear = $_REQUEST["monthyear"];

		if (!$monthyear) $monthyear = date("Y-m");
		$cal = explode("-", $monthyear);
		$m = $cal[1];
		$y = $cal[0];

		echo "<h3 align='left'>Monthly Receipts</h3>
		Select month <select name='monthyear' onchange=\"javascript: document.location.href='?pg=$pg&monthyear='+this.value\">
		<option value=''></option>";

		$rs = mysql_query("select distinct concat(year(rec_date),'-',month(rec_date)) as monthyear from receipts order by rec_date desc");
		while ($o = mysql_fetch_object($rs)) {
			if (strlen($o->monthyear) == 6) $myear = str_replace("-","-0",$o->monthyear); 
			else $myear = $o->monthyear; 
			echo "<option value='$myear'";
			if ($myear == $monthyear) echo " selected";
			echo ">$myear</option>";
		}
		echo "</select>
		<center>";

		$no = cal_days_in_month(CAL_GREGORIAN, $m, $y);

		echo "<table border='1' width='90%'>
		<tr><th rowspan='2'>Sr</th><th rowspan='2'>Dates =><br>Medicines v</th>
		<th colspan='$no'>Date-wise medicines received in the month $monthyear</th><th rowspan='2'>Total<br>Qty</th></tr>
		<tr>";
		for ($i=1; $i <= $no; $i++) {
			echo "<th>".($i < 10 ? '0' : '')."$i</th>";
		}
		echo "</tr>";
		$sl = 0;
		$rs = mysql_query("select med_id,med_name from $tbl order by med_name");
		while ($o = mysql_fetch_object($rs)) {
			$sl++;
			echo "<tr><td>$sl</td><td>$o->med_name</td>";
			$tot = 0;
			for ($i=1; $i <= $no; $i++) {
				$d = ($i<10 ? '0'.$i : $i);
				$sr = mysql_query("select rec_date as dated,sum(qty_receipt) as rq from receipts group by med_id,dated having med_id=$o->med_id and dated='$monthyear-$d'");
				echo '<td>';
				if (mysql_num_rows($sr)) {
					$q = mysql_fetch_object($sr);
					$tot += $q->rq;
					echo $q->rq;
				} else {
					echo '';
				}
				echo '</td>';
			}
			echo "<td>$tot</td></tr>";
		}
		echo "</table>";
	}

	public function ihcPatient($action, $patientID) {
		$tbl = 'registrations';

		$regno = $_REQUEST["regno"];

		if ($regno) {        
			$sql = "select reg_no,reg_datetime as date_time,concat(pat_group,'-',pat_id,' (',dependent,')') as patient,dr_id as doctor,login_id as staff         
			from $tbl where reg_no=$regno";        

			$rs = mysql_query($sql);        

			if (mysql_num_rows($rs)) {
						$colHeads = mysql_num_fields($rs);
						echo "<table border='1' width='90%'><tr><th>Sr</th>";

						for ($i=0; $i < $colHeads; $i++) { // Header
								$fld = ucwords(str_replace("_"," ",mysql_field_name($rs, $i)));
								echo "<th>$fld</th>";
						}

						echo "</tr>";

						while ($row = mysql_fetch_row($rs)) { //data
								$j++;
								echo "<tr><td><a href='?pg=$pg&patid=$patid&regno=".$row[0]."'>$j</a></td><td>".implode($row,'</td><td>')."</td></tr>";
						}
						echo "</table>";
				}

				$heads = array('Prescriptions','Admissions','Medications');

				if ($regno) {
						echo "<h3 align='center'>Medical History of Registration No.- $regno</h3>";
						$sqls = array("select concat(medicine,'- ',dose,', ',frequency,' times, ',course_days,' days') as prescription,login_id as staff 
				from prescriptions where reg_no=$regno order by pres_id",
						"select adm_datetime as ADT,diagnosis,referral,dis_datetime as DDT,login_id as staff 
				from admissions where reg_no=$regno",
						"select dis_datetime as date_time,concat(med_name,' ',specification,' (',med_type ,')') as medicine,qty,a.login_id as staff 
				from medications as a, medicines as b where a.med_id=b.med_id and reg_no=$regno");

						$no = 0;
						foreach ($sqls as $sql) {
								echo "<div align='left'><b>".$heads[$no]."</b></div>";
								$no++;

								echo list_tabledata($sql);
						}
				}

		} else {

			$pgno = $_REQUEST["pgno"];
			if (!$pgno) $pgno = 0;

			$pgsz = 10;

			$sql = "select reg_no,reg_datetime as date_time,concat(pat_group,'-',pat_id,' (',dependent,')') as patient,dr_id as doctor,login_id as staff 
			from $tbl order by reg_no desc limit $pgno,$pgsz";

			$rs = mysql_query($sql);
			if (mysql_num_rows($rs)) {
					$colHeads = mysql_num_fields($rs);

					echo "<table border='1' width='90%'>
				<tr><th>Sr.</th>";
					for ($i=0; $i < $colHeads; $i++) { // Header
						$fld = ucwords(str_replace("_"," ",mysql_field_name($rs, $i)));
						echo "<th>$fld</th>";
					}
					echo "</tr>";
				
				$j = $pgno;
					while ($row = mysql_fetch_row($rs)) { //data
						$j++;
						echo "<tr><td><a href='?pg=$pg&regno=".$row[0]."'>$j</a></td><td>".implode($row,'</td><td>')."</td></tr>";
					}
					echo "</table>";

				if ($pgno) {
					$pgno = $pgno - $pgsz;
					echo "[ <a href='?pg=$pg&pgno=$pgno'>Previous</a> ] ";
					$pgno = $pgno + $pgsz;
				}
				if ($j % $pgsz == 0) {
					$pgno = $pgno + $pgsz;
					echo " [ <a href='?pg=$pg&pgno=$pgno'>Next</a> ]";
				}
			} else {
					echo "---";
			}
		}

		$tbl = 'registrations';

		$pgno = $_REQUEST["pgno"];
		if (!$pgno) $pgno = 0;

		$pgsz = 30;

		$dated = $_REQUEST["dated"];
		$regno = $_REQUEST["regno"];
		$patid = $_REQUEST["patid"];

		$sql = "select pat_id,count(reg_no) as no from $tbl group by pat_id order by no desc limit $pgno,$pgsz";
		$rs = mysql_query($sql);

		echo "<h3 align='left'>Patient Status</h3>
		<table border='1' width='90%'>
		<tr valign='top'><td width='30%'>";

		while ($o = mysql_fetch_object($rs)) { //data
			$patid1 = strtoupper($o->pat_id);
			if ($patid == $patid1) {
					echo "<font color='red' size=+1>- $patid ($o->no)</font>";
				$sr = mysql_query("select reg_no,reg_date from $tbl where pat_id='$patid' order by reg_no desc");
				echo "<dir>";
				while ($q = mysql_fetch_object($sr)) { //data
					if ($regno == $q->reg_no)
						echo "<font color='red' size=+1>- $q->reg_no ($q->reg_date)</font>";
					else
						echo "+ <a href='?pg=$pg&regno=$q->reg_no&patid=$patid&pgno=$pgno'>$q->reg_no</a> ($q->reg_date)";
					echo "<br>";
				}
				echo "</dir>";
				} else {
					echo "+ <a href='?pg=$pg&patid=$patid1&pgno=$pgno'>$patid1</a> ($o->no)";
			}
			echo "<br>";
		}
		echo "</td><td>";

		if ($regno) {
			$heads = array('Registrations','Medications');
				echo "<h3 align='center'>Treatment Record of Registration No.- $regno</h3>";

				$sqls = array("select reg_no,concat(reg_date,' ',reg_time) as dated,concat(dr_name,' (',specialization,')') as doctor,a.login_id as staff from registrations a, doctors b where a.dr_id=b.dr_id and reg_no=$regno",
				"select med_name,qty,a.login_id as staff from medications as a, medicines as b where a.med_id=b.med_id and reg_no=$regno");

			echo patient_name($regno);
			//echo registration_detail($regno);
				$no = 0;
				foreach ($sqls as $sql) {
						echo "<p align='left'><b>".$heads[$no]."</b></p>";
						$no++;

						echo list_tabledata($sql);
				}
		}
		echo "</td></tr></table>";

		if ($pgno) {
				$pgno = $pgno - $pgsz;
				echo "[ <a href='?pg=$pg&pgno=$pgno'>Previous</a> ] ";
				$pgno = $pgno + $pgsz;
		}
		if ($j % $pgsz == 0) {
				$pgno = $pgno + $pgsz;
				echo " [ <a href='?pg=$pg&pgno=$pgno'>Next</a> ]";
		}
	}
	
	public function ihcPHReport($action, $regNo) {
		$tbl = 'phresults';
		$regno = $_REQUEST["regno"];

		if ($regno) {
			if (is_registration($regno)) {
				echo registration_detail($regno);
			
				//if (is_prescription($regno)) {
					echo "<h3 align='left'>Pathology Report</h3>
					<div align='right'>Date Time: ".date("Y-m-d H:i:s")."</div>

					<h3><u>REPORT</u></h3>

					<table border='1' width='100%'>
					<tr><th>Haematology</th><th>Biochemical</th></tr>
					<tr valign='top'><td><table border='0' width='100%'>
					<tr><th>Sr.</th><th>Test</th><th>Normal Range</th><th>Result</th></tr>";	

					$rs = mysql_query("select * from phtests where test_group='Haemetology' order by test_id");
					while ($o = mysql_fetch_object($rs)) {
						$i++;
						echo "<tr><td align='center'>$i</td><td>$o->test_name</td><td>$o->test_range</td>
						<td align='center'>";

							$sr = mysql_query("select * from $tbl where reg_no=$regno and test_id=$o->test_id");
								while ($q = mysql_fetch_object($sr)) {
							echo $q->test_result;
						}
						echo "</td></tr>";
					}
					echo "</table></td><td><table border='0' width='100%'>
					<tr><th>Sr.</th><th>Test</th><th>Normal Range</th><th>Result</th></tr>";
						
					$i = 0;
					$rs = mysql_query("select * from phtests where test_group='Biochemical' order by test_id");
					while ($o = mysql_fetch_object($rs)) {
						$i++;
						echo "<tr><td align='center'>$i</td><td>";
						if (strpos($o->test_name,'Exam') && !$z) {
							echo "<b>URINE EXAMINATION</b><br>";
							$z++;
						}
						echo str_replace("Urine Examination",'&nbsp;&nbsp;&nbsp;&nbsp;',$o->test_name);
						echo "</td><td>$o->test_range</td>
						<td align='center'>";
								
						$sr = mysql_query("select * from $tbl where reg_no=$regno and test_id=$o->test_id");
						while ($q = mysql_fetch_object($sr)) {
							echo $q->test_result;
						}
						echo "</td></tr>";
					}
					echo "</table></td></tr>
					</table>
				
					<br><br>
					<div align='right'>
					<b>Reported by: </b>(<?php echo $user; ?>) _______________________
					</div>";
				//} else
				//	echo "No prescription";
			} else {
				echo "No registration";
			}
		}
	}
	
	public function ihcPHResult($action, $regNo) {
		$tbl = 'phresults';
		$regno = $_REQUEST["regno"];

		if ($_POST["submit"] == 'SAVE') {

			$testids = $_POST["testid"];
				$testresults = $_POST["testresult"];
			$i = 0;

				foreach ($testresults as $testresult) {
					if (mysql_num_rows(mysql_query("select * from $tbl where reg_no=$regno and test_id=".$testids[$i]))) {
							mysql_query("update $tbl set reg_no=$regno,test_id=".$testids[$i].",test_result='$testresult',
							login_id='$user' where reg_no=$regno and test_id=".$testids[$i]);
					} else if ($testresult) {
							mysql_query("insert into $tbl(reg_no,test_id,test_result,test_date,test_time,login_id) 
							values($regno,".$testids[$i].",'$testresult',current_date(),current_time(),'$user')");
					}
				$i++;
			}

			//delete null results
			mysql_query("delete from $tbl where test_result=''");
		}

		echo "<h3 align='left'>Pathology Result</h3>
		Registration No. <input type='text' name='regno' value='<?php echo $regno; ?>' size='10'>
		<input type='submit' name='submit' value='FIND'>
		<br>";

		$j = 0;

		if ($regno) {
			if (is_registration($regno)) {
				echo registration_detail($regno);
			
				//if (is_prescription($regno)) {
				//	echo prescription_detail($regno);

								echo "<table border='1' width='100%'>
								<tr><th>Haematology</th><th>Biochemical</th></tr>
								<tr valign='top'><td><table border='0' width='100%'>
								<tr><th>Sr.</th><th>Test Name</th><th>Normal Range</th><th>Result</th></tr>";

								$rs = mysql_query("select * from phtests where test_group='Haemetology' order by test_id");
								while ($o = mysql_fetch_object($rs)) {
										$j++;
										echo "<tr><td align='center'>$j</td>
						<td><input type='hidden' name='testid[]' value='$o->test_id'>$o->test_name</td>
						<td>$o->test_range</td>";
				
						$sr = mysql_query("select * from $tbl where reg_no=$regno and test_id=$o->test_id");
									if (mysql_num_rows($sr)) {
							$q = mysql_fetch_object($sr);
							$testresult = $q->test_result;
						} else {
							$testresult = '';
						}

						echo "<td><input type='text' name='testresult[]' value='$testresult' size='15'></td></tr>";
								}
								echo "</table></td><td><table border='0' width='100%'>
								<tr><th>Sr.</th><th>Test Name</th><th>Normal Range</th><th>Result</th></tr>";

								$j = 0;
								$rs = mysql_query("select * from phtests where test_group='Biochemical' order by test_id");
								while ($o = mysql_fetch_object($rs)) {
										$j++;
										echo "<tr><td align='center'>$j</td>
										<td><input type='hidden' name='testid[]' value='$o->test_id'>";
						if (strpos($o->test_name,'Exam') && !$z) {
							echo "<b>URINE EXAMINATION</b><br>";
							$z++;
						}
						echo str_replace("Urine Examination",'&nbsp;&nbsp;&nbsp;&nbsp;',$o->test_name);
						echo "</td><td>$o->test_range</td>";

						$sr = mysql_query("select * from $tbl where reg_no=$regno and test_id=$o->test_id");
									if (mysql_num_rows($sr)) {
							$q = mysql_fetch_object($sr);
							$testresult = $q->test_result;
						} else {
							$testresult = '';
						}

						echo "<td><input type='text' name='testresult[]' value='$testresult' size='15'></td></tr>";
								}
								echo "</table></td></tr>
					<tr><th colspan='2'><input type='submit' name='submit' value='SAVE'></th></tr>     
								</table>
					<a href='?pg=phreport&print=1&regno=$regno' target='new'>PRINT REPORT</a>";
				//} else
				//	echo "No prescription";
			} else
				echo "No registration";
		}

	}

	public function ihcPHTest($action, $testID) {
		$tbl = 'phresults';
		$regno = $_REQUEST["regno"];
		echo "<h3 align='left'>Pathology Report</h3>";

		if ($regno && is_registration($regno)) {
			include "../fpdf.php";
			
			// generate pdf file of receipt
			$pdf 		= new Receipt($institute, 'P', 'mm', 'A4');
			$pdf->SetDisplayMode(real, 'default');
			// create first page
			$pdf->AddPage();
			$pdf->SetTitle('ERP PDF Generator');
			$pdf->SetAuthor('IIIT-A');
			$pdf->SetAutoPageBreak(0);

			$pdf->SetFont('Times', 'U', 13);
			$pdf->Cell(0, 0, 'Enrollment Receipt - ' .date("Y"), 0, 1, 'C');
			$pdf->SetFont('Times', 'I', 11);
			$pdf->Cell(0, 12, '( Under ' .str_repeat('.', 20). ' Category )', 0, 1, 'C');
			$pdf->Ln(5);
			
			echo registration_detail($regno);
		
			//if (is_prescription($regno)) {
				echo "<div align='right'>Date Time: ".date("Y-m-d H:i:s")."</div>

				<h3><u>REPORT</u></h3>

				<table border='1' width='100%'>
				<tr><th>Haematology</th><th>Biochemical</th></tr>
				<tr valign='top'><td><table border='0' width='100%'>
				<tr><th>Sr.</th><th>Test</th><th>Normal Range</th><th>Result</th></tr>";	

				$rs = mysql_query("select * from phtests where test_group='Haemetology' order by test_id");
				while ($o = mysql_fetch_object($rs)) {
					$i++;
					echo "<tr><td align='center'>$i</td><td>$o->test_name</td><td>$o->test_range</td>
					<td align='center'>";

						$sr = mysql_query("select * from $tbl where reg_no=$regno and test_id=$o->test_id");
							while ($q = mysql_fetch_object($sr)) {
						echo $q->test_result;
					}
					echo "</td></tr>";
				}
				echo "</table></td><td><table border='0' width='100%'>
				<tr><th>Sr.</th><th>Test</th><th>Normal Range</th><th>Result</th></tr>";
					
				$i = 0;
				$rs = mysql_query("select * from phtests where test_group='Biochemical' order by test_id");
				while ($o = mysql_fetch_object($rs)) {
					$i++;
					echo "<tr><td align='center'>$i</td><td>";
					if (strpos($o->test_name,'Exam') && !$z) {
						echo "<b>URINE EXAMINATION</b><br>";
						$z++;
					}
					echo str_replace("Urine Examination",'&nbsp;&nbsp;&nbsp;&nbsp;',$o->test_name);
					echo "</td><td>$o->test_range</td>
					<td align='center'>";
							
					$sr = mysql_query("select * from $tbl where reg_no=$regno and test_id=$o->test_id");
					while ($q = mysql_fetch_object($sr)) {
						echo $q->test_result;
					}
					echo "</td></tr>";
				}
				echo "</table></td></tr>
				</table>
			
				<br><br>
				<div align='right'>
				<b>Reported by: </b>(<?php echo $user; ?>) _______________________
				</div>";
			//} else
			//	echo "No prescription";
		} else {
			echo "No registration";
		}

		$pdf->Image('https://erp.iiita.ac.in/images/dummy.jpg', 175, 48, 22, 28);
		
		$pdf->SetFont('Times', 'B', 11);
		$pdf->Write(5, "Official Details:\n");
		$pdf->Ln(1);

		$pdf->SetFont('Times', '', 10);
		$y = 72;
		$pdf->SetXY(20, $y);
		$pdf->Cell(50, 5, 'Program Name', 0, 0, 'L');
		$pdf->SetXY(50, $y);
		$pdf->Cell(65, 5, ': ' .str_repeat('.', 60), 0, 1, 'L');
			
		$y += 5;
		$pdf->SetXY(20, $y);
		$pdf->Cell(50, 5, 'Batch Year', 0, 0, 'L');
		$pdf->SetXY(50, $y);
		$pdf->Cell(65, 5, ': ' .date("Y"). ' - ' . str_repeat('.', 10), 0, 1, 'L');
	
		$y += 5;
		$pdf->SetXY(20, $y);
		$pdf->Cell(50, 5, 'Enrollment No.', 0, 0, 'L');
		$pdf->SetXY(50, $y);
		$pdf->Cell(25, 5, ': ' .str_repeat('.', 60), 0, 1, 'L');

		$pdf->Ln(4);
		$pdf->SetFont('Times', 'B', 11);
		$pdf->Write(5, "Personal Details:\n");
		$pdf->Ln(1);

		$pdf->SetFont('Times', '', 10);
		$y += 15;
		$pdf->SetXY(20, $y);
		$pdf->Cell(50, 5, 'Student Name', 0, 0, 'L');
		$pdf->SetXY(50, $y);
		$pdf->Cell(65, 5, ': ' .str_repeat('.', 60), 0, 1, 'L');
			
		$y += 5;
		$pdf->SetXY(20, $y);
		$pdf->Cell(50, 5, 'Date of Birth', 0, 0, 'L');
		$pdf->SetXY(50, $y);
		$pdf->Cell(65, 5, ': ' .'..../..../..........', 0, 1, 'L');
	
		$y += 5;
		$pdf->SetXY(20, $y);
		$pdf->Cell(50, 5, 'Gender', 0, 0, 'L');
		$pdf->SetXY(50, $y);
		$pdf->Cell(65, 5, ': ' .str_repeat('.', 60), 0, 1, 'L');
	
		$y += 5;
		$pdf->SetXY(20, $y);
		$pdf->Cell(50, 5, 'Blood Group', 0, 0, 'L');
		$pdf->SetXY(50, $y);
		$pdf->Cell(65, 5, ': ' .str_repeat('.', 60), 0, 1, 'L');
	
		$y += 5;
		$pdf->SetXY(20, $y);
		$pdf->Cell(50, 5, 'Pwd Status', 0, 0, 'L');
		$pdf->SetXY(50, $y);
		$pdf->Cell(65, 5, ': ' .str_repeat('.', 60), 0, 1, 'L');
	
		$y += 5;
		$pdf->SetXY(20, $y);
		$pdf->Cell(50, 5, 'Category', 0, 0, 'L');
		$pdf->SetXY(50, $y);
		$pdf->Cell(65, 5, ': ' .str_repeat('.', 60), 0, 1, 'L');
	
		$y += 5;
		$pdf->SetXY(20, $y);
		$pdf->Cell(50, 5, 'Marital Status', 0, 0, 'L');
		$pdf->SetXY(50, $y);
		$pdf->Cell(65, 5, ': ' .str_repeat('.', 60), 0, 1, 'L');
	
		$y += 5;
		$pdf->SetXY(20, $y);
		$pdf->Cell(50, 5, 'Religion', 0, 0, 'L');
		$pdf->SetXY(50, $y);
		$pdf->Cell(65, 5, ': ' .str_repeat('.', 60), 0, 1, 'L');
	
		$y += 5;
		$pdf->SetXY(20, $y);
		$pdf->Cell(50, 5, 'Nationality', 0, 0, 'L');
		$pdf->SetXY(50, $y);
		$pdf->Cell(65, 5, ': ' .str_repeat('.', 60), 0, 1, 'L');

		$y += 5;
		$pdf->SetXY(20, $y);
		$pdf->Cell(50, 5, 'Aadhar No.', 0, 0, 'L');
		$pdf->SetXY(50, $y);
		$pdf->Cell(65, 5, ': ' .str_repeat('.', 60), 0, 1, 'L');

		$pdf->Ln(4);
		$pdf->SetFont('Times', 'B', 11);
		$pdf->Write(5, "Contact Details:\n");
		$pdf->Ln(1);

		$pdf->SetFont('Times', '', 10);
		$y += 15;
		$pdf->SetXY(20, $y);
		$pdf->Cell(50, 5, 'Phone No.', 0, 0, 'L');
		$pdf->SetXY(50, $y);
		$pdf->Cell(65, 5, ': ' .str_repeat('.', 60), 0, 1, 'L');
	
		$y += 5;
		$pdf->SetXY(20, $y);
		$pdf->Cell(50, 5, 'Email', 0, 0, 'L');
		$pdf->SetXY(50, $y);
		$pdf->Cell(65, 5, ': ' .str_repeat('.', 60), 0, 1, 'L');
	
		$y += 5;
		$pdf->SetXY(20, $y);
		$pdf->Cell(50, 5, 'Police Station', 0, 0, 'L');
		$pdf->SetXY(50, $y);
		$pdf->Cell(65, 5, ': ' .str_repeat('.', 60), 0, 1, 'L');
			
		$y += 5;
		$pdf->SetFont('Times', '', 9.5);
		$pdf->SetXY(20, $y);
		$pdf->Cell(50, 5, 'Communic. Address', 0, 0, 'L');
		$pdf->SetXY(50, $y);
		$pdf->Cell(65, 5, ': ' .str_repeat('.', 60), 0, 1, 'L');
	
		$y += 5;
		$pdf->SetXY(20, $y);
		$pdf->Cell(50, 5, 'Permanent Address', 0, 0, 'L');
		$pdf->SetXY(50, $y);
		$pdf->Cell(65, 5, ': ' .str_repeat('.', 60), 0, 1, 'L');

		$y += 5;
		$pdf->SetXY(50, $y);
		$pdf->Cell(65, 5, '  ' .str_repeat('.', 60), 0, 1, 'L');
	
		$pdf->Ln(4);
		$pdf->SetFont('Times', 'B', 11);
		$pdf->Write(5, "Parent's / Guardian's Details:\n");
		$pdf->Ln(1);

		$pdf->SetFont('Times', '', 9.5);
		$y += 15;
		$pdf->SetXY(20, $y);
		$pdf->Cell(50, 5, "Father's Name", 0, 0, 'L');
		$pdf->SetXY(50, $y);
		$pdf->Cell(65, 5, ': ' .str_repeat('.', 60). ' (Profession: ' .str_repeat('.', 20). ') Email: ' .str_repeat('.', 25), 0, 1, 'L');
	
		$y += 5;
		$pdf->SetXY(20, $y);
		$pdf->Cell(50, 5, 'Contact', 0, 0, 'L');
		$pdf->SetXY(50, $y);
		$pdf->Cell(65, 5, ': ' .str_repeat('.', 60). ', Phone: ' .str_repeat('.', 60), 0, 1, 'L');
	
		$y += 5;
		$pdf->SetXY(20, $y);
		$pdf->Cell(50, 5, "Mother's Name", 0, 0, 'L');
		$pdf->SetXY(50, $y);
		$pdf->Cell(65, 5, ': ' .str_repeat('.', 60). ' (Profession: ' .str_repeat('.', 20). '), Email: ' .str_repeat('.', 25), 0, 1, 'L');
	
		$y += 5;
		$pdf->SetXY(20, $y);
		$pdf->Cell(50, 5, 'Contact', 0, 0, 'L');
		$pdf->SetXY(50, $y);
		$pdf->Cell(65, 5, ': ' .str_repeat('.', 60). ', Phone: ' .str_repeat('.', 60), 0, 1, 'L');

		$y += 5;
		$pdf->SetXY(20, $y);
		$pdf->Cell(50, 5, "Guardian's Name", 0, 0, 'L');
		$pdf->SetXY(50, $y);
		$pdf->Cell(65, 5, ': ' .str_repeat('.', 40). ' (Profession: ' .str_repeat('.', 20). ') Relation: ' .str_repeat('.', 25). ', Email: ' .str_repeat('.', 25) , 0, 1, 'L');
	
		$y += 5;
		$pdf->SetXY(20, $y);
		$pdf->Cell(50, 5, 'Contact', 0, 0, 'L');
		$pdf->SetXY(50, $y);
		$pdf->Cell(65, 5, ': ' .str_repeat('.', 60). ', Phone: ' .str_repeat('.', 60), 0, 1, 'L');

		$pdf->Ln(4);
		$pdf->SetFont('Times', 'B', 11);
		$pdf->Write(5, "Academic Details:\n");
		$pdf->Ln(1);

		$pdf->SetFont('Times', '', 10);
		$y += 15;
		$pdf->SetXY(20, $y);
		$pdf->Cell(180, 5, '[ X Grade/% - ' .str_repeat('.', 15). ', Year - ' .str_repeat('.', 15). ', Board - ' .str_repeat('.', 60). ' ]', 0, 1, 'L');
		$y += 5;
		$pdf->SetXY(20, $y);
		$pdf->Cell(180, 5, '[ XII Grade/% - ' .str_repeat('.', 15). ', Year - ' .str_repeat('.', 15). ', Board - ' .str_repeat('.', 60). ' ]', 0, 1, 'L');
		$y += 5;
		$pdf->SetXY(20, $y);
		$pdf->Cell(180, 5, '[ UG Grade/% - ' .str_repeat('.', 15). ', Year - ' .str_repeat('.', 15). ', Institute - ' .str_repeat('.', 60). ' ] ', 0, 1, 'L');
		$y += 5;
		$pdf->SetXY(20, $y);
		$pdf->Cell(180, 5, '[ PG Grade/% - ' .str_repeat('.', 15). ', Year - ' .str_repeat('.', 15). ', Institute - ' .str_repeat('.', 60). ' ]', 0, 1, 'L');
		
		$pdf->SetFont('Times', 'B', 11);
		$pdf->SetXY(110, 75);
		$pdf->Cell(20, 5, "Documents Submitted:\n", 0, 0, 'L');

		for($i =0; $i < 20; $i++) {
			$docs .= ($i < 10 ? "0$i" : "$i") .") " .str_repeat('.', 60). "\n";
		}
		$pdf->SetFont('Times', '', 8.5);
		$pdf->SetXY(110, 80);
		$pdf->MultiCell(87, 4, $docs, 1, 'L');

		$pdf->SetFont('Times', 'B', 10);
		$pdf->SetXY(10, 267);
		$pdf->Cell(0, 10, '[ Seal & Signatures ]', 0, 1, 'C');
		$pdf->Line(0, 275, 500, 275);

		$pdf->SetFont('Helvetica', 'B', 9);
		$pdf->SetXY(20, 280);
		$pdf->Write(9, '(Student)');
		$pdf->SetXY(90, 280);
		$pdf->Write(9, '(Parent/Guardian)');
		$pdf->SetXY(165, 280);
		$pdf->Write(9, '(AAA Office)');
		$pdf->Line(0, 288, 500, 288);

		$pdf->SetFont('Helvetica', 'I', 6.5);
		$pdf->SetXY(150, 288);
		$pdf->Cell(0, 5, 'Processed by: ' .str_repeat('.', 60). ' (dated: ..../..../..........)', 0, 1, 'R');
		
		$filename = __DIR__ ."/../uploads/enrollment-format-" .date("Y"). ".pdf";
		$pdf->Output($filename, 'F');

		$str .= "<div align='center'>
		<object data='../uploads/phtest-report-" .$reg_no. ".pdf#page=1' type='application/pdf' title='Enrollment Receipt' width='100%' height='650px'>
			<embed src='../uploads/phtest-report-" .$reg_no. ".pdf#page=1' width='100%' height='650' type='application/pdf'>
				<p>This browser does not support PDFs. Please download the PDF to view it:<br><br><a href='../uploads/phtest-report-" .$reg_no. ".pdf'>Download PDF</a></p>
			</embed>
		</object>
		</div>";
					
		return $str;
	}

	public function ihcMaterialReceipt($action, $matID) {
		$tbl = 'preceipts';
		$recid = $_REQUEST["recid"];
			
		$medid = $_POST["medid"];
		$unitrate = $_POST["unitrate"];
		$qtyreceipt = $_POST["qtyreceipt"];
		$xqtyreceipt = $_POST["xqtyreceipt"];
		$recdate = $_REQUEST["recdate"];
		if (!$recdate) $recdate = date("Y-m-d");

		if ($_POST["submit"] == 'SAVE') {
			
			if (mysql_num_rows(mysql_query("select * from $tbl where rec_id=$recid"))) {
				mysql_query("update $tbl set med_id=$medid,unit_rate=$unitrate,qty_receipt=$qtyreceipt,
				rec_date='$recdate',login_id='$user' 
				where rec_id=$recid");
				
				//update medicine qty_inhand
				mysql_query("update materials set unit_rate=$unitrate,qty_receipt=qty_receipt+$qtyreceipt-$xqtyreceipt,
				qty_inhand=qty_inhand+$qtyreceipt-$xqtyreceipt,login_id='$user' 
				where med_id=$medid");
			} else {
				mysql_query("insert into $tbl(med_id,unit_rate,qty_receipt,rec_date,login_id) 
				values($medid,$unitrate,$qtyreceipt,'$recdate','$user')");
				//update medicine qty_inhand
				mysql_query("update meterials set unit_rate=$unitrate,qty_receipt=qty_receipt+$qtyreceipt,
				qty_inhand=qty_inhand+$qtyreceipt,login_id='$user' 
				where med_id=$medid");
			}

		}

		if ($_GET["del"] == 1) {
			mysql_query("delete from $tbl where rec_id=$recid");
			//update medicine qty_inhand
			mysql_query("update materials set qty_inhand=qty_inhand-$xqtyreceipt,login_id='$user' 
			where med_id=$medid");
		}


		$dated1 = date('Y-m-d', strtotime($recdate .' -1 day'));
		$dated2 = date('Y-m-d', strtotime($recdate .' +1 day'));

		echo "<h3 align='left'>Material Receipt</h3>
		Dated <a href='?pg=$pg&recdate=$dated1'> &lt;&lt; </a> 
		<font size='+1' color='red'>&nbsp;<input type='text' name='recdate' value='$recdate' size='10'>&nbsp;</font>"; 

		if ($recdate != date("Y-m-d")) echo "<a href='?pg=$pg&recdate=$dated2'> &gt;&gt; </a>";
		echo " [ <a href='?pg=receipt_print&recdate=$recdate'>PRINT</a> ]"; 
	
		echo "<br><br>
		<table border='1' width='80%'>
		<tr><th>Sr</th><th>Material Name</th><th>Unit Rate<th>Receipt Qty</th><td align='center'>Action</td></tr>
		";

		if (!$recid) {
			echo "<tr><td>+</td>
			<td>".material_list(0,'+')."</td>
			<td align='center'>Rs. <input type='text' name='unitrate' value='0.00' size='6'></td>
			<td align='center'><input type='text' name='qtyreceipt' value='0' size='5'></td>
			<td align='center'><input type='submit' name='submit' value='SAVE'></td></tr>";     
		} else {
			echo "<tr><td colspan='5'><a href='?pg=$pg&recdate=$recdate&recid='>+</a></td></tr>";
		}

		$i = $pgno;
		$rs = mysql_query("select * from $tbl where rec_date like '$recdate%' order by med_id");
		while ($o = mysql_fetch_object($rs)) {
			$i++;
				echo "<tr><td><a name='$i' href='?pg=$pg&recdate=$recdate&recid=$o->rec_id#$i'>$i</a></td>";
			if ($recid == $o->rec_id) {
					echo "<td><input type='hidden' name='recid' value='$o->rec_id'>
				".material_list($o->med_id,'+')."</td>
					<td align='center'><input type='text' name='unitrate' value='$o->unit_rate' size='6'></td>
					<td align='center'><input type='text' name='qtyreceipt' value='$o->qty_receipt' size='5'>
					<input type='hidden' name='xqtyreceipt' value='$o->qty_receipt'></td>
				<td align='center'><input type='submit' name='submit' value='SAVE'> 
				<a href='?pg=$pg&del=1&recdate=$recdate&recid=$recid'>x</a></td>";     
			} else {
				echo "<td>".medicine_detail($o->med_id)."</td>
				<td align='right'>Rs. $o->unit_rate</td>
				<td align='right'>$o->qty_receipt</td>";	
			}
			echo "</tr>";
		}
		echo "</table>";
	}
	
	public function ihcPrescription($action, $regNo) {
		$tbl = 'prescriptions';
		$regno = $_REQUEST["regno"];
		$presid = $_REQUEST["presid"];
		$presfor = $_REQUEST["presfor"];
		if (!$presfor) $presfor = 'Medicine';

		if ($_POST["submit"] == 'SAVE') {
			
			$medicine = $_POST["medicine"];
			if (!$medicine) $medicine = $_POST["testid"];
			$dose = $_POST["dose"];
			if (!$dose) $dose='';
			$frequency = $_POST["frequency"];
			if (!$frequency) $frequency = 1;
			$coursedays = $_POST["coursedays"];
			if (!$coursedays) $coursedays = 1;
			
			if (mysql_num_rows(mysql_query("select * from $tbl where pres_id=$presid"))) {
				mysql_query("update $tbl set reg_no=$regno,medicine='$medicine',dose='$dose',frequency=$frequency,course_days=$coursedays,
				login_id='$user' where pres_id=$presid");
			} else {
				mysql_query("insert into $tbl(reg_no,medicine,dose,frequency,course_days,login_id) 
				values($regno,'$medicine','$dose',$frequency,$coursedays,'$user')");
			}

		}

		if ($_GET["del"] == 1) {
		//	mysql_query("delete from $tbl where pres_id=$presid");

		}

		echo "<h3 align='left'>Prescription</h3>
		Registration No. <input type='text' name='regno' value='<?php echo $regno; ?>' size='10'>
		<input type='submit' name='submit' value='FIND'>
		<br>";

		if ($regno) {
			if (is_registration($regno)) {
					echo registration_detail($regno);


				echo "<table border='1' width='90%'><tr><th>Sr</th><th>";
				
				foreach ($prescriptions as $pf) {
							echo "<input type='radio' name='presfor' value='$pf'";
							if ($presfor == $pf) echo " checked";
							echo " onclick=\"document.location.href='?pg=$pg&regno=$regno&presfor='+this.value\"> $pf";
					}
					echo "</th><th>Dose</th><th>Frequency/Day</th><th>Course Days</th><td align='center'>Action</td></tr>";

					if (!$presid) {
							echo "<tr><td>+</td><td nowrap>";
					if ($presfor == 'Test') {
								echo phtest_list('',0);
							} else {
								echo "<input type='text' name='medicine' value='' size='25'>";
					}
					
					echo "</td><td><input type='text' name='dose' value='1' size='10'></td>
							<td nowrap><input type='text' name='frequency' value='1' size='5'> times</td>
							<td nowrap><input type='text' name='coursedays' value='1' size='5'> days</td>
					<td align='center'><input type='submit' name='submit' value='SAVE'></td></tr>";
					} else {
							echo "<tr><td colspan='6'><a href='?pg=$pg&regno=$regno&presid='>+</a></td></tr>";
					}

					$rs = mysql_query("select * from $tbl where reg_no=$regno order by pres_id");
					while ($o = mysql_fetch_object($rs)) {
							$i++;
							echo "<tr><td>$i</td><td nowrap>";
							if ($presid == $o->pres_id) {
						if ($presfor == 'Test') {
									echo phtest_list('',$o->medicine);
								} else {
										echo "<input type='text' name='medicine' value='$o->medicine' size='25'>";
						}
								echo "<input type='hidden' name='presid' value='$o->pres_id'></td>
						<td><input type='text' name='dose' value='$o->dose' size='10'></td>
									<td nowrap><input type='text' name='frequency' value='$o->frequency' size='5'> times</td>
									<td nowrap><input type='text' name='coursedays' value='$o->course_days' size='5'> days</td>
									<td align='center'><input type='submit' name='submit' value='SAVE'> 
						<a href='?pg=$pg&regno=$regno&presid=$presid&del=1'>x</a></td>";
							} else {
									if (is_numeric($o->medicine)) {
							echo "<a href='?pg=$pg&regno=$regno&presfor=Test&presid=$o->pres_id'>".phtest_detail($o->medicine)."</a>";
									} else {
							echo "<a href='?pg=$pg&regno=$regno&presid=$o->pres_id'>$o->medicine</a>";
						}
						echo "</td><td>$o->dose</td>
									<td>$o->frequency times</td>
									<td>$o->course_days days</td>";
							}
					echo "</tr>";
					}
					echo "</table>";
			} else
				echo "No registration";
		}
	}
	
	public function ihcReceipt($action, $regNo) {
		$tbl = 'receipts';
		$recid = $_REQUEST["recid"];
			
		$medid = $_POST["medid"];
		$batchNo = $_POST["batchNo"];
		$dateExpiry = $_POST["dateExpiry"];
		$unitrate = $_POST["unitrate"];
		$qtyreceipt = $_POST["qtyreceipt"];
		$xqtyreceipt = $_POST["xqtyreceipt"];
		$recdate = $_REQUEST["recdate"];
		if (!$recdate) $recdate = date("Y-m-d");
		$dated = date("Y-m-d");

		if ($_POST["submit"] == 'SAVE') {
			if (mysql_num_rows(mysql_query("select * from $tbl where rec_id=$recid"))) {
				mysql_query("update $tbl set med_id=$medid,batchNo='$batchNo',dateExpiry='$dateExpiry',
				unit_rate=$unitrate,qty_receipt=$qtyreceipt,rec_date='$recdate',login_id='$user' 
				where rec_id=$recid");
				
				//update batchnos qty_inhand
				mysql_query("update batchnos set dateExpiry='$dateExpiry',unit_rate=$unitrate,
				qty_inhand=qty_inhand+$qtyreceipt-$xqtyreceipt,login_id='$user' 
				where batchNo='$batchNo'");
				//update medicine qty_inhand
				mysql_query("update medicines set unit_rate=$unitrate,qty_receipt=qty_receipt+$qtyreceipt-$xqtyreceipt,
				qty_inhand=qty_inhand+$qtyreceipt-$xqtyreceipt,login_id='$user' 
				where med_id=$medid");
			} else {
				mysql_query("insert into $tbl(med_id,unit_rate,dateExpiry,qty_receipt,rec_date,login_id) 
				values($medid,$unitrate,'$dateExpiry',$qtyreceipt,'$recdate','$user')");
				if (mysql_num_rows(mysql_query("select * from batchnos where batchNo='$batchNo'"))) {
					mysql_query("update batchnos set batchNo,dateExpiry='$dateExpiry',unit_rate=$unitrate,
					qty_inhand=qty_inhand+$qtyreceipt-$xqtyreceipt,login_id='$user'
					batchNo='$batchNo'"); 
				} else {
					mysql_query("insert into $tbl(med_id,batchNo,dateExpiry,unit_rate,qty_inhand,login_id) 
					values($medid,'$batchNo','$dateExpiry',$unitrate,$qtyreceipt,'$user')");
				}
				//update medicine qty_inhand
				mysql_query("update medicines set unit_rate=$unitrate,qty_receipt=qty_receipt+$qtyreceipt,
				qty_inhand=qty_inhand+$qtyreceipt,login_id='$user' 
				where med_id=$medid");
			}
		} else if ($_GET["del"] == 1) {
			mysql_query("delete from $tbl where rec_id=$recid");
			//update medicine qty_inhand
			mysql_query("update medicines set qty_inhand=qty_inhand-$xqtyreceipt,login_id='$user' 
			where med_id=$medid");
		}


		$dated1 = date('Y-m-d', strtotime($recdate .' -1 day'));
		$dated2 = date('Y-m-d', strtotime($recdate .' +1 day'));

		echo "<h3 align='left'>Medicine Receipt</h3>
		<a href='?pg=$pg&recdate=$dated1'> &lt;&lt; </a> 
		<font size='+1' color='red'>&nbsp;<input type='text' name='recdate' value='$recdate' size='10'>&nbsp;</font>"; 

		if ($recdate != date("Y-m-d")) echo "<a href='?pg=$pg&recdate=$dated2'> &gt;&gt; </a>";

		echo "<br><br>
		<table border='1' width='80%'>
		<tr><th>Sr</th><th>Medicine Name</th><th>Batch No.</th><th>Expiry Date</th><th>Unit Rate</th><th>Receipt Qty</th><th>Staff</th><td align='center'>Action</td></tr>
		";

		if (!$recid) {
			echo "<tr><td>+</td>
			<td>".medicine_list(0,'+')."</td>
			<td align='center'><input type='text' name='batchNo' value='' size='20'></td>	
			<td align='center'><input type='text' name='dateExpiry' value='$dated' size='10'></td>	
			<td align='center'>Rs. <input type='text' name='unitrate' value='0.00' size='6'></td>
			<td align='center'><input type='text' name='qtyreceipt' value='0' size='5'></td>
			<td align='center'>$user</td>
			<td align='center'><input type='submit' name='submit' value='SAVE'></td></tr>";     
		} else {
			echo "<tr><td colspan='7'><a href='?pg=$pg&recdate=$recdate&recid='>+</a></td></tr>";
		}

		$i = $pgno;
		$rs = mysql_query("select * from $tbl where rec_date like '$recdate%' order by rec_date,med_id");
		while ($o = mysql_fetch_object($rs)) {
			$i++;
				echo "<tr><td><a name='$i' href='?pg=$pg&recdate=$recdate&recid=$o->rec_id#$i'>$i</a></td>";
			if ($recid == $o->rec_id) {
				echo "<td><input type='hidden' name='recid' value='$o->rec_id'>".medicine_list($o->med_id,'+')."</td>
				<td align='center'><input type='text' name='batchNo' value='$o->batchNo' size='20'></td>
				<td align='center'><input type='text' name='dateExpiry' value='$o->dateExpiry' size='10'></td>
				<td align='center'><input type='text' name='unitrate' value='$o->unit_rate' size='6'></td>
				<td align='center'><input type='text' name='qtyreceipt' value='$o->qty_receipt' size='5'>
				<input type='hidden' name='xqtyreceipt' value='$o->qty_receipt'></td>
				<td align='center'>$user</td>
				<td align='center'><input type='submit' name='submit' value='SAVE'> 
				<a href='?pg=$pg&del=1&recdate=$recdate&recid=$recid'>x</a></td>";     
			} else {
				echo "<td>".medicine_detail($o->med_id)."</td><td align='center'>$o->batchNo</td><td align='center'>$o->dateExpiry</td>
				<td align='right'>Rs. $o->unit_rate</td><td align='right'>$o->qty_receipt</td><td align='center'>$o->login_id</td><td></td>";	
			}
			echo "</tr>";
		}
		echo "</table>";
	}
	
	public function ihcReceiptPrint() {
		echo "<h3 align='left'>Medicine Receipt</h3>
		<div align='right'>
		<b>
		Dated: ";

		$tbl = 'receipts';
		$recdate = $_REQUEST["recdate"];
		if (!$recdate) $recdate = date("Y-m-d");

		echo $recdate;


		echo "</b>
		</div>
		<br><br>
		<table border='1' width='80%' cellpadding='3pt'>
		<tr><th>Sr</th><th>Medicine Name</th><th>Unit Rate</th><th>Expiry Date</th><th>Receipt Qty</th></tr>
		";

		$i = $pgno;
		$rs = mysql_query("select * from $tbl where date(rec_date)='$recdate' order by rec_date,med_id");
		while ($o = mysql_fetch_object($rs)) {
			$i++;
			echo "<tr><td>$i</td><td>".medicine_detail($o->med_id)."</td><td align='right'>Rs.$o->unit_rate</td><td align='center'>$o->dateExpiry</td>
			<td align='right'>".number_format($o->qty_receipt,2)."</td></tr>";
			
			if ($staff != $o->login_id) $staffs .= "[ $o->login_id ]&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;";
			$staff = $o->login_id;
		}

		echo "</table>
		<br><br>
		<div align='right'>
		<b>
		Received by:" .ucwords($staffs). "</b>
		</div>

		<h3 align='left'>Medicine Receipt</h3>";
	
		$tbl = 'receipts';
		$recid = $_REQUEST["recid"];
			
		$medid = $_POST["medid"];
		$batchNo = $_POST["batchNo"];
		$dateExpiry = $_POST["dateExpiry"];
		$unitrate = $_POST["unitrate"];
		$qtyreceipt = $_POST["qtyreceipt"];
		$xqtyreceipt = $_POST["xqtyreceipt"];
		$recdate = $_REQUEST["recdate"];
		if (!$recdate) $recdate = date("Y-m-d");
		$dated = date("Y-m-d");

		if ($_POST["submit"] == 'SAVE') {
			if (mysql_num_rows(mysql_query("select * from $tbl where rec_id=$recid"))) {
				mysql_query("update $tbl set med_id=$medid,batchNo='$batchNo',dateExpiry='$dateExpiry',
				unit_rate=$unitrate,qty_receipt=$qtyreceipt,rec_date='$recdate',login_id='$user' 
				where rec_id=$recid");
				
				//update batchnos qty_inhand
				mysql_query("update batchnos set dateExpiry='$dateExpiry',unit_rate=$unitrate,
				qty_inhand=qty_inhand+$qtyreceipt-$xqtyreceipt,login_id='$user' 
				where batchNo='$batchNo'");
				//update medicine qty_inhand
				mysql_query("update medicines set unit_rate=$unitrate,qty_receipt=qty_receipt+$qtyreceipt-$xqtyreceipt,
				qty_inhand=qty_inhand+$qtyreceipt-$xqtyreceipt,login_id='$user' 
				where med_id=$medid");
			} else {
				mysql_query("insert into $tbl(med_id,unit_rate,dateExpiry,qty_receipt,rec_date,login_id) 
				values($medid,$unitrate,'$dateExpiry',$qtyreceipt,'$recdate','$user')");
				if (mysql_num_rows(mysql_query("select * from batchnos where batchNo='$batchNo'"))) {
					mysql_query("update batchnos set batchNo,dateExpiry='$dateExpiry',unit_rate=$unitrate,
					qty_inhand=qty_inhand+$qtyreceipt-$xqtyreceipt,login_id='$user'
					batchNo='$batchNo'"); 
				} else {
					mysql_query("insert into $tbl(med_id,batchNo,dateExpiry,unit_rate,qty_inhand,login_id) 
					values($medid,'$batchNo','$dateExpiry',$unitrate,$qtyreceipt,'$user')");
				}
				//update medicine qty_inhand
				mysql_query("update medicines set unit_rate=$unitrate,qty_receipt=qty_receipt+$qtyreceipt,
				qty_inhand=qty_inhand+$qtyreceipt,login_id='$user' 
				where med_id=$medid");
			}
		} else if ($_GET["del"] == 1) {
			mysql_query("delete from $tbl where rec_id=$recid");
			//update medicine qty_inhand
			mysql_query("update medicines set qty_inhand=qty_inhand-$xqtyreceipt,login_id='$user' 
			where med_id=$medid");
		}


		$dated1 = date('Y-m-d', strtotime($recdate .' -1 day'));
		$dated2 = date('Y-m-d', strtotime($recdate .' +1 day'));

		echo "<center>
		<a href='?pg=$pg&recdate=$dated1'> &lt;&lt; </a> 
		<font size='+1' color='red'>&nbsp;<input type='text' name='recdate' value='$recdate' size='10'>&nbsp;</font>"; 

		if ($recdate != date("Y-m-d")) echo "<a href='?pg=$pg&recdate=$dated2'> &gt;&gt; </a>";

		echo "<br><br>
		<table border='1' width='80%'>
		<tr><th>Sr</th><th>Medicine Name</th><th>Batch No.</th><th>Expiry Date</th><th>Unit Rate</th><th>Receipt Qty</th><th>Staff</th><td align='center'>Action</td></tr>
		";
		
		if (!$recid) {
			echo "<tr><td>+</td>
			<td>".medicine_list(0,'+')."</td>
			<td align='center'><input type='text' name='batchNo' value='' size='20'></td>	
			<td align='center'><input type='text' name='dateExpiry' value='$dated' size='10'></td>	
			<td align='center'>Rs. <input type='text' name='unitrate' value='0.00' size='6'></td>
			<td align='center'><input type='text' name='qtyreceipt' value='0' size='5'></td>
			<td align='center'>$user</td>
			<td align='center'><input type='submit' name='submit' value='SAVE'></td></tr>";     
		} else {
			echo "<tr><td colspan='7'><a href='?pg=$pg&recdate=$recdate&recid='>+</a></td></tr>";
		}

		$i = $pgno;
		$rs = mysql_query("select * from $tbl where rec_date like '$recdate%' order by rec_date,med_id");
		while ($o = mysql_fetch_object($rs)) {
			$i++;
				echo "<tr><td><a name='$i' href='?pg=$pg&recdate=$recdate&recid=$o->rec_id#$i'>$i</a></td>";
			if ($recid == $o->rec_id) {
				echo "<td><input type='hidden' name='recid' value='$o->rec_id'>".medicine_list($o->med_id,'+')."</td>
				<td align='center'><input type='text' name='batchNo' value='$o->batchNo' size='20'></td>
				<td align='center'><input type='text' name='dateExpiry' value='$o->dateExpiry' size='10'></td>
				<td align='center'><input type='text' name='unitrate' value='$o->unit_rate' size='6'></td>
				<td align='center'><input type='text' name='qtyreceipt' value='$o->qty_receipt' size='5'>
				<input type='hidden' name='xqtyreceipt' value='$o->qty_receipt'></td>
				<td align='center'>$user</td>
				<td align='center'><input type='submit' name='submit' value='SAVE'> 
				<a href='?pg=$pg&del=1&recdate=$recdate&recid=$recid'>x</a></td>";     
			} else {
				echo "<td>".medicine_detail($o->med_id)."</td><td align='center'>$o->batchNo</td><td align='center'>$o->dateExpiry</td>
				<td align='right'>Rs. $o->unit_rate</td><td align='right'>$o->qty_receipt</td><td align='center'>$o->login_id</td><td></td>";	
			}
			echo "</tr>";
		}
		echo "</table>";
	}
	
	public function ihcRegistrations($action, $dated) {
		$reg = $_REQUEST["reg"];
		switch ($reg) {
			case 'daily':
				$ttl = 'Todays';
				$regdate = date('Y-m-d');
				break;
			case 'monthly':
				$ttl = 'Monthly';
				$regdate = date('Y-m-');
				break;
			default:
				$ttl = 'Yearly';
				$regdate = date('Y-');
				break;
		}
		
		echo "<h3 align='left'><?php echo $ttl; ?> Registrations</h3>
		<center>
		<table width='90%' border='1'>
		<tr valign='top'>";

		$heads = array('Registration For','Registration By','Pathology Tests By','Patients','Batch','Course','Gender','Hostel','BG');

		$sqls = array("select concat(dr_name,', ',specialization) as doctor,count(reg_no) as patients 
			from registrations as a, doctors as b 
			where a.dr_id=b.dr_id and reg_date like '$regdate%' group by a.dr_id",
			"select concat(ph_name,', ',specialization) as staff,count(reg_no) as patients 
			from registrations as a, staffs as b 
			where a.login_id=b.ph_id and reg_date like '$regdate%' group by a.login_id",
				"select concat(ph_name,', ',specialization) as staff,count(distinct reg_no) as patients 
				from phresults as a, staffs as b    
				where a.login_id=b.ph_id and test_date like '$regdate%' group by a.login_id",
			"select pat_group as Category,count(reg_no) as patients 
			from registrations 
			where reg_date like '$regdate%' group by pat_group",
				"select year as batch,count(reg_no) as patients
				from students as a,registrations as b
				where a.roll_no=b.pat_id and reg_date like '$regdate%' group by year",
			"select course_name,count(reg_no) as patients 
			from students as a,registrations as b
			where a.roll_no=b.pat_id and reg_date like '$regdate%' group by course_name",
			"select gender,count(reg_no) as patients     
				from students as a,registrations as b
				where a.roll_no=b.pat_id and reg_date like '$regdate%' group by gender",
			"select hostel_no,count(reg_no) as patients     
				from students as a,registrations as b
				where a.roll_no=b.pat_id and reg_date like '$regdate%' group by hostel_no",
			"select bg as blood_group,count(reg_no) as patients     
				from students as a,registrations as b
				where a.roll_no=b.pat_id and reg_date like '$regdate%' group by bg");

		$cols = 3;
		$colw = 100/$cols;
		$no = 0;
		foreach ($sqls as $sql) {
				echo "<td width='$colw%' align='center'><h3>".$heads[$no]."</h3>";
				$no++;
			$tno = 0;
				$rs = mysql_query($sql);
				if (mysql_num_rows($rs)) {
						$colHeads = mysql_num_fields($rs);

						echo "<table border='0' width='90%' align='center'>
				<tr>";
						for ($i=0; $i < $colHeads; $i++) { // Header
								echo "<th>".ucwords(str_replace("_"," ",mysql_field_name($rs, $i)))."</th>";
						}
						echo "</tr>";
						
				$j = 0;
						while ($row = mysql_fetch_row($rs)) { //data
								$j++;
								echo "<tr><td>".implode($row,'</td><td>')."</td></tr>\n";
							$tno = $tno + $row[1];
						}
						echo "<tr><th>Total</th><th>$tno</th></tr></table><br>";
				} else {
					echo "---";      	
			}
			echo "</td>";
				$k++;
				if ($k % $cols == 0) echo "</tr><tr valign='top'>";
		}
		echo "</tr></table>";
	}
	
	public function ihcRequisition($action, $matID) {
		$tbl = 'medicines';
		$fyear = date("Y") - 1;
		$fyear = date("Y");

		echo "<h3 align='left'>Medicine requirement prediction for 6 months based on previous consumptions</h3>
		<div align='right'>Date: ".date("d-m-Y")."
		<table border='1' width='100%'>
		<tr><th rowspan='2'>Sr</th><th rowspan='2'>Medicine Name<br>(with specification)</th>
		<th colspan='12'>Monthly Quantity Used in the Year $fyear</th>
		<th rowspan='2'>Total<br>Used</th><th rowspan='2'>Average<br>/Month</th>
		<th rowspan='2'>Predicted<br>Qty (+5%)</th><th rowspan='2'>Indent<br>Qty</th></tr>
		<tr>";

		foreach ($months as $mnth) {
			echo "<th>$mnth</th>";
		}

		echo "</tr>";

		$no = 12; $sl = 0;
		$rs = mysql_query("select med_id,med_name from $tbl order by med_name");
		while ($o = mysql_fetch_object($rs)) {
			$sl++;
			$mid = $o->med_id;
			echo "<tr><td>$sl</td><td>$o->med_name</td>";

			$tot = 0; $j = 0; $avg = 0;
			for ($i=1; $i <= $no; $i++) {
				$sr = mysql_query("select sum(qty) as iq from medications where med_id=$mid and concat(year(dis_datetime),'-',month(dis_datetime))='$fyear-$i' group by med_id");
				echo '<td>';
				if (mysql_num_rows($sr)) {
					$j++;
					$q = mysql_fetch_object($sr);
					$iqty = $q->iq;
					$tot += $iqty;
					$avg = ceil($tot/$j);
					echo $iqty;
				} else {
					echo '';
				}
				echo '</td>';
			}
			//projected qty for 6 months plus 5% extra
			$pqty = $avg * 6;
			$pqty += round(($pqty * 5 / 100));

			echo "<td>$tot</td><td>$avg</td><td>$pqty</td><td>&nbsp;</td></tr>";

		}

		for ($i = $sl+1; $i<$sl+15; $i++) {	
			echo "<tr><td>$i</td><td></td><td colspan='15'></td><td>&nbsp;</td></tr>";
		}
		echo "
		</table>
		<br>
		<pre>.............................                                                                                                              ..................................
		Pharmacist/Nurse                                                                                                              CMO, IIIT Allahabad</pre>
		";
	}
	
	public function ihcSSchedule($action, $month) {
		$tbl = 'sschedules';
		$schid = $_REQUEST["schid"];
		$monthyear = $_REQUEST["monthyear"];
		$schshift = $_REQUEST["schshift"];

		$i = 0; $j = 0; $k = 0;

		if ($_POST["submit"] == 'SAVE') {
			
			$schdate = $_POST["schdate"];
			$phid = $_POST["phid"];

			if (is_array($phid)) {
				while (list ($key, $val) = each ($phid)) {
					if (mysql_num_rows(mysql_query("select * from $tbl where sch_date='$schdate' and ph_id='$val'"))) {
						mysql_query("update $tbl set ph_id='$val',sch_date='$schdate',sch_shift='$schshift',
						login_id='$user' where sch_id=$schid");
					} else {
						mysql_query("insert into $tbl(ph_id,sch_date,sch_shift,login_id) 
						values('$val','$schdate','$schshift','$user')");
					}
				}
			} else if (mysql_num_rows(mysql_query("select * from $tbl where sch_id=$schid"))) {
				mysql_query("update $tbl set ph_id='$phid',sch_date='$schdate',sch_shift='$schshift',
				login_id='$user' where sch_id=$schid");
			} else {
				mysql_query("insert into $tbl(ph_id,sch_date,sch_shift,login_id) 
				values('$phid','$schdate','$schshift','$user')");
			}
			$schid = '';
			
		} else if ($_POST["submit"] == 'DELETE') {
			$i = mysql_num_rows(mysql_query("select * from $tbl where sch_date=(select sch_date from $tbl where sch_id=$schid) and sch_shift=(select sch_shift from $tbl where sch_id=$schid)"));
			if ($i > 1) {
				mysql_query("delete from $tbl where sch_id=$schid");
			} else {
				mysql_query("update $tbl set ph_id='' where sch_id=$schid");
			}
			$schid = '';
		}

		if (!$monthyear) $monthyear = date("Y-m");

		echo "<h3 align='left'>Staff Schedule</h3>
		Select month <select name='monthyear'>
		";
		$cal = explode("-", $monthyear);
		$m = $cal[1];
		$y = $cal[0];

		$rs = mysql_query("select distinct concat(year(reg_date),'-',month(reg_date)) as monthyear 
		from registrations order by reg_date desc");
		while ($o = mysql_fetch_object($rs)) {
				if (strlen($o->monthyear) == 6) $myear = str_replace("-","-0",$o->monthyear);
				else $myear = $o->monthyear;
				echo "<option value='$myear'";
				if ($myear == $monthyear) echo " selected";
				echo ">$myear</option>";
		}
		echo "</select> <input type='submit' name='submit' value='OK'>

		<table border='1' width='80%'>
		<tr><th width='20%' nowrap>Date \ Duty Shift</th><th width='20%'><?php echo implode($shifts,"</th><th width='20%'>"); ?></th></tr>
		";

		$i = 0; $j = 0; $k = 0;

		$rs = mysql_query("select distinct sch_date from $tbl where sch_date like '$monthyear%' order by sch_date");
		while ($o = mysql_fetch_object($rs)) {
			$i++;
			$k = 0;	
			echo "<tr><th>$o->sch_date</th>";
				
			foreach ($shifts as $sf) {
				echo "<td align='center'>";
			
				$j = 0;
				$rr = mysql_query("select * from $tbl where sch_date='$o->sch_date' and sch_shift='$sf' order by sch_id");
				if (mysql_num_rows($rr)) {
					while ($q = mysql_fetch_object($rr)) {
							$j++;
				
						echo ($j > 1 ? ' + ' : '');	
						if ($schid == $q->sch_id) { //edit existing schedules
										echo staffmulti_list($q->ph_id) . "<input type='hidden' name='schdate' value='$q->sch_date'>
										<input type='hidden' name='schshift' value='$q->sch_shift'><input type='hidden' name='schid' value='$q->sch_id'>";
								} else {
							echo "<a href='?pg=$pg&schid=$q->sch_id'>" . ($q->ph_id ? $q->ph_id : 'x') ."</a>";
						}
					}
				} else if (!$schid) { //get schedule for other shifts
								echo staffmulti_list('') . "<input type='hidden' name='schdate' value='$o->sch_date'>
								<input type='hidden' name='schshift' value='$sf'></td>";
					break;
				}
				echo "</td>";
				$k++;
			}
			echo "</tr>";
			$schdate = $o->sch_date;
		}

		$no = cal_days_in_month(CAL_GREGORIAN, $m, $y);
		if (!$i || ($k == 4 && !$schid)) {
			if ($schdate != "$monthyear-$no") {
				$schdate = ($i == 0 ? $monthyear.'-00' : $schdate++);
				$schdate++;
				echo "<tr><th><input type='hidden' name='schdate' value='$schdate'>$schdate</th>
				<td>" . staffmulti_list($phid) . "<input type='hidden' name='schshift' value='" . $shifts[0] . "'></td></tr>";
			}
		}

		echo "<tr><th colspan='5'>
		<input type='submit' name='submit' value='SAVE'> <input type='submit' name='submit' value='DELETE'>
		</th></tr>
		</table>

		<br>
		<table width='50%' border='5'>
		";

		$rs = mysql_query("select ph_id,count(sch_id) as no from $tbl where sch_date like '$monthyear%' group by ph_id");

		while ($o = mysql_fetch_object($rs)) {
			if ($o->ph_id) echo "<tr><td>".staff_detail($o->ph_id)."</td>
			<td>".$o->no." days</td></tr>";
		}
		echo "</table>";
	}
	
	public function ihcStockBook() {
		echo "<h3 align='left'>Stockbook</h3>
		<center>
		<table border='1' width='98%'>
		<tr><th rowspan='2'>Sr.</th><th rowspan='2'>Medicine</th><th rowspan='2'>Date</th><th colspan='5'>Stock</th></tr>
		<tr><th>Opening</th><th>Receipts</th><th>Total</th><th>Consumed</th><th>Closing</th></tr>
		";

		$tbl = 'medicines';
		$summary = $_REQUEST["summary"];
		if ($summary == 1) $dated = date('Y-m-d');

		$rs = mysql_query("select med_id,med_name,opening_stock,date(date_creation) as dated from $tbl order by med_name");
		while ($o = mysql_fetch_object($rs)) {
			$i++;
			if (!$summary) $dated = $o->dated;
			$opening_stock = $o->opening_stock;
			$qty_total = $opening_stock;
			$qty_balance = $opening_stock;
				
			echo "<tr>
			<th><a name='$i'></a>$i</th><th><a href='?pg=$pg&medid=$o->med_id#$i'>$o->med_name</a></th>
			<th>$dated</th><td align='right'>$opening_stock</td>";

			if ($summary) {
				//receipt summary
				$sr = mysql_query("select sum(qty_receipt) as qty_received from receipts where med_id=$o->med_id group by med_id");
				if (mysql_num_rows($sr)) {
					$q = mysql_fetch_object($sr);
					$qty_total = $qty_total + $q->qty_received;
					echo "<td align='right'>$q->qty_received</td><td align='right'>$qty_total</td>";
				} else {
					echo "<td></td><td align='right'>$qty_total</td>";
				}

				//consumption summary
				$rr = mysql_query("select sum(qty) as qty_used from medications where med_id=$o->med_id group by med_id");
				if (mysql_num_rows($rr)) {
					$r = mysql_fetch_object($rr);
					$qty_balance = $qty_total - $r->qty_used;
					echo "<td align='right'>$r->qty_used</td><td align='right'>$qty_balance</td>";
				} else {
					echo "<td></td><td align='right'>$qty_balance</td>";
				}
				echo "</tr>";
			} else {
				//receipt on opening day
				$sr = mysql_query("select date(rec_date) as rec_date,sum(qty_receipt) as qty_received from receipts 
				where med_id=$o->med_id and date(rec_date)=$o->dated group by med_id,date(rec_date)");
				if (mysql_num_rows($sr)) {
					while ($q = mysql_fetch_object($sr)) {
						$qty_total = $qty_total + $q->qty_received;
						echo "<td align='right'>$q->qty_received</td><td align='right'>$qty_total</td>";
					}
				} else {
					echo "<td></td><td align='right'>$qty_total</td>";
				} 
				
				//consumption on opening day
				$rr = mysql_query("select date(dis_datetime) as dis_date,sum(qty) as qty_used from medications
				where med_id=$o->med_id and date(dis_datetime)=$o->dated group by med_id,date(dis_datetime)");
				if (mysql_num_rows($rr)) {
					while ($r = mysql_fetch_object($rr)) {
						$qty_balance = $qty_total - $r->qty_used;
						echo "<td align='right'>$r->qty_used</td><td align='right'>$qty_balance</td>";
					}
				} else {
					echo "<td></td><td align='right'>$qty_balance</td>";
				}
				echo "</tr>"; 

				$j = 0;
			
				$sr = mysql_query("select rec_date,sum(qty_receipt) as qty_received
				from receipts where med_id=$o->med_id group by rec_date");
				if (mysql_num_rows($sr)) {//procurement is done, check for consumption
					while ($q = mysql_fetch_object($sr)) {
						$rr = mysql_query("select date(dis_datetime) as dis_date,sum(qty) as qty_used from medications
						where med_id=$o->med_id and date(dis_datetime) >= $dated group by date(dis_datetime)");
						if (mysql_num_rows($rr)) {//consumption is done, check dates
							while ($r = mysql_fetch_object($rr)) {
								if (strtotime($r->dis_date) > strtotime($dated) && strtotime($r->dis_date) < strtotime($q->rec_date)) {
									//consumption is earlier to procurement
									$j++;

									echo "<tr><td>&nbsp;&nbsp;$i . $j</td><td></td><td>$r->dis_date [-]</td>
									<td align='right'>$qty_balance</td>";
						
									$qty_balance = $qty_total - $r->qty_used;
									
									echo "<td></td><td align='right'>$qty_total</td>
									<td align='right'>$r->qty_used</td><td align='right'>$qty_balance</td></tr>";
									
									$qty_total = $qty_balance;
									$dated = $r->dis_date;
								} else if (strtotime($q->rec_date) == strtotime($r->dis_date)) {
									//simultaneous procurement/consumption
									$j++;
									$qty_total = $qty_total + $q->qty_received;

									echo "<tr><td>&nbsp;&nbsp;$i . $j</td><td></td><td>$q->rec_date [+-]</td>
									<td align='right'>$qty_balance</td>";
						
									$qty_balance = $qty_total - $r->qty_used;
									
									echo "<td align='right'>$q->qty_received</td><td align='right'>$qty_total</td>
									<td align='right'>$r->qty_used</td><td align='right'>$qty_balance</td></tr>";
							
									$qty_total = $qty_balance;
									$dated = $r->dis_date;
								} else if (strtotime($q->rec_date) > strtotime($dated) && strtotime($q->rec_date) < strtotime($r->dis_date)) {
									//procurement is earlier to consumption
									$j++;
									$qty_total = $qty_total + $q->qty_received;

									echo "<tr><td>&nbsp;&nbsp;$i . $j</td><td></td><td>$q->rec_date [+]</td>
									<td align='right'>$qty_balance</td>";
						
									$qty_balance = $qty_total;
									
									echo "<td align='right'>$q->qty_received</td><td align='right'>$qty_total</td>
									<td align='right'></td><td align='right'>$qty_balance</td></tr>";
							
									$dated = $q->rec_date;
								} else {//consumption is after procurement
									//$dated = (strtotime($q->rec_date) > strtotime($r->dis_date) ? $q->rec_date : $r->dis_date);
									continue;
								}
								//$dated = (strtotime($q->rec_date) > strtotime($r->dis_date) ? $q->rec_date : $r->dis_date);
							}
						} else {//first procurement is earlier to first consumption
							$j++;
							$qty_total = $qty_total + $q->qty_received;

							echo "<tr><td>&nbsp;&nbsp;$i . $j</td><td></td><td>$q->rec_date [+]</td>
							<td align='right'>$qty_balance</td>";

							$qty_balance = $qty_total;

							echo "<td align='right'>$q->qty_received</td><td align='right'>$qty_total</td>
							<td></td><td align='right'>$qty_balance</td></tr>";
						}
						$dated = (strtotime($q->rec_date) > strtotime($r->dis_date) ? $q->rec_date : $r->dis_date);
					}
					//remaining consumption
					$rr = mysql_query("select date(dis_datetime) as dis_date,sum(qty) as qty_used from medications
					where med_id=$o->med_id group by date(dis_datetime)");
					 if (mysql_num_rows($rr)) {
						while ($r = mysql_fetch_object($rr)) {
							if (strtotime($r->dis_date) > strtotime($dated)) {
								$j++;
		 
								echo "<tr><td>&nbsp;&nbsp;$i . $j</td><td></td><td>$r->dis_date [-]</td>
								<td align='right'>$qty_balance</td>";

								$qty_balance = $qty_total - $r->qty_used;

								echo "<td></td><td align='right'>$qty_total</td>
								<td align='right'>$r->qty_used</td><td align='right'>$qty_balance</td></tr>";
											
								$qty_total = $qty_balance;
								$dated = $r->dis_date;
							}
						}
					}
				} else {//no procurement, only consumption
					$rr = mysql_query("select date(dis_datetime) as dis_date,sum(qty) as qty_used from medications
						where med_id=$o->med_id and date(dis_datetime) > $dated group by date(dis_datetime)");
						if (mysql_num_rows($rr)) {
						while ($r = mysql_fetch_object($rr)) {
							$j++;
							   
							echo "<tr><td>&nbsp;&nbsp;$i . $j</td><td></td><td>$r->dis_date [-]</td>
							<td align='right'>$qty_balance</td>";

							$qty_balance = $qty_total - $r->qty_used;

							echo "<td></td><td align='right'>$qty_total</td>
							<td align='right'>$r->qty_used</td><td align='right'>$qty_balance</td></tr>";
							$qty_total = $qty_balance;
						}       
					}
				}
			}
		}
		echo "</table>";
	}
	
	public function ihcStockList() {
		$list = $_REQUEST["list"];

		if ($list == 'medicine') {
			$ttl = 'Medicine';
			$sql = "select med_name as medicine,unit_rate,opening_stock,qty_receipt,qty_used,qty_inhand,qty_critical,date_updation as dated,login_id as staff from medicines order by med_name";

		} else {
			$ttl = 'Material';
			$sql = "select med_name as material,unit_rate,opening_stock,qty_receipt,qty_used,qty_inhand,qty_critical,qty_used,date_updation as dated,login_id as staff from materials order by med_name";

		}

		echo "<h3 align='left'>$ttl Stock</h3>
		<center>";

		echo list_tabledata($sql);
	}
	
	public function ihcYearlyMedication() {
		$tbl = 'medicines';
		$fyear = $_REQUEST["fyear"];

		if (!$fyear) $fyear = date("Y");

		echo "<h3 align='left'>Yearly Medications</h3>
		Select year <select name='fyear' onchange=\"javascript: document.location.href='?pg=$pg&fyear='+this.value\">
		<option value=''></option>";

		$rs = mysql_query("select year(dis_datetime) as fyear from medications group by fyear desc");
		while ($o = mysql_fetch_object($rs)) {
			$fyear1 = $o->fyear; 
			echo "<option value='$fyear1'";
			if ($fyear1 == $fyear) echo " selected";
			echo ">$fyear1</option>";
		}
		echo "</select>
		<center>";

		$no = 12;//cal_days_in_month(CAL_GREGORIAN, $m, $y);
		echo "<table border='1' width='90%'>
		<tr><th rowspan='2'>Sr</th><th rowspan='2'>Months =><br>Medicines v</th>
		<th rowspan='2'>Opening<br>Qty</th><th colspan='12'>Monthly use of medicines during year $fyear</th>
		<th rowspan='2'>Used<br>Qty</th><th rowspan='2'>Closing<br>Qty</th></tr>
		<tr>";
		for ($i=0; $i < $no; $i++) {
			echo "<th>".$months[$i]."</th>";
		}
		echo "</tr>";
		$sl = 0;
		$rs = mysql_query("select med_id,med_name from $tbl order by med_name");
		while ($o = mysql_fetch_object($rs)) {
			$sl++;
			$mid = $o->med_id;
			echo "<tr><td>$sl</td><td>$o->med_name</td>";

				$sr = mysql_query("select sum(qty_receipt) as rq from receipts where med_id=$mid and year(rec_date)<$fyear group by med_id");
				if (mysql_num_rows($sr)) {
					  $q = mysql_fetch_object($sr);
					  $rqty = $q->rq;
			} else $rqty = 0;

				$sr = mysql_query("select sum(qty) as uq from medications where med_id=$mid and year(dis_datetime)<$fyear group by med_id");
				if (mysql_num_rows($sr)) {
					  $q = mysql_fetch_object($sr);
					  $uqty = $q->uq;
				} else $uqty = 0;

			$oqty = $rqty - $uqty;
				echo "<td>$oqty</td>";

			$tot = 0;
			for ($i=1; $i <= $no; $i++) {
				//$d = ($i<10 ? '0'.$i : $i);
				$sr = mysql_query("select sum(qty) as iq from medications where med_id=$mid and concat(year(dis_datetime),'-',month(dis_datetime))='$fyear-$i' group by med_id");
				echo '<td>';
				if (mysql_num_rows($sr)) {
					$q = mysql_fetch_object($sr);
					$iqty = $q->iq;
					$tot += $iqty;
					echo $iqty;
				} else {
					echo '';
				}
				echo '</td>';
			}
			echo "<td>$tot</td>";

				$sr = mysql_query("select sum(qty_receipt) as rq from receipts where med_id=$mid and year(rec_date)=$fyear group by med_id");
				if (mysql_num_rows($sr)) {
					  $q = mysql_fetch_object($sr);
					  $rqty = $q->rq;
				} else $rqty = 0;

			$cqty = ($oqty + $rqty) - $tot;
			echo "<td>$cqty</td></tr>";
		}
		echo "</table>";
	}
	
	public function ihcYearlyReceipt() {
		$tbl = 'medicines';
		$fyear = $_REQUEST["fyear"];

		if (!$fyear) $fyear = date("Y");

		echo "<h3 align='left'>Yearly Receipts</h3>
		Select year <select name='fyear' onchange=\"javascript: document.location.href='?pg=$pg&fyear='+this.value\">
		<option value=''></option>";

		$rs = mysql_query("select year(dis_datetime) as fyear from medications group by fyear desc");
		while ($o = mysql_fetch_object($rs)) {
			$fyear1 = $o->fyear; 
			echo "<option value='$fyear1'";
			if ($fyear1 == $fyear) echo " selected";
			echo ">$fyear1</option>";
		}
		echo "</select> 
		<center>";

		$no = 12;//cal_days_in_month(CAL_GREGORIAN, $m, $y);
		echo "<table border='1' width='90%'>
		<tr><th rowspan='2'>Sr</th><th rowspan='2'>Months =><br>Medicines v</th>
		<th rowspan='2'>Opening<br>Qty</th><th colspan='12'>Monthly receipt of medicines during year $fyear</th>
		<th rowspan='2'>Received<br>Qty</th><th rowspan='2'>Used<br>Qty</th><th rowspan='2'>Closing<br>Qty</th></tr>
		<tr>";
		for ($i=0; $i < $no; $i++) {
			echo "<th>".$months[$i]."</th>";
		}
		echo "</tr>";
		$sl = 0;
		$rs = mysql_query("select med_id,med_name from $tbl order by med_name");
		while ($o = mysql_fetch_object($rs)) {
			$sl++;
			$mid = $o->med_id;
			echo "<tr><td>$sl</td><td>$o->med_name</td>";

				$sr = mysql_query("select sum(qty_receipt) as rq from receipts where med_id=$mid and year(rec_date)<$fyear group by med_id");
				if (mysql_num_rows($sr)) {
					  $q = mysql_fetch_object($sr);
					  $rqty = $q->rq;
			} else $rqty = 0;

				$sr = mysql_query("select sum(qty) as uq from medications where med_id=$mid and year(dis_datetime)<$fyear group by med_id");
				if (mysql_num_rows($sr)) {
					  $q = mysql_fetch_object($sr);
					  $uqty = $q->uq;
				} else $uqty = 0;

			$oqty = $rqty - $uqty;
				echo "<td>$oqty</td>";

			$tot = 0;
			for ($i=1; $i <= $no; $i++) {
				//$d = ($i<10 ? '0'.$i : $i);
				$sr = mysql_query("select sum(qty_receipt) as iq from receipts where med_id=$mid and concat(year(rec_date),'-',month(rec_date))='$fyear-$i' group by med_id");
				echo '<td>';
				if (mysql_num_rows($sr)) {
					$q = mysql_fetch_object($sr);
					$iqty = $q->iq;
					$tot += $iqty;
					echo $iqty;
				} else {
					echo '';
				}
				echo '</td>';
			}
			echo "<td>$tot</td>";

			$sr = mysql_query("select sum(qty) as uq from medications where med_id=$mid and year(dis_datetime)=$fyear group by med_id");
				if (mysql_num_rows($sr)) {
					  $q = mysql_fetch_object($sr);
					  $uqty = $q->uq;
				} else $uqty = 0;

			$cqty = ($oqty + $tot) - $uqty;
			echo "<td>$uqty</td><td>$cqty</td></tr>";
		}
		echo "</table>";
	}
*/