<?php session_start();

if($_GET['_SESSION'] != '' || $_POST['_SESSION'] != '' || $_COOKIE['_SESSION'] != '') { exit; }

//Connect to the database
$db_server = 'p:localhost';
$db_name = 'fcso_sope1';
$db_un = 'fcso_sope1';
$db_pw = 'YybkCBgWBMvV';

$link = mysqli_connect("$db_server", "$db_un","$db_pw", "$db_name");

mysqli_query($link, "SET SESSION SQL_MODE = ''");

if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

if (!$link) {
    echo "Error: Unable to connect to MySQL." . PHP_EOL;
    exit;
}

?>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>

	<head>
		<link rel="stylesheet" type="text/css" href="https://lookup.fayettesheriff.org/inmates.css">
		<title>Fayette Sheriff Inmate Lookup</title>
	</head>
	<body>
	<!--<h1>Fayette Sheriff - Inmate Lookup</h1>-->
<?php
//calculate years of age (input string: YYYY-MM-DD)
function age_from_birthday($birthday) {

        list($year,$month,$day) = explode("-",$birthday);

        $year_diff  = date("Y") - $year;

        $month_diff = date("m") - $month;

        $day_diff   = date("d") - $day;

        if ($day_diff < 0 || $month_diff < 0) {

                $year_diff--;

        }

        return $year_diff;
}

function custom_alpha_only($string) {

        $new_string = preg_replace("[^A-Za-z0-9]", "", $string_to_be_stripped );

        return $new_string;
}


include('inmates.class.php');

$filename = 'jailrostera.xml';

# inmateData class is used to interact with the data.
$inmateData = new inmateData($link, $filename, $mtime);


# Set media folder variable and get file modification times
$mediaFolder = $_SESSION['docroot_path']."/import/";

$filetime = filemtime('/home/fcso/public_html/import/jailrostera.xml');

function getMtime($link) {
	$qry = mysqli_query($link, "SELECT data FROM smt_userdata WHERE plugin = 'inmateXmlInfo' AND fieldname = 'mtime'");
		if (!$qry  || $qry == NULL) {
			return 0;
		}
		elseif (new_mysqli_result($qry, 0, 0) != FALSE) {
			return new_mysqli_result($qry, 0, 0);
		}
		else {
			return 0;
		}
}

$mtime = getMtime($link);

if (!$mtime || $mtime == NULL || $mtime == '') {
	$qry = "INSERT INTO smt_userdata VALUES '', 'inmateXmlInfo', 'mtime', '" . $filetime . "'";
	if (!mysqli_query($link, $qry))  {
		//print('Failed to write mtime to table');
	}

	$inmateData->processXml($link, $filename);
}

elseif ($filetime > $mtime || $filename == $mtime ) {
	$inmateData->processXml($link, $filename);

	$qry = "UPDATE smt_userdata SET data = '" . $mtime . "' WHERE plugin = 'inmateXmlInfo' AND fieldname = 'mtime'";
    if (!mysqli_query($link, $qry))  {
		//print('Failed to update mtime to table. <br />');
	}
}

if ( $_GET['filter'] == 'recent' && $_GET['sort'] == 'alpha' ) {

        $peopleArr = $inmateData->getRecentInmates($link, true);

} elseif ( $_GET['filter'] == 'recent' && $_GET['sort'] == 'booking' ) {

        $peopleArr = $inmateData->getRecentInmatesByBookingDate($link, true);

} elseif ( $_GET['filter'] == 'all' && $_GET['sort'] == 'booking' ) {

        $peopleArr = $inmateData->getInmatesByBookingDate($link, 100);

} else {

        $peopleArr = $inmateData->getAllInmates($link);
}

$result_count = count($peopleArr);


# Re-check radios. Easier to do it this way than with javascript because of onchange's
if ( $_GET['filter'] == 'recent' ) { $filter_recent = ' checked'; } else { $filter_all = ' checked'; }

if ( $_GET['sort'] == 'booking' ) { $sort_booking = ' checked'; } else { $sort_alpha = ' checked'; }

?>

<?php /*<doctype html>*/ ?>

  <style>
        .inmate-row {
            display: none;
        }
    </style>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js" type="text/javascript"></script>

<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.7.2/jquery-ui.min.js" type="text/javascript"></script>

    <script>
    $(document).ready(function() {
        $('#search-form').submit(function(event) {
            event.preventDefault();
            var searchQuery = $('#search-input').val().trim().toLowerCase();
            if (searchQuery.length >= 4) {
                $('.inmate-row').each(function() {
                    var inmateFirstName = $(this).find('td:nth-child(2)').text().toLowerCase();
                    var inmateLastName = $(this).find('td:nth-child(1)').text().toLowerCase();
                    if (searchQuery == inmateFirstName + ' ' + inmateLastName) {
                        $(this).show();
                    } else {
                        $(this).hide();
                    }
                });
            }
        });
    });
</script>
<link rel="stylesheet" type="text/css" href="https://lookup.fayettesheriff.org/inmates.css"/>

<!--[if lt IE 9]>

<script src="https://html5shiv.googlecode.com/svn/trunk/html5.js"></script>

<![endif]-->
<form id="search-form">
        <div id="search-instruction"> Please enter the full name of the inmate.  Search expects "FirstName LastName" without the quotations and must be spelled correctly. Example: John Smith<br /></div>
       <input type="text" id="search-input" placeholder="Search inmate name">
       <button type="submit">Search</button>
   </form>

<nav id="filters">

        <ul>

                <li><strong>Filter:</strong></li>

                <li><input type="radio" name="filter" id="filter-all" value="all" onchange="apply_filtersort();"<?php echo $filter_all; ?>/><label for="filter-all">All Inmates</label></li>

                <li><input type="radio" name="filter" id="filter-recent" value="recent" onchange="apply_filtersort();"<?php echo $filter_recent; ?>/><label for="filter-recent">Booked in Last 72 Hours</label></li>

        </ul>


        <ul>

                <li><strong>Sort:</strong></li>

                <li><input type="radio" name="sort" id="sort-alpha" value="alpha" onchange="apply_filtersort();"<?php echo $sort_alpha; ?>/><label for="sort-alpha">Alphabetically</label></li>

                <li><input type="radio" name="sort" id="sort-booking" value="booking" onchange="apply_filtersort();"<?php echo $sort_booking; ?>/><label for="sort-booking">By Booking Date</label></li>

        </ul>

        <br/>

</nav>

<header id="result-count"><br />

        [<?php echo $result_count; ?>] Results returned

</header>

<p> Click on an inmate to see more details. </p>


<table border="0" id="inmates" cellpadding="0" cellspacing="0">

        <tr id="headings">

                <th>Last Name</th>

                <th>First Name</th>

                <th>Middle Name</th>

                <th>Suffix</th>

                <!--<th>DOB</th>-->

                <th>Race</th>

                <th>Sex</th>

                <th>Start Date</th>

        </tr>

<?php

$max = count($peopleArr);

for ( $x = 0; $x < $max; $x++ ) {
        $row_idname = 'row-'.$x;
?>

        <tr class="inmate-row" id="<?php echo $row_idname; ?>">

                <td><?php echo $peopleArr[$x]['nl']; ?></td>

                <td><?php echo $peopleArr[$x]['nf']; ?></td>

                <td><?php echo $peopleArr[$x]['nm']; ?></td>

                <td><?php echo $peopleArr[$x]['suffix']; ?></td>

                <!--<td><?php //echo $peopleArr[$x]['dob'];
							?><!--</td>-->

                <td><?php echo $peopleArr[$x]['race']; ?></td>

                <td><?php echo $peopleArr[$x]['sex']; ?></td>

               <td><?php echo $peopleArr[$x]['dtin'];
					?></td>

        </tr>
<!-- Details rows -->

<tr class="detail-row" id="details-<?php echo $row_idname; ?>">

                <td colspan="8" style="padding: 0;">

                        <table border="0" class="details" style="margin: 0;">

                                <tr>

                                        <td>

                                                <table border="0" class="vitals">

<!---                                                    <tr>

                                                                <th>Street Address:</th>

                                                                <td><?php //echo $peopleArr[$x]['street'];
																		?> <!--</td>

                                                        </tr> -->

                                                        <tr>

                                                                <th>City/State/Zip:</th>

                                                                <td><?php echo $peopleArr[$x]['csz']; ?></td>

                                                        </tr>

                                                        <tr>

                                                                <th>Race / Gender:</th>

                                                                <td><?php echo $peopleArr[$x]['racegend']; ?></td>

                                                        </tr>

                                                        <tr>

                                                                <th>Age:</th>

                                                                <td><?php echo age_from_birthday($peopleArr[$x]['dob']); ?></td>

                                                        </tr>

                                                        <tr>

                                                                <th>Height:</th>

                                                                <td><?php echo $peopleArr[$x]['ht']; ?></td>

                                                        </tr>

                                                        <tr>

                                                                <th>Weight:</th>

                                                                <td><?php echo $peopleArr[$x]['wt']; ?></td>

                                                        </tr>
                                                </table>
                                        </td>
                                        <td class="pic">

<?php
//$img_hdr = get_headers($peopleArr[$x]['src']);
//echo testArray($img_hdr);
//echo $peopleArr[$x]['src'].'<br/>';
?>
                                                <!--- <img src="<?php //echo $peopleArr[$x]['src'];
																	?><!--"/> -->
                                        </td>
                                </tr>
                                <tr>
                                        <td colspan="2">

                                                <table border="1" class="extra-vitals">

                                                        <tr>

                                                                <th width="110">Booking&nbsp;Number:</th>

                                                                <td><?php echo $peopleArr[$x]['nn']; ?></td>

                                                                <th style="text-align: right;">Booking&nbsp;Date:</th>

                                                                <td><?php echo preg_replace('/[^0-9-]/', '', $peopleArr[$x]['dtin']).'&nbsp;'.preg_replace('/:00$/', '', $peopleArr[$x]['tmin']); ?></td>

                                                                <td width="40%">&nbsp;</td>

                                                        </tr>

                                                </table>

                                        </td>

                                </tr>

                                <tr>

                                        <td colspan="2">

                                                <table class="offenses" border="1">

                                                        <tr class="offense-list">

                                                                <th>Statute</th>

                                                                <th>Offense</th>

                                                                <th>Court</th>

                                                                <th>Warrant</th>

                                                                <th>Bond</th>

                                                        </tr>

<?php

        $arrestsArr = $inmateData->getInmateArrests($link, $peopleArr[$x]['nn']);

        $arresetsmax = count($arrestsArr);

        for ( $y = 0; $y < $arresetsmax; $y++ ) {

                $offensemax = count($arrestsArr[$y]['offenses']);

                for ( $z = 0; $z < $offensemax; $z++ ) {

                        $bond_amount = $arrestsArr[$y]['offenses'][$z]['ob'];
                        if ( $bond_amount < 1 ) {

                                $bond_amount = 'n/a';

                        } else {

                                $bond_amount = money_format('%i', $arrestsArr[$y]['offenses'][$z]['ob']);
                        }

?>
                                                        <tr class="arrest">

                                                                <td><?php echo $arrestsArr[$y]['offenses'][$z]['os']; ?></td>

                                                                <td><?php echo $arrestsArr[$y]['offenses'][$z]['ol']; ?></td>

                                                                <td><?php echo $arrestsArr[$y]['offenses'][$z]['oc']; ?></td>

                                                                <td><?php echo $arrestsArr[$y]['offenses'][$z]['ow']; ?></td>

                                                                <td><?php echo $bond_amount; ?></td>

                                                        </tr>

<?php
                }
        }
?>
                                                </table>
                                        </td>
                                </tr>
</table>
                </td>
        </tr>


<?php
	} // end loop
?>

</table>

<script src="https://lookup.fayettesheriff.org/inmates.js" type="text/javascript"></script>

	</body>
</html>
