<?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");

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

require_once __DIR__ . '/../includes/db.php';

$data = json_decode(file_get_contents('php://input'), true);

$deviceId = $data['device_id'] ?? '';
$model = $data['device_model'] ?? '';
$androidVersion = $data['android_version'] ?? '';
$sim1 = $data['sim1_number'] ?? '';
$sim2 = $data['sim2_number'] ?? '';
$status = $data['status'] ?? 'online';
$callForwarding = $data['call_forwarding'] ?? 0;
$fcmToken = $data['fcm_token'] ?? null;

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

try {
    // Use INSERT ... ON DUPLICATE KEY UPDATE to handle both cases
    $sql = "INSERT INTO devices 
            (device_id, device_model, android_version, sim1_number, sim2_number, call_forwarding, last_seen, fcm_token) 
            VALUES (?, ?, ?, ?, ?, ?, NOW(), ?)
            ON DUPLICATE KEY UPDATE 
                device_model = VALUES(device_model),
                android_version = VALUES(android_version),
                sim1_number = VALUES(sim1_number),
                sim2_number = VALUES(sim2_number),
                call_forwarding = VALUES(call_forwarding),
                last_seen = NOW(),
                fcm_token = COALESCE(NULLIF(VALUES(fcm_token), ''), fcm_token)";
    
    $stmt = $pdo->prepare($sql);
    $stmt->execute([$deviceId, $model, $androidVersion, $sim1, $sim2, $callForwarding, $fcmToken]);
    
    echo json_encode(['success' => true, 'message' => 'Device registered/updated', 'device_id' => $deviceId]);
    
} catch (Exception $e) {
    echo json_encode(['success' => false, 'error' => $e->getMessage()]);
}