<?php
require_once __DIR__ . '/db.php';

function save_device_upload(array $file, string $deviceId, string $type, array $allowedExt, ?int $maxBytes = null): string
{
    $dirs = ensure_device_upload_dirs($deviceId);
    switch ($type) {
        case 'logo':
            $destDir = $dirs['logo'];
            break;
        case 'wallpaper':
            $destDir = $dirs['wallpaper'];
            break;
        case 'icons':
            $destDir = $dirs['icons'];
            break;
        case 'apk':
            $destDir = $dirs['apk'];
            break;
        default:
            throw new RuntimeException('Tipo de upload inválido.');
    }
    if ($file['error'] !== UPLOAD_ERR_OK) {
        throw new RuntimeException('Erro no upload: código ' . $file['error']);
    }
    if ($maxBytes !== null && $file['size'] > $maxBytes) {
        throw new RuntimeException('Arquivo excede o tamanho máximo permitido.');
    }
    $ext = strtolower(pathinfo($file['name'], PATHINFO_EXTENSION));
    if (!in_array($ext, $allowedExt, true)) {
        throw new RuntimeException('Extensão não permitida: ' . $ext);
    }
    $filename = uniqid('f_', true) . '.' . $ext;
    $path = rtrim($destDir, '/\\') . DIRECTORY_SEPARATOR . $filename;
    if (!move_uploaded_file($file['tmp_name'], $path)) {
        throw new RuntimeException('Falha ao salvar arquivo.');
    }
    return $filename;
}

function ensure_upload_dirs(): void
{
    foreach ([UPLOAD_LOGO, UPLOAD_WALLPAPER, UPLOAD_APP_APK, UPLOAD_APP_ICON] as $dir) {
        if (!is_dir($dir)) {
            mkdir($dir, 0755, true);
        }
    }
}

function save_upload(array $file, string $destDir, array $allowedExt, ?int $maxBytes = null): string
{
    ensure_upload_dirs();
    if ($file['error'] !== UPLOAD_ERR_OK) {
        throw new RuntimeException('Erro no upload: código ' . $file['error']);
    }
    if ($maxBytes !== null && $file['size'] > $maxBytes) {
        throw new RuntimeException('Arquivo excede o tamanho máximo permitido.');
    }
    $ext = strtolower(pathinfo($file['name'], PATHINFO_EXTENSION));
    if (!in_array($ext, $allowedExt, true)) {
        throw new RuntimeException('Extensão não permitida: ' . $ext);
    }
    $filename = uniqid('f_', true) . '.' . $ext;
    $path = rtrim($destDir, '/\\') . DIRECTORY_SEPARATOR . $filename;
    if (!move_uploaded_file($file['tmp_name'], $path)) {
        throw new RuntimeException('Falha ao salvar arquivo.');
    }
    return $filename;
}

function validate_icon_dimensions(string $path): void
{
    $info = @getimagesize($path);
    if ($info === false) {
        throw new RuntimeException('Imagem de ícone inválida.');
    }
    if ($info[0] !== ICON_WIDTH || $info[1] !== ICON_HEIGHT) {
        throw new RuntimeException(
            'Ícone deve ser exatamente ' . ICON_WIDTH . 'x' . ICON_HEIGHT . ' px (padrão Android TV).'
        );
    }
}

function flash(string $type, string $message): void
{
    $_SESSION['flash'] = ['type' => $type, 'message' => $message];
}

function get_flash(): ?array
{
    if (empty($_SESSION['flash'])) {
        return null;
    }
    $f = $_SESSION['flash'];
    unset($_SESSION['flash']);
    return $f;
}

function json_response(array $data, int $code = 200): void
{
    http_response_code($code);
    header('Content-Type: application/json; charset=utf-8');
    header('Access-Control-Allow-Origin: *');
    echo json_encode($data, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
    exit;
}

function normalize_phone_digits(string $phone): string
{
    return preg_replace('/\D+/', '', $phone) ?: '';
}

function build_whatsapp_url(string $phone, string $message = ''): string
{
    $digits = normalize_phone_digits($phone);
    if ($digits === '') {
        return '';
    }
    $url = 'https://wa.me/' . $digits;
    $message = trim($message);
    if ($message !== '') {
        $url .= '?text=' . rawurlencode($message);
    }
    return $url;
}

function get_renewal_contact(): array
{
    ensure_default_settings();
    $phone = trim(setting('renewal_contact_phone', '') ?: '');
    $message = trim(setting('renewal_contact_message', '') ?: '');
    if ($message === '') {
        $message = 'Olá, preciso renovar meu acesso IPTV.';
    }
    $whatsappUrl = build_whatsapp_url($phone, $message);
    return [
        'contact_phone' => $phone,
        'contact_message' => $message,
        'whatsapp_url' => $whatsappUrl,
    ];
}
