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

include 'connection.php';
include '/home/screensh/private/encryption_helper.php'; // AES-256-CBC decrypt
include '/home/screensh/private/privet_key.php';
include 'decrypt_and_validate.php';                     // AES-128-ECB decrypt for Android input

$response = [];

try {
    $uidEnc    = $_POST['User_Id'] ?? '';
    $apiKeyEnc = $_POST['API_Key'] ?? '';
    $type      = $_POST['Feedback_Type'] ?? '';
    $comment   = $_POST['Comment'] ?? '';

    // Decrypt both
    $userId = decryptData($uidEnc);
    $apiKey = decryptData($apiKeyEnc);

    // Validate API key
    $validation = validateApiKey($apiKey);
    if (!$validation['status']) {
        throw new Exception($validation['message']);
    }
    if (empty($userId)) {
        throw new Exception("User ID required");
    }

    if (empty($type)) {
        throw new Exception("Feedback type required");
    }

    // Insert feedback
    $stmt = $conn->prepare("INSERT INTO User_Feed_Back (User_ID, Feedback_Type, Comment, Date) 
                            VALUES (?, ?, ?, NOW())");
    $stmt->bind_param("sss", $userId, $type, $comment);

    if ($stmt->execute()) {
        $response = ["status" => "success", "message" => "Feedback submitted"];
    } else {
        throw new Exception("Insert failed: " . $stmt->error);
    }

    $stmt->close();

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

echo json_encode($response);
?>
