<?php
/**
 * API pública consumida pelo app Android (Retrofit)
 * GET ?device_id=UUID — configuração exclusiva do dispositivo
 */
require_once __DIR__ . '/../../includes/db.php';
require_once __DIR__ . '/../../includes/helpers.php';

header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, OPTIONS');
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    exit(0);
}

try {
    ensure_default_settings();

    $deviceId = trim($_GET['device_id'] ?? '');
    if (!is_valid_device_id($deviceId)) {
        json_response([
            'success' => false,
            'error' => 'Parâmetro device_id obrigatório (UUID).',
        ], 400);
    }

    $device = get_device($deviceId);
    if (!$device) {
        register_device($deviceId, null, trim($_GET['model'] ?? '') ?: null);
        ensure_device_upload_dirs($deviceId);
        $device = get_device($deviceId);
    } else {
        touch_device($deviceId);
    }

    $dnsStmt = db()->query(
        'SELECT id, name, server_url, priority
         FROM dns_servers WHERE is_active = 1 ORDER BY priority ASC, id ASC'
    );
    $dnsServers = [];
    foreach ($dnsStmt->fetchAll() as $row) {
        $dnsServers[] = [
            'id' => (int) $row['id'],
            'name' => $row['name'],
            'url' => rtrim($row['server_url'], '/'),
            'priority' => (int) $row['priority'],
        ];
    }

    $appsStmt = db()->prepare(
        'SELECT id, name, package_name, icon_file, apk_file, sort_order
         FROM device_apps
         WHERE device_id = ? AND is_enabled = 1
         ORDER BY sort_order ASC, id ASC
         LIMIT ' . MAX_APPS
    );
    $appsStmt->execute([$deviceId]);
    $apps = [];
    foreach ($appsStmt->fetchAll() as $row) {
        $apps[] = [
            'id' => (int) $row['id'],
            'name' => $row['name'],
            'package_name' => $row['package_name'] ?? '',
            'icon_url' => device_upload_url($deviceId, 'apps/icons/' . $row['icon_file']),
            'apk_url' => $row['apk_file']
                ? device_upload_url($deviceId, 'apps/apk/' . $row['apk_file'])
                : null,
            'sort_order' => (int) $row['sort_order'],
        ];
    }

    $launcherBlocked = (int) ($device['launcher_blocked'] ?? 0) === 1;
    $settingsLockEnabled = (int) ($device['settings_lock_enabled'] ?? 0) === 1;
    $settingsLockHash = $device['settings_lock_hash'] ?? '';
    $renewal = get_renewal_contact();

    json_response([
        'success' => true,
        'panel_url' => PANEL_BASE_URL,
        'device_id' => $deviceId,
        'updated_at' => date('c'),
        'data' => [
            'branding' => [
                'app_name' => $device['app_name'] ?: 'NEXUS TV',
                'logo_url' => !empty($device['logo_file'])
                    ? device_upload_url($deviceId, 'logo/' . $device['logo_file'])
                    : null,
                'wallpaper_url' => !empty($device['wallpaper_file'])
                    ? device_upload_url($deviceId, 'wallpaper/' . $device['wallpaper_file'])
                    : null,
            ],
            'security' => [
                'launcher_blocked' => $launcherBlocked,
                'block_message' => $device['block_message']
                    ?: 'Este launcher foi desativado pelo administrador.',
                'settings_lock_enabled' => $settingsLockEnabled && $settingsLockHash !== '',
                'settings_lock_hash' => ($settingsLockEnabled && $settingsLockHash !== '') ? $settingsLockHash : null,
                'iptv_reset_nonce' => (int) ($device['iptv_reset_nonce'] ?? 0),
            ],
            'dns_servers' => $dnsServers,
            'apps' => $apps,
            'renewal' => $renewal,
        ],
    ]);
} catch (Throwable $e) {
    json_response([
        'success' => false,
        'error' => $e->getMessage(),
    ], 500);
}
