<?php
include 'includes/header.php';

if(!isset($_SESSION['user_id'])) {
    header('Location: login.php');
    exit;
}

$user_id = $_SESSION['user_id'];

// Get wallet balance
$stmt = $pdo->prepare("SELECT balance FROM user_wallets WHERE user_id = ?");
$stmt->execute([$user_id]);
$wallet = $stmt->fetch(PDO::FETCH_ASSOC);

// Get transaction history
$stmt = $pdo->prepare("SELECT * FROM transactions WHERE user_id = ? ORDER BY created_at DESC LIMIT 10");
$stmt->execute([$user_id]);
$transactions = $stmt->fetchAll(PDO::FETCH_ASSOC);

// Handle coin transfer
if($_POST && isset($_POST['transfer_coins'])) {
    $receiver_username = $_POST['receiver_username'];
    $amount = floatval($_POST['amount']);
    $note = $_POST['note'] ?? '';
    
    try {
        $pdo->beginTransaction();
        
        // Check if user has sufficient balance
        if($wallet['balance'] < $amount) {
            throw new Exception("Insufficient ZIT Coins balance!");
        }
        
        // Find receiver
        $stmt = $pdo->prepare("SELECT id FROM users WHERE username = ?");
        $stmt->execute([$receiver_username]);
        $receiver = $stmt->fetch(PDO::FETCH_ASSOC);
        
        if(!$receiver) {
            throw new Exception("User not found!");
        }
        
        if($receiver['id'] == $user_id) {
            throw new Exception("You cannot transfer coins to yourself!");
        }
        
        if($amount <= 0) {
            throw new Exception("Invalid amount!");
        }
        
        // Deduct from sender
        $stmt = $pdo->prepare("UPDATE user_wallets SET balance = balance - ? WHERE user_id = ?");
        $stmt->execute([$amount, $user_id]);
        
        // Add to receiver (create wallet if doesn't exist)
        $stmt = $pdo->prepare("INSERT INTO user_wallets (user_id, balance) VALUES (?, ?) ON DUPLICATE KEY UPDATE balance = balance + ?");
        $stmt->execute([$receiver['id'], $amount, $amount]);
        
        // Record transactions
        $stmt = $pdo->prepare("INSERT INTO transactions (user_id, type, amount, description) VALUES (?, 'transfer_sent', ?, ?)");
        $stmt->execute([$user_id, $amount, "Transfer to @{$receiver_username}: {$note}"]);
        
        $stmt = $pdo->prepare("INSERT INTO transactions (user_id, type, amount, description) VALUES (?, 'transfer_received', ?, ?)");
        $stmt->execute([$receiver['id'], $amount, "Transfer from @{$_SESSION['username']}: {$note}"]);
        
        // Record transfer
        $stmt = $pdo->prepare("INSERT INTO coin_transfers (sender_id, receiver_id, amount, note) VALUES (?, ?, ?, ?)");
        $stmt->execute([$user_id, $receiver['id'], $amount, $note]);
        
        $pdo->commit();
        $_SESSION['success'] = "Successfully transferred {$amount} ZIT Coins to @{$receiver_username}!";
        header('Location: wallet.php');
        exit;
        
    } catch(Exception $e) {
        $pdo->rollBack();
        $_SESSION['error'] = $e->getMessage();
    }
}
?>

<div class="container">
    <h1>My ZIT Coin Wallet</h1>
    
    <?php if(isset($_SESSION['success'])): ?>
        <div class="alert success"><?php echo $_SESSION['success']; unset($_SESSION['success']); ?></div>
    <?php endif; ?>
    
    <?php if(isset($_SESSION['error'])): ?>
        <div class="alert error"><?php echo $_SESSION['error']; unset($_SESSION['error']); ?></div>
    <?php endif; ?>
    
    <div class="wallet-overview">
        <div class="balance-card">
            <h2>Current Balance</h2>
            <div class="balance-amount"><?php echo number_format($wallet['balance'] ?? 0, 2); ?> ZIT Coins</div>
            <small>1 Vote = 10 ZIT Coins</small>
        </div>
        
        <div class="wallet-actions">
            <a href="buy-coins.php" class="btn btn-primary">
                <i class="fas fa-coins"></i> Buy More Coins
            </a>
            <button onclick="openTransferModal()" class="btn btn-secondary">
                <i class="fas fa-paper-plane"></i> Send Coins
            </button>
        </div>
    </div>
    
    <!-- Coin Transfer Modal -->
    <div id="transferModal" class="modal" style="display: none;">
        <div class="modal-content">
            <h2>Transfer ZIT Coins</h2>
            <form method="POST">
                <div class="form-group">
                    <label>Receiver Username:</label>
                    <input type="text" name="receiver_username" placeholder="Enter username (without @)" required>
                </div>
                
                <div class="form-group">
                    <label>Amount:</label>
                    <input type="number" name="amount" min="1" max="<?php echo $wallet['balance'] ?? 0; ?>" step="1" placeholder="Enter amount" required>
                    <small>Available: <?php echo number_format($wallet['balance'] ?? 0, 2); ?> ZIT Coins</small>
                </div>
                
                <div class="form-group">
                    <label>Note (Optional):</label>
                    <textarea name="note" placeholder="Add a note for the receiver" rows="3"></textarea>
                </div>
                
                <div class="form-actions">
                    <button type="submit" name="transfer_coins" class="btn btn-primary">Transfer Coins</button>
                    <button type="button" class="btn btn-secondary" onclick="closeTransferModal()">Cancel</button>
                </div>
            </form>
        </div>
    </div>
    
    <div class="transaction-history">
        <h2>Recent Transactions</h2>
        <?php if($transactions): ?>
            <div class="transactions-list">
                <?php foreach($transactions as $transaction): ?>
                <div class="transaction-item">
                    <div class="transaction-info">
                        <strong><?php echo $transaction['description']; ?></strong>
                        <span class="transaction-date"><?php echo date('M j, Y g:i A', strtotime($transaction['created_at'])); ?></span>
                    </div>
                    <div class="transaction-amount <?php echo $transaction['type'] === 'transfer_received' || $transaction['type'] === 'bonus' ? 'positive' : 'negative'; ?>">
                        <?php echo ($transaction['type'] === 'transfer_received' || $transaction['type'] === 'bonus' ? '+' : '-'); ?>
                        <?php echo number_format($transaction['amount'], 2); ?> ZIT
                    </div>
                </div>
                <?php endforeach; ?>
            </div>
        <?php else: ?>
            <p>No transactions yet.</p>
        <?php endif; ?>
    </div>
</div>

<style>
.wallet-overview {
    display: grid;
    grid-template-columns: 1fr auto;
    gap: 2rem;
    margin: 2rem 0;
    align-items: center;
}

.balance-card {
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    color: white;
    padding: 2rem;
    border-radius: 15px;
    text-align: center;
    box-shadow: 0 10px 30px rgba(0,0,0,0.2);
}

.balance-amount {
    font-size: 3rem;
    font-weight: bold;
    margin: 1rem 0;
}

.wallet-actions {
    display: flex;
    flex-direction: column;
    gap: 1rem;
}

.transaction-history {
    background: white;
    padding: 2rem;
    border-radius: 10px;
    box-shadow: 0 5px 15px rgba(0,0,0,0.1);
    margin-top: 2rem;
}

.transactions-list {
    margin-top: 1rem;
}

.transaction-item {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 1rem;
    border-bottom: 1px solid #e0e0e0;
}

.transaction-item:last-child {
    border-bottom: none;
}

.transaction-amount.positive {
    color: #27ae60;
    font-weight: bold;
}

.transaction-amount.negative {
    color: #e74c3c;
    font-weight: bold;
}

.transaction-date {
    color: #666;
    font-size: 0.9rem;
}

@media (max-width: 768px) {
    .wallet-overview {
        grid-template-columns: 1fr;
        text-align: center;
    }
    
    .balance-amount {
        font-size: 2.5rem;
    }
}
</style>

<script>
function openTransferModal() {
    document.getElementById('transferModal').style.display = 'block';
}

function closeTransferModal() {
    document.getElementById('transferModal').style.display = 'none';
}

// Close modal when clicking outside
window.onclick = function(event) {
    const modal = document.getElementById('transferModal');
    if (event.target == modal) {
        closeTransferModal();
    }
}
</script>

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