<script>
  const courseDefaultPageTitle = document.title.split(" | ")
  const courseName = '{{course.name}}'
  document.title = `${courseName}  | ${courseDefaultPageTitle[1]}`
  const courseDescription = '{{course.short_description}}'
  $('head').append( `<meta name="description" content="${courseDescription}">` );
</script>

{% if current_person.signed_in? == false and current_school.sso_active? == false %}
<script> window.location.replace('/learners/sign_in')</script>
{% else %}
  {% include "header" %}
  
  {% if course.ribbon == "VIDEO" %}
    {% include "video_tutorial_cover" %}
  {% else %}
    {% include "course_cover" %}
  {% endif %}
  
  {% include "footer" %}
  
  {% if current_person.signed_in? == false and current_school.sso_active? %}
    <script>
      const redirectionLink = 'https://user-learn.pipedrive.com/app/courses/{{ course.properties.second_school_course_uuid }}'
      document.querySelector('#redirect-between-academies').setAttribute('href', redirectionLink)
    </script>
  {% endif %}
  
  {% if current_person.signed_in? and current_school.properties.sandbox == false %}
    <script>
      function setupLatestCourses() {
        let newCourse = '{{ course.id }}';
        {% if course.ribbon == "VIDEO" %}
          var latestCourses = '{{ current_person.properties.latest_tutorials }}';
          var courseType = 'latest_tutorials'
        {% else %}
          var latestCourses = '{{ current_person.properties.latest_courses }}';
          var courseType = 'latest_courses'
        {% endif %}
        let newLatest = []
        if (latestCourses === 'NULL') {
          newLatest = [newCourse]
        } else {
          let latestCoursesArray = latestCourses.split(',');
          if (latestCoursesArray.includes(newCourse)) {
            if (latestCoursesArray[0] === newCourse) {
              return 0
            } else {
              newLatest = latestCoursesArray.filter(item => item !== newCourse)
              newCourse.unshift(newCourse)
            }
          } else {
            newLatest = latestCoursesArray
            if (latestCoursesArray.length === 3) {
              newLatest.pop()
            }
            newLatest.unshift(newCourse)
          }
        }
        let xhr = new XMLHttpRequest();
        {% if current_school.sso_active? %}
          var url = "https://www.workato.com/webhooks/rest/bd1a1eb7-7e79-4208-a1db-8e9c7440bcc9/pipedrive-sso-last-courses";
        {% else %}
          var url = "https://www.workato.com/webhooks/rest/bd1a1eb7-7e79-4208-a1db-8e9c7440bcc9/pipedrive-open-last-courses";
        {% endif %}
        xhr.open("POST", url, true);
        xhr.send(JSON.stringify({
          user_id: '{{ current_person.id }}',
          school_id: '{{ current_school.id }}',
          latest_courses: newLatest.toString(),
          course_type: courseType
        }));
      }
      setupLatestCourses()
    </script>
  {% endif %}
{% endif %}
