<?php
/*
  Plugin Name: Quiz by rainysoft
  Version: 0.1
  Description: Adds quiz to post, count points for each user
  Author: Rainysoft
  Author URI: http://www.rainysoft.com/
 */

  /* rejestracja tabeli -  pytani do quizu, odpowiedzi użytkowników */ 



  function qplu_install() {
    global $wpdb;
    $prefix = $wpdb->prefix;
    $qplu_tablename = $prefix . "quiz_content";
    $qplu_tablename2 = $prefix . "quiz_results";
 
    $qplu_db_version = "1.0";
 
    if ($wpdb->get_var("SHOW TABLES LIKE '" . $qplu_tablename . "'") != $qplu_tablename) {
        $query = "CREATE TABLE " . $qplu_tablename . " ( 
        q_id bigint(20) NOT NULL AUTO_INCREMENT, 
        post_id bigint(20) NOT NULL,
        question varchar(250) NOT NULL,  
        answer_1 varchar(250) NOT NULL,  
        answer_2 varchar(250) NOT NULL, 
        answer_3 varchar(250) NOT NULL, 
        answer_4 varchar(250) NOT NULL, 
        correct_answer int(9) NOT NULL, 
        PRIMARY KEY  (q_id)
        )";
 
        $wpdb->query($query);
 
        add_option("qplu_db_version", $qplu_db_version);
        add_option( 'qplu_speed', '2000' );
        add_option( 'qplu_interval', '2000');
        add_option( 'qplu_type', 'vertical');
    }
     if ($wpdb->get_var("SHOW TABLES LIKE '" . $qplu_tablename2 . "'") != $qplu_tablename2) {
        $query = "CREATE TABLE " . $qplu_tablename2 . " ( 
        r_id bigint(20) NOT NULL AUTO_INCREMENT, 
        user_id bigint(20) NOT NULL, 
        quiz_id bigint(20) NOT NULL, 
        post_id bigint(20) NOT NULL,
      	points  bigint(20) NOT NULL,
      	points_sum  bigint(20) NOT NULL,
        PRIMARY KEY  (r_id)
        )";
 
        $wpdb->query($query);
 
        add_option("qplu_db_version", $qplu_db_version);
        add_option( 'qplu_speed', '2000' );
        add_option( 'qplu_interval', '2000');
        add_option( 'qplu_type', 'vertical');
    }
}

register_activation_hook(__FILE__, 'qplu_install');

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

/**
 * Usuwa tabele bazy danych
 * @global $wpdb $wpdb
 */
function qplu_uninstall() {
    global $wpdb;
    $prefix = $wpdb->prefix;
    $qplu_tablename = $prefix . "quiz_content";
    $qplu_tablename2 = $prefix . "quiz_results";
   /* $query ='DROP TABLE '.$qplu_tablename;
    $query2 ='DROP TABLE '.$qplu_tablename2;
        $wpdb->query($query);
        $wpdb->query($query2); */
}
register_deactivation_hook(__FILE__, 'qplu_uninstall');


/*ładowanie plików */

add_action( 'wp_enqueue_scripts', 'rs_quiz_enqueue_scripts' );
function rs_quiz_enqueue_scripts() {
  if( is_single() ) {
        wp_enqueue_script( 'jq',  'https://code.jquery.com/jquery-3.2.1.min.js', array(), '1.0.0', false );

    wp_enqueue_style( 'rs_quiz', plugins_url( '/rs_quiz.css', __FILE__ ) );
  }



}


/* zakłądka w panelu admina  RS quiz */
add_action('admin_menu', 'rs_quiz_setup_menu');
 
function rs_quiz_setup_menu(){


  add_menu_page( 'RS quiz', 'RS quiz', 'manage_options', 'rsquiz-plugin', 'rsquiz_init' );
}
 
 /* zawartość zakładki RS quiz - funkcja usuwani quizu  */
function rsquiz_init()
{
 global $wpdb;
  wp_enqueue_script( 'rs_quiz', plugins_url( '/rs_quiz.js', __FILE__ ), array('jquery'), '1.0', true );
  $quizes = $wpdb->get_results( "SELECT question, q_id FROM wp_quiz_content" );
  $deps = array('jquery');
  $version= '1.0'; 
  $in_footer = true;
    

  wp_localize_script( 'rs_quiz', 'rsquiz', 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>
<div class="row"><h1> Dodane quizy</h1><br></div>
  <?php
 
 
foreach ($quizes as $quizes)
{
   echo '<div class="row"><div class="col-md-4">'. $quizes->question. '</div>';
   echo '<div class="col-md-4">  [quiz type ='. $quizes->q_id. ']</div><div class="col-md-3"><a class="btn btn-danger"  id="delrow'.$quizes->q_id.'">Usuń</a></div></div>'; 
   ?>
  <script>
  $("#delrow<?php echo $quizes->q_id;?>").click( function()
  {

   var post_id = jQuery(this).data('id');
              var q_idd = <?php echo $quizes->q_id;?>;
              jQuery.ajax({
                url : rsquiz.ajax_url,
                type : 'post',
                data : {
                  action : 'delete_quiz',
                  quiz_id : q_idd 
                  

                },
                success : function( response ) {
                  
                 // return response;
             
                  if(confirm('Pomyślnie usunięto element')){
                    window.location.reload();  
}

                }
              })});
</script>

  <?php 
 }

   

             
}
/* funkcja którą ma wczytywać ajax i usuwać pojedynczy wiersz */
add_action( 'wp_ajax_nopriv_delete_quiz', 'delete_quiz' );
add_action( 'wp_ajax_delete_quiz', 'delete_quiz' );
function delete_quiz()
{
    global $wpdb; 

 $qid = $_REQUEST['quiz_id'];
$wpdb->delete( 'wp_quiz_content', array( 'q_id' => $qid ) );
$wpdb->delete( 'wp_quiz_results', array( 'quiz_id' => $qid ) );
    if ( defined( 'DOING_AJAX' ) && DOING_AJAX ) { 
    die();
  }
  
  else {
    wp_redirect( get_permalink( $_REQUEST['post_id'] ) );
    exit();
  }
}

/*shortcode  [quiz type = $type] można wrzucać quiz przez shortcode, równocześnie plugin wrzuca sam */ 
function quiz_shortcode($type) 
{
  extract(shortcode_atts(array(
    'type' => 'type'), $type)); 
  global $wpdb; 

  $qu = $wpdb->get_row( "SELECT correct_answer, question, q_id, answer_1, answer_2, answer_3, answer_4   FROM wp_quiz_content
  WHERE q_id = $type",  OBJECT );  
  $qid = $qu->q_id; 
?>

  <div class="row quiz-border">
    <div class="col-xs-11 col-sm-8 col-md-10 col-xs-offset-1 col-sm-offset-2 col-md-offset-1">
      <div class="row quiz-quest">
        <?php echo $qu->question; ?>
      </div>
      <div id="<?php echo "".$qid."1"; ?>" class="row quiz-radio ">
        <form id="ww">
           <?php if (!empty($qu->answer_1)){?>
        <input  class="<?php echo "but".$qid."1"; ?>" type="radio" name="gender" value="odp1" > <?php echo $qu->answer_1;} ?></input>
      </div>
      <div id="<?php echo "".$qid."2"; ?>" class="quiz-radio row">
         <?php if (!empty($qu->answer_2)){?>
        <input  class="<?php echo "but".$qid."2"; ?>" type="radio" name="gender" value="odp2"> <?php echo $qu->answer_2; } ?>
      </div>
      <div id="<?php echo "".$qid."3"; ?>"  class="quiz-radio row">
         <?php if (!empty($qu->answer_3)){?>
        <input class="<?php echo "but".$qid."3"; ?>" type="radio" name="gender" value="odp3"> <?php echo $qu->answer_3; }?>
      </div>
      <div id="<?php echo "".$qid."4"; ?>" class="quiz-radio row">
        <?php if (!empty($qu->answer_4)){?>
        <input  class=" <?php echo "but".$qid."4"; ?>" type="radio" name="gender" value="odp3"> <?php echo $qu->answer_4;  } ?> 
      </div>
        <div class="quiz-button" id="<?php echo "qb".$qid."";?>" value="Click me">Zapisz i sprawdź</div>
      </form>
      </div>
    </div>


  <?php   


  wp_enqueue_script( 'rs_quiz', plugins_url( '/rs_quiz.js', __FILE__ ), array('jquery'), '1.0', true );
 
         
  $current_user =  wp_get_current_user();
  $pid =get_the_ID();
  $deps = array('jquery');
  $version= '1.0'; 
  $in_footer = true;
    

  wp_localize_script( 'rs_quiz', 'rsquiz', array(
    'ajax_url' => admin_url( 'admin-ajax.php' ),
    'postID' => $pid,
    'userID' => $current_user->ID,
    'quizID' => $ss
  ));
   $post1 = get_post(); $post2= $post1->ID; 
   /* skrypt quizu w jquery */
   ?>

  <script>
    $("#<?php echo "".$qid."1"; ?>").click(function(){
        $(this).find("input:radio").prop('checked', true);
    });
      $("#<?php echo "".$qid."2"; ?>").click(function(){
        $(this).find("input:radio").prop('checked', true);

    });
      $("#<?php echo "".$qid."3"; ?>").click(function(){
        $(this).find("input:radio").prop('checked', true);

    });
        $("#<?php echo "".$qid."4"; ?>").click(function(){
        $(this).find("input:radio").prop('checked', true);

    });









    $('<?php echo "#qb".$qid."";?>').click(function() {

     var dbplace = <?php echo $qu->correct_answer; ?> // pobiera z database odpowiedź w formie 1,2,3 bądź 4
     var answer = "#<?php echo $qid; ?>" + dbplace;
     var ans = ["#<?php echo $qid; ?>1" , "#<?php echo $qid; ?>2", "#<?php echo $qid; ?>3", "#<?php echo $qid; ?>4"];

    for(var j= 0; j<= ans.length; j++)
    {
      $(ans[j-1]).removeClass("qufalse");
      $(ans[j-1]).removeClass("qutrue");
    }


    for (var i=0; i<=ans.length; i++)
    {

       if($("<?php echo ".but".$qid.""; ?>"+ i).is(':checked' )) 
      { 

        if(ans[i-1] === answer)
        {
        $(ans[i-1]).addClass("qutrue"); 
        //alert("<?php echo $qid; ?>");
          var post_id = jQuery(this).data('id');
          var qty =   <?php echo $type; ?>;
              jQuery.ajax({
                url : rsquiz.ajax_url,
                type : 'post',
                data : {
                  action : 'post_results',
                  post_id : rsquiz.postID,
                  user_id: rsquiz.userID,
                  quiz_id: qty


                },
                success : function( response ) {
                  return response ;
                }
              });
        }
        else
        {
          $(ans[i-1]).addClass("qufalse"); 
         
        }

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

}
add_shortcode('quiz', 'quiz_shortcode'); 

add_action( 'wp_ajax_nopriv_post_results', 'post_results' );
add_action( 'wp_ajax_post_results', 'post_results' );
function post_results()
{


  global $wpdb; 

  $pos_id = $_REQUEST['post_id'];  
  $user_id = $_REQUEST['user_id'];  
  $qui_id = $_REQUEST['quiz_id'];  
  
  $current_user =  wp_get_current_user();
  $once = $wpdb->get_row("SELECT quiz_id, post_id, user_id FROM wp_quiz_results  WHERE quiz_id = $qui_id and user_id = $user_id");

  if(empty($once->quiz_id) === true  )
  {
            
      $wpdb->insert("wp_quiz_results", array(
         "quiz_id" =>   $qui_id,
       "user_id" =>  $user_id ,
        "post_id" =>  $pos_id,
        "points" => 1,
        "points_sum" => 1,
    )); 
  }

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

/* wyświetl formularz w widoku single editor */ 

function quiz_meta_box_markup()
{
   global $wpdb;


    ?> 
<script
  src="https://code.jquery.com/jquery-3.2.1.min.js"
  integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4="
  crossorigin="anonymous"></script>
  <script
  src="<?php echo plugin_dir_url( __FILE__ ) .'quiz-scripts.js'?>"></script>
    <form id="33bn">
      <input class="insq" id="pyt" type="text" name="pytanie" value="" placeholder="Pytanie"/ >
      <input class="insq" id="odpow1" type="text" name="odp1" placeholder="Odpowiedź 1"/ >
      <input class="insq" id="odpow2" type="text" name="odp2" placeholder="Odpowiedź 2"/ >
      <input  class="insq" id="odpow3" type="text" name="odp3" placeholder="Odpowiedź 3"/ >
      <input class="insq" id="odpow4" type="text" name="odp4" placeholder="Odpowiedź 4"/ >
      <br>Poprawna odpowiedź (numer) <br> <input class="insq" id="corr1" type="number" name="correct" min="1" max="4">
      <a class=""  id="submit-quiz" value="Dodaj">send</a>

    </form>

    <?php 
      wp_enqueue_script( 'rs_quiz', plugins_url( '/rs_quiz.js', __FILE__ ), array('jquery'), '1.0', true );
 
         
          $current_user =  wp_get_current_user();
        $pid =get_the_ID();
        $deps = array('jquery');
        $version= '1.0'; 
        $in_footer = true;
    
    

  wp_localize_script( 'rs_quiz', 'rsquiz', array(
    'ajax_url' => admin_url( 'admin-ajax.php' ),
    'postID' => $pid
   

   
  ));
  /* ajax zapisu do db */
  ?>
<script>
  $("#submit-quiz").click( function()
  {

   var post_id = jQuery(this).data('id');
      var quest = $("#pyt").val();
      var odpow1 = $("#odpow1").val();
      var odpow2 = $("#odpow2").val();
      var odpow3 = $("#odpow3").val();
      var odpow4 = $("#odpow4").val();
      var corr = $("#corr1").val();
              jQuery.ajax({
                url : rsquiz.ajax_url,
                type : 'post',
                data : {
                  action : 'post_form',
                  post_id : rsquiz.postID,
                  odp_1 :  odpow1,
                  odp_2 :  odpow2,
                  odp_3 :  odpow3,
                  odp_4 :  odpow4,
                  correct_ans : corr,
                  question :  quest


                },
                success : function( response ) {
                  $('.insq').val("");
                  alert("pomyślnie dodano zadanie");
                  jQuery('#submit-quiz').text( response );
                }
              })});
</script>

    <?php
    
}

/* dodanie okienek do poszczególnych lekcji */
function add_quiz_meta_box()
{
    add_meta_box("demo-meta-box", "Quiz Meta Box", "quiz_meta_box_markup", "lekcja_1", "side", "high", null);
    add_meta_box("demo-meta-box", "Quiz Meta Box", "quiz_meta_box_markup", "lekcja_2", "side", "high", null);
     add_meta_box("demo-meta-box", "Quiz Meta Box", "quiz_meta_box_markup", "lekcja_3", "side", "high", null);
     add_meta_box("demo-meta-box", "Quiz Meta Box", "quiz_meta_box_markup", "lekcja_4", "side", "high", null);
     add_meta_box("demo-meta-box", "Quiz Meta Box", "quiz_meta_box_markup", "lekcja_5", "side", "high", null);
     add_meta_box("demo-meta-box", "Quiz Meta Box", "quiz_meta_box_markup", "lekcja_6", "side", "high", null);

}

add_action("add_meta_boxes", "add_quiz_meta_box");
add_action( 'wp_ajax_nopriv_post_form', 'post_form' );
add_action( 'wp_ajax_post_form', 'post_form' );
/*funkcja zapisująca do db wczytywana przez ajax */ 
function post_form()
{


  global $wpdb; 
  $quiz = $wpdb->get_results( "SELECT question, q_id FROM wp_quiz_content" );
  $qu = $wpdb->get_row( "SELECT correct_answer, question, q_id, answer_1, answer_2, answer_3, answer_4   FROM wp_quiz_content
  WHERE q_id = $type",  OBJECT );  
  $qid = $qu->q_id; 
   $post1 = get_post(); $post2= $post1->ID; 

   $pos_id = $_REQUEST['post_id'];  
   $odp1 = $_REQUEST['odp_1'];  
   $odp2 = $_REQUEST['odp_2'];  
  $odp3 = $_REQUEST['odp_3'];
  $odp4 = $_REQUEST['odp_4'];
  $cora = $_REQUEST['correct_ans'];
  $quest = $_REQUEST['question'];
 
    
      
           
   $wpdb->insert("wp_quiz_content", array(
    "post_id" =>  $pos_id,
   "question" =>   $quest,
   "answer_1" => $odp1,
   "answer_2" => $odp2,
   "answer_3" => $odp3,
   "answer_4" => $odp4,
   "correct_answer" => $cora , 

));

       
  if ( defined( 'DOING_AJAX' ) && DOING_AJAX ) { 
    echo "send";
    die();
  }
  
  else {
    wp_redirect( get_permalink( $_REQUEST['post_id'] ) );
    exit();
  }
}
/* funkcja wrzucania streamu quziów dla dla danego posta */ 
function quiz_in_modal()
{

   global $wpdb;
   $p_id = get_the_id();
   $quizy = $wpdb->get_results( "SELECT question, q_id, post_id FROM wp_quiz_content WHERE post_id = $p_id");

   foreach ( $quizy as $quizy ) 
   {
      echo do_shortcode('[quiz type ='.$quizy->q_id.']'); 
   } 



}
/* liczy ilość wytworzonych quizów na post */
function post_quiz_num()
{
  global $wpdb;
  $idd = get_the_id();
  $current_user =  wp_get_current_user();

  $isdon = $wpdb->get_var("SELECT count(q_id)  FROM wp_quiz_content  WHERE post_id = $idd");

  return $isdon;
}
/* liczy ilość wykonanych quizów przez użytkownika w danym post_id */
function quiz_done_num()
{
  global $wpdb;
   $current_user =  wp_get_current_user();
   $idd = get_the_id();
    $res = $wpdb->get_var("SELECT count(quiz_id)  FROM wp_quiz_results  WHERE post_id = $idd AND user_id=  $current_user->ID");
 return $res;
}

function check_all()
{
  ?>
<a class="quiz-button"  id="save_all">Zapisz i sprawdź </a> 

  <?php
global $wpdb;
   $current_user =  wp_get_current_user();
   $idd = get_the_id();
$qcon  = $wpdb->get_results( "SELECT q_id FROM wp_quiz_content WHERE post_id = $idd" );

      foreach ($qcon as $qc)
      {
        
        ?>
        <script>
          $('<?php echo "#qb".$qc->q_id."";?>').hide();
          $('#save_all').click(function(){
              $('<?php echo "#qb".$qc->q_id."";?>').click();

          });
        </script>
        <?php
      }

}
add_shortcode( 'check', 'check_all' );