<div class="content-wrapper">
  <div class="container-full">
    <!-- Main content -->
    <section class="content">
      <div class="row">
        <?php if (user()->role == 'Student'): ?>
          <div class="col-xxl-12">
            <div class="row fx-element-overlay">

              <div class="col-lg-8 col-md-8 col-12">
                <div class="box pull-up">
                  <div class="box-body">
                    <div class="d-flex align-items-center">
                      <div class="d-flex flex-column flex-grow-1">
                        <h4 class="mb-1">Medals</h4>
                      </div>
                    </div>
                    <?php echo $medal_report; ?>
                  </div>
                </div>
              </div>

              <div class="col-xl-4 col-lg-5 col-12">
                <div class="box">
                  <div class="box-header no-border">
                    <h3 class="fw-500 m-0 fs-22">Upcoming Video Lessons</h3>
                  </div>
                  <div class="box-body pt-2">
                    <div class="d-flex align-items-center justify-content-center" style="height: 215px; overflow-y: auto;-webkit-overflow-scrolling: touch;">
                      <div
                        class="d-flex align-items-center justify-content-between mb-15">
                        <div class="d-flex align-items-center">
                          <h6>No Lession Found</h6>
                        </div>
                      </div>
                    </div>
                  </div>
                </div>
              </div>

              <div id="study-reminder-box"></div>


              <div class="col-xl-12 col-lg-12 col-12">
                <div class="box pull-up">
                  <div class="box-body">
                    <div class="row align-items-center">
                      <div class="col-md-4 mb-3 mb-md-0">
                        <h6 class="mb-1 fw-bold">
                          Set A Weekly Study Reminder
                        </h6>
                        <p class="mb-0 text-muted">
                          Learners who set study reminders are 75% more
                          likely to complete a course. You can change this
                          any time.
                        </p>
                      </div>

                      <div class="col-md-8">

                        <div class="d-flex gap-3 flex-wrap">
                          <!-- Option 1 -->
                          <a href="javascript:void(0)" onclick="open_reminder_model(2)" class="reminder-btn">
                            <div class="reminder-btn-row">
                              <input type="radio" name="study-reminder" />
                              <div class="title-reminder">
                                Learn <b>2 days</b> a week
                              </div>
                            </div>
                          </a>
                          <a href="javascript:void(0)" class="reminder-btn" onclick="open_reminder_model(3)">
                            <div
                              class="reminder-btn-row align-items-center">
                              <input type="radio" name="study-reminder" />
                              <div class="column">
                                <span class="recommended">Recommended</span>
                                <div class="title-reminder">
                                  Learn <b>3 days</b> a week
                                </div>
                              </div>
                            </div>
                          </a>
                          <a href="javascript:void(0)" class="reminder-btn" onclick="open_reminder_model(5)">
                            <div class="reminder-btn-row">
                              <input type="radio" name="study-reminder" />
                              <div class="title-reminder">
                                Learn <b>5 days</b> a week
                              </div>
                            </div>
                          </a>
                        </div>
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>

          <div class="col-xxl-4">
            <div class="box bg-black">
              <div class="box-body">
                <div class="row">
                  <div class="col-8">
                    <img src="<?php echo student_lms_css(); ?>images/logo-light-text.png" alt="logo" />
                    <h3 class="mt-25 fw-500">Upgrade to Pro</h3>
                    <p class="text-fade">
                      Get 1 Month Free on Annual Subscription and Explore
                      More.
                    </p>
                    <div>
                      <button
                        class="btn btn-success waves-effect rounded-5 px-25">
                        Get Access
                      </button>
                    </div>
                  </div>
                  <div
                    class="col-4 book-image align-content-center text-center">
                    <img
                      src="<?php echo student_lms_css(); ?>images/front-end-img/courses/book-3.png"
                      alt="" />
                  </div>
                </div>
              </div>
            </div>
          </div>
        <?php endif; ?>


        <div class="col-xl-8 col-lg-7 col-12">
          <div class="box bg-transparent no-shadow mb-20">
            <div
              class="box-header no-border d-flex justify-content-between align-items-center pb-0 px-0">
              <h3 class="fw-500 m-0 fs-22">Your <?php if (user()->role == 'Student'): ?>Courses<?php else: ?> Product<?php endif; ?></h3>
              <div class="dropdown">
                <button
                  class="btn btn-light py-5 dropdown-toggle text-fade sem-drop"
                  type="button"
                  data-bs-toggle="dropdown"
                  aria-expanded="false">
                  Active
                </button>
                <div class="dropdown-menu dropdown-menu-end" style="">
                  <a class="dropdown-item" href="#">Close</a>
                  <a class="dropdown-item" href="#">Progress</a>
                  <a class="dropdown-item" href="#">Panding</a>
                </div>
              </div>
            </div>
          </div>
          <div class="box mb-15 pull-up">

            <?php
            if (user()->role == 'Student') {
              foreach ($enrolments as $enrolment):
                $course_details = $this->course_model->get_course_by_id_for_lms($enrolment->course_id)->row_array();
                // $instructor_details = $this->user_model->get_all_user($course_details['creator'])->row_array();
                $course_duration = $this->course_model->get_total_duration_of_lesson_by_course_id($course_details['course_id']);
                $lectures = $this->db->get_where('lesson', ['course_id' => $course_details['course_id'], 'lesson_type !=' => 'quiz']);
                $quizzes = $this->db->get_where('lesson', ['course_id' => $course_details['course_id'], 'lesson_type' => 'quiz']);
                $watch_history = $this->course_model->get_watch_histories(user()->id, $course_details['course_id'])->row_array();
                $course_progress = isset($watch_history['course_progress']) ? $watch_history['course_progress'] : 0;
            ?>

                <div class="box-body">
                  <div
                    class="d-flex align-items-center justify-content-between">
                    <div class="d-flex align-items-center">
                      <div
                        class="me-15 bg-primary-light h-50 w-50 l-h-40 rounded text-center">
                        <img
                          src="<?php echo student_lms_css(); ?>images/front-end-img/courses/lesson.png"
                          alt=""
                          class="align-self-end h-50 w-50" />
                      </div>
                      <div class="d-flex flex-column fw-500">
                        <a href="<?php echo site_url('admin/admin/lesson/' . $course_details['course_slug'] . '/' . $course_details['course_id'])
                                  ?>" class="text-dark hover-primary mb-1 fs-16"><?php echo $course_details['course_heading']; ?></a>
                        <span class="text-fade"><?php echo get_phrase('Lectures') . ' ' . $lectures->num_rows(); ?> | <?php echo get_phrase('Quizzes') . ' ' . $quizzes->num_rows(); ?></span>
                      </div>
                    </div>
                    <div>
                      <p class="m-0 text-fade">Time</p>
                      <h5 class="m-0"><?php echo $course_duration; ?></h5>
                    </div>
                    <div class="d-none d-md-block">
                      <div class="d-flex align-items-center justify-content-between">
                        <div class="w-100">
                          <div class="progress progress-sm mb-0">
                            <div class="progress-bar progress-bar-danger" role="progressbar" aria-valuenow="<?php echo $course_progress; ?>" aria-valuemin="0" aria-valuemax="100" style="width: <?php echo $course_progress; ?>%">
                            </div>
                          </div>
                        </div>
                        <div class="ps-3">
                          <div><?php echo $course_progress; ?>%</div>
                        </div>
                      </div>
                    </div>
                  </div>
                </div>
              <?php endforeach;
            } else {
              // $this->db->select('product_purchase.*, products.*');
              $this->db->where('product_purchase.pur_user_id', user()->id);
              // $this->db->join('products', 'products.prd_id = product_purchase.pur_prd_id', 'left');

              $all_products = $this->db->get('product_purchase')->result();

              foreach ($all_products as $key => $prd):

                $this->db->where('prd_id', $prd->pur_prd_id);
                $product = $this->db->get('products')->row();

                $this->db->where('lead_id', $prd->pur_lead_id);
                $quots_details = $this->db->get('quotes')->row();
                
                
              ?>

                <div class="box-body">
                  <div
                    class="d-flex align-items-center justify-content-between">
                    <div class="d-flex align-items-center">
                      <div
                        class="me-15 bg-primary-light h-50 w-50 l-h-40 rounded text-center">
                        <img
                          src="<?php echo base_url(); ?><?php echo $product->prd_image; ?>"
                          alt=""
                          class="align-self-end h-50 w-50" />
                      </div>
                      <div class="d-flex flex-column fw-500">
                        <a href="<?php //echo site_url('admin/admin/lesson/')
                                  ?>" class="text-dark hover-primary mb-1 fs-16"><?php echo $product->prd_name; ?></a>
                        <span class="text-fade">₹<?php echo $product->disocunt_price ?? $product->prd_price; ?> <?php if($quots_details->emi_months > 1):?>(<?php echo $quots_details->emi_months; ?> X ₹<?php echo $quots_details->emi_amount; ?>)<?php endif; ?></span>
                      </div>
                    </div>
                    <div>
                      <a href=""><button class="btn btn-primary">Pay Now</button></a>
                    </div>
                    
                  </div>
                </div>
              <?php endforeach; ?>

            <?php } ?>
          </div>

        </div>
        <div class="col-xl-4 col-lg-5 col-12">
          <div class="box">
            <div class="box-body">
              <div id="calendar" class="dask evt-cal min-h-400"></div>
            </div>
          </div>
        </div>
      </div>
    </section>
    <!-- /.content -->
  </div>
</div>

<div class="modal fade" id="timerModal" tabindex="-1" aria-labelledby="timerModalLabel" aria-hidden="true">
  <div class="modal-dialog modal-lg">
    <div class="modal-content p-3">
      <div class="modal-header">
        <h5 class="modal-title">Study Reminder</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
      </div>
      <div class="modal-body">
        <p>You’re more likely to complete a course if you dedicate some time per week to study.</p>
        <h6><b>Choose the days that work for you.</b></h6>
        <div class="d-flex flex-wrap justify-content-center mt-4">
          <div class="main-time-content">
            <div class="day-toggle" data-day="Mon">Mon
            </div>
            <div id="timeSections-Mon"></div>
          </div>
          <div class="main-time-content">
            <div class="day-toggle" data-day="Tue">Tue</div>
            <div id="timeSections-Tue"></div>
          </div>
          <div class="main-time-content">
            <div class="day-toggle" data-day="Wed">Wed</div>
            <div id="timeSections-Wed"></div>
          </div>
          <div class="main-time-content">
            <div class="day-toggle" data-day="Thu">Thu</div>
            <div id="timeSections-Thu"></div>
          </div>
          <div class="main-time-content">
            <div class="day-toggle" data-day="Fri">Fri</div>
            <div id="timeSections-Fri"></div>
          </div>
          <div class="main-time-content">
            <div class="day-toggle" data-day="Sat">Sat</div>
            <div id="timeSections-Sat"></div>
          </div>
          <div class="main-time-content">
            <div class="day-toggle" data-day="Sun">Sun</div>
            <div id="timeSections-Sun"></div>
          </div>
        </div>
      </div>
      <div class="modal-footer justify-content-center">
        <button class="btn btn-set-reminder" style="background-color:#0f2449; color:#fff">Set Study Reminder</button>
      </div>
    </div>
  </div>
</div>

<script>
  document.addEventListener('DOMContentLoaded', function() {
    function loadReminders() {
      console.log("jjj");
      fetch('<?= base_url("admin/admin/get_reminder") ?>')
        .then(response => response.json())
        .then(data => {
          if (data.length === 0) {
            document.getElementById('study-reminder-box').innerHTML = "<p>No reminders set yet.</p>";
            return;
          }

          let html = `
          <div class="col-xl-12 col-lg-12 col-12">
            <div class="box pull-up">
              <div class="box-body">
                <div class="row align-items-center">
                  <div class="col-md-4 mb-3 mb-md-0">
                    <h6 class="mb-1 fw-bold">Study Reminders</h6>
                    <p class="mb-0 text-muted" id="next-reminder">
                    </p>
                  </div>
                  <div class="col-md-8">
                    <div class="d-flex gap-4 flex-wrap">
        `;

          const allDays = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'];
          const activeDays = {};

          // Make activeDays object for quick lookup
          data.forEach(reminder => {
            activeDays[reminder.day] = {
              time: reminder.time,
              ampm: reminder.ampm
            };
          });

          allDays.forEach(day => {
            const isActive = activeDays.hasOwnProperty(day);
            html += `
            <div class="active-reminder-circle">
              <div class="day-circle ${isActive ? 'active' : ''}">
                <div class="day-label">${day}</div>
              </div>
              <div class="time-label">
                ${isActive ? `${activeDays[day].time} ${activeDays[day].ampm}` : ''}
              </div>
            </div>
          `;
          });

          html += `
                    </div> <!-- d-flex gap-3 flex-wrap -->
                  </div> <!-- col-md-8 -->
                </div> <!-- row align-items-center -->
              
              </div> <!-- box-body -->
            </div> <!-- box pull-up -->
          </div> <!-- col-xl-12 col-lg-12 col-12 -->
        `;

          document.getElementById('study-reminder-box').innerHTML = html;

          // Set next reminder (first one)
          if (data.length > 0) {
            document.getElementById('next-reminder').innerHTML = `Next reminder on <b>${data[0].day} ${data[0].time} ${data[0].ampm}</b>`;
          }
        })
        .catch(error => {
          console.error('Error loading reminders:', error);
        });
    }

    loadReminders();
  });




  document.querySelector('.btn-set-reminder').addEventListener('click', function() {
    const selectedReminders = [];

    document.querySelectorAll('.day-toggle.active').forEach(dayEl => {
      const day = dayEl.dataset.day;
      const time = document.getElementById(`${day}-time`).textContent;
      const ampm = document.getElementById(`${day}-AM`).checked ? 'AM' : 'PM';

      selectedReminders.push({
        day,
        time,
        ampm
      });
    });

    // Send to server
    fetch('<?= base_url("admin/admin/reminder_save") ?>', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json'
        },
        body: JSON.stringify({
          reminders: selectedReminders
        })
      })
      .then(response => response.json())
      .then(data => {
        iziToast.success({
          title: 'OK',
          message: 'Reminders saved successfully!',
          position: 'topRight',
          messageColor: '#000'
        });
        location.reload();
        $('#timerModal').modal('hide');
      })
      .catch(error => {
        console.error('Error:', error);
      });
  });

  function open_reminder_model(dayCount) {
    $('#timerModal').modal('show');

    // Reset all days
    days.forEach(day => {
      document.querySelector(`.day-toggle[data-day="${day}"]`)?.classList.remove('active');
      document.getElementById(`${day}-control`)?.classList.remove('show');
    });

    // Define which days to activate based on the selected option
    let selectedDays = [];
    if (dayCount === 2) {
      selectedDays = ["Mon", "Fri"];
    } else if (dayCount === 3) {
      selectedDays = ["Mon", "Wed", "Fri"];
    } else if (dayCount === 5) {
      selectedDays = ["Mon", "Tue", "Wed", "Thu", "Fri"];
    }

    // Activate and show selected days
    selectedDays.forEach(day => {
      const toggle = document.querySelector(`.day-toggle[data-day="${day}"]`);
      const control = document.getElementById(`${day}-control`);
      if (toggle && control) {
        toggle.classList.add('active');
        control.classList.add('show');
      }
    });
  }


  const days = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"];

  days.forEach(day => {
    const control = document.createElement('div');
    control.className = 'time-control';
    control.id = `${day}-control`;
    control.innerHTML = `
<div class="time-display mt-2">
  <button class="time-btn" onclick="changeTime('${day}', -1)">−</button>
  <span id="${day}-time">12:00</span>
  <button class="time-btn" onclick="changeTime('${day}', 1)">+</button>
</div>
<div class="btn-group ampm-toggle mt-2" role="group">
  <input type="radio" class="btn-check" name="${day}-ampm" id="${day}-AM" autocomplete="off" checked>
  <label class="btn btn-outline-primary" for="${day}-AM">AM</label>
  <input type="radio" class="btn-check" name="${day}-ampm" id="${day}-PM" autocomplete="off">
  <label class="btn btn-outline-primary" for="${day}-PM">PM</label>
</div>
<div class="remove-link" onclick="removeSelection('${day}')">Remove</div>
`;
    document.getElementById(`timeSections-${day}`).appendChild(control);
    control.addEventListener('click', (event) => event.stopPropagation());
  });

  document.querySelectorAll('.day-toggle').forEach(toggle => {
    toggle.addEventListener('click', () => {
      const day = toggle.dataset.day;
      toggle.classList.toggle('active');
      document.getElementById(`${day}-control`).classList.toggle('show');
    });
  });

  function changeTime(day, delta) {
    const timeSpan = document.getElementById(`${day}-time`);
    let [hour, minute] = timeSpan.textContent.split(':').map(Number);
    let totalMinutes = hour % 12 * 60 + minute + delta * 5;
    if (document.getElementById(`${day}-PM`).checked) totalMinutes += 720;
    totalMinutes = (totalMinutes + 1440) % 1440;

    let ampm = totalMinutes >= 720 ? 'PM' : 'AM';
    let displayHour = Math.floor((totalMinutes % 720) / 60);
    if (displayHour === 0) displayHour = 12;
    let displayMinute = (totalMinutes % 60).toString().padStart(2, '0');

    timeSpan.textContent = `${displayHour}:${displayMinute}`;
    document.getElementById(`${day}-${ampm}`).checked = true;
  }

  function removeSelection(day) {
    console.log(day);
    document.querySelector(`.day-toggle[data-day="${day}"]`).classList.remove('active');
    document.getElementById(`${day}-control`).classList.remove('show');
  }
</script>

<style>
  [type="radio"]+label::before,
  [type="radio"]+label::after {
    content: '';
    position: absolute;
    left: 0;
    top: 0;
    margin: 4px;
    width: 16px;
    height: 16px;
    z-index: 0;
    transition: .28s ease;
    display: none;
  }

  [type="radio"]:not(:checked)+label,
  [type="radio"]:checked+label {
    position: relative;
    padding-left: 10px;
    cursor: pointer;
    display: inline-block;
    height: 25px;
    line-height: 10px;
    font-size: 1rem;
    transition: .28s ease;
    -webkit-user-select: none;
    -moz-user-select: none;
    -ms-user-select: none;
    user-select: none;
  }

  .ampm-toggle {
    border: 1px solid #f00;
  }

  .btn-check:checked+.btn,
  :not(.btn-check)+.btn:active,
  .btn:first-child:active,
  .btn.active,
  .btn.show {
    color: var(--bs-btn-active-color);
    background-color: #f00;
    border-color: #f00;
  }

  .day-toggle {
    width: 50px;
    height: 50px;
    border-radius: 50%;
    border: 2px solid #0f2449;
    text-align: center;
    line-height: 46px;
    font-weight: bold;
    cursor: pointer;
    margin: 5px;
    color: #0f2449;
    margin: 0 auto;
  }

  .day-toggle.active {
    background-color: #0f2449;
    color: white;
  }

  .time-control {
    display: none;
    flex-direction: column;
    align-items: center;
    margin-bottom: 20px;
  }

  .time-control.show {
    display: flex;
  }

  .time-display {
    display: flex;
    align-items: center;
    gap: 0;
    font-size: 15px;
    color: #000;
  }

  .time-btn {
    font-size: 10px;
    background: none;
    cursor: pointer;
    border: 1px solid #000;
    border-radius: 100%;
    display: flex;
    height: 18px;
    line-height: 12px;
  }

  .ampm-toggle .btn {
    padding-left: 10px;
    padding-right: 10px;
  }

  .ampm-toggle label {
    font-size: 12px;
  }

  .remove-link {
    font-size: 0.9rem;
    color: #6c757d;
    text-decoration: underline;
    cursor: pointer;
    line-height: 2;
  }

  [id$="-time"] {
    min-width: 50px;
    text-align: center;
  }

  .main-time-content {
    width: 100px;
  }

  #calendar {
    height: 426px;
    overflow: hidden;
  }

  .reminder-btn {
    background: #ffffff 0 0 no-repeat padding-box;
    border: 1px solid #d7d7d7;
    border-radius: 8px;
    opacity: 1;
    padding: 16px 18px;
    height: 73px;
    justify-content: center;
    align-items: center;
    display: flex;
    color: #000;
  }

  .reminder-btn:hover {
    border: 1px solid #f00;
    color: #000;
  }

  .recommended {
    text-align: left;
    letter-spacing: 0;
    font-family: Roboto, sans-serif;
    font-size: 12px;
    margin-bottom: 5px;
    color: #007646;
    font-weight: 500;
    opacity: 1;
  }

  .reminder-btn input[type="radio"] {
    background: #ffffff 0 0 no-repeat padding-box;
    border: 1px solid #d7d7d7;
    border-radius: 8px;
    opacity: 1;
    justify-content: center;
    align-items: center;
    display: flex;
    margin-right: 10px;
  }

  .reminder-btn-row {
    display: flex;
  }

  .days-container {
    display: flex;
    gap: 10px;
  }

  .day-circle {
    width: 60px;
    height: 60px;
    border-radius: 50%;
    border: 2px solid #ccc;
    text-align: center;
    font-size: 17px;
    align-content: center;
    display: block;

  }

  .day-label {
    font-weight: bold;
  }

  .edit-btn {
    background: none;
    border: none;
    position: absolute;
    right: 10px;
    top: 10px;
  }

  .day-circle.active {
    border: 2px solid #0f2449;
    /* Blue border */
    background-color: #e3f2fd;
    /* Light blue background */
    color: #0f2449;
    /* Text blue */
    position: relative;
  }

  .day-circle.active::before {
    content: "\f00c";
    /* Unicode for Font Awesome check icon */
    font-family: "FontAwesome";
    /* Important: load FA */
    position: absolute;
    top: -5px;
    right: -5px;
    background-color: #0f2449;
    color: #fff;
    border-radius: 50%;
    width: 18px;
    height: 18px;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 10px;
  }
</style>
<script>
  var defaultEvents = <?php echo json_encode($week_event); ?>;
  var hours_spent = [];
</script>