<?php
session_start();
require_once 'config.php'; // Ensure this path is correct

// Define role constants
if (!defined('ROLE_SUPER_ADMIN')) define('ROLE_SUPER_ADMIN', 1);
if (!defined('ROLE_ADMIN')) define('ROLE_ADMIN', 2);
if (!defined('ROLE_TEACHER')) define('ROLE_TEACHER', 2);
if (!defined('ROLE_STUDENT')) define('ROLE_STUDENT', 4);
if (!defined('ROLE_PARENT')) define('ROLE_PARENT', 5);
if (!defined('ROLE_STAFF')) define('ROLE_STAFF', 6);

// Function to check user role and redirect if unauthorized
function check_role_access($required_role_code) {
    if (!isset($_SESSION["loggedin"]) || $_SESSION["loggedin"] !== true || !isset($_SESSION["school_id"])) {
        header("location: login.php");
        exit;
    }

    if ($_SESSION["role"] !== $required_role_code) {
        switch ($_SESSION["role"]) {
            case ROLE_SUPER_ADMIN:
                header("location: super_admin_dashboard.php");
                break;
            case ROLE_TEACHER:
                header("location: teacher_dashboard.php");
                break;
            case ROLE_STUDENT:
                header("location: student_dashboard.php");
                break;
            default:
                header("location: login.php");
                break;
        }
        exit;
    }
}

// Call the check for Admin role
check_role_access(ROLE_ADMIN);

$user_id = $_SESSION["id"];
$username = htmlspecialchars($_SESSION["username"]);
$school_id = $_SESSION["school_id"];

// Initialize school name and logo for header/sidebar
$school_name = "School Name"; // Default if not fetched
$school_logo_path = "images/default_school_logo.png"; // Default if not fetched
$photo = 'https://via.placeholder.com/80/cccccc/FFFFFF?text=AD'; // Default user photo

// Determine role name for display (for header/sidebar)
$role_name = "Unknown";
switch ($_SESSION["role"]) {
    case ROLE_SUPER_ADMIN: $role_name = "Super Admin"; break;
    case ROLE_ADMIN:        $role_name = "Admin";       break;
    case ROLE_TEACHER:      $role_name = "Teacher";     break;
    case ROLE_STUDENT:      $role_name = "Student";     break;
    case ROLE_PARENT:       $role_name = "Parent";      break;
    case ROLE_STAFF:        $role_name = "Staff";       break;
}

// Ensure $conn is available from config.php
if (isset($conn) && $conn instanceof mysqli) {
    // Fetch user's photo for display in header
    $sql_user_photo = "SELECT photo FROM users WHERE id = ? AND school_id = ?";
    if ($stmt_user_photo = $conn->prepare($sql_user_photo)) {
        $stmt_user_photo->bind_param("ii", $user_id, $school_id);
        $stmt_user_photo->execute();
        $stmt_user_photo->bind_result($photo_db);
        if ($stmt_user_photo->fetch()) {
            $photo = !empty($photo_db) ? htmlspecialchars($photo_db) : 'https://via.placeholder.com/80/cccccc/FFFFFF?text=AD';
        }
        $stmt_user_photo->close();
    } else {
        error_log("Failed to prepare user photo query: " . $conn->error);
    }

    // Fetch school name and logo for header/sidebar
    $sql_school_info = "SELECT school_name, logo FROM schools WHERE school_id = ?";
    if ($stmt_school_info = $conn->prepare($sql_school_info)) {
        $stmt_school_info->bind_param("i", $school_id);
        $stmt_school_info->execute();
        $stmt_school_info->bind_result($school_name_fetched, $school_logo_fetched);
        if ($stmt_school_info->fetch()) {
            $school_name = htmlspecialchars($school_name_fetched);
            $school_logo_path = !empty($school_logo_fetched) ? htmlspecialchars($school_logo_fetched) : 'images/default_school_logo.png';
        }
        $stmt_school_info->close();
    } else {
        error_log("Failed to prepare school info query: " . $conn->error);
    }

    $conn->close(); // Close the database connection
} else {
    error_log("Database connection \$conn not available in admin_financial_reports.php");
}

// Placeholder for financial data - no specific tables in schema for this yet.
$financial_summary = [
    'total_fees_expected' => 'N/A',
    'total_fees_collected' => 'N/A',
    'outstanding_balance' => 'N/A',
    'total_expenses' => 'N/A',
    'net_balance' => 'N/A'
];
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Financial Reports - <?php echo $school_name; ?></title>
    <link href="https://cdn.jsdelivr.net/npm/tailwindcss@2.2.19/dist/tailwind.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0-beta3/css/all.min.css">
    <link rel="stylesheet" href="style.css">
    <style>
        @media print {
            body * {
                visibility: hidden;
            }
            #report-content, #report-content * {
                visibility: visible;
            }
            #report-content {
                position: absolute;
                left: 0;
                top: 0;
                width: 100%;
                padding: 20px;
            }
            .no-print {
                display: none !important;
            }
        }
        .report-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 1.5rem;
            border-bottom: 2px solid #e2e8f0;
            padding-bottom: 1rem;
        }
        .report-header img {
            max-height: 80px;
            width: auto;
        }
        .report-header h2 {
            font-size: 1.875rem;
            font-weight: 700;
            color: #1e293b;
            text-align: right;
        }
        .summary-card {
            background-color: #f8fafc;
            border: 1px solid #e2e8f0;
            border-radius: 0.5rem;
            padding: 1.5rem;
            margin-bottom: 1.5rem;
            box-shadow: 0 1px 3px rgba(0,0,0,0.1);
        }
        .summary-item {
            display: flex;
            justify-content: space-between;
            padding: 0.5rem 0;
            border-bottom: 1px dashed #e2e8f0;
        }
        .summary-item:last-child {
            border-bottom: none;
        }
        .summary-label {
            font-weight: 600;
            color: #475569;
        }
        .summary-value {
            font-weight: 700;
            color: #1e293b;
        }
        .print-button {
            background-color: #2563eb;
            color: white;
            padding: 0.75rem 1.5rem;
            border-radius: 0.5rem;
            font-weight: 600;
            cursor: pointer;
            transition: background-color 0.2s ease-in-out;
            display: inline-flex;
            align-items: center;
            gap: 0.5rem;
        }
        .print-button:hover {
            background-color: #1d4ed8;
        }
    </style>
</head>
<body class="bg-gray-100 font-sans">

    <?php include 'admin_navbar.php'; ?>

    <div class="dashboard-container" id="dashboardContainer">
        <!-- Sidebar -->
        <aside class="sidebar" id="sidebar">
            <div class="logo">
                <img src="images/logo.png" alt="divine Logo">
                DIVINE REPORTS
            </div>
            <nav>
                <ul>
                    <li><a href="admin_dashboard.php"><i class="fas fa-th-large"></i> Dashboard</a></li>
                    <li><a href="admin_calendar.php"><i class="far fa-calendar-alt"></i> Calendar</a></li>
                    <li><a href="admin_user_management.php"><i class="fas fa-users-cog"></i> User Management</a></li>
                    <li><a href="admin_students.php"><i class="fas fa-user-graduate"></i> Students</a></li>
                    <li><a href="admin_teachers.php"><i class="fas fa-chalkboard-teacher"></i> Teachers</a></li>
                    <li><a href="admin_staff.php"><i class="fas fa-user-friends"></i> Staff</a></li>
                    <li><a href="admin_classes.php"><i class="fas fa-chalkboard"></i> Classes</a></li>
                    <li><a href="admin_subjects.php"><i class="fas fa-chalkboard"></i> Subjects</a></li>
                    <li><a href="admin_exams.php"><i class="fas fa-file-alt"></i> Exam Management</a></li>
                    <li><a href="admin_messages.php"><i class="fas fa-envelope"></i> Messages</a></li>
                    <li class="active"><a href="admin_reports_printouts.php"><i class="fas fa-print"></i> Reports & Printouts</a></li>
                    <li><a href="admin_system_settings.php"><i class="fas fa-cog"></i> System Settings</a></li>
                    <li><a href="logout.php"><i class="fas fa-sign-out-alt"></i> Logout</a></li>
                </ul>
            </nav>
        </aside>

        <div class="main-content">
            <div class="content-area p-6">
                <h1 class="text-3xl font-bold text-gray-800 mb-6 no-print">Financial Reports</h1>

                <div class="bg-white p-6 rounded-lg shadow-md mb-6 no-print">
                    <p class="text-gray-600 mb-4">
                        This section provides an overview of the school's financial status.
                        Please note: The current database schema does not include tables for detailed financial transactions (e.g., fees, payments, expenses).
                        The data displayed here is placeholder information.
                    </p>
                    <button type="button" onclick="window.print()" class="print-button">
                        <i class="fas fa-print"></i> Print Report
                    </button>
                </div>

                <div id="report-content" class="bg-white p-6 rounded-lg shadow-md">
                    <div class="report-header">
                        <img src="<?php echo $school_logo_path; ?>" alt="<?php echo $school_name; ?> Logo">
                        <div>
                            <h2 class="text-right"><?php echo $school_name; ?></h2>
                            <p class="text-gray-600 text-sm text-right">Financial Summary Report</p>
                            <p class="text-gray-600 text-xs text-right">Date Generated: <?php echo date('F j, Y'); ?></p>
                        </div>
                    </div>

                    <div class="summary-card">
                        <h3 class="text-xl font-semibold text-gray-700 mb-4">Overall Financial Summary</h3>
                        <div class="space-y-2">
                            <div class="summary-item">
                                <span class="summary-label">Total Fees Expected:</span>
                                <span class="summary-value"><?php echo htmlspecialchars($financial_summary['total_fees_expected']); ?></span>
                            </div>
                            <div class="summary-item">
                                <span class="summary-label">Total Fees Collected:</span>
                                <span class="summary-value"><?php echo htmlspecialchars($financial_summary['total_fees_collected']); ?></span>
                            </div>
                            <div class="summary-item">
                                <span class="summary-label">Outstanding Balance:</span>
                                <span class="summary-value"><?php echo htmlspecialchars($financial_summary['outstanding_balance']); ?></span>
                            </div>
                            <div class="summary-item">
                                <span class="summary-label">Total Expenses:</span>
                                <span class="summary-value"><?php echo htmlspecialchars($financial_summary['total_expenses']); ?></span>
                            </div>
                            <div class="summary-item">
                                <span class="summary-label">Net Balance:</span>
                                <span class="summary-value"><?php echo htmlspecialchars($financial_summary['net_balance']); ?></span>
                            </div>
                        </div>
                    </div>

                    <p class="text-gray-500 text-center text-sm mt-8">
                        This report provides a high-level financial summary. For detailed financial reporting,
                        dedicated financial modules and database tables would be required.
                    </p>
                </div>
            </div>
        </div>
    </div>

    <div class="overlay" id="overlay"></div>

    <script>
        document.addEventListener('DOMContentLoaded', function() {
            const menuToggle = document.getElementById('menuToggle');
            const sidebar = document.getElementById('sidebar');
            const dashboardContainer = document.getElementById('dashboardContainer');
            const overlay = document.getElementById('overlay');

            menuToggle.addEventListener('click', function() {
                sidebar.classList.toggle('active');
                dashboardContainer.classList.toggle('sidebar-open');
                overlay.classList.toggle('active');
            });

            overlay.addEventListener('click', function() {
                sidebar.classList.remove('active');
                dashboardContainer.classList.remove('sidebar-open');
                overlay.classList.remove('active');
            });
        });
    </script>
</body>
</html>
