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

// Require valid auth token
requireAuth();

try {
    // Auto-create preferred_sim column if it doesn't exist
    try {
        $pdo->exec("ALTER TABLE devices ADD COLUMN preferred_sim VARCHAR(4) DEFAULT NULL");
    } catch (Exception $e) { /* already exists */ }

    // ✅ Device status is calculated using MySQL TIMESTAMPDIFF
    $stmt = $pdo->query("
        SELECT 
            device_id, 
            device_model, 
            android_version, 
            sim1_number, 
            sim2_number, 
            last_seen, 
            call_forwarding,
            preferred_sim,
            IF(TIMESTAMPDIFF(SECOND, last_seen, NOW()) <= 300, 'online', 'offline') AS device_status
        FROM devices
        ORDER BY last_seen DESC
    ");

    $devices = $stmt->fetchAll(PDO::FETCH_ASSOC);

    echo json_encode(['success' => true, 'devices' => $devices]);
} catch (Exception $e) {
    echo json_encode(['success' => false, 'message' => $e->getMessage()]);
}
?>
