<?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 decrypt for DB fields
include '/home/screensh/private/privet_key.php';        // secret key
include 'decrypt_and_validate.php';                     // AES-128-ECB decrypt for Android input

try {
    // Step 2: Read encrypted POST data
    $uidEnc    = $_POST['User_Id'] ?? '';
    $apiKeyEnc = $_POST['API_Key'] ?? '';

    // Step 3: Decrypt incoming values (AES-128-ECB)
    $userId = decryptData($uidEnc);   // from decrypt_and_validate.php
    $apiKey = decryptData($apiKeyEnc);

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

    if (empty($userId)) {
        throw new Exception("User ID required");
    }

    // Step 5: Query DB
    $sql = "SELECT Name, Gmail, Phone FROM User_Database WHERE id = ?";
    $stmt = $conn->prepare($sql);
    $stmt->bind_param("s", $userId);
    $stmt->execute();
    $result = $stmt->get_result();

    if ($row = $result->fetch_assoc()) {
        // Step 6: Decrypt Gmail and Phone from DB (AES-256-CBC)
        $decryptedEmail = decryptSensitive($row['Gmail'], $GLOBALS['PRIVATE_KEY']);
        $decryptedPhone = decryptSensitive($row['Phone'], $GLOBALS['PRIVATE_KEY']);

        echo json_encode([
            "status" => "success",
            "data" => [
                "Name"  => $row['Name'],
                "Email" => $decryptedEmail,
                "Phone" => $decryptedPhone
            ]
        ]);
    } else {
        throw new Exception("User not found");
    }

} catch (Exception $e) {
    echo json_encode([
        "status" => "error",
        "message" => $e->getMessage()
    ]);
}
?>
