<?php
require_once '../functions.php';
requireAdminAuth();

$admin = getCurrentAdmin();
$db = getDB();

$error = '';
$success = '';

// Add wallet
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['add_wallet'])) {
    $coinSymbol = $_POST['coin_symbol'] ?? '';
    $address = trim($_POST['address'] ?? '');
    $network = trim($_POST['network'] ?? '');
    $minDeposit = floatval($_POST['min_deposit'] ?? 0);
    
    $coinNames = [
        'BTC' => 'Bitcoin',
        'ETH' => 'Ethereum',
        'USDT' => 'Tether',
        'LTC' => 'Litecoin',
        'BCH' => 'Bitcoin Cash',
        'DOGE' => 'Dogecoin',
        'ADA' => 'Cardano',
        'SOL' => 'Solana',
        'DOT' => 'Polkadot'
    ];
    $coinName = $coinNames[$coinSymbol] ?? 'Cryptocurrency';

    if (empty($coinSymbol) || empty($address)) {
        $error = 'Please fill in all required fields.';
    } else {
        $stmt = $db->prepare("INSERT INTO crypto_wallets (coin_name, coin_symbol, network, address, min_deposit, is_active) VALUES (?, ?, ?, ?, ?, 1)");
        $stmt->bind_param('ssssd', $coinName, $coinSymbol, $network, $address, $minDeposit);
        if ($stmt->execute()) {
            $success = 'Wallet added successfully!';
        } else {
            $error = 'Failed to add wallet. Database query execution failed.';
        }
    }
}

// Edit wallet
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['edit_wallet'])) {
    $walletId = intval($_POST['wallet_id'] ?? 0);
    $coinSymbol = $_POST['coin_symbol'] ?? '';
    $address = trim($_POST['address'] ?? '');
    $network = trim($_POST['network'] ?? '');
    $minDeposit = floatval($_POST['min_deposit'] ?? 0);
    
    $coinNames = [
        'BTC' => 'Bitcoin',
        'ETH' => 'Ethereum',
        'USDT' => 'Tether',
        'LTC' => 'Litecoin',
        'BCH' => 'Bitcoin Cash',
        'DOGE' => 'Dogecoin',
        'ADA' => 'Cardano',
        'SOL' => 'Solana',
        'DOT' => 'Polkadot'
    ];
    $coinName = $coinNames[$coinSymbol] ?? 'Cryptocurrency';

    if (empty($walletId) || empty($coinSymbol) || empty($address)) {
        $error = 'Please fill in all required fields.';
    } else {
        $stmt = $db->prepare("UPDATE crypto_wallets SET coin_name = ?, coin_symbol = ?, network = ?, address = ?, min_deposit = ? WHERE id = ?");
        $stmt->bind_param('ssssdi', $coinName, $coinSymbol, $network, $address, $minDeposit, $walletId);
        if ($stmt->execute()) {
            $success = 'Wallet updated successfully!';
        } else {
            $error = 'Failed to update wallet. Database query execution failed.';
        }
    }
}

// Toggle wallet status
if (isset($_GET['toggle'])) {
    $walletId = intval($_GET['toggle']);
    $db->query("UPDATE crypto_wallets SET is_active = NOT is_active WHERE id = $walletId");
    header('Location: crypto-wallets.php');
    exit();
}

// Delete wallet
if (isset($_GET['delete'])) {
    $walletId = intval($_GET['delete']);
    $db->query("DELETE FROM crypto_wallets WHERE id = $walletId");
    header('Location: crypto-wallets.php');
    exit();
}

// Fetch wallet for editing
$editWallet = null;
if (isset($_GET['edit'])) {
    $editId = intval($_GET['edit']);
    $stmt = $db->prepare("SELECT * FROM crypto_wallets WHERE id = ?");
    $stmt->bind_param('i', $editId);
    $stmt->execute();
    $result = $stmt->get_result();
    $editWallet = $result->fetch_assoc();
}

// Fetch wallets from database directly
$wallets = $db->query("SELECT * FROM crypto_wallets ORDER BY id DESC");
$flash = getFlash();
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
    <title>Crypto Wallets - <?php echo SITE_NAME; ?></title>
    <link rel="stylesheet" href="../assets/css/style.css">
    <style>
        /* Mobile-first responsive grid */
        .wallet-grid {
            display: grid;
            grid-template-columns: 1fr;
            gap: 16px;
        }
        
        /* Tablet and up: side-by-side layout */
        @media (min-width: 992px) {
            .wallet-grid {
                grid-template-columns: 340px 1fr;
                gap: 24px;
            }
        }
        
        /* Desktop: more space for table */
        @media (min-width: 1200px) {
            .wallet-grid {
                grid-template-columns: 380px 1fr;
            }
        }

        /* Table container with horizontal scroll */
        .table-scroll-wrapper {
            overflow-x: auto;
            -webkit-overflow-scrolling: touch;
            border-radius: 6px;
            border: 1px solid var(--border-color, #e0e0e0);
        }
        
        .table-scroll-wrapper .data-table {
            min-width: 700px;
            margin: 0;
            border: none;
        }

        /* Mobile card view (hidden on desktop) */
        .mobile-wallet-cards {
            display: flex;
            flex-direction: column;
            gap: 12px;
        }
        
        .wallet-card {
            background: var(--card-bg, #fff);
            border: 1px solid var(--border-color, #e0e0e0);
            border-radius: 8px;
            padding: 16px;
            display: flex;
            flex-direction: column;
            gap: 10px;
        }
        
        .wallet-card-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
        }
        
        .wallet-card-title {
            font-weight: 600;
            font-size: 15px;
        }
        
        .wallet-card-row {
            display: flex;
            justify-content: space-between;
            align-items: center;
            font-size: 13px;
            padding: 4px 0;
            border-bottom: 1px solid var(--border-light, #f0f0f0);
        }
        
        .wallet-card-row:last-child {
            border-bottom: none;
        }
        
        .wallet-card-label {
            color: var(--gray, #666);
        }
        
        .wallet-card-value {
            font-weight: 500;
            text-align: right;
            max-width: 60%;
            word-break: break-all;
        }
        
        .wallet-card-actions {
            display: grid;
            grid-template-columns: 1fr 1fr 1fr;
            gap: 6px;
            margin-top: 4px;
        }
        
        .wallet-card-actions .btn {
            padding: 8px 4px;
            font-size: 12px;
            text-align: center;
        }

        /* Desktop table view (hidden on mobile) */
        .desktop-table-view {
            display: none;
        }
        
        @media (min-width: 768px) {
            .mobile-wallet-cards {
                display: none;
            }
            .desktop-table-view {
                display: block;
            }
        }

        /* Modal responsive styles */
        .modal-overlay {
            display: none;
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(0, 0, 0, 0.6);
            z-index: 1000;
            justify-content: center;
            align-items: flex-end;
            padding: 0;
        }
        
        .modal-overlay.active {
            display: flex;
        }
        
        .modal-content {
            background: var(--card-bg, #fff);
            border-radius: 16px 16px 0 0;
            width: 100%;
            max-height: 90vh;
            overflow-y: auto;
            padding: 20px;
            animation: slideUp 0.3s ease-out;
        }
        
        @keyframes slideUp {
            from { transform: translateY(100%); }
            to { transform: translateY(0); }
        }
        
        .modal-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 20px;
            padding-bottom: 12px;
            border-bottom: 1px solid var(--border-light, #f0f0f0);
        }
        
        .modal-header h3 {
            margin: 0;
            font-size: 18px;
        }
        
        .modal-close {
            background: none;
            border: none;
            font-size: 28px;
            cursor: pointer;
            color: var(--gray, #666);
            line-height: 1;
            padding: 0;
            width: 36px;
            height: 36px;
            display: flex;
            align-items: center;
            justify-content: center;
            border-radius: 50%;
        }
        
        .modal-close:hover {
            background: var(--bg-light, #f5f5f5);
            color: var(--danger, #dc3545);
        }

        /* Tablet and up: centered modal */
        @media (min-width: 768px) {
            .modal-overlay {
                align-items: center;
                padding: 20px;
            }
            .modal-content {
                border-radius: 12px;
                max-width: 520px;
                width: 90%;
                animation: fadeIn 0.2s ease-out;
            }
            @keyframes fadeIn {
                from { opacity: 0; transform: scale(0.95); }
                to { opacity: 1; transform: scale(1); }
            }
        }

        /* Form improvements */
        .form-group {
            margin-bottom: 16px;
        }
        
        .form-label {
            display: block;
            margin-bottom: 6px;
            font-size: 14px;
            font-weight: 500;
        }
        
        .form-control {
            width: 100%;
            padding: 12px;
            font-size: 16px; /* Prevents iOS zoom on focus */
            border-radius: 8px;
            border: 1px solid var(--border-color, #d0d0d0);
            background: var(--input-bg, #fff);
            box-sizing: border-box;
        }
        
        textarea.form-control {
            resize: vertical;
            min-height: 80px;
        }

        /* Button improvements */
        .btn {
            padding: 12px 16px;
            font-size: 14px;
            border-radius: 8px;
            cursor: pointer;
            border: none;
            text-decoration: none;
            display: inline-flex;
            align-items: center;
            justify-content: center;
            transition: all 0.2s;
        }
        
        .btn-sm {
            padding: 8px 12px;
            font-size: 12px;
        }
        
        .w-100 {
            width: 100%;
        }

        /* Action buttons in table */
        .action-group {
            display: flex;
            flex-wrap: wrap;
            gap: 4px;
            min-width: 140px;
        }
        
        .action-group .btn-sm {
            flex: 1;
            min-width: 60px;
            white-space: nowrap;
        }

        /* Page header responsive */
        .page-content {
            padding: 16px;
        }
        
        @media (min-width: 768px) {
            .page-content {
                padding: 24px;
            }
        }

        /* Card improvements */
        .card {
            border-radius: 12px;
            overflow: hidden;
        }
        
        .card-header {
            padding: 16px 20px;
        }
        
        .card-body {
            padding: 20px;
        }

        /* Alert improvements */
        .alert {
            padding: 14px 16px;
            border-radius: 8px;
            margin-bottom: 16px;
            font-size: 14px;
            display: flex;
            align-items: center;
            gap: 8px;
        }

        /* Status badge */
        .status-badge {
            padding: 4px 10px;
            border-radius: 20px;
            font-size: 12px;
            font-weight: 500;
            white-space: nowrap;
        }
        
        .status-badge.success {
            background: #d4edda;
            color: #155724;
        }
        
        .status-badge.secondary {
            background: #e2e3e5;
            color: #383d41;
        }

        /* Address display */
        .address-preview {
            font-family: monospace;
            font-size: 11px;
            background: var(--bg-light, #f5f5f5);
            padding: 2px 6px;
            border-radius: 4px;
            word-break: break-all;
        }
    </style>
</head>
<body>
    <?php include 'includes/admin-sidebar.php'; ?>
    
    <div class="main-content">
        <?php include 'includes/admin-header.php'; ?>
        
        <div class="page-content">
            <?php if ($flash): ?>
                <div class="alert alert-<?php echo $flash['type']; ?> fade-in">
                    <span><?php echo $flash['type'] === 'success' ? '✓' : '⚠'; ?></span> <?php echo e($flash['message']); ?>
                </div>
            <?php endif; ?>
            
            <?php if ($error): ?>
                <div class="alert alert-danger fade-in"><span>⚠</span> <?php echo e($error); ?></div>
            <?php endif; ?>
            
            <?php if ($success): ?>
                <div class="alert alert-success fade-in"><span>✓</span> <?php echo e($success); ?></div>
            <?php endif; ?>
            
            <div class="wallet-grid">
                <!-- Add Wallet Card -->
                <div class="card">
                    <div class="card-header">
                        <span class="card-title">Add Wallet</span>
                    </div>
                    <div class="card-body">
                        <form method="POST" action="">
                            <input type="hidden" name="add_wallet" value="1">
                            
                            <div class="form-group">
                                <label class="form-label">Cryptocurrency *</label>
                                <select name="coin_symbol" class="form-control" required>
                                    <option value="">Select</option>
                                    <option value="BTC">Bitcoin (BTC)</option>
                                    <option value="ETH">Ethereum (ETH)</option>
                                    <option value="USDT">Tether (USDT)</option>
                                    <option value="LTC">Litecoin (LTC)</option>
                                    <option value="BCH">Bitcoin Cash (BCH)</option>
                                    <option value="DOGE">Dogecoin (DOGE)</option>
                                    <option value="ADA">Cardano (ADA)</option>
                                    <option value="SOL">Solana (SOL)</option>
                                    <option value="DOT">Polkadot (DOT)</option>
                                </select>
                            </div>
                            
                            <div class="form-group">
                                <label class="form-label">Wallet Address *</label>
                                <textarea name="address" class="form-control" rows="3" required placeholder="Enter wallet address"></textarea>
                            </div>
                            
                            <div class="form-group">
                                <label class="form-label">Network</label>
                                <input type="text" name="network" class="form-control" placeholder="e.g., ERC-20, TRC-20">
                            </div>

                            <div class="form-group">
                                <label class="form-label">Min Deposit Amount</label>
                                <input type="number" step="any" name="min_deposit" class="form-control" value="0.00000000" placeholder="0.00000000">
                            </div>
                            
                            <button type="submit" class="btn btn-primary w-100">Add Wallet</button>
                        </form>
                    </div>
                </div>
                
                <!-- Wallets List -->
                <div class="card">
                    <div class="card-header">
                        <span class="card-title">Active Wallets</span>
                    </div>
                    <div class="card-body" style="padding: 0;">
                        
                        <!-- Desktop Table View -->
                        <div class="desktop-table-view">
                            <div class="table-scroll-wrapper">
                                <table class="data-table">
                                    <thead>
                                        <tr>
                                            <th>Coin</th>
                                            <th>Address</th>
                                            <th>Network</th>
                                            <th>Min</th>
                                            <th>Status</th>
                                            <th>Actions</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <?php 
                                        $walletList = [];
                                        if ($wallets && $wallets->num_rows > 0): 
                                            while ($wallet = $wallets->fetch_assoc()): 
                                                $walletList[] = $wallet;
                                        ?>
                                            <tr>
                                                <td>
                                                    <strong><?php echo e($wallet['coin_symbol']); ?></strong>
                                                    <div style="font-size: 11px; color: var(--gray);"><?php echo e($wallet['coin_name']); ?></div>
                                                </td>
                                                <td>
                                                    <code class="address-preview" title="<?php echo e($wallet['address']); ?>">
                                                        <?php echo substr(e($wallet['address']), 0, 12); ?>...
                                                    </code>
                                                </td>
                                                <td><?php echo e($wallet['network'] ?? '-'); ?></td>
                                                <td><?php echo e($wallet['min_deposit']); ?></td>
                                                <td>
                                                    <span class="status-badge <?php echo $wallet['is_active'] ? 'success' : 'secondary'; ?>">
                                                        <?php echo $wallet['is_active'] ? 'Active' : 'Inactive'; ?>
                                                    </span>
                                                </td>
                                                <td>
                                                    <div class="action-group">
                                                        <a href="?edit=<?php echo $wallet['id']; ?>" class="btn btn-sm btn-primary">Edit</a>
                                                        <a href="?toggle=<?php echo $wallet['id']; ?>" class="btn btn-sm <?php echo $wallet['is_active'] ? 'btn-warning' : 'btn-success'; ?>">
                                                            <?php echo $wallet['is_active'] ? 'Off' : 'On'; ?>
                                                        </a>
                                                        <a href="?delete=<?php echo $wallet['id']; ?>" class="btn btn-sm btn-danger" onclick="return confirm('Delete?')">Del</a>
                                                    </div>
                                                </td>
                                            </tr>
                                        <?php endwhile; ?>
                                        <?php else: ?>
                                            <tr><td colspan="6" class="text-center" style="padding: 40px;">No wallets configured</td></tr>
                                        <?php endif; ?>
                                    </tbody>
                                </table>
                            </div>
                        </div>

                        <!-- Mobile Card View -->
                        <div class="mobile-wallet-cards">
                            <?php if (!empty($walletList)): ?>
                                <?php foreach ($walletList as $wallet): ?>
                                    <div class="wallet-card">
                                        <div class="wallet-card-header">
                                            <div>
                                                <div class="wallet-card-title"><?php echo e($wallet['coin_name']); ?></div>
                                                <div style="font-size: 12px; color: var(--gray);">
                                                    <strong><?php echo e($wallet['coin_symbol']); ?></strong>
                                                </div>
                                            </div>
                                            <span class="status-badge <?php echo $wallet['is_active'] ? 'success' : 'secondary'; ?>">
                                                <?php echo $wallet['is_active'] ? 'Active' : 'Inactive'; ?>
                                            </span>
                                        </div>
                                        
                                        <div class="wallet-card-row">
                                            <span class="wallet-card-label">Address</span>
                                            <span class="wallet-card-value">
                                                <code class="address-preview"><?php echo substr(e($wallet['address']), 0, 20); ?>...</code>
                                            </span>
                                        </div>
                                        
                                        <div class="wallet-card-row">
                                            <span class="wallet-card-label">Network</span>
                                            <span class="wallet-card-value"><?php echo e($wallet['network'] ?? '-'); ?></span>
                                        </div>
                                        
                                        <div class="wallet-card-row">
                                            <span class="wallet-card-label">Min Deposit</span>
                                            <span class="wallet-card-value"><?php echo e($wallet['min_deposit']); ?></span>
                                        </div>
                                        
                                        <div class="wallet-card-actions">
                                            <a href="?edit=<?php echo $wallet['id']; ?>" class="btn btn-primary">Edit</a>
                                            <a href="?toggle=<?php echo $wallet['id']; ?>" class="btn <?php echo $wallet['is_active'] ? 'btn-warning' : 'btn-success'; ?>">
                                                <?php echo $wallet['is_active'] ? 'Disable' : 'Enable'; ?>
                                            </a>
                                            <a href="?delete=<?php echo $wallet['id']; ?>" class="btn btn-danger" onclick="return confirm('Delete this wallet?')">Delete</a>
                                        </div>
                                    </div>
                                <?php endforeach; ?>
                            <?php else: ?>
                                <div class="text-center" style="padding: 40px; color: var(--gray);">No wallets configured</div>
                            <?php endif; ?>
                        </div>
                        
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Edit Modal -->
    <div class="modal-overlay <?php echo $editWallet ? 'active' : ''; ?>" id="editModal">
        <div class="modal-content">
            <div class="modal-header">
                <h3>Edit Wallet</h3>
                <a href="crypto-wallets.php" class="modal-close">&times;</a>
            </div>
            <?php if ($editWallet): ?>
            <form method="POST" action="">
                <input type="hidden" name="edit_wallet" value="1">
                <input type="hidden" name="wallet_id" value="<?php echo e($editWallet['id']); ?>">
                
                <div class="form-group">
                    <label class="form-label">Cryptocurrency *</label>
                    <select name="coin_symbol" class="form-control" required>
                        <option value="">Select</option>
                        <option value="BTC" <?php echo $editWallet['coin_symbol'] === 'BTC' ? 'selected' : ''; ?>>Bitcoin (BTC)</option>
                        <option value="ETH" <?php echo $editWallet['coin_symbol'] === 'ETH' ? 'selected' : ''; ?>>Ethereum (ETH)</option>
                        <option value="USDT" <?php echo $editWallet['coin_symbol'] === 'USDT' ? 'selected' : ''; ?>>Tether (USDT)</option>
                        <option value="LTC" <?php echo $editWallet['coin_symbol'] === 'LTC' ? 'selected' : ''; ?>>Litecoin (LTC)</option>
                        <option value="BCH" <?php echo $editWallet['coin_symbol'] === 'BCH' ? 'selected' : ''; ?>>Bitcoin Cash (BCH)</option>
                        <option value="DOGE" <?php echo $editWallet['coin_symbol'] === 'DOGE' ? 'selected' : ''; ?>>Dogecoin (DOGE)</option>
                        <option value="ADA" <?php echo $editWallet['coin_symbol'] === 'ADA' ? 'selected' : ''; ?>>Cardano (ADA)</option>
                        <option value="SOL" <?php echo $editWallet['coin_symbol'] === 'SOL' ? 'selected' : ''; ?>>Solana (SOL)</option>
                        <option value="DOT" <?php echo $editWallet['coin_symbol'] === 'DOT' ? 'selected' : ''; ?>>Polkadot (DOT)</option>
                    </select>
                </div>
                
                <div class="form-group">
                    <label class="form-label">Wallet Address *</label>
                    <textarea name="address" class="form-control" rows="3" required placeholder="Enter wallet address"><?php echo e($editWallet['address']); ?></textarea>
                </div>
                
                <div class="form-group">
                    <label class="form-label">Network</label>
                    <input type="text" name="network" class="form-control" value="<?php echo e($editWallet['network'] ?? ''); ?>" placeholder="e.g., ERC-20, TRC-20">
                </div>

                <div class="form-group">
                    <label class="form-label">Min Deposit Amount</label>
                    <input type="number" step="any" name="min_deposit" class="form-control" value="<?php echo e($editWallet['min_deposit'] ?? '0.00000000'); ?>" placeholder="0.00000000">
                </div>
                
                <div style="display: flex; gap: 10px;">
                    <button type="submit" class="btn btn-primary w-100">Update Wallet</button>
                    <a href="crypto-wallets.php" class="btn btn-secondary w-100" style="text-align: center;">Cancel</a>
                </div>
            </form>
            <?php endif; ?>
        </div>
    </div>

    <script src="../assets/js/main.js"></script>
</body>
</html>
