<?php
require_once '../config/conn.php';
session_start();

if (!isset($_SESSION['user_id'])) {
    die('Unauthorized');
}

$student_id = $_SESSION['user_id'];

// Get student registration number to use as wallet ID
$student_stmt = $conn->prepare("SELECT reg_number FROM students WHERE id = ?");
$student_stmt->bind_param("i", $student_id);
$student_stmt->execute();
$student_result = $student_stmt->get_result();
$student = $student_result->fetch_assoc();
$reg_number = $student['reg_number'];

// Check if user has set transaction PIN
$pin_stmt = $conn->prepare("SELECT * FROM wallet_pins WHERE student_id = ?");
$pin_stmt->bind_param("i", $student_id);
$pin_stmt->execute();
$has_pin = $pin_stmt->get_result()->num_rows > 0;

// Get or create wallet
$wallet_stmt = $conn->prepare("SELECT id, wallet_id, balance FROM student_wallets WHERE student_id = ?");
$wallet_stmt->bind_param("i", $student_id);
$wallet_stmt->execute();
$wallet_result = $wallet_stmt->get_result();

if ($wallet_result->num_rows === 0) {
    // Create wallet if doesn't exist using registration number as wallet ID
    $create_stmt = $conn->prepare("INSERT INTO student_wallets (wallet_id, student_id, balance) VALUES (?, ?, 0.00)");
    $create_stmt->bind_param("si", $reg_number, $student_id);
    
    try {
        $create_stmt->execute();
    } catch (mysqli_sql_exception $e) {
        // Handle potential duplicate wallet_id case
        if ($e->getCode() == 1062) {
            // If wallet_id already exists, try with a modified wallet_id
            $modified_reg_number = $reg_number . '-' . substr(uniqid(), -4);
            $create_stmt = $conn->prepare("INSERT INTO student_wallets (wallet_id, student_id, balance) VALUES (?, ?, 0.00)");
            $create_stmt->bind_param("si", $modified_reg_number, $student_id);
            $create_stmt->execute();
        } else {
            throw $e; // Re-throw other exceptions
        }
    }
    
    // Re-fetch wallet
    $wallet_stmt->execute();
    $wallet_result = $wallet_stmt->get_result();
} else {
    // Wallet exists - ensure wallet_id matches current reg_number
    $wallet = $wallet_result->fetch_assoc();
    if ($wallet['wallet_id'] !== $reg_number) {
        $update_stmt = $conn->prepare("UPDATE student_wallets SET wallet_id = ? WHERE student_id = ?");
        $update_stmt->bind_param("si", $reg_number, $student_id);
        $update_stmt->execute();
    }
}

// Final wallet fetch
$wallet_stmt->execute();
$wallet_result = $wallet_stmt->get_result();
$wallet = $wallet_result->fetch_assoc();

// Get recent transactions
$transactions_stmt = $conn->prepare("
    SELECT t.*, b.bank_name, b.account_number 
    FROM wallet_transactions t
    LEFT JOIN student_bank_accounts b ON t.bank_account_id = b.id
    WHERE t.wallet_id = ?
    ORDER BY t.created_at DESC
    LIMIT 5
");
$transactions_stmt->bind_param("i", $wallet['id']);
$transactions_stmt->execute();
$transactions_result = $transactions_stmt->get_result();
$transactions = $transactions_result->fetch_all(MYSQLI_ASSOC);

// Get linked bank accounts
$accounts_stmt = $conn->prepare("
    SELECT * FROM student_bank_accounts
    WHERE student_id = ?
    ORDER BY is_primary DESC, created_at DESC
");
$accounts_stmt->bind_param("i", $student_id);
$accounts_stmt->execute();
$accounts_result = $accounts_stmt->get_result();
$bank_accounts = $accounts_result->fetch_all(MYSQLI_ASSOC);
?>

<!-- Balance Card -->
<div class="p-6 lg:col-span-1">
    <div class="flex justify-between items-start">
        <div>
            <p class="text-gray-500 text-sm">Wallet ID</p>
            <div class="flex items-center">
                <p class="text-lg font-bold text-primary-600 mb-2" id="wallet-id"><?= $reg_number ?></p>
                <button id="copy-wallet-id" class="ml-2 text-gray-500 hover:text-primary-500">
                    <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M8 5H6a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2v-1M8 5a2 2 0 002 2h2a2 2 0 002-2M8 5a2 2 0 012-2h2a2 2 0 012 2m0 0h2a2 2 0 012 2v3m2 4H10m0 0l3-3m-3 3l3 3"></path>
                    </svg>
                </button>
            </div>
            
            <p class="text-gray-500 text-sm">Available Balance</p>
            <div class="flex items-center">
                <p class="text-3xl font-bold text-primary-600 mt-1" id="balance-amount" style="display: none;">
                    ₦<?= number_format($wallet['balance'], 2) ?>
                </p>
                <p class="text-3xl font-bold text-primary-600 mt-1" id="balance-mask">
                    ₦••••••
                </p>
                <button id="toggle-balance" class="ml-2 text-gray-500 hover:text-primary-500">
                    <svg id="eye-icon" class="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 12a3 3 0 11-6 0 3 3 0 016 0z"></path>
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M2.458 12C3.732 7.943 7.523 5 12 5c4.478 0 8.268 2.943 9.542 7-1.274 4.057-5.064 7-9.542 7-4.477 0-8.268-2.943-9.542-7z"></path>
                    </svg>
                    <svg id="eye-off-icon" class="w-6 h-6 hidden" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M13.875 18.825A10.05 10.05 0 0112 19c-4.478 0-8.268-2.943-9.543-7a9.97 9.97 0 011.563-3.029m5.858.908a3 3 0 114.243 4.243M9.878 9.878l4.242 4.242M9.88 9.88l-3.29-3.29m7.532 7.532l3.29 3.29M3 3l3.59 3.59m0 0A9.953 9.953 0 0112 5c4.478 0 8.268 2.943 9.543 7a10.025 10.025 0 01-4.132 5.411m0 0L21 21"></path>
                    </svg>
                </button>
            </div>
            
            <?php if (!$has_pin): ?>
                <div class="mt-3 bg-yellow-50 border-l-4 border-yellow-400 p-3 rounded">
                    <div class="flex items-center">
                        <svg class="w-5 h-5 text-yellow-400 mr-2" fill="currentColor" viewBox="0 0 20 20">
                            <path fill-rule="evenodd" d="M8.257 3.099c.765-1.36 2.722-1.36 3.486 0l5.58 9.92c.75 1.334-.213 2.98-1.742 2.98H4.42c-1.53 0-2.493-1.646-1.743-2.98l5.58-9.92zM11 13a1 1 0 11-2 0 1 1 0 012 0zm-1-8a1 1 0 00-1 1v3a1 1 0 002 0V6a1 1 0 00-1-1z" clip-rule="evenodd"></path>
                        </svg>
                        <p class="text-sm text-yellow-700">You need to set a transaction PIN</p>
                    </div>
                    <a href="pin.php" class="mt-2 text-sm text-yellow-700 underline">
                        Set PIN now
                    </a>
                </div>
            <?php endif; ?>
        </div>
        <div class="w-12 h-12 bg-primary-100 rounded-full flex items-center justify-center">
            <svg class="w-6 h-6 text-primary-500" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M17 9V7a2 2 0 00-2-2H5a2 2 0 00-2 2v6a2 2 0 002 2h2m2 4h10a2 2 0 002-2v-6a2 2 0 00-2-2H9a2 2 0 00-2 2v6a2 2 0 002 2zm7-5a2 2 0 11-4 0 2 2 0 014 0z"></path>
            </svg>
        </div>
    </div>
    
    <div class="mt-6 space-y-3">
        <a href="deposit.php"
                class="w-full flex items-center justify-center bg-primary-500 hover:bg-primary-600 text-white px-4 py-3 rounded-lg text-sm font-medium transition">
            <svg class="w-5 h-5 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 6v6m0 0v6m0-6h6m-6 0H6"></path>
            </svg>
            Deposit Funds
        </a>
        
        <a href="withdraw.php"
                class="w-full flex items-center justify-center text-primary-500 border border-primary-500 hover:bg-primary-50 px-4 py-3 rounded-lg text-sm font-medium transition"
                <?= !$has_pin ? 'disabled title="You need to set a transaction PIN first"' : '' ?>>
            <svg class="w-5 h-5 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M20 12H4"></path>
            </svg>
            Withdraw Funds
        </a>
        
        <a href="bank_accounts.php"
           class="w-full flex items-center justify-center bg-gray-100 hover:bg-gray-200 text-gray-700 px-4 py-3 rounded-lg text-sm font-medium transition">
            <svg class="w-5 h-5 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M3 6l3 1m0 0l-3 9a5.002 5.002 0 006.001 0M6 7l3 9M6 7l6-2m6 2l3-1m-3 1l-3 9a5.002 5.002 0 006.001 0M18 7l3 9m-3-9l-6-2m0-2v2m0 16V5m0 16H9m3 0h3"></path>
            </svg>
            <?= count($bank_accounts) > 0 ? 'Manage Bank Accounts' : 'Add Bank Account' ?>
        </a>
    </div>
</div>

<div class=" dark:bg-gray-800  p-6 dark:border-gray-700 lg:col-span-2">
    <div class="flex justify-between items-center mb-4">
        <h3 class="text-lg font-semibold dark:text-white">Quick Actions</h3>
        <button id="scroll-left" class="p-2 rounded-full bg-gray-100 dark:bg-gray-700 text-gray-500 dark:text-gray-300 hover:bg-gray-200 dark:hover:bg-gray-600">
            <i class="fas fa-chevron-left"></i>
        </button>
    </div>
    
    <div class="relative overflow-hidden">
        <div id="quick-actions-container" class="flex overflow-x-auto pb-4 scrollbar-hide space-x-4">
            <div class="flex space-x-4" id="quick-actions-track">
                <button class="bg-primary-50 dark:bg-gray-700 p-4 rounded-xl flex flex-col items-center hover:bg-primary-100 dark:hover:bg-gray-600 transition flex-shrink-0 w-24">
                    <div class="w-12 h-12 bg-primary-100 dark:bg-primary-200 rounded-full flex items-center justify-center mb-2">
                        <i class="fas fa-utensils text-primary-500 dark:text-primary-600 text-xl"></i>
                    </div>
                    <span class="text-sm font-medium text-gray-700 dark:text-gray-200">Cafeteria</span>
                </button>
                <button class="bg-primary-50 dark:bg-gray-700 p-4 rounded-xl flex flex-col items-center hover:bg-primary-100 dark:hover:bg-gray-600 transition flex-shrink-0 w-24">
                    <div class="w-12 h-12 bg-primary-100 dark:bg-primary-200 rounded-full flex items-center justify-center mb-2">
                        <i class="fas fa-book text-primary-500 dark:text-primary-600 text-xl"></i>
                    </div>
                    <span class="text-sm font-medium text-gray-700 dark:text-gray-200">Bookstore</span>
                </button>
                <button class="bg-primary-50 dark:bg-gray-700 p-4 rounded-xl flex flex-col items-center hover:bg-primary-100 dark:hover:bg-gray-600 transition flex-shrink-0 w-24">
                    <div class="w-12 h-12 bg-primary-100 dark:bg-primary-200 rounded-full flex items-center justify-center mb-2">
                        <i class="fas fa-t-shirt text-primary-500 dark:text-primary-600 text-xl"></i>
                    </div>
                    <span class="text-sm font-medium text-gray-700 dark:text-gray-200">Merchandise</span>
                </button>
                <button class="bg-primary-50 dark:bg-gray-700 p-4 rounded-xl flex flex-col items-center hover:bg-primary-100 dark:hover:bg-gray-600 transition flex-shrink-0 w-24">
                    <div class="w-12 h-12 bg-primary-100 dark:bg-primary-200 rounded-full flex items-center justify-center mb-2">
                        <i class="fas fa-bus text-primary-500 dark:text-primary-600 text-xl"></i>
                    </div>
                    <span class="text-sm font-medium text-gray-700 dark:text-gray-200">Transport</span>
                </button>
                <button class="bg-primary-50 dark:bg-gray-700 p-4 rounded-xl flex flex-col items-center hover:bg-primary-100 dark:hover:bg-gray-600 transition flex-shrink-0 w-24">
                    <div class="w-12 h-12 bg-primary-100 dark:bg-primary-200 rounded-full flex items-center justify-center mb-2">
                        <i class="fas fa-ticket-alt text-primary-500 dark:text-primary-600 text-xl"></i>
                    </div>
                    <span class="text-sm font-medium text-gray-700 dark:text-gray-200">Events</span>
                </button>
                <button class="bg-primary-50 dark:bg-gray-700 p-4 rounded-xl flex flex-col items-center hover:bg-primary-100 dark:hover:bg-gray-600 transition flex-shrink-0 w-24">
                    <div class="w-12 h-12 bg-primary-100 dark:bg-primary-200 rounded-full flex items-center justify-center mb-2">
                        <i class="fas fa-print text-primary-500 dark:text-primary-600 text-xl"></i>
                    </div>
                    <span class="text-sm font-medium text-gray-700 dark:text-gray-200">Printing</span>
                </button>
                <button class="bg-primary-50 dark:bg-gray-700 p-4 rounded-xl flex flex-col items-center hover:bg-primary-100 dark:hover:bg-gray-600 transition flex-shrink-0 w-24">
                    <div class="w-12 h-12 bg-primary-100 dark:bg-primary-200 rounded-full flex items-center justify-center mb-2">
                        <i class="fas fa-ellipsis-h text-primary-500 dark:text-primary-600 text-xl"></i>
                    </div>
                    <span class="text-sm font-medium text-gray-700 dark:text-gray-200">More</span>
                </button>
            </div>
        </div>
    </div>
</div>

<style>
    .scrollbar-hide::-webkit-scrollbar {
        display: none;
    }
    .scrollbar-hide {
        -ms-overflow-style: none;
        scrollbar-width: none;
    }
    
    #toggle-balance {
        cursor: pointer;
        transition: all 0.2s ease;
        background: none;
        border: none;
        padding: 0;
    }
    
    #toggle-balance:hover {
        transform: scale(1.1);
        color: #3b82f6;
    }
    
    #eye-icon, #eye-off-icon {
        transition: opacity 0.2s ease;
    }
    
    #eye-icon.hidden, #eye-off-icon.hidden {
        display: none;
    }
</style>

<script>
document.addEventListener('DOMContentLoaded', function() {
    const container = document.getElementById('quick-actions-container');
    const track = document.getElementById('quick-actions-track');
    const scrollLeftBtn = document.getElementById('scroll-left');
    
    let isDown = false;
    let startX;
    let scrollLeft;
    
    // Mouse drag functionality
    container.addEventListener('mousedown', (e) => {
        isDown = true;
        startX = e.pageX - container.offsetLeft;
        scrollLeft = container.scrollLeft;
    });
    
    container.addEventListener('mouseleave', () => {
        isDown = false;
    });
    
    container.addEventListener('mouseup', () => {
        isDown = false;
    });
    
    container.addEventListener('mousemove', (e) => {
        if(!isDown) return;
        e.preventDefault();
        const x = e.pageX - container.offsetLeft;
        const walk = (x - startX) * 2; // Adjust scroll speed
        container.scrollLeft = scrollLeft - walk;
    });
    
    // Touch drag functionality
    container.addEventListener('touchstart', (e) => {
        isDown = true;
        startX = e.touches[0].pageX - container.offsetLeft;
        scrollLeft = container.scrollLeft;
    });
    
    container.addEventListener('touchend', () => {
        isDown = false;
    });
    
    container.addEventListener('touchmove', (e) => {
        if(!isDown) return;
        const x = e.touches[0].pageX - container.offsetLeft;
        const walk = (x - startX) * 2; // Adjust scroll speed
        container.scrollLeft = scrollLeft - walk;
    });
    
    // Scroll left button
    scrollLeftBtn.addEventListener('click', () => {
        container.scrollBy({
            left: -200,
            behavior: 'smooth'
        });
    });
    
    // Show/hide scroll left button based on scroll position
    container.addEventListener('scroll', () => {
        if(container.scrollLeft > 0) {
            scrollLeftBtn.style.display = 'block';
        } else {
            scrollLeftBtn.style.display = 'none';
        }
    });
    
    // Handle balance toggle
    const toggleBalance = document.getElementById('toggle-balance');
    if (toggleBalance) {
        toggleBalance.addEventListener('click', function() {
            const balanceAmount = document.getElementById('balance-amount');
            const balanceMask = document.getElementById('balance-mask');
            const eyeIcon = document.getElementById('eye-icon');
            const eyeOffIcon = document.getElementById('eye-off-icon');
            
            if (balanceAmount.style.display === 'none') {
                balanceAmount.style.display = 'block';
                balanceMask.style.display = 'none';
                eyeIcon.classList.add('hidden');
                eyeOffIcon.classList.remove('hidden');
            } else {
                balanceAmount.style.display = 'none';
                balanceMask.style.display = 'block';
                eyeIcon.classList.remove('hidden');
                eyeOffIcon.classList.add('hidden');
            }
        });
    }
    
    // Handle wallet ID copy
    const copyWalletId = document.getElementById('copy-wallet-id');
    if (copyWalletId) {
        copyWalletId.addEventListener('click', function() {
            const walletId = document.getElementById('wallet-id').textContent;
            navigator.clipboard.writeText(walletId).then(() => {
                alert('Wallet ID copied to clipboard!');
            }).catch(err => {
                console.error('Failed to copy: ', err);
            });
        });
    }
});
</script>

<!-- Bank Accounts Summary -->
<div class="p-6 lg:col-span-1">
    <div class="flex justify-between items-center mb-4">
        <h3 class="text-lg font-semibold">Bank Accounts</h3>
        <a href="bank_accounts.php" class="text-primary-500 hover:text-primary-600 text-sm font-medium">
            <?= count($bank_accounts) > 0 ? 'Manage' : 'Add' ?>
        </a>
    </div>
    
    <?php if (empty($bank_accounts)): ?>
        <div class="text-center py-8 text-gray-500">
            <svg class="w-12 h-12 mx-auto mb-3 text-gray-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="1" d="M3 6l3 1m0 0l-3 9a5.002 5.002 0 006.001 0M6 7l3 9M6 7l6-2m6 2l3-1m-3 1l-3 9a5.002 5.002 0 006.001 0M18 7l3 9m-3-9l-6-2m0-2v2m0 16V5m0 16H9m3 0h3"></path>
            </svg>
            <p>No bank accounts linked</p>
            <a href="bank_accounts.php" class="text-primary-500 hover:text-primary-600 mt-2 inline-block">
                Add your bank account
            </a>
        </div>
    <?php else: ?>
        <div class="space-y-3">
            <?php foreach ($bank_accounts as $account): ?>
                <div class="flex items-center p-3 bg-gray-50 hover:bg-gray-100 rounded-lg transition">
                    <div class="w-10 h-10 rounded-full bg-blue-100 flex items-center justify-center mr-3">
                        <svg class="w-5 h-5 text-blue-500" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="1.5" d="M3 6l3 1m0 0l-3 9a5.002 5.002 0 006.001 0M6 7l3 9M6 7l6-2m6 2l3-1m-3 1l-3 9a5.002 5.002 0 006.001 0M18 7l3 9m-3-9l-6-2m0-2v2m0 16V5m0 16H9m3 0h3"></path>
                        </svg>
                    </div>
                    <div class="flex-1">
                        <p class="font-medium"><?= htmlspecialchars($account['bank_name']) ?></p>
                        <p class="text-xs text-gray-500">
                            <?= htmlspecialchars($account['account_name']) ?> • ****<?= substr($account['account_number'], -4) ?>
                            <?= $account['is_primary'] ? ' • Primary' : '' ?>
                        </p>
                    </div>
                </div>
            <?php endforeach; ?>
        </div>
    <?php endif; ?>
</div>


<!-- Recent Transactions -->
<div class="p-6 lg:col-span-1">
    <div class="flex justify-between items-center mb-4">
        <h3 class="text-lg font-semibold">Recent Transactions</h3>
        <a href="wallet_history.php" class="text-primary-500 hover:text-primary-600 text-sm font-medium">View All</a>
    </div>
    <div class="space-y-3">
        <?php if (empty($transactions)): ?>
            <div class="text-center py-8 text-gray-500">
                <svg class="w-12 h-12 mx-auto mb-3 text-gray-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="1" d="M8 7h12m0 0l-4-4m4 4l-4 4m0 6H4m0 0l4 4m-4-4l4-4"></path>
                </svg>
                <p>No transactions yet</p>
            </div>
        <?php else: ?>
            <?php foreach ($transactions as $transaction): ?>
                <div class="flex items-center p-3 hover:bg-gray-50 rounded-lg transition">
                    <div class="w-10 h-10 rounded-full flex items-center justify-center mr-3 
                        <?= $transaction['transaction_type'] === 'credit' || $transaction['transaction_type'] === 'deposit' ? 'bg-green-100' : 'bg-red-100' ?>">
                        <?php if ($transaction['transaction_type'] === 'credit' || $transaction['transaction_type'] === 'deposit'): ?>
                            <svg class="w-5 h-5 text-green-500" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M5 10l7-7m0 0l7 7m-7-7v18"></path>
                            </svg>
                        <?php else: ?>
                            <svg class="w-5 h-5 text-red-500" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 14l-7 7m0 0l-7-7m7 7V3"></path>
                            </svg>
                        <?php endif; ?>
                    </div>
                    <div class="flex-1">
                        <p class="font-medium"><?= htmlspecialchars($transaction['description']) ?></p>
                        <p class="text-xs text-gray-500">
                            <?= date('M j, Y', strtotime($transaction['created_at'])) ?>
                            • <?= ucfirst($transaction['status']) ?>
                            <?php if ($transaction['bank_name']): ?>
                                <br><?= ($transaction['transaction_type'] === 'credit' || $transaction['transaction_type'] === 'deposit') ? 'From' : 'To' ?>: 
                                <?= htmlspecialchars($transaction['bank_name']) ?> (****<?= substr($transaction['account_number'], -4) ?>)
                            <?php endif; ?>
                        </p>
                    </div>
                    <p class="font-medium <?= ($transaction['transaction_type'] === 'credit' || $transaction['transaction_type'] === 'deposit') ? 'text-green-600' : 'text-red-600' ?>">
                        <?= ($transaction['transaction_type'] === 'credit' || $transaction['transaction_type'] === 'deposit') ? '+' : '-' ?>₦<?= number_format($transaction['amount'], 2) ?>
                    </p>
                </div>
            <?php endforeach; ?>
        <?php endif; ?>
    </div>
</div>