<?php
include 'includes/conn.php';
include 'includes/functions.php';
requireRole('teacher');

enforceAccessControl($pdo);

error_reporting(E_ALL);
ini_set('display_errors', 0);

// Get active session and term
$active_session = $pdo->query("SELECT * FROM sessions WHERE is_active = 1 LIMIT 1")->fetch(PDO::FETCH_ASSOC);
$active_term = $pdo->query("SELECT * FROM terms WHERE is_active = 1 LIMIT 1")->fetch(PDO::FETCH_ASSOC);

// Ensure they exist
if (!$active_session || !$active_term) {
    echo "<div class='alert alert-danger text-center m-3'>
            <strong>Error:</strong> No active session or term found. Please contact the admin.
          </div>";
    exit;
}

// Store IDs for later use
$session_id = $active_session['id'];
$term_id = $active_term['id'];

$teacher_id = $_SESSION['user_id'];

// ---------- Fetch teacher subjects (teacher_subjects -> subjects + classrooms) ----------
$teacher_subjects_stmt = $pdo->prepare("
    SELECT 
        ts.id AS teacher_subject_id, 
        ts.classroom_id, 
        s.id AS subject_id, 
        s.name AS subject_name,
        c.name AS classroom_name
    FROM teacher_subjects ts
    JOIN subjects s ON ts.subject_id = s.id
    JOIN classrooms c ON ts.classroom_id = c.id
    WHERE ts.teacher_id = ?
    ORDER BY c.name, s.name
");
$teacher_subjects_stmt->execute([$teacher_id]);
$teacher_subjects = $teacher_subjects_stmt->fetchAll(PDO::FETCH_ASSOC);


// Defensive: ensure variables are arrays to avoid count() errors
if (!is_array($teacher_subjects)) $teacher_subjects = [];

// ---------- Fetch students the teacher teaches (distinct students across classrooms the teacher is assigned to) ----------
$students = [];
try {
    $students_stmt = $pdo->prepare("
        SELECT DISTINCT u.id, u.first_name, u.last_name, u.username, u.current_class
        FROM users u
        JOIN classroom_students cs ON u.id = cs.student_id
        JOIN teacher_subjects ts ON cs.classroom_id = ts.classroom_id
        WHERE ts.teacher_id = ?
        ORDER BY u.first_name, u.last_name
    ");
    $students_stmt->execute([$teacher_id]);
    $students = $students_stmt->fetchAll(PDO::FETCH_ASSOC);
} catch (Exception $e) {
    $students = [];
}

// ---------- Statistics calculations ----------
// 1) Total distinct students taught (from classroom_students joined to teacher_subjects)
$total_students_taught = 0;
try {
    $totStudentsStmt = $pdo->prepare("
        SELECT COUNT(DISTINCT cs.student_id) AS cnt
        FROM classroom_students cs
        JOIN teacher_subjects ts ON cs.classroom_id = ts.classroom_id
        WHERE ts.teacher_id = ?
    ");
    $totStudentsStmt->execute([$teacher_id]);
    $total_students_taught = (int)$totStudentsStmt->fetchColumn();
} catch (Exception $e) {
    $total_students_taught = 0;
}

// 2) Total grades assigned by this teacher (optionally limited to current session/term)
$total_grades_assigned = 0;
try {
    $totGradesStmt = $pdo->prepare("
        SELECT COUNT(*) FROM grades
        WHERE teacher_id = ?
        AND session_id = ?
        AND term_id = ?
    ");
    $totGradesStmt->execute([$teacher_id, $session_id, $term_id]);
    $total_grades_assigned = (int)$totGradesStmt->fetchColumn();
} catch (Exception $e) {
    // fallback: count all grades by teacher if the above fails
    try {
        $fallback = $pdo->prepare("SELECT COUNT(*) FROM grades WHERE teacher_id = ?");
        $fallback->execute([$teacher_id]);
        $total_grades_assigned = (int)$fallback->fetchColumn();
    } catch (Exception $e2) {
        $total_grades_assigned = 0;
    }
}

// 3) Total distinct (classroom, subject) pairs the teacher teaches
$total_class_subject_pairs = 0;
try {
    $totPairsStmt = $pdo->prepare("
        SELECT COUNT(*) FROM (
            SELECT DISTINCT classroom_id, subject_id FROM teacher_subjects WHERE teacher_id = ?
        ) AS pairs
    ");
    $totPairsStmt->execute([$teacher_id]);
    $total_class_subject_pairs = (int)$totPairsStmt->fetchColumn();
} catch (Exception $e) {
    $total_class_subject_pairs = count($teacher_subjects);
}

// ---------- Breakdown data for modal (classroom | subject | student_count) ----------
$breakdown_rows = [];
try {
    $breakdown_stmt = $pdo->prepare("
        SELECT
            ts.classroom_id,
            c.name AS classroom_name,
            ts.subject_id,
            s.name AS subject_name,
            COUNT(DISTINCT cs.student_id) AS student_count
        FROM teacher_subjects ts
        JOIN subjects s ON ts.subject_id = s.id
        JOIN classrooms c ON ts.classroom_id = c.id
        LEFT JOIN classroom_students cs ON cs.classroom_id = ts.classroom_id
        WHERE ts.teacher_id = ?
        GROUP BY ts.classroom_id, ts.subject_id
        ORDER BY c.name, s.name
    ");
    $breakdown_stmt->execute([$teacher_id]);
    $breakdown_rows = $breakdown_stmt->fetchAll(PDO::FETCH_ASSOC);
} catch (Exception $e) {
    $breakdown_rows = [];
}

?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="icon" type="image/png" sizes="32x32" href="BCA-Logo.png">
    <link rel="icon" type="image/png" sizes="16x16" href="BCA-Logo.png">
    <title>Teacher Dashboard - Bethany Christian Academy</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet">
    <link href="major.css" rel="stylesheet">
    <style>
        .sidebar {
            background: linear-gradient(135deg, #28a745 0%, #20c997 100%);
            color: white;
            min-height: 100vh;
            padding: 0;
        }
        .sidebar .nav-link {
            color: white;
            padding: 1rem 1.5rem;
            border-left: 4px solid transparent;
        }
        .sidebar .nav-link:hover, .sidebar .nav-link.active {
            background: rgba(255,255,255,0.1);
            border-left-color: white;
        }
        .grade-card {
            transition: transform 0.2s;
        }
        .grade-card:hover {
            transform: translateY(-2px);
        }
    </style>
</head>
<body>
    <div class="container-fluid">
        <div class="row">
            <!-- Sidebar -->
            <div class="col-md-3 col-lg-2 sidebar">
                <div class="d-flex flex-column p-3">
                    <div class="text-center mb-4">
                        <a href="../"><img src="BCA-Logo.png" alt="BCA LOGO" height="100px" width="100px"></a>
                        <h5>Bethany Christian Academy</h5>
                        <h5>Teacher Portal</h5>
                        <small><?php echo htmlspecialchars($_SESSION['first_name'] . ' ' . $_SESSION['last_name']); ?></small>
                    </div>
                    
                    <ul class="nav nav-pills flex-column">
                        <li class="nav-item">
                            <a class="nav-link active" href="#dashboard" data-bs-toggle="tab">
                                <i class="fas fa-tachometer-alt me-2"></i>Dashboard
                            </a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link" href="#students" data-bs-toggle="tab">
                                <i class="fas fa-user-graduate me-2"></i>My Students
                            </a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link" href="grades.php">
                                <i class="fas fa-edit me-2"></i>Manage Grades
                            </a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link" href="/BCA/student-grades-management-system/CBT-EXAM/teacher/exam_report.php">
                                <i class="fas fa-edit me-2"></i>Computer-Based Exam
                            </a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link" href="logout.php">
                                <i class="fas fa-sign-out-alt me-2"></i>Logout
                            </a>
                        </li>
                    </ul>
                    <button id="themeToggle" class="toggle-btn">
                        <i class="fas fa-moon"></i> Dark Mode
                    </button>
                    <script src="dark.js"></script>
                </div>
            </div>

            <!-- Main Content -->
            <div class="col-md-9 col-lg-10 ms-sm-auto px-4 py-4">
                <div class="tab-content">
                    <!-- Dashboard Tab -->
                    <div class="tab-pane fade show active" id="dashboard">
                        <div class="d-flex justify-content-between align-items-center mb-4">
                            <h2>Teacher Dashboard</h2>
                            <div>
                                <span class="me-3">Welcome, <?php echo htmlspecialchars($_SESSION['first_name']); ?>!</span>
                                <!-- View Breakdown button in top-right -->
                                <button class="btn btn-outline-secondary" data-bs-toggle="modal" data-bs-target="#breakdownModal">
                                    <i class="fas fa-chart-bar me-1"></i> View Breakdown
                                </button>
                            </div>
                        </div>

                        <!-- Statistics -->
                        <div class="row mb-4">
                            <div class="col-md-4">
                                <div class="card grade-card bg-primary text-white">
                                    <div class="card-body">
                                        <div class="d-flex justify-content-between">
                                            <div>
                                                <h4><?php echo number_format($total_students_taught); ?></h4>
                                                <p>Total Students Taught</p>
                                            </div>
                                            <i class="fas fa-user-graduate fa-2x"></i>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            <div class="col-md-4">
                                <div class="card grade-card bg-success text-white">
                                    <div class="card-body">
                                        <div class="d-flex justify-content-between">
                                            <div>
                                                <h4><?php echo number_format($total_grades_assigned); ?></h4>
                                                <p>Total Grades Assigned (current session/term)</p>
                                            </div>
                                            <i class="fas fa-clipboard-check fa-2x"></i>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            <div class="col-md-4">
                                <div class="card grade-card bg-info text-white">
                                    <div class="card-body">
                                        <div class="d-flex justify-content-between">
                                            <div>
                                                <h4><?php echo number_format($total_class_subject_pairs); ?></h4>
                                                <p>Classes & Subjects</p>
                                            </div>
                                            <i class="fas fa-book fa-2x"></i>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <!-- VIEW USERS (unchanged) -->
                        <div class="tab-pane fade" id="users">
                            <h2 class="mb-4">View Users</h2>
                            <div class="card">
                                <div class="card-header d-flex justify-content-between align-items-center">
                                    <h5>All Users</h5>
                                    <input type="text" id="userSearch" class="form-control form-control-sm w-50" placeholder="Search users...">
                                </div>
                                <div class="card-body">
                                    <div class="table-responsive" id="userTableContainer"></div>
                                </div>
                            </div>
                        </div>

                        <!-- My Subjects -->
                        <div class="row">
                            <div class="col-12">
                                <div class="card">
                                    <div class="card-header">
                                        <h5>My Subjects</h5>
                                    </div>
                                    <div class="card-body">
                                        <div class="row">
                                            <?php foreach($teacher_subjects as $subject): ?>
                                                <div class="col-md-4 mb-3">
                                                    <div class="card grade-card border-primary">
                                                        <div class="card-body">
                                                            <h5 class="card-title">
                                                                <?php echo htmlspecialchars($subject['subject_name']); ?>
                                                                (<?php echo htmlspecialchars($subject['classroom_name']); ?>)
                                                            </h5>
                                                            <a href="grades.php?subject_id=<?php echo $subject['teacher_subject_id']; ?>" class="btn btn-primary btn-sm">
                                                                Manage Grades
                                                            </a>
                                                        </div>
                                                    </div>
                                                </div>
                                            <?php endforeach; ?>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Students Tab -->
                    <div class="tab-pane fade" id="students">
                        <h2 class="mb-4">My Students</h2>
                        
                        <div class="card">
                            <div class="card-header">
                                <h5>Student List</h5>
                            </div>
                            <div class="card-body">
                                <div class="table-responsive">
                                    <table class="table table-striped">
                                        <thead>
                                            <tr>
                                                <th>ID</th>
                                                <th>Name</th>
                                                <th>Username</th>
                                                <th>Classroom</th>
                                                <th>Actions</th>
                                            </tr>
                                        </thead>
                                        <tbody>
                                            <?php foreach($students as $student): ?>
                                            <tr>
                                                <td><?php echo $student['id']; ?></td>
                                                <td><?php echo htmlspecialchars($student['first_name'] . ' ' . $student['last_name']); ?></td>
                                                <td><?php echo htmlspecialchars($student['username']); ?></td>
                                                <td><?php echo htmlspecialchars($student['current_class']); ?></td>
                                                <td>
                                                    <a href="grades.php?student_id=<?php echo $student['id']; ?>" class="btn btn-sm btn-outline-primary">View Grades</a>
                                                    <a href="grades.php?action=add&student_id=<?php echo $student['id']; ?>" class="btn btn-sm btn-outline-success">Add Grade</a>
                                                </td>
                                            </tr>
                                            <?php endforeach; ?>
                                        </tbody>
                                    </table>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- Breakdown Modal -->
        <div class="modal fade" id="breakdownModal" tabindex="-1" aria-labelledby="breakdownModalLabel" aria-hidden="true">
          <div class="modal-dialog modal-lg modal-dialog-scrollable">
            <div class="modal-content">
              <div class="modal-header">
                <h5 class="modal-title" id="breakdownModalLabel">Class & Subject Breakdown</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
              </div>
              <div class="modal-body">
                <?php if (empty($breakdown_rows)): ?>
                    <div class="alert alert-info">No breakdown data available.</div>
                <?php else: ?>
                    <div class="table-responsive">
                      <table class="table table-bordered table-striped">
                        <thead>
                          <tr>
                            <th>Classroom</th>
                            <th>Subject</th>
                            <th>Students</th>
                          </tr>
                        </thead>
                        <tbody>
                          <?php foreach ($breakdown_rows as $row): ?>
                            <tr>
                              <td><?php echo htmlspecialchars($row['classroom_name']); ?></td>
                              <td><?php echo htmlspecialchars($row['subject_name']); ?></td>
                              <td><?php echo (int)$row['student_count']; ?></td>
                            </tr>
                          <?php endforeach; ?>
                        </tbody>
                      </table>
                    </div>
                <?php endif; ?>
              </div>
              <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
              </div>
            </div>
          </div>
        </div>
                    <!-- Footer -->
                    <footer class="mt-5">
                        <div class="container py-3 d-flex flex-column flex-md-row justify-content-between align-items-center">
                            <div>
                                &copy; <?= date('Y') ?> Bethany Christian Academy *Designed by Peter Danye. All rights reserved.
                            </div>
                            <div>
                                <a href="#" class="text-decoration-none me-3">Privacy Policy</a>
                                <a href="#" class="text-decoration-none">Terms of Service</a>
                            </div>
                        </div>
                    </footer>
    </div>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        document.addEventListener('DOMContentLoaded', function() {
            var triggerTabList = [].slice.call(document.querySelectorAll('a[data-bs-toggle="tab"]'))
            triggerTabList.forEach(function (triggerEl) {
                var tabTrigger = new bootstrap.Tab(triggerEl)
                triggerEl.addEventListener('click', function (event) {
                    event.preventDefault()
                    tabTrigger.show()
                })
            })
        });
    </script>
</body>
</html>
