<?php
/**
 * Check Device Status API
 * Quick check if device is online (last_seen within 5 min).
 * Used after wake to poll if device responded.
 * 
 * GET Parameters:
 *   - device_id (required)
 */
require_once __DIR__ . '/../includes/db.php';
require_once __DIR__ . '/../includes/auth.php';

header("Content-Type: application/json");
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: GET, OPTIONS");
header("Access-Control-Allow-Headers: Content-Type, Authorization");

if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    http_response_code(200);
    exit;
}

requireAuth();

$device_id = $_GET['device_id'] ?? '';

if (empty($device_id)) {
    echo json_encode(['success' => false, 'message' => 'Missing device_id']);
    exit;
}

$device_id = preg_replace('/[^a-zA-Z0-9_\-]/', '', $device_id);

try {
    $stmt = $pdo->prepare("SELECT last_seen FROM devices WHERE device_id = ? LIMIT 1");
    $stmt->execute([$device_id]);
    $device = $stmt->fetch(PDO::FETCH_ASSOC);

    if (!$device) {
        echo json_encode(['success' => false, 'message' => 'Device not found']);
        exit;
    }

    $lastSeen = $device['last_seen'];
    $isOnline = false;

    if ($lastSeen) {
        $lastSeenTime = strtotime($lastSeen);
        $isOnline = (time() - $lastSeenTime) < 300;
    }

    echo json_encode([
        'success' => true,
        'device_status' => $isOnline ? 'online' : 'offline',
        'last_seen' => $lastSeen ?? 'Never'
    ]);

} catch (Exception $e) {
    echo json_encode(['success' => false, 'message' => 'Server error']);
}
