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

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

// ── GET: students for a class on a date ────────────────────────────────────
if ($method === 'GET') {
    $class_name = trim($_GET['class'] ?? '');
    $date       = trim($_GET['date']  ?? date('Y-m-d'));

    // Validate teacher owns this class
    $classes = tp_teacher_classes($teacher_id);
    if ($class_name === '' || !in_array($class_name, $classes, true)) {
        tp_json(false, null, 'Class not found or not assigned to you.');
    }

    // Students
    $stmt = $conn->prepare(
        "SELECT id, student_id, first_name, last_name, photo_path
           FROM students
          WHERE class = ? AND status = 'active'
          ORDER BY first_name, last_name"
    );
    $stmt->bind_param('s', $class_name);
    $stmt->execute();
    $students = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);
    $stmt->close();

    // Existing attendance for this date
    $stmt = $conn->prepare(
        "SELECT student_id, status, notes
           FROM attendance
          WHERE class_name = ? AND attendance_date = ?"
    );
    $stmt->bind_param('ss', $class_name, $date);
    $stmt->execute();
    $rows = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);
    $stmt->close();

    $existing = [];
    foreach ($rows as $r) {
        $existing[$r['student_id']] = ['status' => $r['status'], 'notes' => $r['notes']];
    }

    // Merge
    foreach ($students as &$s) {
        $s['att_status'] = $existing[$s['id']]['status'] ?? '';
        $s['att_notes']  = $existing[$s['id']]['notes']  ?? '';
        $s['photo_url']  = $s['photo_path']
            ? '../../' . ltrim($s['photo_path'], '/')
            : '../../assets/images/default-student.png';
    }
    unset($s);

    tp_json(true, [
        'class_name' => $class_name,
        'date'       => $date,
        'students'   => $students,
        'saved'      => !empty($existing),
    ]);
}

// ── POST: save batch attendance ───────────────────────────────────────────
if ($method === 'POST') {
    $input      = json_decode(file_get_contents('php://input'), true) ?? [];
    $class_name = trim((string)($input['class_name'] ?? ''));
    $date       = trim((string)($input['date']       ?? date('Y-m-d')));
    $records    = (array)($input['records'] ?? []);  // [{student_id, status, notes}]

    if ($class_name === '' || empty($records)) {
        tp_json(false, null, 'Missing class or records.');
    }

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

    $saved = 0;
    $stmt  = $conn->prepare(
        "INSERT INTO attendance (student_id, class_name, attendance_date, status, recorded_by, notes)
         VALUES (?, ?, ?, ?, ?, ?)
         ON DUPLICATE KEY UPDATE
           status      = VALUES(status),
           recorded_by = VALUES(recorded_by),
           notes       = VALUES(notes)"
    );

    $valid_statuses = ['present','absent','late','excused'];
    foreach ($records as $rec) {
        $sid    = (int)($rec['student_id'] ?? 0);
        $status = in_array($rec['status'] ?? '', $valid_statuses) ? $rec['status'] : 'present';
        $notes  = trim((string)($rec['notes'] ?? ''));
        if ($sid <= 0) continue;
        $stmt->bind_param('isssss', $sid, $class_name, $date, $status, $teacher_id, $notes);
        $stmt->execute();
        $saved++;
    }
    $stmt->close();

    tp_json(true, ['saved' => $saved], "Attendance saved for {$saved} students.");
}
