<?php

include('includes/session1.php');

error_reporting(0);

include('includes/dbconnection.php');
require_once __DIR__ . '/includes/missed_attendance_helper.php';



if (!isset($_SESSION['sid'])) {

    header('location:logoutteacher.php');

    exit();

}





$id = $_SESSION['sid'];



// Get admin details

$sql1 = "SELECT * FROM tblusers WHERE id = '$id'";

$result = mysqli_query($con, $sql1);

$row = mysqli_fetch_assoc($result);



// Assign variables

$status = isset($row['status']) ? (int) $row['status'] : 0;

$firstname = $row['name'] ?? '';

$lastname = $row['lastname'] ?? '';

$permission = $row['permission'] ?? '';

$userimage = !empty($row['userimage']) && file_exists("staff_images/" . $row['userimage'])

    ? "staff_images/" . htmlspecialchars($row['userimage'])

    : "default.png";

$title = $row['title'] ?? 'Mr';



$teacher_id = $_SESSION['sid'];



// Check if teacher is a class teacher

$class_teacher_stmt = $con->prepare("

    SELECT cs.class, cs.section 

    FROM teacher_assignments ta

    JOIN class_section cs ON ta.class_id = cs.id

    WHERE ta.teacher_id = ? AND ta.is_class_teacher = 1

    LIMIT 1

");

$class_teacher_stmt->bind_param("i", $teacher_id);

$class_teacher_stmt->execute();

$class_teacher_result = $class_teacher_stmt->get_result();

$is_class_teacher = $class_teacher_result->num_rows > 0;

$class_teacher_data = $class_teacher_result->fetch_assoc();



// If class teacher, fetch attendance summary

if ($is_class_teacher) {

    $attendance_stmt = $con->prepare("

        SELECT 

            COUNT(DISTINCT s.id) AS total_students,

            COUNT(DISTINCT CASE WHEN a.status = 'Present' THEN a.student_id END) AS present_count,

            COUNT(DISTINCT CASE WHEN a.status = 'Absent' THEN a.student_id END) AS absent_count,

            (COUNT(DISTINCT s.id) - COUNT(DISTINCT a.student_id)) AS not_marked

        FROM teacher_assignments ta

        JOIN class_section cs ON ta.class_id = cs.id

        JOIN students s ON s.class = cs.class AND s.section = cs.section AND s.status < 3

        LEFT JOIN attendance a 

            ON a.student_id = s.id 

            AND a.date = CURDATE()

        WHERE ta.teacher_id = ? 

          AND ta.is_class_teacher = 1

    ");

    $attendance_stmt->bind_param("i", $teacher_id);

    $attendance_stmt->execute();

    $attendance_result = $attendance_stmt->get_result();

    $attendance_data = $attendance_result->fetch_assoc();

}





// Fetch assigned classes where the teacher is a class teacher

$class_stmt = $con->prepare("

    SELECT c.class, c.section 

    FROM teacher_assignments ta

    JOIN class_section c ON ta.class_id = c.id

    WHERE ta.teacher_id = ? AND ta.is_class_teacher = 1

");

$class_stmt->bind_param("i", $teacher_id);

$class_stmt->execute();

$class_result = $class_stmt->get_result();

$class_teacher_classes = $class_result->fetch_all(MYSQLI_ASSOC);



// Fetch assigned subjects where the teacher is a subject teacher

$subject_stmt = $con->prepare("

    SELECT c.class, c.section, s.Subject_name 

    FROM teacher_assignments ta

    JOIN subjectcombination s ON ta.subject_id = s.id

    JOIN class_section c ON c.class = s.Class AND c.section = s.section

    WHERE ta.teacher_id = ? AND ta.subject_id IS NOT NULL

");

$subject_stmt->bind_param("i", $teacher_id);

$subject_stmt->execute();

$subject_result = $subject_stmt->get_result();

$subject_teacher_classes = $subject_result->fetch_all(MYSQLI_ASSOC);



// Fetch unread notifications

$notif_stmt = $con->prepare("

    SELECT * FROM notifications WHERE teacher_id = ? AND status = 'unread'

");

$notif_stmt->bind_param("i", $teacher_id);

$notif_stmt->execute();

$notif_result = $notif_stmt->get_result();

$notifications = $notif_result->fetch_all(MYSQLI_ASSOC);



$id = $_SESSION['sid'];

$sql = "SELECT name, lastname FROM tblusers WHERE id = ?";

$stmt = $con->prepare($sql);

$stmt->bind_param("i", $id);

$stmt->execute();

$result = $stmt->get_result();

$row = $result->fetch_assoc(); // Now it's correctly an associative array



// Check if row exists

if (!$row) {

    $row = ['name' => 'Unknown', 'lastname' => 'User'];

}



?>







<!DOCTYPE html>

<html>

<?php @include("includes/head.php"); ?>

<style>
    .dashboard-header {

        font-size: 1.4rem;

        font-weight: bold;

        color: #333;

        text-align: center;

        margin-bottom: 15px;

    }



    /* Cards */

    .card {

        border-radius: 10px;

        transition: 0.3s ease-in-out;

        height: 100%;

    }



    .card:hover {

        transform: translateY(-3px);

    }



    /* Card Headers */

    .card-header {

        font-size: 1.2rem;

        font-weight: bold;

    }



    .bg-primary {

        background-color: #007bff !important;

    }



    .bg-success {

        background-color: #28a745 !important;

    }



    .bg-warning {

        background-color: #ffc107 !important;

        color: black !important;

    }



    /* Buttons */

    .mark-read-btn {

        cursor: pointer;

        border: none;

        background: none;

        color: #28a745;

        font-weight: bold;

    }



    .mark-read-btn:hover {

        text-decoration: underline;

    }



    /* Responsive Fix */

    @media (max-width: 768px) {

        .col-md-6 {

            margin-bottom: 15px;

        }

    }
</style>



<body class="hold-transition sidebar-mini layout-fixed">

    <div class="wrapper">

        <?php @include("includes/headert.php"); ?>

        <?php @include("includes/sidebart.php"); ?>



        <div class="content-wrapper">



            <!-- Admin Header -->

            <div id="pageHeader" class="content-header py-4 rounded shadow-sm mb-4 sticky-top"
                style="background: linear-gradient(135deg, var(--dark), var(--primary)); color: #fff; z-index: 1020; transition: all 0.3s ease;">

                <div class="container-fluid">

                    <div class="d-flex justify-content-between align-items-center flex-wrap">



                        <!-- Profile & Welcome -->

                        <div class="d-flex align-items-center mb-2 mb-md-0">

                            <div
                                style="width:60px; height:60px; border-radius:50%; overflow:hidden; background:#fff; display:flex; align-items:center; justify-content:center; margin-right:15px; transition: all 0.3s ease;">

                                <?php if ($userimage !== "default.png"): ?>

                                    <img src="<?php echo $userimage; ?>" alt="Admin Picture"
                                        style="width:100%; height:100%; object-fit:cover;" class="img-circle img-fluid">

                                <?php else: ?>

                                    <i class="fas fa-user-circle" style="font-size:60px; color:var(--primary);"></i>

                                <?php endif; ?>

                            </div>

                            <div>

                                <h4 class="mb-1 fw-bold" style="transition: all 0.3s ease;">

                                    <?php echo htmlspecialchars($title . '. ' . $firstname . ' ' . $lastname); ?>,

                                </h4>

                                <h6 class="mb-0">Welcome to your dashboard</h6>

                                <small style="opacity:0.9;">Manage classes, results, attendance, subjects and
                                    more.</small>

                            </div>

                        </div>





                        <!-- Admin Status -->

                        <div>

                            <h6 class="fw-bold mb-2 student-status-heading">Teacher Status</h6>

                            <?php

                            $admissionStatusOptions = [

                                2 => ['text' => 'Active', 'class' => 'bg-success'],

                                1 => ['text' => 'Active', 'class' => 'bg-success'],

                            ];

                            $admissionStatus = $admissionStatusOptions[$status] ?? ['text' => 'Unknown', 'class' => 'bg-secondary'];

                            ?>

                            <div>

                                <span class="badge <?= $admissionStatus['class']; ?> d-block p-2"
                                    style="font-size:1rem;">

                                    <?= htmlspecialchars($admissionStatus['text']); ?>

                                </span>

                            </div>

                        </div>



                    </div>

                </div>

            </div>



            <!-- âœ… Attendance Summary Notification -->

            <div class="col-12 mt-3">

                <?php if ($is_class_teacher): ?>

                    <?php if (!empty($attendance_data) && $attendance_data['total_students'] > 0): ?>

                        <?php

                        $marked_total = $attendance_data['present_count'] + $attendance_data['absent_count'];

                        $total = $attendance_data['total_students'];

                        $percent = round(($marked_total / $total) * 100, 1);

                        $not_marked = $attendance_data['not_marked'];

                        $fully_marked = ($marked_total == $total);

                        $alert_color = $fully_marked ? 'success' : 'info';

                        ?>

                        <div class="alert alert-<?= $alert_color; ?> shadow-sm border-0 mt-3" style="<?= $fully_marked

                               ? 'background: linear-gradient(135deg, var(--dark), var(--primary)); color:#fff;'

                               : 'background: linear-gradient(135deg, var(--dark), var(--primary)); color:#fff;'; ?>">

                            <i class="fas fa-calendar-check mr-2"></i>

                            <strong>Attendance Update

                                (<?= htmlspecialchars($class_teacher_data['class']) . ' ' . htmlspecialchars($class_teacher_data['section']); ?>):

                            </strong>

                            You have marked <strong><?= $marked_total; ?></strong> out of

                            <strong><?= $total; ?></strong> students today.

                            <strong><?= $attendance_data['present_count']; ?></strong> Present,

                            <strong><?= $attendance_data['absent_count']; ?></strong> Absent,

                            and <strong><?= $not_marked; ?></strong> not marked yet.

                            <br>

                            <small><?= $percent; ?>% of attendance completed for <?= date('l, F j, Y'); ?>.</small>

                        </div>

                    <?php else: ?>

                        <div class="alert alert-warning shadow-sm border-0 mt-3">

                            <i class="fas fa-exclamation-circle mr-2"></i>

                            You have not marked attendance yet today for your class.

                        </div>

                    <?php endif; ?>

                <?php else: ?>

                    <div class="alert alert-secondary shadow-sm border-0 mt-3">

                        <i class="fas fa-info-circle mr-2"></i>

                        You are not assigned as a class teacher, attendance summary not applicable.

                    </div>

                <?php endif; ?>

            </div>

            <!-- âœ… End Attendance Notification -->



            <style>
                .student-status-heading {

                    position: relative;

                    display: inline-block;

                    color: #fff;

                    padding-bottom: 4px;

                }

                .student-status-heading::after {

                    content: "";

                    position: absolute;

                    left: 0;

                    bottom: 0;

                    height: 2px;

                    width: 0;

                    background-color: rgba(255, 255, 255, 0.3);

                    transition: width 0.6s ease-in-out;

                }

                body.loaded .student-status-heading::after {

                    width: 100%;

                }
            </style>



            <script>

                window.addEventListener("load", function () {

                    document.body.classList.add("loaded");

                });



                // Shrink header on scroll

                window.addEventListener('scroll', function () {

                    let header = document.getElementById('pageHeader');

                    let profilePic = header.querySelector("div[style*='width:60px']");

                    let nameTag = header.querySelector("h4");



                    if (window.scrollY > 50) {

                        header.style.padding = "0.5rem 0";

                        profilePic.style.width = "40px";

                        profilePic.style.height = "40px";

                        nameTag.style.fontSize = "1rem";

                    } else {

                        header.style.padding = "1rem 0";

                        profilePic.style.width = "60px";

                        profilePic.style.height = "60px";

                        nameTag.style.fontSize = "1.25rem";

                    }

                });

            </script>





<style>
.td-section-label{font-size:.68rem;font-weight:700;text-transform:uppercase;letter-spacing:.06em;color:#6c757d;margin-bottom:6px;padding:0 2px}
.td-action-group{display:flex;flex-wrap:wrap;gap:5px;margin-bottom:10px}
.td-action-group .btn{font-size:.75rem;padding:4px 10px;border-radius:6px;white-space:nowrap}
.td-class-card{border:1px solid #e3e8f0;border-radius:10px;padding:14px 16px;margin-bottom:10px;background:#f8faff}
.td-class-card:last-child{margin-bottom:0}
.td-class-badge{display:inline-flex;align-items:center;gap:6px;background:linear-gradient(135deg,#007bff,#0056b3);color:#fff;border-radius:20px;padding:4px 14px;font-size:.82rem;font-weight:600;margin-bottom:12px}
.td-subject-item{border:1px solid #e3e8f0;border-radius:10px;padding:12px 14px;margin-bottom:8px;background:#f8faff}
.td-subject-item:last-child{margin-bottom:0}
.td-subject-name{font-weight:600;font-size:.88rem;color:#1a2340;margin-bottom:4px}
.td-subject-meta{font-size:.75rem;color:#6c757d;margin-bottom:8px}
.td-notif-item{display:flex;align-items:flex-start;gap:12px;padding:12px 14px;border-bottom:1px solid #f0f0f0;transition:background .2s}
.td-notif-item:last-child{border-bottom:none}
.td-notif-item:hover{background:#f8f9fa}
.td-notif-icon{width:36px;height:36px;border-radius:50%;background:linear-gradient(135deg,#ffc107,#e0a800);display:flex;align-items:center;justify-content:center;flex-shrink:0;color:#fff;font-size:.85rem}
.td-notif-text{flex:1;font-size:.875rem;color:#333;line-height:1.4}
.td-card-hdr{border-radius:10px 10px 0 0!important;padding:14px 18px}
.td-empty-state{text-align:center;padding:30px 20px;color:#adb5bd}
.td-empty-state i{font-size:2rem;margin-bottom:8px;display:block}
.td-empty-state p{margin:0;font-size:.875rem}
</style>

            <section class="content">
                <div class="container-fluid">

                    <!-- Row 1: Class Teacher + Subjects -->
                    <div class="row mt-4">

                        <!-- Class Teacher Responsibilities -->
                        <div class="col-lg-6 mb-4">
                            <div class="card shadow-sm border-0 h-100" style="border-radius:12px;">
                                <div class="card-header td-card-hdr d-flex align-items-center" style="background:linear-gradient(135deg,#007bff,#0056b3);">
                                    <i class="fas fa-chalkboard-teacher mr-2 text-white"></i>
                                    <h6 class="mb-0 text-white font-weight-bold">Class Teacher Responsibilities</h6>
                                </div>
                                <div class="card-body p-3">
                                    <?php if (!empty($class_teacher_classes)): ?>
                                        <?php foreach ($class_teacher_classes as $class): ?>
                                            <div class="td-class-card">
                                                <div class="td-class-badge">
                                                    <i class="fas fa-school"></i>
                                                    <?= htmlspecialchars($class['class'] . ' - ' . $class['section']); ?>
                                                </div>
                                                <div class="td-section-label"><i class="fas fa-calendar-check mr-1"></i>Attendance</div>
                                                <div class="td-action-group">
                                                    <a href="mark_attendance.php?class=<?= urlencode($class['class']); ?>&section=<?= urlencode($class['section']); ?>" class="btn btn-outline-success"><i class="fas fa-check-circle mr-1"></i>Mark Attendance</a>
                                                    <a href="attendance_report.php?class=<?= urlencode($class['class']); ?>&section=<?= urlencode($class['section']); ?>" class="btn btn-outline-info"><i class="fas fa-file-alt mr-1"></i>Attendance Report</a>
                                                    <?php if (checkMissedAttendanceAccess($con, $teacher_id, $class['class'], $class['section'])): ?>
                                                    <a href="missed_attendance_remark.php?class=<?= urlencode($class['class']); ?>&section=<?= urlencode($class['section']); ?>" class="btn btn-outline-danger"><i class="fas fa-history mr-1"></i>Missed Attendance</a>
                                                    <?php endif; ?>
                                                </div>
                                                <div class="td-section-label"><i class="fas fa-pen mr-1"></i>Remarks</div>
                                                <div class="td-action-group">
                                                    <a href="add_remarks_test.php?class=<?= urlencode($class['class']); ?>&section=<?= urlencode($class['section']); ?>" class="btn btn-outline-primary"><i class="fas fa-pen mr-1"></i>Mid Term</a>
                                                    <a href="add_remarks.php?class=<?= urlencode($class['class']); ?>&section=<?= urlencode($class['section']); ?>" class="btn btn-outline-warning"><i class="fas fa-clipboard mr-1"></i>End of Term</a>
                                                </div>
                                                <div class="td-section-label"><i class="fas fa-star mr-1"></i>Ratings</div>
                                                <div class="td-action-group">
                                                    <a href="rating_form.php?class=<?= urlencode($class['class']); ?>&section=<?= urlencode($class['section']); ?>" class="btn btn-outline-primary"><i class="fas fa-star mr-1"></i>Student Ratings</a>
                                                    <a href="view_ratings.php?class=<?= urlencode($class['class']); ?>&section=<?= urlencode($class['section']); ?>" class="btn btn-outline-info"><i class="fas fa-chart-bar mr-1"></i>Rating Report</a>
                                                </div>
                                                <div class="td-section-label"><i class="fas fa-print mr-1"></i>Broadsheets</div>
                                                <div class="td-action-group">
                                                    <a href="print_broadsheet.php?class=<?= urlencode($class['class']); ?>&section=<?= urlencode($class['section']); ?>" class="btn btn-outline-success"><i class="fas fa-print mr-1"></i>End of Term</a>
                                                    <a href="print_broadsheet_test.php?class=<?= urlencode($class['class']); ?>&section=<?= urlencode($class['section']); ?>" class="btn btn-outline-primary"><i class="fas fa-print mr-1"></i>Mid Term</a>
                                                    <a href="print_broadsheet1.php?class=<?= urlencode($class['class']); ?>&section=<?= urlencode($class['section']); ?>" class="btn btn-outline-secondary"><i class="fas fa-history mr-1"></i>Prev Term</a>
                                                    <a href="print_broadsheet_test1.php?class=<?= urlencode($class['class']); ?>&section=<?= urlencode($class['section']); ?>" class="btn btn-outline-secondary"><i class="fas fa-history mr-1"></i>Prev Midterm</a>
                                                </div>
                                                <div class="td-section-label"><i class="fas fa-book mr-1"></i>Subjects</div>
                                                <div class="td-action-group">
                                                    <a href="assign_subjects.php?class=<?= urlencode($class['class']); ?>&section=<?= urlencode($class['section']); ?>&tid=<?= urlencode($teacher_id); ?>" class="btn btn-outline-dark"><i class="fas fa-book mr-1"></i>Assign Subjects to Students</a>
                                                </div>
                                            </div>
                                        <?php endforeach; ?>
                                    <?php else: ?>
                                        <div class="td-empty-state"><i class="fas fa-chalkboard-teacher"></i><p>No class assigned as class teacher.</p></div>
                                    <?php endif; ?>
                                </div>
                            </div>
                        </div>

                        <!-- Subjects Assigned -->
                        <div class="col-lg-6 mb-4">
                            <div class="card shadow-sm border-0 h-100" style="border-radius:12px;">
                                <div class="card-header td-card-hdr d-flex align-items-center" style="background:linear-gradient(135deg,#007bff,#0056b3);">
                                    <i class="fas fa-book-open mr-2 text-white"></i>
                                    <h6 class="mb-0 text-white font-weight-bold">Subjects Assigned</h6>
                                    <?php if (!empty($subject_teacher_classes)): ?><span class="badge badge-light ml-auto"><?= count($subject_teacher_classes); ?></span><?php endif; ?>
                                </div>
                                <div class="card-body p-3">
                                    <?php if (!empty($subject_teacher_classes)): ?>
                                        <?php foreach ($subject_teacher_classes as $subject): ?>
                                            <div class="td-subject-item">
                                                <div class="td-subject-name"><i class="fas fa-book-reader mr-1 text-primary"></i><?= htmlspecialchars($subject['Subject_name']); ?></div>
                                                <div class="td-subject-meta"><i class="fas fa-layer-group mr-1"></i><?= htmlspecialchars($subject['class'] . ' - ' . $subject['section']); ?></div>
                                                <div class="td-action-group">
                                                    <a href="add_results_midterm.php?subject=<?= urlencode($subject['Subject_name']); ?>&class=<?= urlencode($subject['class']); ?>&section=<?= urlencode($subject['section']); ?>" class="btn btn-outline-info"><i class="fas fa-clipboard-list mr-1"></i>Mid-Term Results</a>
                                                    <a href="add_results.php?subject=<?= urlencode($subject['Subject_name']); ?>&class=<?= urlencode($subject['class']); ?>&section=<?= urlencode($subject['section']); ?>" class="btn btn-outline-primary"><i class="fas fa-file-alt mr-1"></i>Exam Results</a>
                                                    <a href="print_scoresheet_test.php?subject=<?= urlencode($subject['Subject_name']); ?>&class=<?= urlencode($subject['class']); ?>&section=<?= urlencode($subject['section']); ?>" class="btn btn-outline-secondary"><i class="fas fa-print mr-1"></i>Test Sheet</a>
                                                    <a href="print_scoresheet.php?subject=<?= urlencode($subject['Subject_name']); ?>&class=<?= urlencode($subject['class']); ?>&section=<?= urlencode($subject['section']); ?>" class="btn btn-outline-secondary"><i class="fas fa-print mr-1"></i>Exam Sheet</a>
                                                </div>
                                            </div>
                                        <?php endforeach; ?>
                                    <?php else: ?>
                                        <div class="td-empty-state"><i class="fas fa-book-open"></i><p>No subjects assigned yet.</p></div>
                                    <?php endif; ?>
                                </div>
                            </div>
                        </div>
                    </div>
                    <!-- End Row 1 -->

                    <!-- Row 2: Notifications -->
                    <div class="row mt-3">
                        <div class="col-12">
                            <div class="card shadow-sm border-0" style="border-radius:12px;">
                                <div class="card-header bg-primary text-white td-card-hdr d-flex align-items-center">
                                    <i class="fas fa-bell mr-2 text-white"></i>
                                    <h6 class="mb-0 text-white font-weight-bold">Notifications</h6>
                                    <?php if (!empty($notifications)): ?><span class="badge badge-light ml-2"><?= count($notifications); ?></span><?php endif; ?>
                                    <input type="hidden" id="teacher_id" value="<?= $teacher_id ?>">
                                    <button class="btn btn-sm btn-light ml-auto" id="mark-all-read"><i class="fas fa-check mr-1"></i>Mark All Read</button>
                                </div>
                                <div class="card-body p-0">
                                    <?php if (!empty($notifications)): ?>
                                        <?php foreach ($notifications as $notif): ?>
                                            <div class="td-notif-item">
                                                <div class="td-notif-icon"><i class="fas fa-bell"></i></div>
                                                <div class="td-notif-text"><?= htmlspecialchars($notif['message']); ?></div>
                                                <input type="hidden" name="notif_id" value="<?= $notif['id'] ?>">
                                                <button class="mark-read-btn btn btn-sm btn-outline-success ml-2" data-id="<?= $notif['id']; ?>"><i class="fas fa-check-circle"></i></button>
                                            </div>
                                        <?php endforeach; ?>
                                    <?php else: ?>
                                        <div class="td-empty-state"><i class="fas fa-bell-slash"></i><p>No new notifications.</p></div>
                                    <?php endif; ?>
                                </div>
                            </div>
                        </div>
                    </div>
                    <!-- End Row 2 -->

                    <!-- Row 3: AI Insights (class teacher only) -->
                    <?php if ($is_class_teacher): ?>
                    <div class="row mt-3">
                        <div class="col-12">
                            <div class="card shadow-sm border-0" style="border-radius:12px;">
                                <div class="card-header bg-primary text-white td-card-hdr d-flex align-items-center">
                                    <i class="fas fa-robot mr-2 text-white flex-shrink-0"></i>
                                    <div>
                                        <h6 class="mb-0 text-white font-weight-bold">AI Class Performance Insights</h6>
                                        <small class="text-white" style="opacity:.85;font-size:.75rem;"><?= htmlspecialchars($class_teacher_data['class'] . ' ' . $class_teacher_data['section']); ?></small>
                                    </div>
                                    <button class="btn btn-sm btn-light ml-auto" id="refresh-ai-btn"><i class="fas fa-sync-alt mr-1"></i>Refresh</button>
                                </div>
                                <div class="card-body" id="ai-insights-body">
                                    <div class="text-center text-muted py-4"><i class="fas fa-spinner fa-spin fa-2x"></i><p class="mt-2">Loading AI insights...</p></div>
                                </div>
                            </div>
                        </div>
                    </div>
                    <!-- End AI Insights -->

                    <!-- Row 4: Students Table -->
                    <div class="row mt-3">
                        <div class="col-12">
                            <div class="card shadow-sm border-0" style="border-radius:12px;">
                                <div class="card-header td-card-hdr d-flex align-items-center" style="background:linear-gradient(135deg,#007bff,#0056b3);">
                                    <i class="fas fa-users mr-2 text-white"></i>
                                    <h6 class="mb-0 text-white font-weight-bold">Students in <?= htmlspecialchars($class_teacher_data['class'] . ' ' . $class_teacher_data['section']); ?></h6>
                                </div>
                                <div class="card-body">
                                    <?php
                                    $students_stmt = $con->prepare('SELECT id, studentName, studentno FROM students WHERE class = ? AND section = ? AND status < 3 ORDER BY studentno ASC');
                                    $students_stmt->bind_param('ss', $class_teacher_data['class'], $class_teacher_data['section']);
                                    $students_stmt->execute();
                                    $students_result = $students_stmt->get_result();
                                    if ($students_result->num_rows > 0): ?>
                                    <div class="table-responsive">
                                        <table class="table table-hover table-sm mb-0" id="example1">
                                            <thead style="background:linear-gradient(135deg,#343a40,#495057);color:#fff;">
                                                <tr>
                                                    <th style="width:50px;">#</th>
                                                    <th>Admission No</th>
                                                    <th>Student Name</th>
                                                    <th style="width:130px;">Action</th>
                                                </tr>
                                            </thead>
                                            <tbody>
                                                <?php $cnt=1; while($std=$students_result->fetch_assoc()): ?>
                                                <tr>
                                                    <td><?= $cnt++; ?></td>
                                                    <td><?= htmlspecialchars($std['studentno']); ?></td>
                                                    <td><?= htmlspecialchars($std['studentName']); ?></td>
                                                    <td><button class="btn btn-sm btn-outline-primary view-subjects-btn" data-student-id="<?= $std['id']; ?>" data-student-name="<?= htmlspecialchars($std['studentName']); ?>"><i class="fas fa-eye mr-1"></i>Subjects</button></td>
                                                </tr>
                                                <?php endwhile; ?>
                                            </tbody>
                                        </table>
                                    </div>
                                    <?php else: ?>
                                    <div class="alert alert-warning mb-0">No students found in this class.</div>
                                    <?php endif; ?>
                                </div>
                            </div>
                        </div>
                    </div>
                    <!-- End Students -->
                    <?php endif; ?>

                </div>
            </section>
        </div>
    </div>

    <!-- Student Subjects Modal -->
    <div class="modal fade" id="studentSubjectsModal" tabindex="-1" role="dialog" aria-labelledby="studentSubjectsLabel" aria-hidden="true">
        <div class="modal-dialog modal-lg modal-dialog-centered" role="document">
            <div class="modal-content" style="border-radius:12px;overflow:hidden;">
                <div class="modal-header" style="background:linear-gradient(135deg,#007bff,#0056b3);">
                    <h5 class="modal-title text-white" id="studentSubjectsLabel"><i class="fas fa-book-open mr-2"></i>Allocated Subjects</h5>
                    <button type="button" class="close text-white" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
                </div>
                <div class="modal-body">
                    <h6 id="studentName" class="text-center mb-3 text-primary"></h6>
                    <div id="subjectsTableContainer" class="table-responsive text-center"><p class="text-muted">Loading subjects...</p></div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-dismiss="modal"><i class="fas fa-times mr-1"></i>Close</button>
                </div>
            </div>
        </div>
    </div>
    <!-- End Modal -->

    <?php @include('includes/footer.php'); ?>

    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script>
    function getRiskBadge(level) {
        var colors = { Critical: '#dc3545', High: '#fd7e14', Moderate: '#ffc107' };
        var color = colors[level] || '#6c757d';
        return level
            ? '<span style="background:' + color + ';color:#fff;padding:2px 8px;border-radius:10px;font-size:11px;">' + level + '</span>'
            : '<span style="background:#28a745;color:#fff;padding:2px 8px;border-radius:10px;font-size:11px;">OK</span>';
    }
    function getBandColor(band) {
        var high = ['A1','B2','B3','Distinction','Excellent','Very Good','A','B'];
        var low  = ['F9','Fail','F'];
        if (high.indexOf(band) !== -1) return '#28a745';
        if (low.indexOf(band)  !== -1) return '#dc3545';
        return '#ffc107';
    }
    function loadAIInsights() {
        if (!$('#ai-insights-body').length) return;
        $('#ai-insights-body').html('<div class="text-center text-muted py-4"><i class="fas fa-spinner fa-spin fa-2x"></i><p class="mt-2">Loading AI insights...</p></div>');
        $.getJSON('api/get_teacher_ai_report.php', function(resp) {
            if (!resp.success) { $('#ai-insights-body').html('<div class="alert alert-warning">' + (resp.message || 'Error loading AI report.') + '</div>'); return; }
            var d = resp.data;
            if (!d.students || d.students.length === 0) { $('#ai-insights-body').html('<div class="alert alert-info">' + (d.message || 'No AI report available yet.') + '</div>'); return; }
            var s = d.summary;
            var genAt = s.generated_at ? '<small class="text-muted ml-2" style="font-size:11px;">Last updated: ' + s.generated_at + '</small>' : '';
            var html = '<div class="row mb-3">';
            html += '<div class="col-6 col-md-3 mb-2"><div class="card text-center border-0 shadow-sm p-2"><div style="font-size:1.5rem;font-weight:700;">' + s.total_students + '</div><small>Total Students</small></div></div>';
            html += '<div class="col-6 col-md-3 mb-2"><div class="card text-center border-0 shadow-sm p-2"><div style="font-size:1.5rem;font-weight:700;color:' + (s.average_score >= 50 ? '#28a745' : '#dc3545') + ';">'+s.average_score+'%</div><small>Class Average</small></div></div>';
            html += '<div class="col-6 col-md-3 mb-2"><div class="card text-center border-0 shadow-sm p-2"><div style="font-size:1.5rem;font-weight:700;color:' + (s.pass_rate >= 70 ? '#28a745' : '#ffc107') + ';">'+s.pass_rate+'%</div><small>Pass Rate</small></div></div>';
            html += '<div class="col-6 col-md-3 mb-2"><div class="card text-center border-0 shadow-sm p-2"><div style="font-size:1.5rem;font-weight:700;color:' + (s.at_risk_count > 0 ? '#dc3545' : '#28a745') + ';">'+s.at_risk_count+'</div><small>At-Risk Students</small></div></div>';
            html += '</div>' + genAt;
            if (s.weak_subjects && s.weak_subjects.length > 0) html += '<div class="alert alert-warning py-2 mb-3"><i class="fas fa-exclamation-triangle mr-1"></i><strong>Improvement areas:</strong> ' + s.weak_subjects.join(', ') + '</div>';
            if (s.critical_count > 0) html += '<div class="alert alert-danger py-2 mb-2"><i class="fas fa-exclamation-circle mr-1"></i><strong>URGENT:</strong> ' + s.critical_count + ' student(s) critically below 30%.</div>';
            if (s.high_count > 0) html += '<div class="alert alert-warning py-2 mb-2"><i class="fas fa-exclamation mr-1"></i><strong>' + s.high_count + ' student(s)</strong> below 40%  high risk.</div>';
            html += '<div class="table-responsive"><table class="table table-bordered table-hover table-sm" style="font-size:13px;">';
            html += '<thead class="thead-dark"><tr><th>#</th><th>Adm. No</th><th>Student Name</th><th>Score</th><th>Band</th><th>Trend</th><th>Risk</th><th>Strengths</th><th>Needs Work</th></tr></thead><tbody>';
            $.each(d.students, function(i, st) {
                var trend = parseFloat(st.trend_score);
                var trendHtml = trend > 0 ? '<span style="color:#28a745">&#9650; +' + trend.toFixed(1) + '</span>' : (trend < 0 ? '<span style="color:#dc3545">&#9660; ' + trend.toFixed(1) + '</span>' : '<span style="color:#6c757d">&#8212; 0</span>');
                var strengths = (st.strength_subjects || []).map(function(x){ return x.subject; }).join(', ') || '&mdash;';
                var improvements = (st.improvement_subjects || []).map(function(x){ return x.subject; }).join(', ') || '&mdash;';
                var rowStyle = st.risk_level === 'Critical' ? 'background:#fff0f0;' : (st.risk_level === 'High' ? 'background:#fff8f0;' : '');
                html += '<tr style="' + rowStyle + '"><td>' + (i+1) + '</td><td>' + st.studentno + '</td><td>' + st.studentName + '</td>';
                html += '<td style="font-weight:bold;color:' + (parseFloat(st.base_score) >= 50 ? '#28a745' : '#dc3545') + ';">'+parseFloat(st.base_score).toFixed(1)+'%</td>';
                html += '<td><span style="color:' + getBandColor(st.ai_band) + ';font-weight:bold;">'+st.ai_band+'</span></td>';
                html += '<td>'+trendHtml+'</td><td>'+getRiskBadge(st.risk_level)+'</td>';
                html += '<td style="font-size:11px;color:#28a745;">'+strengths+'</td><td style="font-size:11px;color:#dc3545;">'+improvements+'</td></tr>';
            });
            html += '</tbody></table></div>';
            $('#ai-insights-body').html(html);
        }).fail(function() { $('#ai-insights-body').html('<div class="alert alert-danger">Could not load AI insights.</div>'); });
    }
    $(document).ready(function() {
        loadAIInsights();
        $('#refresh-ai-btn').on('click', loadAIInsights);

        // Mark individual notification as read
        $('.mark-read-btn').click(function() {
            var notifId = $(this).data('id');
            $(this).closest('.td-notif-item').fadeOut();
            $.post('mark_notification.php', { id: notifId }, function(response) {
                location.reload();
            });
        });

        // Mark all notifications as read
        $('#mark-all-read').click(function() {
            var teacherId = $('#teacher_id').val();
            $.post('mark_notification.php', { mark_all_read: true, teacher_id: teacherId }, function(response) {
                location.reload();
            });
        });

        // View student subjects modal
        $(document).on('click', '.view-subjects-btn', function() {
            var studentId = $(this).data('student-id');
            var studentName = $(this).data('student-name');
            $('#studentSubjectsLabel').html("<i class='fas fa-book-open mr-2'></i>Subjects for " + studentName);
            $('#subjectsTableContainer').html("<p class='text-muted'>Loading...</p>");
            $('#studentSubjectsModal').modal('show');
            $.ajax({
                url: 'fetch_student_subjects.php',
                type: 'GET',
                data: { student_id: studentId },
                success: function(response) { $('#subjectsTableContainer').html(response); },
                error: function() { $('#subjectsTableContainer').html("<div class='alert alert-danger'>Error loading subjects.</div>"); }
            });
        });
    });
    </script>

    <?php @include('includes/foot.php'); ?>
</body>
</html>
