<?php
require_once __DIR__ . '/../includes/db.php';
require_once __DIR__ . '/../includes/auth.php';
header('Content-Type: application/json');

// Require valid auth token
requireAuth();

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

if ($device_id === '') {
    echo json_encode(['success' => false, 'message' => 'Device ID is required']);
    exit;
}

try {
    // ✅ Calculate device_status inside SQL
    $stmt = $pdo->prepare("
        SELECT 
            device_id, 
            device_model, 
            android_version, 
            sim1_number, 
            sim2_number, 
            last_seen, 
            call_forwarding,
            IF(TIMESTAMPDIFF(SECOND, last_seen, NOW()) <= 300, 'online', 'offline') AS device_status
        FROM devices
        WHERE device_id = ?
    ");
    $stmt->execute([$device_id]);
    $device = $stmt->fetch(PDO::FETCH_ASSOC);

    if ($device) {
        echo json_encode(['success' => true, 'device' => $device]);
    } else {
        echo json_encode(['success' => false, 'message' => 'Device not found']);
    }
} catch (Exception $e) {
    echo json_encode(['success' => false, 'message' => $e->getMessage()]);
}
?>
