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

if (!isset($_SESSION['user_id'])) {
    echo json_encode(['success' => false, 'message' => 'Unauthorized access.']);
    exit;
}

$userId = $_SESSION['user_id'];
global $pdo;

$data = json_decode(file_get_contents("php://input"), true);
$type = $data['type'] ?? '';

try {
    if ($type === 'bank') {
        $bName = htmlspecialchars($data['bank_name']);
        $accNo = htmlspecialchars($data['account_no']);
        $ifsc = htmlspecialchars($data['ifsc_code']);
        $holder = htmlspecialchars($data['account_holder']);

        // Check if already exists
        $stmt = $pdo->prepare("SELECT id FROM bank_details WHERE user_id = ?");
        $stmt->execute([$userId]);
        if($stmt->rowCount() > 0) {
            $upd = $pdo->prepare("UPDATE bank_details SET bank_name=?, account_no=?, ifsc_code=?, account_holder=? WHERE user_id=?");
            $upd->execute([$bName, $accNo, $ifsc, $holder, $userId]);
        } else {
            $ins = $pdo->prepare("INSERT INTO bank_details (user_id, bank_name, account_no, ifsc_code, account_holder) VALUES (?, ?, ?, ?, ?)");
            $ins->execute([$userId, $bName, $accNo, $ifsc, $holder]);
        }
        echo json_encode(['success' => true, 'message' => 'Bank account saved successfully!']);
    } 
    elseif ($type === 'upi') {
        $upiId = htmlspecialchars($data['upi_id']);
        $stmt = $pdo->prepare("SELECT id FROM upi_details WHERE user_id = ?");
        $stmt->execute([$userId]);
        if($stmt->rowCount() > 0) {
            $upd = $pdo->prepare("UPDATE upi_details SET upi_id=? WHERE user_id=?");
            $upd->execute([$upiId, $userId]);
        } else {
            $ins = $pdo->prepare("INSERT INTO upi_details (user_id, upi_id) VALUES (?, ?)");
            $ins->execute([$userId, $upiId]);
        }
        echo json_encode(['success' => true, 'message' => 'UPI ID saved successfully!']);
    } 
    elseif ($type === 'usdt') {
        $usdtAdd = htmlspecialchars($data['usdt_address']);
        $stmt = $pdo->prepare("SELECT id FROM usdt_details WHERE user_id = ?");
        $stmt->execute([$userId]);
        if($stmt->rowCount() > 0) {
            $upd = $pdo->prepare("UPDATE usdt_details SET usdt_address=? WHERE user_id=?");
            $upd->execute([$usdtAdd, $userId]);
        } else {
            $ins = $pdo->prepare("INSERT INTO usdt_details (user_id, usdt_address) VALUES (?, ?)");
            $ins->execute([$userId, $usdtAdd]);
        }
        echo json_encode(['success' => true, 'message' => 'USDT Address saved successfully!']);
    } else {
        echo json_encode(['success' => false, 'message' => 'Invalid account type.']);
    }
} catch(Exception $e) {
    echo json_encode(['success' => false, 'message' => 'DB Error: ' . $e->getMessage()]);
}
?>