#!/usr/bin/perl

require "config.idx";

$long = $ENV{'QUERY_STRING'};

if ($long) {
	@pairs=split(/&/,$long);
	foreach $item(@pairs) {
		($name,$content)=split (/=/,$item,2);
		$content=~tr/+/ /;
		$content=~ s/%(..)/pack("c",hex($1))/ge;
		if ($INPUT{$name}) { $INPUT{$name} = $INPUT{$name}.",".$content; }
		else { $INPUT{$name} = $content; }
	}
}
else {
	read(STDIN, $buffer, $ENV{'CONTENT_LENGTH'});
	@pairs = split(/&/, $buffer);
	foreach $pair (@pairs) {
		($name, $value) = split(/=/, $pair);
		$value =~ tr/+/ /;
		$value =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C", hex($1))/eg;
		if ($INPUT{$name}) { $INPUT{$name} = $INPUT{$name}.",".$value; }
		else { $INPUT{$name} = $value; }
	}
}


&checklogin;

if ($INPUT{action} eq "activity_log") { &activity_log; }
elsif ($INPUT{action} eq "login") { &login; }
elsif ($INPUT{action} eq "logoff") { &logout; }
else { &main; }

sub login {

use DBI;
my $dsn = "DBI:mysql:database=$d_name;host=localhost";
my $dbh = DBI->connect($dsn, $d_username, $d_pass, {RaiseError => 1}) || die $DBI::errstr;
my $fasth = $dbh->prepare("select userid from users where email = '$INPUT{Email}' AND password = PASSWORD('$INPUT{Password}') AND agentid != ''");
$fasth->execute;


while (($uid) = $fasth->fetchrow_array()) {
$userid = $uid;

### GET AGENT ID FOR COOKIE
my $vasth = $dbh->prepare("select agentid from users where userid = '$userid' AND email = '$INPUT{Email}'");
$vasth->execute;
while (($mymlsid) = $vasth->fetchrow_array()) {
$agent_id = $mymlsid;
}
### END GET AGENT ID FOR COOKIE

my $uasth = $dbh->do("update users set lastlogin = now() where userid = '$userid'");
my $pasth = $dbh->prepare("select DATE_FORMAT(DATE_ADD(NOW(), INTERVAL 1 DAY), '%a\, %d\-%b\-%Y %T')");
$pasth->execute;

while (($nextmonthsdate) = $pasth->fetchrow_array()) {
$setcookiedate = "$nextmonthsdate";
}


print "Set-cookie: userid=$userid\|$INPUT{Email}\|$agent_id\; expires=$setcookiedate GMT\n";
print "Content-type: text/html\n\n";

print qq~

<html><head><title>Loading Your MY HOMES Data...</title>
<meta http-equiv="Refresh" content="3; URL=$theurl">
</head>
<body>
<br><br><br><br><br>
<center>
<table border="0" cellpadding="12" cellspacing="1" bgcolor="navy">
<tr>
<td valign="middle" bgcolor="white">
<br>
<center>
<img src="images/StatusBar4.gif" alt="Loading"><br>
<img src="images/nowloading.gif"><br>
</center>
</td>
</tr>
</table>
</center>
~;

$dbh->disconnect;

exit 0;

}

print "Set-cookie: userid=\n";
print "Content-type: text/html\n\n";

print qq~
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" /> 
<title>Login to The ORR Home Selling Team CONNECT Real Estate Management System</title>
<link rel="stylesheet" href="includes/login.css" type="text/css" media="all" />
</head>
<body>
	<div id="container">
			<div id="logo"></div>
			<div id="connectlogo"></div>
			<div id="content">
				<span class="status">Authorization error has occured....</span><br>
				<form method="post" action="index.idx">
				<input type="hidden" name="action" value="login" />
				email address<br/>
				<input type="text" name="Email" value="$INPUT{Email}" class="form" /><br/>
				password<br/>
				<input type="password" name="Password"><br/>
					<div id="animated"></div>
				<input type="submit" value="login" class="button" /><br/>
				</form>
			</div>
		<span class="cl"></span>
		<div id="footer">&copy; Copyright 2008-2013 The ORR Home Selling Team RE/MAX Real Estate Groups  For Office Staff and Agent use only!</div>
	</div>
</body>
</html>
~;

}

sub logout {


print "Set-cookie: userid=\n";
print "Content-type: text/html\n\n";

print qq~


<html><head><title>Logging out...</title>
<meta http-equiv="Refresh" content="2; URL=index.idx">
</head>
<body>
<br><br><br><br><br>
<center>
<table border="0" cellpadding="12" cellspacing="1" bgcolor="navy">
<tr>
<td valign="middle" bgcolor="white">
<br>
<center><font face=Arial size=3>
<img src="images/StatusBar4.gif" alt="Loading"><br>
You Are Now Being Logged out....
</center>
</td>
</tr>
</table>
</center>
~;
}

sub main {

use DBI;
my $dsn = "DBI:mysql:database=$d_name;host=localhost";
my $dbh = DBI->connect($dsn, $d_username, $d_pass, {RaiseError => 1}) || die $DBI::errstr;

my $tdatebasth = $dbh->prepare("select DATE_FORMAT(now(), '%Y-%m-%d')");
$tdatebasth->execute;
while (($todaydate) = $tdatebasth->fetchrow_array()) {
$today = "$todaydate";
}


my $dateaasth = $dbh->prepare("select DATE_FORMAT(DATE_ADD(now(), INTERVAL -7 DAY), '%Y-%m-%d')");
$dateaasth->execute;
while (($newbackdate) = $dateaasth->fetchrow_array()) {
$findsdate = "$newbackdate";
}


#### CHECK EXPIREDS IN NEXT TWO WEEKS AND DISPLAY LIST  ######

my $datebasth = $dbh->prepare("select DATE_FORMAT(DATE_ADD(now(), INTERVAL 14 DAY), '%Y-%m-%d')");
$datebasth->execute;
while (($newstartdate) = $datebasth->fetchrow_array()) {
$findldate = "$newstartdate";
}

my $aasth = $dbh->prepare("select count(id) from trans_board where (expiredate BETWEEN '$today' AND '$findldate') AND (status = 'Active' or status = 'Pending') AND agent = '$Cook{agentid}'");
$aasth->execute;
while (($temp_expiretwoweeks) = $aasth->fetchrow_array()) {
$expired_twoweeks = $temp_expiretwoweeks;
}

my $nameaasth = $dbh->prepare("select id,agent,addressnumber,addressstreet,city from trans_board where (expiredate BETWEEN '$today' AND '$findldate') AND (status = 'Active' or status = 'Pending') AND agent = '$Cook{agentid}'");
$nameaasth->execute;
while (($id,$agent,$addressnumber,$addressstreet,$city) = $nameaasth->fetchrow_array()) {
$expired_twoweeks_list .= "<hr><a href=\"transactions.idx?action=overview&transid=$id&agent=$agent\">$addressnumber $addressstreet, $city</a><br>";
}


my $aeasth = $dbh->prepare("select count(id) from trans_board where expiredate < '$today' AND status = 'Active' AND agent = '$Cook{agentid}'");
$aeasth->execute;
while (($temp_expireddate) = $aeasth->fetchrow_array()) {
$expired_listings = $temp_expireddate;
}
my $aelasth = $dbh->prepare("select id,agent,addressnumber,addressstreet,city from trans_board where expiredate < '$today' AND status = 'Active' AND agent = '$Cook{agentid}'");
$aelasth->execute;
while (($id,$agent,$addressnumber,$addressstreet,$city) = $aelasth->fetchrow_array()) {
$expired_listings_list .= "<hr><a href=\"transactions.idx?action=overview&transid=$id&agent=$agent\">$addressnumber $addressstreet, $city</a><br>";
}

#### END CHECK EXPIREDS #####

### GET NUMBER OF ACTIVE LISTINGS ###

my $active_listings = $dbh->prepare("select count(id) from trans_board where status = 'Active' AND agent = '$Cook{agentid}'");
$active_listings->execute;
while (($temp_active_listings) = $active_listings->fetchrow_array()) {
$active_listings_number = $temp_active_listings;
}

$active_listings_number = ($active_listings_number-$expired_listings);

### END GET NUMBER OF ACTIVE LISTINGS ####


### GET NUMBER OF PENDING LISTINGS AND DETAILS OF PENDING TYPE ####

my $pending_listings = $dbh->prepare("select count(id) from trans_board where status = 'Pending' AND agent = '$Cook{agentid}'");
$pending_listings->execute;
while (($temp_pending_listings) = $pending_listings->fetchrow_array()) {
$pending_listings_total = $temp_pending_listings;
}

my $pending_listings_list = $dbh->prepare("select count(id) from trans_board where status = 'Pending' AND type = 'Listing' AND agent = '$Cook{agentid}'");
$pending_listings_list->execute;
while (($temp_pending_listings_list) = $pending_listings_list->fetchrow_array()) {
$pending_listings_list_num = $temp_pending_listings_list;
}

my $pending_listings_bsp = $dbh->prepare("select count(id) from trans_board where status = 'Pending' AND type = 'BSP' AND agent = '$Cook{agentid}'");
$pending_listings_bsp->execute;
while (($temp_pending_listings_bsp) = $pending_listings_bsp->fetchrow_array()) {
$pending_listings_bsp_num = $temp_pending_listings_bsp;
}

my $pending_listings_bp = $dbh->prepare("select count(id) from trans_board where status = 'Pending' AND type = 'BP' AND agent = '$Cook{agentid}'");
$pending_listings_bp->execute;
while (($temp_pending_listings_bp) = $pending_listings_bp->fetchrow_array()) {
$pending_listings_bp_num = $temp_pending_listings_bp;
}

### END GET NUMBER OF PENDING LISTINGS ####

print qq~
<html>
<head>
<title>The ORR Home Selling Team - Connect.EagleSold.com</title>
<script language="JavScript">
function submit()
{
	 document.changestatus.submit();
}
</script>
~;

&header;


print qq~
<td valign="top" width="830">
<img src="images/headers/intranet.gif" height="33" width="830" alt="The ORR Team Intranet"><br>
~;

print qq~
<br>
<table border="0" cellpadding="3" cellspacing="1" width="100%">
<tr>
<td valign="top" width="100%">
<font color="green" size="4"><b><u>My Listing and Prospect Tasks</u></b></font><br><br>

<table border="0" cellpadding="0" cellspacing="0" width="100%">
<tr>
<td valign="top" width="65%">
<div class="notify">
<u>Expired Listing Reminders</u><br>
<b>You Have $expired_twoweeks Listings That Will Expire In The Next 2 Weeks!</b><br>
$expired_twoweeks_list<br>
<b>You Have $expired_listings Listings That Have Expired!</b><br>
$expired_listings_list<br><br>

<b>My Tasks</b><br>
<form method="get" action="tasks.idx" target="_blank">
<input type="hidden" name="action" value="report" target="_blank">
<select name="template_id">
<option value="all">All</option>
~;


my $ssth = $dbh->prepare("select id,task_type,template_name from trans_boardtask_templates where agent_id = '$Cook{agentid}' order by id DESC");
$ssth->execute;
while (($ttemplate_id,$ttemplate_type,$ttemplate_name) = $ssth->fetchrow_array()) {
print qq~
<option value="$ttemplate_id">$ttemplate_type - $ttemplate_name</option>
~;
}


print qq~
</select><br><input type="submit" value="Launch Tasks">
</form>
<a target="_blank" href="tasks.idx?action=report&template_id=all">Print All Action Plan Report</a><br>
<a target="_blank" href="tasks.idx?action=reportgridview">Print Action Plan Grid</a>
<br><br>


</div>
</td>
<td valign="top" width="35%" bgcolor="#ccffcc">
<b>My Statistics</b><br>
You have $active_listings_number Active Listings!<br>
You have $pending_listings_total Pending Sales!<br>
$pending_listings_list_num List | $pending_listings_bp_num Buyer | $pending_listings_bsp_num List&Buyer<br><br><br>
<b>Showing & Listing Report</b>
<a target="_blank" href="showing_list.idx">View Report</a><br>
* For Use when setting up after hours showings.<br><br>
<b>Quick Number References</b>
<br><u>Accessors</u><br>
765-348-1707 - <a href="http://beacon.schneidercorp.com/Application.aspx?AppID=113&LayerID=1281&PageTypeID=2&PageID=730" target="_blank">Blackford Co</a><br>
765-747-7710 - Center TWP<br>
765-747-7715 - <a href="http://www.sidwellmaps.com/website/delawareco/viewer.php" target="_blank">Delaware Co</a><br>
<a href="http://beacon.schneidercorp.com/Application.aspx?AppID=213&LayerID=2828&PageTypeID=2&PageID=1566" target="_blank">NEW Delaware Co Beacon</a><br>
765-529-2104 - <a href="http://assessor.henry.in.uinquire.us/nxweb.exe?CALL_PROGRAM=C008LIST" target="_blank">Henry Co</a><br>
260-726-4456 - <a href="http://in38.plexisgroup.com/map/index.cfm" target="_blank">Jay Co</a><br>
765-641-9401 - Madison Co<br>
765-584-2427 - <a href="http://in-randolph-assessor.governmax.com/propertymax/rover30.asp?sid=E096C837A6CD46DF97BA8C5C99A53DDE" target="_blank">Randolph Co</a><br>
<br><u>Treasurers</u><br>
765-348-2504 - Blackford Co<br>
765-747-7808 - <a href="http://198.63.33.49/" target="_blank">Delaware Co</a><br>
<a href="http://beacon.schneidercorp.com/Application.aspx?AppID=213&LayerID=2828&PageTypeID=2&PageID=1566" target="_blank">NEW Delaware Co Beacon</a><br>
765-529-4404 - Henry Co<br>
260-726-7007 - Jay Co<br>
765-641-9645 - Madison Co<br>
765-584-0704 - Randolph Co<br>
<br>
</td>
</tr>
<tr>
<td colspan="2" bgcolor="navy">
<div class="notify">
<b><font color="white">Recent Account Activity</font></b><br>
<iframe src="index.idx?action=activity_log" width="100%" height="125" noresize="noresize" scrolling ="yes" frameborder="0" marginwidth="3" marginheight="3"></iframe>
</div>
</td>
</tr>
</table>

</td>
</tr>
</table>
</td>
</tr>
</table>
~;
&footer;

}

sub activity_log {

use DBI;
my $dsn = "DBI:mysql:database=$d_name;host=localhost";
my $dbh = DBI->connect($dsn, $d_username, $d_pass, {RaiseError => 1}) || die $DBI::errstr;

### START ACTIVITY LOG ###

$activity_log .= "<table width=\"100%\">";

$trcolor = "1";
$trcolor2 = "2";
my $activity_log_db = $dbh->prepare("select note,name,DATE_FORMAT(date, '%b %D, %Y at %h\:%i%p') from trans_boardactivity where agent = '$Cook{agentid}' order by date DESC");
$activity_log_db->execute;
while (($activity_note,$activity_name,$activity_date) = $activity_log_db->fetchrow_array()) {
	if ($trcolor eq $trcolor2) {
	$trcolor = "1";
	$setcolor = "#FFFF99";
	}
	else {
	$setcolor = "#FFFFFF";
	$trcolor++;
	}
$activity_log .=qq~<tr><td bgcolor="$setcolor" valign="top"><b>$activity_note<br><i>By $activity_name on $activity_date</i></b><br></td></tr>~;
$activity_found = "yes";
}

unless ($activity_found eq "yes") {
$activity_log =qq~<tr><td><font color="red"><b>Activity Tracker Added April 28th, 2007.  System will now track activity after this date!</b></font></td></tr>~;
}

$activity_log .= "</table>";

print qq~
<html>
<head>
<title>Activity Log</title>
<link rel="stylesheet" TYPE="text/css" href="includes/style.css">
</head>
<body bgcolor="white" leftMargin="0" topMargin="0" marginwidth="0" marginheight="0">
$activity_log
</body>
</html>
~;

### END ACTIVITY LOG ####

}
