<?php
require_once __DIR__ . '/../includes/bootstrap_api.php';

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

$keyFilePath = __DIR__ . '/key.json';
$logFilePath = __DIR__ . '/auth_debug.log';

$simpleConfig = simpleGetKeyappConfig($db);
$simpleAesKey = isset($simpleConfig['aes_key']) ? trim((string)$simpleConfig['aes_key']) : '';
$simpleAesMode = false;

function generateUniqueKey($length = 6) {
    return str_pad(rand(0, pow(10, $length) - 1), $length, '0', STR_PAD_LEFT);
}

function log_auth($msg) {
    global $logFilePath;
    if (!defined('APP_DEBUG') || !APP_DEBUG) {
        return;
    }
    $line = "[" . date("Y-m-d H:i:s") . "] " . $msg . "\n";
    app_log_append($logFilePath, $line);
}

function auth_fail_response($msg) {
    global $simpleAesMode, $simpleAesKey;

    $payload = json_encode(array(
        'STORAGE' => 'smart-tv-box',
        'error' => $msg
    ), JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);

    if ($simpleAesMode && !empty($simpleAesKey)) {
        header('Content-Type: text/plain; charset=utf-8');
        $encrypted = simpleEncryptAesPayload($payload, $simpleAesKey);
        echo ($encrypted !== false) ? $encrypted : '';
        exit;
    }

    header('Content-Type: application/json; charset=utf-8');
    echo json_encode(array(
        'STORAGE' => 'smart-tv-box',
        'data' => json_encode(array(
            'error' => $msg
        ), JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES)
    ), JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
    exit;
}

function decodeAuthDataSafe($dataEncoded) {
    $decoded1 = null;

    if (function_exists('getDecodedString')) {
        try {
            $decoded1 = getDecodedString($dataEncoded);
        } catch (Throwable $e) {
            $decoded1 = null;
        }
    }

    if (is_string($decoded1) && strlen($decoded1) > 0) {
        $tmp = json_decode($decoded1, true);
        if (is_array($tmp)) return $decoded1;
    }

    $decoded2 = base64_decode($dataEncoded, true);
    if (is_string($decoded2) && strlen($decoded2) > 0) {
        $tmp2 = json_decode($decoded2, true);
        if (is_array($tmp2)) return $decoded2;
    }

    return null;
}

$rawBody = file_get_contents('php://input');
$headerMode = isset($_SERVER['HTTP_X_AUTH_MODE']) ? trim((string)$_SERVER['HTTP_X_AUTH_MODE']) : '';

$authData = null;

if ($headerMode === 'simple_aes_v1' && !empty($simpleAesKey)) {
    $simpleAesMode = true;
    $decrypted = simpleDecryptAesPayload($rawBody, $simpleAesKey);
    if (is_string($decrypted) && strlen($decrypted) > 0) {
        $tmp = json_decode($decrypted, true);
        if (is_array($tmp)) {
            $authData = $tmp;
        }
    }

    if (!is_array($authData)) {
        log_auth('ERRO: simple_aes_decode_failed');
        auth_fail_response('decode_failed');
    }
} else {
    header('Content-Type: application/json; charset=utf-8');

    $resonse = json_decode($rawBody, true);

    if (!is_array($resonse) && isset($_POST['data'])) {
        $resonse = array('data' => $_POST['data']);
    }

    if (!is_array($resonse) || !isset($resonse['data'])) {
        log_auth('ERRO: invalid_request');
        auth_fail_response('invalid_request');
    }

    $decoded = decodeAuthDataSafe($resonse['data']);
    $authData = json_decode($decoded ? $decoded : '', true);

    if (!is_array($authData)) {
        log_auth('ERRO: Falha ao decodificar data');
        auth_fail_response('decode_failed');
    }
}

$formattedMac = '';

if (!empty($authData['app_device_id'])) {
    $macAddress = base64_decode($authData['app_device_id'], true);
    $macAddress = substr($macAddress, 0, 12);
    $formattedMac = strtoupper(preg_replace('/..(?!$)/', '$0:', $macAddress));
} else if (!empty($authData['mac_address'])) {
    $formattedMac = strtoupper($authData['mac_address']);
}

if (empty($formattedMac)) {
    log_auth('ERRO: MAC não encontrado');
    auth_fail_response('mac_not_found');
}

$keys = file_exists($keyFilePath)
    ? json_decode(file_get_contents($keyFilePath), true)
    : array();

if (isset($keys[$formattedMac])) {
    $deviceKey = $keys[$formattedMac]['key'];
} else {
    $deviceKey = generateUniqueKey();
    $keys[$formattedMac] = array(
        'key' => $deviceKey,
        'message' => 'ULTRA IBO 4.3'
    );
    file_put_contents($keyFilePath, json_encode($keys, JSON_PRETTY_PRINT));
}

$res_bot = $db->select('chatbot', 'bot_status, bot_url, bot_dns', 'id = :id', '', array(':id' => 1));
$bot_status = isset($res_bot[0]['bot_status']) ? $res_bot[0]['bot_status'] : 0;
$bot_url = isset($res_bot[0]['bot_url']) ? $res_bot[0]['bot_url'] : '';
$bot_dns_id = isset($res_bot[0]['bot_dns']) ? $res_bot[0]['bot_dns'] : '';

$existingClient = $db->select(
    'playlist',
    '*',
    'mac_address = :mac_address',
    '',
    array(':mac_address' => $formattedMac)
);

if (empty($existingClient)) {
    if ($bot_status == 1 && !empty($bot_url)) {

        $jsonBot = json_encode(array(
            'receiveMessageAppId' => 'com.whatsapp',
            'receiveMessagePattern' => array('*'),
            'senderName' => 'API DE CADASTRO',
            'senderMessage' => 'api_cadastro',
            'messageDateTime' => time(),
            'isMessageFromGroup' => false
        ));

        $ch = curl_init($bot_url);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonBot);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_TIMEOUT, 10);
        curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));

        $jsonRetorno = curl_exec($ch);
        curl_close($ch);

        $botDecoded = json_decode($jsonRetorno, true);

        $u = isset($botDecoded['username']) ? $botDecoded['username'] : null;
        $p = isset($botDecoded['password']) ? $botDecoded['password'] : null;
        $link = isset($botDecoded['payUrl']) ? $botDecoded['payUrl'] : '';

        if ($u && $p) {
            $db->insert('playlist', array(
                'dns_id' => $bot_dns_id,
                'mac_address' => $formattedMac,
                'username' => $u,
                'password' => $p,
                'pin' => '0000',
                'link' => $link,
                'device_key' => $deviceKey
            ));

            $existingClient = $db->select(
                'playlist',
                '*',
                'mac_address = :mac_address',
                '',
                array(':mac_address' => $formattedMac)
            );
        }
    }
}

$allDns = $db->select('dns', '*', '', '');
$urls = array();
$portals = array();

foreach ($allDns as $dns) {
    $p = $db->select(
        'playlist',
        '*',
        'dns_id = :d AND mac_address = :m',
        '',
        array(':d' => $dns['id'], ':m' => $formattedMac)
    );

    if (!empty($p)) {
        $urls[] = array(
            'is_protected' => 0,
            'id' => $dns['id'],
            'url' => rtrim($dns['url'], '/') .
                '/get.php?username=' . $p[0]['username'] .
                '&password=' . $p[0]['password'] .
                '&type=m3u_plus&output=ts',
            'name' => $dns['title'],
            'type' => 'conectado',
            'created_at' => date('Y-m-d H:i:s'),
            'updated_at' => date('Y-m-d H:i:s')
        );
    }

    $portals[] = array(
        'id' => $dns['id'],
        'url' => $dns['url'],
        'name' => $dns['title'],
        'type' => 'conectado'
    );
}

try {
    @$db->exec("ALTER TABLE settings ADD COLUMN whatsapp_phone TEXT NOT NULL DEFAULT ''");
} catch (Throwable $e) {
    // coluna já existe
}

$settings = $db->select('settings', '*', 'id = :id', '', array(':id' => 1));
$theme = $db->select('themes', '*', 'id = :id', '', array(':id' => 1));

$baseScheme = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') ? 'https://' : 'http://';
$baseHost = isset($_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : 'localhost';
$baseDir = rtrim(dirname(dirname($_SERVER['PHP_SELF'])), '/\\');
$baseUrl = $baseScheme . $baseHost . $baseDir;
$logoPath = dirname(__DIR__) . '/img/logo.png';
$bgPath = dirname(__DIR__) . '/img/bg.png';
$logoVersion = file_exists($logoPath) ? (string)filemtime($logoPath) : '0';
$bgVersion = file_exists($bgPath) ? (string)filemtime($bgPath) : '0';
$brandingVersion = max((int)$logoVersion, (int)$bgVersion);
$logoUrl = file_exists($logoPath) ? ($baseUrl . '/img/logo.png?v=' . $logoVersion) : '';
$backgroundUrl = file_exists($bgPath) ? ($baseUrl . '/img/bg.png?v=' . $bgVersion) : '';

$response = array(
    'android_version_code' => '1.0.0',
    'device_key' => $deviceKey,
    'expire_date' => '2034-03-26',
    'is_google_paid' => true,
    'mac_address' => $formattedMac,
    'urls' => $urls,
    'portals' => $portals,
    'STORAGE' => 'smart-tv-box',
    'pin' => isset($existingClient[0]['pin']) ? $existingClient[0]['pin'] : '0000',
    'note_title' => isset($settings[0]['note_title']) ? $settings[0]['note_title'] : '',
    'note_content' => isset($settings[0]['note_content']) ? $settings[0]['note_content'] : '',
    'whatsapp_phone' => isset($settings[0]['whatsapp_phone']) ? $settings[0]['whatsapp_phone'] : '',
    'logo_url' => $logoUrl,
    'background_url' => $backgroundUrl,
    'branding_version' => (string)$brandingVersion,
    'home_url1' => (isset($_SERVER['HTTPS']) ? 'https://' : 'http://') .
        $_SERVER['HTTP_HOST'] .
        dirname($_SERVER['PHP_SELF']) .
        '/backdrop.php',
    'theme' => isset($theme[0]['theme_id']) ? $theme[0]['theme_id'] : '1'
);

if ($simpleAesMode && !empty($simpleAesKey)) {
    header('Content-Type: text/plain; charset=utf-8');
    $encryptedResponse = simpleEncryptAesPayload(
        json_encode($response, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES),
        $simpleAesKey
    );
    echo ($encryptedResponse !== false) ? $encryptedResponse : '';
    exit;
}

header('Content-Type: application/json; charset=utf-8');
echo json_encode(array(
    'STORAGE' => 'smart-tv-box',
    'data' => json_encode($response, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES)
), JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);

exit;
