<?php
// status.php - Recebe status do app (aberto/fechado)
//<----------------------------------------------------------->
//<-------------------COPIA AI BRUXÃO------------------------->
//<-------------CONTATO: https://t.me/eonbry------------------>
//<-------------DEVELOPER: EMANUEL NASCIMENTO----------------->
//<----------------------------------------------------------->

date_default_timezone_set('America/Sao_Paulo');
error_reporting(0);

// LOG PARA DEBUG
function logAppStatus($message, $mac_address = '') {
    $log_file = './status.log';
    $timestamp = date('Y-m-d H:i:s');
    $mac_info = $mac_address ? " [MAC: $mac_address]" : "";
    $log_message = "[$timestamp]$mac_info: $message\n";
    file_put_contents($log_file, $log_message, FILE_APPEND);
}

// FUNÇÕES DE ENCRYPT (MESMAS DO SEU SISTEMA)
const ALLOWED_CHARACTERS = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";

function getDecodedString($str) {
    if (empty($str)) return '';
    $encryptKeyPosition = strpos(ALLOWED_CHARACTERS, substr($str, -2, 1));
    $encryptKeyPosition2 = strpos(ALLOWED_CHARACTERS, substr($str, -1));
    
    if ($encryptKeyPosition === false || $encryptKeyPosition2 === false) return '';
    
    $substring = substr($str, 0, -2);
    $decoded = substr($substring, 0, $encryptKeyPosition) . substr($substring, $encryptKeyPosition + $encryptKeyPosition2);
    return trim(utf8_decode(base64_decode($decoded)));
}

function updateDeviceStatus($mac_address, $status) {
    logAppStatus("📡 ATUALIZANDO STATUS: MAC=$mac_address -> $status", $mac_address);
    
    $db_path = './api/.adb.db';
    
    if (!file_exists($db_path)) {
        logAppStatus("❌ Banco não encontrado: $db_path", $mac_address);
        return false;
    }
    
    try {
        $db = new SQLite3($db_path);
        $current_time = date('Y-m-d H:i:s');
        
        // Atualiza o status
        $stmt = $db->prepare("UPDATE connections SET status = :status, last_seen = :last_seen WHERE mac_address = :mac");
        $stmt->bindValue(':status', $status, SQLITE3_TEXT);
        $stmt->bindValue(':last_seen', $current_time, SQLITE3_TEXT);
        $stmt->bindValue(':mac', $mac_address, SQLITE3_TEXT);
        
        $result = $stmt->execute();
        
        if ($db->changes() > 0) {
            logAppStatus("✅ Status atualizado com sucesso!", $mac_address);
            return true;
        } else {
            // Se não encontrou, cria um novo registro
            $stmt = $db->prepare("INSERT INTO connections (mac_address, status, last_seen, ip_address, user_agent) 
                                  VALUES (:mac, :status, :last_seen, :ip, :ua)");
            
            $stmt->bindValue(':mac', $mac_address, SQLITE3_TEXT);
            $stmt->bindValue(':status', $status, SQLITE3_TEXT);
            $stmt->bindValue(':last_seen', $current_time, SQLITE3_TEXT);
            $stmt->bindValue(':ip', $_SERVER['REMOTE_ADDR'] ?? '0.0.0.0', SQLITE3_TEXT);
            $stmt->bindValue(':ua', $_SERVER['HTTP_USER_AGENT'] ?? 'AppStatus', SQLITE3_TEXT);
            
            $stmt->execute();
            logAppStatus("✅ Novo registro criado!", $mac_address);
            return true;
        }
        
    } catch (Exception $e) {
        logAppStatus("❌ ERRO SQL: " . $e->getMessage(), $mac_address);
        return false;
    }
}

// ============================================
// PROCESSAMENTO PRINCIPAL
// ============================================
logAppStatus("=== NOVA REQUISIÇÃO STATUS ===");

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $post_data = file_get_contents('php://input');
    
    logAppStatus("📥 Dados recebidos: " . substr($post_data, 0, 200));
    
    $json_data = json_decode($post_data, true);
    
    if ($json_data && isset($json_data['data'])) {
        $mac_encrypted = $json_data['data'];
        $mac_address = getDecodedString($mac_encrypted);
        
        if ($mac_address) {
            // Formata MAC
            $mac_address = strtolower($mac_address);
            if (strlen($mac_address) == 12) { // Sem separadores
                $mac_address = chunk_split($mac_address, 2, ':');
                $mac_address = rtrim($mac_address, ':');
            }
            
            logAppStatus("✅ MAC identificado: $mac_address", $mac_address);
            
            // Verifica se é comando de "app_closed"
            if (isset($json_data['action']) && $json_data['action'] == 'app_closed') {
                updateDeviceStatus($mac_address, 'offline');
                logAppStatus("📴 APP FECHADO DETECTADO!", $mac_address);
            } else {
                updateDeviceStatus($mac_address, 'online');
                logAppStatus("📱 APP ABERTO DETECTADO!", $mac_address);
            }
            
            // Resposta de sucesso
            echo json_encode(['status' => 'success', 'message' => 'Status updated']);
            exit;
        }
    }
    
    logAppStatus("❌ Dados inválidos ou MAC não identificado");
    echo json_encode(['status' => 'error', 'message' => 'Invalid data']);
    exit;
}

// Se GET, mostra info
echo json_encode([
    'status' => 'running',
    'endpoint' => 'status.php',
    'description' => 'Recebe status do app (online/offline)',
    'timestamp' => date('Y-m-d H:i:s')
]);
?>