<?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');

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

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

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

    $stmt = $conn->prepare(
        "SELECT h.id, h.class_name, h.subject_name, h.title, h.due_date,
                h.assigned_date, h.max_score, h.is_visible_to_parents,
                h.status, h.term,
                COUNT(st.id)                                            AS total_students,
                COALESCE(SUM(CASE WHEN hs.status='submitted'  THEN 1 ELSE 0 END),0) AS submitted,
                COALESCE(SUM(CASE WHEN hs.status='missing'    THEN 1 ELSE 0 END),0) AS missing,
                COALESCE(SUM(CASE WHEN hs.status='pending'    THEN 1 ELSE 0 END),0) AS pending,
                COALESCE(SUM(CASE WHEN hs.score IS NOT NULL   THEN 1 ELSE 0 END),0) AS marked
           FROM homework h
           LEFT JOIN students st
                  ON st.class = h.class_name AND st.status = 'active'
           LEFT JOIN homework_submissions hs
                  ON hs.homework_id = h.id AND hs.student_id = st.id
           {$where}
           GROUP BY h.id
           ORDER BY h.due_date DESC
           LIMIT 60"
    );
    $stmt->bind_param($types, ...$params);
    $stmt->execute();
    $list = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);
    $stmt->close();

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

    tp_json(true, [
        'homework' => $list,
        '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'));

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

    if ($action === 'toggle_visibility') {
        $id = (int)($input['id'] ?? 0);
        $stmt = $conn->prepare(
            "UPDATE homework
                SET is_visible_to_parents = 1 - is_visible_to_parents,
                    updated_at = NOW()
              WHERE id = ? AND teacher_id = ?"
        );
        $stmt->bind_param('ii', $id, $teacher_id);
        $stmt->execute();
        $stmt->close();
        tp_json(true, null, 'Visibility toggled.');
    }

    if ($action === 'close') {
        $id = (int)($input['id'] ?? 0);
        $stmt = $conn->prepare(
            "UPDATE homework SET status='closed', updated_at=NOW()
              WHERE id = ? AND teacher_id = ? AND status = 'active'"
        );
        $stmt->bind_param('ii', $id, $teacher_id);
        $stmt->execute();
        $stmt->close();
        tp_json(true, null, 'Homework closed.');
    }

    // 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']    ?? ''));
    $title        = trim((string)($input['title']           ?? ''));
    $description  = trim((string)($input['description']     ?? ''));
    $due_date     = trim((string)($input['due_date']        ?? ''));
    $assigned_date= trim((string)($input['assigned_date']   ?? date('Y-m-d')));
    $max_score    = max(1, (int)($input['max_score']        ?? 10));
    $visible      = (int)($input['is_visible_to_parents']   ?? 1);

    if ($class_name === '' || $title === '' || $due_date === '') {
        tp_json(false, null, 'Class, title, and due 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 homework
                SET class_name=?, subject_id=?, subject_name=?, title=?,
                    description=?, due_date=?, assigned_date=?, max_score=?,
                    is_visible_to_parents=?, updated_at=NOW()
              WHERE id=? AND teacher_id=? AND status='active'"
        );
        $stmt->bind_param(
            'sisssssiiii',
            $class_name, $subject_id, $subject_name, $title,
            $description, $due_date, $assigned_date, $max_score,
            $visible, $id, $teacher_id
        );
        $stmt->execute();
        $stmt->close();
        tp_json(true, ['id' => $id], 'Homework updated.');
    } else {
        $stmt = $conn->prepare(
            "INSERT INTO homework
               (teacher_id, class_name, subject_id, subject_name, title,
                description, due_date, assigned_date, max_score,
                is_visible_to_parents, term, academic_year)
             VALUES (?,?,?,?,?,?,?,?,?,?,?,?)"
        );
        $stmt->bind_param(
            'iissssssiss',
            $teacher_id, $class_name, $subject_id, $subject_name, $title,
            $description, $due_date, $assigned_date, $max_score,
            $visible, $term, $ay
        );
        $stmt->execute();
        $new_id = $conn->insert_id;
        $stmt->close();
        tp_json(true, ['id' => $new_id], 'Homework assigned.');
    }
}
