<?php

include 'connection.php';

// Get data from POST request
$email = isset($_POST['email']) ? $_POST['email'] : '';
$deviceName = isset($_POST['devicename']) ? $_POST['devicename'] : '';
$token = isset($_POST['token']) ? $_POST['token'] : '';

// Check if the device exists based on the email and deviceName
$sql = "SELECT COUNT(*) FROM user WHERE email = :email AND devicename = :devicename";
$stmt = $conn->prepare($sql);
$stmt->bindParam(':email', $email);
$stmt->bindParam(':devicename', $deviceName);
$stmt->execute();
$deviceExists = $stmt->fetchColumn();

if ($deviceExists > 0) {
    // If the device exists, update the token
    $sql = "UPDATE user SET token = :token WHERE email = :email AND devicename = :devicename";
    $stmt = $conn->prepare($sql);
    $stmt->bindParam(':token', $token);
    $stmt->bindParam(':email', $email);
    $stmt->bindParam(':devicename', $deviceName);

    if ($stmt->execute()) {
        echo "Device token updated successfully";
    } else {
        echo "Error: " . $stmt->errorInfo()[2];
    }
} else {
    // If the device does not exist, insert a new record
    $sql = "INSERT INTO user (email, devicename, token) VALUES (:email, :devicename, :token)";
    $stmt = $conn->prepare($sql);
    $stmt->bindParam(':email', $email);
    $stmt->bindParam(':devicename', $deviceName);
    $stmt->bindParam(':token', $token);

    if ($stmt->execute()) {
        echo "New device inserted successfully";
    } else {
        echo "Error: " . $stmt->errorInfo()[2];
    }
}

?>
