<?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;
}

$classes_data = [];
$subjects_data = [];
$selected_class_id = isset($_GET['class_id']) ? (int)$_GET['class_id'] : 0;

// 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);
    }

    // Fetch classes for the dropdown and report
    $sql_classes = "
        SELECT
            c.class_id,
            c.class_name,
            COUNT(DISTINCT s.ADM) AS total_students,
            GROUP_CONCAT(DISTINCT sub.subject_name ORDER BY sub.subject_name ASC SEPARATOR ', ') AS assigned_subjects,
            GROUP_CONCAT(DISTINCT st.stream_name ORDER BY st.stream_name ASC SEPARATOR ', ') AS streams
        FROM classes c
        LEFT JOIN students s ON c.class_id = s.class_id AND c.school_id = s.school_id
        LEFT JOIN class_subjects cs ON c.class_id = cs.class_id
        LEFT JOIN subjects sub ON cs.subject_id = sub.subject_id AND sub.school_id = c.school_id
        LEFT JOIN streams st ON c.class_id = st.class_id AND c.school_id = st.school_id
        WHERE c.school_id = ?
    ";
    $params = [$school_id];
    $types = "i";

    if ($selected_class_id > 0) {
        $sql_classes .= " AND c.class_id = ?";
        $params[] = $selected_class_id;
        $types .= "i";
    }
    $sql_classes .= " GROUP BY c.class_id ORDER BY c.class_name ASC";

    if ($stmt_classes = $conn->prepare($sql_classes)) {
        $stmt_classes->bind_param($types, ...$params);
        $stmt_classes->execute();
        $result_classes = $stmt_classes->get_result();
        while ($row = $result_classes->fetch_assoc()) {
            $classes_data[] = $row;
        }
        $stmt_classes->close();
    } else {
        error_log("Failed to prepare classes data query: " . $conn->error);
    }

    // Fetch all subjects for a general subject list report
    $sql_subjects = "SELECT subject_id, subject_name FROM subjects WHERE school_id = ? ORDER BY subject_name ASC";
    if ($stmt_subjects = $conn->prepare($sql_subjects)) {
        $stmt_subjects->bind_param("i", $school_id);
        $stmt_subjects->execute();
        $result_subjects = $stmt_subjects->get_result();
        while ($row = $result_subjects->fetch_assoc()) {
            $subjects_data[] = $row;
        }
        $stmt_subjects->close();
    } else {
        error_log("Failed to prepare subjects data query: " . $conn->error);
    }

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

?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Class & Subject 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-classes, #report-content-subjects, #report-content-classes *, #report-content-subjects * {
                visibility: visible;
            }
            #report-content-classes, #report-content-subjects {
                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;
        }
        table {
            width: 100%;
            border-collapse: collapse;
            margin-top: 1rem;
        }
        th, td {
            border: 1px solid #cbd5e1;
            padding: 0.75rem;
            text-align: left;
            font-size: 0.9rem;
            color: #334155;
        }
        th {
            background-color: #e2e8f0;
            font-weight: 600;
            color: #475569;
        }
        tr:nth-child(even) {
            background-color: #f8fafc;
        }
        .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">Class & Subject Reports</h1>

                <div class="bg-white p-6 rounded-lg shadow-md mb-6 no-print">
                    <form action="admin_class_subject_reports.php" method="GET" class="flex flex-col md:flex-row items-center gap-4">
                        <div class="flex-grow w-full">
                            <label for="class_id" class="block text-sm font-medium text-gray-700 mb-1">Filter Classes by Name:</label>
                            <select id="class_id" name="class_id" class="mt-1 block w-full pl-3 pr-10 py-2 text-base border-gray-300 focus:outline-none focus:ring-blue-500 focus:border-blue-500 sm:text-sm rounded-md">
                                <option value="0">All Classes</option>
                                <?php foreach ($classes_data as $class): ?>
                                    <option value="<?php echo htmlspecialchars($class['class_id']); ?>" <?php echo ($selected_class_id == $class['class_id'] ? 'selected' : ''); ?>>
                                        <?php echo htmlspecialchars($class['class_name']); ?>
                                    </option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                        <button type="submit" class="mt-4 md:mt-0 px-6 py-2 bg-blue-600 text-white rounded-md hover:bg-blue-700 transition duration-150 ease-in-out">
                            Generate Class Report
                        </button>
                        <button type="button" onclick="printElement('report-content-classes')" class="mt-4 md:mt-0 print-button">
                            <i class="fas fa-print"></i> Print Class Report
                        </button>
                        <button type="button" onclick="printElement('report-content-subjects')" class="mt-4 md:mt-0 print-button">
                            <i class="fas fa-print"></i> Print Subject List
                        </button>
                    </form>
                </div>

                <!-- Class Report Section -->
                <div id="report-content-classes" class="bg-white p-6 rounded-lg shadow-md mb-8">
                    <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">Class Overview Report</p>
                            <?php if ($selected_class_id > 0): ?>
                                <?php
                                    $current_class_name = "N/A";
                                    foreach ($classes_data as $c) {
                                        if ($c['class_id'] == $selected_class_id) {
                                            $current_class_name = $c['class_name'];
                                            break;
                                        }
                                    }
                                ?>
                                <p class="text-gray-600 text-sm text-right">For Class: <span class="font-semibold"><?php echo htmlspecialchars($current_class_name); ?></span></p>
                            <?php else: ?>
                                <p class="text-gray-600 text-sm text-right">For All Classes</p>
                            <?php endif; ?>
                            <p class="text-gray-600 text-xs text-right">Date: <?php echo date('F j, Y'); ?></p>
                        </div>
                    </div>

                    <?php if (empty($classes_data)): ?>
                        <p class="text-gray-500 text-center">No classes found for the selected criteria.</p>
                    <?php else: ?>
                        <table class="min-w-full bg-white">
                            <thead>
                                <tr>
                                    <th>#</th>
                                    <th>Class Name</th>
                                    <th>Total Students</th>
                                    <th>Streams</th>
                                    <th>Assigned Subjects</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php $counter = 1; ?>
                                <?php foreach ($classes_data as $class): ?>
                                    <tr>
                                        <td><?php echo $counter++; ?></td>
                                        <td><?php echo htmlspecialchars($class['class_name']); ?></td>
                                        <td><?php echo htmlspecialchars($class['total_students']); ?></td>
                                        <td><?php echo htmlspecialchars($class['streams'] ?? 'N/A'); ?></td>
                                        <td><?php echo htmlspecialchars($class['assigned_subjects'] ?? 'N/A'); ?></td>
                                    </tr>
                                <?php endforeach; ?>
                            </tbody>
                        </table>
                    <?php endif; ?>
                </div>

                <!-- Subject List Report Section -->
                <div id="report-content-subjects" 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">All Subjects List</p>
                            <p class="text-gray-600 text-xs text-right">Date: <?php echo date('F j, Y'); ?></p>
                        </div>
                    </div>

                    <?php if (empty($subjects_data)): ?>
                        <p class="text-gray-500 text-center">No subjects found.</p>
                    <?php else: ?>
                        <table class="min-w-full bg-white">
                            <thead>
                                <tr>
                                    <th>#</th>
                                    <th>Subject Name</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php $counter = 1; ?>
                                <?php foreach ($subjects_data as $subject): ?>
                                    <tr>
                                        <td><?php echo $counter++; ?></td>
                                        <td><?php echo htmlspecialchars($subject['subject_name']); ?></td>
                                    </tr>
                                <?php endforeach; ?>
                            </tbody>
                        </table>
                    <?php endif; ?>
                </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');
            });

            // Function to print a specific element
            window.printElement = function(elementId) {
                const printContents = document.getElementById(elementId).innerHTML;
                const originalContents = document.body.innerHTML;

                document.body.innerHTML = printContents;
                window.print();
                document.body.innerHTML = originalContents; // Restore original content
                // Re-attach event listeners after restoring content
                attachEventListeners();
            }

            // Function to re-attach event listeners (important after printElement)
            function attachEventListeners() {
                const menuToggle = document.getElementById('menuToggle');
                const sidebar = document.getElementById('sidebar');
                const dashboardContainer = document.getElementById('dashboardContainer');
                const overlay = document.getElementById('overlay');

                if (menuToggle) {
                    menuToggle.addEventListener('click', function() {
                        sidebar.classList.toggle('active');
                        dashboardContainer.classList.toggle('sidebar-open');
                        overlay.classList.toggle('active');
                    });
                }
                if (overlay) {
                    overlay.addEventListener('click', function() {
                        sidebar.classList.remove('active');
                        dashboardContainer.classList.remove('sidebar-open');
                        overlay.classList.remove('active');
                    });
                }
            }
            // Initial attachment of event listeners
            attachEventListeners();
        });
    </script>
</body>
</html>
