<?php
error_reporting(0);
include 'connect.php';
$json = file_get_contents('php://input');
$objdata = json_decode( $json );
header('Content-Type: application/json; charset=utf-8');
header("Access-Control-Allow-Origin: *");

$function = $objdata->{'function'};

try {

    switch ($function) {
    case 'getpopularsearches':
    $response['result'] = getpopularsearches($db_connection, $objdata);
    break;
    case 'getrecentsearches':
    $response['result'] = getrecentsearches($db_connection, $objdata);
    break;
    case 'addpopularsearches':
    $response['result'] = addpopularsearches($db_connection, $objdata);
    break;

    default:
    # code...
    break;
    }

    $response['message'] = 'Success';
	$response['error'] = false;

} catch (UnexpectedValueException $e) {
	$response['message'] = "Invalid data.";
	$response['error'] = true;
} catch (Exception $e) {
	$response['message'] = "Error";
	$response['error'] = true;
}
echo json_encode($response);

function getpopularsearches($db_connection, $objdata) {

	pg_prepare($db_connection, 'sqlfetchp', '
  SELECT name
  FROM popular_searches
  WHERE name IS NOT NULL
  ORDER BY id DESC
');
$result = pg_execute($db_connection, 'sqlfetchp', array());

$popularsearch = [];
$used = [];

while ($row = pg_fetch_assoc($result)) {
    $name = strtolower(trim($row['name'])); // normalize text
    $name = preg_replace('/[^a-z0-9\s]/i', '', $name); // remove symbols
    $name = preg_replace('/\s+/', ' ', $name); // remove extra spaces

    // skip empty or too-short words
    if (strlen($name) < 6) continue;

    // skip if contains only numbers
    if (preg_match('/^\d+$/', $name)) continue;

    // skip if already added
    if (in_array($name, $used)) continue;

    $obj = new stdClass();
    $obj->name = ucfirst($name);
    $popularsearch[] = $obj;
    $used[] = $name;
}

return $popularsearch;

}

function getrecentsearches($db_connection, $objdata) {
	$user_id = $objdata->{'user_id'};
  $curdate = date('Y-m-d');
	/*pg_prepare($db_connection, 'sqlfetch', 'SELECT DISTINCT ON (name) id, name FROM popular_searches WHERE user_id = $1 ORDER BY name ASC, id DESC');
	$result = pg_execute($db_connection, 'sqlfetch', array($user_id));
	$recentsearch = array();
	while($row = pg_fetch_array($result)){
    $obj = new stdClass();
    $obj->id = (int)$row['id'];
    $obj->name = $row['name'];
    array_push($recentsearch,$obj);
    }
    return $recentsearch;*/
  pg_prepare($db_connection, 'sqlfetchp', '
  SELECT name
  FROM popular_searches
  WHERE user_id = $1 AND name IS NOT NULL
  ORDER BY id DESC
');
$result = pg_execute($db_connection, 'sqlfetchp', array($user_id));

$popularsearch = [];
$used = [];

while ($row = pg_fetch_assoc($result)) {
    $name = strtolower(trim($row['name'])); // normalize text
    $name = preg_replace('/[^a-z0-9\s]/i', '', $name); // remove symbols
    $name = preg_replace('/\s+/', ' ', $name); // remove extra spaces

    // skip empty or too-short words
    if (strlen($name) < 6) continue;

    // skip if contains only numbers
    if (preg_match('/^\d+$/', $name)) continue;

    // skip if already added
    if (in_array($name, $used)) continue;

    $obj = new stdClass();
    $obj->name = ucfirst($name);
    $popularsearch[] = $obj;
    $used[] = $name;
}

return $popularsearch;

}

function addpopularsearches($db_connection, $objdata) {

$name = $objdata->{'value'};
$user_id = $objdata->{'user_id'};
$curdate = date('Y-m-d');


pg_prepare($db_connection,'sqlseq',"SELECT * from popular_searches ORDER BY id DESC LIMIT 1");
$resultkey = pg_execute($db_connection,'sqlseq',array());

if (pg_num_rows($resultkey)==1){
  $rowsq = pg_fetch_array($resultkey);
  $seqid = $rowsq['id'] + 1;
}else{
  $seqid = 1;
}

pg_prepare($db_connection,'sqlins','INSERT INTO popular_searches(id,name,user_id,date) VALUES($1,$2,$3,$4)');
pg_execute($db_connection,'sqlins',array($seqid,$name,$user_id,$curdate ));

}

?>
