<?php
ob_start();

$api_url = "https://projects.funtashtechnologies.com/gomeetapi/adminpanel/getallcities.php";

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

// Fetch cities
$response = file_get_contents($api_url);
$data = json_decode($response, true);

// Parse cities
$cities = $data['Result'] === "true" ? $data['Data'] : [];
$totalCities = count($cities);
$totalPages = ceil($totalCities / $limit);

// Get current slice
$paginatedCities = array_slice($cities, $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">
      <h1>All Cities</h1>
      <div class="hstack gap-2 ms-auto">
        <a href="../pages/createcity.php" class="btn btn-sm btn-primary"><i class="bi bi-plus-lg me-2"></i> New City</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="citySearch" class="form-control" placeholder="Search city...">
        </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">City Name</th>
          <th scope="col">Action</th>
        </tr>
      </thead>
      <tbody id="cityTableBody">
        <?php if (!empty($paginatedCities)) {
        foreach ($paginatedCities as $city) {
          echo "<tr>
              <td>{$city['id']}</td>
              <td>{$city['city']}</td>
              <td>
                  <a href='updatecity.php?id={$city['id']}' class='btn btn-primary'>Edit</a>
                  <button class='btn btn-sm btn-danger deleteCityBtn' data-id='{$city['id']}'>Delete</button>
              </td>
          </tr>";
          }
        } else {
          echo "<tr><td colspan='3'>No cities 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, $totalCities); ?> to <?php echo min($offset + $limit, $totalCities); ?> of <?php echo $totalCities; ?> cities
        </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() {
    $("#citySearch").on("keyup", function() {
      var value = $(this).val().toLowerCase();
      $("#cityTableBody tr").filter(function() {
        $(this).toggle($(this).text().toLowerCase().indexOf(value) > -1)
      });
    });
  });
</script>
<script>
$(document).on('click', '.deleteCityBtn', function () {
    if (!confirm("Are you sure you want to delete this city?")) return;

    const cityId = $(this).data('id');
    const row = $(this).closest('tr');

$.ajax({
    url: 'https://projects.funtashtechnologies.com//gomeetapi/adminpanel/deletecity.php',
    type: 'POST',
    contentType: 'application/json',
    data: JSON.stringify({ id: cityId }),
    success: function (response) {
        if (response.status) {
            alert(response.message);
            row.remove();
        } else {
            alert("Error: " + response.message);
        }
    },
    error: function (xhr, status, error) {
        alert("An error occurred: " + xhr.statusText);
    }
});

});
</script>


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