<?php
require("codebase/connector/scheduler_connector.php");
require("codebase/connector/db_mysqli.php");
 

 if(isset($_GET['table'])){
  $table = $_GET['table'];
  date_default_timezone_set("America/Costa_Rica");
  $res = db ();
  if (!$res){
      echo "NO ESTOY CONECTADO"; 
    }

  $scheduler = new SchedulerConnector($res,"MySQLi");
  $scheduler->enable_log("logDataBaseScheduler.log",true);
  $scheduler->event->attach("beforeUpdate","myUpdate");
  $scheduler->event->attach("beforeDelete","myDelete");
  $scheduler->render_table($table,"id","start_date,end_date,text,calendar,personnel,location,customer,vehicle,color,eventComm,serieComm,seriesId");
  }else{
  echo "Ocurrio un problema con la tabla temporal en la base de datos."; 
  die();
  }

  
  function doOnDBError($action, $exception){
    $action->set_response_xml("<errorinfo>".((String)$exception)."</errorinfo>");
  };
 
  function myUpdate($action){
    
    $table = $_GET['eventbl'];
    $change = false;
    $res = db ();

    $sql = "UPDATE rmscheduler_orkincr.".$table." SET
          start_date='".formatString($action->get_value('start_date'))."' ,
          end_date='".formatString($action->get_value('end_date'))."' ,
          text='".formatString($action->get_value('text'))."' ,
          calendar='".formatString($action->get_value('calendarNew'))."' ,
          personnel='".formatString($action->get_value('personnelNew'))."' ,
          location='".formatString($action->get_value('location'))."' ,
          customer='".formatString($action->get_value('customer'))."' ,
          vehicle='".formatString($action->get_value('vehicleNew'))."' ,
          eventComm='".formatString($action->get_value('eventCommNew'))."' ,
          serieComm='".formatString($action->get_value('serieCommNew'))."' 
                WHERE id='".$action->get_id()."'";


     $oldValues = " Old Values : start_date='".formatString($action->get_value('start_date_old'))."' ,
          end_date='".formatString($action->get_value('end_date_old'))."' ,
          text='".formatString($action->get_value('text_old'))."' ,
          calendar='".formatString($action->get_value('calendar'))."' ,
          personnel='".formatString($action->get_value('personnel'))."' ,
          location='".formatString($action->get_value('location'))."' ,
          customer='".formatString($action->get_value('customer'))."' ,
          vehicle='".formatString($action->get_value('vehicle'))."' ,
          eventComm='".formatString($action->get_value('eventComm'))."' ,
          serieComm='".formatString($action->get_value('serieComm'));

     LogMaster::log($oldValues);

     LogMaster::log($sql);

     $res->autocommit(false);
     $result = $res->query($sql);
     LogMaster::log("Affected Rows: ".$res->affected_rows);
    if($res->affected_rows > 0){
        $change = true;
         $sql = "Update rmscheduler_orkincr.eventsPermanent set serieComm='".formatString($action->get_value('serieComm'))."' 
         where seriesId = ".$action->get_value('seriesId').";";
         $res->query($sql);
         LogMaster::log($sql);

         $empleArra = explode("|",$action->get_value('personnel'));
     $sql = "delete from rmscheduler_orkincr.eventPerson where idEvent = ".$action->get_id().";";
      LogMaster::log($sql);
     $res->query($sql);
     foreach ($empleArra as $emp) {
        if($emp != ""){
          $empArra = explode(":",$emp);
          if(count($empArra) > 1){
            $sql = "insert into rmscheduler_orkincr.eventPerson (idPerson,idEvent) values(".$empArra[1].",".$action->get_id().");";
             LogMaster::log($sql);
            $res->query($sql);
          }
        }
      }

    $equiArra = explode("|",$action->get_value('vehicle'));
     $sql = "delete from rmscheduler_orkincr.eventEquipment where idEvent = ".$action->get_id().";";
      LogMaster::log($sql);
     $res->query($sql);
     foreach ($equiArra as $eq) {
        if($eq != ""){
          $eqArra = explode(":",$eq);
          if(count($eqArra) > 1){
            $sql = "insert into rmscheduler_orkincr.eventEquipment (idEquipment,idEvent) values(".$eqArra[1].",".$action->get_id().");";
             LogMaster::log($sql);
            $res->query($sql);
          }
        }
      }

     $actiArra = explode("|",$action->get_value('calendar'));
     $sql = "delete from rmscheduler_orkincr.eventActivity where idEvent = ".$action->get_id().";";
     LogMaster::log($sql);
     $res->query($sql);
     foreach ($actiArra as $acti) {
        if($acti != ""){
          $sql = "Select id from rmscheduler_orkincr.organizationActivities where description = '".formatString($acti)."';";
           LogMaster::log($sql);
          $result2 = $res->query($sql);
          if ($result2->num_rows > 0) {
            $idActivity = 0;
            while($row = $result2->fetch_assoc()) {
              $idActivity = $row['id'];
            }
            $sql = "insert into rmscheduler_orkincr.eventActivity (idActivity,idEvent) values(".$idActivity.",".$action->get_id().");";
             LogMaster::log($sql);
            $res->query($sql);
          }
        }
      }
      }
       

     
    if (!$res->commit()) {
       LogMaster::log("rollback");
      $res->rollback();
      $change = false;
    }
     $res->autocommit(true);
     if($change){
      LogMaster::log("Success!");
      $action->success();
     }else{
        if($res->error == ""){
          LogMaster::log("No hubo actualizacion.");
          $action->set_status("samevalues");
        }else{ 
          LogMaster::log($res->error);
          $action->error();
        }
     }
 };
 
 function myDelete($action){
    $table = $_GET['eventbl'];
    $sql = "DELETE FROM ".$table." WHERE id='".$action->get_id()."'";
    $res = db ();
    $result = $res->query($sql);
    if($res->affected_rows > 0){
      LogMaster::log($sql);
      LogMaster::log("Success!");
      $action->success();
     }else{
        LogMaster::log($sql);
        if($res->error == ""){
          LogMaster::log("No se encontro el evento a borrar.");
          $action->set_status("notfound");
        }else{
          LogMaster::log($res->error);
          $action->error();
        }
     }
 };
 
 function db () {
    static $conn;
    if ($conn===NULL){ 
        $conn = new mysqli('localhost','orkindb','rmschpsw1','rmscheduler_orkincr'); 
        $conn->set_charset("utf8");
    }
    return $conn;
}

function formatString($string){
    $conn = db();

    $newString = preg_replace("/(\|)\\1+/", "$1", $string);
    $newString = preg_replace('/[[:cntrl:]]/', '', $newString);
    $newString = $conn->real_escape_string($newString);

    return $newString;
}
 
  

?>
