<!---
This file is Copyright © 1998-2009 by Home Care Business Services. This work may not be reproduced, in whole or in part, 
using any medium, including, but not limited to, electronic transmission, CD-ROM or published in print, without the express 
permission of Home Care Business Services.

$Revision: 1.2 $
$Id: exportdata.php,v 1.2 2009/11/02 15:24:35 arlen Exp $
$Date: 2009/11/02 15:24:35 $
--->

<?php

$hostname = "76.12.30.67";
$database = "hhapowerpath";
$username = "hha";
$password = "pRc826ee9";

$tablelist=array("Agency"=>50000,"ScheduleItems"=>20000,"Assessment_New"=>50000,"Assessment_Forms"=>50000,"patient"=>50000,"PatientMeds"=>50000,"PatientContact"=>50000,"Payer"=>50000,"Pathway_Details"=>50000,"Employee"=>50000,"Diagnosis"=>50000,"PatientVisitDetails"=>5000);



$databaseConnect = mysql_connect($hostname, $username, $password) or trigger_error(mysql_error(),E_USER_ERROR);

mysql_select_db($database, $databaseConnect);

error_reporting(E_ALL);

$sql = 	"SELECT Agency_Name, Agency_ID, ExportData, Agency_Contact_Email,Agency_Login FROM Agency a  WHERE a.ExportData = 1 AND Status = 'active' ORDER BY Agency_Name";

$syscfg2=mysql_query($sql) or die("SQL Error: $sql");


while($sys2 = mysql_fetch_array($syscfg2)) {

	$agency_id=$sys2['Agency_ID'];
	$agency_name=$sys2['Agency_Name'];
	$agency_login=$sys2['Agency_Login'];
	$mailoutput='';

	$f_dir = "e:/wwwroot/exportdata/$agency_id-$agency_name/";
	$url_dir="http://76.12.35.143/exportdata/$agency_id-$agency_name/";
	$amt=10000;

	mkdir($f_dir,0777,true);

	$mailoutput="<br><br>$mailoutput$agency_name ($agency_id)<br><br><table>";

	foreach ($tablelist as $thetable => $amt) {

		if ($thetable == 'PatientMeds' || $thetable == 'PatientContact') {
			$sql="Select count(agency_id) as totalrecords from $thetable left outer join patient on $thetable".".patient_id = patient.patient_id where patient.Agency_ID = $agency_id";
		} else if ( $thetable == 'Diagnosis' || $thetable == 'Pathway_Details' || $thetable == 'Assessment_Forms') {
			$sql="Select count(agency_id) as totalrecords from $thetable where Agency_ID = $agency_id";
		} else if ( $thetable == 'PatientVisitDetails') {
			$sql="select count(PatientVisitDetails.agency_id) as totalrecords from ScheduleItems left outer join PatientVisitDetails on ScheduleItems.ScheduleItems_ID = PatientVisitDetails.scheduleitems_id where ScheduleItems.Agency_ID = $agency_id";
		} else {
			$sql="Select count(agency_id) as totalrecords from $thetable where Agency_ID = $agency_id";
		}

		$syscfg=mysql_query($sql) or die("SQL Error: $sql");
		$sys = mysql_fetch_array($syscfg);
		$f_name = $thetable.date("mdy")."_XXX.csv";
		$nfiles= number_format($sys['totalrecords']/$amt + 1,0);
		$start=0;

//		echo "Record: $thetable ".$sys['totalrecords']." $nfiles <br>";


		for ($filecnt=1;$filecnt<=$nfiles;$filecnt++) {

			$tablecolumnlist="";
			$tsql="SHOW COLUMNS FROM $thetable";
			$tsyscfg=mysql_query($tsql) or die("SQL Error: $tsql");
			while($item = mysql_fetch_array($tsyscfg)) {
				$tablecolumnlist="$tablecolumnlist,".$item[0];
			}
			$tablearray=explode(',',$tablecolumnlist);

			$use_f_name=str_replace('XXX',$filecnt,$f_name);
//			echo "FILE: $f_dir.$use_f_name $nfiles<br>";

			if ($thetable == 'PatientMeds' || $thetable == 'PatientContact') {
				$sql="Select * from $thetable left outer join patient on $thetable".".patient_id = patient.patient_id where patient.Agency_ID = $agency_id LIMIT $start,$amt";
			} else if ( $thetable == 'Diagnosis' || $thetable == 'Pathway_Details' || $thetable == 'Assessment_Forms') {
				$sql="Select * from $thetable where Agency_ID = $agency_login LIMIT $start,$amt";
			} else if ( $thetable == 'PatientVisitDetails') {
				$sql="Select PatientVisitDetails.* from ScheduleItems left outer join PatientVisitDetails on ScheduleItems.ScheduleItems_ID = PatientVisitDetails.scheduleitems_id where ScheduleItems.Agency_ID = $agency_id LIMIT $start,$amt";
			} else {
				$sql="Select * from $thetable where Agency_ID = $agency_id LIMIT $start,$amt";	
			}
	
			$syscfg1=mysql_query($sql) or die("SQL Error: $sql");

			$tablerecordcount=mysql_num_rows($syscfg1);

//			$mailoutput="$mailoutput<tr><td>$use_f_name</td></tr>";

			if ($fhandle = fopen($f_dir.$use_f_name,'w')) {
				fwrite($fhandle,",$tablecolumnlist\n");
//				$mailoutput="$mailoutput<tr><td colspan=3>$tablecolumnlist</td></tr>";
				while($sys = mysql_fetch_array($syscfg1)) {
					$outputstring="";
					foreach ($tablearray as $item) {
						if (strlen(trim($item)) == 0) $tmp='';
						else $tmp=str_replace(',','~',$sys[$item]);
						$outputstring="$outputstring,$tmp";
					}
					fwrite($fhandle,"$outputstring\n");
				}
				$mailoutput="$mailoutput<tr><Td>$thetable</td><td>$tablerecordcount</td><td><a href='$url_dir$use_f_name'>$use_f_name</a></td></tr>";
				$start=$start+$amt;
			}
		}
	}
	$mailoutput="$mailoutput</table>";

	echo $mailoutput;

	$f_name = $f_dir."index.txt";

	$farray = array();
	$n=0;
//	unlink($f_name);
	if ($fhandle = fopen($f_name,'w')) {
		if ($handle = @opendir($f_dir)) {
			while (false !== ($file = @readdir($handle))) {
				if ($file != '.' && $file != '..' && stripos($file,".csv")) {

					$curdate = date("Ymd",filemtime($f_dir.$file));
					$term = 30;
					$expdate = date( "Ymd", mktime(0, 0, 0, date("m"), date("d")-$term, date("y")) );
					if (strcmp($curdate,$expdate) <= 0) {
						unlink($f_dir.$file);
					} else {
						$date=date ("m/d/Y", filemtime($f_dir.$file));
						$farray[$n++]="$date:$file";
					}
				}
			}
			@closedir($handle);
		} else {
			echo "error opening $f_dir";
		}
		rsort($farray);

			fwrite($fhandle,"<table><tr><td nowrap>&nbsp;</td><td nowrap>&nbsp;</td></tr>\n");
			$lastdate='';
			foreach ($farray as $item) {
				list($date,$file) = split(":",$item);
				if ($date != $lastdate) {
					$str="<tr><td nowrap>$date</td><td nowrap><a href='$url_dir$file'>$file</a></td></tr>\n";
					$lastdate=$date;
				} else {
					$str="<tr><td nowrap>&nbsp;</td><td nowrap><a href='$url_dir$file'>$file</a></td></tr>\n";
				}
				fwrite($fhandle,$str);
				
			}
			@closedir($handle);
			fwrite($fhandle,"</table>\n");

	} else {
			echo "error opening $f_name";
	}

}