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

$attendance_records = [];
$classes = [];
$selected_class_id = isset($_GET['class_id']) ? (int)$_GET['class_id'] : 0;
$start_date = isset($_GET['start_date']) ? $_GET['start_date'] : '';
$end_date = isset($_GET['end_date']) ? $_GET['end_date'] : '';

// Set default dates if not provided
if (empty($start_date)) {
    $start_date = date('Y-m-01'); // First day of current month
}
if (empty($end_date)) {
    $end_date = date('Y-m-t'); // Last day of current month
}

// 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
    $sql_classes = "SELECT class_id, class_name FROM classes WHERE school_id = ? ORDER BY class_name ASC";
    if ($stmt_classes = $conn->prepare($sql_classes)) {
        $stmt_classes->bind_param("i", $school_id);
        $stmt_classes->execute();
        $result_classes = $stmt_classes->get_result();
        while ($row = $result_classes->fetch_assoc()) {
            $classes[] = $row;
        }
        $stmt_classes->close();
    } else {
        error_log("Failed to prepare classes query: " . $conn->error);
    }

    // Placeholder for fetching attendance data (assuming an 'attendance' table)
    // The schema provided does not have an 'attendance' table.
    // For demonstration, this query will be commented out, and $attendance_records will remain empty.
    // If you have an attendance table, uncomment and adjust this query.
    /*
    $sql_attendance = "
        SELECT
            u.username AS student_name,
            s.ADM,
            c.class_name,
            att.attendance_date,
            att.status AS attendance_status,
            att.remarks
        FROM attendance att
        JOIN users u ON att.user_id = u.id AND att.school_id = u.school_id
        LEFT JOIN students s ON u.id = s.user_id AND u.school_id = s.school_id
        LEFT JOIN classes c ON s.class_id = c.class_id AND s.school_id = c.school_id
        WHERE att.school_id = ? AND att.attendance_date BETWEEN ? AND ?
    ";
    $params = [$school_id, $start_date, $end_date];
    $types = "iss";

    if ($selected_class_id > 0) {
        $sql_attendance .= " AND c.class_id = ?";
        $params[] = $selected_class_id;
        $types .= "i";
    }
    $sql_attendance .= " ORDER BY att.attendance_date ASC, u.username ASC";

    if ($stmt_attendance = $conn->prepare($sql_attendance)) {
        $stmt_attendance->bind_param($types, ...$params);
        $stmt_attendance->execute();
        $result_attendance = $stmt_attendance->get_result();
        while ($row = $result_attendance->fetch_assoc()) {
            $attendance_records[] = $row;
        }
        $stmt_attendance->close();
    } else {
        error_log("Failed to prepare attendance query: " . $conn->error);
    }
    */

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

?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Attendance 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;
        }
        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">Attendance Reports</h1>

                <div class="bg-white p-6 rounded-lg shadow-md mb-6 no-print">
                    <form action="admin_attendance_reports.php" method="GET" class="flex flex-col md:flex-row items-end gap-4">
                        <div class="flex-grow w-full">
                            <label for="class_id" class="block text-sm font-medium text-gray-700 mb-1">Filter by Class (Optional):</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 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>
                        <div class="flex-grow w-full">
                            <label for="start_date" class="block text-sm font-medium text-gray-700 mb-1">Start Date:</label>
                            <input type="date" id="start_date" name="start_date" value="<?php echo htmlspecialchars($start_date); ?>" required class="mt-1 block w-full pl-3 pr-3 py-2 text-base border-gray-300 focus:outline-none focus:ring-blue-500 focus:border-blue-500 sm:text-sm rounded-md">
                        </div>
                        <div class="flex-grow w-full">
                            <label for="end_date" class="block text-sm font-medium text-gray-700 mb-1">End Date:</label>
                            <input type="date" id="end_date" name="end_date" value="<?php echo htmlspecialchars($end_date); ?>" required class="mt-1 block w-full pl-3 pr-3 py-2 text-base border-gray-300 focus:outline-none focus:ring-blue-500 focus:border-blue-500 sm:text-sm rounded-md">
                        </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 Report
                        </button>
                        <button type="button" onclick="window.print()" class="mt-4 md:mt-0 print-button">
                            <i class="fas fa-print"></i> Print Report
                        </button>
                    </form>
                </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">Attendance Report</p>
                            <?php if ($selected_class_id > 0 && !empty($classes)): ?>
                                <?php
                                    $selected_class_name = "N/A";
                                    foreach ($classes as $class) {
                                        if ($class['class_id'] == $selected_class_id) {
                                            $selected_class_name = $class['class_name'];
                                            break;
                                        }
                                    }
                                ?>
                                <p class="text-gray-600 text-sm text-right">For Class: <span class="font-semibold"><?php echo htmlspecialchars($selected_class_name); ?></span></p>
                            <?php endif; ?>
                            <p class="text-gray-600 text-sm text-right">Period: <span class="font-semibold"><?php echo htmlspecialchars($start_date); ?></span> to <span class="font-semibold"><?php echo htmlspecialchars($end_date); ?></span></p>
                            <p class="text-gray-600 text-xs text-right">Date Generated: <?php echo date('F j, Y'); ?></p>
                        </div>
                    </div>

                    <?php if (empty($attendance_records)): ?>
                        <p class="text-gray-500 text-center">No attendance records found for the selected criteria. (Note: An 'attendance' table is needed in the database to fetch this data.)</p>
                    <?php else: ?>
                        <table class="min-w-full bg-white">
                            <thead>
                                <tr>
                                    <th>#</th>
                                    <th>Student Name</th>
                                    <th>Admission No.</th>
                                    <th>Class</th>
                                    <th>Date</th>
                                    <th>Status</th>
                                    <th>Remarks</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php $counter = 1; ?>
                                <?php foreach ($attendance_records as $record): ?>
                                    <tr>
                                        <td><?php echo $counter++; ?></td>
                                        <td><?php echo htmlspecialchars($record['student_name']); ?></td>
                                        <td><?php echo htmlspecialchars($record['ADM']); ?></td>
                                        <td><?php echo htmlspecialchars($record['class_name'] ?? 'N/A'); ?></td>
                                        <td><?php echo htmlspecialchars($record['attendance_date']); ?></td>
                                        <td><?php echo htmlspecialchars($record['attendance_status']); ?></td>
                                        <td><?php echo htmlspecialchars($record['remarks'] ?? 'N/A'); ?></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');
            });
        });
    </script>
</body>
</html>
