<?php
include(__DIR__ . '/../includes/functions.php');

if (!isset($_GET['username']) || !isset($_GET['password'])) {
    outecho(0, null);
    exit;
}

$username = $_GET['username'];
$password = $_GET['password'];

// Busca o DNS cadastrado no banco
$dns_list = $db->select('dns', '*', '', '');
$dns_url  = !empty($dns_list) ? rtrim($dns_list[0]['url'], '/') : null;

if (!$dns_url) {
    outecho(0, null);
    exit;
} // <---- faltou essa chave no seu código!

// Pega todo o resto da Url de maneira automática para filmes/canais
$action_query = "";
if (isset($_GET['action'])) {
    $action_query .= "&action=" . urlencode($_GET['action']);
}
if (isset($_GET['category_id'])) {
    $action_query .= "&category_id=" . urlencode($_GET['category_id']);
}

$api_url = $dns_url . '/player_api.php?username=' . urlencode($username) . '&password=' . urlencode($password) . $action_query;

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $api_url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_TIMEOUT, 10);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
$response = curl_exec($ch);
curl_close($ch);

// SE FOR UM PEDIDO DE CANAIS/FILMES, nós mandamos a resposta direto pro celular e FIM!
if(isset($_GET['action'])) {
    header('Content-type: application/json; charset=UTF-8');
    echo $response;
    exit;
}

// SE NÃO (significa que é o Login inicial), continua validando como antes para salvar a Sessão
$data = json_decode($response, true);
if (!$data || !isset($data['user_info'])) {
    outecho(0, null);
    exit;
}

$auth = isset($data['user_info']['auth']) ? (int)$data['user_info']['auth'] : 0;

if ($auth === 1) {
    // Registra ou atualiza usuário no banco local
    registerUser($username, $password, $data['user_info']);
    // Registra sessão ativa
    registerSession($username);
    outecho(1, $data);
} else {
    outecho(2, $data);
}

// ── Registra usuário no menualuser ──────────────────────────
function registerUser($username, $password, $user_info) {
    global $db;

    $expire_ts   = isset($user_info['exp_date']) ? (int)$user_info['exp_date'] : 0;
    date_default_timezone_set('America/Sao_Paulo');
    $expire_date = $expire_ts ? date('Y-m-d', $expire_ts) : '';
    $title       = isset($user_info['message']) && !empty($user_info['message']) ? $user_info['message'] : $username;

    $existing = $db->select('menualuser', '*', 'username = :u', '', [':u' => $username]);

    if (!empty($existing)) {
        $db->update('menualuser',
            ['password' => $password, 'expire_date' => $expire_date],
            'username = :u',
            [':u' => $username]
        );
    } else {
        $db->insert('menualuser', [
            'title'       => $title,
            'username'    => $username,
            'password'    => $password,
            'expire_date' => $expire_date,
        ]);
    }
}

// ── Registra sessão ativa ────────────────────────────────────
function registerSession($username) {
    global $db;
    $ip     = isset($_SERVER['HTTP_X_FORWARDED_FOR']) ? explode(',', $_SERVER['HTTP_X_FORWARDED_FOR'])[0] : $_SERVER['REMOTE_ADDR'];
    $ip     = htmlspecialchars(trim($ip), ENT_QUOTES, 'UTF-8');
    $device = isset($_SERVER['HTTP_USER_AGENT']) ? htmlspecialchars($_SERVER['HTTP_USER_AGENT'], ENT_QUOTES, 'UTF-8') : 'Unknown';
    $now    = time();

    $existing = $db->select('active_sessions', '*', 'username = :u', '', [':u' => $username]);

    if (!empty($existing)) {
        $db->update('active_sessions',
            ['ip' => $ip, 'device' => $device, 'last_seen' => $now],
            'username = :u',
            [':u' => $username]
        );
    } else {
        $db->insert('active_sessions', [
            'username'  => $username,
            'ip'        => $ip,
            'device'    => $device,
            'last_seen' => $now,
        ]);
    }
}

// ── Resposta ao app ──────────────────────────────────────────
function outecho($status, $external_data) {
    $now      = time();
    $time_now = date('Y-m-d H:i:s');

    // Usa dados do servidor externo se disponível
    if ($external_data && isset($external_data['server_info'])) {
        $server_info = $external_data['server_info'];
    } else {
        $server_info = array(
            "url"             => "teste.apkpremium.fun",
            "port"            => "80",
            "https_port"      => "443",
            "server_protocol" => "https",
            "rtmp_port"       => "1935",
            "timezone"        => "America/Sao_Paulo",
            "timestamp_now"   => $now,
            "time_now"        => $time_now
        );
    }

    if ($status == 1 && $external_data) {
        // Retorna exatamente o que o servidor externo retornou
        $response = $external_data;
    } else if ($status == 2 && $external_data) {
        $response = $external_data;
    } else {
        $response = array(
            "user_info" => array(
                "username"               => isset($_GET['username']) ? $_GET['username'] : '',
                "password"               => isset($_GET['password']) ? $_GET['password'] : '',
                "message"                => "User not found",
                "auth"                   => 0,
                "status"                 => "Disabled",
                "exp_date"               => (string)($now + 86400),
                "is_trial"               => "0",
                "active_cons"            => "0",
                "created_at"             => (string)$now,
                "max_connections"        => "1",
                "allowed_output_formats" => ["m3u8", "ts"]
            ),
            "server_info" => $server_info
        );
    }

    header('Content-type: application/json; charset=UTF-8');
    echo json_encode($response, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
}
?>
