<?php

    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 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['phone']] = $row['token'];
        }

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

        // 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);
    }

?>
