<?php
/**
 * IBVTE College - Fund Requests Management
 */

require_once __DIR__ . '/../config.php';
require_once __DIR__ . '/../includes/db.php';
require_once __DIR__ . '/../includes/auth.php';

$collegePage = 'funds';
Auth()->requireRole(['college']);

$db = DB();
$flash = getFlashMessage();
$user = Auth()->getUser();

// Get college wallet
$wallet = $db->fetchOne("SELECT * FROM wallets WHERE user_id = ?", [$user['id']]);

// Check affiliation status
$collegeData = $db->fetchOne("SELECT affiliation_status FROM users WHERE id = ?", [$user['id']]);
$isApproved = ($collegeData['affiliation_status'] === 'approved');

// Handle fund request submission
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (!$isApproved) {
        redirectWithMessage('fund-requests.php', 'You must be an approved college to request funds. Your current status is ' . ucfirst($collegeData['affiliation_status']), 'danger');
    }
    $amount = floatval($_POST['amount'] ?? 0);
    $transactionId = cleanInput($_POST['transaction_id'] ?? '');
    $date = $_POST['transaction_date'] ?? date('Y-m-d');
    $purpose = cleanInput($_POST['purpose'] ?? 'Wallet Topup');
    
    // Handle snapshot upload
    $snapshotPath = '';
    if (isset($_FILES['snapshot']) && $_FILES['snapshot']['error'] === 0) {
        $targetDir = "../uploads/fund_requests/";
        if (!is_dir($targetDir)) mkdir($targetDir, 0777, true);
        
        $fileName = time() . '_' . basename($_FILES['snapshot']['name']);
        $targetPath = $targetDir . $fileName;
        
        if (move_uploaded_file($_FILES['snapshot']['tmp_name'], $targetPath)) {
            $snapshotPath = "uploads/fund_requests/" . $fileName;
        }
    }
    
    if ($amount > 0 && !empty($transactionId)) {
        $db->insert('fund_requests', [
            'requester_id' => $user['id'],
            'amount' => $amount,
            'purpose' => $purpose,
            'supporting_document' => $snapshotPath,
            'remarks' => "Trans ID: $transactionId | Date: $date",
            'status' => 'pending',
            'created_at' => date('Y-m-d H:i:s')
        ]);
        
        redirectWithMessage('fund-requests.php', 'Fund request submitted successfully. Admin will review and approve soon.', 'success');
    } else {
        $error = 'Please enter a valid amount and transaction ID.';
    }
}

// Get request history
$requests = $db->fetchAll("SELECT * FROM fund_requests WHERE requester_id = ? ORDER BY created_at DESC", [$user['id']]);

?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Wallet & Fund Requests - College Panel</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">
    <style>
        /* ── College Sidebar ─────────────────────────── */
        :root { --primary:#3b0b7c; --secondary:#6c4ab6; }
        .college-sidebar {
            width: 250px;
            background: white;
            min-height: 100vh;
            position: fixed;
            top: 0; left: 0;
            display: flex;
            flex-direction: column;
            box-shadow: 3px 0 15px rgba(59,11,124,0.08);
            z-index: 1040;
            transition: transform .3s;
        }
        .sidebar-brand {
            padding: 28px 20px 20px;
            text-align: center;
            background: linear-gradient(135deg, var(--primary), var(--secondary));
        }
        .sidebar-logo {
            width: 68px; height: 68px;
            border-radius: 50%;
            border: 3px solid rgba(255,255,255,.35);
            object-fit: cover;
            margin-bottom: 12px;
        }
        .sidebar-college-name {
            color: white;
            font-weight: 700;
            font-size: .9rem;
            line-height: 1.3;
        }
        .sidebar-code {
            color: rgba(255,255,255,.65);
            font-size: .75rem;
            margin-top: 4px;
        }
        .sidebar-nav {
            flex: 1;
            padding: 16px 12px;
            overflow-y: auto;
        }
        .sidebar-link {
            display: flex;
            align-items: center;
            gap: 12px;
            padding: 11px 16px;
            border-radius: 10px;
            color: #555;
            text-decoration: none;
            font-size: .9rem;
            font-weight: 500;
            margin-bottom: 4px;
            transition: background .2s, color .2s, transform .15s;
        }
        .sidebar-link:hover {
            background: #f0ebf8;
            color: var(--primary);
            transform: translateX(3px);
        }
        .sidebar-link.active {
            background: linear-gradient(135deg, var(--primary), var(--secondary));
            color: white !important;
            box-shadow: 0 4px 12px rgba(59,11,124,.25);
        }
        .sidebar-icon { width: 18px; text-align: center; flex-shrink: 0; font-size: .95rem; }
        .sidebar-footer { padding: 12px; border-top: 1px solid #f0f0f0; }
        .sidebar-logout { color: #dc3545 !important; }
        .sidebar-logout:hover { background: #fff0f0; color: #dc3545 !important; }
        .college-main { margin-left: 250px; padding: 30px; min-height: 100vh; background: #f8f9fa; }
        @media (max-width: 768px) {
            .college-sidebar { transform: translateX(-100%); }
            .college-sidebar.open { transform: translateX(0); }
            .college-main { margin-left: 0; padding: 20px 15px; }
            .mobile-menu-btn { display: flex !important; }
        }

        :root { --primary: #3b0b7c; --secondary: #6c4ab6; }
        body { background: #f8f9fa; font-family: 'Inter', sans-serif; }
        .wallet-card { background: linear-gradient(135deg, var(--primary), var(--secondary)); color: white; border-radius: 15px; padding: 30px; box-shadow: 0 10px 30px rgba(59,11,124,0.2); }
        .sidebar { min-height: 100vh; background: white; border-right: 1px solid #eee; }
        .nav-link { color: #555; padding: 12px 20px; border-radius: 8px; margin-bottom: 5px; }
        .nav-link:hover, .nav-link.active { background: #f0ebf7; color: var(--primary); font-weight: 600; }
        .card-custom { border-radius: 15px; border: none; box-shadow: 0 5px 20px rgba(0,0,0,0.05); }
    </style>
</head>
<body>

<div class="container-fluid">
    <div class="row">
        <!-- Sidebar -->
        <?php include __DIR__ . '/../includes/college_sidebar.php'; ?><!-- Main Content -->
        <div class="college-main">
            <div class="d-flex justify-content-between align-items-center mb-4">
                <h2 class="fw-bold">Wallet & Fund Requests</h2>
                <button class="btn btn-primary d-md-none" data-bs-toggle="offcanvas" data-bs-target="#mobileMenu">Menu</button>
            </div>

            <?php if (isset($error)): ?>
                <div class="alert alert-danger"><?= $error ?></div>
            <?php endif; ?>
            <?php if ($flash): ?>
                <div class="alert alert-<?= $flash['type'] ?>"><?= $flash['message'] ?></div>
            <?php endif; ?>

            <div class="row g-4">
                <!-- Wallet Balance -->
                <div class="col-lg-4">
                    <div class="wallet-card mb-4">
                        <h6 class="opacity-75">Current Balance</h6>
                        <h1 class="fw-bold mb-0">₹<?= number_format($wallet['balance'] ?? 0, 2) ?></h1>
                        <hr class="opacity-25">
                        <p class="small mb-0">Virtual wallet for student admissions & fees</p>
                    </div>

                    <div class="card card-custom p-4">
                        <h5 class="fw-bold mb-3">Request Fund Addition</h5>
                        <?php if (!$isApproved): ?>
                            <div class="alert alert-warning mb-0">
                                <i class="fas fa-exclamation-triangle me-2"></i> Only approved colleges can request funds. Your current status is: <strong><?= ucfirst($collegeData['affiliation_status'] ?? 'pending') ?></strong>.
                            </div>
                        <?php else: ?>
                        <form method="POST" enctype="multipart/form-data">
                            <div class="mb-3">
                                <label class="form-label small fw-bold">Amount to Add (INR) *</label>
                                <input type="number" name="amount" class="form-control" placeholder="0.00" required>
                            </div>
                            <div class="mb-3">
                                <label class="form-label small fw-bold">Transaction ID *</label>
                                <input type="text" name="transaction_id" class="form-control" placeholder="UTR / Ref No" required>
                            </div>
                            <div class="mb-3">
                                <label class="form-label small fw-bold">Transaction Date *</label>
                                <input type="date" name="transaction_date" class="form-control" value="<?= date('Y-m-d') ?>" required>
                            </div>
                            <div class="mb-3">
                                <label class="form-label small fw-bold">Payment Snapshot *</label>
                                <input type="file" name="snapshot" class="form-control" accept="image/*" required>
                            </div>
                                            <button type="submit" class="btn btn-primary w-100 fw-bold py-2">
                                                <i class="fas fa-paper-plane me-2"></i>Submit Request
                                            </button>
                        </form>
                        <?php endif; ?>
                    </div>
                </div>

                <!-- History -->
                <div class="col-lg-8">
                    <div class="card card-custom overflow-hidden">
                        <div class="card-header bg-white py-3">
                            <h5 class="fw-bold mb-0">Request History</h5>
                        </div>
                        <div class="table-responsive">
                            <table class="table table-hover align-middle mb-0">
                                <thead class="bg-light">
                                    <tr>
                                        <th>Date</th>
                                        <th>Amount</th>
                                        <th>Status</th>
                                        <th>Remarks</th>
                                        <th>Details</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php if (empty($requests)): ?>
                                        <tr><td colspan="5" class="text-center py-4">No requests found</td></tr>
                                    <?php else: ?>
                                        <?php foreach ($requests as $req): ?>
                                            <tr>
                                                <td class="small"><?= date('d M, Y', strtotime($req['created_at'])) ?></td>
                                                <td class="fw-bold">₹<?= number_format($req['amount'], 2) ?></td>
                                                <td>
                                                    <?php if ($req['status'] == 'pending'): ?>
                                                        <span class="badge bg-warning text-dark">Pending</span>
                                                    <?php elseif ($req['status'] == 'approved'): ?>
                                                        <span class="badge bg-success">Approved</span>
                                                    <?php else: ?>
                                                        <span class="badge bg-danger">Rejected</span>
                                                    <?php endif; ?>
                                                </td>
                                                <td class="small text-muted"><?= htmlspecialchars($req['remarks']) ?></td>
                                                <td>
                                                    <?php if ($req['supporting_document']): ?>
                                                        <a href="../<?= $req['supporting_document'] ?>" target="_blank" class="btn btn-sm btn-outline-primary"><i class="fas fa-image"></i> View</a>
                                                    <?php endif; ?>
                                                </td>
                                            </tr>
                                        <?php endforeach; ?>
                                    <?php endif; ?>
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
            </div>
        </div>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>

<script>
function toggleSidebar() {
    const sb = document.getElementById('collegeSidebar');
    const ov = document.getElementById('sidebarOverlay');
    sb.classList.toggle('open');
    ov.classList.toggle('d-none');
}
// On mobile, show menu button
if (window.innerWidth < 768) {
    document.getElementById('mobileMenuBtn').style.display = 'flex';
}
window.addEventListener('resize', function() {
    const btn = document.getElementById('mobileMenuBtn');
    if (btn) btn.style.display = window.innerWidth < 768 ? 'flex' : 'none';
});
</script>

</body>
</html>
