<?php
require __DIR__ . '/../includes/bootstrap.php';
require_login();
require_admin();

header('Content-Type: application/json');

$payload = json_decode(file_get_contents('php://input'), true);
if (!is_array($payload)) {
    http_response_code(400);
    echo json_encode(['success' => false, 'message' => 'Invalid payload.']);
    exit;
}

$qrToken = trim($payload['qr_token'] ?? '');
$activityId = (int) ($payload['activity_id'] ?? 0);
$notes = trim($payload['notes'] ?? '');

if ($qrToken === '' || !$activityId) {
    http_response_code(422);
    echo json_encode(['success' => false, 'message' => 'QR token and activity are required.']);
    exit;
}

$pdo = db();

$activityStmt = $pdo->prepare('SELECT * FROM activities WHERE id = :id AND status = 1 LIMIT 1');
$activityStmt->execute(['id' => $activityId]);
$activity = $activityStmt->fetch();

if (!$activity) {
    http_response_code(404);
    echo json_encode(['success' => false, 'message' => 'Activity not found or inactive.']);
    exit;
}

$studentStmt = $pdo->prepare(
    'SELECT * FROM students WHERE (qr_code = :token OR student_id = :token) AND status = 1 LIMIT 1'
);
$studentStmt->execute(['token' => $qrToken]);
$student = $studentStmt->fetch();

if (!$student) {
    http_response_code(404);
    echo json_encode(['success' => false, 'message' => 'Student not found or inactive.']);
    exit;
}

$pdo->beginTransaction();
try {
    $attendanceStmt = $pdo->prepare(
        'SELECT * FROM attendance WHERE student_id = :student_id AND activity_id = :activity_id LIMIT 1'
    );
    $attendanceStmt->execute([
        'student_id' => $student['id'],
        'activity_id' => $activity['id'],
    ]);
    $attendance = $attendanceStmt->fetch();

    $now = (new DateTime())->format('Y-m-d H:i:s');
    $action = '';

    if (!$attendance) {
        $insert = $pdo->prepare(
            'INSERT INTO attendance (student_id, activity_id, time_in, status, notes)
             VALUES (:student_id, :activity_id, :time_in, :status, :notes)'
        );
        $insert->execute([
            'student_id' => $student['id'],
            'activity_id' => $activity['id'],
            'time_in' => $now,
            'status' => 'present',
            'notes' => $notes,
        ]);
        $attendanceId = (int) $pdo->lastInsertId();
        $action = 'time_in';
    } elseif ($attendance['time_out'] === null) {
        $update = $pdo->prepare(
            'UPDATE attendance SET time_out = :time_out, notes = :notes, updated_at = CURRENT_TIMESTAMP
             WHERE id = :id'
        );
        $update->execute([
            'time_out' => $now,
            'notes' => $notes ?: $attendance['notes'],
            'id' => $attendance['id'],
        ]);
        $attendanceId = (int) $attendance['id'];
        $action = 'time_out';
    } else {
        $pdo->rollBack();
        echo json_encode([
            'success' => true,
            'message' => 'Attendance already completed for this student.',
            'meta' => [
                'student' => $student['full_name'],
                'activity' => $activity['name'],
                'action' => 'ignored',
                'timestamp' => format_datetime($attendance['updated_at']),
            ],
        ]);
        exit;
    }

    $log = $pdo->prepare(
        'INSERT INTO attendance_logs (attendance_id, action, old_value, new_value, changed_by, notes)
         VALUES (:attendance_id, :action, :old_value, :new_value, :changed_by, :notes)'
    );
    $log->execute([
        'attendance_id' => $attendanceId,
        'action' => $action,
        'old_value' => null,
        'new_value' => $now,
        'changed_by' => current_user()['id'],
        'notes' => $notes,
    ]);

    $pdo->commit();

    echo json_encode([
        'success' => true,
        'message' => sprintf(
            'Marked %s for %s.',
            $action === 'time_in' ? 'time in' : 'time out',
            $student['full_name']
        ),
        'meta' => [
            'student' => $student['full_name'],
            'activity' => $activity['name'],
            'action' => $action,
            'timestamp' => format_datetime($now),
        ],
    ]);
} catch (Throwable $exception) {
    $pdo->rollBack();
    http_response_code(500);
    echo json_encode(['success' => false, 'message' => 'Unable to record attendance.']);
}
