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

// Fetch all countries
try {
    $stmt = $pdo->prepare("SELECT * FROM otp_server ORDER BY id DESC");
    $stmt->execute();
    $countries = $stmt->fetchAll(PDO::FETCH_ASSOC);
} catch (PDOException $e) {
    $countries = [];
    error_log("Error fetching countries: " . $e->getMessage());
}

// Fetch all APIs for the dropdowns
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 = [];
    error_log("Error fetching APIs: " . $e->getMessage());
}

// Load current price settings
try {
    $ps_stmt = $pdo->query("SELECT setting_key, setting_value FROM price_settings");
    $price_settings_raw = $ps_stmt->fetchAll(PDO::FETCH_KEY_PAIR);
} catch (PDOException $e) {
    $price_settings_raw = [];
}
$current_markup = $price_settings_raw['markup_percent'] ?? '35';
$current_rate   = $price_settings_raw['usd_to_ngn']     ?? '1600';
$rate_updated   = $price_settings_raw['rate_updated_at'] ?? 'Never';
$auto_refresh   = $price_settings_raw['auto_refresh_enabled'] ?? '0';
?>
  <title>Manage Countries - <?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">Manage Countries</h1>
      <ol class="breadcrumb">
        <li class="breadcrumb-item"><a href="dashboard.php">Home</a></li>
        <li class="breadcrumb-item active" aria-current="page">Manage Countries</li>
      </ol>
    </div>

    <!-- ══ PRICE SETTINGS CARD ══════════════════════════════════════════════ -->
    <div class="row mb-4">
      <div class="col-lg-12">
        <div class="card border-left-primary shadow">
          <div class="card-header py-3 d-flex align-items-center justify-content-between">
            <h6 class="m-0 font-weight-bold text-primary">
              <i class="fas fa-sliders-h mr-2"></i>Live Pricing Settings
            </h6>
            <span class="badge badge-info px-3 py-2" style="font-size:0.82rem;">
              <i class="fas fa-info-circle mr-1"></i>
              Prices are auto-converted from USD to ₦ with your markup at purchase time
            </span>
          </div>
          <div class="card-body">
            <div class="row align-items-end">

              <!-- Markup % -->
              <div class="col-md-3">
                <label class="font-weight-bold text-gray-700 small">
                  <i class="fas fa-percent mr-1 text-primary"></i>Markup Percentage
                </label>
                <div class="input-group input-group-sm">
                  <input type="number" id="markup_input" class="form-control"
                         value="<?php echo htmlspecialchars($current_markup); ?>"
                         min="0" max="10000" step="0.1"
                         placeholder="e.g. 35">
                  <div class="input-group-append">
                    <span class="input-group-text">%</span>
                  </div>
                </div>
                <small class="text-muted">Added on top of converted ₦ price</small>
              </div>

              <!-- Exchange Rate - USD only -->
              <div class="col-md-4">
                <label class="font-weight-bold text-gray-700 small">
                  <i class="fas fa-exchange-alt mr-1 text-success"></i>USD → NGN Rate
                </label>

                <!-- USD Rate Input -->
                <div class="input-group input-group-sm mb-2">
                  <div class="input-group-prepend"><span class="input-group-text" style="font-size:0.75rem;">$1 USD =</span></div>
                  <input type="number" id="usd_rate_input" class="form-control"
                         value="<?php echo htmlspecialchars($current_rate); ?>"
                         min="0" step="0.01" placeholder="1600"
                         title="USD to NGN rate">
                  <div class="input-group-append">
                    <span class="input-group-text">₦</span>
                  </div>
                </div>

                <small class="text-muted"><i class="fas fa-clock mr-1"></i>Last Updated: <span id="rate_updated_time"><?php echo htmlspecialchars($rate_updated); ?></span></small>
              </div>

              <!-- Auto-Refresh Toggle -->
              <div class="col-md-3">
                <div class="form-group">
                  <label class="font-weight-bold text-gray-700 small">
                    <i class="fas fa-sync-alt mr-1 text-info"></i>Auto Refresh
                  </label>
                  <div class="custom-control custom-switch">
                    <input type="checkbox" class="custom-control-input" id="auto_refresh_toggle"
                           <?php echo ($auto_refresh == '1') ? 'checked' : ''; ?>>
                    <label class="custom-control-label" for="auto_refresh_toggle">
                      Enable auto-fetch every hour
                    </label>
                  </div>
                  <small class="text-muted d-block mt-2">When enabled, rates update automatically.</small>
                </div>
              </div>

              <!-- Action Buttons -->
              <div class="col-md-2">
                <div class="d-flex flex-wrap" style="gap:6px;">
                  <button class="btn btn-sm btn-primary" onclick="saveMarkup()" title="Save markup percentage">
                    <i class="fas fa-save mr-1"></i>Save Markup
                  </button>
                  <button class="btn btn-sm btn-warning" onclick="saveRates()" title="Save manual USD rate">
                    <i class="fas fa-check mr-1"></i>Save Rate
                  </button>
                  <button class="btn btn-sm btn-success" onclick="refreshRateLive()" title="Fetch live rate now">
                    <i class="fas fa-sync-alt mr-1"></i>Refresh Now
                  </button>
                </div>
              </div>

            </div>

            <!-- Price Example Row -->
            <div class="row mt-3">
              <div class="col-md-12">
                <div class="alert alert-light border-left-info">
                  <strong><i class="fas fa-calculator mr-2 text-info"></i>Example Calculation:</strong>
                  <p id="price_example_text" class="mb-0" style="font-size:1rem; font-weight:600; color:#1cc88a;">
                    A service priced at $0.50 USD would cost: <span id="price_example_value">₦0.00</span>
                    <br><small class="text-muted">(base + <?php echo htmlspecialchars($current_markup); ?>% markup)</small>
                  </p>
                </div>
              </div>
            </div>

            <!-- Auto-Resync Button -->
            <div class="row mt-3">
              <div class="col-md-12">
                <button class="btn btn-warning" onclick="resyncAllPrices()" style="width: 100%;">
                  <i class="fas fa-tags mr-2"></i>Resync All Service Prices (with current rates)
                </button>
                <small class="text-muted d-block mt-2">
                  <i class="fas fa-info-circle mr-1"></i>This will update ALL service prices using the current USD→₦ rate + markup.
                </small>
              </div>
            </div>

          </div>
        </div>
      </div>
    </div>
    <!-- ══ END PRICE SETTINGS CARD ══════════════════════════════════════════ -->

    <!-- 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-globe mr-2"></i>All Countries
            </h6>
            <div>
              <button class="btn btn-sm btn-success mr-2" onclick="openSyncCountriesModal()">
                <i class="fas fa-sync-alt mr-1"></i> Sync Countries from API
              </button>
              <a href="country_flags.php" target="_blank" class="btn btn-sm btn-info mr-2">
                <i class="fas fa-flag mr-1"></i> Browse Flags
              </a>
              <button class="btn btn-sm btn-primary" onclick="openAddCountryModal()">
                <i class="fas fa-plus mr-1"></i> Add Country
              </button>
            </div>
          </div>
          <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>Flag</th>
                  <th>Country Name</th>
                  <th>Country Code (ISO)</th>
                  <th>API ID</th>
                  <th>Status</th>
                  <th>Actions</th>
                </tr>
              </thead>
              <tbody>
                <?php
                $i = 1;
                foreach ($countries as $data) {
                    $status_class = ($data['status'] == '1') ? 'badge badge-success' : 'badge badge-danger';
                    $status_label = ($data['status'] == '1') ? 'Active' : 'Inactive';
                    $js_name     = addslashes(htmlspecialchars($data['server_name'], ENT_QUOTES));
                    $js_code     = addslashes(htmlspecialchars($data['server_code'], ENT_QUOTES));
                    $js_flag     = addslashes(htmlspecialchars($data['flag_url'] ?? '', ENT_QUOTES));
                    $js_api      = (int)$data['api_id'];
                    $js_status   = (int)$data['status'];
                ?>
                <tr>
                  <td><?php echo $i; ?></td>
                  <td>
                    <?php if (!empty($data['flag_url'])): ?>
                      <img src="<?php echo htmlspecialchars($data['flag_url']); ?>"
                           alt="<?php echo htmlspecialchars($data['server_name']); ?>"
                           class="flag-img-sm"
                           onerror="this.style.display='none'">
                    <?php else: ?>
                      <i class="fas fa-flag text-muted"></i>
                    <?php endif; ?>
                  </td>
                  <td><strong><?php echo htmlspecialchars($data['server_name']); ?></strong></td>
                  <td><code><?php echo htmlspecialchars($data['server_code']); ?></code></td>
                  <td><?php echo htmlspecialchars($data['api_id']); ?></td>
                  <td><span class="<?php echo $status_class; ?>"><?php echo $status_label; ?></span></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="openEditCountryModal(<?php echo $data['id']; ?>, '<?php echo $js_name; ?>', '<?php echo $js_code; ?>', '<?php echo $js_flag; ?>', <?php echo $js_api; ?>, <?php echo $js_status; ?>)">
                          <i class="fas fa-edit text-primary"></i> Edit Country
                        </a>
                        <div class="dropdown-divider"></div>
                        <a class="dropdown-item" href="#"
                           onclick="deleteCountry(<?php echo $data['id']; ?>, '<?php echo $js_name; ?>')">
                          <i class="fas fa-trash text-danger"></i> Delete Country
                        </a>
                      </div>
                    </div>
                  </td>
                </tr>
                <?php $i++; } ?>
              </tbody>
            </table>
          </div>
        </div>
      </div>
    </div>
    <!-- End Row -->

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


  <!-- ===================== SYNC COUNTRIES MODAL ===================== -->
  <div class="modal fade" id="syncCountriesModal" tabindex="-1" role="dialog" aria-labelledby="syncCountriesModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered" role="document">
      <div class="modal-content">
        <div class="modal-header">
          <h5 class="modal-title font-weight-bold text-success" id="syncCountriesModalLabel">
            <i class="fas fa-sync-alt mr-2"></i> Sync Countries 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>
            This will fetch all available countries from smscodes.io and add any new ones to your list.
            Existing countries will have their names updated but <strong>your status settings will be preserved</strong>.
          </div>
          <div class="form-group">
            <label><strong>Select API to sync from</strong></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 id="syncCountriesResult" 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="submitSyncCountries">
            <i class="fas fa-sync-alt mr-1"></i> Start Sync
          </button>
        </div>
      </div>
    </div>
  </div>

  <!-- ===================== ADD COUNTRY MODAL ===================== -->
  <div class="modal fade" id="addCountryModal" tabindex="-1" role="dialog" aria-labelledby="addCountryModalLabel" 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="addCountryModalLabel">
            <i class="fas fa-plus-circle mr-2"></i> Add Country
          </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 API</strong></label>
                <select class="form-control" id="add_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 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>Country Name</strong></label>
                <input type="text" class="form-control" id="add_server_name" placeholder="e.g. United States">
              </div>
            </div>
            <div class="col-md-6">
              <div class="form-group">
                <label><strong>Country ISO Code</strong></label>
                <input type="text" class="form-control" id="add_server_code" placeholder="e.g. us">
                <small class="text-muted">Use lowercase ISO 2-letter code (e.g. us, gb, ng)</small>
              </div>
            </div>
          </div>
          <div class="form-group">
            <label><strong>Country Flag URL</strong></label>
            <div class="input-group mb-1">
              <input type="text" class="form-control" id="add_flag_url"
                     placeholder="e.g. https://flagcdn.com/w160/us.png"
                     oninput="previewFlag('add_flag_url', 'add_flag_preview')">
              <div class="input-group-append">
                <a href="country_flags.php" target="_blank" class="btn btn-info">
                  <i class="fas fa-flag mr-1"></i> Browse Flags
                </a>
              </div>
            </div>
            <small class="text-muted"><i class="fas fa-info-circle mr-1"></i>Open "Browse Flags" to copy a flag URL, then paste it here. Or it will auto-generate from ISO code during sync.</small>
            <div class="mt-2">
              <img id="add_flag_preview" class="flag-preview-box d-none" src="" alt="Flag Preview">
            </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="submitAddCountry">
            <i class="fas fa-plus mr-1"></i> Add Country
          </button>
        </div>
      </div>
    </div>
  </div>

  <!-- ===================== EDIT COUNTRY MODAL ===================== -->
  <div class="modal fade" id="editCountryModal" tabindex="-1" role="dialog" aria-labelledby="editCountryModalLabel" 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="editCountryModalLabel">
            <i class="fas fa-edit mr-2"></i> Edit Country
          </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 API</strong></label>
                <select class="form-control" id="edit_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 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>Country Name</strong></label>
                <input type="text" class="form-control" id="edit_server_name" placeholder="e.g. United States">
              </div>
            </div>
            <div class="col-md-6">
              <div class="form-group">
                <label><strong>Country ISO Code</strong></label>
                <input type="text" class="form-control" id="edit_server_code" placeholder="e.g. us">
                <small class="text-muted">Use lowercase ISO 2-letter code (e.g. us, gb, ng)</small>
              </div>
            </div>
          </div>
          <div class="form-group">
            <label><strong>Country Flag URL</strong></label>
            <div class="input-group mb-1">
              <input type="text" class="form-control" id="edit_flag_url"
                     placeholder="e.g. https://flagcdn.com/w160/us.png"
                     oninput="previewFlag('edit_flag_url', 'edit_flag_preview')">
              <div class="input-group-append">
                <a href="country_flags.php" target="_blank" class="btn btn-info">
                  <i class="fas fa-flag mr-1"></i> Browse Flags
                </a>
              </div>
            </div>
            <small class="text-muted"><i class="fas fa-info-circle mr-1"></i>Open "Browse Flags" to copy a flag URL, then paste it here.</small>
            <div class="mt-2">
              <img id="edit_flag_preview" class="flag-preview-box d-none" src="" alt="Flag Preview">
            </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="submitEditCountry">
            <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>
    // ── Global Variables ──────────────────────────────────────────────
    var currentUsdRate = <?php echo (float)$current_rate; ?>;
    var currentMarkup  = <?php echo (float)$current_markup; ?>;
    var autoRefreshEnabled = <?php echo ($auto_refresh == '1') ? 'true' : 'false'; ?>;
    var autoRefreshInterval = null;

    // ── Update Price Example (USD based) ──────────────────────────────
    function updatePriceExample() {
      var markup   = parseFloat($('#markup_input').val()) || 0;
      var usd_rate = parseFloat($('#usd_rate_input').val()) || currentUsdRate;

      // Example: a service that costs $0.50 USD (typical smscodes.io price)
      var exampleUsd = 0.50;
      var base       = exampleUsd * usd_rate;
      var markupVal  = base * (markup / 100);
      var final_val  = base + markupVal;

      $('#price_example_value').html('₦' + final_val.toLocaleString('en-NG', {minimumFractionDigits: 2, maximumFractionDigits: 2}));
    }

    $('#markup_input, #usd_rate_input').on('input', updatePriceExample);
    updatePriceExample();

    // ── Initialize DataTable ──────────────────────────────────────────
    $(document).ready(function () {
      $('#dataTable').DataTable({
        ordering: true,
        pageLength: 25,
        order: [[2, 'asc']]
      });

      // Set auto-refresh interval if enabled
      if (autoRefreshEnabled) {
        startAutoRefresh();
      }
    });

    // ── Auto-Refresh Toggle ───────────────────────────────────────────
    $('#auto_refresh_toggle').on('change', function() {
      var enabled = this.checked ? '1' : '0';

      $.ajax({
        url: 'ajax/sync_data.php',
        type: 'POST',
        data: { action: 'toggle_auto_refresh', enabled: enabled },
        dataType: 'json',
        success: function(data) {
          if (data.status == '1') {
            autoRefreshEnabled = enabled == '1';
            if (autoRefreshEnabled) {
              startAutoRefresh();
              Swal.fire('Enabled!', 'Auto-refresh is now ON. Rates will update every hour.', 'success');
            } else {
              stopAutoRefresh();
              Swal.fire('Disabled!', 'Auto-refresh is now OFF.', 'info');
            }
          }
        }
      });
    });

    // ── Start Auto-Refresh ────────────────────────────────────────────
    function startAutoRefresh() {
      if (autoRefreshInterval) clearInterval(autoRefreshInterval);
      autoRefreshInterval = setInterval(function() {
        refreshRateLive();
      }, 3600000); // 1 hour
      console.log('Auto-refresh started. Will update rates every 60 minutes.');
    }

    // ── Stop Auto-Refresh ─────────────────────────────────────────────
    function stopAutoRefresh() {
      if (autoRefreshInterval) clearInterval(autoRefreshInterval);
      console.log('Auto-refresh stopped.');
    }

    // ── Save Markup Percentage ────────────────────────────────────────
    function saveMarkup() {
      var markup = $.trim($('#markup_input').val());
      if (markup === '' || isNaN(markup)) {
        Swal.fire('Validation Error', 'Please enter a valid markup percentage.', 'warning');
        return;
      }
      $.ajax({
        url: 'ajax/sync_data.php',
        type: 'POST',
        data: { action: 'save_markup', markup_percent: markup },
        dataType: 'json',
        success: function (data) {
          if (data.status == '1') {
            currentMarkup = parseFloat(markup);
            updatePriceExample();
            Swal.fire({ title: 'Saved!', text: data.msg, icon: 'success', confirmButtonColor: '#1cc88a' });
          } else {
            Swal.fire('Error!', data.msg, 'error');
          }
        },
        error: function () { Swal.fire('Error!', 'An error occurred. Please try again.', 'error'); }
      });
    }

    // ── Save Manual Rate (USD→NGN only) ───────────────────────────────
    function saveRates() {
      var usd_rate = $.trim($('#usd_rate_input').val());

      if (usd_rate === '' || isNaN(usd_rate) || parseFloat(usd_rate) <= 0) {
        Swal.fire('Validation Error', 'Please enter a valid USD rate (greater than 0).', 'warning');
        return;
      }

      $.ajax({
        url: 'ajax/sync_data.php',
        type: 'POST',
        data: {
          action: 'save_rates_manual',
          usd_to_ngn: usd_rate
        },
        dataType: 'json',
        success: function (data) {
          if (data.status == '1') {
            currentUsdRate = parseFloat(usd_rate);
            updatePriceExample();
            Swal.fire({
              title: 'Saved!',
              html: '$1 = ₦' + currentUsdRate.toLocaleString('en-NG', {minimumFractionDigits: 2}),
              icon: 'success',
              confirmButtonColor: '#1cc88a'
            });
          } else {
            Swal.fire('Error!', data.msg, 'error');
          }
        },
        error: function () { Swal.fire('Error!', 'An error occurred. Please try again.', 'error'); }
      });
    }

    // ── Refresh Exchange Rate (Live Fetch — USD only) ──────────────────
    function refreshRateLive() {
      Swal.fire({
        title: 'Refreshing Rate...',
        html: 'Fetching live USD → NGN rate from the API...',
        allowOutsideClick: false,
        allowEscapeKey: false,
        didOpen: () => { Swal.showLoading(); }
      });
      $.ajax({
        url: 'ajax/sync_data.php',
        type: 'POST',
        data: { action: 'refresh_rate' },
        dataType: 'json',
        success: function (data) {
          Swal.close();
          if (data.status == '1') {
            currentUsdRate = parseFloat(data.usd_rate) || currentUsdRate;
            $('#usd_rate_input').val(currentUsdRate.toFixed(2));
            $('#rate_updated_time').text(new Date().toLocaleString());
            updatePriceExample();
            Swal.fire({
              title: 'Updated!',
              html: '$1 = ₦' + currentUsdRate.toLocaleString('en-NG', {minimumFractionDigits: 2}),
              icon: 'success',
              confirmButtonColor: '#1cc88a'
            });
          } else {
            Swal.fire('Warning', data.msg, 'warning');
          }
        },
        error: function () { Swal.close(); Swal.fire('Error!', 'Could not refresh rate.', 'error'); }
      });
    }

    // ── Resync All Service Prices ─────────────────────────────────────
    function resyncAllPrices() {
      Swal.fire({
        title: 'Resync All Prices?',
        html: 'This will re-fetch live USD prices from smscodes.io for every service across all countries, then recalculate prices using the current USD→₦ rate and markup.<br><br><strong>This may take a moment.</strong>',
        icon: 'question',
        showCancelButton: true,
        confirmButtonColor: '#f6c23e',
        cancelButtonColor: '#858796',
        confirmButtonText: 'Yes, Resync',
        cancelButtonText: 'Cancel',
      }).then(function (result) {
        if (!result.isConfirmed) return;
        Swal.fire({
          title: 'Resyncing Prices...',
          html: 'Fetching live prices from smscodes.io...',
          allowOutsideClick: false,
          allowEscapeKey: false,
          didOpen: () => { Swal.showLoading(); }
        });
        $.ajax({
          url: 'ajax/sync_data.php',
          type: 'POST',
          data: { action: 'resync_prices' },
          dataType: 'json',
          success: function (data) {
            Swal.close();
            if (data.status == '1') {
              Swal.fire({ title: 'Done!', html: data.msg, icon: 'success', confirmButtonColor: '#1cc88a' });
            } else {
              Swal.fire('Error!', data.msg, 'error');
            }
          },
          error: function () { Swal.close(); Swal.fire('Error!', 'An error occurred.', 'error'); }
        });
      });
    }

    // ── Open Sync Countries Modal ─────────────────────────────────────
    function openSyncCountriesModal() {
      $('#syncCountriesResult').addClass('d-none').html('');
      $('#submitSyncCountries').prop('disabled', false).html('<i class="fas fa-sync-alt mr-1"></i> Start Sync');
      $('#syncCountriesModal').modal('show');
    }

    // ── Submit Sync Countries ─────────────────────────────────────────
    $('#submitSyncCountries').on('click', function () {
      var api_id = $('#sync_api_id').val();
      if (!api_id) {
        Swal.fire('Validation Error', 'Please select an API.', 'warning');
        return;
      }
      $(this).prop('disabled', true).html('<i class="fas fa-spinner fa-spin mr-1"></i> Syncing...');
      $('#syncCountriesResult').addClass('d-none').html('');

      $.ajax({
        url: 'ajax/sync_data.php',
        type: 'POST',
        data: { action: 'sync_countries', api_id: api_id },
        dataType: 'json',
        success: function (data) {
          $('#submitSyncCountries').prop('disabled', false).html('<i class="fas fa-sync-alt mr-1"></i> Start Sync');
          var alertClass = data.status == '1' ? 'alert-success' : 'alert-danger';
          var icon       = data.status == '1' ? 'fas fa-check-circle' : 'fas fa-exclamation-circle';
          $('#syncCountriesResult')
            .removeClass('d-none')
            .html('<div class="alert ' + alertClass + '"><i class="' + icon + ' mr-2"></i>' + data.msg + '</div>');
          if (data.status == '1') {
            setTimeout(function () {
              $('#syncCountriesModal').modal('hide');
              location.reload();
            }, 2000);
          }
        },
        error: function () {
          $('#submitSyncCountries').prop('disabled', false).html('<i class="fas fa-sync-alt mr-1"></i> Start Sync');
          $('#syncCountriesResult')
            .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>');
        }
      });
    });

    // ── Flag preview helper ───────────────────────────────────────────
    function previewFlag(inputId, previewId) {
      var url = $('#' + inputId).val().trim();
      if (url) {
        $('#' + previewId).attr('src', url).removeClass('d-none');
      } else {
        $('#' + previewId).addClass('d-none').attr('src', '');
      }
    }

    // ── Open Add Modal ────────────────────────────────────────────────
    function openAddCountryModal() {
      $('#add_server_name').val('');
      $('#add_server_code').val('');
      $('#add_flag_url').val('');
      $('#add_api_id').val($('#add_api_id option:first').val());
      $('#add_status').val('1');
      $('#add_flag_preview').addClass('d-none').attr('src', '');
      $('#addCountryModal').modal('show');
    }

    // ── Submit Add Country ────────────────────────────────────────────
    $('#submitAddCountry').on('click', function () {
      var server_name = $.trim($('#add_server_name').val());
      var server_code = $.trim($('#add_server_code').val()).toLowerCase();
      var flag_url    = $.trim($('#add_flag_url').val());
      var api_id      = $('#add_api_id').val();
      var status      = $('#add_status').val();

      if (!server_name || !server_code || !api_id) {
        Swal.fire('Validation Error', 'Country Name, ISO Code and API are required.', 'warning');
        return;
      }

      // Auto-generate flag URL if empty
      if (!flag_url && server_code.length === 2) {
        flag_url = 'https://flagcdn.com/w160/' + server_code + '.png';
      }

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

      $.ajax({
        url: 'ajax/countries.php',
        type: 'POST',
        data: { action: 'add', server_name: server_name, server_code: server_code, flag_url: flag_url, api_id: api_id, status: status },
        dataType: 'json',
        success: function (data) {
          $('#submitAddCountry').prop('disabled', false).html('<i class="fas fa-plus mr-1"></i> Add Country');
          if (data.status == '1') {
            $('#addCountryModal').modal('hide');
            Swal.fire({ title: 'Success!', text: data.msg, icon: 'success', confirmButtonColor: '#1cc88a' })
              .then(() => { location.reload(); });
          } else {
            Swal.fire('Error!', data.msg, 'error');
          }
        },
        error: function () {
          $('#submitAddCountry').prop('disabled', false).html('<i class="fas fa-plus mr-1"></i> Add Country');
          Swal.fire('Error!', 'An error occurred. Please try again.', 'error');
        }
      });
    });

    // ── Open Edit Modal ───────────────────────────────────────────────
    function openEditCountryModal(id, name, code, flag, api_id, status) {
      $('#edit_id').val(id);
      $('#edit_server_name').val(name);
      $('#edit_server_code').val(code);
      $('#edit_flag_url').val(flag);
      $('#edit_api_id').val(api_id);
      $('#edit_status').val(status);

      if (flag) {
        $('#edit_flag_preview').attr('src', flag).removeClass('d-none');
      } else {
        $('#edit_flag_preview').addClass('d-none').attr('src', '');
      }

      $('#editCountryModal').modal('show');
    }

    // ── Submit Edit Country ───────────────────────────────────────────
    $('#submitEditCountry').on('click', function () {
      var id          = $('#edit_id').val();
      var server_name = $.trim($('#edit_server_name').val());
      var server_code = $.trim($('#edit_server_code').val()).toLowerCase();
      var flag_url    = $.trim($('#edit_flag_url').val());
      var api_id      = $('#edit_api_id').val();
      var status      = $('#edit_status').val();

      if (!server_name || !server_code || !api_id) {
        Swal.fire('Validation Error', 'Country Name, ISO Code and API are required.', 'warning');
        return;
      }

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

      $.ajax({
        url: 'ajax/countries.php',
        type: 'POST',
        data: { action: 'edit', id: id, server_name: server_name, server_code: server_code, flag_url: flag_url, api_id: api_id, status: status },
        dataType: 'json',
        success: function (data) {
          $('#submitEditCountry').prop('disabled', false).html('<i class="fas fa-save mr-1"></i> Save Changes');
          if (data.status == '1') {
            $('#editCountryModal').modal('hide');
            Swal.fire({ title: 'Updated!', text: data.msg, icon: 'success', confirmButtonColor: '#1cc88a' })
              .then(() => { location.reload(); });
          } else {
            Swal.fire('Error!', data.msg, 'error');
          }
        },
        error: function () {
          $('#submitEditCountry').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 Country ────────────────────────────────────────────────
    function deleteCountry(id, countryName) {
      Swal.fire({
        title: 'Delete Country?',
        html: `Are you sure you want to delete <strong>${countryName}</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((result) => {
        if (result.isConfirmed) {
          Swal.fire({ title: 'Processing...', html: 'Please wait...', allowOutsideClick: false, allowEscapeKey: false, didOpen: () => { Swal.showLoading(); } });

          $.ajax({
            url: 'ajax/countries.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(() => { location.reload(); });
              } else {
                Swal.fire('Error!', data.msg, 'error');
              }
            },
            error: function () { Swal.close(); Swal.fire('Error!', 'An error occurred. Please try again.', 'error'); }
          });
        }
      });
    }
  </script>

  <style>
    .flag-img-sm {
      width: 44px; height: 28px; object-fit: contain;
      border: 1px solid #e3e6f0; border-radius: 4px; padding: 2px; background: #fff;
    }
    .flag-preview-box {
      width: 100px; height: 62px; object-fit: contain;
      border: 2px solid #e3e6f0; border-radius: 6px; padding: 4px; background: #fff;
    }
    .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; }
    .border-left-primary { border-left: 4px solid #4e73df !important; }
    .custom-switch { padding-top: 0.5rem; }
    .input-group-text { font-weight: 600; min-width: 80px; }
    code { color: #e83e8c; background: #f8f9fc; padding: 2px 5px; border-radius: 3px; font-size: 0.85em; }
  </style>

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