<?php
// grades.php - Teacher grade management (final version)
// Assumes includes/conn.php and includes/functions.php exist and provide:
// $pdo (PDO), isLoggedIn(), hasRole(), requireRole(), deleteGrade()

include 'includes/conn.php';
include 'includes/functions.php';
requireRole('teacher'); // redirect if not teacher

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

$teacher_id = (int)($_SESSION['user_id'] ?? 0);
$message = '';
$message_type = '';

// Get active session / term
$active_session = $pdo->query("SELECT * FROM sessions WHERE is_active = 1 LIMIT 1")->fetch(PDO::FETCH_ASSOC) ?: null;
$active_term    = $pdo->query("SELECT * FROM terms WHERE is_active = 1 LIMIT 1")->fetch(PDO::FETCH_ASSOC) ?: null;
$session_id_val = $active_session['id'] ?? 1;
$term_id_val    = $active_term['id'] ?? 1;

// ---------- Handle grade submission ----------
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['add_grade'])) {
    $student_id    = (int)($_POST['student_id'] ?? 0);
    $subject_combo = $_POST['subject_combo'] ?? '';
    $session_id    = (int)($_POST['session_id'] ?? $session_id_val);
    $term_id       = (int)($_POST['term_id'] ?? $term_id_val);

    if (strpos($subject_combo, '|') === false) {
        $message = "Invalid subject selection.";
        $message_type = "danger";
    } else {
        list($subject_id, $classroom_id) = explode('|', $subject_combo);
        $subject_id = (int)$subject_id;
        $classroom_id = (int)$classroom_id;

        if (!$student_id || !$subject_id || !$classroom_id) {
            $message = "Missing required fields.";
            $message_type = "danger";
        } else {
            $chkTs = $pdo->prepare("SELECT 1 FROM teacher_subjects WHERE teacher_id = ? AND subject_id = ? AND classroom_id = ? LIMIT 1");
            $chkTs->execute([$teacher_id, $subject_id, $classroom_id]);
            if (!$chkTs->fetchColumn()) {
                $message = "You are not assigned to that subject/class combination.";
                $message_type = "danger";
            } else {
                // Read numeric scores
                $first_note   = floatval($_POST['first_note'] ?? 0);
                $first_ass    = floatval($_POST['first_ass'] ?? 0);
                $first_test   = floatval($_POST['first_test'] ?? 0);
                $second_note  = floatval($_POST['second_note'] ?? 0);
                $second_ass   = floatval($_POST['second_ass'] ?? 0);
                $second_test  = floatval($_POST['second_test'] ?? 0);
                $exam         = floatval($_POST['exam'] ?? 0);

                $total = $first_note + $first_ass + $first_test + $second_note + $second_ass + $second_test + $exam;

                if ($total >= 85) $grade = 'A1';
                elseif ($total >= 75) $grade = 'A2';
                elseif ($total >= 70) $grade = 'B1';
                elseif ($total >= 65) $grade = 'B2';
                elseif ($total >= 60) $grade = 'UC';
                elseif ($total >= 55) $grade = 'LC';
                elseif ($total >= 50) $grade = 'P';
                else $grade = 'F';

                $dupCheck = $pdo->prepare("SELECT id FROM grades WHERE student_id = ? AND subject_id = ? AND session_id = ? AND term_id = ? LIMIT 1");
                $dupCheck->execute([$student_id, $subject_id, $session_id, $term_id]);
                if ($dupCheck->fetch()) {
                    $message = "A grade for this student, subject and term already exists. Use edit if you need to change it.";
                    $message_type = "danger";
                } else {
                    $insert = $pdo->prepare("
                        INSERT INTO grades (
                            session_id, term_id, student_id, subject_id, classroom_id, teacher_id,
                            first_note, first_ass, first_test,
                            second_note, second_ass, second_test,
                            exam, total, grade, graded_at
                        ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, NOW())
                    ");
                    $insert->execute([
                        $session_id, $term_id, $student_id, $subject_id, $classroom_id, $teacher_id,
                        $first_note, $first_ass, $first_test,
                        $second_note, $second_ass, $second_test,
                        $exam, $total, $grade
                    ]);
                    $message = "Grade saved successfully.";
                    $message_type = "success";
                }
            }
        }
    }
}

// ---------- Delete grade ----------
if (isset($_GET['action'], $_GET['id']) && $_GET['action'] === 'delete_grade') {
    $grade_id = (int)$_GET['id'];
    $res = deleteGrade($pdo, $grade_id, $teacher_id);
    if ($res === true) { $message = "Grade deleted."; $message_type = "success"; }
    else { $message = $res; $message_type = "danger"; }
}

// ---------- Fetch teacher subjects ----------
$teacher_subjects_stmt = $pdo->prepare("
    SELECT ts.subject_id, ts.classroom_id, s.name AS subject_name, s.code, 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);

// ---------- Build students_by_class ----------
$students_by_class = [];
$students_flat = [];

$classroom_ids = array_unique(array_map(fn($r)=> (int)$r['classroom_id'], $teacher_subjects));

if (!empty($classroom_ids)) {
    $placeholders = implode(',', array_fill(0, count($classroom_ids), '?'));
    $sql = "
        SELECT u.id, u.first_name, u.last_name, u.username, cs.classroom_id
        FROM users u
        JOIN classroom_students cs ON u.id = cs.student_id
        WHERE cs.classroom_id IN ($placeholders)
        ORDER BY u.first_name, u.last_name
    ";
    $stmt = $pdo->prepare($sql);
    $stmt->execute(array_values($classroom_ids)); // ensure indexed array
    $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
    foreach ($rows as $r) {
        $cid = (int)$r['classroom_id'];
        if (!isset($students_by_class[$cid])) $students_by_class[$cid] = [];
        $students_by_class[$cid][] = $r;
        $students_flat[$r['id']] = $r;
    }
}


// ---------- Fetch grades ----------
$sql = "
    SELECT g.*, u.first_name, u.last_name, s.name AS subject_name, c.name AS classroom_name, 
           se.name AS session_name, t.name AS term_name
    FROM grades g
    JOIN users u ON g.student_id = u.id
    JOIN subjects s ON g.subject_id = s.id
    JOIN classrooms c ON g.classroom_id = c.id
    LEFT JOIN sessions se ON g.session_id = se.id
    LEFT JOIN terms t ON g.term_id = t.id
    WHERE g.teacher_id = ?
";
$params = [$teacher_id];
if (!empty($_GET['classroom_id'])) { $sql .= " AND g.classroom_id = ?"; $params[] = intval($_GET['classroom_id']); }
if (!empty($_GET['session_id'])) { $sql .= " AND g.session_id = ?"; $params[] = intval($_GET['session_id']); }
if (!empty($_GET['term_id'])) { $sql .= " AND g.term_id = ?"; $params[] = intval($_GET['term_id']); }
$sql .= " ORDER BY g.graded_at DESC";

$grades_stmt = $pdo->prepare($sql);
$grades_stmt->execute($params);
$grades = $grades_stmt->fetchAll(PDO::FETCH_ASSOC);

// Stats
$total_grades = count($grades);
$average_grade = $total_grades ? array_sum(array_column($grades,'total'))/$total_grades : 0;
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<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>Manage Grades - Teacher Panel</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>.cursor-pointer { cursor:pointer; }</style>
</head>
<body>
<nav class="navbar navbar-expand-lg navbar-dark bg-info">
  <div class="container">
    <a class="navbar-brand" href="teacher.php"><i class="fas fa-edit"></i> Grade Management</a>
    <div class="navbar-nav ms-auto">
      <span class="navbar-text me-3">Welcome, <?= htmlspecialchars($_SESSION['first_name'] ?? '') ?></span>
      <a class="nav-link" href="teacher.php">Dashboard</a>
      <a class="nav-link" href="logout.php">Logout</a>
      <button id="themeToggle" class="btn btn-outline-light btn-sm ms-2"><i class="fas fa-moon"></i> Dark Mode</button>
    </div>
  </div>
</nav>

<div class="container mt-4">
<?php if($message): ?>
<div class="alert alert-<?= htmlspecialchars($message_type) ?> alert-dismissible fade show" role="alert">
<?= htmlspecialchars($message) ?>
<button type="button" class="btn-close" data-bs-dismiss="alert"></button>
</div>
<?php endif; ?>

<div class="row">
<!-- Add Grade Form -->
<div class="col-md-6">
<div class="card">
<div class="card-header"><h4><i class="fas fa-plus-circle"></i> Add New Grade</h4></div>
<div class="card-body">
<form method="POST" id="gradeForm">
<div class="mb-3">
<label class="form-label">Subject (Class)</label>
<select class="form-select" name="subject_combo" id="subjectSelect" required>
<option value="">Select subject...</option>
<?php foreach($teacher_subjects as $ts):
$val = intval($ts['subject_id']).'|'.intval($ts['classroom_id']);
$label = htmlspecialchars($ts['subject_name']).' ('.htmlspecialchars($ts['classroom_name']).')';
?>
<option value="<?= $val ?>"><?= $label ?></option>
<?php endforeach; ?>
</select>
</div>

<div class="mb-3">
    <label class="form-label fw-bold">Student (only students in selected class)</label>
    <div class="position-relative">
        <input type="text" id="studentSearch" class="form-control" placeholder="Type to search..." disabled>
        <ul id="studentDropdown" class="list-group position-absolute w-100" 
            style="z-index:1000; display:none; max-height:200px; overflow-y:auto;"></ul>
        <input type="hidden" name="student_id" id="studentIdHidden" required>
    </div>
</div>


<div class="row mt-3">
<div class="col-6 col-md-6">
<label class="form-label">First Note</label>
<input type="number" step="0.01" min="0" max="2" class="form-control score" name="first_note" required>
</div>
<div class="col-6 col-md-6">
<label class="form-label">First Assignment</label>
<input type="number" step="0.01" min="0" max="3" class="form-control score" name="first_ass" required>
</div>
<div class="col-12 col-md-12">
<label class="form-label">First Test</label>
<input type="number" step="0.01" min="0" max="15" class="form-control score" name="first_test" required>
</div>
<div class="col-6 col-md-6 mt-2">
<label class="form-label">Second Note</label>
<input type="number" step="0.01" min="0" max="2" class="form-control score" name="second_note" required>
</div>
<div class="col-6 col-md-6 mt-2">
<label class="form-label">Second Assignment</label>
<input type="number" step="0.01" min="0" max="3" class="form-control score" name="second_ass" required>
</div>
<div class="col-12 col-md-12 mt-2">
<label class="form-label">Second Test</label>
<input type="number" step="0.01" min="0" max="15" class="form-control score" name="second_test" required>
</div>
<div class="col-6 col-md-6 mt-2">
<label class="form-label">Exam</label>
<input type="number" step="0.01" min="0" max="60" class="form-control score" name="exam" required>
</div>
<div class="col-6 col-md-6 mt-2">
<label class="form-label">Total</label>
<input type="text" class="form-control bg-success text-white" id="total" readonly>
</div>
</div>

<input type="hidden" name="classroom_id" id="classroomIdField" value="">
<input type="hidden" name="session_id" value="<?= intval($session_id_val) ?>">
<input type="hidden" name="term_id" value="<?= intval($term_id_val) ?>">

<button type="submit" name="add_grade" class="btn btn-primary mt-3"><i class="fas fa-save"></i> Add Grade</button>
</form>
</div>
</div>
</div>

<!-- Stats -->
<div class="col-md-6">
<div class="card">
<div class="card-header"><h4><i class="fas fa-chart-bar"></i> Grade Statistics</h4></div>
<div class="card-body text-center">
<div class="row">
<div class="col-4"><h3 class="text-primary"><?= intval($total_grades) ?></h3><small>Total Grades</small></div>
<div class="col-4"><h3 class="text-success"><?= number_format($average_grade,1) ?></h3><small>Average</small></div>
<div class="col-4"><h3 class="text-info"><?= intval(count($teacher_subjects)) ?></h3><small>Subjects</small></div>
</div>
</div>
</div>
</div>
</div>

<!-- Recent Grades Table -->
<div class="row mt-4">
<div class="col-12">
<div class="card">
<div class="card-header"><h4><i class="fas fa-list"></i> Recent Grades</h4></div>
<div class="card-body">
<div class="table-responsive">
<table class="table table-striped">
<thead>
<tr>
<th>Student</th><th>Subject</th><th>Note1</th><th>Ass1</th><th>Test1</th>
<th>Note2</th><th>Ass2</th><th>Test2</th><th>Exam</th><th>Total</th><th>Grade</th>
<th>Session</th><th>Term</th><th>Action</th>
</tr>
</thead>
<tbody>
<?php foreach(array_slice($grades,0,20) as $grade): ?>
<tr>
<td><?= htmlspecialchars($grade['first_name'].' '.$grade['last_name']) ?></td>
<td><?= htmlspecialchars($grade['subject_name']) ?></td>
<td><?= $grade['first_note'] ?></td>
<td><?= $grade['first_ass'] ?></td>
<td><?= $grade['first_test'] ?></td>
<td><?= $grade['second_note'] ?></td>
<td><?= $grade['second_ass'] ?></td>
<td><?= $grade['second_test'] ?></td>
<td><?= $grade['exam'] ?></td>
<td><?= $grade['total'] ?></td>
<td><span class="badge bg-primary"><?= $grade['grade'] ?></span></td>
<td><?= htmlspecialchars($grade['session_id']) ?></td>
<td><?= htmlspecialchars($grade['term_id']) ?></td>
<td>
<a href="?action=delete_grade&id=<?= $grade['id'] ?>" 
class="btn btn-sm btn-outline-danger" onclick="return confirm('Delete this grade?')">Delete</a>
</td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
</div>
</div>
</div>
</div>
</div>
</div>

<script>
// Preload students_by_class
const studentsByClass = <?= json_encode($students_by_class ?? [], JSON_HEX_TAG|JSON_HEX_AMP|JSON_HEX_APOS|JSON_HEX_QUOT) ?>;
const subjectSelect = document.getElementById('subjectSelect');
const studentSelect = document.getElementById('studentSelect');
const classroomIdField = document.getElementById('classroomIdField');
const totalField = document.getElementById('total');
const scoreInputs = document.querySelectorAll('.score');

function formatName(u){ return (u.first_name || '')+' '+(u.last_name || ''); }

subjectSelect?.addEventListener('change', function(){
    const val = this.value;
    studentSelect.innerHTML = '<option value="">Select student...</option>';
    classroomIdField.value = '';
    if(!val) return;
    const parts = val.split('|');
    if(parts.length!==2) return;
    const cid = parseInt(parts[1],10);
    classroomIdField.value = cid;
    const students = studentsByClass[cid] || [];
    if(students.length===0){ studentSelect.innerHTML='<option value="">No students in this class</option>'; return; }
    students.forEach(s=>{
        const opt = document.createElement('option');
        opt.value = s.id;
        opt.textContent = formatName(s) + (s.username ? ' ('+s.username+')' : '');
        studentSelect.appendChild(opt);
    });
});

function recalcTotal(){
    let total=0;
    scoreInputs.forEach(i=>total+=parseFloat(i.value)||0);
    totalField.value = total.toFixed(2);
}
scoreInputs.forEach(i=>i.addEventListener('input',recalcTotal));
recalcTotal();

document.getElementById('themeToggle')?.addEventListener('click', function(){
    const isDark=document.documentElement.getAttribute('data-theme')==='dark';
    if(isDark){ document.documentElement.removeAttribute('data-theme'); localStorage.setItem('theme','light'); }
    else { document.documentElement.setAttribute('data-theme','dark'); localStorage.setItem('theme','dark'); }
});

const studentSearch = document.getElementById('studentSearch');
const studentDropdown = document.getElementById('studentDropdown');
const studentIdHidden = document.getElementById('studentIdHidden');

subjectSelect?.addEventListener('change', function(){
    const val = this.value;
    studentSearch.value = '';
    studentIdHidden.value = '';
    studentDropdown.innerHTML = '';
    studentSearch.disabled = true;
    classroomIdField.value = '';

    if(!val) return;
    const parts = val.split('|');
    if(parts.length !== 2) return;
    const cid = parseInt(parts[1],10);
    classroomIdField.value = cid;

    const students = studentsByClass[cid] || [];
    if(students.length === 0){
        studentSearch.placeholder = 'No students in this class';
        return;
    }

    studentSearch.placeholder = 'Type to search...';
    studentSearch.disabled = false;
    studentSearch.addEventListener('input', function(){
        const query = this.value.toLowerCase();
        studentDropdown.innerHTML = '';
        if(query === ''){
            studentDropdown.style.display = 'none';
            studentIdHidden.value = '';
            return;
        }
        const filtered = students.filter(s => ((s.first_name+' '+s.last_name).toLowerCase().includes(query)));
        if(filtered.length === 0){
            studentDropdown.style.display = 'none';
            studentIdHidden.value = '';
            return;
        }
        filtered.forEach(s => {
            const li = document.createElement('li');
            li.className = 'list-group-item list-group-item-action';
            li.style.cursor = 'pointer';
            li.textContent = s.first_name+' '+s.last_name + (s.username ? ' ('+s.username+')' : '');
            li.addEventListener('click', function(){
                studentSearch.value = s.first_name+' '+s.last_name;
                studentIdHidden.value = s.id;
                studentDropdown.style.display = 'none';
            });
            studentDropdown.appendChild(li);
        });
        studentDropdown.style.display = 'block';
    });
});

// Close dropdown if clicked outside
document.addEventListener('click', function(e){
    if(!studentSearch.contains(e.target) && !studentDropdown.contains(e.target)){
        studentDropdown.style.display = 'none';
    }
});

(function(){ const s=localStorage.getItem('theme'); if(s==='dark')document.documentElement.setAttribute('data-theme','dark'); })();
</script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
<script src="dark.js"></script>
</body>
</html>
