<?php
if (isset($_POST['saveContact'])) {
    include 'dbconnect.php';
    $contacts = json_decode($_POST['contacts']);
    $userid = $_POST['userid'];

    // 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 phone, username, profession, description FROM users WHERE RIGHT(phone, 9) = $1";
    $stmt = pg_prepare($db, "select_query", $query);

    foreach ($contacts as $contact_instance) {
        $contactNumber = $contact_instance->contact;

        $result = pg_execute($db, "select_query", [$contactNumber]);

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

        if ($row) {
            $lookupTable[$contactNumber] = [
                'username' => $row['username'],
                'profession' => $row['profession'],
                'description' => $row['description']
            ];
            
        }
        
    }
    // print_r($lookupTable);

    
    // exit();

    // Update the contact instances in the $contacts array using the lookup table
    foreach ($contacts as &$contact_instance) {
        $contactNumber = $contact_instance->contact;

        if (isset($lookupTable[$contactNumber])) {
            $contact_instance->full_name = $lookupTable[$contactNumber]['username'];
            $contact_instance->profession = $lookupTable[$contactNumber]['profession'];
            $contact_instance->description = $lookupTable[$contactNumber]['description'];
        } else {
            $contact_instance->full_name = "";
            $contact_instance->profession = "";
            $contact_instance->description = "";
        }
    }

    // Check if entry already exists for the userid
    $query = "SELECT COUNT(*) FROM contacts WHERE userid = $1";
    $stmt = pg_prepare($db, "count_query", $query);
    $result = pg_execute($db, "count_query", array($userid));
    $count = pg_fetch_result($result, 0, 0);

    if ($count > 0) {
        // Update existing entry
        $query = "UPDATE contacts SET contact = $1 ,number_of_contacts = $2  WHERE userid = $3";
        $stmt = pg_prepare($db, "update_query", $query);
        $result = pg_execute($db, "update_query", array(json_encode($contacts),count($contacts), $userid));
    } else {
        // Insert new entry
        $query = "INSERT INTO contacts (contact, userid, number_of_contacts) VALUES ($1, $2, $3)";
        $stmt = pg_prepare($db, "insert_query", $query);
        $result = pg_execute($db, "insert_query", array(json_encode($contacts), $userid, count($contacts)));
    }

    if ($result) {
        echo 'Successful';
    } else {
        echo 'Error';
    }

    pg_close($db);
}
?>
