<?php
header('Content-Type: application/json; charset=utf-8');

// Step 1: Include DB connection and helpers
include 'connection.php';
include '/home/screensh/private/encryption_helper.php'; // AES-256-CBC encrypt/decrypt
include '/home/screensh/private/privet_key.php';        // secret key
include 'decrypt_and_validate.php';                     // AES-128-ECB decrypt for Android input

$response = [];

try {
    // Step 2: Read encrypted POST data
    $uidEnc    = $_POST['User_Id'] ?? '';
    $apiKeyEnc = $_POST['API_Key'] ?? '';
    $name      = $_POST['Name'] ?? '';
    $emailEnc  = $_POST['Email'] ?? '';
    $phoneEnc  = $_POST['Phone_Number'] ?? '';

    // Step 3: Decrypt incoming values (AES-128-ECB)
    $userId = decryptData($uidEnc);
    $apiKey = decryptData($apiKeyEnc);
    $emailPlain = decryptData($emailEnc);
    $phonePlain = decryptData($phoneEnc);

    // Step 4: Validate API key
    $validation = validateApiKey($apiKey);
    if (!$validation['status']) {
        throw new Exception($validation['message']);
    }

    if (empty($userId) || empty($name) || empty($emailPlain) || empty($phonePlain)) {
        throw new Exception("All fields are required.");
    }

    // Step 5: Encrypt values for DB storage (AES-256-CBC)
    $emailDb = encryptSensitive($emailPlain);
    $phoneDb = encryptSensitive($phonePlain);

    // Step 6: Update user record
    $stmt = $conn->prepare("UPDATE User_Database SET Name = ?, Gmail = ?, Phone = ? WHERE id = ?");
    $stmt->bind_param("ssss", $name, $emailDb, $phoneDb, $userId);

    if ($stmt->execute()) {
        if ($stmt->affected_rows > 0) {
            $response = ["status" => "success", "message" => "Profile updated successfully."];
        } else {
            throw new Exception("No changes made or user not found.");
        }
    } else {
        throw new Exception("Update failed: " . $stmt->error);
    }

    $stmt->close();

} catch (Exception $e) {
    $response = ["status" => "error", "message" => $e->getMessage()];
} finally {
    $conn->close();
}

// Step 7: Return JSON response
echo json_encode($response);
?>
