<?php
if (isset($_POST['regContacts'])) {
    include 'dbconnect.php';
    $rawContacts = $_POST['contacts'];
    $rawContacts = json_decode($rawContacts, true);
    $matchingContacts = [];

    $contacts = array_map(function($contact) {
        return substr($contact['contact'], -9);
    }, $rawContacts);

    // Build the comma-separated string of contact values
    $contactString = "'" . implode("','", $contacts) . "'";
    $query = "SELECT phone, token, iphone, search_token,profile FROM reg_contacts WHERE iphone IN ($contactString)";

    // Execute the query
    $result = pg_query($db, $query);

    if ($result) {
        // Fetch the matching contacts from the database and store them in $matchingContacts
        while ($row = pg_fetch_assoc($result)) {
            $matchingContacts[$row['iphone']] = [
                'token' => $row['token'],
                'search_token' => $row['search_token'],
                'profile' =>$row['profile']
            ];
        }

        // Update the 'token' and 'search_token' properties for each filtered contact with the corresponding values from the database
        foreach ($rawContacts as &$contact) {
            if (isset($matchingContacts[$contact['contact']])) {
                $matchingContact = $matchingContacts[$contact['contact']];
                $contact['token'] = $matchingContact['token'];
                $contact['search_token'] = $matchingContact['search_token'];
                $contact['profile'] = $matchingContact['profile'];
            }
        }

        // Filter the original array to only contain elements with matching contacts
        $filteredContacts = array_values(array_filter($rawContacts, function ($element) use ($matchingContacts) {
            return isset($element['token']) && $element['token'] !== '';
        }));

        // Output the filtered array as JSON
        echo json_encode($filteredContacts);
    } else {
        // Query execution failed
        echo "Query execution failed: " . pg_last_error($db);
    }
}
?>