<?php
require_once('ajax_auth.inc.php');
require_once('../../includes/class.shorturl.php');
require_once('../../includes/functions.inc.php');
$db = Database::getDatabase();

$results		= (int)$_REQUEST['results'];
$startIndex		= (int)$_REQUEST['startIndex'];
$sort			= $_REQUEST['sort']?$_REQUEST['sort']:"dateCreated";
$dir			= $_REQUEST['dir']?$_REQUEST['dir']:"desc";
$filter			= $_REQUEST['filter']?$_REQUEST['filter']:"";
$filterDisabled		= $_REQUEST['filterDisabled']?$_REQUEST['filterDisabled']:"true";

$sqlClause = "WHERE 1=1 ";
if($filter)
{
	$filter		= $db->escape($filter);
	$sqlClause .= "AND (status = '".$filter."' OR ";
	$sqlClause .= "CONCAT('".WEB_ROOT."/".SHORT_URL_PREFIX."', shortUrl) LIKE '%".$filter."%' OR ";
	$sqlClause .= "originalUrl LIKE '%".$filter."%' OR ";
	$sqlClause .= "createdIp LIKE '%".$filter."%' OR ";
	$sqlClause .= "id = '".$filter."')";
}

if($filterDisabled == "false")
{
    $sqlClause .= " AND status = 'active'";
}

$totalRS 	= $db->getRows("SELECT id FROM shorturl ".$sqlClause);
$limitedRS	= $db->getRows("SELECT * FROM shorturl ".$sqlClause." ORDER BY ".$sort." ".$dir." LIMIT ".$startIndex.", ".$results);

$resultArr = array();
$resultArr["totalRecords"] 			= COUNT($totalRS);
$resultArr["startIndex"] 			= $startIndex;
$resultArr["sort"] 					= $sort;
$resultArr["dir"] 					= $dir;
$resultArr["totalResultsReturned"] 	= 10;
$resultArr["firstResultPosition"] 	= 1;
$resultArr["records"]				= array();

if(COUNT($limitedRS) > 0)
{
	foreach($limitedRS AS $row)
	{
		$resultArr["records"][] 	= array("shortUrl"=>WEB_ROOT."/".SHORT_URL_PREFIX.$row['shortUrl'], "fullUrl"=>$row['originalUrl'], "dateCreated"=>dater($row['dateCreated']), "visits"=>(int)$row['visits'], "createdIp"=>$row['createdIP'], "lastAccessed"=>dater($row['lastAccessed']), "status"=>$row['status'], "id"=>$row['id']);
	}
}

echo json_encode($resultArr);
?>