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

$teacher_id = tp_require_auth();
$method     = $_SERVER['REQUEST_METHOD'];
$conn       = getDBConnection();
$ay         = (string)(getSettingValue('academic_year') ?? date('Y'));
$term       = (string)(getSettingValue('current_term')  ?? '');

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

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

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

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

    $stmt = $conn->prepare(
        "SELECT lp.id, lp.class_name, lp.subject_name, lp.week_start,
                lp.term, lp.status, lp.objectives,
                lp.created_at, lp.updated_at
           FROM teacher_lesson_plans lp
           {$where}
          ORDER BY lp.week_start DESC, lp.class_name ASC
          LIMIT 50"
    );
    $stmt->bind_param($types, ...$params);
    $stmt->execute();
    $plans = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);
    $stmt->close();

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

    tp_json(true, [
        'plans'    => $plans,
        'subjects' => $subjects,
        'classes'  => $classes,
        'ay'       => $ay,
        'term'     => $term,
    ]);
}

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

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

    // SUBMIT for approval
    if ($action === 'submit') {
        $id = (int)($input['id'] ?? 0);
        $stmt = $conn->prepare(
            "UPDATE teacher_lesson_plans SET status='submitted', updated_at=NOW()
              WHERE id = ? AND teacher_id = ? AND status = 'draft'"
        );
        $stmt->bind_param('ii', $id, $teacher_id);
        $stmt->execute();
        tp_json(true, null, 'Plan submitted for approval.');
    }

    // SAVE (create or update)
    $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']     ?? ''));
    $week_start  = trim((string)($input['week_start']       ?? ''));
    $objectives  = trim((string)($input['objectives']       ?? ''));
    $content     = trim((string)($input['content']          ?? ''));
    $methods     = trim((string)($input['teaching_methods'] ?? ''));
    $materials   = trim((string)($input['materials']        ?? ''));
    $assessment  = trim((string)($input['assessment']       ?? ''));
    $notes       = trim((string)($input['notes']            ?? ''));

    if ($class_name === '' || $week_start === '') {
        tp_json(false, null, 'Class and week start date are 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_plans
                SET class_name=?, subject_id=?, subject_name=?, week_start=?,
                    term=?, academic_year=?, objectives=?, content=?,
                    teaching_methods=?, materials=?, assessment=?, notes=?,
                    updated_at=NOW()
              WHERE id=? AND teacher_id=? AND status='draft'"
        );
        $stmt->bind_param(
            'sissssssssssii',
            $class_name, $subject_id, $subject_name, $week_start,
            $term, $ay, $objectives, $content,
            $methods, $materials, $assessment, $notes,
            $id, $teacher_id
        );
        $stmt->execute();
        tp_json(true, ['id' => $id], 'Plan updated.');
    } else {
        $stmt = $conn->prepare(
            "INSERT INTO teacher_lesson_plans
               (teacher_id, class_name, subject_id, subject_name, week_start,
                term, academic_year, objectives, content,
                teaching_methods, materials, assessment, notes, status)
             VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,'draft')"
        );
        $stmt->bind_param(
            'iissssssssssss',
            $teacher_id, $class_name, $subject_id, $subject_name, $week_start,
            $term, $ay, $objectives, $content,
            $methods, $materials, $assessment, $notes
        );
        $stmt->execute();
        tp_json(true, ['id' => $conn->insert_id], 'Plan created.');
    }
}
