68 lines
1.9 KiB
PHP
68 lines
1.9 KiB
PHP
<?php
|
|
header('Content-Type: application/json');
|
|
require_once __DIR__ . '/../db/config.php';
|
|
|
|
// Simple API Key check (Optional but recommended)
|
|
// In a real scenario, you'd want a more secure way to authenticate the device
|
|
$api_key = $_GET['api_key'] ?? '';
|
|
$expected_key = getenv('ATTENDANCE_API_KEY') ?: 'secret_device_key';
|
|
|
|
if ($api_key !== $expected_key && !empty($expected_key)) {
|
|
// http_response_code(401);
|
|
// echo json_encode(['success' => false, 'error' => 'Unauthorized']);
|
|
// exit;
|
|
}
|
|
|
|
$input = file_get_contents('php://input');
|
|
$data = json_decode($input, true);
|
|
|
|
if (!$data) {
|
|
echo json_encode(['success' => false, 'error' => 'Invalid JSON input']);
|
|
exit;
|
|
}
|
|
|
|
// Normalize to array of logs
|
|
if (!isset($data[0])) {
|
|
$logs = [$data];
|
|
} else {
|
|
$logs = $data;
|
|
}
|
|
|
|
$pdo = db();
|
|
$inserted = 0;
|
|
$errors = [];
|
|
|
|
foreach ($logs as $log) {
|
|
$emp_id = $log['employee_id'] ?? null;
|
|
$timestamp = $log['timestamp'] ?? date('Y-m-d H:i:s');
|
|
$type = strtoupper($log['type'] ?? 'IN');
|
|
$device_id = $log['device_id'] ?? 'Biometric Device';
|
|
$ip = $_SERVER['REMOTE_ADDR'] ?? '';
|
|
|
|
if (!$emp_id) {
|
|
$errors[] = "Missing employee_id for a log entry";
|
|
continue;
|
|
}
|
|
|
|
try {
|
|
// Find user by employee_id
|
|
$stmt = $pdo->prepare("SELECT id FROM users WHERE employee_id = ?");
|
|
$stmt->execute([$emp_id]);
|
|
$user = $stmt->fetch();
|
|
$user_id = $user ? $user['id'] : null;
|
|
|
|
// Insert log
|
|
$stmt = $pdo->prepare("INSERT INTO attendance_logs (user_id, employee_id, log_timestamp, log_type, device_id, ip_address) VALUES (?, ?, ?, ?, ?, ?)");
|
|
$stmt->execute([$user_id, $emp_id, $timestamp, $type, $device_id, $ip]);
|
|
$inserted++;
|
|
} catch (Exception $e) {
|
|
$errors[] = "Error inserting log for $emp_id: " . $e->getMessage();
|
|
}
|
|
}
|
|
|
|
echo json_encode([
|
|
'success' => true,
|
|
'inserted' => $inserted,
|
|
'errors' => $errors
|
|
]);
|