<?php
/**
 * Get Attendance Records API
 * 
 * Returns JSON list of attendance records for the logged-in user
 */

require_once($_SERVER['DOCUMENT_ROOT'] . '/session.php');
require_once($_SERVER['DOCUMENT_ROOT'] . '/lib/mydb.php');

header('Content-Type: application/json; charset=utf-8');

// Check if user is logged in
if (!isset($_SESSION['userid'])) {
    echo json_encode([
        'status' => 'error',
        'message' => 'User not logged in',
        'records' => []
    ]);
    exit;
}

try {
    $pdo = db_connect();
    
    // Get records for current user, ordered by most recent first
    $sql = "SELECT id, type, lat, lng, distance, is_verified, created_at 
            FROM geo_attendance 
            WHERE user_id = ? 
            ORDER BY created_at DESC 
            LIMIT 100";
    
    $stmt = $pdo->prepare($sql);
    $stmt->execute([$_SESSION['userid']]);
    $records = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    // Format records for frontend
    $formattedRecords = array_map(function($record) {
        return [
            'id' => (string)$record['id'],
            'type' => $record['type'],
            'timestamp' => strtotime($record['created_at']) * 1000, // JavaScript timestamp (milliseconds)
            'location' => [
                'latitude' => floatval($record['lat']),
                'longitude' => floatval($record['lng'])
            ],
            'distanceFromOffice' => floatval($record['distance']),
            'isVerified' => $record['is_verified'] == 1
        ];
    }, $records);
    
    echo json_encode([
        'status' => 'success',
        'records' => $formattedRecords
    ]);
    
} catch (PDOException $e) {
    echo json_encode([
        'status' => 'error',
        'message' => 'Database error: ' . $e->getMessage(),
        'records' => []
    ]);
}
?>
