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

// Generate a CSRF token for the delete forms
if (empty($_SESSION['csrf_token'])) {
    $_SESSION['csrf_token'] = bin2hex(random_bytes(32));
}

$page = 'crypto_settings';
$database = new Database();
$db = $database->getConnection();

// --- Helper function to check if a table exists ---
function tableExists($db, $tableName) {
    try {
        $result = $db->query("SELECT 1 FROM `$tableName` LIMIT 1");
        return $result !== false;
    } catch (Exception $e) { return false; }
}

// Auto-create tables if they don't exist
if (!tableExists($db, 'crypto_wallets')) {
    $db->exec("CREATE TABLE crypto_wallets (id INT AUTO_INCREMENT PRIMARY KEY, currency VARCHAR(20) NOT NULL, wallet_address VARCHAR(255) NOT NULL, network VARCHAR(50) DEFAULT NULL, is_active BOOLEAN DEFAULT TRUE, created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP)");
}
if (!tableExists($db, 'settings')) {
    $db->exec("CREATE TABLE settings (id INT AUTO_INCREMENT PRIMARY KEY, setting_key VARCHAR(100) NOT NULL UNIQUE, setting_value TEXT, created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP)");
    $db->exec("INSERT INTO settings (setting_key, setting_value) VALUES ('btc_deposit_instructions', 'Default BTC instructions.'), ('usdt_deposit_instructions', 'Default USDT instructions.') ON DUPLICATE KEY UPDATE setting_key=setting_key;");
}

// Handle form submissions
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // CSRF Token validation for all POST actions
    if (!isset($_POST['csrf_token']) || !hash_equals($_SESSION['csrf_token'], $_POST['csrf_token'])) {
        $_SESSION['error'] = "Invalid CSRF token. Action denied.";
        header("Location: crypto_settings.php");
        exit();
    }

    if (isset($_POST['add_wallet'])) {
        $stmt = $db->prepare("INSERT INTO crypto_wallets (currency, wallet_address, network) VALUES (?, ?, ?)");
        $stmt->execute([$_POST['currency'], $_POST['wallet_address'], $_POST['network'] ?? null]);
        $_SESSION['success'] = "Wallet added successfully.";
    }
    elseif (isset($_POST['update_wallet'])) {
        $stmt = $db->prepare("UPDATE crypto_wallets SET wallet_address = ?, network = ?, is_active = ? WHERE id = ?");
        $stmt->execute([$_POST['wallet_address'], $_POST['network'] ?? null, isset($_POST['is_active']) ? 1 : 0, $_POST['wallet_id']]);
        $_SESSION['success'] = "Wallet updated successfully.";
    }
    elseif (isset($_POST['delete_wallet'])) {
        $stmt = $db->prepare("DELETE FROM crypto_wallets WHERE id = ?");
        $stmt->execute([$_POST['wallet_id']]);
        $_SESSION['success'] = "Wallet deleted successfully.";
    }
    elseif (isset($_POST['save_instructions'])) {
        $stmt = $db->prepare("INSERT INTO settings (setting_key, setting_value) VALUES ('btc_deposit_instructions', ?) ON DUPLICATE KEY UPDATE setting_value = VALUES(setting_value)");
        $stmt->execute([$_POST['btc_instructions']]);
        $stmt = $db->prepare("INSERT INTO settings (setting_key, setting_value) VALUES ('usdt_deposit_instructions', ?) ON DUPLICATE KEY UPDATE setting_value = VALUES(setting_value)");
        $stmt->execute([$_POST['usdt_instructions']]);
        $_SESSION['success'] = "Deposit instructions saved successfully.";
    }
    
    header("Location: crypto_settings.php");
    exit();
}

// Get wallet to edit if edit_id is set
$edit_wallet = null;
if (isset($_GET['edit_id'])) {
    $stmt = $db->prepare("SELECT * FROM crypto_wallets WHERE id = ?");
    $stmt->execute([$_GET['edit_id']]);
    $edit_wallet = $stmt->fetch(PDO::FETCH_ASSOC);
}

// Get all wallet addresses
$stmt = $db->query("SELECT * FROM crypto_wallets ORDER BY currency, network");
$wallets = $stmt->fetchAll(PDO::FETCH_ASSOC);

// Get deposit instructions
$stmt = $db->query("SELECT setting_key, setting_value FROM settings WHERE setting_key IN ('btc_deposit_instructions', 'usdt_deposit_instructions')");
$instructionsData = $stmt->fetchAll(PDO::FETCH_KEY_PAIR);
$btc_instructions = $instructionsData['btc_deposit_instructions'] ?? '';
$usdt_instructions = $instructionsData['usdt_deposit_instructions'] ?? '';

include 'includes/header.php';
?>

<div class="content-wrapper">
    <div class="container-fluid">
        <div class="page-header">
            <h1 class="page-header-title">Crypto Wallet Settings</h1>
            <p class="text-muted">Configure cryptocurrency wallet addresses for customer deposits.</p>
        </div>

        <!-- Display any success/error messages -->
        <?php if (isset($_SESSION['success'])): ?><div class="alert alert-success alert-dismissible fade show" role="alert"><?php echo $_SESSION['success']; unset($_SESSION['success']); ?><button type="button" class="btn-close" data-bs-dismiss="alert"></button></div><?php endif; ?>
        <?php if (isset($_SESSION['error'])): ?><div class="alert alert-danger alert-dismissible fade show" role="alert"><?php echo $_SESSION['error']; unset($_SESSION['error']); ?><button type="button" class="btn-close" data-bs-dismiss="alert"></button></div><?php endif; ?>

        <div class="row">
            <!-- Left Column: Add/Edit Form -->
            <div class="col-lg-4">
                <div class="card shadow mb-4">
                    <div class="card-header"><h6 class="m-0 font-weight-bold text-primary"><?php echo $edit_wallet ? 'Edit Wallet' : 'Add New Wallet'; ?></h6></div>
                    <div class="card-body">
                        <form method="post" action="crypto_settings.php">
                            <input type="hidden" name="csrf_token" value="<?php echo htmlspecialchars($_SESSION['csrf_token']); ?>">
                            <?php if ($edit_wallet): ?>
                                <input type="hidden" name="wallet_id" value="<?php echo $edit_wallet['id']; ?>">
                            <?php endif; ?>

                            <div class="mb-3">
                                <label for="currency" class="form-label">Currency</label>
                                <select class="form-select" id="currency" name="currency" required <?php if ($edit_wallet) echo 'disabled'; ?>>
                                    <option value="BTC" <?php if (($edit_wallet['currency'] ?? '') === 'BTC') echo 'selected'; ?>>Bitcoin (BTC)</option>
                                    <option value="USDT" <?php if (($edit_wallet['currency'] ?? '') === 'USDT') echo 'selected'; ?>>Tether (USDT)</option>
                                </select>
                            </div>
                            <div class="mb-3">
                                <label for="wallet_address" class="form-label">Wallet Address</label>
                                <input type="text" class="form-control" id="wallet_address" name="wallet_address" value="<?php echo htmlspecialchars($edit_wallet['wallet_address'] ?? ''); ?>" required>
                            </div>
                            <div class="mb-3" id="network_group" style="display: <?php echo ($edit_wallet['currency'] ?? 'BTC') === 'USDT' ? 'block' : 'none'; ?>;">
                                <label for="network" class="form-label">Network (for USDT)</label>
                                <select class="form-select" id="network" name="network">
                                    <option value="">Select Network</option>
                                    <option value="ERC20" <?php if (($edit_wallet['network'] ?? '') === 'ERC20') echo 'selected'; ?>>ERC20 (Ethereum)</option>
                                    <option value="TRC20" <?php if (($edit_wallet['network'] ?? '') === 'TRC20') echo 'selected'; ?>>TRC20 (Tron)</option>
                                    <option value="BEP20" <?php if (($edit_wallet['network'] ?? '') === 'BEP20') echo 'selected'; ?>>BEP20 (Binance Smart Chain)</option>
                                </select>
                            </div>
                            <?php if ($edit_wallet): ?>
                                <div class="form-check form-switch mb-3">
                                    <input class="form-check-input" type="checkbox" id="is_active" name="is_active" <?php echo ($edit_wallet['is_active'] ?? 0) ? 'checked' : ''; ?>>
                                    <label class="form-check-label" for="is_active">Wallet is Active</label>
                                </div>
                            <?php endif; ?>
                            
                            <div class="d-grid gap-2">
                                <button type="submit" name="<?php echo $edit_wallet ? 'update_wallet' : 'add_wallet'; ?>" class="btn btn-primary"><?php echo $edit_wallet ? 'Save Changes' : 'Add Wallet'; ?></button>
                                <?php if ($edit_wallet): ?>
                                    <a href="crypto_settings.php" class="btn btn-secondary">Cancel Edit</a>
                                <?php endif; ?>
                            </div>
                        </form>
                    </div>
                </div>
            </div>

            <!-- Right Column: Wallets Table & Instructions -->
            <div class="col-lg-8">
                <div class="card shadow mb-4">
                    <div class="card-header"><h6 class="m-0 font-weight-bold text-primary">Configured Wallets</h6></div>
                    <div class="card-body">
                        <div class="table-responsive">
                            <table class="table table-hover" width="100%">
                                <thead class="table-light">
                                    <tr><th>Currency</th><th>Address</th><th>Network</th><th>Status</th><th>Actions</th></tr>
                                </thead>
                                <tbody>
                                    <?php if (empty($wallets)): ?>
                                        <tr><td colspan="5" class="text-center text-muted py-3">No wallets configured.</td></tr>
                                    <?php else: ?>
                                        <?php foreach ($wallets as $wallet): ?>
                                            <tr>
                                                <td><?php echo htmlspecialchars($wallet['currency']); ?></td>
                                                <td class="text-monospace" style="max-width: 200px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap;"><?php echo htmlspecialchars($wallet['wallet_address']); ?></td>
                                                <td><?php echo htmlspecialchars($wallet['network'] ?? 'N/A'); ?></td>
                                                <td><span class="badge bg-<?php echo $wallet['is_active'] ? 'success' : 'secondary'; ?>"><?php echo $wallet['is_active'] ? 'Active' : 'Inactive'; ?></span></td>
                                                <td class="text-center">
                                                    <a href="crypto_settings.php?edit_id=<?php echo $wallet['id']; ?>" class="btn btn-sm btn-warning" title="Edit Wallet"><i class='bx bx-pencil'></i></a>
                                                    <form action="crypto_settings.php" method="POST" class="d-inline" onsubmit="confirmWalletDelete(event, '<?php echo htmlspecialchars(addslashes($wallet['wallet_address'])); ?>');">
                                                        <input type="hidden" name="wallet_id" value="<?php echo $wallet['id']; ?>">
                                                        <input type="hidden" name="csrf_token" value="<?php echo htmlspecialchars($_SESSION['csrf_token']); ?>">
                                                        <button type="submit" name="delete_wallet" class="btn btn-sm btn-danger" title="Delete Wallet"><i class='bx bx-trash'></i></button>
                                                    </form>
                                                </td>
                                            </tr>
                                        <?php endforeach; ?>
                                    <?php endif; ?>
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>

                <div class="card shadow mb-4">
                    <div class="card-header"><h6 class="m-0 font-weight-bold text-primary">Deposit Instructions</h6></div>
                    <div class="card-body">
                        <form method="post" action="crypto_settings.php">
                            <input type="hidden" name="csrf_token" value="<?php echo htmlspecialchars($_SESSION['csrf_token']); ?>">
                            <div class="mb-3">
                                <label for="btc_instructions" class="form-label">Bitcoin (BTC) Instructions</label>
                                <textarea class="form-control" id="btc_instructions" name="btc_instructions" rows="3"><?php echo htmlspecialchars($btc_instructions); ?></textarea>
                            </div>
                            <div class="mb-3">
                                <label for="usdt_instructions" class="form-label">Tether (USDT) Instructions</label>
                                <textarea class="form-control" id="usdt_instructions" name="usdt_instructions" rows="3"><?php echo htmlspecialchars($usdt_instructions); ?></textarea>
                            </div>
                            <button type="submit" name="save_instructions" class="btn btn-primary">Save Instructions</button>
                        </form>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
// Toggle network field based on currency selection
document.getElementById('currency').addEventListener('change', function() {
    const networkGroup = document.getElementById('network_group');
    if (this.value === 'USDT') {
        networkGroup.style.display = 'block';
    } else {
        networkGroup.style.display = 'none';
        document.getElementById('network').value = '';
    }
});

// SweetAlert confirmation for wallet deletion
function confirmWalletDelete(event, walletAddress) {
    event.preventDefault();
    const form = event.target;
    Swal.fire({
        title: 'Are you sure?',
        html: `You are about to delete the wallet: <br><b>${walletAddress}</b>.<br><br><strong class='text-danger'>This action cannot be undone.</strong>`,
        icon: 'warning',
        showCancelButton: true,
        confirmButtonColor: '#d33',
        cancelButtonColor: '#3085d6',
        confirmButtonText: 'Yes, delete it!'
    }).then((result) => {
        if (result.isConfirmed) {
            form.submit();
        }
    });
}
</script>

<?php include 'includes/footer.php'; ?>
