<?php
require_once("admin/inc/protecao-final.php");
require_once("app/wideimage/WideImage.php");

$total_avisos_ativos = mysqli_num_rows(mysqli_query($conexao,"SELECT * FROM avisos WHERE area = 'streaming'"));
$checar_status_aviso = mysqli_num_rows(mysqli_query($conexao,"SELECT * FROM avisos_desativados WHERE area = 'streaming' AND codigo_usuario = '".$dados_stm["porta"]."'"));
$total_avisos_exibir = ($total_avisos_ativos > $checar_status_aviso) ? $total_avisos_ativos-$checar_status_aviso : 0;

//Funções
function formatar_nome_radio_novo($nome){$characteres=array('S'=>'S','s'=>'s','Ð'=>'Dj','Z'=>'Z','z'=>'z','À'=>'A','Á'=>'A','Â'=>'A','Ã'=>'A','Ä'=>'A','Å'=>'A','Æ'=>'A','Ç'=>'C','È'=>'E','É'=>'E','Ê'=>'E','Ë'=>'E','Ì'=>'I','Í'=>'I','Î'=>'I','Ï'=>'I','Ñ'=>'N','Ò'=>'O','Ó'=>'O','Ô'=>'O','Õ'=>'O','Ö'=>'O','Ø'=>'O','Ù'=>'U','Ú'=>'U','Û'=>'U','Ü'=>'U','Ý'=>'Y','Þ'=>'B','ß'=>'Ss','à'=>'a','á'=>'a','â'=>'a','ã'=>'a','ä'=>'a','å'=>'a','æ'=>'a','ç'=>'c','è'=>'e','é'=>'e','ê'=>'e','ë'=>'e','ì'=>'i','í'=>'i','î'=>'i','ï'=>'i','ð'=>'o','ñ'=>'n','ò'=>'o','ó'=>'o','ô'=>'o','õ'=>'o','ö'=>'o','ø'=>'o','ù'=>'u','ú'=>'u','û'=>'u','ý'=>'y','ý'=>'y','þ'=>'b','ÿ'=>'y','f'=>'f','¹'=>'','²'=>'','&'=>'e','³'=>'','£'=>'','$'=>'','%'=>'','¨'=>'','§'=>'','º'=>'','ª'=>'','©'=>'','Ã£'=>'','('=>'',')'=>'',"'"=>'','@'=>'','='=>'',':'=>'','!'=>'','?'=>'','...'=>'','®'=>'','/'=>'','´'=>'','+'=>'','*'=>'','['=>'',']'=>'');return strtr($nome,$characteres);}function nome_app_play_novo($texto){$characteres=array('S'=>'S','s'=>'s','Ð'=>'Dj','Z'=>'Z','z'=>'z','À'=>'A','Á'=>'A','Â'=>'A','Ã'=>'A','Ä'=>'A','Å'=>'A','Æ'=>'A','Ç'=>'C','È'=>'E','É'=>'E','Ê'=>'E','Ë'=>'E','Ì'=>'I','Í'=>'I','Î'=>'I','Ï'=>'I','Ñ'=>'N','Ò'=>'O','Ó'=>'O','Ô'=>'O','Õ'=>'O','Ö'=>'O','Ø'=>'O','Ù'=>'U','Ú'=>'U','Û'=>'U','Ü'=>'U','Ý'=>'Y','Þ'=>'B','ß'=>'Ss','à'=>'a','á'=>'a','â'=>'a','ã'=>'a','ä'=>'a','å'=>'a','æ'=>'a','ç'=>'c','è'=>'e','é'=>'e','ê'=>'e','ë'=>'e','ì'=>'i','í'=>'i','î'=>'i','ï'=>'i','ð'=>'o','ñ'=>'n','ò'=>'o','ó'=>'o','ô'=>'o','õ'=>'o','ö'=>'o','ø'=>'o','ù'=>'u','ú'=>'u','û'=>'u','ý'=>'y','ý'=>'y','þ'=>'b','ÿ'=>'y','f'=>'f','¹'=>'','²'=>'','&'=>'e','³'=>'','£'=>'','$'=>'','%'=>'','¨'=>'','§'=>'','º'=>'','ª'=>'','©'=>'','Ã£'=>'','('=>'',')'=>'',"'"=>'','@'=>'','='=>'',':'=>'','!'=>'','?'=>'','...'=>'',' '=>'','-'=>'','^'=>'','~'=>'','.'=>'','|'=>'',','=>'','<'=>'','>'=>'','{'=>'','}'=>'','®'=>'','/'=>'','´'=>'','+'=>'','*'=>'','['=>'',']'=>'');return strtolower(strtr($texto,$characteres));}function nome_app_apk_novo($texto){$characteres=array('S'=>'S','s'=>'s','Ð'=>'Dj','Z'=>'Z','z'=>'z','À'=>'A','Á'=>'A','Â'=>'A','Ã'=>'A','Ä'=>'A','Å'=>'A','Æ'=>'A','Ç'=>'C','È'=>'E','É'=>'E','Ê'=>'E','Ë'=>'E','Ì'=>'I','Í'=>'I','Î'=>'I','Ï'=>'I','Ñ'=>'N','Ò'=>'O','Ó'=>'O','Ô'=>'O','Õ'=>'O','Ö'=>'O','Ø'=>'O','Ù'=>'U','Ú'=>'U','Û'=>'U','Ü'=>'U','Ý'=>'Y','Þ'=>'B','ß'=>'Ss','à'=>'a','á'=>'a','â'=>'a','ã'=>'a','ä'=>'a','å'=>'a','æ'=>'a','ç'=>'c','è'=>'e','é'=>'e','ê'=>'e','ë'=>'e','ì'=>'i','í'=>'i','î'=>'i','ï'=>'i','ð'=>'o','ñ'=>'n','ò'=>'o','ó'=>'o','ô'=>'o','õ'=>'o','ö'=>'o','ø'=>'o','ù'=>'u','ú'=>'u','û'=>'u','ý'=>'y','ý'=>'y','þ'=>'b','ÿ'=>'y','f'=>'f','¹'=>'','²'=>'','&'=>'e','³'=>'','£'=>'','$'=>'','%'=>'','¨'=>'','§'=>'','º'=>'','ª'=>'','©'=>'','Ã£'=>'','('=>'',')'=>'',"'"=>'','@'=>'','='=>'',':'=>'','!'=>'','?'=>'','...'=>'',' '=>'','-'=>'','^'=>'','~'=>'','.'=>'','|'=>'',','=>'','<'=>'','>'=>'','{'=>'','}'=>'',' '=>'','®'=>'','/'=>'','´'=>'','+'=>'','*'=>'','['=>'',']'=>'');return strtr($texto,$characteres);}function copiar_source_novo($DirFont,$DirDest){mkdir($DirDest);if($dd=opendir($DirFont)){while(false!==($Arq=readdir($dd))){if($Arq!="."&&$Arq!=".."){$PathIn="$DirFont/$Arq";$PathOut="$DirDest/$Arq";if(is_dir($PathIn)){copiar_source_novo($PathIn,$PathOut);chmod($PathOut,0777);}elseif(is_file($PathIn)){copy($PathIn,$PathOut);chmod($PathOut,0777);}}}closedir($dd);}}function criar_arquivo_config_novo($arquivo,$conteudo){$fd=fopen($arquivo,"w");fputs($fd,$conteudo);fclose($fd);}function browse_novo($dir){global $filenames;if($handle=opendir($dir)){while(false!==($file=readdir($handle))){if($file!="."&&$file!=".."&&is_file($dir.'/'.$file)){$filenames[]=$dir.'/'.$file;}else if($file!="."&&$file!=".."&&is_dir($dir.'/'.$file)){browse_novo($dir.'/'.$file);}}closedir($handle);}return $filenames;}function replace_novo($arquivo,$string_atual,$string_nova){$str=file_get_contents($arquivo);$str=str_replace($string_atual,$string_nova,$str);file_put_contents($arquivo,$str);}function remover_source_app_novo($Dir){if($dd=@opendir($Dir)){while(false!==($Arq=@readdir($dd))){if($Arq!="."&&$Arq!=".."){$Path="$Dir/$Arq";if(is_dir($Path)){remover_source_app_novo($Path);}elseif(is_file($Path)){@unlink($Path);}}}@closedir($dd);}@rmdir($Dir);}function mudar_permissao_novo($Dir){if($dd=opendir($Dir)){while(false!==($Arq=readdir($dd))){if($Arq!="."&&$Arq!=".."){$Path="$Dir/$Arq";@chmod($Path,0777);}}closedir($dd);}}

$dados_config = mysqli_fetch_array(mysqli_query($conexao,"SELECT * FROM configuracoes"));
$dados_stm = mysqli_fetch_array(mysqli_query($conexao,"SELECT * FROM streamings where porta = '".$_SESSION["porta_logada"]."'"));
$dados_servidor = mysqli_fetch_array(mysqli_query($conexao,"SELECT * FROM servidores where codigo = '".$dados_stm["codigo_servidor"]."'"));


/////////////////////////////////////////////////
/////////////////// Idioma //////////////////////
/////////////////////////////////////////////////

if($dados_stm["idioma_painel"] == "pt-br") {

$lang[ 'lang_info_streaming_app_android_tab_app_pronto' ] = 'App Pronto' ;
$lang[ 'lang_info_streaming_app_android_tab_criar_app' ] = 'Criar App' ;
$lang[ 'lang_info_streaming_app_android_tab_configurar_app' ] = 'Configurar App' ;
$lang[ 'lang_info_streaming_app_android_info_configuracoes' ] = 'As demais configura&ccedil;&otilde;es do app, como site, redes sociais e outros ser&atilde;o configurados aqui ap&oacute;s criar o app.' ;
$lang[ 'lang_info_streaming_app_android_info_configuracoes2' ] = 'Ao alterar as configura&ccedil;&otilde;es abaixo, as mesmas ser&atilde;o atualizadas autom&aacute;ticamente no app sem precisar criar um novo.' ;
$lang[ 'lang_info_streaming_app_android_info_desativar_campo' ] = 'Para desativar alguma op&ccedil;&atilde;o, deixe em branco o campo correspondente.';
$lang[ 'lang_info_streaming_app_android_exibir_capa_artista' ] = 'Exibir Capa Artista' ;
$lang[ 'lang_info_streaming_app_android_certificado' ] = 'Certificado Assinatura' ;
$lang[ 'lang_info_streaming_app_android_certificado_opcao1' ] = 'Criar Certificado Pr&oacute;prio(somente se estiver criando o app pela primeira vez)' ;
$lang[ 'lang_info_streaming_app_android_certificado_opcao2' ] = 'Usar Certificado Pr&oacute;prio' ;
$lang[ 'lang_info_streaming_app_android_saudacao' ] = 'Mensagem de Sauda&ccedil;&atilde;o' ;
$lang[ 'lang_info_streaming_app_android_historia' ] = 'História' ;
$lang[ 'lang_info_streaming_app_android_programacao' ] = 'Programação' ;
$lang[ 'lang_info_streaming_app_android_pedido' ] = 'Pedir Música' ;
$lang[ 'lang_info_streaming_app_android_status_modal' ] = 'Criando aplicativo, isso pode levar alguns minutos, por favor aguarde!' ;

} else if($dados_stm["idioma_painel"] == "en") {

$lang[ 'lang_info_streaming_app_android_tab_app_pronto' ] = 'App Created' ;
$lang[ 'lang_info_streaming_app_android_tab_criar_app' ] = 'Create App' ;
$lang[ 'lang_info_streaming_app_android_tab_configurar_app' ] = 'Configure App' ;
$lang[ 'lang_info_streaming_app_android_info_configuracoes' ] = 'The other settings of the app, such as website, social networks and others will be configured here after creating the app.' ;
$lang[ 'lang_info_streaming_app_android_info_configuracoes2' ] = 'When changing the settings below, they will be updated automatically in the app without having to create a new one.' ;
$lang[ 'lang_info_streaming_app_android_info_desativar_campo' ] = 'To disable any option, leave the corresponding field blank.';
$lang[ 'lang_info_streaming_app_android_exibir_capa_artista' ] = 'Show Cover' ;
$lang[ 'lang_info_streaming_app_android_certificado' ] = 'Signing Certificate' ;
$lang[ 'lang_info_streaming_app_android_certificado_opcao1' ] = 'Create a new certificate(only if is your first app)' ;
$lang[ 'lang_info_streaming_app_android_certificado_opcao2' ] = 'User current own certificate' ;
$lang[ 'lang_info_streaming_app_android_saudacao' ] = 'Salutation Mensage' ;
$lang[ 'lang_info_streaming_app_android_historia' ] = 'History' ;
$lang[ 'lang_info_streaming_app_android_programacao' ] = 'Schedule' ;
$lang[ 'lang_info_streaming_app_android_pedido' ] = 'Request Song' ;
$lang[ 'lang_info_streaming_app_android_status_modal' ] = 'Building app, this can take some minutes, please wait!' ;

} else {

$lang[ 'lang_info_streaming_app_android_tab_app_pronto' ] = 'App Listo' ;
$lang[ 'lang_info_streaming_app_android_tab_criar_app' ] = 'Crear App' ;
$lang[ 'lang_info_streaming_app_android_tab_configurar_app' ] = 'Configurar App' ;
$lang[ 'lang_info_streaming_app_android_info_configuracoes' ] = 'Las otras configuraciones de la aplicaci&oacute;n, como sitio web, redes sociales y otras, se configurar&aacute;n aquí despu&eacute;s de crear la aplicaci&oacute;n.' ;
$lang[ 'lang_info_streaming_app_android_info_configuracoes2' ] = 'Al cambiar la configuraci&oacute;n a continuaci&oacute;n, los datos se actualizar&aacute;n automáticamente en la aplicaci&oacute;n sin tener que crear uno nuevo.' ;
$lang[ 'lang_info_streaming_app_android_info_desativar_campo' ] = 'Para deshabilitar alguna opci&oacute;n, deje en blanco el campo correspondiente.';
$lang[ 'lang_info_streaming_app_android_exibir_capa_artista' ] = 'Mostrar Caratula' ;
$lang[ 'lang_info_streaming_app_android_certificado' ] = 'Certificado Assinatura' ;
$lang[ 'lang_info_streaming_app_android_certificado_opcao1' ] = 'Crear Certificado Pr&oacute;pio(solo si es tu primer App)' ;
$lang[ 'lang_info_streaming_app_android_certificado_opcao2' ] = 'Usar Certificado Pr&oacute;pio' ;
$lang[ 'lang_info_streaming_app_android_saudacao' ] = 'Mensaje de Saludo' ;
$lang[ 'lang_info_streaming_app_android_historia' ] = 'Historia' ;
$lang[ 'lang_info_streaming_app_android_programacao' ] = 'Programación' ;
$lang[ 'lang_info_streaming_app_android_pedido' ] = 'Pedir Canción' ;
$lang[ 'lang_info_streaming_app_android_status_modal' ] = 'Creando app, esto puede llevar algun tiempo, por favor espere!' ;

}

$url_player = (!empty($dados_revenda["dominio_padrao"])) ? "player.".$dados_revenda["dominio_padrao"]."" : "player.".$dados_config["dominio_padrao"]."";

$dados_app_criado = mysqli_fetch_array(mysqli_query($conexao,"SELECT * FROM apps where codigo_stm = '".$dados_stm["codigo"]."'"));

$dados_servidor_camera_studio = mysqli_fetch_array(mysqli_query($conexao,"SELECT * FROM servidores where codigo = '".$dados_stm["codigo_servidor_camera_studio_atual"]."' OR codigo = '".$dados_stm["codigo_servidor_camera_studio"]."'"));

if($dados_servidor_camera_studio["nome_principal"]) {
$servidor_camera_studio = code_decode($dados_servidor_camera_studio["nome_principal"].".".$dados_config["dominio_padrao"],"E");
} else {
$servidor_camera_studio = code_decode($dados_servidor_camera_studio["nome"].".".$dados_config["dominio_padrao"],"E");
}

if($_POST["acao_form"] == "criar") {

// Valida extensão
if($_FILES["logo"]["type"] != "image/png") {
die ("<script> alert(\"Logo deve ser PNG\\n\\nLogo must be PNG\");
       window.location = 'javascript:history.back(-1)'; </script>");
}

if($_FILES["icone"]["type"] != "image/png") {
die ("<script> alert(\"Icone deve ser PNG\\n\\nIcon must be PNG\");
       window.location = 'javascript:history.back(-1)'; </script>");
}

if($_FILES["fundo"]["type"] != "image/jpeg") {
die ("<script> alert(\"Fundo deve ser JPG\\n\\nBackground must be JPG\");
       window.location = 'javascript:history.back(-1)'; </script>");
}

if(strlen($_POST["radio_nome"]) > 30) {
die ("<script> alert(\"Nome da radio deve ter maximo 30 caracteres.\\n\\nRadio name max 30 character.\");
       window.location = 'javascript:history.back(-1)'; </script>");
}

if(empty($_POST["radio_nome"])) {
die ("<script> alert(\"Nome da radio esta vazio.\\n\\nRadio name is empty.\");
       window.location = 'javascript:history.back(-1)'; </script>");
}

// Verifica se o primeiro caracter é numérico
if(preg_match('/^\d/',$_POST["radio_nome"])) {
die ("<script> alert(\"Nome da radio não pode iniciar com numeros.\\n\\nRadio name cant stat with number.\");
       window.location = 'javascript:history.back(-1)'; </script>");
}

$radio_nome = $_POST["radio_nome"];
$app_exibir_capa = ($_POST["app_exibir_capa"]) ? "true" : "false";
$app_auto_play = ($_POST["app_auto_play"]) ? "true" : "false";

if($dados_stm["tipo_servidor"] == "icecast") {
$url_streaming = "https://".strtolower($dados_servidor["nome"]).".".$dados_config["dominio_padrao"].":".$dados_stm["porta"]."/stream";
} else {
$url_streaming = "http://".strtolower($dados_servidor["nome"]).".".$dados_config["dominio_padrao"].":".$dados_stm["porta"]."/stream";
}

$source = "source-2.0";

if($_POST["pkg_personalizado"]) {
$package_uniq = str_replace("com.","",$_POST["pkg_personalizado"]);
} else if($_POST["pkg_personalizado_historico"]) {
$package_uniq = str_replace("com.","",$_POST["pkg_personalizado_historico"]);
} else {
$package_uniq = "app".md5(uniqid(rand(), true));
}

$array_pastas_package = explode(".", $package_uniq);

$package = "com.shoutcast.stm.".$package_uniq."";
$package_path = str_replace(".","/",$package_uniq);

$hash = $package_uniq."_".md5($radio_nome);

$patch_dir_apps = $_SERVER['DOCUMENT_ROOT']."/app/apps";
$patch_app = $_SERVER['DOCUMENT_ROOT']."/app/apps/".$hash."";
$patch_tmp = $_SERVER['DOCUMENT_ROOT']."/app/apps/tmp";
$patch_player = $_SERVER['DOCUMENT_ROOT']."/player/app";

//Bug fix - Remove pasta do app caso exista
remover_source_app_novo($_SERVER['DOCUMENT_ROOT']."/app/apps/".$hash."/");

@unlink($_SERVER['DOCUMENT_ROOT']."/app/apps/".$hash.".zip");
@unlink($_SERVER['DOCUMENT_ROOT']."/player/app/logo-".$dados_stm["porta"].".png");
@unlink($_SERVER['DOCUMENT_ROOT']."/player/app/icone-".$dados_stm["porta"].".png");
@unlink($_SERVER['DOCUMENT_ROOT']."/player/app/background-".$dados_stm["porta"].".jpg");

@copy($_FILES["logo"]["tmp_name"],"".$patch_tmp."/logo_".$hash.".png");
@copy($_FILES["icone"]["tmp_name"],"".$patch_tmp."/icone_".$hash.".png");
@copy($_FILES["fundo"]["tmp_name"],"".$patch_tmp."/fundo_".$hash.".jpg");

// Valida a dimensão(largura x altura) das imagens
list($logo_width, $logo_height, $logo_type, $logo_attr) = getimagesize("".$patch_tmp."/logo_".$hash.".png");
list($icone_width, $icone_height, $icone_type, $icone_attr) = getimagesize("".$patch_tmp."/icone_".$hash.".png");
list($fundo_width, $fundo_height, $fundo_type, $fundo_attr) = getimagesize("".$patch_tmp."/fundo_".$hash.".jpg");

if($logo_width != 300 || $logo_height != 300) {
die ("<script> alert(\"Ooops!\\n\\nA logomarca esta com dimensão inválida!\\n\\nEnvie uma logomarca com 300 pixels de largura e 300 pixels de altura.\");
       window.location = 'javascript:history.back(-1)'; </script>");
}

if($icone_width != 144 || $icone_height != 144) {
die ("<script> alert(\"Ooops!\\n\\nO ícone esta com dimensão inválida!\\n\\nEnvie um ícone com 144 pixels de largura e 144 pixels de altura.\");
       window.location = 'javascript:history.back(-1)'; </script>");
}

if($fundo_width != 640 || $fundo_height != 1136) {
die ("<script> alert(\"Ooops!\\n\\nO fundo esta com dimensão inválida!\\n\\nEnvie um fundo com 640 pixels de largura e 1136 pixels de altura.\");
       window.location = 'javascript:history.back(-1)'; </script>");
}

copiar_source_novo($_SERVER['DOCUMENT_ROOT']."/app/".$source."/", $patch_app);

@rename("".$patch_app."/app/src/main/java/com/shoutcast/stm/radio_nome","".$patch_app."/app/src/main/java/com/shoutcast/stm/".$package_uniq."");

// Copia o ícone
// Copia o ícone
$icone = WideImage::load("".$patch_tmp."/icone_".$hash.".png");
$icone = $icone->resize(72, 72);
$icone->saveToFile("".$patch_app."/app/src/main/res/mipmap-hdpi/ic_launcher.png");
$icone->saveToFile("".$patch_app."/app/src/main/res/mipmap-hdpi/ic_launcher_foreground.png");
$icone->saveToFile("".$patch_app."/app/src/main/res/mipmap-hdpi/ic_launcher_round.png");

$icone = WideImage::load("".$patch_tmp."/icone_".$hash.".png");
$icone = $icone->resize(72, 72);
$icone->saveToFile("".$patch_app."/app/src/main/res/mipmap-mdpi/ic_launcher.png");
$icone->saveToFile("".$patch_app."/app/src/main/res/mipmap-mdpi/ic_launcher_foreground.png");
$icone->saveToFile("".$patch_app."/app/src/main/res/mipmap-mdpi/ic_launcher_round.png");

$icone = WideImage::load("".$patch_tmp."/icone_".$hash.".png");
$icone = $icone->resize(96, 96);
$icone->saveToFile("".$patch_app."/app/src/main/res/mipmap-xhdpi/ic_launcher.png");
$icone->saveToFile("".$patch_app."/app/src/main/res/mipmap-xhdpi/ic_launcher_foreground.png");
$icone->saveToFile("".$patch_app."/app/src/main/res/mipmap-xhdpi/ic_launcher_round.png");

$icone = WideImage::load("".$patch_tmp."/icone_".$hash.".png");
$icone = $icone->resize(144, 144);
$icone->saveToFile("".$patch_app."/app/src/main/res/mipmap-xxhdpi/ic_launcher.png");
$icone->saveToFile("".$patch_app."/app/src/main/res/mipmap-xxhdpi/ic_launcher_foreground.png");
$icone->saveToFile("".$patch_app."/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.png");

$icone = WideImage::load("".$patch_tmp."/icone_".$hash.".png");
$icone = $icone->resize(192, 192);
$icone->saveToFile("".$patch_app."/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png");
$icone->saveToFile("".$patch_app."/app/src/main/res/mipmap-xxxhdpi/ic_launcher_foreground.png");
$icone->saveToFile("".$patch_app."/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.png");

$icone = WideImage::load("".$patch_tmp."/icone_".$hash.".png");
$icone = $icone->resize(48, 48);
$icone->saveToFile("".$patch_player."/icone-".$dados_stm["porta"].".png");

// Copia a logo
$logo = WideImage::load("".$patch_tmp."/logo_".$hash.".png");
$logo = $logo->resize(300, 300);
$logo->saveToFile("".$patch_player."/logo-".$dados_stm["porta"].".png");

// Copia o fundo
@copy($patch_tmp."/fundo_".$hash.".jpg", "".$patch_player."/background-".$dados_stm["porta"].".jpg");
/*
// Cria o splash
$fundo = WideImage::load("".$patch_tmp."/fundo_".$hash.".jpg");
$fundo = $fundo->resize(640, 1136);
$logo_splash = WideImage::load("".$patch_tmp."/logo_".$hash.".png");
$splash = $fundo->merge($logo_splash, 'center', 'center', 100);
$splash->saveToFile("".$patch_app."/app/src/main/res/drawable-hdpi/bg_splash.jpg");
*/
// Cria icone para o Play
$play_icone = WideImage::load("".$patch_tmp."/logo_".$hash.".png");
$play_icone = $play_icone->resize(512, 512);
$play_icone->saveToFile("".$patch_app."/arquivos_google_play/img-play-logo.png");

// Cria a imagem de destaque para o Play com a logo da radio
$destaque = WideImage::load("".$patch_app."/arquivos_google_play/img-play-destaque.jpg");
$logo_destaque = WideImage::load("".$patch_tmp."/logo_".$hash.".png");
$play_destaque = $destaque->merge($logo_destaque, 'center', 'center', 100);
$play_destaque->saveToFile("".$patch_app."/arquivos_google_play/img-play-destaque.jpg");

// Cria o print do app para o Play com a logo da radio
$fundo_print_play = WideImage::load("".$patch_tmp."/fundo_".$hash.".jpg");
$fundo_print_play = $fundo_print_play->resize(640, 1136);
$logo_print_play = WideImage::load("".$patch_tmp."/logo_".$hash.".png");
$print_play = $fundo_print_play->merge($logo_print_play, 'center', 'center', 100);
$print_play->saveToFile("".$patch_app."/arquivos_google_play/img-play-app.png");

// Cria preview do app
$print_play->saveToFile("".$patch_dir_apps."/preview/preview-".$dados_stm["porta"].".png");

// Cria tamanhos diferenciados par google play
$printapp_800x1280 = WideImage::load("".$patch_app."/arquivos_google_play/img-play-app.png");
$printapp_800x1280 = $printapp_800x1280->resize(800, 1280, 'fill');
$printapp_800x1280->saveToFile("".$patch_app."/arquivos_google_play/img-play-app-800x1280.png");

// Muda o package
@shell_exec("find ".$patch_app." -type f | xargs replace 'com.shoutcast.stm.radio_nome' '".$package."' --");

// Dados/Personalizacao da Radio
replace_novo("".$patch_app."/app/src/main/res/values/strings.xml","radio_nome",utf8_encode(str_replace("&","&amp;",$radio_nome)));
replace_novo("".$patch_app."/app/src/main/java/com/shoutcast/stm/".$package_uniq."/Config.java","URL_JSON_STREAMING","https://".$_SERVER["HTTP_HOST"]."/app/json/".$dados_stm["porta"].".json");
replace_novo("".$patch_app."/app/src/main/java/com/shoutcast/stm/".$package_uniq."/Config.java","CAPA_ARTISTA",$app_exibir_capa);
replace_novo("".$patch_app."/app/src/main/java/com/shoutcast/stm/".$package_uniq."/Config.java","AUTO_PLAY",$app_auto_play);

if($_POST["versao"] == '1.0') {
$codigo_versao = 1;
} elseif($_POST["versao"] == '1.1') {
$codigo_versao = 2;
} elseif($_POST["versao"] == '1.2') {
$codigo_versao = 3;
} elseif($_POST["versao"] == '1.3') {
$codigo_versao = 4;
} elseif($_POST["versao"] == '1.4') {
$codigo_versao = 5;
} elseif($_POST["versao"] == '1.5') {
$codigo_versao = 6;
} elseif($_POST["versao"] == '1.6') {
$codigo_versao = 7;
} elseif($_POST["versao"] == '1.7') {
$codigo_versao = 8;
} elseif($_POST["versao"] == '1.8') {
$codigo_versao = 9;
} elseif($_POST["versao"] == '1.9') {
$codigo_versao = 10;
} elseif($_POST["versao"] == '1.10') {
$codigo_versao = 11;
} elseif($_POST["versao"] == '1.11') {
$codigo_versao = 12;
} elseif($_POST["versao"] == '1.12') {
$codigo_versao = 13;
} elseif($_POST["versao"] == '1.13') {
$codigo_versao = 14;
} elseif($_POST["versao"] == '1.14') {
$codigo_versao = 15;
} elseif($_POST["versao"] == '1.15') {
$codigo_versao = 16;
} elseif($_POST["versao"] == '1.16') {
$codigo_versao = 17;
} elseif($_POST["versao"] == '1.17') {
$codigo_versao = 18;
} elseif($_POST["versao"] == '1.18') {
$codigo_versao = 19;
} elseif($_POST["versao"] == '1.19') {
$codigo_versao = 20;
} elseif($_POST["versao"] == '1.20') {
$codigo_versao = 21;
} elseif($_POST["versao"] == '1.20') {
$codigo_versao = 21;
} elseif($_POST["versao"] == '1.20') {
$codigo_versao = 21;
} elseif($_POST["versao"] == '1.20') {
$codigo_versao = 21;
} elseif($_POST["versao"] == '1.20') {
$codigo_versao = 21;
} elseif($_POST["versao"] == '1.20') {
$codigo_versao = 21;
} elseif($_POST["versao"] == '1.20') {
$codigo_versao = 21;
} elseif($_POST["versao"] == '1.20') {
$codigo_versao = 21;
} elseif($_POST["versao"] == '1.20') {
$codigo_versao = 21;
} elseif($_POST["versao"] == '1.20') {
$codigo_versao = 21;
} elseif($_POST["versao"] == '1.20') {
$codigo_versao = 21;
} elseif($_POST["versao"] == '1.20') {
$codigo_versao = 21;
} elseif($_POST["versao"] == '2.0') {
$codigo_versao = 22;
} elseif($_POST["versao"] == '2.1') {
$codigo_versao = 23;
} elseif($_POST["versao"] == '2.2') {
$codigo_versao = 24;
} elseif($_POST["versao"] == '2.3') {
$codigo_versao = 25;
} elseif($_POST["versao"] == '2.4') {
$codigo_versao = 26;
} elseif($_POST["versao"] == '2.5') {
$codigo_versao = 27;
} elseif($_POST["versao"] == '2.6') {
$codigo_versao = 28;
} elseif($_POST["versao"] == '2.7') {
$codigo_versao = 29;
} elseif($_POST["versao"] == '2.8') {
$codigo_versao = 30;
} elseif($_POST["versao"] == '2.9') {
$codigo_versao = 31;
} elseif($_POST["versao"] == '3.0') {
$codigo_versao = 32;
} elseif($_POST["versao"] == '4.0') {
$codigo_versao = 33;
} elseif($_POST["versao"] == '5.0') {
$codigo_versao = 34;
} else {
$codigo_versao = 1;
}

replace_novo("".$patch_app."/app/build.gradle","codigo_versao",$codigo_versao);
replace_novo("".$patch_app."/app/build.gradle","numero_versao",$_POST["versao"]);

// Muda o idioma do app conforme o idioma do painel
if($_POST["idioma_painel"] == "pt-br") {

replace_novo("".$patch_app."/app/src/main/res/values/strings.xml","MSG_BTN_SHARE","Compartilhar");
replace_novo("".$patch_app."/app/src/main/res/values/strings.xml","MSG_SHARE","Gostaria de compartilhar meu app favorito:");
replace_novo("".$patch_app."/app/src/main/res/values/strings.xml","MSG_BTN_RATE","Avaliar App");
replace_novo("".$patch_app."/app/src/main/res/values/strings.xml","MSG_SAIR","O que deseja fazer?");
replace_novo("".$patch_app."/app/src/main/res/values/strings.xml","MSG_BTN_SAIR","Sair");
replace_novo("".$patch_app."/app/src/main/res/values/strings.xml","MSG_BTN_MINIMIZAR","Minimizar");
replace_novo("".$patch_app."/app/src/main/res/values/strings.xml","MSG_BTN_CANCELAR","Cancelar");
replace_novo("".$patch_app."/app/src/main/res/values/strings.xml","MSG_BTN_MAIS","Mais");
replace_novo("".$patch_app."/app/src/main/res/values/strings.xml","MSG_BTN_SOBRE","Sobre");
replace_novo("".$patch_app."/app/src/main/res/values/strings.xml","MSG_BTN_POLITICA",utf8_encode("Politica de Privacidade"));
replace_novo("".$patch_app."/app/src/main/res/values/strings.xml","MSG_BTN_OUTROS","Outros");
replace_novo("".$patch_app."/app/src/main/res/values/strings.xml","MSG_VERSAO",utf8_encode("Versão"));
replace_novo("".$patch_app."/app/src/main/res/values/strings.xml","MSG_SL_TIME_MINUTE","Minutos");
replace_novo("".$patch_app."/app/src/main/res/values/strings.xml","MSG_SL_TIME_SET","Definir");
replace_novo("".$patch_app."/app/src/main/res/values/strings.xml","MSG_SL_TIME_CANCEL","Cancelar");
replace_novo("".$patch_app."/app/src/main/res/values/strings.xml","MSG_SL_TIME_STOP","Parar");
replace_novo("".$patch_app."/app/src/main/res/values/strings.xml","MSG_SL_TIME",utf8_encode("Função Dormir(Desligar APP)"));
replace_novo("".$patch_app."/app/src/main/res/values/strings.xml","MSG_BTN_PERM",utf8_encode("Permissão Adicional"));
replace_novo("".$patch_app."/app/src/main/res/values/strings.xml","MSG_PERM1","Obrigado por instalar nosso App!");
replace_novo("".$patch_app."/app/src/main/res/values/strings.xml","MSG_PERM2","Permitir agora");
replace_novo("".$patch_app."/app/src/main/res/values/strings.xml","MSG_PERM3","Mais tarde");
replace_novo("".$patch_app."/app/src/main/res/values/strings.xml","MSG_PERM4",utf8_encode("<p>Por favor, nos dê as permissões abaixo:</p>
        <p><strong>PERMISSÃO DE TELEFONE:</strong> ele será usado para parar de tocar rádio quando houver uma chamada telefônica.</p>
        <p>Não se preocupe, garantimos que seus dados são 100% seguros e não coletamos nenhum dado que você tenha, a permissão que você dá é apenas para que este aplicativo funcione corretamente.</p>"));

} elseif($_POST["idioma_painel"] == "en-us") {

replace_novo("".$patch_app."/app/src/main/res/values/strings.xml","MSG_BTN_SHARE","Share");
replace_novo("".$patch_app."/app/src/main/res/values/strings.xml","MSG_SHARE","I want to share my favorite app with you.");
replace_novo("".$patch_app."/app/src/main/res/values/strings.xml","MSG_BTN_RATE","Rate App");
replace_novo("".$patch_app."/app/src/main/res/values/strings.xml","MSG_SAIR","What do you want?");
replace_novo("".$patch_app."/app/src/main/res/values/strings.xml","MSG_BTN_SAIR","Exit");
replace_novo("".$patch_app."/app/src/main/res/values/strings.xml","MSG_BTN_MINIMIZAR","Minimize");
replace_novo("".$patch_app."/app/src/main/res/values/strings.xml","MSG_BTN_CANCELAR","Back");
replace_novo("".$patch_app."/app/src/main/res/values/strings.xml","MSG_BTN_MAIS","More");
replace_novo("".$patch_app."/app/src/main/res/values/strings.xml","MSG_BTN_SOBRE","About");
replace_novo("".$patch_app."/app/src/main/res/values/strings.xml","MSG_BTN_POLITICA","Privacy Policy");
replace_novo("".$patch_app."/app/src/main/res/values/strings.xml","MSG_BTN_OUTROS","Others");
replace_novo("".$patch_app."/app/src/main/res/values/strings.xml","MSG_VERSAO","Version");
replace_novo("".$patch_app."/app/src/main/res/values/strings.xml","MSG_SL_TIME_MINUTE","Minutes");
replace_novo("".$patch_app."/app/src/main/res/values/strings.xml","MSG_SL_TIME_SET","Set");
replace_novo("".$patch_app."/app/src/main/res/values/strings.xml","MSG_SL_TIME_CANCEL","Cancel");
replace_novo("".$patch_app."/app/src/main/res/values/strings.xml","MSG_SL_TIME_STOP","Stop");
replace_novo("".$patch_app."/app/src/main/res/values/strings.xml","MSG_SL_TIME","Sleeping Time(Close APP)");
replace_novo("".$patch_app."/app/src/main/res/values/strings.xml","MSG_BTN_PERM","Additional Permission");
replace_novo("".$patch_app."/app/src/main/res/values/strings.xml","MSG_PERM1","Thankyou for installing our App!");
replace_novo("".$patch_app."/app/src/main/res/values/strings.xml","MSG_PERM2","Allow now");
replace_novo("".$patch_app."/app/src/main/res/values/strings.xml","MSG_PERM3","Later");
replace_novo("".$patch_app."/app/src/main/res/values/strings.xml","MSG_PERM4","<p>Please give us the below permissions:</p>
        <p><strong>PHONE PERMISSION:</strong> it will used to stop playing radio when there is an incoming phone call.</p>
        <p>Do not worry, we guarantee your data is 100% safe and we do not collect any data that you have, the permission you give is only for the purpose of this app running properly.</p>");

} else {

replace_novo("".$patch_app."/app/src/main/res/values/strings.xml","MSG_BTN_SHARE","Compartir");
replace_novo("".$patch_app."/app/src/main/res/values/strings.xml","MSG_SHARE","Me gustaria compartir mi app favorito con tu.");
replace_novo("".$patch_app."/app/src/main/res/values/strings.xml","MSG_BTN_RATE","Avaliar App");
replace_novo("".$patch_app."/app/src/main/res/values/strings.xml","MSG_SAIR","Elija?");
replace_novo("".$patch_app."/app/src/main/res/values/strings.xml","MSG_BTN_SAIR","Salir");
replace_novo("".$patch_app."/app/src/main/res/values/strings.xml","MSG_BTN_MINIMIZAR","Minimizar");
replace_novo("".$patch_app."/app/src/main/res/values/strings.xml","MSG_BTN_CANCELAR","Volver");
replace_novo("".$patch_app."/app/src/main/res/values/strings.xml","MSG_BTN_MAIS","Mas");
replace_novo("".$patch_app."/app/src/main/res/values/strings.xml","MSG_BTN_SOBRE","Sobre");
replace_novo("".$patch_app."/app/src/main/res/values/strings.xml","MSG_BTN_POLITICA",utf8_encode("Politica de Privacidade"));
replace_novo("".$patch_app."/app/src/main/res/values/strings.xml","MSG_BTN_OUTROS","Otros");
replace_novo("".$patch_app."/app/src/main/res/values/strings.xml","MSG_VERSAO",utf8_encode("Versión"));
replace_novo("".$patch_app."/app/src/main/res/values/strings.xml","MSG_SL_TIME_MINUTE","Minutos");
replace_novo("".$patch_app."/app/src/main/res/values/strings.xml","MSG_SL_TIME_SET","Definir");
replace_novo("".$patch_app."/app/src/main/res/values/strings.xml","MSG_SL_TIME_CANCEL","Cancelar");
replace_novo("".$patch_app."/app/src/main/res/values/strings.xml","MSG_SL_TIME_STOP","Parar");
replace_novo("".$patch_app."/app/src/main/res/values/strings.xml","MSG_SL_TIME",utf8_encode("Función de Sueño(Apagar APP)"));
replace_novo("".$patch_app."/app/src/main/res/values/strings.xml","MSG_BTN_PERM","Permiso Adicional");
replace_novo("".$patch_app."/app/src/main/res/values/strings.xml","MSG_PERM1","Gracias por instalar nuestra App!");
replace_novo("".$patch_app."/app/src/main/res/values/strings.xml","MSG_PERM2","Permitir ahora");
replace_novo("".$patch_app."/app/src/main/res/values/strings.xml","MSG_PERM3","Mas tarde");
replace_novo("".$patch_app."/app/src/main/res/values/strings.xml","MSG_PERM4",utf8_encode("<p>Por favor danos los permisos a continuación:</p>
        <p><strong>PERMISO TELEFÓNICO:</strong> se usará para dejar de reproducir la radio cuando haya una llamada telefónica.</p>
        <p>No se preocupe, le garantizamos que sus datos están 100% seguros y no recopilamos ningún dato que tenga, el permiso que otorga es solo para que esta aplicación funcione correctamente.</p>"));

}

// Remove o source do app
@unlink("".$patch_tmp."/logo_".$hash.".png");
@unlink("".$patch_tmp."/icone_".$hash.".png");
@unlink("".$patch_tmp."/fundo_".$hash.".jpg");

// Compila o app
$nome_apk = nome_app_apk_novo($_POST["radio_nome"]);

//Bug fix
remover_source_app_novo($_SERVER['DOCUMENT_ROOT']."/app/apps/".$hash."/app/src/main/java/com/shoutcast/stm/radio_nome");

// Compila o App
shell_exec("export JAVA_HOME=/usr;export PATH=\$JAVA_HOME/bin:\$PATH;cd ".$_SERVER['DOCUMENT_ROOT']."/app/apps/".$hash.";./gradlew bundleRelease;./gradlew assembleRelease");

// Assina o app com certificado
if($_POST["certificado"] == "padrao") {

shell_exec("export JAVA_HOME=/usr;export PATH=\$JAVA_HOME/bin:\$PATH;/opt/android-sdk-linux/build-tools/28.0.3/apksigner sign --ks-pass pass:EE4F5AD2D81078B62EBA6EA5E8 --ks /home/painel/public_html/app/apps/".$hash."/certificado.jks --out /home/painel/public_html/app/apps/".$hash."/arquivos_google_play/App-".$nome_apk.".apk /home/painel/public_html/app/apps/".$hash."/app/build/outputs/apk/release/app-release-unsigned.apk;jarsigner -verbose -sigalg SHA256withRSA -digestalg SHA-256 -keystore /home/painel/public_html/app/apps/".$hash."/certificado.jks -storepass EE4F5AD2D81078B62EBA6EA5E8 -keypass EE4F5AD2D81078B62EBA6EA5E8 /home/painel/public_html/app/apps/".$hash."/app/build/outputs/bundle/release/app-release.aab chave;cp -f /home/painel/public_html/app/apps/".$hash."/app/build/outputs/bundle/release/app-release.aab /home/painel/public_html/app/apps/".$hash."/arquivos_google_play/App-".$nome_apk.".aab");

// Cria TXT com dados do certificado
$txt_certificado = "Certificado: certificado.jks\nKey: EE4F5AD2D81078B62EBA6EA5E8\nAlias: chave";
@file_put_contents($_SERVER['DOCUMENT_ROOT']."/app/apps/".$hash."/arquivos_google_play/Certificado.txt", $txt_certificado);
@copy($_SERVER['DOCUMENT_ROOT']."/app/apps/".$hash."/certificado.jks",$_SERVER['DOCUMENT_ROOT']."/app/apps/".$hash."/arquivos_google_play/certificado.jks");
}

if($_POST["certificado"] == "novo") {

//Cria o certificado
$nome_certificado = md5($nome_apk);

shell_exec("export JAVA_HOME=/usr;export PATH=\$JAVA_HOME/bin:\$PATH;keytool -genkey -alias streaming -keyalg RSA -keystore /home/painel/public_html/app/keys/".$nome_certificado.".jks -dname 'CN=Streaming, OU=Streaming, O=Streaming, L=Streaming, S=Brasil, C=BR' -storepass ".$nome_certificado." -keypass ".$nome_certificado." -validity 365000");

// Assina o app com certificado
shell_exec("export JAVA_HOME=/usr;export PATH=\$JAVA_HOME/bin:\$PATH;/opt/android-sdk-linux/build-tools/28.0.3/apksigner sign --ks-pass pass:".$nome_certificado." --ks /home/painel/public_html/app/keys/".$nome_certificado.".jks --out /home/painel/public_html/app/apps/".$hash."/arquivos_google_play/App-".$nome_apk.".apk /home/painel/public_html/app/apps/".$hash."/app/build/outputs/apk/release/app-release-unsigned.apk;jarsigner -verbose -sigalg SHA256withRSA -digestalg SHA-256 -keystore /home/painel/public_html/app/keys/".$nome_certificado.".jks -storepass ".$nome_certificado." -keypass ".$nome_certificado." /home/painel/public_html/app/apps/".$hash."/app/build/outputs/bundle/release/app-release.aab streaming;cp -f /home/painel/public_html/app/apps/".$hash."/app/build/outputs/bundle/release/app-release.aab /home/painel/public_html/app/apps/".$hash."/arquivos_google_play/App-".$nome_apk.".aab");


// Cria TXT com dados do certificado
$txt_certificado = "Certificado: certificado.jks\nKey: ".$nome_certificado."\nAlias: streaming";
@file_put_contents($_SERVER['DOCUMENT_ROOT']."/app/apps/".$hash."/arquivos_google_play/Certificado.txt", $txt_certificado);
@copy($_SERVER['DOCUMENT_ROOT']."/app/keys/".$nome_certificado.".jks",$_SERVER['DOCUMENT_ROOT']."/app/apps/".$hash."/arquivos_google_play/certificado.jks");

mysqli_query($conexao,"Update streamings set app_certificado = '".$nome_certificado."' where porta = '".$_POST["porta"]."'");

}

if($_POST["certificado"] == "personalizado") {

shell_exec("export JAVA_HOME=/usr;export PATH=\$JAVA_HOME/bin:\$PATH;/opt/android-sdk-linux/build-tools/28.0.3/apksigner sign --ks-pass pass:".$dados_stm["app_certificado"]." --ks /home/painel/public_html/app/keys/".$dados_stm["app_certificado"].".jks --out /home/painel/public_html/app/apps/".$hash."/arquivos_google_play/App-".$nome_apk.".apk /home/painel/public_html/app/apps/".$hash."/app/build/outputs/apk/release/app-release-unsigned.apk;jarsigner -verbose -sigalg SHA256withRSA -digestalg SHA-256 -keystore /home/painel/public_html/app/keys/".$dados_stm["app_certificado"].".jks -storepass ".$dados_stm["app_certificado"]." -keypass ".$dados_stm["app_certificado"]." /home/painel/public_html/app/apps/".$hash."/app/build/outputs/bundle/release/app-release.aab streaming;cp -f /home/painel/public_html/app/apps/".$hash."/app/build/outputs/bundle/release/app-release.aab /home/painel/public_html/app/apps/".$hash."/arquivos_google_play/App-".$nome_apk.".aab");

// Cria TXT com dados do certificado
$txt_certificado = "Certificado: certificado.jks\nKey: ".$dados_stm["app_certificado"]."\nAlias: streaming";
@file_put_contents($_SERVER['DOCUMENT_ROOT']."/app/apps/".$hash."/arquivos_google_play/Certificado.txt", $txt_certificado);
@copy($_SERVER['DOCUMENT_ROOT']."/app/keys/".$dados_stm["app_certificado"].".jks",$_SERVER['DOCUMENT_ROOT']."/app/apps/".$hash."/arquivos_google_play/certificado.jks");

}

if(file_exists($_SERVER['DOCUMENT_ROOT']."/app/apps/".$hash."/arquivos_google_play/App-".$nome_apk.".apk") && file_exists($_SERVER['DOCUMENT_ROOT']."/app/apps/".$hash."/arquivos_google_play/App-".$nome_apk.".aab")) {

// Cria o zip com o conteudo para publicação no google play
$zip = new ZipArchive();
if ($zip->open($_SERVER['DOCUMENT_ROOT']."/app/apps/".$hash.".zip", ZIPARCHIVE::CREATE)!==TRUE) {
    die("Não foi possível criar o arquivo ZIP: ".$hash.".zip");
}

$zip->addEmptyDir("".$nome_apk."");
$zip->addFile($_SERVER['DOCUMENT_ROOT']."/app/apps/".$hash."/arquivos_google_play/App-".$nome_apk.".apk","".$nome_apk."/App-".$nome_apk.".apk");
$zip->addFile($_SERVER['DOCUMENT_ROOT']."/app/apps/".$hash."/arquivos_google_play/App-".$nome_apk.".aab","".$nome_apk."/App-".$nome_apk.".aab");
$zip->addFile($_SERVER['DOCUMENT_ROOT']."/app/apps/".$hash."/arquivos_google_play/Certificado.txt","".$nome_apk."/Certificado.txt");
$zip->addFile($_SERVER['DOCUMENT_ROOT']."/app/apps/".$hash."/arquivos_google_play/certificado.jks","".$nome_apk."/certificado.jks");
$zip->addFile($_SERVER['DOCUMENT_ROOT']."/app/apps/".$hash."/arquivos_google_play/img-play-logo.png","".$nome_apk."/img-play-logo.png");
$zip->addFile($_SERVER['DOCUMENT_ROOT']."/app/apps/".$hash."/arquivos_google_play/img-play-destaque.jpg","".$nome_apk."/img-play-destaque.jpg");
$zip->addFile($_SERVER['DOCUMENT_ROOT']."/app/apps/".$hash."/arquivos_google_play/img-play-app.png","".$nome_apk."/img-play-app.png");
$zip->addFile($_SERVER['DOCUMENT_ROOT']."/app/apps/".$hash."/arquivos_google_play/img-play-app-800x1280.png","".$nome_apk."/img-play-app-800x1280.png");
$status=$zip->getStatusString();
$zip->close();

if(!file_exists($_SERVER['DOCUMENT_ROOT']."/app/apps/".$hash.".zip")) {
shell_exec("cd ".$_SERVER['DOCUMENT_ROOT']."/app/apps/;/usr/bin/zip -1 ".$hash.".zip ".$hash.";/usr/bin/zip -1 ".$hash.".zip ".$hash."/arquivos_google_play/*");
}

// Remove source
if($hash != "") {
remover_source_app_novo($_SERVER['DOCUMENT_ROOT']."/app/apps/".$hash."");
}

// Insere os dados no banco de dados
mysqli_query($conexao,"INSERT INTO apps (codigo_stm,radio_nome,package,data,hash,zip,compilado,status) VALUES ('".$dados_stm["codigo"]."','".$_POST["radio_nome"]."','".$package."',NOW(),'".$hash."','".$hash.".zip','sim','1')");

// Atualiza configuracoes do app com logo e fundo
mysqli_query($conexao,"Update streamings set app_nome = '".$_POST["radio_nome"]."', app_package = '".$package."' where codigo = '".$dados_stm["codigo"]."'");

// Atualiza o package unico do streaming
$verifica_package_bd = mysqli_num_rows(mysqli_query($conexao,"SELECT * FROM app_packages WHERE codigo_stm = '".$dados_stm["codigo"]."' AND package = '".$package."'"));
    
if($verifica_package_bd == 0) {
mysqli_query($conexao,"INSERT INTO app_packages (codigo_stm,package) VALUES ('".$dados_stm["codigo"]."','".$package."')");
}

// Cria arquivo json com as configs do streaming
$config_json = '{
  "radio": [
    {
      "radio_name": "'.$_POST["radio_nome"].'",
      "radio_genre": "'.$dados_stm["app_msg_saudacao"].'",
      "radio_url": "'.$url_streaming.'",
      "radio_image_url": "https://'.$_SERVER["HTTP_HOST"].'/player/app/logo-'.$dados_stm["porta"].'.png?'.time().'",
      "background_image_url": "https://'.$_SERVER["HTTP_HOST"].'/player/app/background-'.$dados_stm["porta"].'.jpg?'.time().'"
    }
  ],
  "settings": [
    {
      "onesignal_app_id": "000000000-0000-0000-0000-000000000000",
      "fcm_notification_topic": "your_single_radio_topic",
      "privacy_policy_url": "https://'.$_SERVER["HTTP_HOST"].'/app/politica-'.$dados_stm["idioma_painel"].'.html",
           "more_apps_url": ""
    }
  ],
  "ads": [
    {
      "ad_status": "off"
    }
  ],
  "socials": []
}';

@unlink($_SERVER['DOCUMENT_ROOT']."/app/json/".$dados_stm["porta"].".json");
@file_put_contents($_SERVER['DOCUMENT_ROOT']."/app/json/".$dados_stm["porta"].".json", utf8_encode($config_json));

} else {
// Cria o sessão do status das ações executadas e redireciona.
$_SESSION["status_acao"] = '<div class="alert alert-danger text-center" role="alert">'.$lang['lang_info_streaming_app_android_requisicao_em_andamento'].'</div>';
}

header("Location: /app-android");
exit();

}

if($_POST["acao_form"] == "configurar") {

if($dados_stm["tipo_servidor"] == "icecast") {
$url_streaming = "https://".strtolower($dados_servidor["nome"]).".".$dados_config["dominio_padrao"].":".$dados_stm["porta"]."/stream";
} else {
$url_streaming = "http://".strtolower($dados_servidor["nome"]).".".$dados_config["dominio_padrao"].":".$dados_stm["porta"]."/stream";
}

if($_FILES["logo"]["tmp_name"]) {
@copy($_FILES["logo"]["tmp_name"],$_SERVER['DOCUMENT_ROOT']."/player/app/logo-".$dados_stm["porta"].".png");
}
if($_FILES["fundo"]["tmp_name"]) {
@copy($_FILES["fundo"]["tmp_name"],$_SERVER['DOCUMENT_ROOT']."/player/app/background-".$dados_stm["porta"].".jpg");
}

// Cria o print do app para o Play com a logo da radio
if($_FILES["logo"]["tmp_name"] || $_FILES["fundo"]["tmp_name"]) {

$fundo_print_play = WideImage::load($_SERVER['DOCUMENT_ROOT']."/player/app/background-".$dados_stm["porta"].".jpg");
$fundo_print_play = $fundo_print_play->resize(640, 1136);
$logo_print_play = WideImage::load($_SERVER['DOCUMENT_ROOT']."/player/app/logo-".$dados_stm["porta"].".png");
$print_play = $fundo_print_play->merge($logo_print_play, 'center', 'center', 100);
$print_play->saveToFile($_SERVER['DOCUMENT_ROOT']."/app/apps/preview/preview-".$dados_stm["porta"].".png");

}

$ativar_chat = ($_POST["app_url_chat"]) ? "sim" : "nao";
$app_url_camera_studio = ($_POST["ativar_camera_studio"]) ? $_POST["app_url_camera_studio"] : "";
$ativar_pedido_musica = ($_POST["ativar_pedido_musica"]) ? "sim" : "nao";
$app_msg_saudacao = ($_POST["app_msg_saudacao"]) ? $_POST["app_msg_saudacao"] : $dados_stm["app_msg_saudacao"];

$app_whatsapp = str_replace("+", "", $_POST["app_whatsapp"]);
$app_whatsapp = str_replace(" ", "", $_POST["app_whatsapp"]);
$app_whatsapp = str_replace("(", "", $_POST["app_whatsapp"]);
$app_whatsapp = str_replace(")", "", $_POST["app_whatsapp"]);

// Atualiza configuracoes do app com logo e fundo
mysqli_query($conexao,"Update streamings set app_nome = '".$_POST["app_nome"]."', app_msg_saudacao = '".$app_msg_saudacao."', app_email = '".$_POST["app_email"]."', app_whatsapp = '".$app_whatsapp."', app_url_facebook = '".$_POST["app_url_facebook"]."', app_url_instagram = '".$_POST["app_url_instagram"]."', app_url_twitter = '".$_POST["app_url_twitter"]."', app_url_site = '".$_POST["app_url_site"]."', app_url_youtube = '".$_POST["app_url_youtube"]."', app_text_prog = '".$_POST["app_text_prog"]."', app_text_hist = '".$_POST["app_text_hist"]."', app_url_chat = '".$ativar_chat."', app_url_camera_studio = '".$app_url_camera_studio."', app_url_pedir_musica = '".$ativar_pedido_musica."' where codigo = '".$dados_stm["codigo"]."'");

$dados_stm = mysqli_fetch_array(mysqli_query($conexao,"SELECT * FROM streamings where porta = '".$_SESSION["porta_logada"]."'"));

// Atualiza arquivo json com as configs do streaming
$config_json = '{
  "radio": [
    {
      "radio_name": "'.$dados_stm["app_nome"].'",
      "radio_genre": "'.$dados_stm["app_msg_saudacao"].'",
      "radio_url": "'.$url_streaming.'",
      "radio_image_url": "https://'.$_SERVER["HTTP_HOST"].'/player/app/logo-'.$dados_stm["porta"].'.png?'.time().'",
      "background_image_url": "https://'.$_SERVER["HTTP_HOST"].'/player/app/background-'.$dados_stm["porta"].'.jpg?'.time().'"
    }
  ],
  "settings": [
    {
      "onesignal_app_id": "000000000-0000-0000-0000-000000000000",
      "fcm_notification_topic": "your_single_radio_topic",
      "privacy_policy_url": "https://'.$_SERVER["HTTP_HOST"].'/app/politica-'.$dados_stm["idioma_painel"].'.html",
           "more_apps_url": ""
    }
  ],
  "ads": [
    {
      "ad_status": "off"
    }
  ],
  ';

$config_json .= '"socials": [';

if($_POST["app_url_site"]) {

$config_json .= '{
      "social_name": "Site",
      "social_icon": "https://'.$_SERVER["HTTP_HOST"].'/app/img/icone-site.png",
      "social_url": "'.$_POST["app_url_site"].'",
      "social_ext": "true"
    },';

}

if($_POST["app_url_instagram"]) {

$config_json .= '{
      "social_name": "Instagram",
      "social_icon": "https://'.$_SERVER["HTTP_HOST"].'/app/img/icone-instagram.png",
      "social_url": "'.$_POST["app_url_instagram"].'",
      "social_ext": "true"
    },';

}

if($_POST["app_url_facebook"]) {

$config_json .= '{
      "social_name": "Facebook",
      "social_icon": "https://'.$_SERVER["HTTP_HOST"].'/app/img/icone-facebook.png",
      "social_url": "'.$_POST["app_url_facebook"].'",
      "social_ext": "true"
    },';

}

if($_POST["app_url_twitter"]) {

$config_json .= '{
      "social_name": "Twitter",
      "social_icon": "https://'.$_SERVER["HTTP_HOST"].'/app/img/icone-twitter.png",
      "social_url": "'.$_POST["app_url_twitter"].'",
      "social_ext": "true"
    },';

}

if($_POST["app_url_youtube"]) {

$config_json .= '{
      "social_name": "Youtube",
      "social_icon": "https://'.$_SERVER["HTTP_HOST"].'/app/img/icone-youtube.png",
      "social_url": "'.$_POST["app_url_youtube"].'",
      "social_ext": "true"
    },';

}

if($_POST["app_whatsapp"]) {

$config_json .= '{
      "social_name": "Whatsapp",
      "social_icon": "https://'.$_SERVER["HTTP_HOST"].'/app/img/icone-whatsapp.png",
      "social_url": "https://api.whatsapp.com/send/?phone='.$app_whatsapp.'&text&type=phone_number&app_absent=0",
      "social_ext": "true"
    },';

}

if($_POST["app_text_prog"]) {

$config_json .= '{
      "social_name": "'.$lang[ 'lang_info_streaming_app_android_programacao' ].'",
      "social_icon": "https://'.$_SERVER["HTTP_HOST"].'/app/img/icone-programacao.png",
      "social_url": "https://'.$_SERVER["HTTP_HOST"].'/app/texto.php?porta='.$dados_stm["porta"].'&tipo=programacao",
      "social_ext": "false"
    },';

}

if($_POST["app_text_hist"]) {

$config_json .= '{
      "social_name": "'.$lang[ 'lang_info_streaming_app_android_historia' ].'",
      "social_icon": "https://'.$_SERVER["HTTP_HOST"].'/app/img/icone-historia.png",
      "social_url": "https://'.$_SERVER["HTTP_HOST"].'/app/texto.php?porta='.$dados_stm["porta"].'&tipo=historia",
      "social_ext": "false"
    },';

}

if($ativar_chat == "sim") {

$config_json .= '{
      "social_name": "Chat",
      "social_icon": "https://'.$_SERVER["HTTP_HOST"].'/app/img/icone-chat.png",
      "social_url": "https://'.$url_player.'/chat/'.$dados_stm["porta"].'",
      "social_ext": "false"
    },';

}

if($_POST["app_url_camera_studio"]) {

$config_json .= '{
      "social_name": "Camera Studio",
      "social_icon": "https://'.$_SERVER["HTTP_HOST"].'/app/img/icone-camera-studio.png",
      "social_url": "'.$_POST["app_url_camera_studio"].'",
      "social_ext": "false"
    },';

}

if($ativar_pedido_musica == "sim") {

$config_json .= '{
      "social_name": "'.$lang[ 'lang_info_streaming_app_android_pedido' ].'",
      "social_icon": "https://'.$_SERVER["HTTP_HOST"].'/app/img/icone-pedidos.png",
      "social_url": "https://'.$url_player.'/pedido/'.$dados_stm["porta"].'",
      "social_ext": "false"
    },';

}

$config_json .= ']}';

@unlink($_SERVER['DOCUMENT_ROOT']."/app/json/".$dados_stm["porta"].".json");
@file_put_contents($_SERVER['DOCUMENT_ROOT']."/app/json/".$dados_stm["porta"].".json", utf8_encode(str_replace("},]}", "}]}", $config_json)));

$_SESSION["status_acao"] = '<div class="alert alert-success text-center" role="alert">'.$lang['lang_info_config_painel_resultado_ok'].'</div>';

header("Location: /app-android");
exit();
}

$package_atual = str_replace("com.shoutcast.stm.","",$dados_stm["app_package"]);
?>
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
  <title>Streaming <?php echo $dados_stm["porta"]; ?></title>
  <link rel="stylesheet" href="/inc/materialdesignicons.min.css">
  <link rel="stylesheet" href="/inc/font-awesome.min.css">
  <link rel="stylesheet" href="/inc/vendor.bundle.base.css">
  <link rel="stylesheet" href="/inc/vendor.bundle.addons.css">
  <link rel="stylesheet" href="/inc/theme.css">
  <link rel="shortcut icon" href="/img/favicon.ico">
  <script type="text/javascript" src="/inc/ajax-streaming.js"></script>
  <script type="text/javascript" src="/inc/javascript.js"></script>
  <style type="text/css">.form-check .form-check-label { min-height: 13px; display: block; margin-left: 25px; font-size: 12px; line-height: 1.5; }.form-check .form-check-label input[type="radio"] + .input-helper:before { position: absolute; content: ""; top: 0; left: 0; border: solid #464dee; border-width: 2px; width: 18px; height: 18px; border-radius: 50%; -webkit-transition: all; -moz-transition: all; -ms-transition: all; -o-transition: all; transition: all; transition-duration: 0s; -webkit-transition-duration: 250ms; transition-duration: 250ms; }</style>
</head>

<body>
  <div class="container-scroller">
      <nav class="navbar col-lg-12 col-12 p-0 fixed-top d-flex flex-row">
      <div class="text-center navbar-brand-wrapper d-flex align-items-center justify-content-center">
        <?php if($dados_revenda["url_logo"]) { ?>
        <a class="navbar-brand brand-logo" href="/dashboard"><img id="logo" src="<?php echo $dados_revenda["url_logo"]; ?>" title="Painel" height="60" border="0"></a>
        <?php } else { ?>
        <a class="navbar-brand brand-logo" href="/dashboard"><span>Painel Streaming</span></a>
        <?php } ?>
        <a class="navbar-brand brand-logo-mini" href="/dashboard"><img src="/img/icones/img-icone-logo.png" title="Painel" width="32" height="32" border="0"></a>
      </div>
      <div class="navbar-menu-wrapper d-flex align-items-center justify-content-end justify-content-lg-start">
        <button class="navbar-toggler navbar-toggler align-self-center" type="button" data-toggle="minimize">
          <span class="mdi mdi-menu text-icones"></span>
        </button>
        <ul class="navbar-nav navbar-nav-right">
          <li class="nav-item nav-profile dropdown show">
            <a class="nav-link dropdown-toggle" href="#" data-toggle="dropdown" id="profileDropdown" aria-expanded="true">
              <i class="fa fa-power-off f-18 text-icones" data-toggle="tooltip" data-placement="bottom" title="<?php echo $lang['lang_botao_titulo_ligar']; ?>/<?php echo $lang['lang_botao_titulo_desligar']; ?>"></i>
            </a>
            <div class="dropdown-menu dropdown-menu-right navbar-dropdown" aria-labelledby="profileDropdown">
              <a class="dropdown-item text-success" href="javascript:ligar_streaming('<?php echo $porta_code; ?>');"> <?php echo $lang['lang_botao_titulo_ligar']; ?> Streaming</a>
              <a class="dropdown-item text-danger" href="javascript:desligar_streaming('<?php echo $porta_code; ?>');"> <?php echo $lang['lang_botao_titulo_desligar']; ?> Streaming</a>
              <?php if($dados_stm["autodj"] == "sim") { ?>
              <div class="dropdown-divider"></div>              
              <a class="dropdown-item text-success" href="javascript:carregar_opcoes_ligar_autodj('<?php echo $porta_code; ?>');"> <?php echo $lang['lang_botao_titulo_ligar']; ?> AutoDJ</a>
              <a class="dropdown-item text-danger" href="javascript:desligar_autodj('<?php echo $porta_code; ?>');"> <?php echo $lang['lang_botao_titulo_desligar']; ?> AutoDJ</a>
              <?php } ?>
            </div>
          </li>
          <li class="nav-item dropdown">
            <a class="nav-link count-indicator dropdown-toggle d-flex align-items-center justify-content-center" id="notificationDropdown" href="#" data-toggle="dropdown" aria-expanded="false">
              <i class="mdi mdi-bell f-22 text-icones" data-toggle="tooltip" data-placement="bottom" title="<?php echo $lang['lang_info_pagina_informacoes_tab_avisos']; ?>"></i>
              <?php if($total_avisos_exibir > 0) { ?><span class="count bg-success"><?php echo $total_avisos_exibir; ?></span><?php } ?>           
            </a>
            <div class="dropdown-menu dropdown-menu-right navbar-dropdown preview-list" aria-labelledby="notificationDropdown">
              <a class="dropdown-item">
                <p class="mb-0 font-weight-normal float-left"><?php echo $lang['lang_info_pagina_informacoes_tab_avisos']; ?></p>
              </a>
              <div class="dropdown-divider"></div>
              <?php carregar_avisos_streaming($conexao,$dados_stm["porta"],$dados_servidor["codigo"]); ?>
            </div>
          </li>
          <li class="nav-item">
            <a class="nav-link" href="/sair"><i class="mdi mdi-logout f-22 text-icones" data-toggle="tooltip" data-placement="bottom" title="Sair/logout"></i></a>
          </li>
          <li>
            <button type="button" class="btn btn-info" id="status-streaming" onClick="status_streaming('<?php echo $porta_code; ?>');" style="margin: 10px;min-width: 150px; min-height: 40px"><i class="fa fa-refresh"></i></button>
          </li>
        </ul>
        <button class="navbar-toggler navbar-toggler-right d-lg-none align-self-center" type="button" data-toggle="offcanvas">
          <span class="mdi mdi-menu text-icones"></span>
        </button>
      </div>
    </nav>

    <!-- modal -->
      <div class="modal fade" id="app-android-loading" tabindex="-1" role="dialog" aria-hidden="true">
        <div class="modal-dialog" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">App Android</h5>
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close"><i class="fa fa-window-close text-muted"></i></button>
                </div>
                <div class="modal-body text-center"><?php echo $lang['lang_info_streaming_app_android_status_modal']; ?><br><img src="/img/ajax-loader.gif" align="center" /></div>
            </div>
        </div>
      </div>
      <div class="modal fade" id="avisos" tabindex="-1" role="dialog" aria-hidden="true">
        <div class="modal-dialog" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title"><?php echo $lang['lang_info_pagina_informacoes_tab_avisos']; ?></h5>
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
                </div>
                <div class="modal-body" id="avisos-conteudo"><img src="/img/ajax-loader.gif" align="center" /></div>
            </div>
        </div>
      </div>
                
      <div class="modal fade" id="playlists-autodj" tabindex="-1" role="dialog" aria-hidden="true">
          <div class="modal-dialog" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">AutoDJ</h5>
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
                </div>
                <div class="modal-body text-center" id="playlists-autodj-conteudo" style="text-align: center;"><img src="/img/ajax-loader.gif" /></div>
            </div>
          </div>
      </div>
                
      <div class="modal fade" id="log-sistema" tabindex="-1" role="dialog" aria-hidden="true">
        <div class="modal-dialog modal-dialog-centered" role="document">
            <div class="modal-content">
                <div class="modal-body" id="log-sistema-conteudo" style="text-align:center"><img src="/img/ajax-loader.gif" /></div>
            </div>
        </div>
      </div>
      
    <div class="container-fluid page-body-wrapper">      
    <?php require_once("menu.php"); ?>
      <div class="main-panel">
        <div class="content-wrapper">
          <div id="local-status-acoes"><?php echo $_SESSION['status_acao'];unset($_SESSION['status_acao']); ?></div>
          <div class="row">            
            <?php if(isset($dados_app_criado["codigo"])) { ?>
            <div class="col-lg-12">
              <div class="card">
                  <div class="card-body">
                      <table width="100%" border="0" cellpadding="0" cellspacing="0">
                          <tr>
                            <td width="50%" height="500" align="center"><img src="/app/apps/preview/preview-<?php echo $dados_stm["porta"];?>.png" width="250" height="auto"></td>
                            <td width="50%" align="center" class="texto_padrao_verde"><div class="alert alert-info text-center" role="alert"><?php echo $lang['lang_info_streaming_app_android_requisicao_concluida']; ?><br /><br />
      <br />
        <a href="/app/apps/<?php echo $dados_app_criado["zip"]; ?>" target="_blank"><img src="data:image/png;base64, " alt="Download" width="96" height="96" border="0" /></a><br>
    <br>
    <a href="javascript:remover_app_android('<?php echo code_decode($dados_app_criado["codigo"],"E"); ?>');"><img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAFgklEQVR42sVXW0xdRRRdB+6j2Is8bUVQCgQ1amJJizH+WFqlxZpqY/2z0dRXQIxI2lCjaPFHsRVbJFCtNtEY+4N+tApCtNjERyJYEp+phiKxLbby7OVC79s158xczrmcy0ObuJOVmXPP3Flr79mzZ46G/9m0JY7PJtYRa4gC4ko5xyQxSPQTPcTfl1OAGLOZqHYAG0oAh2AvlmqSiBHid6KPOAmEQoaIFuIYEf0vAsiH1jzg9ofYuZ/IdQOe5YCTzMlSQJgIRoBpH3DOD3zM5/eJP4Hv2FQR3/8bATXkenUH4N5OprwMIFUQkiBEokjEcE1BzJTsYcM/zfBxeIIiGIpDQIB/eY4/NS1FQNNKCmjg+zszgRwyRMathAvBmQ5MMDxfjQH1/GkYaBZOLUbAi9cAexod0Mo4iWdsrrea6Y/qNw5BSLaxqFBAhA58y2jsDCF6DqBPOhIKKOfyduxzInkrO+4J02RxxIlMiPDLNvZfOvIFl60miLDPSOguOwEpxC/VGlbVcXN5Jq3kS7UgjFxQEQmnMZu9wIEI/uDjTfK1RcAz1wP7j5C88KI1tJaQuVyIBgK2pPHvxH99MHaJmGucc2/n3L8ZuXDALEC0p+rdKK7l6GhIqo6LwBW7dsG9bRsmN25EZGLCQp6Uno60ri7429sxvXevRcSUbDUWkg+4o172Cw24UUyvBKyhuN4TKdDyZwxSlVDKlpPc09gITdMQ7O3FuBAxPm6QZ2Qgg+TO0lJEo1FM1dXBZxIhlmNaOjPGhd40g6jXqKb9SkDtHUl4/SizVgsZxOYge0ieKsmVBShirLxc72d2d8NFcmVChJcipkwifNIpMAqPkeCbCJ7l034147vVTuxoCBoqAzL8unepqVjR3w9HUdGcNRcihJnJlYUGBnChpAQRr9eSlGL+ZifwdhDvsPu4EvDJvmRsfiRsDFADlTny87Hi+HE4CguxGAudPo0L69cjNDQ0GxWZC6L9iHmwJ6yfE1uUgM6DGjY9EDXCP20zqRCxsqcHzoKCecmDg4M4X1ZmIVc2LSPbQdbdUXzGbkVMwFvMja1ywHSCyYWIHEbCmSASQXo+HOe52Wbk/J3EblgFHOPZee+DcoAvgYBkZnsOE27Z2rW27y/19WGYiRmWu2POezm/iH09rEtw6AUmZzWMJfDakXOf5wpym4SzkDAxzwoRcXVCCRDzHybe1A9KPKEE1PCsf6MNRpJ4Ya0BwvM87vOUBchjoaaIM6wT5kiIef2yZfjRzcrLplkJWM3bzUnep7QkuVZ++SLJ40E+192OPDA4qLcum8QUIoaYjBGfsaAi9CEJVo8o47Oa3R/MpfjX94AbNkjvL0q1ovhc3dKCzMpKayFiwg0y4YQVUKDLlJiiEI21teGv6mq9D8xW1hNELQ89NjcrYmVP38aQtJvWa0a9IXEuRWRVVemPfkkekNnu4u4QItxSxGhrK86SHJI8YsKjwm2gks3BeAHLiJ+ZHIVbpPcieIGYBkNEakUFBhjaQNxWEyKKWCe8nZ06ufJcCRBPnxIvGffXW9TU8feLu3lsdx5l3l2XQERyVhZCIyO2yefIzkZ4dDRGrmH2WBdyH+ZKsBreJVcCdgKE1TOlGo7w3VWm7FVbaDEWf2U7TzzJ7hljA7wWP9bOmq7l1mR11IoxezEJwHpQxVuShNnzU8RO41L6CrvP24lNZDVMikZeXVzim8AB6y0pjLn3RfPFVQj9kKATlwJ64qMtUbTmM3FpaGM+lHL9cA+Mb7H5ruOi/nVIct6Cv4aR8T/Ot1yLWdL7iKcYhXW3MhgihblE8EhSUTP4FYSfDKYgo/M59GqrnzsLTr4U4/eK/nEqPtlWEWlSg/o45achvoTxubgoW6qAy27/ABy1Jj/tibxvAAAAAElFTkSuQmCC" alt="Remover" width="32" height="32" border="0" /></a></div><br><br><div class="alert alert-warning text-center" role="alert"><?php echo $lang['lang_info_streaming_app_android_info_configuracoes2']; ?></div></td>
  </tr>
</table>
                  </div>
              </div>
            </div>
            <?php } ?>
            <?php if($dados_app_criado["codigo"] == 0 || empty($dados_app_criado["codigo"])) { ?>  
            <div class="col-lg-12">
              <div class="card">
                  <div class="card-body">
                      <form method="post" action="/app-android" style="padding:0px; margin:0px" enctype="multipart/form-data"> 
                    <div class="alert alert-info text-center" role="alert"><?php echo $lang['lang_info_streaming_app_android_info_configuracoes']; ?></div>
                    <table width="100%" border="0" cellpadding="0" cellspacing="0">
                      <tr>
                        <td width="20%" height="60" class="texto_padrao_destaque"><strong><?php echo $lang['lang_info_streaming_app_android_radio_nome']; ?></strong></td>
                        <td width="80%" class="texto_padrao_pequeno">
                          <input name="radio_nome" type="text" id="radio_nome" class="form-control" value="" />
                          <small><?php echo $lang['lang_info_streaming_app_android_info_radio_nome']; ?></small></td>
                      </tr>
                      <tr>
                        <td height="50" class="texto_padrao_destaque"><strong><?php echo $lang['lang_info_streaming_app_android_versao']; ?></strong></td>
                        <td class="texto_padrao_pequeno">
                          <select name="versao" id="versao" class="form-control" style="width:70px">
                            <option value="1.0" selected="selected">1.0</option>
                            <option value="1.1">1.1</option>
                            <option value="1.2">1.2</option>
                            <option value="1.3">1.3</option>
                            <option value="1.4">1.4</option>
                            <option value="1.5">1.5</option>
                            <option value="1.6">1.6</option>
                            <option value="1.7">1.7</option>
                            <option value="1.8">1.8</option>
                            <option value="1.9">1.9</option>
                            <option value="1.10">1.10</option>
                            <option value="1.11">1.11</option>
                            <option value="1.12">1.12</option>
                            <option value="1.13">1.13</option>
                            <option value="1.14">1.14</option>
                            <option value="1.15">1.15</option>
                            <option value="1.16">1.16</option>
                            <option value="1.17">1.17</option>
                            <option value="1.18">1.18</option>
                            <option value="1.19">1.19</option>
                            <option value="1.20">1.20</option>
                            <option value="2.0">2.0</option>
                            <option value="2.1">2.1</option>
                            <option value="2.2">2.2</option>
                            <option value="2.3">2.3</option>
                            <option value="2.4">2.4</option>
                            <option value="2.5">2.5</option>
                            <option value="2.6">2.6</option>
                            <option value="2.7">2.7</option>
                            <option value="2.8">2.8</option>
                            <option value="2.9">2.9</option>
                            <option value="3.0">3.0</option>
                            <option value="4.0">4.0</option>
                            <option value="5.0">5.0</option>
                          </select>
                          <small><?php echo $lang['lang_info_streaming_app_android_info_versao']; ?></small></td>
                      </tr>
                      <tr>
                        <td height="30" class="texto_padrao_destaque"><strong><?php echo $lang[ 'lang_info_streaming_app_android_exibir_capa_artista' ];?></strong></td>
                        <td class="texto_padrao_pequeno"><input name="app_exibir_capa" type="checkbox" id="app_exibir_capa" value="sim" checked="checked"></div>
                        </td>
                      </tr>
                      <tr>
                        <td height="30" class="texto_padrao_destaque"><strong>Auto Play</strong></td>
                        <td class="texto_padrao_pequeno"><input name="app_auto_play" type="checkbox" id="app_auto_play" value="sim" checked="checked"></td>
                      </tr>
                      <tr>
                        <td height="50" class="texto_padrao_destaque"><strong><?php echo $lang[ 'lang_info_streaming_app_android_certificado' ];?></strong></td>
                        <td class="texto_padrao_pequeno"><?php if($dados_stm["app_certificado"] == "padrao") { ?>
                          <div class="form-check"><label class="form-check-label">
                            <input type="radio" class="form-check-input" name="certificado" id="certificado" value="padrao" checked="checked">&nbsp;Usar Padr&atilde;o<i class="input-helper"></i></label>
                          </div>
                          <div class="form-check"><label class="form-check-label">
                            <input type="radio" class="form-check-input" name="certificado" id="certificado" value="novo">&nbsp;<?php echo $lang['lang_info_streaming_app_android_certificado_opcao1'];?><i class="input-helper"></i></label>
                          </div>
                          <?php } ?><?php if($dados_stm["app_certificado"] != "padrao") { ?>
                          <div class="form-check"><label class="form-check-label">
                            <input type="radio" class="form-check-input" name="certificado" id="certificado" value="personalizado" checked="checked">&nbsp;<?php echo $lang['lang_info_streaming_app_android_certificado_opcao2'];?><i class="input-helper"></i></label>
                          </div>
                          <?php } ?></td>
                      </tr>
                      <tr id="row_package_personalizar">
                        <td height="50" class="texto_padrao_destaque"><strong>Package</strong></td>
                        <td class="texto_padrao_pequeno"><div class="input-group"><div class="input-group-prepend"><span class="input-group-text" style="font-size:12px;color:#000000">com.shoutcast.stm.</span></div><input class="form-control" name="pkg_personalizado" type="text" id="pkg_personalizado" pattern="[a-z0-9]+" onkeyup="bloquear_caracteres(this.id);" maxlength="32" value="<?php echo $package_atual; ?>" /><div class="input-group-append" onclick="gerar_pkg();" style="cursor:pointer" title="Gerar Automaticamente/Auto Generate"><span class="input-group-text"><i class="fa fa-retweet" style="color:#000000"></i></span></div><div class="input-group-prepend" id="botao_historico" style="cursor:pointer" title="Carregar Hist&oacute;rico/Load History"><span class="input-group-text"><i class="fa fa-history" style="color:#000000"></i></span></div></div></td>
                      </tr>
                      <tr id="row_package_historico" style="display:none">
                        <td height="50" class="texto_padrao_destaque"><strong>Package</strong></td>
                        <td class="texto_padrao_pequeno"><div class="input-group"><div class="input-group-prepend"><span class="input-group-text" style="font-size:12px;color:#000000">com.shoutcast.stm.</span></div>
                        <select name="pkg_personalizado_historico" id="pkg_personalizado_historico" class="form-control">
                        <option value="" selected="selected"></option>
                  <?php
                  $sql = mysqli_query($conexao,"SELECT * FROM app_packages where codigo_stm = '".$dados_stm["codigo"]."' ORDER by codigo DESC");
                  while ($dados_pkg = mysqli_fetch_array($sql)) {
                  echo '<option value="' . str_replace("com.shoutcast.stm.","",$dados_pkg["package"]) . '">' . str_replace("com.shoutcast.stm.","",$dados_pkg["package"]) . '</option>';
                  }

                  ?>
                    </select>
                        <div class="input-group-prepend" id="botao_personalizar" style="cursor:pointer" title="Digitar Manualmente/Type Manually"><span class="input-group-text"><i class="fa fa-pencil-square-o" style="color:#000000"></i></span></div></div></td>
                      </tr>
                      <tr>
                        <td width="20%" height="50" class="texto_padrao_destaque"><strong><?php echo $lang['lang_info_streaming_app_android_radio_logo']; ?></strong></td>
                        <td width="80%" class="texto_padrao_pequeno"><div class="input-group"><input name="logo" type="file" id="logo" class="form-control" /><div class="input-group-prepend"><span class="input-group-text" style="color:#000000">PNG / 300x300</span></div></div></td>
                      </tr>
                      <tr>
                        <td height="50" class="texto_padrao_destaque"><strong><?php echo $lang['lang_info_streaming_app_android_radio_icone']; ?></strong></td>
                        <td class="texto_padrao_pequeno"><div class="input-group"><input name="icone" type="file" id="icone" class="form-control" /><div class="input-group-prepend"><span class="input-group-text" style="color:#000000">PNG / 144x144</span></div></div></td>
                      </tr>
                      <tr>
                        <td height="50" class="texto_padrao_destaque"><strong><?php echo $lang['lang_info_streaming_app_android_radio_fundo']; ?></strong></td>
                        <td class="texto_padrao_pequeno"><div class="input-group"><input name="fundo" type="file" id="fundo" class="form-control" /><div class="input-group-prepend"><span class="input-group-text" style="color:#000000">JPG / 640x1136</span></div></div></td>
                      </tr>
                      <tr>
                        <td height="70" colspan="2" align="center"><button type="submit" class="btn btn-info" onclick="$('#app-android-loading').modal('show');"><?php echo $lang['lang_info_streaming_app_android_botao_submit']; ?></button><input name="acao_form" type="hidden" id="acao_form" value="criar" /><input name="idioma_painel" type="hidden" value="<?php echo $dados_stm["idioma_painel"]; ?>" /></td>
                      </tr>
                    </table>
                    </form>
                  </div>
              </div>
            </div>
            <?php } ?>
              <?php if($dados_app_criado["codigo"] > 0) { ?> 
            <div class="col-lg-12">
              <div class="card">
                  <div class="card-body">
                      <form method="post" action="/app-android" style="padding:0px; margin:0px" enctype="multipart/form-data">
                  <div class="alert alert-info text-center" role="alert"><?php echo $lang['lang_info_streaming_app_android_info_configuracoes2']; ?><br><strong><?php echo $lang['lang_info_streaming_app_android_info_desativar_campo']; ?></strong></div>
                  <table width="100%" border="0" cellpadding="0" cellspacing="0">
                  <tr>
                    <td width="20%" height="50" class="texto_padrao_destaque"><strong><?php echo $lang['lang_info_streaming_app_android_radio_nome']; ?></strong></td>
                    <td width="80%" class="texto_padrao_pequeno">
                      <input name="app_nome" type="text" id="app_nome" class="form-control"  value="<?php echo $dados_stm["app_nome"]; ?>" required="required" /></td>
                  </tr>
                  <tr>
                    <td width="20%" height="50" class="texto_padrao_destaque"><strong><?php echo $lang['lang_info_streaming_app_android_saudacao']; ?></strong></td>
                    <td width="80%" class="texto_padrao_pequeno">
                      <input name="app_msg_saudacao" type="text" id="app_msg_saudacao" class="form-control"  value="<?php echo $dados_stm["app_msg_saudacao"]; ?>" required="required" /></td>
                  </tr>
                  <tr>
                    <td width="20%" height="50" class="texto_padrao_destaque"><strong>E-mail</strong></td>
                    <td width="80%" class="texto_padrao_pequeno">
                      <input name="app_email" type="text" id="app_email" class="form-control"  value="<?php echo $dados_stm["app_email"]; ?>" /></td>
                  </tr>
                  <tr>
                    <td width="20%" height="50" class="texto_padrao_destaque"><strong>Site</strong></td>
                    <td width="80%" class="texto_padrao_pequeno">
                      <input name="app_url_site" type="text" id="app_url_site" class="form-control" value="<?php echo $dados_stm["app_url_site"]; ?>" /></td>
                  </tr>
                  <tr>
                    <td width="20%" height="50" class="texto_padrao_destaque"><strong>FaceBook</strong></td>
                    <td width="80%" class="texto_padrao_pequeno">
                      <input name="app_url_facebook" type="text" id="app_url_facebook" class="form-control" value="<?php echo $dados_stm["app_url_facebook"]; ?>" /></td>
                  </tr>
                  <tr>
                    <td width="20%" height="50" class="texto_padrao_destaque"><strong>Twitter</strong></td>
                    <td width="80%" class="texto_padrao_pequeno">
                      <input name="app_url_twitter" type="text" id="app_url_twitter" class="form-control" value="<?php echo $dados_stm["app_url_twitter"]; ?>" /></td>
                  </tr>    
                  <tr>
                    <td width="20%" height="50" class="texto_padrao_destaque"><strong>Instagram</strong></td>
                    <td width="80%" class="texto_padrao_pequeno">
                      <input name="app_url_instagram" type="text" id="app_url_instagram" class="form-control" value="<?php echo $dados_stm["app_url_instagram"]; ?>" /></td>
                  </tr>   
                  <tr>
                    <td width="20%" height="50" class="texto_padrao_destaque"><strong>Youtube</strong></td>
                    <td width="80%" class="texto_padrao_pequeno">
                      <input name="app_url_youtube" type="text" id="app_url_youtube" class="form-control" value="<?php echo $dados_stm["app_url_youtube"]; ?>" /></td>
                  </tr>
                  <tr>
                    <td width="20%" height="50" class="texto_padrao_destaque"><strong>WhatsApp</strong></td>
                    <td width="80%" class="texto_padrao_pequeno">
                      <input name="app_whatsapp" type="text" id="app_whatsapp" class="form-control" value="<?php echo $dados_stm["app_whatsapp"]; ?>" pattern="[0-9]+" /></td>
                  </tr>
                  <tr>
                    <td width="20%" height="100" class="texto_padrao_destaque"><strong>Texto <?php echo $lang['lang_info_streaming_app_android_programacao']; ?></strong></td>
                    <td width="80%" class="texto_padrao_pequeno"><textarea class="form-control" name="app_text_prog" id="app_text_prog" rows="5"><?php echo $dados_stm["app_text_prog"]; ?></textarea></td>
                  </tr>
                  <tr>
                    <td width="20%" height="100" class="texto_padrao_destaque"><strong>Texto <?php echo $lang['lang_info_streaming_app_android_historia']; ?></strong></td>
                    <td width="80%" class="texto_padrao_pequeno"><textarea class="form-control" name="app_text_hist" id="app_text_hist" rows="5"><?php echo $dados_stm["app_text_hist"]; ?></textarea></td>
                  </tr>
                  <tr>
                    <td width="20%" height="50" class="texto_padrao_destaque"><strong>Modulo Chat</strong></td>
                    <td width="80%" class="texto_padrao_pequeno"><input name="app_url_chat" type="checkbox" value="sim" <?php if($dados_stm["app_url_chat"] == "sim") { echo ' checked="checked"'; } ?> /></td>
                  </tr>
                  <tr>
                    <td width="20%" height="50" class="texto_padrao_destaque"><strong><?php echo $lang['lang_info_streaming_app_android_pedido']; ?></strong></td>
                    <td width="80%" class="texto_padrao_pequeno"><input name="ativar_pedido_musica" type="checkbox" value="sim" <?php if($dados_stm["app_url_pedir_musica"] == "sim") { echo ' checked="checked"'; } ?> /></td>
                  </tr>
                <?php if($dados_stm["camera_studio"] == "sim" && $dados_stm["camera_studio_instalado"] == "sim") { ?>    
                  <tr>
                    <td width="20%" height="50" class="texto_padrao_destaque"><strong>Modulo Camera Studio</strong></td>
                    <td width="80%" class="texto_padrao_pequeno"><input name="ativar_camera_studio" type="checkbox" value="sim" <?php if($dados_stm["app_url_camera_studio"]) { echo ' checked="checked"'; } ?> />
                      <input name="app_url_camera_studio" type="hidden" id="app_url_camera_studio" value="https://player.<?php echo $dados_config["dominio_padrao"]; ?>/camera-studio/<?php echo $dados_stm["porta"]; ?>/<?php echo $servidor_camera_studio; ?>/16:9/true" /></td>
                  </tr>
                  <?php } else { ?> 
                  <tr>
                    <td width="20%" height="50" class="texto_padrao_destaque"><strong>Modulo Camera Studio</strong></td>
                    <td width="80%" class="texto_padrao_pequeno"><div class="input-group"><input name="ativar_camera_studio" type="checkbox" value="sim" <?php if($dados_stm["app_url_camera_studio"]) { echo ' checked="checked"'; } ?> />&nbsp;<input name="app_url_camera_studio" type="text" id="app_url_camera_studio" value="<?php echo $dados_stm["app_url_camera_studio"]; ?>" placeholder="https://url-camera-studio..." class="input" style="width: 383px;height: 30px" /></td>
                  </tr>
                  <?php } ?> 
                      <tr>
                        <td width="20%" height="50" class="texto_padrao_destaque"><strong><?php echo $lang['lang_info_streaming_app_android_radio_logo']; ?></strong></td>
                        <td width="80%" class="texto_padrao_pequeno"><div class="input-group"><input name="logo" type="file" id="logo" class="form-control" /><div class="input-group-prepend"><span class="input-group-text" style="color:#000000">PNG / 300x300</span></div></div></td>
                      </tr>
                      <tr>
                        <td height="50" class="texto_padrao_destaque"><strong><?php echo $lang['lang_info_streaming_app_android_radio_fundo']; ?></strong></td>
                        <td class="texto_padrao_pequeno"><div class="input-group"><input name="fundo" type="file" id="fundo" class="form-control" /><div class="input-group-prepend"><span class="input-group-text" style="color:#000000">JPG / 640x1136</span></div></div></td>
                      </tr>
                        <tr>
                          <td height="70" colspan="2" align="center"><button type="submit" class="btn btn-info" onclick="$('#app-android-loading').modal('show');"><?php echo $lang['lang_botao_titulo_alterar_config']; ?></button><input name="acao_form" type="hidden" id="acao_form" value="configurar" /></td>
                        </tr>
                </table>
                </form>
                  </div>
              </div>
            </div>
            <?php } ?>
          </div>
        </div>
      </div>      

    </div>
  </div>
  <script src="/inc/vendor.bundle.base.js"></script>
  <script src="/inc/vendor.bundle.addons.js"></script>
  <script src="/inc/theme.js"></script>
  <script>
  status_streaming('<?php echo $porta_code; ?>');
  setInterval("status_streaming('<?php echo $porta_code; ?>')",60000);      function bloquear_caracteres(id) {
var novo = document.getElementById(id).value.replace(/[^a-z0-9]/gi,'');
var final = novo.toLowerCase();
document.getElementById(id).value = final;
}
function gerar_pkg() {

var nome_app = document.getElementById("radio_nome").value;

if(nome_app == "") {
alert("Ooops! Primeiro deve informar o nome da sua radio.");
document.getElementById("radio_nome").focus();
} else {

var parte_nome_app = nome_app.replace(/[^a-z0-9]/gi,'').substring(0,15).toLowerCase();
var parte_rnd = Array.from(Array(10), () => Math.floor(Math.random() * 36).toString(36)).join('');
var pkg_gerado = parte_nome_app+parte_rnd;
document.getElementById("pkg_personalizado").value = pkg_gerado;

}

}
$('#botao_historico, #botao_personalizar').click(function() {
  $('#row_package_personalizar').toggle();
  $('#row_package_historico').toggle();
  $('#pkg_personalizado').val('');
});
  </script>
</body>
</html>