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

$logFilePath = __DIR__ . '/auth_debug.log';

function auth_log(string $message): void {
    global $logFilePath;
    if (defined('APP_DEBUG') && APP_DEBUG) {
        app_log_append($logFilePath, '[' . date('Y-m-d H:i:s') . '] ' . $message . "\n");
    }
}

function auth_fail(string $message, int $status = 400): void {
    auth_log('ERROR ' . $message);
    api_json_response([
        'STORAGE' => 'smart-tv-box',
        'data' => json_encode([
            'STORAGE' => 'smart-tv-box',
            'error' => $message,
            'urls' => [],
            'portals' => []
        ], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES)
    ], $status);
}

$request = api_read_request();
if (!isset($request['data'])) auth_fail('invalid_request');

$authData = api_decode_app_data($request['data']);
if (!is_array($authData)) auth_fail('decode_failed');

$mac = api_mac_from_payload($authData);
if ($mac === '') auth_fail('mac_not_found');

$deviceType = strtolower(trim((string)($authData['device_type'] ?? '')));
if (!in_array($deviceType, ['tv', 'mobile'], true)) $deviceType = '';

$device = api_get_or_create_device($db, $mac, $deviceType);
$deviceKey = (string)$device['device_key'];

// Provisionamento opcional pelo chatbot. É executado somente quando o MAC ainda não possui lista.
$existingClient = $db->select('playlist', '*', 'mac_address = :mac', 'id DESC', [':mac' => $mac]);
if (empty($existingClient)) {
    $botRows = $db->select('chatbot', '*', 'id = :id', '', [':id' => 1]);
    $bot = $botRows[0] ?? [];
    if ((int)($bot['bot_status'] ?? 0) === 1 && trim((string)($bot['bot_url'] ?? '')) !== '' && function_exists('curl_init')) {
        $botPayload = json_encode([
            'receiveMessageAppId' => 'com.whatsapp',
            'receiveMessagePattern' => ['*'],
            'senderName' => 'API DE CADASTRO',
            'senderMessage' => 'api_cadastro',
            'messageDateTime' => time(),
            'isMessageFromGroup' => false
        ]);

        $ch = curl_init((string)$bot['bot_url']);
        curl_setopt_array($ch, [
            CURLOPT_POST => true,
            CURLOPT_POSTFIELDS => $botPayload,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_CONNECTTIMEOUT => 4,
            CURLOPT_TIMEOUT => 10,
            CURLOPT_HTTPHEADER => ['Content-Type: application/json']
        ]);
        $botResponse = curl_exec($ch);
        curl_close($ch);
        $decodedBot = json_decode(is_string($botResponse) ? $botResponse : '', true);

        $botUser = trim((string)($decodedBot['username'] ?? ''));
        $botPass = trim((string)($decodedBot['password'] ?? ''));
        $botDnsId = (int)($bot['bot_dns'] ?? 0);

        if ($botUser !== '' && $botPass !== '' && $botDnsId > 0) {
            $dnsExists = $db->select('dns', 'id', 'id = :id', '', [':id' => $botDnsId]);
            if (!empty($dnsExists)) {
                $db->insert('playlist', [
                    'dns_id' => $botDnsId,
                    'mac_address' => $mac,
                    'username' => $botUser,
                    'password' => $botPass,
                    'pin' => (string)($device['parent_control'] ?? '0000'),
                    'link' => trim((string)($decodedBot['payUrl'] ?? '')),
                    'device_key' => $deviceKey,
                    'last_used' => time()
                ]);
            }
        }
    }
    $existingClient = $db->select('playlist', '*', 'mac_address = :mac', 'id DESC', [':mac' => $mac]);
}

$allDns = $db->select('dns', '*', '', 'id ASC');
$urls = [];
$portals = [];
$playlistsByDns = [];
foreach ($existingClient as $row) {
    $playlistsByDns[(string)$row['dns_id']] = $row;
}

foreach ($allDns as $dns) {
    $dnsId = (string)$dns['id'];
    $baseUrl = rtrim(trim((string)$dns['url']), '/');
    if ($baseUrl === '') continue;

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

    if (isset($playlistsByDns[$dnsId])) {
        $playlist = $playlistsByDns[$dnsId];
        $urls[] = [
            'id' => (string)$dns['id'],
            'is_protected' => '0',
            'name' => (string)$dns['title'],
            'type' => 'conectado',
            'url' => $baseUrl . '/get.php?username=' . rawurlencode((string)$playlist['username'])
                . '&password=' . rawurlencode((string)$playlist['password'])
                . '&type=m3u_plus&output=ts'
        ];
    }
}

$settingsRows = $db->select('settings', '*', 'id = :id', '', [':id' => 1]);
$settings = $settingsRows[0] ?? [];
$theme = api_active_theme($db);
$update = api_update_settings($db);
$panelBase = api_panel_base_url();

$pin = trim((string)($device['parent_control'] ?? '0000'));
if (($pin === '' || $pin === '0000') && !empty($existingClient)) {
    foreach ($existingClient as $client) {
        $candidate = trim((string)($client['pin'] ?? ''));
        if ($candidate !== '' && $candidate !== '0') {
            $pin = $candidate;
            break;
        }
    }
}
if ($pin === '') $pin = '0000';

$inner = [
    'STORAGE' => 'smart-tv-box',
    'apk_link' => (string)($update['apk_url'] ?? ''),
    'app_version' => (string)($update['version_name'] ?? ''),
    'android_version_code' => (string)($update['version_code'] ?? 0),
    'device_key' => $deviceKey,
    'device_type' => $deviceType,
    'expire_date' => '2034-03-26',
    'home_url1' => $panelBase . '/api/backdrop.php',
    'home_url2' => $panelBase . '/api/qr.php',
    'is_google_paid' => true,
    'is_trial' => 0,
    'languages' => [],
    'lock' => 0,
    'mac_address' => $mac,
    'mac_registered' => !empty($existingClient),
    'note_content' => (string)($settings['note_content'] ?? ''),
    'note_title' => (string)($settings['note_title'] ?? ''),
    'parent_control' => $pin,
    'parent_synced' => 1,
    'pin' => $pin,
    'plan_id' => '0',
    'portals' => $portals,
    'price' => '0',
    'qr_url' => $panelBase . '/api/qr.php',
    'qr_url_short' => api_qr_target($db),
    'theme' => (string)($theme['theme_id'] ?? '1'),
    'urls' => $urls
];

auth_log('OK mac=' . $mac . ' device=' . $deviceType . ' urls=' . count($urls) . ' portals=' . count($portals));
api_json_response([
    'STORAGE' => 'smart-tv-box',
    'data' => json_encode($inner, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES)
]);
