<?php
include( "../lib_PHP/PhPage.lib.php" );
require( "../lib_PHP/JsrsServer.class.php" );

class dataAccess
{
  var $errorFile = 'errorBuffer.txt';
  var $path = '';
    
  function get_ajuda( $txt )
  {
    return "Ajuda";
  }
  
  function teste( $txt )
  {
      $arr  = explode( ':', $txt );
      $nUsr = $arr[0];  // login do Usuário
      $nObj = $arr[1];  // nome Objeto dbGrid
      $key  = $arr[2];  // chave (PK) do dbGrid

      $lib = $_SERVER['DOCUMENT_ROOT'] . "/Studio/core/dbGrid.lib.php";
      include( $lib );

      $path = $_SERVER['DOCUMENT_ROOT'] . "/Studio/desenv/usuarios/".$nUsr."/config/";
      $nFile = $path . $nObj . ".config.data.ini";
      $field = array();

      if( file_exists( $nFile ) )
      {
  /**
   *  le o .config.data.ini do dbGrid
   */
        $arrINI = readINIfile( $nFile );

        $ind = $nObj . '_field';
        $arrField = $arrINI[ $ind ];
        $dts = $path . $arrINI[ $nObj . '_data']['datasource'] . '.config.data.ini';

        if( file_exists( $dts ) )
        {
  /**
   *  le o .config.data.ini do DataSource
   */
          $arrDTS = readINIfile( $dts );
          $host  = $arrDTS['db_conect']['host'];
          $user  = $arrDTS['db_conect']['user'];
          $pass  = $arrDTS['db_conect']['pass'];
          $dbase = $arrDTS['db_conect']['dbase'];

  /**
   *  Abre a conexão com o SGDB
   */
          $con = mysql_connect( $host, $user );
          $db = mysql_select_db( $dbase, $con);

          $tabela = $arrINI[ $nObj . '_data']['tabela'];
          $pk_    = $arrINI[ $nObj . '_data']['pk'];
          $pkey   = explode( '*', $pk_ );
          $update  = " UPDATE " . $tabela . " SET status = 'L' WHERE " . $pkey[0] . " = '" . $key . "';";
          if( !$re = mysql_query( $update ) )
          {
            $ret = '0#erro#not found ' . $update;
          }else
          {
            $ret = '1#'.$conf.'#Mensagem lida com sucesso';
          }// End if( !$re = mysql_query( $update ) )

        }else
        {
          $ret = '0#erro#dataource.config.data.ini not found. ';
        }// End if( file_exists( $dts ) )

      }else
      {
        //$ret = '0#erro#'.$arr[0].'.config.data.ini not found.';
        $ret = '0#erro#'.$nFile.' not found ';
      }// End if( file_exists( $nFile ) )

      return( $ret );

  }// End function teste( $txt )


  function set_path( $txt )
  {
    return $txt;
  }// End function set_path( $txt )


/**
 *  set_record()
 *  ============
 *  Atualizar/Incluir Registro  --------------------------------------------  //
 */
  function set_record( $linha )
  {
    $arrLinha = explode( '#', $linha );
    $arrCampo = array();
    $arrValor = array();

    foreach( $arrLinha as $ind => $val )
    {
      $arr = explode( ':', $val );
      if( $ind == 0 )
      {
        $logUser = $arr[0];
        $dbGrid  = $arr[1];
        $nrLinha = $arr[2];
        $cmdo    = $arr[3];
      }else
      {
        $arrCampo[] = $arr[0];
        $arrValor[] = $arr[1];
      }// End if( $ind = 1 )
    }// end foreach( $arrLinha as $ind => $val )
//return 'cmdo: '.$cmdo;

    $path = $_SERVER['DOCUMENT_ROOT'] . '/'. getRoot(). "Studio/desenv/usuarios/".$logUser."/config/" ;
//    $path = $_SERVER['DOCUMENT_ROOT'] . '/Studio/desenv/usuarios/'.$logUser.'/config/' ;
    $nFile = $path . $dbGrid . ".config.data.ini";

    if( file_exists( $nFile ) )
    {
/**
 *  le o .config.data.ini do dbGrid
 */
      $arrINI   = readINIfile( $nFile );
      $ind      = $dbGrid . '_field';
      $data     = $dbGrid . '_data';
      $arrField = $arrINI[ $ind ];
      $pk       = $arrINI[ $data ]['pk'];

      $dts = $path . $arrINI[ $data ]['datasource'] . '.config.data.ini';
      if( file_exists( $dts ) )
      {
/**
 *  le o .config.data.ini do DataSource
 */
        $arrDTS = readINIfile( $dts );
        $host  = $arrDTS['db_conect']['host'];
        $user  = $arrDTS['db_conect']['user'];
        $pass  = $arrDTS['db_conect']['pass'];
        $dbase = $arrDTS['db_conect']['dbase'];

        $con = mysql_connect( $host, $user );
        $db = mysql_select_db( $dbase, $con);

        $tabela = $arrINI[ $dbGrid .'_data']['tabela'];
      }// End if( file_exists( $dts ) )
    }// End if( file_exists( $nFile ) )

//return "erro:".$nrLinha;
    if( $nrLinha == 0 )
    {
/**
 *  Inclui um Registro no Banco de Dados  ----------------------------------  //
 */
      $ret = 'insert:' . $logUser;
      $query = "INSERT INTO " . $tabela . ' ';

      $listaCampos = '( ';
      $nrCampos = count( $arrCampo )-1;
//return $nrCampos;
      foreach( $arrCampo as $ii => $nField )
      {
        $listaCampos .= $nField;
        if( $ii < $nrCampos )
        {
          $listaCampos .=  ', ';
        }// End if( $ii < $nrCampos )
      }// End foreach( $arrCampo as $ii => $nField )
      $listaCampos .= ' ) values ( ';
      foreach( $arrValor as $ii => $val )
      {
        $listaCampos .= "'".$val."'";
        if( $ii < $nrCampos )
        {
          $listaCampos .= ',';
        }// End if( $ii < $nrCampos )
      }// End foreach( $arrValor as $ii => $valor )
      $listaCampos .= ' )';
      $query .= $listaCampos;
      $result = mysql_query($query);
      if( $result )
      {
        $ret = $dbGrid;
      }else
      {
        $ret = 'erro:'.mysql_error();
      }//
    }else
    {
      if( $cmdo == 'Del' )
      {
/**
 *  Deleta um Registro no Banco de Dados  ----------------------------------  //
 */
        $query = "DELETE FROM " . $tabela . ' WHERE ';
        $nrCampos = count( $arrCampo )-1;
        foreach( $arrCampo as $ii => $nField )
        {
          if( $nField == $pk )
          {
            $valPK = $arrValor[$ii];
          }// End if( $nField == $pk )
        }// End foreach( $arrCampo as $ii => $nField )
        $query .= $pk . ' = "' . $valPK . '"';
        $result = mysql_query($query);
        if( $result )
        {
          return $dbGrid;
        }else
        {
          return 'erro[del]:' . $query;
//          return 'erro[del]:'.mysql_error();
        }
      }else
      {
/**
 *  Atualiza um Registro no Banco de Dados
 */
      $ret = 'upDate';
      $query = "UPDATE " . $tabela . ' SET ';
      $nrCampos = count( $arrCampo )-1;
//return $nrCampos;
//return 'erro'.$arrCampo;
      foreach( $arrCampo as $ii => $nField )
      {
        $listaCampos .= $nField . "='" . $arrValor[$ii] . "'";
        
        if( $nField == $pk )
        {
          $valPK = $arrValor[$ii];
        }
        if( $ii < $nrCampos )
        {
          $listaCampos .=  ', ';
        }// End if( $ii < $nrCampos )
      }// End foreach( $arrCampo as $ii => $nField )
      
      $query .= $listaCampos . " WHERE ".$pk."='".$valPK . "' LIMIT 1";
//return 'erro: '.$query;
      }// End if( $cmdo == 'Del' )
      
      $result = mysql_query($query);
      if( $result )
      {
        $ret = $dbGrid;
      }else
      {
        $ret = 'erro[Upd]:'.mysql_error();
      }//
//return 'status: '.$ret;

      //$ret = $listaCampos;
      //$ret = $query;
    }// end if( $nrLinha == 0 )
    return( $ret );
  }// End function inc_record( $linha )

/**
 *  get_result()
 *  ------------------------------------------------------------------------  //
 *  Method para retornar a lista dos campos da Tabela
 */
  function get_result( $nObj )
  {
  $_root_ = $_SERVER['DOCUMENT_ROOT'] . '/' . getRoot() . "Studio/";
//return $_root_;

    $lib = $_root_ . "core/dbGrid.lib.php";
//return( $lib );
    include( $lib );
    
    $arrList = array();
    $arr = explode( ':', $nObj );
    $nUser     = $arr[0];
    $nObj      = $arr[1];
    $masterKey = $arr[2];
//return($masterKey);
//    $path = $_SERVER['DOCUMENT_ROOT'] . "/Studio/desenv/usuarios/othuki/config/" ;
    $path = getRoot() . "Studio/desenv/usuarios/" . $nUser . "/config/" ;
    $nFile = $_SERVER['DOCUMENT_ROOT'].'/'.$path . $nObj . ".config.data.ini";
//return( $nFile );

//return $_SERVER['DOCUMENT_ROOT'].'/'.$nFile;
    if( file_exists( $nFile ) )
    {
//return $nFile;
/**
 *  le o .config.data.ini do dbGrid  ---------------------------------------  //
 */
      $arrINI = readINIfile( $nFile );
      $ind = $nObj . '_field';
      $arrField = $arrINI[ $ind ];
      $dts = $_SERVER['DOCUMENT_ROOT'].'/'.$path . $arrINI[ $nObj . '_data']['datasource'] . '.config.data.ini';
      $pks = $arrINI[ $nObj . '_data']['pk'];
      if( file_exists( $dts ) )
      {
//return 'PK: '.$pks;
/**
 *  le o .config.data.ini do DataSource
 */
        $arrDTS = readINIfile( $dts );
        $host  = $arrDTS['db_conect']['host'];
        $user  = $arrDTS['db_conect']['user'];
        $pass  = $arrDTS['db_conect']['pass'];
        $dbase = $arrDTS['db_conect']['dbase'];

        $con = mysql_connect( $host, $user );
        $db = mysql_select_db( $dbase, $con);

        $tabela = $arrINI[ $nObj .'_data']['tabela'];
        $query = "SELECT * FROM " . $tabela ;
        if( $masterKey != '' )
        {
          //$query .= " WHERE $pks = '" . $masterKey . "';";
          $query .= " WHERE codigo_formula = '" . $masterKey . "';";
          
        }// End
//return($query);
        $result = mysql_query($query);

        $arrList[0] = $nObj;
        $_idx_ = 1;
        $nrLinhas = mysql_num_rows( $result );
        if( $nrLinhas == 0 )
        {
          $linha = '';
          foreach( $arrField as $ii_ => $vv_ )
          {
            if( $arrINI[ $nObj . '_' . $ii_][ 'grid' ] == 'visible' )
            {
              $linha .= 'F:'.$arrINI[ $nObj . '_' . $ii_ ]['field'].': #';
            }// End
          }// End
          $arrList[ $_idx_ ] = $linha;
        }else
        {
          while ($line = mysql_fetch_array( $result, MYSQL_ASSOC ))
          {
            $linha = '';
            $_i_ = 0;
            foreach( $arrField as $ii_ => $vv_ )
            {
              if( $arrINI[ $nObj . '_' . $ii_][ 'grid' ] == 'visible' )
              {
                if( $_i_ > 0 ) $linha .= '#';
                $nField = $arrINI[ $nObj . '_' . $ii_ ][ 'field' ];
              
                switch( $arrINI[ $nObj . '_field' ][ $ii_ ] )
                {
                  case 'lookup':
                    $nTab = $arrINI[ $nObj . '_' . $ii_ ][ 'tabela' ];
                    $nKey = $arrINI[ $nObj . '_' . $ii_ ][ 'field_key' ];
                    $nVal = $line[ $nKey ];
                    $nGet = $arrINI[ $nObj . '_' . $ii_ ]['field'];
                    $linha .= 'L:' . $arrINI[ $nObj . '_' . $ii_ ]['field'] . ':' .
                              lookUP( $nTab, $nKey, $nVal, $nGet );

                    break;
                  case 'calc':
                    $linha .= 'x:calc'.':'.$line[ $nField ];
                    break;
                  case 'calculado':
//                    $linha .= 'C:calc:' . $arrINI[ $nObj . '_' . $ii_ ]['formula'];
                    $linha .= 'C:'.$arrINI[ $nObj . '_' . $ii_ ]['field'].':' . $arrINI[ $nObj . '_' . $ii_ ]['formula'];
                    break;
                  default:
                   $linha .= 'F:'.$arrINI[ $nObj . '_' . $ii_ ]['field'].':'.
                             $line[ $nField ];
                    break;
                }// End switch( $arrINI[ $nObj . '_field' ][ $ii_ ] )

                //$linha .= $arrINI[ $nObj . '_field' ][ $ii_ ];
                $_i_ ++;
              }// End if( $arrINI[ $nObj . '_' . $ii_][ 'grid' ] == 'visible' )
            }// End foreach( $arrField as $ii_ => $vv_ )
            $arrList[ $_idx_ ] = $linha;
            $_idx_ ++;
          }// End while ($line = mysql_fetch_array($result, MYSQL_ASSOC))
        }// End
        //return 'ok: ' . $linha;
      }// End if( file_exists( $dts ) )
    }// End if( file_exists( $nFile ) )

    return( $arrList );
  }// End function get_result( $nObj )
  
  

/**
 *  Method para retornar o valor de um campo da Tabela
 */
  function get_field_value( $cmd )
  {
    $arr = explode( ':', $cmd);
    $nUsr = $arr[0];  // login do Usuário
    $nObj = $arr[1];  // nome Objeto dbGrid
    $key  = $arr[2];  // chave (PK) do dbGrid
    $nCpo = $arr[3];  // nome do Campo a ter o valor retornado
    $dest = $arr[4];  // nome do Obj a receber o valor retornado

    $lib = $_SERVER['DOCUMENT_ROOT'] . "/Studio/core/dbGrid.lib.php";
    include( $lib );

    $path = $_SERVER['DOCUMENT_ROOT'] . "/Studio/desenv/usuarios/".$nUsr."/config/" ;
    $nFile = $path . $nObj . ".config.data.ini";
    $field = array();

    if( file_exists( $nFile ) )
    {
/**
 *  le o .config.data.ini do dbGrid
 */
      $arrINI = readINIfile( $nFile );

      $ind = $nObj . '_field';
      $arrField = $arrINI[ $ind ];
      $dts = $path . $arrINI[ $nObj . '_data']['datasource'] . '.config.data.ini';

      if( file_exists( $dts ) )
      {
/**
 *  le o .config.data.ini do DataSource
 */
        $arrDTS = readINIfile( $dts );
        $host  = $arrDTS['db_conect']['host'];
        $user  = $arrDTS['db_conect']['user'];
        $pass  = $arrDTS['db_conect']['pass'];
        $dbase = $arrDTS['db_conect']['dbase'];

/**
 *  Abre a conexão com o SGDB
 */
        $con = mysql_connect( $host, $user );
        $db = mysql_select_db( $dbase, $con);

        $tabela = $arrINI[ $nObj . '_data']['tabela'];
        $pk_    =  $arrINI[ $nObj . '_data']['pk'];
        $pkey   = explode( '*', $pk_ );
        $query = "Select ".$nCpo." FROM " . $tabela . " WHERE " . $pkey[0] . " = '" . $key . "';";
        $result = mysql_query($query);

        $valField = mysql_result( $result, 0 );
        $ret = '1#' . $dest . '#' . $valField;
        //$ret = '1#' . $dest . '#' . $query;
      }else
      {
        $ret = '0#erro#dataource.config.data.ini not found.';
      }// End if( file_exists( $dts ) )



    }else
    {
      //$ret = '0#erro#'.$arr[0].'.config.data.ini not found.';
      $ret = '0#erro#'.$nFile.' not found';
    }// End if( file_exists( $nFile ) )
    
    return( $ret );
  }// End function get_field_value( $cmd )


/**
 *  Method para retornar a lista de campos da Tabela
 */
  function get_fields( $cmd )
  {
    $arr = explode( ':', $cmd);
    $nLog = $arr[0];
    $nObj = $arr[1];
    $path = $_SERVER['DOCUMENT_ROOT'] . '/'. getRoot(). "Studio/desenv/usuarios/".$nLog."/config/" ;
    $nFile = $path . $nObj . ".config.data.ini";
    $field = array();
//$field[0] = 'erro: ' . $nFile;
//return( $field );

    if( file_exists( $nFile ) )
    {
      $arrINI = readINIfile( $nFile );
      $ind = $nObj . '_field';
      $arrField = $arrINI[ $ind ];

      $field[0] = $nObj;
      $ii_ = 1;
      foreach( $arrField as $i_ => $v_ )
      {
        if( $arrINI[ $nObj . '_' . $i_ ][ 'grid' ] == 'visible' )
        {
          $field[ $ii_ ] = $arrINI[ $nObj . '_' . $i_ ][ 'caption' ];
          $ii_ ++;
        }// End
      }// End foreach( $arrField as $i_ => $v_ )
    }else
    {
      $field[0] = 'erro: config.data.ini não existe.';
    }// End
    
    return( $field );
  }// End function get_fields( $nObj )

/**
 *  up_date()
 *  ------------------------------------------------------------------------  //
 *  Method para atualizar uma tabela
 */
  function up_date( $txt )
  {
    $arr = explode( ":", $txt );
    $log_ = $arr[0];
    $obj_ = $arr[1];
    $key_ = $arr[2];
    $val_ = $arr[3];
    $col_ = $arr[4];
    $new_ = $arr[5];
    $path = $_SERVER['DOCUMENT_ROOT'] . "/Studio/desenv/usuarios/" . $log_ . "/config/" ;
    if( $path . $obj_ . ".config.def.php" )
    {
      include( $path . $obj_ . ".config.def.php" );
      $tmp = $obj_ . "_Conf";;
      $arrConf = $$tmp;
      $dataSet = $arrConf[ 'data_set' ];

    //return $dataSet;
    }else
    {
      return "erro [dbGrid] arquivo de Config não localizado.";
    }// End

    if( file_exists( $path . $dataSet . ".config.data.ini" ) )
    {
      $arrINI = readINIfile( $path . $dataSet . ".config.data.ini" );

//return $arrINI[ $dataSet.'_data' ]['datasource'];
      $dtSet = ucFirst($dataSet);
//return $dtSet;

      $dts = $path . $arrINI[ $dataSet . '_data']['datasource'] . '.config.data.ini';
//return $dts;
      if( file_exists( $dts ) )
      {
        $arrDTS = readINIfile( $dts );

        $fp = @fopen("teste.txt", 'wb');
        foreach( $arrDTS as $_i => $_v )
        {
          $var = $_i .' '. $_v;
          @fwrite($fp, $var, strLen($var));
        }
        @fclose($fp);

        $host  = $arrDTS['db_conect']['host'];
        $user  = $arrDTS['db_conect']['user'];
        $pass  = $arrDTS['db_conect']['pass'];
        $dbase = $arrDTS['db_conect']['dbase'];

        $con = mysql_connect( $host, $user );
        $db = mysql_select_db( $dbase, $con);
//return $host;

        $tabela = $arrINI[ $dataSet .'_data']['tabela'];
//          $query = "UPDATE ".$tabela." SET ".$col_." = '".$new_."' WHERE ".$key_."=".$val_." LIMIT 1;";
        $query = "UPDATE ".$tabela." SET ".$col_." = '".$new_."' WHERE ";

/**
 *  monta a condição de WHERE conforme a PK
 */
        $arrKey = explode( '*', $key_ );
        $arrVal = explode( '*', $val_ );
        $cond   = '';
        $indx   = false;

        foreach( $arrKey as $ii_ => $vv_ )
        {
          if( $indx )
            $cond .= ' and ';
          $newVal = $arrVal[$ii_ ];
          $cond .= ( ' ' . $vv_ . ' = ' . $newVal );
          $indx = true;
        }// End foreach( $arrKey as $ii_ => $vv_ )
        $query .=  $cond . " LIMIT 1;";

        $result = mysql_query($query);

      }else
      {
        return "erro DTS: " . $dts;
      }// End if( file_exists( $dts ) )

    }else
    {
      return('erro.');
    }// End
    return "OK. upDate [$query] com sucesso.";

  }// End function up_date( $txt )

  function exec_sql( $query )
  {
    $host  = "localhost";
    $user  = "root";
    $pass  = "";
    $dbase = "frotintas";

    $con = mysql_connect( $host, $user );
    $db = mysql_select_db( $dbase, $con);

    $result = mysql_query($query);
//return( $query );
    if( $result)
    {
      $ret = "Ok";
    }else
    {
      $ret = "erro";
    }
    return $ret;
  }




}// End class MsgServer
  
  // First create the object to be called. (Pseudo static)
  $theMsgServer = new dataAccess();
  
  // Use the static $JsrsServer to 
  // propergate the methodes that are available for the client
  $JsrsServer->propergateMethod($theMsgServer, 'get_ajuda');
  $JsrsServer->propergateMethod($theMsgServer, 'teste');

  $JsrsServer->propergateMethod($theMsgServer, 'set_path');
  $JsrsServer->propergateMethod($theMsgServer, 'set_record');

  $JsrsServer->propergateMethod($theMsgServer, 'up_date');
  $JsrsServer->propergateMethod($theMsgServer, 'get_fields');
  $JsrsServer->propergateMethod($theMsgServer, 'get_field_value');
  $JsrsServer->propergateMethod($theMsgServer, 'get_result');

  $JsrsServer->propergateMethod($theMsgServer, 'exec_sql');

  // Start the JsrsServer to handle the request from the client
  $JsrsServer->start();
?>                                                     	

