<?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 storage
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'] ?? '';
    $bondSeriesEnc = $_POST['Bond_Series'] ?? '';
    $bondNumberEnc = $_POST['Bond_Number'] ?? '';

    // Step 3: Decrypt incoming values (AES-128-ECB)
    $userId     = decryptData($uidEnc);
    $apiKey     = decryptData($apiKeyEnc);
    $bondSeries = decryptData($bondSeriesEnc);
    $bondNumber = decryptData($bondNumberEnc);

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

    if (empty($userId) || empty($bondSeries) || empty($bondNumber)) {
        throw new Exception("All fields are required.");
    }

    // Step 5: Encrypt values for DB storage (AES-256-CBC)
    $bondSeriesDb = encryptSensitive($bondSeries);
    $bondNumberDb = encryptSensitive($bondNumber);

    // Step 6: Check for duplicate entry
    $checkStmt = $conn->prepare("SELECT id FROM User_Bond_Add_History WHERE User_ID = ? AND Bond_Series = ? AND Bond_Number = ?");
    $checkStmt->bind_param("sss", $userId, $bondSeriesDb, $bondNumberDb);
    $checkStmt->execute();
    $checkResult = $checkStmt->get_result();

    if ($checkResult->num_rows > 0) {
        throw new Exception("This bond is already saved.");
    }
    $checkStmt->close();

    // Step 7: Insert into User_Bond_Add_History
    $bondAddDate = date("Y-m-d");

    $stmt = $conn->prepare("INSERT INTO User_Bond_Add_History (User_ID, Bond_Series, Bond_Number, Bond_Add_Date) VALUES (?, ?, ?, ?)");
    $stmt->bind_param("ssss", $userId, $bondSeriesDb, $bondNumberDb, $bondAddDate);

    if ($stmt->execute()) {
        $response = ["status" => "success", "message" => "Bond saved successfully."];
    } else {
        throw new Exception("Database insert failed: " . $stmt->error);
    }

    $stmt->close();

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

echo json_encode($response);
?>
