<?php
//Developer: core tech web designTechnology
//Whatsapp: +2349162671360
//Telegram: @jeditech
include ('include/header.php');
$page_title = WEB_NAME . " | SMS Services";

// Fetch all countries for dropdowns
try {
    $stmt_countries = $pdo->prepare(
        "SELECT os.id, os.server_name, os.flag_url, os.api_id, ad.api_type AS provider
           FROM otp_server os
           JOIN api_detail ad ON ad.id = os.api_id
          ORDER BY ad.api_type ASC, os.server_name ASC"
    );
    $stmt_countries->execute();
    $countries = $stmt_countries->fetchAll(PDO::FETCH_ASSOC);
} catch (PDOException $e) {
    $countries = [];
    error_log("Error fetching countries: " . $e->getMessage());
}

// Fetch APIs for sync modal
try {
    $stmt_api = $pdo->prepare("SELECT id, api_name FROM api_detail ORDER BY id ASC");
    $stmt_api->execute();
    $apis = $stmt_api->fetchAll(PDO::FETCH_ASSOC);
} catch (PDOException $e) {
    $apis = [];
}

// Build a map of server_id => api_id for auto-selection in the sync modal
$server_api_map = [];
foreach ($countries as $c) {
    $server_api_map[(int)$c['id']] = (int)$c['api_id'];
}
?>
  <title>SMS Services - <?php echo $site_data['web_name']; ?></title>

  <link href="vendor/datatables/dataTables.bootstrap4.min.css" rel="stylesheet">

  <!-- Container Fluid-->
  <div class="container-fluid" id="container-wrapper">
    <div class="d-sm-flex align-items-center justify-content-between mb-4">
      <h1 class="h3 mb-0 text-gray-800">SMS Services</h1>
      <ol class="breadcrumb">
        <li class="breadcrumb-item"><a href="dashboard.php">Home</a></li>
        <li class="breadcrumb-item active" aria-current="page">SMS Services</li>
      </ol>
    </div>

    <!-- Row -->
    <div class="row">
      <div class="col-lg-12">
        <div class="card mb-4">
          <div class="card-header py-3 d-flex flex-row align-items-center justify-content-between">
            <h6 class="m-0 font-weight-bold text-primary">
              <i class="fas fa-sms mr-2"></i>SMS Services
            </h6>
            <div>
              <button class="btn btn-sm btn-success mr-2" onclick="openSyncServicesModal()">
                <i class="fas fa-sync-alt mr-1"></i> Sync Services from API
              </button>
              <button class="btn btn-sm btn-primary" onclick="openAddServiceModal()">
                <i class="fas fa-plus mr-1"></i> Add Service
              </button>
              <button class="btn btn-sm btn-danger ml-2" onclick="deleteAllServices()">
                <i class="fas fa-trash-alt mr-1"></i> Delete All
              </button>
            </div>
          </div>

          <!-- ── Country Selector Bar ── -->
          <div class="px-3 pt-3 pb-3 border-bottom bg-light">
            <div class="d-flex align-items-center flex-wrap" style="gap:10px;">
              <label class="mb-0 font-weight-bold text-muted" for="countrySelect" style="font-size:0.9rem; white-space:nowrap;">
                <i class="fas fa-globe mr-1 text-primary"></i> Select Country:
              </label>
              <select id="countrySelect" class="form-control form-control-sm" style="max-width:280px;">
                <option value="">-- Choose a Country --</option>
                <?php foreach ($countries as $c): ?>
                  <option value="<?php echo (int)$c['id']; ?>"
                          data-name="<?php echo htmlspecialchars($c['server_name']); ?>"
                          data-flag="<?php echo htmlspecialchars($c['flag_url'] ?? ''); ?>"
                          data-api="<?php echo (int)$c['api_id']; ?>"
                          data-provider="<?php echo htmlspecialchars($c['provider'] ?? 'smscodes'); ?>">
                    <?php echo htmlspecialchars($c['server_name']); ?>
                    <?php echo ($c['provider'] ?? 'smscodes') === 'smspva' ? ' [Server1]' : ' [Server2]'; ?>
                  </option>
                <?php endforeach; ?>
              </select>
              <button class="btn btn-sm btn-primary" id="goBtn" onclick="loadServices()">
                <i class="fas fa-arrow-right mr-1"></i> Go
              </button>
              <span id="selectedCountryBadge" class="d-none">
                <span class="badge badge-primary px-3 py-2" style="font-size:0.82rem;">
                  <img id="selectedFlag" src="" alt="" class="filter-flag mr-1" style="display:none;">
                  <span id="selectedCountryName"></span>
                </span>
              </span>
            </div>
          </div>

          <!-- ── Placeholder (shown before a country is chosen) ── -->
          <div id="noSelectionPlaceholder" class="text-center py-5">
            <i class="fas fa-hand-point-up fa-3x text-muted mb-3"></i>
            <p class="text-muted">Please select a country above and click <strong>Go</strong> to view its services.</p>
          </div>

          <!-- ── Loading spinner ── -->
          <div id="loadingSpinner" class="text-center py-5 d-none">
            <i class="fas fa-spinner fa-spin fa-2x text-primary mb-2"></i>
            <p class="text-muted mt-2">Loading services...</p>
          </div>

          <!-- ── Services Table (hidden until a country is loaded) ── -->
          <div id="servicesTableWrapper" class="d-none">
            <!-- Search & Info Bar -->
            <div class="px-3 pt-3 pb-2 d-flex align-items-center justify-content-between flex-wrap" style="gap:10px; border-bottom: 1px solid #e3e6f0;">
              <small id="serviceCountLabel" class="text-muted font-weight-bold mb-2"></small>
              
              <!-- Search Input -->
              <div class="input-group input-group-sm" style="max-width:300px;">
                <div class="input-group-prepend">
                  <span class="input-group-text"><i class="fas fa-search"></i></span>
                </div>
                <input type="text" id="serviceSearch" class="form-control" placeholder="Search by name or ID...">
              </div>
            </div>

            <!-- Table -->
            <div class="table-responsive p-3">
              <table class="table align-items-center table-flush table-hover" id="dataTable">
                <thead class="thead-light">
                  <tr>
                    <th>#</th>
                    <th>Country</th>
                    <th>Service Name</th>
                    <th>Service ID</th>
                    <th>Price (₦)</th>
                    <th>Status</th>
                    <th>Actions</th>
                  </tr>
                </thead>
                <tbody id="servicesTableBody">
                </tbody>
              </table>
            </div>

            <!-- Pagination Controls -->
            <div class="px-3 pb-3 d-flex align-items-center justify-content-between flex-wrap" style="gap:10px;">
              <div>
                <small class="text-muted">
                  Showing <strong id="pageStart">0</strong> to <strong id="pageEnd">0</strong> of <strong id="totalServices">0</strong> services
                </small>
              </div>
              <nav aria-label="Page navigation">
                <ul class="pagination pagination-sm mb-0">
                  <li class="page-item" id="prevPageItem">
                    <button class="page-link" onclick="previousPage()" title="Previous page">
                      <i class="fas fa-chevron-left"></i> Previous
                    </button>
                  </li>
                  <li class="page-item active">
                    <span class="page-link" id="pageInfo">Page 1</span>
                  </li>
                  <li class="page-item" id="nextPageItem">
                    <button class="page-link" onclick="nextPage()" title="Next page">
                      Next <i class="fas fa-chevron-right"></i>
                    </button>
                  </li>
                </ul>
              </nav>
            </div>

          </div>

        </div>
      </div>
    </div>
    <!-- End Row -->

  </div>
  <!-- End Container Fluid -->


  <!-- ===================== SYNC SERVICES MODAL ===================== -->
  <div class="modal fade" id="syncServicesModal" tabindex="-1" role="dialog" aria-labelledby="syncServicesModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered modal-lg" role="document">
      <div class="modal-content">
        <div class="modal-header">
          <h5 class="modal-title font-weight-bold text-success" id="syncServicesModalLabel">
            <i class="fas fa-sync-alt mr-2"></i> Sync Services from API
          </h5>
          <button type="button" class="close" data-dismiss="modal" aria-label="Close">
            <span aria-hidden="true">&times;</span>
          </button>
        </div>
        <div class="modal-body">
          <div class="alert alert-info">
            <i class="fas fa-info-circle mr-2"></i>
            Syncs services from the correct provider based on the selected country:
            <strong>[Server1]</strong> countries use <strong>smspva.com</strong> (<code>/activation/serviceprice</code>),
            <strong>[Server2]</strong> countries use <strong>smscodes.io</strong> (<code>/GetCountryPrices</code>).
            Prices are in <strong>USD</strong> and converted to ₦ with your exchange rate and markup.
          </div>
          <div class="row">
            <div class="col-md-6">
              <div class="form-group">
                <label><strong>Select Country</strong></label>
                <select class="form-control" id="sync_server_id" onchange="autoSelectApi()">
                  <option value="">-- Choose a Country --</option>
                  <?php foreach ($countries as $c): ?>
                    <option value="<?php echo (int)$c['id']; ?>"
                            data-api="<?php echo (int)$c['api_id']; ?>">
                      <?php echo htmlspecialchars($c['server_name']); ?>
                      <?php echo ($c['provider'] ?? 'smscodes') === 'smspva' ? ' [Server1]' : ' [Server2]'; ?>
                    </option>
                  <?php endforeach; ?>
                </select>
              </div>
            </div>
            <div class="col-md-6">
              <div class="form-group">
                <label><strong>API</strong> <small class="text-muted">(auto-selected from country)</small></label>
                <select class="form-control" id="sync_api_id">
                  <?php foreach ($apis as $api): ?>
                    <option value="<?php echo $api['id']; ?>"><?php echo htmlspecialchars($api['api_name']); ?></option>
                  <?php endforeach; ?>
                </select>
              </div>
            </div>
          </div>
          <div id="syncServicesResult" class="d-none mt-3"></div>
        </div>
        <div class="modal-footer">
          <button type="button" class="btn btn-secondary" data-dismiss="modal">Cancel</button>
          <button type="button" class="btn btn-success" id="submitSyncServices">
            <i class="fas fa-sync-alt mr-1"></i> Sync Services
          </button>
        </div>
      </div>
    </div>
  </div>

  <!-- ===================== ADD SERVICE MODAL ===================== -->
  <div class="modal fade" id="addServiceModal" tabindex="-1" role="dialog" aria-labelledby="addServiceModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered modal-lg" role="document">
      <div class="modal-content">
        <div class="modal-header">
          <h5 class="modal-title font-weight-bold text-primary" id="addServiceModalLabel">
            <i class="fas fa-plus-circle mr-2"></i> Add New Service
          </h5>
          <button type="button" class="close" data-dismiss="modal" aria-label="Close">
            <span aria-hidden="true">&times;</span>
          </button>
        </div>
        <div class="modal-body">
          <div class="row">
            <div class="col-md-6">
              <div class="form-group">
                <label><strong>Select Country</strong></label>
                <select class="form-control" id="add_server_id">
                  <?php foreach ($countries as $c): ?>
                    <option value="<?php echo $c['id']; ?>">
                      <?php echo htmlspecialchars($c['server_name']); ?>
                    </option>
                  <?php endforeach; ?>
                </select>
              </div>
            </div>
            <div class="col-md-6">
              <div class="form-group">
                <label><strong>Status</strong></label>
                <select class="form-control" id="add_status">
                  <option value="1">Active</option>
                  <option value="0">Inactive</option>
                </select>
              </div>
            </div>
          </div>
          <div class="row">
            <div class="col-md-6">
              <div class="form-group">
                <label><strong>Service Name</strong></label>
                <input type="text" class="form-control" id="add_service_name" placeholder="e.g. WhatsApp">
              </div>
            </div>
            <div class="col-md-6">
              <div class="form-group">
                <label><strong>Service ID</strong></label>
                <input type="text" class="form-control" id="add_service_id" placeholder="e.g. whatsapp (smscodes.io ServiceId)">
              </div>
            </div>
          </div>
          <div class="form-group">
            <label><strong>Service Price (₦)</strong></label>
            <div class="input-group">
              <div class="input-group-prepend">
                <span class="input-group-text">₦</span>
              </div>
              <input type="number" step="0.01" min="0" class="form-control" id="add_service_price" placeholder="e.g. 3000.00">
            </div>
            <small class="text-muted"><i class="fas fa-info-circle mr-1"></i>You can leave this blank if you plan to sync prices automatically.</small>
          </div>
        </div>
        <div class="modal-footer">
          <button type="button" class="btn btn-secondary" data-dismiss="modal">Cancel</button>
          <button type="button" class="btn btn-primary" id="submitAddService">
            <i class="fas fa-plus mr-1"></i> Add Service
          </button>
        </div>
      </div>
    </div>
  </div>

  <!-- ===================== EDIT SERVICE MODAL ===================== -->
  <div class="modal fade" id="editServiceModal" tabindex="-1" role="dialog" aria-labelledby="editServiceModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered modal-lg" role="document">
      <div class="modal-content">
        <div class="modal-header">
          <h5 class="modal-title font-weight-bold text-primary" id="editServiceModalLabel">
            <i class="fas fa-edit mr-2"></i> Edit Service
          </h5>
          <button type="button" class="close" data-dismiss="modal" aria-label="Close">
            <span aria-hidden="true">&times;</span>
          </button>
        </div>
        <div class="modal-body">
          <input type="hidden" id="edit_id">
          <div class="row">
            <div class="col-md-6">
              <div class="form-group">
                <label><strong>Select Country</strong></label>
                <select class="form-control" id="edit_server_id">
                  <?php foreach ($countries as $c): ?>
                    <option value="<?php echo $c['id']; ?>">
                      <?php echo htmlspecialchars($c['server_name']); ?>
                    </option>
                  <?php endforeach; ?>
                </select>
              </div>
            </div>
            <div class="col-md-6">
              <div class="form-group">
                <label><strong>Status</strong></label>
                <select class="form-control" id="edit_status">
                  <option value="1">Active</option>
                  <option value="0">Inactive</option>
                </select>
              </div>
            </div>
          </div>
          <div class="row">
            <div class="col-md-6">
              <div class="form-group">
                <label><strong>Service Name</strong></label>
                <input type="text" class="form-control" id="edit_service_name" placeholder="e.g. WhatsApp">
              </div>
            </div>
            <div class="col-md-6">
              <div class="form-group">
                <label><strong>Service ID</strong></label>
                <input type="text" class="form-control" id="edit_service_id" placeholder="e.g. whatsapp (smscodes.io ServiceId)">
              </div>
            </div>
          </div>
          <div class="form-group">
            <label><strong>Service Price (₦)</strong></label>
            <div class="input-group">
              <div class="input-group-prepend">
                <span class="input-group-text">₦</span>
              </div>
              <input type="number" step="0.01" min="0" class="form-control" id="edit_service_price" placeholder="e.g. 3000.00">
            </div>
          </div>
        </div>
        <div class="modal-footer">
          <button type="button" class="btn btn-secondary" data-dismiss="modal">Cancel</button>
          <button type="button" class="btn btn-primary" id="submitEditService">
            <i class="fas fa-save mr-1"></i> Save Changes
          </button>
        </div>
      </div>
    </div>
  </div>


  <!-- Page level plugins -->
  <script src="vendor/datatables/jquery.dataTables.min.js"></script>
  <script src="vendor/datatables/dataTables.bootstrap4.min.js"></script>
  <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>

  <script>
    var currentServerId = null;
    var allServices     = [];
    var filteredServices = [];
    var currentPage     = 1;
    var itemsPerPage    = 10;

    // ── Auto-select API when country changes in sync modal ────────────
    function autoSelectApi() {
      var opt = $('#sync_server_id option:selected');
      var apiId = opt.data('api');
      if (apiId) {
        $('#sync_api_id').val(apiId);
      }
    }

    // ── Open Sync Services Modal ──────────────────────────────────────
    function openSyncServicesModal() {
      $('#syncServicesResult').addClass('d-none').html('');
      $('#submitSyncServices').prop('disabled', false).html('<i class="fas fa-sync-alt mr-1"></i> Sync Services');
      // Pre-select current country if one is loaded
      if (currentServerId) {
        $('#sync_server_id').val(currentServerId);
        autoSelectApi();
      }
      $('#syncServicesModal').modal('show');
    }

    // ── Submit Sync Services ──────────────────────────────────────────
    $('#submitSyncServices').on('click', function () {
      var server_id = $('#sync_server_id').val();
      var api_id    = $('#sync_api_id').val();

      if (!server_id || !api_id) {
        Swal.fire('Validation Error', 'Please select both a country and an API.', 'warning');
        return;
      }

      $(this).prop('disabled', true).html('<i class="fas fa-spinner fa-spin mr-1"></i> Syncing...');
      $('#syncServicesResult').addClass('d-none').html('');

      $.ajax({
        url: 'ajax/sync_data.php',
        type: 'POST',
        data: { action: 'sync_services', server_id: server_id, api_id: api_id },
        dataType: 'json',
        success: function (data) {
          $('#submitSyncServices').prop('disabled', false).html('<i class="fas fa-sync-alt mr-1"></i> Sync Services');
          var alertClass = data.status == '1' ? 'alert-success' : 'alert-danger';
          var icon       = data.status == '1' ? 'fas fa-check-circle' : 'fas fa-exclamation-circle';
          $('#syncServicesResult')
            .removeClass('d-none')
            .html('<div class="alert ' + alertClass + '"><i class="' + icon + ' mr-2"></i>' + data.msg + '</div>');
          if (data.status == '1') {
            // Refresh the table after a short delay
            setTimeout(function () {
              $('#syncServicesModal').modal('hide');
              if (currentServerId) { loadServices(); }
            }, 2000);
          }
        },
        error: function () {
          $('#submitSyncServices').prop('disabled', false).html('<i class="fas fa-sync-alt mr-1"></i> Sync Services');
          $('#syncServicesResult')
            .removeClass('d-none')
            .html('<div class="alert alert-danger"><i class="fas fa-exclamation-circle mr-2"></i>An error occurred. Please try again.</div>');
        }
      });
    });

    // ── Load Services by Country (AJAX) ───────────────────────────────
    function loadServices() {
      var select      = document.getElementById('countrySelect');
      var serverId    = select.value;
      var option      = select.options[select.selectedIndex];
      var countryName = option ? option.getAttribute('data-name') : '';
      var flagUrl     = option ? option.getAttribute('data-flag') : '';

      if (!serverId) {
        Swal.fire('Select Country', 'Please select a country first.', 'warning');
        return;
      }

      currentServerId = serverId;
      currentPage = 1;

      $('#selectedCountryName').text(countryName);
      if (flagUrl) {
        $('#selectedFlag').attr('src', flagUrl).show();
      } else {
        $('#selectedFlag').hide();
      }
      $('#selectedCountryBadge').removeClass('d-none');

      $('#noSelectionPlaceholder').addClass('d-none');
      $('#servicesTableWrapper').addClass('d-none');
      $('#loadingSpinner').removeClass('d-none');

      $.ajax({
        url: 'ajax/sms_services.php',
        type: 'POST',
        data: { action: 'get_by_country', server_id: serverId },
        dataType: 'json',
        success: function (res) {
          $('#loadingSpinner').addClass('d-none');
          if (res.status == '1') {
            allServices = res.services || [];
            filteredServices = allServices;
            $('#serviceSearch').val('');
            renderTable(countryName);
          } else {
            Swal.fire('Error', res.msg || 'Failed to load services.', 'error');
            $('#noSelectionPlaceholder').removeClass('d-none');
          }
        },
        error: function () {
          $('#loadingSpinner').addClass('d-none');
          Swal.fire('Error', 'An error occurred while loading services.', 'error');
          $('#noSelectionPlaceholder').removeClass('d-none');
        }
      });
    }

    // ── Search/Filter Services ────────────────────────────────────────
    $('#serviceSearch').on('keyup', function() {
      var query = $(this).val().toLowerCase();
      
      if (!query) {
        filteredServices = allServices;
      } else {
        filteredServices = allServices.filter(function(svc) {
          var name = (svc.service_name || '').toLowerCase();
          var id   = (svc.service_id || '').toLowerCase();
          return name.includes(query) || id.includes(query);
        });
      }
      
      currentPage = 1;
      renderTable($('#selectedCountryName').text());
    });

    // ── Render Table with Pagination ──────────────────────────────────
    function renderTable(countryName) {
      var tbody = $('#servicesTableBody');
      tbody.empty();

      if (!filteredServices || filteredServices.length === 0) {
        tbody.append(
          '<tr><td colspan="7" class="text-center text-muted py-4">' +
          '<i class="fas fa-inbox fa-2x d-block mb-2"></i>No services found.<br>' +
          '<small>Click <strong>Sync Services from API</strong> to automatically import services.</small></td></tr>'
        );
        $('#serviceCountLabel').html(
          '<i class="fas fa-list mr-1 text-primary"></i> No services for <strong>' + escapeHtml(countryName) + '</strong>'
        );
        $('#servicesTableWrapper').removeClass('d-none');
        updatePaginationControls();
        return;
      }

      // Calculate pagination
      var totalPages = Math.ceil(filteredServices.length / itemsPerPage);
      var startIdx   = (currentPage - 1) * itemsPerPage;
      var endIdx     = Math.min(startIdx + itemsPerPage, filteredServices.length);
      var pageData   = filteredServices.slice(startIdx, endIdx);

      // Render rows
      $.each(pageData, function (idx, svc) {
        var actualIndex = startIdx + idx + 1;
        var statusBadge = svc.status == '1'
          ? '<span class="badge badge-success">Active</span>'
          : '<span class="badge badge-danger">Inactive</span>';

        var flagHtml = svc.flag_url
          ? '<img src="' + escapeHtml(svc.flag_url) + '" alt="" class="flag-img-sm mr-2" onerror="this.style.display=\'none\'">'
          : '';

        var row = '<tr>' +
          '<td>' + actualIndex + '</td>' +
          '<td><div class="d-flex align-items-center">' + flagHtml + '<span>' + escapeHtml(svc.server_name || 'N/A') + '</span></div>' +
            (svc.provider === 'smspva'
              ? '<br><span style="font-size:.6rem;font-weight:700;padding:1px 5px;border-radius:99px;background:rgba(99,102,241,.1);color:#6366f1;border:1px solid rgba(99,102,241,.2);">Server1</span>'
              : '<br><span style="font-size:.6rem;font-weight:700;padding:1px 5px;border-radius:99px;background:rgba(34,184,100,.08);color:#16a354;border:1px solid rgba(34,184,100,.2);">Server2</span>') +
          '</td>' +
          '<td><strong>' + escapeHtml(svc.service_name) + '</strong></td>' +
          '<td><code>' + escapeHtml(svc.service_id) + '</code></td>' +
          '<td><strong>₦' + parseFloat(svc.service_price).toLocaleString('en-NG', {minimumFractionDigits: 2}) + '</strong></td>' +
          '<td>' + statusBadge + '</td>' +
          '<td>' +
            '<div class="btn-group" role="group">' +
              '<button type="button" class="btn btn-sm btn-primary dropdown-toggle" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">' +
                '<i class="fas fa-cog"></i> Actions' +
              '</button>' +
              '<div class="dropdown-menu">' +
                '<a class="dropdown-item" href="#" onclick="openEditServiceModal(' +
                  svc.id + ',\'' + jsEscape(svc.service_name) + '\',\'' + jsEscape(svc.service_id) + '\',' +
                  parseFloat(svc.service_price) + ',' + svc.server_id + ',' + svc.status +
                ')">' +
                  '<i class="fas fa-edit text-primary"></i> Edit Service' +
                '</a>' +
                '<div class="dropdown-divider"></div>' +
                '<a class="dropdown-item" href="#" onclick="deleteService(' + svc.id + ',\'' + jsEscape(svc.service_name) + '\')">' +
                  '<i class="fas fa-trash text-danger"></i> Delete Service' +
                '</a>' +
              '</div>' +
            '</div>' +
          '</td>' +
          '</tr>';

        tbody.append(row);
      });

      // Update info labels
      $('#serviceCountLabel').html(
        '<i class="fas fa-list mr-1 text-primary"></i> Showing <strong>' + pageData.length + '</strong> service(s) for <strong>' + escapeHtml(countryName) + '</strong>'
      );
      $('#pageStart').text(startIdx + 1);
      $('#pageEnd').text(endIdx);
      $('#totalServices').text(filteredServices.length);
      $('#pageInfo').text('Page ' + currentPage + ' of ' + totalPages);

      $('#servicesTableWrapper').removeClass('d-none');
      updatePaginationControls();
    }

    // ── Update Pagination Control States ──────────────────────────────
    function updatePaginationControls() {
      var totalPages = Math.ceil(filteredServices.length / itemsPerPage);
      
      // Enable/disable Previous button
      if (currentPage <= 1) {
        $('#prevPageItem').addClass('disabled');
      } else {
        $('#prevPageItem').removeClass('disabled');
      }

      // Enable/disable Next button
      if (currentPage >= totalPages) {
        $('#nextPageItem').addClass('disabled');
      } else {
        $('#nextPageItem').removeClass('disabled');
      }
    }

    // ── Previous Page ─────────────────────────────────────────────────
    function previousPage() {
      if (currentPage > 1) {
        currentPage--;
        renderTable($('#selectedCountryName').text());
        window.scrollTo(0, 0);
      }
    }

    // ── Next Page ─────────────────────────────────────────────────────
    function nextPage() {
      var totalPages = Math.ceil(filteredServices.length / itemsPerPage);
      if (currentPage < totalPages) {
        currentPage++;
        renderTable($('#selectedCountryName').text());
        window.scrollTo(0, 0);
      }
    }

    function escapeHtml(str) {
      if (!str) return '';
      return String(str).replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;');
    }

    function jsEscape(str) {
      if (!str) return '';
      return String(str).replace(/\\/g, '\\\\').replace(/'/g, "\\'");
    }

    // ── Open Add Modal ────────────────────────────────────────────────
    function openAddServiceModal() {
      $('#add_service_name').val('');
      $('#add_service_id').val('');
      $('#add_service_price').val('');
      if (currentServerId) {
        $('#add_server_id').val(currentServerId);
      } else {
        $('#add_server_id').val($('#add_server_id option:first').val());
      }
      $('#add_status').val('1');
      $('#addServiceModal').modal('show');
    }

    // ── Submit Add Service ────────────────────────────────────────────
    $('#submitAddService').on('click', function () {
      var service_name  = $.trim($('#add_service_name').val());
      var service_id    = $.trim($('#add_service_id').val());
      var service_price = $.trim($('#add_service_price').val()) || '0';
      var server_id     = $('#add_server_id').val();
      var status        = $('#add_status').val();

      if (!service_name || !service_id || !server_id) {
        Swal.fire('Validation Error', 'Service Name, Service ID and Country are required.', 'warning');
        return;
      }

      $('#submitAddService').prop('disabled', true).html('<i class="fas fa-spinner fa-spin mr-1"></i> Adding...');

      $.ajax({
        url: 'ajax/sms_services.php',
        type: 'POST',
        data: { action: 'add', service_name: service_name, service_id: service_id, service_price: service_price, server_id: server_id, status: status },
        dataType: 'json',
        success: function (data) {
          $('#submitAddService').prop('disabled', false).html('<i class="fas fa-plus mr-1"></i> Add Service');
          if (data.status == '1') {
            $('#addServiceModal').modal('hide');
            Swal.fire({ title: 'Success!', text: data.msg, icon: 'success', confirmButtonColor: '#1cc88a' })
              .then(function () { if (currentServerId) { loadServices(); } else { location.reload(); } });
          } else {
            Swal.fire('Error!', data.msg, 'error');
          }
        },
        error: function () {
          $('#submitAddService').prop('disabled', false).html('<i class="fas fa-plus mr-1"></i> Add Service');
          Swal.fire('Error!', 'An error occurred. Please try again.', 'error');
        }
      });
    });

    // ── Open Edit Modal ───────────────────────────────────────────────
    function openEditServiceModal(id, name, sid, price, server_id, status) {
      $('#edit_id').val(id);
      $('#edit_service_name').val(name);
      $('#edit_service_id').val(sid);
      $('#edit_service_price').val(price);
      $('#edit_server_id').val(server_id);
      $('#edit_status').val(status);
      $('#editServiceModal').modal('show');
    }

    // ── Submit Edit Service ───────────────────────────────────────────
    $('#submitEditService').on('click', function () {
      var id            = $('#edit_id').val();
      var service_name  = $.trim($('#edit_service_name').val());
      var service_id    = $.trim($('#edit_service_id').val());
      var service_price = $.trim($('#edit_service_price').val());
      var server_id     = $('#edit_server_id').val();
      var status        = $('#edit_status').val();

      if (!service_name || !service_id || !service_price || !server_id) {
        Swal.fire('Validation Error', 'All fields are required.', 'warning');
        return;
      }

      $('#submitEditService').prop('disabled', true).html('<i class="fas fa-spinner fa-spin mr-1"></i> Saving...');

      $.ajax({
        url: 'ajax/sms_services.php',
        type: 'POST',
        data: { action: 'edit', id: id, service_name: service_name, service_id: service_id, service_price: service_price, server_id: server_id, status: status },
        dataType: 'json',
        success: function (data) {
          $('#submitEditService').prop('disabled', false).html('<i class="fas fa-save mr-1"></i> Save Changes');
          if (data.status == '1') {
            $('#editServiceModal').modal('hide');
            Swal.fire({ title: 'Updated!', text: data.msg, icon: 'success', confirmButtonColor: '#1cc88a' })
              .then(function () { if (currentServerId) { loadServices(); } else { location.reload(); } });
          } else {
            Swal.fire('Error!', data.msg, 'error');
          }
        },
        error: function () {
          $('#submitEditService').prop('disabled', false).html('<i class="fas fa-save mr-1"></i> Save Changes');
          Swal.fire('Error!', 'An error occurred. Please try again.', 'error');
        }
      });
    });

    // ── Delete Service ────────────────────────────────────────────────
    function deleteService(id, serviceName) {
      Swal.fire({
        title: 'Delete Service?',
        html: 'Are you sure you want to delete <strong>' + escapeHtml(serviceName) + '</strong>?<br><small class="text-danger">This action cannot be undone.</small>',
        icon: 'warning',
        showCancelButton: true,
        confirmButtonColor: '#e74a3b',
        cancelButtonColor: '#858796',
        confirmButtonText: 'Yes, Delete',
        cancelButtonText: 'Cancel',
        focusCancel: true
      }).then(function (result) {
        if (result.isConfirmed) {
          Swal.fire({ title: 'Processing...', html: 'Please wait...', allowOutsideClick: false, allowEscapeKey: false, didOpen: function () { Swal.showLoading(); } });
          $.ajax({
            url: 'ajax/sms_services.php',
            type: 'POST',
            data: { action: 'delete', id: id },
            dataType: 'json',
            success: function (data) {
              Swal.close();
              if (data.status == '1') {
                Swal.fire({ title: 'Deleted!', text: data.msg, icon: 'success', confirmButtonColor: '#1cc88a' })
                  .then(function () { if (currentServerId) { loadServices(); } else { location.reload(); } });
              } else {
                Swal.fire('Error!', data.msg, 'error');
              }
            },
            error: function () { Swal.close(); Swal.fire('Error!', 'An error occurred. Please try again.', 'error'); }
          });
        }
      });
    }

    $('#countrySelect').on('keydown', function (e) {
      if (e.key === 'Enter') { loadServices(); }
    });
  </script>

  <style>
    .flag-img-sm {
      width: 36px; height: 22px; object-fit: contain;
      border: 1px solid #e3e6f0; border-radius: 3px; padding: 1px; background: #fff;
    }
    .filter-flag {
      width: 22px; height: 14px; object-fit: contain; border-radius: 2px; vertical-align: middle;
    }
    .btn-group { white-space: nowrap; }
    .dropdown-item { cursor: pointer; }
    .dropdown-item i { width: 20px; margin-right: 5px; }
    .modal-header { border-bottom: 2px solid #e3e6f0; }
    .modal-footer { border-top: 1px solid #e3e6f0; }
    code { color: #e83e8c; background: #f8f9fc; padding: 2px 5px; border-radius: 3px; font-size: 0.85em; }
    #noSelectionPlaceholder i { display: block; margin: 0 auto 12px; }
    .pagination-sm { margin: 0; }
    .pagination .page-item.disabled .page-link { cursor: not-allowed; opacity: 0.5; }
    .page-link { cursor: pointer; user-select: none; }
  </style>

<script>
// ── Delete All SMS Services ──────────────────────────────────────────
function deleteAllServices() {
    Swal.fire({
        title: 'Delete ALL SMS Services?',
        html: '<p class="text-danger"><strong>This will permanently delete ALL services from the database.</strong></p><p>This action cannot be undone.</p>',
        icon: 'warning',
        showCancelButton: true,
        confirmButtonColor: '#e74a3b',
        confirmButtonText: '<i class="fas fa-trash-alt mr-1"></i> Yes, Delete All',
        cancelButtonText: 'Cancel',
        showLoaderOnConfirm: true,
        preConfirm: function() {
            return $.ajax({
                url: 'ajax/sms_services.php',
                type: 'POST',
                data: { action: 'delete_all' },
                dataType: 'json'
            });
        }
    }).then(function(result) {
        if (result.isConfirmed && result.value) {
            if (result.value.status == '1') {
                Swal.fire({icon:'success', title:'Deleted!', text: result.value.msg, timer:2000, showConfirmButton:false})
                    .then(function(){ location.reload(); });
            } else {
                Swal.fire('Error', result.value.msg || 'Delete failed.', 'error');
            }
        }
    });
}
</script>

<?php include ('include/footer.php'); ?>