<?php
session_start();
require_once '../../config/database.php';
require_once '../includes/auth_check.php';

// Check if admin is logged in
if (!isset($_SESSION['admin_id'])) {
    echo json_encode(['success' => false, 'message' => 'Unauthorized']);
    exit();
}

$database = new Database();
$db = $database->getConnection();
$action = $_POST['action'] ?? '';

if ($action == 'add') {
    $currency = $_POST['currency'];
    $wallet_address = $_POST['wallet_address'];
    $network = $_POST['network'] ?? null;
    
    try {
        $stmt = $db->prepare("INSERT INTO crypto_wallets (currency, wallet_address, network) VALUES (?, ?, ?)");
        $stmt->execute([$currency, $wallet_address, $network]);
        echo json_encode(['success' => true]);
    } catch (PDOException $e) {
        echo json_encode(['success' => false, 'message' => 'An error occurred: ' . $e->getMessage()]);
    }
} elseif ($action == 'update') {
    $wallet_id = $_POST['wallet_id'];
    $wallet_address = $_POST['wallet_address'];
    $network = $_POST['network'] ?? null;
    $is_active = $_POST['is_active'];
    
    try {
        $stmt = $db->prepare("UPDATE crypto_wallets SET wallet_address = ?, network = ?, is_active = ? WHERE id = ?");
        $stmt->execute([$wallet_address, $network, $is_active, $wallet_id]);
        echo json_encode(['success' => true]);
    } catch (PDOException $e) {
        echo json_encode(['success' => false, 'message' => 'An error occurred: ' . $e->getMessage()]);
    }
} elseif ($action == 'delete') {
    $wallet_id = $_POST['wallet_id'];
    
    try {
        $stmt = $db->prepare("DELETE FROM crypto_wallets WHERE id = ?");
        $stmt->execute([$wallet_id]);
        echo json_encode(['success' => true]);
    } catch (PDOException $e) {
        echo json_encode(['success' => false, 'message' => 'An error occurred: ' . $e->getMessage()]);
    }
} elseif ($action == 'save_instructions') {
    $btc_instructions = $_POST['btc_instructions'];
    $usdt_instructions = $_POST['usdt_instructions'];
    
    try {
        // Save BTC instructions
        $stmt = $db->prepare("INSERT INTO settings (setting_key, setting_value) VALUES ('btc_deposit_instructions', ?) 
                             ON DUPLICATE KEY UPDATE setting_value = ?");
        $stmt->execute([$btc_instructions, $btc_instructions]);
        
        // Save USDT instructions
        $stmt = $db->prepare("INSERT INTO settings (setting_key, setting_value) VALUES ('usdt_deposit_instructions', ?) 
                             ON DUPLICATE KEY UPDATE setting_value = ?");
        $stmt->execute([$usdt_instructions, $usdt_instructions]);
        
        echo json_encode(['success' => true]);
    } catch (PDOException $e) {
        echo json_encode(['success' => false, 'message' => 'An error occurred: ' . $e->getMessage()]);
    }
} else {
    echo json_encode(['success' => false, 'message' => 'Invalid action']);
}
