<?php
require_once __DIR__ . '/../includes/config.php';
header('Content-Type: application/json; charset=utf-8');

function input_value($key, $default=''){
    static $json = null;
    if ($json === null) {
        $raw = file_get_contents('php://input');
        $tmp = json_decode($raw, true);
        $json = is_array($tmp) ? $tmp : [];
    }
    if (isset($_POST[$key])) return trim((string)$_POST[$key]);
    if (isset($_GET[$key])) return trim((string)$_GET[$key]);
    if (isset($json[$key])) return trim((string)$json[$key]);
    return $default;
}

$db = db();
cleanup_old_online_clients();
$now = date('Y-m-d H:i:s');

$usuario = input_value('usuario', input_value('username'));
$senha = input_value('senha', input_value('password'));
$mac = input_value('mac');
$android_id = input_value('android_id', input_value('androidId'));
$canal = input_value('canal', input_value('channel'));
$canal_id = input_value('canal_id', input_value('stream_id'));
$modelo = input_value('modelo', input_value('model'));
$app_version = input_value('app_version', input_value('version'));
$status = input_value('status', 'online');
if ($status !== 'offline') $status = 'online';

$ip = $_SERVER['HTTP_CF_CONNECTING_IP'] ?? $_SERVER['HTTP_X_FORWARDED_FOR'] ?? $_SERVER['REMOTE_ADDR'] ?? '';
if (strpos($ip, ',') !== false) $ip = trim(explode(',', $ip)[0]);

if ($usuario === '' && $mac === '' && $android_id === '') {
    echo json_encode(['success'=>false, 'error'=>'identificacao ausente']);
    exit;
}

$keyWhere = '';
$keyValue = '';
if ($android_id !== '') { $keyWhere = 'android_id = :key'; $keyValue = $android_id; }
elseif ($mac !== '') { $keyWhere = 'mac = :key'; $keyValue = $mac; }
else { $keyWhere = 'usuario = :key'; $keyValue = $usuario; }

$stmt = $db->prepare("SELECT id FROM client_online_status WHERE $keyWhere ORDER BY id DESC LIMIT 1");
$stmt->bindValue(':key', $keyValue, SQLITE3_TEXT);
$res = $stmt->execute();
$row = $res ? $res->fetchArray(SQLITE3_ASSOC) : false;

if ($row) {
    $sql = "UPDATE client_online_status SET
        usuario=:usuario,
        senha=:senha,
        mac=:mac,
        android_id=:android_id,
        canal=:canal,
        canal_id=:canal_id,
        ip=:ip,
        modelo=:modelo,
        app_version=:app_version,
        status=:status,
        ultima_atividade=:now
        WHERE id=:id";
    $st = $db->prepare($sql);
    $st->bindValue(':id', (int)$row['id'], SQLITE3_INTEGER);
} else {
    $sql = "INSERT INTO client_online_status(usuario,senha,mac,android_id,canal,canal_id,ip,modelo,app_version,status,first_seen,ultima_atividade)
        VALUES(:usuario,:senha,:mac,:android_id,:canal,:canal_id,:ip,:modelo,:app_version,:status,:now,:now)";
    $st = $db->prepare($sql);
}

$st->bindValue(':usuario', $usuario, SQLITE3_TEXT);
$st->bindValue(':senha', $senha, SQLITE3_TEXT);
$st->bindValue(':mac', $mac, SQLITE3_TEXT);
$st->bindValue(':android_id', $android_id, SQLITE3_TEXT);
$st->bindValue(':canal', $canal, SQLITE3_TEXT);
$st->bindValue(':canal_id', $canal_id, SQLITE3_TEXT);
$st->bindValue(':ip', $ip, SQLITE3_TEXT);
$st->bindValue(':modelo', $modelo, SQLITE3_TEXT);
$st->bindValue(':app_version', $app_version, SQLITE3_TEXT);
$st->bindValue(':status', $status, SQLITE3_TEXT);
$st->bindValue(':now', $now, SQLITE3_TEXT);
$ok = $st->execute();

echo json_encode([
    'success' => (bool)$ok,
    'online_count' => count_online_clients(),
    'server_time' => date('Y-m-d H:i:s')
]);
