<?php
/*
  Plugin Name: tickets by rainysoft
  Version: 0.1
  Description: Write data to database on display tickets 
  Author: Rainysoft
  Author URI: http://www.rainysoft.com/
 */


/* Tworzymy tabele do db */ 
   function rs_tickets_install() {
    global $wpdb;
    $prefix = $wpdb->prefix;
    $rs_tickets_tablename = $prefix . "rs_tickets";
 
    $rs_tickets_db_version = "1.0";
 
    if ($wpdb->get_var("SHOW TABLES LIKE '" . $rs_tickets_tablename . "'") != $rs_tickets_tablename) {
        $query = "CREATE TABLE " . $rs_tickets_tablename . " ( 
        id bigint(20) NOT NULL AUTO_INCREMENT,
        post_id bigint(20) NOT NULL, 
        user_id bigint(20) NOT NULL, 
        title varchar(250) NOT NULL,  
        text varchar(250) NOT NULL,  
        priority varchar(250) NOT NULL, 
        img_url varchar(250) NOT NULL, 
        feedback varchar(250) NOT NULL, 
        PRIMARY KEY  (id)
        )";
 
        $wpdb->query($query);
 
        add_option("rs_tickets_db_version", $rs_tickets_db_version);
        add_option( 'rs_tickets_speed', '2000' );
        add_option( 'rs_tickets_interval', '2000');
        add_option( 'rs_tickets_type', 'vertical');
    }

}

register_activation_hook(__FILE__, 'rs_tickets_install');

/* deinstalacja wtyczki, skutkuje utratą danych ponieważ usuwa tabele */ 

/**
 * Usuwa tabele bazy danych
 * @global $wpdb $wpdb
 */
function rs_tickets_uninstall() {
    global $wpdb;
    $prefix = $wpdb->prefix;
    $rs_tickets_tablename = $prefix . "rs_tickets";
    $query ='DROP TABLE '.$rs_tickets_tablename;
        $wpdb->query($query);
}
register_deactivation_hook(__FILE__, 'rs_tickets_uninstall');

/*ładowanie plików */

add_action( 'wp_enqueue_scripts', 'rs_tickets_enqueue_scripts' );
function rs_tickets_enqueue_scripts() {

        wp_enqueue_script( 'jq',  'https://code.jquery.com/jquery-3.2.1.min.js', array(), '1.0.0', false );
         wp_enqueue_script( 'rs_tickets',   plugins_url( '/rs_tickets.js', __FILE__ ), array(), '1.0.0', false );

    wp_enqueue_style( 'rs_tickets', plugins_url( '/rs_tickets.css', __FILE__ ) );
  $current_user =  wp_get_current_user();
  $pid =get_the_ID();
  $deps = array('jquery');
  $version= '1.0'; 
  $in_footer = true;
    

  wp_localize_script( 'rs_tickets', 'rstickets', array(
    'ajax_url' => admin_url( 'admin-ajax.php' ),
     'postID' => $pid,
    'userID' => $current_user->ID,
  ));


}

/* zmieniamy docelowy  folder do uploadu plików */ 

/* tworzymy shortcode, który jest ticketsularzem do zbierania danych */

function client_tickets_func( $atts ){
	?>
<div class="row">
    <div class="col-md-12">
      <div class="row row-mar">
        <div class="col-md-6 no-pad">
         <a class="btn zglos_menu" data-toggle="collapse" href="#collapseerrors" aria-expanded="false" aria-controls="collapseExample">
            Zgłoś błędy
          </a>
        </div>
          <div class="col-md-6 no-pad ">
           <a class="btn zglos_menu r-bord" data-toggle="collapse" href="#feedback" aria-expanded="false" aria-controls="collapseExample">
            Lista błędów
          </a>
       </div>
     </div>
    <div class="collapse" id="collapseerrors">
        <form id="upload" method="post" action="#" enctype="multipart/form-data">
          <div class="row">
            <div class="col-md-12">
              <input class="zglos-input-title" id="fb_title" type="text" name="tickets_title" placeholder="skrócona nazwa"/>
            </div>
          </div>
          <div class="row">
            <div class="col-md-12">
              <input class="zglos-input-text" id="fb_content" type="textarea" name="tickets_content" placeholder="treść" />
            </div>
          </div>
          <div class="row">
            <div class="col-md-12">
            <select class="zglos-input-priority" id="fb_priority" name="tickets_priority">
              <option value="natychmiastowy">Natychmiastowy</option>
              <option value="pilny">Pilny</option>
              <option value="standard">Standard</option>
            </select>
          </div>
          </div>
          <div class="row">
            <div class="col-md-12">
              <input class="zglos-input-upload" type="file" name="my_image_upload" id="my_image_upload"  multiple="false" />
                <input type="hidden" name="post_id" id="post_id" value="55" />
             </div>
          </div>
          <div class="row">
            <div class="col-md-12">
           <?php wp_nonce_field( 'my_image_upload', 'my_image_upload_nonce' ); ?>
          <input id="rs_tickets_button" class="btn btn-danger MAR-1" id="submit_my_image_upload" name="submit_my_image_upload" type="submit" value="Prześlij" /> 
          </div>
        </div>
        </form>
      
    </div>
    <div class="collapse" id="feedback">
       <?php show_errors(); ?>
    </div>
  </div>
</div>
<?php



// Check that the nonce is valid, and the user can edit this post.
if ( 
  isset( $_POST['my_image_upload_nonce'], $_POST['post_id'] ) 
  && wp_verify_nonce( $_POST['my_image_upload_nonce'], 'my_image_upload' )
  && current_user_can( 'read_post', $_POST['post_id'] )
) {
  // The nonce was valid and the user has the capabilities, it is safe to continue.

  // These files need to be included as dependencies when on the front end.
  require_once( ABSPATH . 'wp-admin/includes/image.php' );
  require_once( ABSPATH . 'wp-admin/includes/file.php' );
  require_once( ABSPATH . 'wp-admin/includes/media.php' );
  
  // Let WordPress handle the upload.
  // Remember, 'my_image_upload' is the name of our file input in our form above.
  $attachment_id = media_handle_upload( 'my_image_upload', $_POST['post_id'] );
  
  if ( is_wp_error( $attachment_id ) ) {
    // There was an error uploading the image.
  } else {
 //success 
    ?>
      <script>
        window.location = "<?php echo the_permalink(); ?>";
      </script>
    <?php
  }

} else {


  // The security check failed, maybe show the user an error.
}

?>

		</div>
	</div>
<script>
    /* ajax przekazuje dane do funkcji tickets_data */
	$("form#upload").submit(function(e){
   // e.preventDefault();
  var ticketsTitle = $('#fb_title').val();
  var ticketsContent = $('#fb_content').val();
  var ticketsPrior = $('#fb_priority').val();
  var fileInp = $('#my_image_upload').val();
  if(fileInp !== "")
  {
  var name = document.getElementById('my_image_upload'); 
  var aa = name.files.item(0).name;
  var dd = aa.split(' ').join('-');
  }
  else
  {
    var dd = 0;
  }

   var imageUpl = 1;
	jQuery.ajax({
                url : rstickets.ajax_url,
                type : 'post',
                data : {
                  action : 'add_data',
                  tickets_title : ticketsTitle,
                  tickets_content: ticketsContent,
                  tickets_prior: ticketsPrior,
                  post_id : rstickets.postID,
                  user_id: rstickets.userID,
                  img_upl: imageUpl,
                  file_name: dd
                },
          
    

    
                success : function( response ) {
                  if(confirm('Dodano błąd')){
                    window.setTimeout(function(){
                     window.location = "<?php echo the_permalink(); ?>";
                   }, 1000);
               
             
                  
                  }

                }
              
});
});
</script>
<?php 

}
add_shortcode( 'client_tickets', 'client_tickets_func' );

/*funkcja zapisu do db */ 
add_action( 'wp_ajax_nopriv_add_data', 'add_data' );
add_action( 'wp_ajax_add_data', 'add_data' );
function add_data()
{
     global $wpdb; 
       $t_title = $_REQUEST['tickets_title'];  
       $t_content = $_REQUEST['tickets_content']; 
       $t_prior = $_REQUEST['tickets_prior']; 
       $t_post_id = $_REQUEST['post_id']; 
       $t_user_id = $_REQUEST['user_id'];
       $img_u = $_REQUEST['img_upl'];
        $f_name = $_REQUEST['file_name'];
      


       $wpdb->insert("wp_rs_tickets", array(
         "title" =>   $t_title,
         "text" =>  $t_content,
         "priority" =>  $t_prior,
         "post_id" =>  $t_post_id,
         "user_id" =>  $t_user_id,
         "img_url" =>  $f_name,
         "feedback" => 0,

    )); 

   if ( defined( 'DOING_AJAX' ) && DOING_AJAX ) { 
    die();
  }
  
  else {
    wp_redirect( get_permalink( $_REQUEST['post_id'] ) );
    exit();
  }
}


function show_errors()
{
    global $wpdb;
    $pid = get_the_id(); 
    $current_user =  wp_get_current_user();
    $fbcs = $wpdb->get_results( "SELECT id, post_id, user_id, title, text, priority, img_url, feedback FROM wp_rs_tickets WHERE user_id = $current_user->ID AND post_id = $pid" );

    foreach ($fbcs as $fbc)
    {
      ?>
      <a class="btn zglos_blad" data-toggle="collapse" href="#<?php echo 'tic'.$fbc->id; ?>" aria-expanded="false" aria-controls="collapseExample">
        <?php echo $fbc->title; ?>
      </a>
      <div class="collapse" id="<?php echo 'tic'.$fbc->id; ?>">
        <?php if($fbc->img_url !== "0") { ?>
        <div class="row error-help">
          Screenshot
        </div>
        <div class="row col-row pic-align">
          <img class="img-responsive error-pic" src="http://skilltest.com.pl/wp-content/uploads/<?php echo $fbc->img_url; ?>">
        </div>
        <?php }?>
        <div class="row error-help">
          Treść błędu
        </div>
        <div class="row error-text ">
          <?php echo $fbc->text; ?>
        </div>
        <div class="row error-help">
         Priorytet
        </div>
        <div class="row error-text">
         <?php echo $fbc->priority; ?>
        </div>
        <div class="row error-help">
          Feedback
        </div>
        <div class="row error-text">
         <?php 
          if ($fbc->feedback !== "0"){
         echo $fbc->feedback;
       } ?>
        </div>
      </div>
      <?php
     
    }

}
/* Podstrona w panelu admina */ 
/* opcja wyświetlania błędów oraz dodawania feedbacku */
 add_action('admin_menu', 'rs_tickets_setup_menu');
function rs_tickets_setup_menu(){


  add_menu_page( 'RS tickets', 'RS tickets', 'manage_options', 'rstickets-plugin', 'rstickets_init' );
}

function rstickets_init()
{
 global $wpdb;
   wp_enqueue_script( 'jq',  'https://code.jquery.com/jquery-3.2.1.min.js', array(), '1.0.0', false );
         wp_enqueue_script( 'rs_tickets',   plugins_url( '/rs_tickets.js', __FILE__ ), array(), '1.0.0', false );

    wp_enqueue_style( 'rs_tickets', plugins_url( '/rs_tickets.css', __FILE__ ) );
   $deps = array('jquery');
  $version= '1.0'; 
  $in_footer = true;
    

  wp_localize_script( 'rs_tickets', 'rstickets', array(
    'ajax_url' => admin_url( 'admin-ajax.php' )
  ));
   ?>  

  <link rel='stylesheet'   href='<?php echo get_template_directory_uri()?>/assets/css/bootstrap.min.css' type='text/css' media='all' />
  <script
  src="https://code.jquery.com/jquery-3.2.1.min.js"
  integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4="
  crossorigin="anonymous">
  </script>
  <script
  src="<?php echo get_template_directory_uri();?>/assets/js/bootstrap.min.js">
  </script>
  <div class="container-fluid">
    <div class="container">
      <div class="row">
        <h1>Feedback użytkowników</h1><br>
      </div>
      <div class="row">
      <?php
      $users  = $wpdb->get_results( "SELECT distinct user_id FROM wp_rs_tickets" );

      foreach ($users as $user)
      {
        $us_fb = $wpdb->get_results( "SELECT id, user_id, post_id, title, text, priority, feedback FROM wp_rs_tickets WHERE user_id = $user->user_id" );
        $u_nam = $wpdb->get_row( "SELECT user_login FROM wp_users WHERE  ID = $user->user_id" );
        
        ?>
        <a class="btn btn-primary" data-toggle="collapse" href="#fb<?php echo $user->user_id;?>" aria-expanded="false" aria-controls="collapseExample">
    <?php echo "ID: ".$user->user_id." "; echo "Login: ".$u_nam->user_login?>
  </a>
    </div>
    <div class="row">
      <div class="collapse" id="fb<?php echo $user->user_id;?>">
        <div class="col-md-1">
                User id
              </div>
            <div class="col-md-1">
                 Post id
              </div>
              <div class="col-md-2">
                 Tytuł
              </div>
               <div class="col-md-2">
                 Treść
              </div>
              <div class="col-md-2">
                 Priorytet
              </div>
               <div class="col-md-2">
                 Feedback
              </div>
              <div class="col-md-2">
                 Dodaj feedback
              </div>
      
        <?php


          foreach ($us_fb as $us)
          {
            ?>
            <div class="col-md-1">
                 <?php echo $us->user_id."<br>";?>
              </div>
            <div class="col-md-1">
                 <?php echo $us->post_id."<br>";?>
              </div>
              <div class="col-md-2">
                 <?php echo $us->title."<br>";?>
              </div>
               <div class="col-md-2">
                 <?php echo $us->text."<br>";?>
              </div>
              <div class="col-md-2">
                 <?php echo $us->priority."<br>";?>
              </div>
               <div class="col-md-2">
                 <?php echo $us->feedback."<br>";?>
              </div>
              <div class="col-md-2">
                  <div class="row">
                    <form>
                      <input type="text" id="input<?php echo $us->id;?>" name="input<?php echo $us->id;?>"/>
                    </form>
                 </div>
                 <div class="row">
                  <a class="btn btn-danger"  id="do_fb<?php echo $us->id;?>">Wprowadź</a>
                 </div>
              </div>
              <script>
                $('#do_fb<?php echo $us->id;?>').click(function(){
             
                    var id =<?php echo $us->id;?> ; 
                    var inp = $('#input<?php echo $us->id;?>').val();
                    jQuery.ajax({
                    url : rstickets.ajax_url,
                    type : 'post',
                    data : {
                      action : 'add_feedback',
                      tid: id,
                      addFB: inp

                    },
              
        

        
                    success : function( response ) {
                  //   alert("pomyślnie dodano zadanie" + response);
                         if(confirm('Dodano feedback')){
                    window.location.reload();  
}
                   
                 
                      
                      }

                    }
                  );
                });
              </script>
            <?php
          }
          ?>
          </div>
          <?php

      }
    ?>
    </div>
  </div>
</div>
<?php


  }

add_action( 'wp_ajax_nopriv_add_feedback', 'add_feedback' );
add_action( 'wp_ajax_add_feedback', 'add_feedback' );
  function add_feedback()
  {
     global $wpdb; 
    $id = $_REQUEST['tid'];
    $fb = $_REQUEST['addFB'];

$wpdb->update( 
  'wp_rs_tickets', 
  array( 
    'feedback' => $fb
  ), 
  array( 'id' => $id ), 
  array( 
    '%s', // value1
    '%d'  // value2
  ), 
  array( '%d' ) 
);

echo "sdcsdsd".$id;


  if ( defined( 'DOING_AJAX' ) && DOING_AJAX ) { 
    die();
  }
  
  else {
    wp_redirect( get_permalink( $_REQUEST['post_id'] ) );
    exit();
  }
  }

  function liczba_bledow()
  {
    global $wpdb;
   $current_user =  wp_get_current_user();
   $idd = get_the_id();

    $res = $wpdb->get_var("SELECT count(id)  FROM wp_rs_tickets  WHERE post_id = $idd AND user_id=  $current_user->ID");

 return $res;

  }

  function liczba_fb()
  {
    global $wpdb;
   $current_user =  wp_get_current_user();
   $idd = get_the_id();

    $res = $wpdb->get_var("SELECT count(feedback)  FROM wp_rs_tickets  WHERE post_id = $idd AND user_id=  $current_user->ID AND feedback NOT LIKE '0'");

    return $res; 
    
  }