<?php
ob_start();

// API URL
$api_url = "http://localhost/gomeetapi/adminpanel/allassesments";  // Adjust the URL for your API endpoint

// Pagination setup
$page = isset($_GET['page']) && is_numeric($_GET['page']) ? (int) $_GET['page'] : 1;
$limit = 20;
$offset = ($page - 1) * $limit;

// Fetch data from the API
$response = file_get_contents($api_url);
$data = json_decode($response, true);

// Check if the response is valid
if ($data['Result'] === "true") {
    $assesments = $data['Data'];
} else {
    $assesments = [];
}

$totalAssessments = count($assesments);
$totalPages = ceil($totalAssessments / $limit);

// Get current slice
$paginatedAssessments = array_slice($assesments, $offset, $limit);
?>

<main class="container-fluid p-0">
  <div class="px-6 px-lg-7 pt-8 border-bottom mb-4">
    <div class="d-flex align-items-center mb-5">
      <h1>All Assessments</h1>
      <div class="hstack gap-2 ms-auto">
        <a href="../pages/createassessment.php" class="btn btn-sm btn-primary"><i class="bi bi-plus-lg me-2"></i> New Assessment</a>
      </div>
    </div>
  </div>

  <!-- Search Field -->
  <div class="row float-end m-auto d-flex justify-content-end">
    <div class="px-6 col-md-4">
      <div class="mb-3">
        <input type="text" id="assessmentSearch" class="form-control" placeholder="Search assessment...">
      </div>
    </div>
  </div>

  <div class="table-responsive px-6">
    <table class="table table-hover table-striped table-sm table-nowrap">
      <thead>
        <tr>
          <th scope="col">Id</th>
          <th scope="col">User ID</th>
          <th scope="col">Category ID</th>
          <th scope="col">Question ID</th>
          <th scope="col">Answer</th>
          <th scope="col">Rating</th>
          <th scope="col">Posted At</th>
          <th scope="col">Action</th>
        </tr>
      </thead>
      <tbody id="assessmentTableBody">
      <?php if (!empty($paginatedAssessments)) {
    foreach ($paginatedAssessments as $assessment) {
        echo "<tr>
            <td>{$assessment['id']}</td>
            <td>{$assessment['userid']}</td>
            <td>{$assessment['categoryid']}</td>
            <td>{$assessment['questionid']}</td>
            <td>{$assessment['answer']}</td>
            <td>{$assessment['rating']}</td>
            <td>{$assessment['posted_at']}</td>
            <td>
                <a href='updateassessment.php?id={$assessment['id']}' class='btn btn-primary'>Edit</a>
                <button onclick='deleteAssessment({$assessment['id']})' class='btn btn-danger'>Delete</button>
            </td>
        </tr>";
    }
    } else {
        echo "<tr><td colspan='8'>No assessments found.</td></tr>";
    } ?>

      </tbody>
    </table>
  </div>

  <div class="py-4 px-6">
    <div class="row align-items-center justify-content-between">
      <div class="col-md-6 d-none d-md-block">
        <span class="text-muted text-sm">
          Showing <?php echo min($offset + 1, $totalAssessments); ?> to <?php echo min($offset + $limit, $totalAssessments); ?> of <?php echo $totalAssessments; ?> assessments
        </span>
      </div>
      <div class="col-md-auto">
        <nav aria-label="Page navigation">
          <ul class="pagination pagination-spaced gap-1">
            <?php
            $range = 2;

            if ($page > 1) {
              echo "<li class='page-item'><a class='page-link' href='?page=" . ($page - 1) . "'><i class='bi bi-chevron-left'></i></a></li>";
            }

            if ($totalPages <= 5 + ($range * 2)) {
              for ($i = 1; $i <= $totalPages; $i++) {
                $active = ($i == $page) ? 'active' : '';
                echo "<li class='page-item $active'><a class='page-link' href='?page=$i'>$i</a></li>";
              }
            } else {
              if ($page > $range + 2) {
                echo "<li class='page-item'><a class='page-link' href='?page=1'>1</a></li>";
                echo "<li class='page-item disabled'><span class='page-link'>...</span></li>";
              }

              for ($i = max(1, $page - $range); $i <= min($totalPages, $page + $range); $i++) {
                $active = ($i == $page) ? 'active' : '';
                echo "<li class='page-item $active'><a class='page-link' href='?page=$i'>$i</a></li>";
              }

              if ($page < $totalPages - ($range + 1)) {
                echo "<li class='page-item disabled'><span class='page-link'>...</span></li>";
                echo "<li class='page-item'><a class='page-link' href='?page=$totalPages'>$totalPages</a></li>";
              }
            }

            if ($page < $totalPages) {
              echo "<li class='page-item'><a class='page-link' href='?page=" . ($page + 1) . "'><i class='bi bi-chevron-right'></i></a></li>";
            }
            ?>
          </ul>
        </nav>
      </div>
    </div>
  </div>
</main>

<!-- jQuery CDN + Search Script -->
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
  $(document).ready(function () {
    $("#assessmentSearch").on("keyup", function () {
      var value = $(this).val().toLowerCase();
      $("#assessmentTableBody tr").filter(function () {
        $(this).toggle($(this).text().toLowerCase().indexOf(value) > -1)
      });
    });
  });
</script>

<script>
function deleteAssessment(id) {
    if (!confirm("Are you sure you want to delete this assessment?")) return;

    fetch(`/gomeetapi/deleteassessment/${id}`, {
        method: 'DELETE',
    })
    .then(response => response.json())
    .then(data => {
        alert(data.ResponseMsg);
        if (data.Result === "true") {
            location.reload(); // refresh the table after delete
        }
    })
    .catch(error => {
        console.error("Error:", error);
        alert("Something went wrong while deleting.");
    });
}
</script>


<?php
$content = ob_get_clean();
include '../layouts/master.php';
?>
