<?php
declare(strict_types=1);
require_once __DIR__ . '/tp_auth.php';

$teacher_id = tp_require_auth();
$method     = $_SERVER['REQUEST_METHOD'];
$conn       = getDBConnection();

if ($method === 'GET') {
    $action = trim($_GET['action'] ?? 'list');

    if ($action === 'get' && isset($_GET['id'])) {
        $id = (int)$_GET['id'];
        $stmt = $conn->prepare(
            "SELECT * FROM teacher_lesson_notes WHERE id = ? AND teacher_id = ?"
        );
        $stmt->bind_param('ii', $id, $teacher_id);
        $stmt->execute();
        $note = $stmt->get_result()->fetch_assoc();
        $stmt->close();
        $note ? tp_json(true, $note) : tp_json(false, null, 'Note not found.');
    }

    $class_name = trim($_GET['class'] ?? '');
    $where  = 'WHERE ln.teacher_id = ?';
    $params = [$teacher_id];
    $types  = 'i';

    if ($class_name !== '') {
        $where   .= ' AND ln.class_name = ?';
        $params[] = $class_name;
        $types   .= 's';
    }

    $stmt = $conn->prepare(
        "SELECT ln.id, ln.class_name, ln.subject_name, ln.lesson_date,
                ln.period_name, ln.student_engagement,
                ln.what_was_taught, ln.created_at
           FROM teacher_lesson_notes ln
           {$where}
          ORDER BY ln.lesson_date DESC, ln.class_name ASC
          LIMIT 60"
    );
    $stmt->bind_param($types, ...$params);
    $stmt->execute();
    $notes = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);
    $stmt->close();

    $subjects = tp_teacher_subjects($teacher_id);
    $classes  = tp_teacher_classes($teacher_id);

    tp_json(true, [
        'notes'    => $notes,
        'subjects' => $subjects,
        'classes'  => $classes,
    ]);
}

if ($method === 'POST') {
    $input  = json_decode(file_get_contents('php://input'), true) ?? [];
    $action = trim((string)($input['action'] ?? 'save'));

    if ($action === 'delete') {
        $id   = (int)($input['id'] ?? 0);
        $stmt = $conn->prepare(
            "DELETE FROM teacher_lesson_notes WHERE id = ? AND teacher_id = ?"
        );
        $stmt->bind_param('ii', $id, $teacher_id);
        $stmt->execute();
        $stmt->close();
        tp_json(true, null, 'Note deleted.');
    }

    $id          = (int)($input['id']                  ?? 0);
    $class_name  = trim((string)($input['class_name']  ?? ''));
    $subject_id  = (int)($input['subject_id']          ?? 0);
    $subject_name= trim((string)($input['subject_name']?? ''));
    $lesson_date = trim((string)($input['lesson_date'] ?? date('Y-m-d')));
    $period_id   = (int)($input['period_id']           ?? 0) ?: null;
    $period_name = trim((string)($input['period_name'] ?? ''));
    $taught      = trim((string)($input['what_was_taught']  ?? ''));
    $objectives  = trim((string)($input['objectives_met']   ?? ''));
    $engagement  = trim((string)($input['student_engagement']?? 'good'));
    $challenges  = trim((string)($input['challenges']       ?? ''));
    $next_plan   = trim((string)($input['next_lesson_plan'] ?? ''));

    $valid_eng = ['excellent', 'good', 'fair', 'poor'];
    if (!in_array($engagement, $valid_eng, true)) $engagement = 'good';

    if ($class_name === '') {
        tp_json(false, null, 'Class is required.');
    }

    $classes = tp_teacher_classes($teacher_id);
    if (!in_array($class_name, $classes, true)) {
        tp_json(false, null, 'Not authorised for this class.');
    }

    if ($id > 0) {
        $stmt = $conn->prepare(
            "UPDATE teacher_lesson_notes
                SET class_name=?, subject_id=?, subject_name=?, lesson_date=?,
                    period_id=?, period_name=?, what_was_taught=?, objectives_met=?,
                    student_engagement=?, challenges=?, next_lesson_plan=?,
                    updated_at=NOW()
              WHERE id=? AND teacher_id=?"
        );
        $stmt->bind_param(
            'sisssisssssii',
            $class_name, $subject_id, $subject_name, $lesson_date,
            $period_id, $period_name, $taught, $objectives,
            $engagement, $challenges, $next_plan,
            $id, $teacher_id
        );
        $stmt->execute();
        $stmt->close();
        tp_json(true, ['id' => $id], 'Note updated.');
    } else {
        $stmt = $conn->prepare(
            "INSERT INTO teacher_lesson_notes
               (teacher_id, class_name, subject_id, subject_name, lesson_date,
                period_id, period_name, what_was_taught, objectives_met,
                student_engagement, challenges, next_lesson_plan)
             VALUES (?,?,?,?,?,?,?,?,?,?,?,?)"
        );
        // i=teacher_id, s=class_name, i=subject_id, s=subject_name, s=lesson_date,
        // i=period_id, s=period_name, s=taught, s=objectives, s=engagement, s=challenges, s=next_plan
        $stmt->bind_param(
            'isissi' . 'ssssss',
            $teacher_id, $class_name, $subject_id, $subject_name, $lesson_date,
            $period_id, $period_name, $taught, $objectives,
            $engagement, $challenges, $next_plan
        );
        $stmt->execute();
        $new_id = $conn->insert_id;
        $stmt->close();
        tp_json(true, ['id' => $new_id], 'Note saved.');
    }
}
