<?php
/**
 * Save Attendance Record API
 * 
 * Receives POST data: type (CLOCK_IN/CLOCK_OUT), lat, lng, distance, is_verified
 * Inserts into geo_attendance table
 */

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'
    ]);
    exit;
}

// Get POST data
$type = isset($_POST['type']) ? $_POST['type'] : '';
$lat = isset($_POST['lat']) ? floatval($_POST['lat']) : 0;
$lng = isset($_POST['lng']) ? floatval($_POST['lng']) : 0;
$distance = isset($_POST['distance']) ? floatval($_POST['distance']) : 0;
$is_verified = isset($_POST['is_verified']) ? intval($_POST['is_verified']) : 0;

// Validate
if (empty($type) || !in_array($type, ['CLOCK_IN', 'CLOCK_OUT'])) {
    echo json_encode([
        'status' => 'error',
        'message' => 'Invalid type. Must be CLOCK_IN or CLOCK_OUT'
    ]);
    exit;
}

if ($lat == 0 || $lng == 0) {
    echo json_encode([
        'status' => 'error',
        'message' => 'Invalid coordinates'
    ]);
    exit;
}

try {
    $pdo = db_connect();
    
    $sql = "INSERT INTO geo_attendance (user_id, type, lat, lng, distance, is_verified) 
            VALUES (?, ?, ?, ?, ?, ?)";
    
    $stmt = $pdo->prepare($sql);
    $stmt->execute([
        $_SESSION['userid'],
        $type,
        $lat,
        $lng,
        $distance,
        $is_verified
    ]);
    
    $recordId = $pdo->lastInsertId();
    
    echo json_encode([
        'status' => 'success',
        'message' => 'Record saved successfully',
        'record_id' => $recordId,
        'data' => [
            'id' => $recordId,
            'type' => $type,
            'timestamp' => time() * 1000, // JavaScript timestamp (milliseconds)
            'location' => [
                'latitude' => $lat,
                'longitude' => $lng
            ],
            'distanceFromOffice' => $distance,
            'isVerified' => $is_verified == 1
        ]
    ]);
    
} catch (PDOException $e) {
    echo json_encode([
        'status' => 'error',
        'message' => 'Database error: ' . $e->getMessage()
    ]);
}
?>
