<?php
ini_set('display_errors', 1);
include(__DIR__ . '/../includes/functions.php');

$jsonIn = file_get_contents('php://input');
$response = json_decode($jsonIn, true);
$decoded = base64_decode($response['data']);
$authData = json_decode($decoded, true);

$portal = [];

/** ========================
 *   QR CODE desde rgvip_qrcode.db
 *  ======================== */
$qrcode_db_path = __DIR__ . '/rgvip_qrcode.db';
$qrcode_db = new SQLite3($qrcode_db_path);

// Crear tabla si no existe
$qrcode_db->exec("CREATE TABLE IF NOT EXISTS qrcode (
    id INTEGER PRIMARY KEY,
    qrcode TEXT
)");

// Consultar el registro principal
$qrcode_result = $qrcode_db->query("SELECT qrcode FROM qrcode WHERE id = 1 LIMIT 1");
$row = $qrcode_result->fetchArray(SQLITE3_ASSOC);

// URL desde rgvip_qrcode.db
$qrCodeURL   = $row['qrcode'] ?? '';

// Texto corto desde la DB principal (tabla qr_code)
$qr_code_main = $db->select('qr_code', '*', 'id = :id', '', [':id' => 1]);
$qrCodeLabel  = $qr_code_main[0]['name'] ?? '';

/** ========================
 *   MAC Address
 *  ======================== */
if (!empty($authData['app_device_id'])) {
    $macAddress = base64_decode($authData['app_device_id']);
    $macAddress = substr($macAddress, 0, 8);
    $formattedMac = strtoupper(implode(':', str_split($macAddress, 2)));
} else {
    $formattedMac = strtoupper($authData['mac_address']);
}

/** ========================
 *   Consultar Playlists
 *  ======================== */
$res = $db->select('dns', '*', '', '');

foreach ($res as $row) {
    $result = $db->select(
        'playlist',
        '*',
        'dns_id = :dns_id AND mac_address = :mac_address',
        '',
        [':dns_id' => $row['id'], ':mac_address' => $formattedMac]
    );

    if (!empty($result)) {
        $portal[] = [
            'is_protected' => (int)$result[0]['is_protected'],
            'id'           => $row['id'],
            'url'          => $row['url'] . '/get.php?username=' . $result[0]['username'] .
                              '&password=' . $result[0]['password'] .
                              '&type=m3u_plus&output=ts',
            'name'         => $row['title'],
            'playlist_name'=> $row['title'],
            'type'         => 'xc',
            'created_at'   => '2023-03-26 16:42:48',
            'updated_at'   => '2023-03-26 16:42:48'
        ];
    }
}

/** ========================
 *   Helpers
 *  ======================== */
function getBaseUrl() {
    $protocol   = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off'
                  || $_SERVER['SERVER_PORT'] == 443) ? "https://" : "http://";
    $domainName = $_SERVER['HTTP_HOST'];
    $folderPath = dirname($_SERVER['PHP_SELF']);
    return $protocol . $domainName . $folderPath;
}

$backdropUrl  = getBaseUrl() . '/backdrop.php';
$settings     = $db->select('settings', '*', 'id = :id', '', [':id' => 1]);
$theme        = $db->select('themes', '*', 'id = :id', '', [':id' => 1]);
$theme_id     = !empty($theme) ? $theme[0]['theme_id'] : '1';

$result_pin   = $db->select('playlist', '*', 'mac_address = :mac_address', '', [':mac_address' => $formattedMac]);
$urlActivarPublico = dirname(getBaseUrl()) . '/activar_publico.php';

/** ========================
 *   Respuesta final
 *  ======================== */
$response = [
    'android_version_code' => '1.0.0',
    'apk_url'              => '',
    'device_key'           => '883348',
    'expire_date'          => '2034-03-26',
    'is_google_paid'       => true,
    'is_trial'             => 0,
    'languages'            => json_decode(file_get_contents('language.json'), true),
    'mac_registered'       => true,
    'themes'               => [],
    'trial_days'           => 7,
    'plan_id'              => '36269518',
    'mac_address'          => $formattedMac,
    'pin'                  => $result_pin[0]['pin'] ?? '0000',
    'price'                => '7.99',
    'apk_link'             => '',
    'urls'                 => $portal,
    'note_title'           => $settings[0]['note_title'],
    'note_content'         => $settings[0]['note_content'],
    'qr_url'               => $qrCodeURL,
    'qr_url_short'         => $qrCodeLabel,
    'home_mode'            => null,
    'home_url1'            => $backdropUrl,
    'home_url2'            => $backdropUrl,
    'theme'                => $theme_id
];

echo (Encryption::run(json_encode($response), "IBO_38"));
