<?php
session_start();
session_regenerate_id(true);

// Include config and pesapal
require_once 'config.php';
require_once 'pesapal.php';

// Generate CSRF token
if (!isset($_SESSION['csrf_token'])) {
    $_SESSION['csrf_token'] = bin2hex(random_bytes(32));
}
$csrf_token = $_SESSION['csrf_token'];

// Enforce HTTPS
if (!isset($_SERVER['HTTPS']) || $_SERVER['HTTPS'] !== 'on') {
    header("Location: https://" . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI']);
    exit();
}

// Disable debug in production
if ($_SERVER['SERVER_NAME'] !== 'localhost') {
    ini_set('display_errors', 0);
    error_reporting(0);
}

// Check if user is logged in
if (!isset($_SESSION['student_id']) || !in_array($_SESSION['role'], ['student', 'admin'])) {
    header("Location: login.php");
    exit();
}

// Database connection
try {
    $conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $e) {
    error_log("Connection failed: " . $e->getMessage());
    $error = "Connection failed. Please contact support.";
}

// Fetch user's student details
try {
    $stmt = $conn->prepare("SELECT name, grade, contact, admission_no, programme, stage FROM students WHERE id = :student_id");
    $stmt->execute([':student_id' => (int)$_SESSION['student_id']]);
    $user = $stmt->fetch(PDO::FETCH_ASSOC);
    if (!$user) {
        $error = "User data not found.";
    }
} catch(PDOException $e) {
    error_log("User fetch error: " . $e->getMessage());
    $error = "Error fetching user data.";
}

// Fetch financial details
try {
    $financial_stmt = $conn->prepare("SELECT total_billed, total_paid, balance FROM financials WHERE student_id = :student_id");
    $financial_stmt->execute([':student_id' => (int)$_SESSION['student_id']]);
    $financials = $financial_stmt->fetch(PDO::FETCH_ASSOC);
    if (!$financials) {
        $financials = ['total_billed' => 0.00, 'total_paid' => 0.00, 'balance' => 0.00];
    }
} catch(PDOException $e) {
    error_log("Financial fetch error: " . $e->getMessage());
    $error = "Error fetching financial data.";
}

// Fetch transaction history
$transactions = [];
try {
    $transaction_stmt = $conn->prepare("SELECT transaction_type, amount, description, transaction_date FROM transactions WHERE student_id = :student_id ORDER BY transaction_date DESC");
    $transaction_stmt->execute([':student_id' => (int)$_SESSION['student_id']]);
    $transactions = $transaction_stmt->fetchAll(PDO::FETCH_ASSOC);
} catch(PDOException $e) {
    error_log("Transaction fetch error: " . $e->getMessage());
    $error = "Error fetching transaction history.";
}

// Fetch all students' financials (for admin)
$all_financials = [];
if ($_SESSION['role'] === 'admin' && isset($_GET['view_all']) && $_GET['view_all'] === 'true') {
    try {
        $all_financials_stmt = $conn->query("
            SELECT s.id, s.name, s.admission_no, f.total_billed, f.total_paid, f.balance
            FROM students s
            LEFT JOIN financials f ON s.id = f.student_id
            ORDER BY s.name
        ");
        $all_financials = $all_financials_stmt->fetchAll(PDO::FETCH_ASSOC);
    } catch(PDOException $e) {
        error_log("All financials fetch error: " . $e->getMessage());
        $error = "Error fetching all financials.";
    }
}

// Handle initiate payment (student only)
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'initiate_payment' && $_POST['csrf_token'] === $csrf_token && $_SESSION['role'] === 'student') {
    $token = getPesapalToken();
    if ($token) {
        $amount = $financials['balance'];
        if ($amount > 0) {
            $description = "School fees payment";
            $reference = 'PAY-' . $_SESSION['student_id'] . '-' . time();
            $first_name = explode(' ', $user['name'])[0] ?? 'Student';
            $last_name = explode(' ', $user['name'])[1] ?? '';
            $email = $user['contact'] ?? 'student@example.com'; // Adjust if contact is phone
            $phone = $user['contact'] ?? '';

            $redirect_url = submitPesapalOrder($token, $amount, $description, $reference, $first_name, $last_name, $email, $phone);
            if ($redirect_url) {
                header("Location: " . $redirect_url);
                exit();
            } else {
                $error = "Failed to initiate payment.";
            }
        } else {
            $error = "No balance to pay.";
        }
    } else {
        $error = "Failed to authenticate with Pesapal.";
    }
}

// Handle logout
if (isset($_POST['logout']) && $_POST['csrf_token'] === $csrf_token) {
    session_unset();
    session_destroy();
    header("Location: login.php");
    exit();
}

// Handle messages from callback
if (isset($_GET['message'])) {
    $message = htmlspecialchars($_GET['message']);
    $alert_type = $_GET['alert_type'] ?? 'alert-success';
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta name="description" content="View financial details for Cypher University students.">
    <meta name="keywords" content="Cypher University, student portal, financials">
    <meta name="author" content="Cypher University">
    <title>Financials - Cypher University</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.10.5/font/bootstrap-icons.css">
    <link href="https://fonts.googleapis.com/css2?family=Poppins:wght@300;400;600&display=swap" rel="stylesheet">
    <style>
        /* General Styling */
        body {
            font-family: 'Poppins', sans-serif;
            background-color: #f5f6f5;
            color: #333;
            margin: 0;
            overflow-x: hidden;
        }

        /* Sticky Navbar */
        .navbar {
            background-color: #003087;
            padding: 8px 0;
            box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
            z-index: 1001;
            position: sticky;
            top: 0;
        }
        .navbar-brand {
            font-size: 1.25rem;
            font-weight: 600;
            color: #fff !important;
        }
        .nav-link {
            font-size: 0.9rem;
            color: #fff !important;
            padding: 6px 12px;
            transition: color 0.3s ease, background-color 0.3s ease;
        }
        .nav-link:hover {
            color: #a9d6e5 !important;
            background-color: rgba(255, 255, 255, 0.1);
            border-radius: 4px;
        }
        .navbar-toggler {
            border-color: rgba(255, 255, 255, 0.5);
        }

        /* Fixed Sidebar */
        .sidebar {
            position: fixed;
            top: 48px;
            left: 0;
            width: 250px;
            height: calc(100vh - 48px);
            background-color: #003087;
            color: #fff;
            overflow-y: auto;
            z-index: 1000;
            box-shadow: 2px 0 4px rgba(0, 0, 0, 0.1);
            transition: transform 0.3s ease;
        }
        .sidebar-header {
            border-bottom: 1px solid rgba(255, 255, 255, 0.2);
        }
        .sidebar .nav-link {
            font-size: 0.95rem;
            padding: 10px 15px;
            color: #fff;
            transition: background-color 0.3s ease, padding-left 0.3s ease;
        }
        .sidebar .nav-link:hover {
            background-color: rgba(255, 255, 255, 0.1);
            padding-left: 20px;
        }
        .profile-card {
            background: rgba(255, 255, 255, 0.05);
            border-radius: 8px;
            margin: 15px;
            padding: 15px;
        }
        .avatar {
            width: 80px;
            height: 80px;
            display: flex;
            align-items: center;
            justify-content: center;
            border-radius: 50%;
        }

        /* Scrollable Main Content */
        main {
            margin-left: 250px;
            padding: 20px;
            min-height: calc(100vh - 48px - 80px);
            overflow-y: auto;
            background-color: #fff;
            border-radius: 8px;
            box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
        }

        /* Static Footer */
        footer {
            position: relative;
            background-color: #003087;
            color: #fff;
            padding: 20px 0;
            margin-top: 20px;
        }
        footer a {
            color: #a9d6e5;
            text-decoration: none;
            transition: color 0.3s ease;
        }
        footer a:hover {
            color: #fff;
        }

        /* Hero Section */
        .hero-section {
            background: linear-gradient(135deg, #003087, #005f73);
            border-radius: 8px;
            padding: 20px;
            margin-bottom: 2rem;
            margin-left: 150px;
        }
        .hero-section h1 {
            font-size: 1.75rem;
            font-weight: 600;
        }
        .hero-section p {
            font-size: 1rem;
        }

        /* Section Titles */
        .section-title {
            font-size: 1.75rem;
            color: #003087;
            margin-bottom: 1rem;
            position: relative;
        }
        .section-title::after {
            content: '';
            display: block;
            width: 50px;
            height: 3px;
            background: #003087;
            margin-top: 0.5rem;
        }
        section{
            margin-left: 150px;
        }

        /* Cards */
        .card {
            border: none;
            border-radius: 8px;
            box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
            transition: transform 0.3s ease, box-shadow 0.3s ease;
        }
        .card:hover {
            transform: translateY(-5px);
            box-shadow: 0 6px 16px rgba(0, 0, 0, 0.2);
        }
        .card-title {
            font-size: 1.25rem;
            color: #003087;
            margin-bottom: 0.75rem;
        }
        .card-body {
            padding: 1.5rem;
        }

        /* Buttons */
        .btn-primary {
            background-color: #003087;
            border: none;
            padding: 0.75rem 1.5rem;
            border-radius: 8px;
            transition: background-color 0.3s ease;
        }
        .btn-primary:hover {
            background-color: #00205b;
        }
        .btn-outline-primary {
            border-color: #003087;
            color: #003087;
        }
        .btn-outline-primary:hover {
            background-color: #003087;
            color: #fff;
        }
        .btn-outline-success {
            border-color: #28a745;
            color: #28a745;
        }
        .btn-outline-success:hover {
            background-color: #28a745;
            color: #fff;
        }
        .btn-outline-danger {
            border-color: #dc3545;
            color: #dc3545;
        }
        .btn-outline-danger:hover {
            background-color: #dc3545;
            color: #fff;
        }

        /* Tables */
        .table {
            margin-top: 1rem;
        }
        .table th {
            background-color: #e9ecef;
            color: #003087;
        }

        /* Forms */
        .form-control {
            border-radius: 8px;
            border: 1px solid #ced4da;
            transition: border-color 0.3s ease, box-shadow 0.3s ease;
        }
        .form-control:focus {
            border-color: #003087;
            box-shadow: 0 0 5px rgba(0, 48, 135, 0.5);
        }
        .form-label {
            color: #003087;
        }

        /* Alerts */
        .alert {
            border-radius: 8px;
            font-size: 0.9rem;
        }

        /* Responsive Adjustments */
        @media (max-width: 991px) {
            .sidebar {
                display: none;
            }
            main {
                margin-left: 0;
                width: 100%;
            }
            .navbar-brand {
                font-size: 1.1rem;
            }
            .nav-link {
                font-size: 0.85rem;
            }
            .hero-section {
                padding: 2rem 0;
            }
            .hero-section h1 {
                font-size: 1.5rem;
            }
            .section-title {
                font-size: 1.5rem;
            }
        }
    </style>
</head>
<body>
    <!-- Sticky Navbar -->
    <nav class="navbar navbar-expand-lg bg-primary text-white">
        <div class="container-fluid">
            <a class="navbar-brand" href="#">Cypher University</a>
            <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNav" aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation">
                <span class="navbar-toggler-icon"></span>
            </button>
            <div class="collapse navbar-collapse" id="navbarNav">
                <ul class="navbar-nav ms-auto">
                    <li class="nav-item">
                        <a class="nav-link" href="index.php">Home</a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" href="about.php">About</a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" href="contact.php">Contact</a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" href="news.php">News</a>
                    </li>
                    <li class="nav-item">
                        <form method="POST" class="d-inline">
                            <input type="hidden" name="csrf_token" value="<?php echo htmlspecialchars($csrf_token); ?>">
                            <button type="submit" name="logout" class="nav-link bg-transparent border-0">Logout</button>
                        </form>
                    </li>
                </ul>
            </div>
        </div>
    </nav>

    <div class="d-flex">
        <!-- Fixed Sidebar -->
        <nav class="sidebar bg-primary text-white" id="sidebar">
            <div class="sidebar-header text-center p-3">
                <h4 class="mb-0">Cypher University</h4>
            </div>
            <div class="profile-card p-3">
                <div class="text-center">
                    <div class="avatar bg-light text-primary rounded-circle mx-auto mb-2">
                        <i class="bi bi-person-circle fs-2"></i>
                    </div>
                    <h6 class="mb-1"><?php echo htmlspecialchars($user['name'] ?? ($_SESSION['role'] === 'admin' ? 'Admin' : 'Student')); ?></h6>
                    <small class="text-white-50">Admission No: <?php echo htmlspecialchars($user['admission_no'] ?? 'N/A'); ?></small><br>
                    <small class="text-white-50">Programme: <?php echo htmlspecialchars($user['programme'] ?? 'N/A'); ?></small><br>
                    <small class="text-white-50">Stage: <?php echo htmlspecialchars($user['stage'] ?? 'N/A'); ?></small>
                </div>
            </div>
            <h5 class="p-3">MAIN NAVIGATION</h5>
            <ul class="nav flex-column p-3">
                <li class="nav-item">
                    <a class="nav-link text-white" href="<?php echo $_SESSION['role'] === 'admin' ? 'admin_page.php' : 'student_dashboard.php'; ?>"><i class="bi bi-house me-2"></i>Dashboard</a>
                </li>
                <li class="nav-item">
                    <a class="nav-link text-white active" href="financials.php"><i class="bi bi-wallet me-2"></i>Financials</a>
                </li>
                <li class="nav-item">
                    <a class="nav-link text-white" href="academics.php"><i class="bi bi-book me-2"></i>Academics</a>
                </li>
                <?php if ($_SESSION['role'] === 'admin'): ?>
                    <li class="nav-item">
                        <a class="nav-link text-white" href="manage_students.php"><i class="bi bi-people me-2"></i>Manage Students</a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link text-white" href="manage_news.php"><i class="bi bi-newspaper me-2"></i>Manage News</a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link text-white" href="manage_timetables.php"><i class="bi bi-calendar me-2"></i>Manage Timetables</a>
                    </li>
                <?php endif; ?>
                <li class="nav-item">
                    <a class="nav-link text-white" href="student_requests.php"><i class="bi bi-file-text me-2"></i>Student Requests</a>
                </li>
                <li class="nav-item">
                    <a class="nav-link text-white" href="accommodation.php"><i class="bi bi-building me-2"></i>Accommodation</a>
                </li>
                <li class="nav-item">
                    <a class="nav-link text-white" href="special_exams.php"><i class="bi bi-pencil-square me-2"></i>Special Exams</a>
                </li>
                <li class="nav-item">
                    <a class="nav-link text-white" href="downloads.php"><i class="bi bi-download me-2"></i>Downloads</a>
                </li>
                <li class="nav-item">
                    <a class="nav-link text-white" href="clearance.php"><i class="bi bi-check-circle me-2"></i>Students Clearance</a>
                </li>
                <li class="nav-item">
                    <a class="nav-link text-white" href="transfer.php"><i class="bi bi-arrow-left-right me-2"></i>Inter-School Transfer</a>
                </li>
                <li class="nav-item">
                    <a class="nav-link text-white" href="settings.php"><i class="bi bi-gear me-2"></i>Settings</a>
                </li>
                <li class="nav-item">
                    <form method="POST">
                        <input type="hidden" name="csrf_token" value="<?php echo htmlspecialchars($csrf_token); ?>">
                        <button type="submit" name="logout" class="nav-link text-white bg-transparent border-0"><i class="bi bi-box-arrow-right me-2"></i>Logout</button>
                    </form>
                </li>
            </ul>
            <h5 class="p-3">PERIODIC ACTIVITIES</h5>
            <ul class="nav flex-column p-3">
                <li class="nav-item">
                    <a class="nav-link text-white" href="lecturers_evaluation.php"><i class="bi bi-person-check me-2"></i>Lecturers Evaluation</a>
                </li>
                <li class="nav-item">
                    <a class="nav-link text-white" href="msu_election.php"><i class="bi bi-box-seam me-2"></i>MSU Election</a>
                </li>
                <li class="nav-item">
                    <a class="nav-link text-white" href="notice_board.php"><i class="bi bi-megaphone me-2"></i>Notice Board</a>
                </li>
                <li class="nav-item">
                    <a class="nav-link text-white" href="https://facebook.com/Cypher" target="_blank"><i class="bi bi-facebook me-2"></i>MSU Official Facebook</a>
                </li>
            </ul>
        </nav>

        <!-- Main Content -->
        <main class="flex-grow-1 p-4 container">
            <button class="btn btn-primary d-lg-none mb-3" type="button" data-bs-toggle="offcanvas" data-bs-target="#sidebarOffcanvas" aria-controls="sidebarOffcanvas">
                <i class="bi bi-list"></i> Menu
            </button>
            <div class="offcanvas offcanvas-start bg-primary text-white" tabindex="-1" id="sidebarOffcanvas" aria-labelledby="sidebarOffcanvasLabel">
                <div class="offcanvas-header">
                    <h5 class="offcanvas-title" id="sidebarOffcanvasLabel">Cypher University</h5>
                    <button type="button" class="btn-close btn-close-white" data-bs-dismiss="offcanvas" aria-label="Close"></button>
                </div>
                <div class="offcanvas-body">
                    <div class="profile-card p-3">
                        <div class="text-center">
                            <div class="avatar bg-light text-primary rounded-circle mx-auto mb-2">
                                <i class="bi bi-person-circle fs-2"></i>
                            </div>
                            <h6 class="mb-1"><?php echo htmlspecialchars($user['name'] ?? ($_SESSION['role'] === 'admin' ? 'Admin' : 'Student')); ?></h6>
                            <small class="text-white-50">Admission No: <?php echo htmlspecialchars($user['admission_no'] ?? 'N/A'); ?></small><br>
                            <small class="text-white-50">Programme: <?php echo htmlspecialchars($user['programme'] ?? 'N/A'); ?></small><br>
                            <small class="text-white-50">Stage: <?php echo htmlspecialchars($user['stage'] ?? 'N/A'); ?></small>
                        </div>
                    </div>
                    <h5>MAIN NAVIGATION</h5>
                    <ul class="nav flex-column">
                        <li class="nav-item">
                            <a class="nav-link text-white" href="<?php echo $_SESSION['role'] === 'admin' ? 'admin_page.php' : 'student_dashboard.php'; ?>"><i class="bi bi-house me-2"></i>Dashboard</a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link text-white active" href="financials.php"><i class="bi bi-wallet me-2"></i>Financials</a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link text-white" href="academics.php"><i class="bi bi-book me-2"></i>Academics</a>
                        </li>
                        <?php if ($_SESSION['role'] === 'admin'): ?>
                            <li class="nav-item">
                                <a class="nav-link text-white" href="manage_students.php"><i class="bi bi-people me-2"></i>Manage Students</a>
                            </li>
                            <li class="nav-item">
                                <a class="nav-link text-white" href="manage_news.php"><i class="bi bi-newspaper me-2"></i>Manage News</a>
                            </li>
                            <li class="nav-item">
                                <a class="nav-link text-white" href="manage_timetables.php"><i class="bi bi-calendar me-2"></i>Manage Timetables</a>
                            </li>
                        <?php endif; ?>
                        <li class="nav-item">
                            <a class="nav-link text-white" href="student_requests.php"><i class="bi bi-file-text me-2"></i>Student Requests</a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link text-white" href="accommodation.php"><i class="bi bi-building me-2"></i>Accommodation</a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link text-white" href="special_exams.php"><i class="bi bi-pencil-square me-2"></i>Special Exams</a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link text-white" href="downloads.php"><i class="bi bi-download me-2"></i>Downloads</a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link text-white" href="clearance.php"><i class="bi bi-check-circle me-2"></i>Students Clearance</a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link text-white" href="transfer.php"><i class="bi bi-arrow-left-right me-2"></i>Inter-School Transfer</a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link text-white" href="settings.php"><i class="bi bi-gear me-2"></i>Settings</a>
                        </li>
                        <li class="nav-item">
                            <form method="POST">
                                <input type="hidden" name="csrf_token" value="<?php echo htmlspecialchars($csrf_token); ?>">
                                <button type="submit" name="logout" class="nav-link text-white bg-transparent border-0"><i class="bi bi-box-arrow-right me-2"></i>Logout</button>
                            </form>
                        </li>
                    </ul>
                    <h5>PERIODIC ACTIVITIES</h5>
                    <ul class="nav flex-column">
                        <li class="nav-item">
                            <a class="nav-link text-white" href="lecturers_evaluation.php"><i class="bi bi-person-check me-2"></i>Lecturers Evaluation</a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link text-white" href="msu_election.php"><i class="bi bi-box-seam me-2"></i>MSU Election</a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link text-white" href="notice_board.php"><i class="bi bi-megaphone me-2"></i>Notice Board</a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link text-white" href="https://facebook.com/Cypher" target="_blank"><i class="bi bi-facebook me-2"></i>MSU Official Facebook</a>
                        </li>
                    </ul>
                </div>
            </div>

            <!-- Hero Section -->
            <header class="hero-section text-white text-center py-4 rounded mb-4">
                <h1 class="display-5">Financials</h1>
                <p class="lead">View your financial details for Cypher University</p>
                <small class="text-white-50">Online</small>
            </header>

            <?php if (isset($message)): ?>
                <div class="alert <?php echo htmlspecialchars($alert_type); ?> alert-dismissible fade show" role="alert">
                    <?php echo htmlspecialchars($message); ?>
                    <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
                </div>
            <?php endif; ?>

            <?php if (isset($error)): ?>
                <div class="alert alert-danger alert-dismissible fade show" role="alert">
                    <?php echo htmlspecialchars($error); ?>
                    <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
                </div>
            <?php endif; ?>

            <!-- Financial Overview -->
            <section class="mb-5">
                <h2 class="section-title">Financial Overview</h2>
                <div class="row g-4">
                    <div class="col-md-4">
                        <div class="card text-center">
                            <div class="card-body">
                                <h5 class="card-title">Total Billed</h5>
                                <p class="card-text">KES <?php echo number_format($financials['total_billed'], 2); ?></p>
                            </div>
                        </div>
                    </div>
                    <div class="col-md-4">
                        <div class="card text-center">
                            <div class="card-body">
                                <h5 class="card-title">Total Paid</h5>
                                <p class="card-text">KES <?php echo number_format($financials['total_paid'], 2); ?></p>
                            </div>
                        </div>
                    </div>
                    <div class="col-md-4">
                        <div class="card text-center">
                            <div class="card-body">
                                <h5 class="card-title">Balance</h5>
                                <p class="card-text">KES <?php echo number_format($financials['balance'], 2); ?></p>
                                <?php if ($_SESSION['role'] === 'student' && $financials['balance'] > 0): ?>
                                    <form method="POST">
                                        <input type="hidden" name="action" value="initiate_payment">
                                        <input type="hidden" name="csrf_token" value="<?php echo htmlspecialchars($csrf_token); ?>">
                                        <button type="submit" class="btn btn-primary mt-2">Pay Balance with Pesapal</button>
                                    </form>
                                <?php endif; ?>
                            </div>
                        </div>
                    </div>
                </div>
            </section>

            <!-- Transaction History -->
            <section class="mb-5">
                <h2 class="section-title">Transaction History</h2>
                <div class="table-responsive">
                    <table class="table table-bordered table-striped">
                        <thead>
                            <tr>
                                <th scope="col">Date</th>
                                <th scope="col">Type</th>
                                <th scope="col">Amount</th>
                                <th scope="col">Description</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php if (!empty($transactions)): ?>
                                <?php foreach ($transactions as $transaction): ?>
                                    <tr>
                                        <td><?php echo date('F j, Y H:i', strtotime($transaction['transaction_date'])); ?></td>
                                        <td><?php echo htmlspecialchars($transaction['transaction_type']); ?></td>
                                        <td>KES <?php echo number_format($transaction['amount'], 2); ?></td>
                                        <td><?php echo htmlspecialchars($transaction['description'] ?? 'N/A'); ?></td>
                                    </tr>
                                <?php endforeach; ?>
                            <?php else: ?>
                                <tr><td colspan="4" class="text-center">No transactions found.</td></tr>
                            <?php endif; ?>
                        </tbody>
                    </table>
                </div>
            </section>

            <?php if ($_SESSION['role'] === 'admin'): ?>
                <!-- All Students Financials (Admin Only) -->
                <section class="mb-5">
                    <h2 class="section-title">All Students Financials</h2>
                    <div class="mb-3">
                        <a href="financials.php?view_all=<?php echo isset($_GET['view_all']) && $_GET['view_all'] === 'true' ? 'false' : 'true'; ?>" class="btn btn-primary">
                            <?php echo isset($_GET['view_all']) && $_GET['view_all'] === 'true' ? 'Hide All Financials' : 'View All Financials'; ?>
                        </a>
                    </div>
                    <?php if (!empty($all_financials)): ?>
                        <div class="table-responsive">
                            <table class="table table-bordered table-striped">
                                <thead>
                                    <tr>
                                        <th scope="col">Student ID</th>
                                        <th scope="col">Name</th>
                                        <th scope="col">Admission No</th>
                                        <th scope="col">Total Billed</th>
                                        <th scope="col">Total Paid</th>
                                        <th scope="col">Balance</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php foreach ($all_financials as $student): ?>
                                        <tr>
                                            <td><?php echo htmlspecialchars($student['id']); ?></td>
                                            <td><?php echo htmlspecialchars($student['name']); ?></td>
                                            <td><?php echo htmlspecialchars($student['admission_no'] ?? 'N/A'); ?></td>
                                            <td>KES <?php echo number_format($student['total_billed'] ?? 0.00, 2); ?></td>
                                            <td>KES <?php echo number_format($student['total_paid'] ?? 0.00, 2); ?></td>
                                            <td>KES <?php echo number_format($student['balance'] ?? 0.00, 2); ?></td>
                                        </tr>
                                    <?php endforeach; ?>
                                </tbody>
                            </table>
                        </div>
                    <?php elseif (isset($_GET['view_all']) && $_GET['view_all'] === 'true'): ?>
                        <p class="card-text text-muted">No financial records found for students.</p>
                    <?php endif; ?>
                </section>
            <?php endif; ?>
        </main>
    </div>

    <!-- Footer -->
    <footer class="bg-dark text-white text-center py-4">
        <div class="container">
            <p>&copy; <?php echo date("Y"); ?> Cypher University. Powered by AppKings Solutions Limited.</p>
            <p>Email: <a href="mailto:info@Cypher.ac.ke" class="text-white">info@Cypher.ac.ke</a> | Phone: <a href="tel:+254123456789" class="text-white">+254 123 456 789</a></p>
        </div>
    </footer>

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