<?php

require_once __DIR__ . '/../connect.php';

// Retrieve and sanitize input parameters
$phone  = filterRequest("phone");
$note   = filterRequest("note");
$editor = filterRequest("editor");

// Encrypt the phone number
$encryptedPhone = $encryptionHelper->encryptData($phone);

// SQL query: insert new row OR update existing one if phone already exists
$sql = "INSERT INTO `notesForDriverService` (`phone`, `note`, `editor`) 
        VALUES (:phone, :note, :editor)
        ON DUPLICATE KEY UPDATE 
            `note` = VALUES(`note`),
            `editor` = VALUES(`editor`)";

// Prepare the SQL statement
$stmt = $con->prepare($sql);

// Bind the parameters
$stmt->bindParam(':phone', $encryptedPhone);
$stmt->bindParam(':note', $note);
$stmt->bindParam(':editor', $editor);

// Execute the query
$success = $stmt->execute();

if ($success) {
    if ($stmt->rowCount() > 0) {
        jsonSuccess(null, "Note inserted/updated successfully");
    } else {
        jsonError("No changes were made");
    }
} else {
    jsonError("Database error");
}
?>