<?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 )
  {
    return "OK";
  }


  function set_path( $txt )
  {
    return $txt;
//    $this->path = $txt;
//    return 'ok[ ' . $this->path . ' ]';
  }//


/**
 *  Method para retornar a lista de campos da Tabela
 */
  function get_result( $nObj )
  {
    $arrList = array();
    $arr = explode( ':', $nObj );
    $nObj      = $arr[0];
    $masterKey = $arr[1];
    
    $path = $_SERVER['DOCUMENT_ROOT'] . "/Studio/desenv/usuarios/othuki/config/" ;
    $nFile = $path . $nObj . ".config.data.ini";

    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';
//return $dts;
      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[ $nObj .'_data']['tabela'];
        $query = "Select * FROM " . $tabela . " WHERE codigo_formula = '" . $masterKey . "';";
        $result = mysql_query($query);
        
        $arrList[0] = $nObj;
        $_idx_ = 1;
        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' ];
              $linha .= $line[ $nField ];
              $_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))
        
        //return 'ok: ' . $linha;
      }// End if( file_exists( $dts ) )
      
    }// End if( file_exists( $nFile ) )

    return( $arrList );
  }// End function get_fields( $nObj )
  
  
/**
 *  Method para retornar a lista de campos da Tabela
 */
  function get_fields( $nObj )
  {
    $path = $_SERVER['DOCUMENT_ROOT'] . "/Studio/desenv/usuarios/othuki/config/" ;
    $nFile = $path . $nObj . ".config.data.ini";
    $field = array();
    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

/**
 *  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 )






}// 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, 'up_date');
  $JsrsServer->propergateMethod($theMsgServer, 'get_fields');
  $JsrsServer->propergateMethod($theMsgServer, 'get_result');

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

