@section('title', 'Hasil Tes')
@extends('user.layouts.index')
@section('content')
  <style>
    .stats-grid {
      display: grid;
      grid-template-columns: repeat(4, 1fr);
      gap: 16px;
    }

    .stat-card {
      padding: 20px;
      border-radius: 12px;
      background: #f5f5f5;
    }

    .bg-custom {
      background: #f5f5f5;
    }
  </style>
  <!-- Page Title -->
  <div class="page-title">
    <div class="heading">
      <div class="container">
        <div class="row d-flex justify-content-center text-center">
          <div class="col-lg-8">
            <h1 class="heading-title">Hasil Tes Anda</h1>
            <p class="mb-0">
              Cek hasil tes kamu dari sini ya, jika kamu sudah mendapatkan kode dari email setelah melakukan booking, kamu bisa melihat hasil tes disini dengan kode tadi.
            </p>
          </div>
        </div>
      </div>
    </div>
    <nav class="breadcrumbs">
      <div class="container">
        <ol>
          <li><a href="{{ route('beranda.index') }}">Home</a></li>
          <li class="current">Hasil Tes</li>
        </ol>
      </div>
    </nav>
  </div><!-- End Page Title -->

  <!-- About Section -->
  <section id="about" class="about section">
    <div class="container mt-5">
      <h1 class="text-center mb-4">
        Prediksi & Analisis Kecemasan
      </h1>
      <div class="row g-4">
        <!-- STAI Score -->
        <div class="col-md-4">
          <div class="card h-100 shadow-sm">
            <div class="card-body">
              <div class="d-flex justify-content-between align-items-start">
                <div class="col-md-10">
                  <h4 class="card-title">
                    Skor STAI-T
                  </h4>
                  <h2 class="mt-4">
                    {{ $data_aswered['totalScore'] }}
                  </h2>
                  <p class="text-muted">
                    Hasil dari kuesioner kecemasan
                  </p>
                </div>
                <div class="col-md-2 d-flex justify-content-center align-items-center bg-primary-subtle border border primary rounded-circle" style="aspect-ratio: 1/1;">
                  <i class="bi bi-clipboard2-pulse fs-3"></i>
                </div>
              </div>
            </div>
          </div>
        </div>
        <!-- Anxiety Level -->
        <div class="col-md-4">
          <div class="card h-100 shadow-sm">
            <div class="card-body">
              <div class="d-flex justify-content-between align-items-start">
                <div class="col-md-10">
                  <h4 class="card-title">
                    Tingkat Kecemasan
                  </h4>
                  @if ($data_aswered['totalScore'] <= 37)
                    <h2 class="mt-4 text-success">
                      Normal
                    </h2>
                  @elseif ($data_aswered['totalScore'] <= 44)
                    <h2 class="mt-4 text-warning">
                      Sedang
                    </h2>
                  @elseif ($data_aswered['totalScore'] <= 80)
                    <h2 class="mt-4 text-danger">
                      Tinggi
                    </h2>
                  @endif
                  <p class="text-muted">
                    Berdasarkan skor <a href="https://headway.co/resources/state-trait-anxiety-inventory-scoring" target="_blank"><i>STAI-T</i></a>
                  </p>
                </div>
                <div class="col-md-2 d-flex justify-content-center align-items-center bg-primary-subtle border border primary rounded-circle" style="aspect-ratio: 1/1;">
                  <i class="bi bi-emoji-neutral fs-3"></i>
                </div>
              </div>
            </div>
          </div>
        </div>
        <!-- AI Prediction -->
        <div class="col-md-4">
          <div class="card h-100 shadow-sm">
            <div class="card-body">
              <div class="d-flex justify-content-between align-items-start">
                <div class="col-md-10">
                  <h4 class="card-title">
                      Prediksi AI
                  </h4>
                  <h2 class="mt-4" id="result-model">
                    Loading...
                  </h2>
                  <p class="text-muted">
                    Model Confidence: <span id="confidence-model"></span>
                  </p>
                </div>
                <div class="col-md-2 d-flex justify-content-center align-items-center bg-primary-subtle border border primary rounded-circle" style="aspect-ratio: 1/1;">
                  <i class="bi bi-cpu fs-3"></i>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
    <div class="container mt-5">
      <div class="row">
        <div class="col-md-12">
          <h2 class="title text-center">Detail Tes/Ujian kamu</h2>
          <div class="row">
            <div class="col-md-4">
              <div class="bg-custom p-4 my-3 border rounded">
                <div class="row">
                  <div class="col-md-10">
                    <h5 class="text-body">Informasi Pribadi</h5>
                  </div>
                  <div class="col-md-2 d-flex justify-content-center align-items-center bg-primary-subtle border border primary rounded-circle" style="aspect-ratio: 1/1;">
                    <i class="bi bi-person-vcard fs-4"></i>
                  </div>
                </div>
                <ul class="list-unstyled">
                  <li><strong>Kode Booking:</strong> {{ $data_information['kode'] }}</li>
                  <li><strong>Nama:</strong> {{ $data_information['nama'] }}</li>
                  <li><strong>Email:</strong> {{ $data_information['email'] }}</li>
                  <li><strong>Nomor Handphone:</strong> {{ $data_information['no_hp'] }}</li>
                </ul>
              </div>
            </div>
            <div class="col-md-4">
              <div class="bg-custom p-4 my-3 border rounded">
                <div class="row">
                  <div class="col-md-10">
                    <h5 class="text-body">Informasi Ujian</h5>
                  </div>
                  <div class="col-md-2 d-flex justify-content-center align-items-center bg-primary-subtle border border primary rounded-circle" style="aspect-ratio: 1/1;">
                    <i class="bi bi-clipboard fs-4"></i>
                  </div>
                </div>
                <ul class="list-unstyled">
                  <li><strong>Durasi Ujian:</strong> {{ $difference }}</li>
                  <li><strong>Resolusi Layar (saat ujian):</strong> {{ $screen_dim['width'] }} x {{ $screen_dim['height'] }}</li>
                  <li><strong>Jumlah Pergerakan Mata:</strong> <span id="total_movement">0</span></li>
                </ul>
              </div>
            </div>
            <div class="col-md-4">
              <div class="bg-custom p-4 my-3 border rounded">
                <div class="row">
                  <div class="col-md-10">
                    <h5 class="text-body">Hasil Ujian (STAI-T)</h5>
                  </div>
                  <div class="col-md-2 d-flex justify-content-center align-items-center bg-primary-subtle border border primary rounded-circle" style="aspect-ratio: 1/1;">
                    <i class="bi bi-easel fs-4"></i>
                  </div>
                </div>
                <ul class="list-unstyled">
                  <li><strong>Jumlah Soal:</strong> {{ $data_aswered['total_question'] }}</li>
                  <li><strong>Soal terjawab:</strong> {{ $data_aswered['answered'] }}</li>
                  <li><strong>Soal tidak terjawab:</strong> {{ $data_aswered['unanswered'] }}</li>
                  <li><strong>Total Skor:</strong> {{ $data_aswered['totalScore'] }}</li>
                </ul>
              </div>
            </div>
          </div>
          <div class="row">
            <div class="col-md-4">
              <div class="bg-custom p-4 my-3 border rounded">
                <div class="row">
                  <div class="col-md-10">
                    <h5 class="text-body">Detail Confidence Prediksi Model</h5>
                  </div>
                  <div class="col-md-2 d-flex justify-content-center align-items-center bg-primary-subtle border border primary rounded-circle" style="aspect-ratio: 1/1;">
                    <i class="bi bi-easel fs-4"></i>
                  </div>
                </div>
                <ul class="list-unstyled">
                  <li><strong>Normal:</strong> <span id="normal-confidence">0%</span></li>
                  <li><strong>Sedang:</strong> <span id="sedang-confidence"></span></li>
                  <li><strong>Tinggi:</strong> <span id="tinggi-confidence"></span></li>
                </ul>
              </div>
            </div>
            <div class="col-md-4">
              <div class="bg-custom p-4 my-3 border rounded">
                <div class="row">
                  <div class="col-md-10">
                    <h5 class="text-body">Avg Velocity</h5>
                  </div>
                  <div class="col-md-2 d-flex justify-content-center align-items-center bg-primary-subtle border border primary rounded-circle" style="aspect-ratio: 1/1;">
                    <i class="bi bi-speedometer2 fs-4"></i>
                  </div>
                </div>
                <h4 id="avgVelocity"></h4>
                <div class="row mt-2">
                  <div class="col-md-12">
                    <div class="btn btn-link p-0"  onclick="showInsight('velocity')"><i class="bi bi-info-circle"></i> Lihat Insight</div>
                  </div>
                </div>
              </div>
            </div>
            <div class="col-md-4">
              <div class="bg-custom p-4 my-3 border rounded">
                <div class="row">
                  <div class="col-md-10">
                    <h5 class="text-body">Fixation Ratio</h5>
                  </div>
                  <div class="col-md-2 d-flex justify-content-center align-items-center bg-primary-subtle border border primary rounded-circle" style="aspect-ratio: 1/1;">
                    <i class="bi bi-bullseye fs-4"></i>
                  </div>
                </div>
                <h4 id="fixationRatio"></h4>
                <div class="row mt-2">
                  <div class="col-md-12">
                    <div class="btn btn-link p-0" onclick="showInsight('fixation')"><i class="bi bi-info-circle"></i> Lihat Insight</div>
                  </div>
                </div>
              </div>
            </div>
            <div class="col-md-4">
              <div class="bg-custom p-4 my-3 border rounded">
                <div class="row">
                  <div class="col-md-10">
                    <h5 class="text-body">Total Eye Distance</h5>
                  </div>
                  <div class="col-md-2 d-flex justify-content-center align-items-center bg-primary-subtle border border primary rounded-circle" style="aspect-ratio: 1/1;">
                    <i class="bi bi-arrows-fullscreen fs-4"></i>
                  </div>
                </div>
                <h4 id="totalDistance"></h4>
                <div class="row mt-2">
                  <div class="col-md-12">
                    <div class="btn btn-link p-0" onclick="showInsight('distance')"><i class="bi bi-info-circle"></i> Lihat Insight</div>
                  </div>
                </div>
              </div>
            </div>
            <div class="col-md-4">
              <div class="bg-custom p-4 my-3 border rounded">
                <div class="row">
                  <div class="col-md-10">
                    <h5 class="text-body">Most Viewed Area</h5>
                  </div>
                  <div class="col-md-2 d-flex justify-content-center align-items-center bg-primary-subtle border border primary rounded-circle" style="aspect-ratio: 1/1;">
                    <i class="bi bi-geo-alt fs-4"></i>
                  </div>
                </div>
                <h4 id="mostViewedArea"></h4>
                <div class="row mt-2">
                  <div class="col-md-12">
                    <div class="btn btn-link p-0" onclick="showInsight('area')"><i class="bi bi-info-circle"></i> Lihat Insight</div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
    <div class="container mt-5" data-aos="fade-up" data-aos-delay="100">
      <div class="row">
        <div class="col-lg-12">
          <h2 class="title text-center">Tabel soal yang telah dijawab</h2>
        </div>
        <div class="col-md-12 mt-2">
          <table class="table" id="table-data-hasil-ujian">
            <thead>
              <tr>
                <th>No</th>
                <th>Pertanyaan</th>
                <th>Jawaban</th>
                <th>Skor</th>
              </tr>
            </thead>
            <tbody></tbody>
          </table>
        </div>

        <div class="col-lg-12">
          <h2 class="title text-center">Tabel soal yang tidak dijawab</h2>
        </div>
        <div class="col-md-12 mt-2">
          <table class="table" id="table-data-soal-not-answer">
            <thead>
              <tr>
                <th>No</th>
                <th>Pertanyaan</th>
                <th>Jawaban</th>
                <th>Skor</th>
              </tr>
            </thead>
            <tbody></tbody>
          </table>
        </div>
      </div>
    </div>

    <div class="container mt-5">
      <div class="row">
        <div class="col-lg-12">
          <h2 class="title text-center">Grafik Kecepatan Mata</h2>
          <canvas id="velocityChart"></canvas>
        </div>
        <div class="col-lg-12 mt-5">
          <h2 class="title text-center">Heatmap Pergerakan Mata</h2>
          <div style="position: relative; aspect-ratio: 16/9;">
            <img src="{{ asset('assets/users/assets/img/overlay/overlay.png') }}" style="width:100%; height:100%; object-fit: cover; position: absolute;">
            <div id="heatmapChart" style="aspect-ratio: 16/9;"></div>
          </div>
        </div>
        <div class="col-lg-12 mt-5">
          <h2 class="title text-center">Heatmap Pergerakan Mata (Grid)</h2>
          <div style="position: relative; aspect-ratio: 16/9;">
            <img src="{{ asset('assets/users/assets/img/overlay/overlay_grid.png') }}" style="width:100%; height:100%; object-fit: cover; position: absolute;">
            <div id="heatmapChartGrid" style="aspect-ratio: 16/9;"></div>
          </div>
        </div>
      </div>
    </div>
  </section><!-- /About Section -->

  <div class="toast-container position-fixed bottom-0 end-0 p-3">
    <div id="liveToast" class="toast" role="alert" aria-live="assertive" aria-atomic="true">
      <div class="toast-header">
        <strong class="me-auto"><i class="bi bi-exclamation-triangle"></i> Kesalahan</strong>
        <button type="button" class="btn-close" data-bs-dismiss="toast" aria-label="Close"></button>
      </div>
      <div class="toast-body">
        {{ session('error') }}
      </div>
    </div>
  </div>

@endsection

@section('script')
  <script>
    const ws = new WebSocket('{{ env("WEBSOCKET_URL") }}');
    let table = null;
    let data_tobii = null;
    let heatmapContainer = null;
    let clientWidth = null;
    let clientHeight = null;
    let recordedScreenWidth = null
    let recordedScreenHeight = null
    let mappedHeatmapData = null;
    let mappedHeatmapDataGrid = null;
    let scaleX = null;
    let scaleY = null;
    let heatmapInstance = null;
    let heatmapInstanceGrid = null;
    let score = null;
    let totalScore = null;
    let soalTerjawab = 0;

    function renderVelocityChart(timeseries) {
      const base = timeseries.timestamp[0];
      const labels = timeseries.timestamp.map(t => (t - base) / 1000);
      const ctx = document.getElementById('velocityChart').getContext('2d');

      new Chart(ctx, {
        type: 'line',
        data: {
          labels: labels,
          datasets: [{
            label: 'Velocity',
            data: timeseries.velocity,
            borderWidth: 2,
            tension: 0.3
          }]
        },
        options: {
          responsive: true,
          plugins: {
            tooltip: {
              callbacks: {
                label: function(context) {
                  return "Velocity: " + context.raw.toFixed(4);
                }
              }
            }
          },
          scales: {
            x: {
              display: false
            }
          }
        }
      });
    }

    async function loadData(data) {
      const res = await fetch("{{ env('PYTHON_API_URL') }}/extract", {
        method: "POST",
        headers: {
            "Content-Type": "application/json"
        },
        body: JSON.stringify(data)
      });

      const result = await res.json();
      if(result != null) {
        renderVelocityChart(result.timeseries);
        mappedHeatmapData = result.heatmap.map(point => ({
          x: point.x * scaleX,
          y: point.y * scaleY,
          value: point.value
        }));
        heatmapInstance.setData({
          max: 10,
          data: mappedHeatmapData
        });
        mappedHeatmapDataGrid = result.heatmap.map(point => ({
          x: point.x * scaleX,
          y: point.y * scaleY,
          value: point.value
        }));
        heatmapInstanceGrid.setData({
          max: 10,
          data: mappedHeatmapDataGrid
        });
        heatmapContainer.style.removeProperty('position');
        renderStats(result.statistics);
      }
    }

    async function getPredict(data) {
      const res = await fetch("{{ env('PYTHON_API_URL') }}/predict", {
        method: "POST",
        headers: {
            "Content-Type": "application/json"
        },
        body: JSON.stringify(data)
      });

      const result = await res.json();
      if(result != null) {
        let classBg = ['text-success', 'text-warning', 'text-danger'];
        let textResult = ['Normal', 'Sedang', 'Tinggi'];
        $('#result-model').addClass(classBg[result.hasil_prediksi]);
        $('#result-model').html(textResult[result.hasil_prediksi]);
        $('#confidence-model').html(result.confidence + '%');
        $('#normal-confidence').html(result.detail_probabilitas.normal + "%");
        $('#sedang-confidence').html(result.detail_probabilitas.sedang + "%");
        $('#tinggi-confidence').html(result.detail_probabilitas.tinggi + "%");
        Swal.close();
      }
    }

    function renderStats(stats) {
      document.getElementById("avgVelocity")
          .innerText = stats.avg_velocity.toFixed(4);

      document.getElementById("fixationRatio")
          .innerText = stats.fixation_ratio.toFixed(2) + "%";

      document.getElementById("totalDistance")
          .innerText = stats.total_distance.toFixed(2);

      document.getElementById("mostViewedArea")
          .innerText = stats.most_viewed_area;
    }

    function showInsight(type) { 
      let title = null;
      let html = null;
      
      if(type === "velocity") {
        title = "Avg Velocity";
        html = `
          <p>
            Rata-rata kecepatan gerakan mata selama ujian.
          </p>
          <hr>
          <b>Nilai tinggi:</b>
          <p>
            Mata aktif berpindah area,
            Aktivitas visual tinggi
          </p>
          <b>Nilai rendah:</b>
          <p>
            Fokus lebih stabil,
            Gerakan mata lebih tenang
          </p>
        `;
    } else if(type === "fixation") {
      title = "Fixation Ratio";

      html = `
        <p>
          Persentase waktu mata berada pada area tertentu.
        </p>
        <hr>
        <b>Semakin tinggi:</b>
        <p>
          Fokus lebih lama pada suatu area,
          Perhatian lebih stabil
        </p>
      `;
    }

    else if(type === "distance") {
      title = "Total Eye Distance";
      html = `
        <p>
          Total jarak perpindahan mata selama ujian.
        </p>
        <hr>
        <b>Nilai besar:</b>
        <p>
          Mata banyak menjelajah layar,
          Aktivitas visual tinggi
        </p>
      `;
    }

    else if(type === "area") {
      title = "Most Viewed Area";
      html = `
        <p>
          Area layar yang paling sering dilihat selama ujian.
        </p>
        <hr>
        <b>Insight:</b>
        <p>
          Menunjukkan fokus utama pengguna,
          Dapat membantu memahami pola perhatian
        </p>
      `;
    } else {
      title = "Huh?";
      html = `<h1>Hello There :D</h1>`;
    }

      Swal.fire({
        title: title,
        html: html,
        icon: 'info',
        showConfirmButton: true,
      });
    }

    $(document).ready(function() {
      table = new DataTable("#table-data-hasil-ujian", {
        searching: false,
        paging: false,
        ajax: {
          url: '{{ route('hasil-tes.getAllAnswer', ['id_test_sessions' => $id_session]) }}',
          dataSrc: 'data' // Specify the key containing the data array
        },
        columns: [
          {
            data: null,
            render: function(data, type, row, meta) {
              return meta.row + 1;
            }
          },
          {
            data: 'soal'
          },
          {
            data: null,
            render: function(data, type, row) {
              let renderedJawaban = null;

              if(row.jawaban_key == 'a') {
                if(row.is_reverse == 1) {
                  renderedJawaban = `<span class="badge text-bg-danger">${row.jawaban}</span>`;
                } else {
                  renderedJawaban = `<span class="badge text-bg-primary">${row.jawaban}</span>`;
                }
              } else if(row.jawaban_key == 'b') {
                if(row.is_reverse == 1) {
                  renderedJawaban = `<span class="badge text-bg-warning">${row.jawaban}</span>`;
                } else {
                  renderedJawaban = `<span class="badge" style="background-color: #fc7938; color: white;">${row.jawaban}</span>`;
                }
              } else if(row.jawaban_key == 'c') {
                if(row.is_reverse == 1) {
                  renderedJawaban = `<span class="badge" style="background-color: #fc7938; color: white;">${row.jawaban}</span>`;
                } else {
                  renderedJawaban = `<span class="badge text-bg-warning">${row.jawaban}</span>`;
                }
              } else if(row.jawaban_key == 'd') {
                if(row.is_reverse == 1) {
                  renderedJawaban = `<span class="badge text-bg-primary">${row.jawaban}</span>`;
                } else {
                  renderedJawaban = `<span class="badge text-bg-danger">${row.jawaban}</span>`;
                }
              } else if(row.jawaban_key == 'e') {
                renderedJawaban = `<span class="badge text-bg-success">${row.jawaban}</span>`;
                score = 5;
              } else {
                renderedJawaban = `<span class="badge text-bg-secondary">${row.jawaban}</span>`;
              }
              return renderedJawaban;
            }
          },
          {
            data: 'skor',
          }
        ]
      });

      table = new DataTable("#table-data-soal-not-answer", {
        searching: false,
        paging: false,
        ajax: {
          url: '{{ route('hasil-tes.getNotAnswered', ['id_test_sessions' => $id_session]) }}',
          dataSrc: 'data' // Specify the key containing the data array
        },
        columns: [
          {
            data: null,
            render: function(data, type, row, meta) {
              return meta.row + 1;
            }
          },
          {
            data: 'soal'
          },
          {
            data: null,
            render: function(data, type, row, meta) {
              return `<span class="badge text-bg-secondary">Tidak dijawab</span>`;
            }
          },
          {
            data: 'skor'
          }
        ]
      });

      ws.onopen = () => {
        console.log("Connected to WebSocket");
        Swal.fire({
          title: 'Status',
          text: 'Memuat data...',
          icon: 'info',
          showConfirmButton: false,
          allowOutsideClick: false,
          allowEscapeKey: false
        });

        ws.send(JSON.stringify({
          type: 'get_json_file',
          session_id: '{{ $id_session }}'
        }));

        ws.onmessage = (event) => {
          const data = JSON.parse(event.data);
          // console.log(data);
          if(data.type === 'json_file_data') {
            if(data.data != null) {
              data_tobii = null;
              let xhttp = new XMLHttpRequest();

              xhttp.onreadystatechange = function() {
                if(this.readyState == 4 && this.status == 200) {
                  let data_ = JSON.parse(this.responseText);
                  $('#total_movement').html(data.data.length + " (1 detik = 3 pergerakan)");
                  if(data_.status) {
                    heatmapContainer = document.getElementById('heatmapChart');
                    clientWidth = heatmapContainer.clientWidth;
                    clientHeight = heatmapContainer.clientHeight;
                    recordedScreenWidth = data_.screen_w;
                    recordedScreenHeight = data_.screen_h;
                    scaleX = clientWidth / recordedScreenWidth;
                    scaleY = clientHeight / recordedScreenHeight;

                    data_tobii = {
                      data: data.data,
                      screen_w: recordedScreenWidth,
                      screen_h: recordedScreenHeight
                    };
                    
                    heatmapInstance = h337.create({
                      container: heatmapContainer,
                      radius: 40,
                      maxOpacity: 0.6,
                      blur: 0.85
                    });
                    heatmapInstanceGrid = h337.create({
                      container: document.getElementById('heatmapChartGrid'),
                      radius: 40,
                      maxOpacity: 0.6,
                      blur: 0.85
                    });
                    loadData(data_tobii);
                    getPredict(data_tobii.data);
                  } else {
                    Swal.fire({
                      title: 'Error',
                      text: 'Gagal mencari data, silahkan coba lagi nanti',
                      icon: 'error',
                      showConfirmButton: true,
                      allowOutsideClick: false,
                      allowEscapeKey: false
                    });
                  }
                }
              };

              xhttp.open('GET', '{{ route('test-sessions.getScreen', ['id_test_sessions' => $id_session]) }}', true);
              xhttp.send();
            } else {
              Swal.fire({
                title: 'Error',
                text: 'Gagal memuat data mata, silahkan coba lagi nanti',
                icon: 'error',
                showConfirmButton: true,
                allowOutsideClick: false,
                allowEscapeKey: false
              });
            }
          }
        };
      };
    });
  </script>

  @if (session('error'))
    <script>
      $(document).ready(function() {
        var toast = new bootstrap.Toast(document.getElementById('liveToast'));
        toast.show();
      });
    </script>
  @endif
@endsection