<?php
header("Content-Type: application/json");
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: POST");
header("Access-Control-Allow-Headers: Content-Type");

require_once 'config.php';

$conn = getDbConnection();
$data = json_decode(file_get_contents("php://input"));

if (isset($data->token) && isset($data->embedding)) {
    $user_token = $data->token;
    $new_embedding = $data->embedding;  // JSON array of 128 floats from the app

    // Retrieve stored facial embedding
    $stmt = $conn->prepare("SELECT facial_embedding FROM user_facial_data WHERE user_token = ?");
    $stmt->bind_param("s", $user_token);
    $stmt->execute();
    $stmt->bind_result($stored_embedding_json);
    $stmt->fetch();
    $stmt->close();

    if ($stored_embedding_json) {
        $stored_embedding = json_decode($stored_embedding_json);

        // Calculate cosine similarity or Euclidean distance between embeddings
        $similarity = cosineSimilarity($stored_embedding, $new_embedding);
        $threshold = 0.4;  // Adjust the threshold based on your model

        if ($similarity >= $threshold) {
            echo json_encode(array("status" => "success", "message" => "Authentication successful"));
        } else {
            echo json_encode(array("status" => "error", "message" => "Authentication failed"));
        }
    } else {
        echo json_encode(array("status" => "error", "message" => "No facial data found for this user"));
    }
} else {
    echo json_encode(array("status" => "error", "message" => "Invalid input"));
}

$conn->close();

// Function to calculate cosine similarity
function cosineSimilarity($vectorA, $vectorB) {
    $dotProduct = 0.0;
    $magnitudeA = 0.0;
    $magnitudeB = 0.0;

    for ($i = 0; $i < count($vectorA); $i++) {
        $dotProduct += $vectorA[$i] * $vectorB[$i];
        $magnitudeA += pow($vectorA[$i], 2);
        $magnitudeB += pow($vectorB[$i], 2);
    }

    $magnitudeA = sqrt($magnitudeA);
    $magnitudeB = sqrt($magnitudeB);

    return ($magnitudeA * $magnitudeB) ? $dotProduct / ($magnitudeA * $magnitudeB) : 0;
}
?>

