<?php

declare(strict_types=1);

require_once __DIR__ . '/tp_auth.php';



$teacher_id = tp_require_auth();

$conn       = getDBConnection();

$method     = $_SERVER['REQUEST_METHOD'];



if ($method === 'GET') {

    $student_id = (int)($_GET['student_id'] ?? 0);

    if ($student_id <= 0) tp_json(false, null, 'Missing student_id.');



    $stmt = $conn->prepare(

        "SELECT si.id, si.type, si.note, si.follow_up_date,

                si.visible_to_parent, si.status, si.created_at,

                s.subject_name

           FROM student_interventions si

           LEFT JOIN subjects s ON s.id = si.subject_id

          WHERE si.student_id = ?

          ORDER BY si.created_at DESC

          LIMIT 50"

    );

    $stmt->bind_param('i', $student_id);

    $stmt->execute();

    $rows = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);

    $stmt->close();



    tp_json(true, ['interventions' => $rows]);

}



if ($method === 'POST') {

    $body   = json_decode(file_get_contents('php://input'), true) ?? [];

    $action = trim((string)($body['action'] ?? 'save'));



    if ($action === 'update_status') {

        $id     = (int)($body['id']     ?? 0);

        $status = trim((string)($body['status'] ?? ''));

        if ($id <= 0 || !in_array($status, ['open','monitoring','resolved'], true)) {

            tp_json(false, null, 'Invalid request.');

        }

        $stmt = $conn->prepare(

            "UPDATE student_interventions SET status = ? WHERE id = ? AND teacher_id = ?"

        );

        $stmt->bind_param('sii', $status, $id, $teacher_id);

        $stmt->execute();

        $affected = $stmt->affected_rows;

        $stmt->close();

        $affected > 0

            ? tp_json(true, null, 'Status updated.')

            : tp_json(false, null, 'Intervention not found or not yours.');

    }



    // Save new intervention

    $student_id        = (int)($body['student_id']        ?? 0);

    $class_name        = trim((string)($body['class_name']        ?? ''));

    $type              = trim((string)($body['type']              ?? 'academic'));

    $note              = trim((string)($body['note']              ?? ''));

    $action_taken      = trim((string)($body['action_taken']      ?? ''));

    $follow_up_date    = trim((string)($body['follow_up_date']    ?? ''));

    $visible_to_parent = (int)(bool)($body['visible_to_parent'] ?? 1);

    $subject_id        = (!empty($body['subject_id']) && (int)$body['subject_id'] > 0)

                         ? (int)$body['subject_id'] : null;



    if ($student_id <= 0 || $class_name === '' || $note === '') {

        tp_json(false, null, 'student_id, class_name and note are required.');

    }

    if (!in_array($type, ['academic','attendance','behaviour','general'], true)) {

        $type = 'general';

    }

    $follow_up  = ($follow_up_date !== '' && strtotime($follow_up_date)) ? $follow_up_date : null;

    $action_val = $action_taken !== '' ? $action_taken : null;



    // types: student_id(i), teacher_id(i), class_name(s), subject_id(i), type(s),

    //        note(s), action_taken(s), follow_up_date(s), visible_to_parent(i)

    $stmt = $conn->prepare(

        "INSERT INTO student_interventions

            (student_id, teacher_id, class_name, subject_id, type, note,

             action_taken, follow_up_date, visible_to_parent)

         VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)"

    );

    $stmt->bind_param(

        'iisissssi',

        $student_id, $teacher_id, $class_name, $subject_id,

        $type, $note, $action_val, $follow_up, $visible_to_parent

    );

    $stmt->execute();

    $new_id = (int)$conn->insert_id;

    $stmt->close();



    tp_json(true, ['id' => $new_id], 'Intervention logged.');

}



tp_json(false, null, 'Method not allowed.');

