<?php 

function cp_load_dependencies() {
  spl_autoload_register(function($class_name) {
    $file = ABSPATH."contents/plugins/classroom_plus/classes/class-".$class_name.".php";
    if(file_exists($file)) include $file;
  });
}

function cp_course_outline_filter() {
	global $post_meta;
  $all_class = get_select_options_from_post(['type' => 'class'], 'class_name');
  $all_category = get_select_options_from_post(['type' => 'category'], 'category_name');

  $selOptions = array();

  if(isset($_POST['class']) && isset($_POST['category'])) {
    $options = get_class_courses($_POST['class'], $_POST['category'], false, false);
    if(_count($options)) {
      foreach ($options as $course_id => $course_name) {
        $selOptions[$course_name] = $course_id;
      }
    }
  }
  $terms = ['First' => 1, 'Second' => 2, 'Third' => 3];
  $class = isset($_POST['class']) ? $_POST['class'] : $_GET['class'];
  $course = isset($_POST['course']) ? $_POST['course'] : $init_course;
  $category = isset($_POST['category']) ? $_POST['category'] : reset($all_category);
  $term = isset($_POST['term']) ? $_POST['term'] : 1;
  
  ?>
  <div class="panel panel-custom bg-white">
    <div class="panel-heading">
      <!-- <h1>Search</h1> -->
    </div>
    <div class="panel-body instruction">
      <form id="search-form" method="post">
      <div class="row mb-4">
        <div class="col-md-3">
          <?php select(['label' => 'Class', 'name' => 'class', 'id' => 'in_class', 'data-form' => 'search-form', 'required' => 'required'], $all_class, $class); ?>
        </div>
        <div class="col-md-3">
          <?php select(['label' => 'Category', 'name' => 'category', 'id' => 'in_category', 'data-form' => 'search-form', 'required' => 'required'], $all_category, $category); ?>
        </div>
        <div class="col-md-3">
          <?php select(['label' => 'Subject/Course', 'name' => 'course', 'id' => 'in_course', 'data-form' => 'search-form', 'required' => 'required'], $selOptions , $course); ?>
        </div>
        <div class="col-md-3">
          <?php select(['label' => 'Term', 'name' => 'term', 'id' => 'in_term', 'data-form' => 'search-form', 'required' => 'required'], $terms , $term); ?>
        </div>
		    <div class="col-md-3">
          <button id="search-query-btn" type="submit" class="btn btn-primary mt-3">Get Contents</button>
        </div>
        <div class="col-md-9" id="create-new" style="display: none;">
          <ul class="nav nav-pills justify-content-end">
              <li class="nav-item dropdown mr-2 mr-md-0">
                <a href="javaScript:void(0);" class="nav-link py-2 px-3 active" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
                  <span class="d-none d-md-block"><i class="ni ni-fat-add mr-2"></i>Create New</span>
                  <span class="d-md-none"><i class="ni ni-fat-add"></i></span>
                </a>
                <div class="dropdown-menu  dropdown-menu-right">
                  <a href="cp-add-lesson" class="dropdown-item pt-1 pb-1 popmeup" id="add-lesson" data-width=700 data-height=500>
                    <i class="ni ni-tv-2"></i>
                    <span>Lesson</span>
                  </a>
                  <a href="cp-add-quiz" class="dropdown-item pt-1 pb-1 popmeup" id="add-quiz" data-width=800 data-height=500>
                    <i class="ni ni-ruler-pencil"></i>
                    <span>Quiz/Test</span>
                  </a>
              </li>
          </ul>
        </div>
      </div> 
      </form> 
    </div>
  </div>
  <?php
  add_page_javascript('contents/plugins/classroom_plus/js/course-outline-filter.js');
  add_page_javascript('app/assets/js/page-scripts/js-functions.js');
}

function cp_view_lesson_header() {
  $id = $_GET['id'];
  if(current_user_can('cp_attach_lesson_material')) :
  ?>
  <ul class="nav nav-pills justify-content-end">
    <li class="nav-item dropdown mr-2 mr-md-0">
      <a href="javaScript:void(0);" class="nav-link py-2 px-3 active" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
        <span class="d-none d-md-block"><i class="ni ni-fat-add mr-2"></i>CREATE</span>
        <span class="d-md-none"><i class="ni ni-fat-add"></i></span>
      </a>
      <div class="dropdown-menu  dropdown-menu-right">
        <a href="attach-lesson-material?id=<?php echo $id ?>" class="dropdown-item pt-1 pb-1 popmeup" data-width=700 data-height=500>
          <i class="ni ni-single-copy-04"></i>
          <span>Material</span>
        </a>
        <a href="attach-lesson-material-link?id=<?php echo $id ?>" class="dropdown-item pt-1 pb-1 popmeup" data-width=700 data-height=500>
          <i class="fas fa-link"></i>
          <span>Link</span>
        </a>
        <a href="cp-add-assignment?id=<?php echo $id ?>" class="dropdown-item pt-1 pb-1 popmeup" data-width=700 data-height=500>
          <i class="ni ni-ruler-pencil"></i>
          <span>Assignment</span>
        </a>
        <div class="dropdown-divider"></div>
        <a href="curriculum" class="dropdown-item pt-1 pb-1">
          <i class="ni ni-paper-diploma"></i>
          <span>New Lesson</span>
        </a>
      </div>
    </li>
  </ul>
  <?php
  endif;
  global $post_meta;
  add_page_javascript('app/assets/js/page-scripts/js-functions.js');
}

function attach_lesson_material_header() {
  ?>
  <ul class="nav nav-pills justify-content-end">
    <li class="nav-item mr-2 mr-md-0">
      <button class="btn btn-primary" onclick="$('#submit-attach_lesson_material').click();">
        <span class="btn-inner--icon"><i class="ni ni-user-run"></i></span>
        <span class="btn-inner--text">Publish</span>
      </button>
    </li>
  </ul>
  <?php
}

function cp_get_lessons($args) {
  $subjects = get_class_courses($args['class'], $args['category'], false, false);
  ?>
  <div class="row">
    <?php if (is_array($subjects)): ?>
      <?php if (_count($subjects)): ?>
        <?php foreach ($subjects as $id => $name): ?>
          <div class="col-lg-3 col-md-4 col-sm-6">
            <div class="card shadow">
              <div class="card-img-top-container">
                <img class="card-img-top" src="<?php echo cp_get_random_banner(); ?>" alt="Card image cap">
                <div class="card-labels">
                  <p><?php echo $name ?></p>
                </div>
              </div>
            
              <div class="card-body">
                  <ul class="nav nav-pills justify-content-end">
                    <li class="nav-item dropdown mr-2 mr-md-0">
                      <a href="javaScript:void(0);" class="nav-link py-2 px-3 active" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
                        <span class="d-none d-md-block"><i class="ni ni-fat-add mr-2"></i>Join Class</span>
                        <span class="d-md-none"><i class="ni ni-fat-add"></i></span>
                      </a>
                      <div class="dropdown-menu  dropdown-menu-right">
                        <a href="cp-select-topic?subject=<?php echo $id; ?>&class=<?php echo $args['class'] ?>" class="dropdown-item pt-1 pb-1">
                          <i class="ni ni-tv-2"></i>
                          <span>Select Topic</span>
                        </a>
                        <a href="#" class="dropdown-item pt-1 pb-1">
                          <i class="ni ni-ruler-pencil"></i>
                          <span>Assignments</span>
                        </a>
                    </li>
                  </ul>
              </div>
            </div>
          </div>
        <?php endforeach ?>
      <?php endif ?>
    <?php endif ?>
  </div>
  <?php
}

function cp_after_contribution_notice($comment) {
  $post = new post;
  $id = $comment->obj;
  $material = $post->get_post_meta($id);
  $session = Session::getInstance();
  $fullname = get_fullname($session->id);
  $stream = new cp_streams;
  $stream->type = "comment";
  $stream->link = "cp-view-material?id=".$comment->obj;
  $stream->mail_subject = "CLASSROOM PLUS: NEW COMMENT BY ".$fullname;
  $stream->message = $fullname. " posted a new comment under ".$comment->dictionary->label_plu." section. <blockquote>".$comment->args['comment']."</blockquote>";
  $stream->class_id = $material['class'];
  $stream->subject = $material['course'];
  $stream->send_communique(EMAIL, NOTIFICATION);
  $stream->log();
}

function cp_after_lesson_contribution_notice($comment) {
  $post = new post;
  $lesson = $post->get_post_meta($comment->obj);
  $session = Session::getInstance();
  $fullname = get_fullname($session->id);
  $stream = new cp_streams;
  $stream->type = "comment";
  $stream->link = "cp-view-lesson?id=".$comment->obj;
  $stream->mail_subject = "CLASSROOM PLUS: NEW COMMENT BY ".$fullname;
  $stream->message = $fullname. " posted a new comment under ".$comment->dictionary->label_plu." section. <blockquote>".$comment->args['comment']."</blockquote>";
  $stream->class_id = $lesson['class'];
  $stream->subject = $lesson['course'];
  $stream->send_communique(EMAIL, NOTIFICATION);
  $stream->log();
}

function cp_get_available_quiz($args) {
  $student_meta = $args['student_meta'];
  $post = new post;
  $term = get_option("current_academic_term");
  $time = time();
  if(!$args['subject']) {
    $subjects = get_class_courses($student_meta['class'], $student_meta['category'], false, false);
    $subjects = array_keys($subjects);
  } else {
    $subjects = $args['subject'];
  }
  
  $quiz = $post->get_post_by_meta_data(['type' => 'cp_quiz', 'class' => $student_meta['class'], 'course' => $subjects, 'term' => $term, 'from' => $time, 'to' => $time, 'status' => 'published'], ['from' => "<", 'to' => ">="], false, 0, 0, 'post_id', 'DESC');
  if(is_array($quiz) && _count($quiz)) :
    $table = new table("lessons-table", $quiz);
    $table->set_display_columns([
        "course" => "Subject",
        "test" => "Test",
        "term" => "Term",
        "from" => "Starts",
        'to' => "Ends",
        "time_allowed" => "Time Allowed"
    ]);
    $table->set_dynamic_columns([
        "course" => "_tf_eedu_get_course_name",
        "term" => "_tf_eedu_display_term_name",
        "from" => "_tf_get_date",
        'to' => "_tf_get_date",
        "time_allowed" => "_tf_cp_display_time_allowed"
    ]);
    $table->set_action_links([
        "Write" => "cp-write-quiz"
    ]);
    $table->set_action_access([
        "Write" => "cp_write_quiz"
    ]);
    $table->set_action_callback([
        "Write" => false
    ]);
    $table->set_action_condition([
        "Write" => ["_check_student_has_written_quiz" => $student_meta]
    ]);
    $table->set_action_args([
        "Write" => ["id" => "id"]
    ]);
    $table->action_pos = 1;
    $table->table_class = "table";
    $table->table_id = "quiz-table";
    ?>
    <div class="card border border-success">
        <div class="card-header">
            <strong class="card-title"><span class="badge badge-danger">Important</span> Ongoing Online Quiz/Tests</strong>
        </div>
        <div class="card-body">
            <p class="card-text"><?php $table->display(); ?></p>
        </div>
    </div>
    <?php
  else:
    echo "There is no ongoing quiz or test";
  endif;
}

function cp_dashboard_additional_top_panels($user_meta) {
  if($user_meta['role'] === 'student') {
    do_action("cp_get_available_quiz", ["student_meta" => $user_meta, "subject" => false]);
  }
}

function cp_play_quiz($quiz_meta) {
  $post = new post;
  $session = Session::getInstance();
  $questions = cp_serve_random_questions($quiz_meta);
  $time = time() + ($quiz_meta['time_allowed'] * 60);
  $time = date("Y/m/d H:i:s", $time);
  $count = _count($questions);
  if(db_post_unique(["type" => "cp_write_quiz", "user_id" => $session->id, "quiz" => $quiz_meta['id']])) {
    ?>
    <div class="row mb-4">
      <div class="flashcardcover">
          <div class="flashcard-container">
            <article class="flashcard">
              You have already submitted this quiz before.
            </article>
          </div>
      </div>
    </div>
    <a href="dashboard" class="btn btn-primary">Go Back</a>
    <?php
    return;
  }
  ?>
  <form id="write-quiz-form" method="post" action="contents/plugins/classroom_plus/ajax.php" data-callback="showQuizResult" data-callbackid="#write-quiz-form">
    <input type="hidden" name="quiz" id="quiz" value="<?php echo $quiz_meta['id'] ?>">
    <input type="hidden" name="class" id="class" value="<?php echo $quiz_meta['class'] ?>">
    <input type="hidden" name="course" id="course" value="<?php echo $quiz_meta['course'] ?>">
    <input type="hidden" name="term" id="term" value="<?php echo $quiz_meta['term'] ?>">
    <input type="hidden" name="start_time" value="<?php echo time(); ?>">
    <input type="hidden" name="number_of_questions" value="<?php echo $count; ?>">
    <input type="hidden" name="action" value="write_quiz">
    <div class="alert alert-warning">Do not close without submitting else you will lose your work and may not be able to write again.</div>
    <div class="privew">
      <div class="questionsBox">
        <div id="slider">
            <div class="slides-container">
              <?php if (_count($questions)): ?>
                <?php foreach ($questions as $question): ?>
                  <?php if ($question['question_meta']['question_type'] == 'objective'): ?>
                    <div class="slide">
                      <input type="hidden" name="obj_question[<?php echo $question['question_meta']['correct_option'] ?>]" value="<?php echo $question['question_meta']['id']; ?>">
                      <div class="questions"><?php echo $question['question_meta']['question'] ?></div>
                        <ul class="answerList">
                          <?php foreach ($question['question_meta']['option']['optionvalue'] as $key => $value): ?>
                            <li>
                                <label>
                                    <input type="radio" name="objective[<?php echo $question['question_meta']['correct_option'] ?>]" value="<?php echo $key ?>">&nbsp;<?php echo $value ?></label>
                            </li>
                          <?php endforeach ?>
                        </ul>
                    </div>
                  <?php endif ?>
                <?php endforeach ?>
              <?php endif ?>
                
            </div>
            <div class="countdown bg-red text-white text-center" data-time="<?php echo $time; ?>">Time Left: {hour:00}:{min:00}:{sec:00}.{ms:00}</div>
            <div class="questionsRow">
              <a href="#" class="button prevquestions" id="prevquestions">Back</a> 
              <a href="#" class="button nextquestions" id="nextquestions">Next</a>
              <button class="button submit confirmThis" id="submit-quiz" data-content="Are you sure you want to submit your answers and close the quiz?" data-continue-btn="Yes" data-cancel-btn="No">Submit</button>

              <span class="pager">1 of <?php echo $count ?></span>
            </div>
            

        </div>
          
      </div>
    </div>
  </form>
  <?php
  global $post_meta;
  add_page_javascript('contents/plugins/classroom_plus/template/assets/js/jquery.countdown-timer.min.js');
  add_page_javascript('app/assets/js/page-scripts/submit.js');
  add_page_javascript('contents/plugins/classroom_plus/js/write-quiz.js');
}