<?php
require_once __DIR__ . '/../config/database.php';
header('Content-Type: application/json');

// Expect Authorization: Bearer <token>
$headers = getallheaders();
$auth = $headers['Authorization'] ?? ($headers['authorization'] ?? '');
if (!$auth || stripos($auth, 'Bearer ') !== 0) {
    http_response_code(401);
    echo json_encode(['error' => 'Missing Authorization header']);
    exit;
}
$token = trim(substr($auth, 7));

if (!$token) {
    http_response_code(401);
    echo json_encode(['error' => 'Invalid token']);
    exit;
}

try {
    $stmt = $pdo->prepare('SELECT user_id, expires_at FROM api_tokens WHERE token = ? LIMIT 1');
    $stmt->execute([$token]);
    $row = $stmt->fetch();

    if (!$row) {
        http_response_code(401);
        echo json_encode(['error' => 'Token not found']);
        exit;
    }

    if (new DateTime($row['expires_at']) < new DateTime()) {
        http_response_code(401);
        echo json_encode(['error' => 'Token expired']);
        exit;
    }

    $user_id = (int)$row['user_id'];

    // Find student record linked to this user
    $s = $pdo->prepare('SELECT id FROM students WHERE user_id = ? LIMIT 1');
    $s->execute([$user_id]);
    $student = $s->fetch();

    if (!$student) {
        http_response_code(400);
        echo json_encode(['error' => 'Student profile not found for this account']);
        exit;
    }

    $student_id = $student['id'];
    $today = (new DateTime())->format('Y-m-d');

    // Insert attendance, avoid duplicate because unique key exists
    $ins = $pdo->prepare('INSERT INTO attendance (student_id, date, status, marked_by) VALUES (?, ?, ?, ?) ON DUPLICATE KEY UPDATE status = VALUES(status), updated_at = CURRENT_TIMESTAMP');
    $ins->execute([$student_id, $today, 'present', $user_id]);

    echo json_encode(['success' => true, 'student_id' => $student_id, 'date' => $today, 'status' => 'present']);
    exit;
} catch (Exception $e) {
    http_response_code(500);
    echo json_encode(['error' => 'Server error', 'detail' => $e->getMessage()]);
    exit;
}
