<?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 for DB fields
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
    $emailEnc   = $_POST['Email'] ?? '';
    $apiKeyEnc  = $_POST['API_Key'] ?? '';

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

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

    if (empty($emailPlain)) {
        throw new Exception("Email required");
    }

    // Step 5: Search DB for matching Gmail
    $stmt = $conn->prepare("SELECT Gmail, Passowrd FROM User_Database");
    $stmt->execute();
    $result = $stmt->get_result();

    $foundPassword = null;

    while ($row = $result->fetch_assoc()) {
        $dbEmailPlain = decryptSensitive($row['Gmail'], $GLOBALS['PRIVATE_KEY']);
        if ($dbEmailPlain === $emailPlain) {
            $foundPassword = decryptSensitive($row['Passowrd'], $GLOBALS['PRIVATE_KEY']);
            break;
        }
    }
    $stmt->close();

    if ($foundPassword) {
        $response = ["status" => "success", "password" => $foundPassword];
    } else {
        throw new Exception("Email not found");
    }

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

echo json_encode($response);
?>
