<?php
if (isset($_POST['search'])) {
    include 'dbconnect.php';
    $searchQuery = $_POST['searchQuery'] ;
    $searchTokens = json_decode($_POST['searchTokens']);

    // Create a lookup table to store the fetched values from the database
    $lookupTable = [];

    // Prepare the SQL query to fetch the matching entries from the database for each contact
    $query = "SELECT contact,number_of_contacts FROM contacts WHERE userid = $1";
    $stmt = pg_prepare($db, "select_query", $query);

    foreach ($searchTokens as $searchTokenInstance) {
        $result = pg_execute($db, "select_query", [$searchTokenInstance]);

        // Fetch the row for the current contact from the database
        $row = pg_fetch_assoc($result);

        if ($row) {
             $lookUpInstance = array(
            'searchToken' =>$searchTokenInstance,
            'number_of_contacts' => $row['number_of_contacts'],
            'contacts'=>$row['contact']
        );
            
            $lookupTable[] = $lookUpInstance;
        }
    }
   
    if ($result) {
        echo json_encode($lookupTable);
    } else {
        echo 'Error';
    }

    pg_close($db);
}
?>
