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

$pdo = db();

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    header('Content-Type: application/json');

    $studentIdentifier = trim($_POST['student'] ?? '');
    $activityId = (int) ($_POST['activity_id'] ?? 0);
    $status = $_POST['status'] ?? 'present';
    $notes = trim($_POST['notes'] ?? 'Manual entry');

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

    $studentStmt = $pdo->prepare(
        'SELECT * FROM students WHERE (student_id = :identifier OR qr_code = :identifier) LIMIT 1'
    );
    $studentStmt->execute(['identifier' => $studentIdentifier]);
    $student = $studentStmt->fetch();
    if (!$student) {
        http_response_code(404);
        echo json_encode(['success' => false, 'message' => 'Student not found.']);
        exit;
    }

    $activityStmt = $pdo->prepare('SELECT * FROM activities WHERE id = :id LIMIT 1');
    $activityStmt->execute(['id' => $activityId]);
    $activity = $activityStmt->fetch();
    if (!$activity) {
        http_response_code(404);
        echo json_encode(['success' => false, 'message' => 'Activity not found.']);
        exit;
    }

    $now = (new DateTime())->format('Y-m-d H:i:s');
    $attendanceStmt = $pdo->prepare(
        'INSERT INTO attendance (student_id, activity_id, time_in, status, notes)
         VALUES (:student_id, :activity_id, :time_in, :status, :notes)
         ON DUPLICATE KEY UPDATE status = VALUES(status), notes = VALUES(notes),
             updated_at = CURRENT_TIMESTAMP'
    );
    $attendanceStmt->execute([
        'student_id' => $student['id'],
        'activity_id' => $activityId,
        'time_in' => $now,
        'status' => $status,
        'notes' => $notes,
    ]);

    $attendanceId = (int) $pdo->lastInsertId();
    if (!$attendanceId) {
        $idLookup = $pdo->prepare(
            'SELECT id FROM attendance WHERE student_id = :student_id AND activity_id = :activity_id LIMIT 1'
        );
        $idLookup->execute([
            'student_id' => $student['id'],
            'activity_id' => $activityId,
        ]);
        $attendanceId = (int) $idLookup->fetchColumn();
    }
    $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' => 'manual_entry',
        'old_value' => null,
        'new_value' => $now,
        'changed_by' => current_user()['id'],
        'notes' => $notes,
    ]);

    echo json_encode(['success' => true, 'message' => 'Manual attendance recorded.']);
    exit;
}

// GET export
$filters = [
    'start_date' => $_GET['start_date'] ?? null,
    'end_date' => $_GET['end_date'] ?? null,
    'activity_id' => $_GET['activity_id'] ?? null,
    'status' => $_GET['status'] ?? null,
];

$conditions = [];
$params = [];
if ($filters['start_date']) {
    $conditions[] = 'DATE(att.time_in) >= :start_date';
    $params['start_date'] = $filters['start_date'];
}
if ($filters['end_date']) {
    $conditions[] = 'DATE(att.time_in) <= :end_date';
    $params['end_date'] = $filters['end_date'];
}
if ($filters['activity_id']) {
    $conditions[] = 'att.activity_id = :activity_id';
    $params['activity_id'] = (int) $filters['activity_id'];
}
if ($filters['status']) {
    $conditions[] = 'att.status = :status';
    $params['status'] = $filters['status'];
}
$where = $conditions ? 'WHERE ' . implode(' AND ', $conditions) : '';

$stmt = $pdo->prepare(
    "SELECT att.*, s.full_name, s.student_id, act.name AS activity_name
     FROM attendance att
     INNER JOIN students s ON att.student_id = s.id
     INNER JOIN activities act ON att.activity_id = act.id
     $where
     ORDER BY att.time_in DESC"
);
$stmt->execute($params);

header('Content-Type: application/json');
echo json_encode($stmt->fetchAll());
