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

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

$student_id = $_SESSION['user_id'];
$page = isset($_GET['page']) ? max(1, intval($_GET['page'])) : 1;
$limit = 15;
$offset = ($page - 1) * $limit;

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

if (!$wallet) {
    die('Wallet not found');
}

// Get total count
$count_stmt = $conn->prepare("SELECT COUNT(*) as total FROM wallet_transactions WHERE wallet_id = ?");
$count_stmt->bind_param("i", $wallet['id']);
$count_stmt->execute();
$count_result = $count_stmt->get_result();
$total_rows = $count_result->fetch_assoc()['total'];
$total_pages = ceil($total_rows / $limit);

// Get 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 ? OFFSET ?
");
$transactions_stmt->bind_param("iii", $wallet['id'], $limit, $offset);
$transactions_stmt->execute();
$transactions_result = $transactions_stmt->get_result();
$transactions = $transactions_result->fetch_all(MYSQLI_ASSOC);

if (empty($transactions)): ?>
    <div class="text-center py-12 text-gray-500">
        <i class="fas fa-exchange-alt text-4xl mb-4"></i>
        <p class="text-lg">No transactions found</p>
        <p class="text-sm mt-2">Your transaction history will appear here</p>
    </div>
<?php else: ?>
    <div class="space-y-3">
        <?php foreach ($transactions as $transaction): 
            // Determine if this is a credit (incoming money) or debit (outgoing money)
            $isCredit = in_array($transaction['transaction_type'], ['credit', 'deposit', 'funding']);
            $sign = $isCredit ? '+' : '-';
            $amountClass = $isCredit ? 'text-green-600' : 'text-red-600';
            $iconClass = $isCredit ? 'bg-green-100 text-green-500' : 'bg-red-100 text-red-500';
            $icon = $isCredit ? 
                '<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M5 10l7-7m0 0l7 7m-7-7v18"></path>' :
                '<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 14l-7 7m0 0l-7-7m7 7V3"></path>';
        ?>
            <div onclick="showTransactionDetails(<?= $transaction['id'] ?>)" 
                 class="flex items-center p-3 hover:bg-gray-50 rounded-lg transition cursor-pointer">
                <div class="w-10 h-10 rounded-full flex items-center justify-center mr-3 <?= $iconClass ?>">
                    <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <?= $icon ?>
                    </svg>
                </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><?= $isCredit ? 'From' : 'To' ?>: 
                            <?= htmlspecialchars($transaction['bank_name']) ?> (****<?= substr($transaction['account_number'], -4) ?>)
                        <?php endif; ?>
                    </p>
                </div>
                <p class="font-medium <?= $amountClass ?>">
                    <?= $sign ?>₦<?= number_format($transaction['amount'], 2) ?>
                </p>
            </div>
        <?php endforeach; ?>
    </div>

    <?php if ($total_pages > 1): ?>
        <div class="flex justify-between items-center mt-6">
            <div class="text-sm text-gray-500">
                Showing <?= ($offset + 1) ?> to <?= min($offset + $limit, $total_rows) ?> of <?= $total_rows ?> transactions
            </div>
            <div class="flex space-x-2">
                <?php if ($page > 1): ?>
                    <a href="#" data-page="<?= $page - 1 ?>" class="pagination-link px-3 py-1 border rounded-lg text-gray-700 hover:bg-gray-50">
                        <i class="fas fa-chevron-left"></i>
                    </a>
                <?php endif; ?>
                
                <?php 
                $start_page = max(1, $page - 2);
                $end_page = min($total_pages, $page + 2);
                
                if ($start_page > 1) {
                    echo '<a href="#" data-page="1" class="pagination-link px-3 py-1 border rounded-lg text-gray-700 hover:bg-gray-50">1</a>';
                    if ($start_page > 2) {
                        echo '<span class="px-3 py-1">...</span>';
                    }
                }
                
                for ($i = $start_page; $i <= $end_page; $i++) {
                    $active = $i == $page ? 'bg-primary-500 text-white' : 'text-gray-700 hover:bg-gray-50';
                    echo '<a href="#" data-page="'.$i.'" class="pagination-link px-3 py-1 border rounded-lg '.$active.'">'.$i.'</a>';
                }
                
                if ($end_page < $total_pages) {
                    if ($end_page < $total_pages - 1) {
                        echo '<span class="px-3 py-1">...</span>';
                    }
                    echo '<a href="#" data-page="'.$total_pages.'" class="pagination-link px-3 py-1 border rounded-lg text-gray-700 hover:bg-gray-50">'.$total_pages.'</a>';
                }
                ?>
                
                <?php if ($page < $total_pages): ?>
                    <a href="#" data-page="<?= $page + 1 ?>" class="pagination-link px-3 py-1 border rounded-lg text-gray-700 hover:bg-gray-50">
                        <i class="fas fa-chevron-right"></i>
                    </a>
                <?php endif; ?>
            </div>
        </div>
    <?php endif; ?>
<?php endif; ?>