<?php
include '../config/db.php';
header('Content-Type: application/json');

// Security: Check if Admin is logged in (Basic Session Check)
// session_start();
// if(!isset($_SESSION['admin_logged_in'])) { die(json_encode(["status"=>"error", "message"=>"Unauthorized"])); }

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    
    $wallet = $_POST['wallet'];
    $amount = $_POST['amount'];

    // 1. Validate Input
    if (empty($wallet) || empty($amount)) {
        echo json_encode(["status" => "error", "message" => "Wallet and Amount are required"]);
        exit;
    }

    // 2. Check if User Exists
    $checkUser = $conn->prepare("SELECT id FROM users WHERE wallet = ?");
    $checkUser->bind_param("s", $wallet);
    $checkUser->execute();
    $result = $checkUser->get_result();

    if ($result->num_rows > 0) {
        $user = $result->fetch_assoc();
        $userId = $user['id'];

        // 3. Insert into DEPOSITS Table (Status = 'success')
        // TxHash me hum 'Manual_By_Admin' likhenge taaki pehchan sakein
        $txHash = "Manual_Admin_" . time();
        
        $stmt = $conn->prepare("INSERT INTO deposits (user_id, wallet, amount, status, tx_hash) VALUES (?, ?, ?, 'success', ?)");
        $stmt->bind_param("isds", $userId, $wallet, $amount, $txHash);

        if ($stmt->execute()) {
            
            // OPTIONAL: Agar Users table me 'total_investment' column alag se hai to update karein
            // $conn->query("UPDATE users SET total_investment = total_investment + $amount WHERE id = $userId");

            echo json_encode(["status" => "success", "message" => "Investment Added Successfully!"]);
        } else {
            echo json_encode(["status" => "error", "message" => "Database Error"]);
        }

    } else {
        echo json_encode(["status" => "error", "message" => "User Wallet Not Found!"]);
    }

} else {
    echo json_encode(["status" => "error", "message" => "Invalid Request"]);
}
?>