<?php
include 'dbconnect.php';
if ($_FILES['file']['name']) {
    
    // File upload is present
    $fileName = $_FILES['file']['name'];
    $fileTmpPath = $_FILES['file']['tmp_name'];
    $fileSize = $_FILES['file']['size'];
    $fileType = $_FILES['file']['type'];
    $fileError = $_FILES['file']['error'];
    $userid = $_POST['account_user'];
    $userid = substr($userid, -9);
    

    // Define the target directory and path to save the file
    $targetDirectory = 'profiles/';
    $targetPath = $targetDirectory . $fileName;

    // Move the uploaded file to the target directory
    if (move_uploaded_file($fileTmpPath, $targetPath)) {
        // File uploaded successfully
         $result = array(
            'success' => true,
            'message' => 'Profile Updated.'
        );
    
tryUpdateUserProfile($db, $targetPath,$userid);
} else {
        // Failed to move the uploaded file
        $result = array(
            'success' => false,
            'message' => 'Failed to upload the file.'
        );
        echo json_encode($result);
        exit;
    }

}



    function tryUpdateUserProfile($db, $targetPath,$userid)
{
$stmt = pg_prepare($db, "update_profile", 'UPDATE reg_contacts SET profile = $1 WHERE iphone = $2');
$result = pg_execute($db, "update_profile", array($targetPath, $userid));
$affectedRows = pg_affected_rows($result);
    
    if ($affectedRows > 0) {
        $response = array('success' => true, 'message' => 'Successfully updated details');
    } else {
        $response = array('success' => false);
    }
    
    
    
    
    $stmt = pg_prepare($db, "update_profile", 'UPDATE users SET profile = $1 WHERE RIGHT(phone, 9) = $2');
$result = pg_execute($db, "update_profile", array($targetPath, $userid));
$affectedRows = pg_affected_rows($result);
    
    if ($affectedRows > 0) {
        $response = array('success' => true, 'message' => 'Successfully updated details');
    } else {
        $response = array('success' => false);
    }
      echo json_encode($response);
}
?>