<?php
/**
 * Wake Device API
 * Sends a high-priority FCM ping to wake up a specific device.
 * Then checks if device responded (last_seen updated).
 * 
 * POST Parameters:
 *   - device_id (required)
 * 
 * Response:
 *   - success: bool
 *   - device_status: "online" | "offline"
 *   - fcm_sent: bool
 *   - last_seen: string (timestamp)
 */
require_once __DIR__ . '/../includes/db.php';
require_once __DIR__ . '/../includes/auth.php';
require_once __DIR__ . '/../../fcm/fcm_send.php';

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

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

// Require valid auth token
requireAuth();

// Accept both form-data and JSON
$rawInput = file_get_contents("php://input");
$inputJson = json_decode($rawInput, true);
$data = array_merge($_POST, is_array($inputJson) ? $inputJson : []);

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

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

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

try {
    // Check device exists and get current last_seen
    $stmt = $pdo->prepare("SELECT device_id, fcm_token, 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;
    }

    // Send FCM wake ping
    $fcmResult = ['success' => false, 'error' => 'FCM not attempted'];

    if (!empty($device['fcm_token']) && isFCMConfigured()) {
        $fcmResult = sendFCMTrigger($device_id, 'wake_ping', [
            'request_heartbeat' => '1'
        ]);
    } else {
        $fcmResult = ['success' => false, 'error' => empty($device['fcm_token']) ? 'No FCM token' : 'FCM not configured'];
    }

    // Check online status (last_seen within 5 minutes = online)
    $lastSeen = $device['last_seen'];
    $isOnline = false;
    
    if ($lastSeen) {
        $lastSeenTime = strtotime($lastSeen);
        $isOnline = (time() - $lastSeenTime) < 300; // 5 minutes
    }

    echo json_encode([
        'success' => true,
        'message' => $fcmResult['success'] ? 'Wake signal sent successfully' : 'Wake signal failed: ' . ($fcmResult['error'] ?? 'Unknown'),
        'fcm_sent' => $fcmResult['success'] ?? false,
        'device_status' => $isOnline ? 'online' : 'offline',
        'last_seen' => $lastSeen ?? 'Never',
        'device_id' => $device_id
    ]);

} catch (Exception $e) {
    error_log("Wake device error for $device_id: " . $e->getMessage());
    echo json_encode(['success' => false, 'message' => 'Server error']);
}
