<?php
/*********************************************
Desciption: Noticias
File: /bsk/noticias/index.php
Project: Basikus.Net
Developers: João Vieira	
Start Date: 2009/05/20
*********************************************/

//configuração principal
require_once($_SERVER['DOCUMENT_ROOT'] . "/bsk/includes/configuracao.default.php");
//funções de tratamento de textos
include($_SERVER['DOCUMENT_ROOT'] . '/bsk/includes/funcoes.default.php'); 
//drop downs e listas simples, aqui por causa das categorias
include($_SERVER['DOCUMENT_ROOT'] . "/bsk/includes/classe.bd.listas.php");
include($_SERVER['DOCUMENT_ROOT'] . "/bsk/includes/classe.categorias.php");

$ondeTou    = 'utilizadores';
$ondeId     = 0;

if ( isset($_GET['id']) ) header('Location: /bsk/utilizadores/?' . $_GET['id'] . '/alterar');

if (isset($_SERVER['QUERY_STRING'])) {
    $dBToDo = explode("/", $_SERVER['QUERY_STRING']);
    $dBToDo[0] = (int) $dBToDo[0];
    if (!isset($dBToDo[1])) $dBToDo[1] = "";
    $dBToDo[1] = addslashes($dBToDo[1]);
    if (!isset($dBToDo[2])) $dBToDo[2] = "";    
}

//campos BD a usar localmente
$erro                   = false;
$fieldId                = 0;
$fieldEmail             = '';
$fieldSenha             = '';
$fieldNome              = '';
$fieldDia               = '';
$fieldEstado            = 'NAO';
$metaJSinTexto          = '';
$jsValidacoesRules      = '';
$jsValidacoesMessages   = '';
$jsId                   = '';
$sqlStmtSenha           = '';

/* tratamento de form comin' */

if (isset($_POST['btProcessar'])) {

    #id
    $_POST['bxId']  = (int) $_POST['bxId'];

    #nome
    $fieldNome      = $_POST['bxNome'];

    #email
    $fieldEmail     = $_POST['bxEmail'];
    if ( !valida_email($fieldEmail) || strlen($fieldEmail) < 5 ) { $error = true; }
    else {
        $sqlStmt = "SELECT id 
                    FROM utilizadores
                    WHERE email like '" . $fieldEmail . "'
                    LIMIT 0, 1 ";
        $resultDb = $connectDb->pedido($sqlStmt);
        if ( $resultDb->rowCount() > 0 ) { $error = true; }
    }

    #senha
    $fieldSenha     = $_POST['bxSenha'];
    if ( strlen($fieldSenha)> 3 ) $sqlStmtSenha = "senha = '" . md5($pwdWord . $fieldSenha) . "'";
    
    #estado
    if (!isset($_POST['bxEstado'])) $_POST['bxEstado'] = "";
    $fieldEstado    = $_POST['bxEstado'];
    if ( $_POST['bxEstado'] == "" ) $fieldEstado = 'NAO';
    else $fieldEstado = 'SIM';

    if ( $_POST['bxId'] > 0 && !($erro) ) { # ou altera
        $sqlStmt = "UPDATE utilizadores 
                SET 
                nome = '" . safe($fieldNome) . "',
                " . $sqlStmtSenha . "
                email = '" . safe($fieldEmail) . "',
                estado = '" . $fieldEstado . "'                
                WHERE id = '" . $_POST['bxId'] . "'";
        $fieldId    = $_POST['bxId'];
        $resultDb   = $connectDb->pedido($sqlStmt);
        $fieldId    = 0;
    }elseif ( !$erro ) { # ou insere
    
        $sqlStmt = "INSERT INTO utilizadores (
                            nome, 
                            senha, 
                            email, 
                            estado,
                            dia
                    ) 
                    VALUES (
                            '" . safe($fieldNome) . "', 
                            '" . md5($pwdWord . $fieldSenha) . "', 
                            '" . safe($fieldEmail) . "', 
                            '" . safe($fieldEstado) . "',
                            NOW()
                    )";
        $resultDb       = $connectDb->pedido($sqlStmt);
        #$fieldId        = $connectDb->registosUltimo();
    }
    #header('Location: /bsk/utilizadores/');

}

/* /tratamento de form comin' */

/* busca de conteudo a gerir */
if ($dBToDo[1] == 'alterar') {
    $sqlStmt = "SELECT 
		nome, 
		senha, 
		email, 
		estado,
		DATE_FORMAT(dia, '%Y-%m-%d') AS dia
            FROM utilizadores
            WHERE id = '" . $dBToDo[0] . "'";
               
    $resultDb       = $connectDb->pedido($sqlStmt);
    if ( $rowResultDb = $resultDb->fetch(PDO::FETCH_ASSOC) ) {
        $fieldId            = $dBToDo[0];
        $fieldNome     = $rowResultDb['nome'];
        $fieldEmail        = $rowResultDb['email'];
        $fieldestado       = $rowResultDb['estado'];
        $fieldDia           = $rowResultDb['dia'];

    }else exit();
}
/* /busca de conteudo a gerir */
if ( $fieldId > 0 ) $jsId = '?id=' . $fieldId;

$metaTitle  = $bngUtilizadores;

$metaJS     = '	jQuery(document).ready(function(){ 
	    
	$("#formConteudos").validate({
	    rules: {
		bxNome: {
		          required: true,
		          minlength: 3
		},
		bxEmail: {
		          required: true, 
		          email: true,
		          remote: \'/bsk/utilizadores/registos/v.email/' . $jsId . '\'
		}
	    },
	    messages: {
		bxNome: {
		  required: "' . $bngCampoInvalido . '",
		  minlength: jQuery.format(\'' . $bngCampoInvalido . '\')
		},
		bxEmail: {
		  required: "' . $bngCampoInvalido . '",
		  email: "' . $bngCampoInvalido . '",
                  remote: "' . $bngCampoEmailExistente . '"		
		}
	    },
	    errorPlacement: function(error, element) {
	        var errEl = \'#erR\' + element.attr("name");
                $(errEl).css({\'color\' : \'red\', \'width\' : \'520px\', \'padding-left\' : \'10px\'});
	        error.appendTo(errEl);
	    },
	    submitHandler: function(form) {
		form.submit();
	    },
	    success: function(label) {
		//label.html("&nbsp;").addClass("checked");
	    }
	});
	    
	    var lastsel;	
	    jQuery("#listaG").jqGrid({
		url:\'/bsk/utilizadores/registos/lista/?xuta=' . $ondeId . '\',
		height: 130,
		datatype: \'json\',
		mtype: \'GET\',    
		colNames:[\'' . $bngEmail . '\',\'' . $bngNome . '\',\'' . $bngActivo . '\'],
		colModel :[ 
		{name:\'email\', index:\'email\', width:280, align:\'left\', editable: false, edittype:"text", formatter: \'showlink\',  formatoptions: {baseLinkUrl: \'/bsk/utilizadores/\', showAction: \'\', addParam:\'\'}}, 
		{name:\'nome\', index:\'nome\', width:400, align:\'left\', editable: true, edittype:"text"},
		{name:\'activo\', index:\'activo\', width:80, align:\'center\', sortable:false, editable: true, edittype:"select", editoptions:{value:"XX:' . $bngAmbos . ';NAO:' . $bngNao . ';SIM:' . $bngSim . '"}}
		],
		rowNum:100,
		rowList:[100,200,400],
		pager: jQuery(\'#listaP\'),
		sortname: \'id\',
		sortorder: "desc",
		toolbar : [true,"top"],
		onSelectRow: function(id){ 
		    if(id && id!==lastsel){ 
			jQuery(\'#listaG\').restoreRow(lastsel); 
			jQuery(\'#listaG\').editRow(id,true); 
			lastsel=id; 
		    } 
		},
		editurl: "/bsk/utilizadores/registos/editar/?' . md5($pwdWord . Date('Ymd')) . '",
		viewrecords: true,
		caption: \'' . $bngListaRegistos . '\',
		loadError : function(xhr,st,err) { 
		    jQuery("#listaErr").html("Type: "+st+"; Response: "+ xhr.status + " "+xhr.statusText); 
		}
		
	    }); 
	    jQuery("#t_listaG").height(25).hide().filterGrid("listaG",{gridModel:true,gridToolbar:true});
	    jQuery("#listaG").navGrid(\'#listaP\',{edit:false,add:false,del:true,search:false,refresh:true});
	    jQuery("#listaG").navButtonAdd("#listaP",{caption:"' . $bngPesquisar . '",title:"' . $bngPesquisa . '\'", 
	       onClickButton:function(){ 
		    if(jQuery("#t_listaG").css("display")=="none") { 
			jQuery("#t_listaG").css("display",""); 
		    }else { 
			jQuery("#t_listaG").css("display","none"); 
		    } 
		} 
	    });
	    
	    function pickdates(id){ 
		jQuery("#" + id + "_udia","#listaG").datepicker({dateFormat:"yy-mm-dd"}); 
	    } 
	   
	   $("#cbxDataIn").datepicker({dateFormat:"yy-mm-dd"});
	   $("#cbxDataOut").datepicker({dateFormat:"yy-mm-dd"});



	});//jquery function start
	
        xinha_editors = xinha_editors ? xinha_editors :
        [
            ' . $metaJSinTexto . '
        ]; 
        Xinha.startEditors(xinha_editors);



	';

include($_SERVER['DOCUMENT_ROOT'] . '/bsk/includes/md.topo.php');

?>
	<div id="middle">
		
	    <div id="center-column">
		    <div class="top-bar">
			    <h1><?php print $bngUtilizadores;?></h1>
			    <div class="breadcrumbs"><a href="/bsk/"><?php print $bngInicial;?></a> / <a href="/bsk/utilizadores/"><b>+</b><?php print $bngInserir;?>&nbsp;<?php print $bngUtilizadores;?></a></div>
		    </div>
		    <br />
		<div class="select-bar">
		&nbsp;
		</div>
	    <!-- tabela -->
	    <table id="listaG" class="scroll"></table> 
	    <div id="listaP" class="scroll" style="text-align:center;"></div> 
	    <span id="listaErr" style="color:red"></span>  
	    <!-- /tabela -->
	<a name="formPos"></a> 
	<!-- form -->
	<div id="form_container" >
	   
	    <form id="formConteudos" class="appnitro"  method="post" action="">
		<ul >				
		<li id="liNome" >
		<label class="description" for="cbxNome"><?php print $bngNome;?> </label>
		<div>
		  <input id="cbxNome" name="bxNome" class="element text medium" type="text" maxlength="120" value="<?php print $fieldNome;?>"/>
		</div> <span id="erRbxNome"></span>
		</li>		
		<li id="liEmail" >
		<label class="description" for="cbxEmail"><?php print $bngEmail;?> </label>
		<div>
		  <input id="cbxEmail" name="bxEmail" class="element text medium" type="text" maxlength="120" value="<?php print $fieldEmail;?>"/>
		</div> <span id="erRbxEmail"></span>
		</li>		
		<li id="liSenha" >
		<label class="description" for="cbxSenha"><?php print $bngSenha;?> </label>
		<div>
		  <input id="cbxSenha" name="bxSenha" class="element text" type="password" maxlength="15" value="<?php print $fieldSenha;?>"/>
		</div> <span id="erRbxSenha"></span>
		</li>		
<?php
if ( strlen($fieldDia) > 8) {
?>
		<li id="liDia" >
		<label class="description" for="cbxSenha"><?php print $bngDataInicio;?> <span id="erRbxDia"></span></label>
		<div>
		  <?php print $fieldDia;?>
		</div> 
		</li>	
<?php
}
?>
		
		</ul>

			
		<li class="buttons">
		    <input type="hidden" id="cbxId" name="bxId" value="<?php print $fieldId;?>" />
		    <input type="hidden" id="cbtProcessar" name="btProcessar" value="<?php print $bngProcessar;?>" />
		    <input id="cbtProcessarB" class="button_text" type="submit" name="btProcessarB" value="<?php print $bngProcessar;?>" />
		</li>
		</ul>
		</form>	
	</div>
	<!-- /form -->
	    
	    
	    
	    </div>

<?php include( $_SERVER['DOCUMENT_ROOT'] . "/bsk/includes/md.direita.php" );?>
	
	</div>
<?php
include($_SERVER['DOCUMENT_ROOT'] . '/bsk/includes/md.fundo.php');	
?>