<?php
if(!isset($_SESSION)) session_start();
require_once 'sqlUtils.php';
$connection = sqlCreateConnection("logoff");
$username = $_SESSION['username'] ?? null;
if(!empty($username)){
    resetSavedSearchTables($connection, $username);
    remove_temp_saved_search($connection, $username);
}
sqlClose($connection, "logoff");
$_SESSION["loggedIn"] = "no";
$_SESSION["username"] = "";
echo json_encode(array("status" =>"ok"));
return;

function resetSavedSearchTables($connection, $username){
    $isRunning_sql = "UPDATE savedsearch SET isrunning=0 WHERE username='$username'";
    sqlQuery($connection, $isRunning_sql);
}

function remove_temp_saved_search($connection, $username){
    $sql = "SELECT id FROM savedsearch WHERE name LIKE ('lastsearch%') AND username='$username'";
    $res = sqlQuery($connection, $sql);
 
    while ($obj = $res->fetch_object()){
        $remove_sql = "DELETE FROM savedsearchid WHERE id = $obj->id";
        sqlQuery($connection, $remove_sql);
    }
    
    $remove_sql = "DELETE FROM savedsearch WHERE name LIKE ('lastsearch%') AND username='$username'";
    sqlQuery($connection, $remove_sql);
}
?>