<?php
/**
 * IBVTE Admin - Manage Wallets & Manual Balance Update
 */
require_once __DIR__ . '/../config.php';
require_once __DIR__ . '/../includes/db.php';
require_once __DIR__ . '/../includes/auth.php';

if (!checkDBConnection()) exit;
Auth()->requireRole(['super_admin', 'admin']);

$db = DB();
$flash = getFlashMessage();

// Handle Manual Top-up
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'topup') {
    $wallet_id = intval($_POST['wallet_id']);
    $amount = floatval($_POST['amount']);
    $remarks = cleanInput($_POST['remarks']);
    
    if ($amount > 0) {
        $wallet = $db->fetchOne("SELECT * FROM wallets WHERE id = ?", [$wallet_id]);
        if ($wallet) {
            $db->query("UPDATE wallets SET balance = balance + ?, total_credited = total_credited + ? WHERE id = ?", [$amount, $amount, $wallet_id]);
            
            // Log transaction
            $db->insert('transactions', [
                'transaction_id' => 'MANUAL_' . time(),
                'to_user_id' => $wallet['user_id'],
                'from_user_id' => $_SESSION['user_id'],
                'transaction_type' => 'manual_topup',
                'amount' => $amount,
                'status' => 'completed',
                'description' => "Manual topup: $remarks"
            ]);
            
            redirectWithMessage('wallet.php', 'Wallet balance updated successfully.', 'success');
        }
    }
}

// Fetch Wallets
$wallets = $db->fetchAll("
    SELECT w.*, u.institution_name, u.institution_code, u.email 
    FROM wallets w 
    LEFT JOIN users u ON w.user_id = u.id 
    WHERE w.wallet_type = 'college'
    ORDER BY w.balance DESC
");
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Manage Wallets - <?= APP_SHORT_NAME ?></title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css" rel="stylesheet">
    <link href="../assets/css/admin-style.css" rel="stylesheet">
</head>
<body>
    <?php include __DIR__ . '/../includes/admin_header.php'; ?>
    <div class="container-fluid">
        <div class="row">
            <?php include __DIR__ . '/../includes/admin_sidebar.php'; ?>
            
            <main class="col-md-9 ms-sm-auto col-lg-10 px-md-4 py-4">
                <div class="d-flex justify-content-between align-items-center mb-4">
                    <h2 class="h3"><i class="fas fa-wallet me-2 text-primary"></i>College Wallets</h2>
                </div>

                <?php if ($flash): ?>
                    <div class="alert alert-<?= $flash['type'] ?> alert-dismissible fade show shadow-sm">
                        <?= $flash['message'] ?>
                        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                    </div>
                <?php endif; ?>

                <div class="card shadow-sm border-0" style="border-radius:15px;">
                    <div class="card-body p-0">
                        <div class="table-responsive">
                            <table class="table table-hover align-middle mb-0">
                                <thead class="bg-light">
                                    <tr>
                                        <th class="ps-4">Institution Name</th>
                                        <th>Code</th>
                                        <th>Current Balance</th>
                                        <th>Total Credited</th>
                                        <th class="text-end pe-4">Actions</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php if(empty($wallets)): ?>
                                        <tr><td colspan="5" class="text-center py-4 text-muted">No wallets found.</td></tr>
                                    <?php endif; ?>
                                    <?php foreach ($wallets as $w): ?>
                                    <tr>
                                        <td class="ps-4 fw-bold">
                                            <?= htmlspecialchars($w['institution_name'] ?? 'Unknown') ?><br>
                                            <small class="text-muted fw-normal"><?= htmlspecialchars($w['email']) ?></small>
                                        </td>
                                        <td><?= htmlspecialchars($w['institution_code']) ?></td>
                                        <td class="fw-bold text-success fs-5">₹<?= number_format($w['balance'], 2) ?></td>
                                        <td class="text-muted">₹<?= number_format($w['total_credited'], 2) ?></td>
                                        <td class="text-end pe-4">
                                            <button class="btn btn-sm btn-primary" data-bs-toggle="modal" data-bs-target="#topupModal<?= $w['id'] ?>">
                                                <i class="fas fa-plus"></i> Add Funds
                                            </button>
                                        </td>
                                    </tr>
                                    
                                    <!-- Topup Modal -->
                                    <div class="modal fade" id="topupModal<?= $w['id'] ?>" tabindex="-1">
                                        <div class="modal-dialog">
                                            <div class="modal-content border-0 shadow-lg">
                                                <div class="modal-header bg-primary text-white">
                                                    <h5 class="modal-title fw-bold">Manual Wallet Topup</h5>
                                                    <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
                                                </div>
                                                <form method="POST">
                                                    <div class="modal-body p-4">
                                                        <input type="hidden" name="action" value="topup">
                                                        <input type="hidden" name="wallet_id" value="<?= $w['id'] ?>">
                                                        <p>Adding funds for: <strong><?= htmlspecialchars($w['institution_name']) ?></strong></p>
                                                        <div class="mb-3">
                                                            <label class="fw-bold small mb-2">Amount to Add (INR)</label>
                                                            <input type="number" name="amount" class="form-control" required min="1" step="1">
                                                        </div>
                                                        <div class="mb-3">
                                                            <label class="fw-bold small mb-2">Remarks / Reason</label>
                                                            <input type="text" name="remarks" class="form-control" placeholder="Optional notes...">
                                                        </div>
                                                    </div>
                                                    <div class="modal-footer border-0">
                                                        <button type="button" class="btn btn-light" data-bs-dismiss="modal">Cancel</button>
                                                        <button type="submit" class="btn btn-success px-4 fw-bold">Confirm Transfer</button>
                                                    </div>
                                                </form>
                                            </div>
                                        </div>
                                    </div>
                                    <?php endforeach; ?>
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
            </main>
        </div>
    </div>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>
