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

// Fetch all countries with their provider info
try {
    $stmt_countries = $pdo->prepare(
        "SELECT os.id, os.server_name, os.server_code, os.flag_url, os.api_id, os.status,
                ad.api_type, ad.api_name
           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 = [];
}

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

// Fetch price settings
try {
    $ps_rows = $pdo->query("SELECT setting_key, setting_value FROM price_settings")->fetchAll(PDO::FETCH_KEY_PAIR);
} catch (PDOException $e) {
    $ps_rows = [];
}

$markup_pct         = isset($ps_rows['markup_percent'])         ? (float)$ps_rows['markup_percent']         : 35.0;
$smspva_markup_pct  = isset($ps_rows['smspva_markup_percent'])  ? (float)$ps_rows['smspva_markup_percent']  : 35.0;
$usd_to_ngn         = isset($ps_rows['usd_to_ngn']) && (float)$ps_rows['usd_to_ngn'] > 0 ? (float)$ps_rows['usd_to_ngn'] : 1600.0;
$cron_last_run      = $ps_rows['cron_last_run']           ?? 'Never';
$cron_status        = $ps_rows['cron_last_status']        ?? 'N/A';
$smspva_cron_run    = $ps_rows['smspva_cron_last_run']    ?? 'Never';
$smspva_cron_status = $ps_rows['smspva_cron_last_status'] ?? 'N/A';
$smspva_enabled     = ($ps_rows['smspva_api_enabled'] ?? '1') === '1';

// Per-country last sync times
$country_sync_times = [];
try {
    $sync_rows = $pdo->query(
        "SELECT setting_key, setting_value FROM price_settings
          WHERE setting_key LIKE 'sync_country_%' OR setting_key LIKE 'smspva_sync_country_%'"
    )->fetchAll(PDO::FETCH_ASSOC);
    foreach ($sync_rows as $row) {
        $sid = preg_replace('/^(smspva_)?sync_country_/', '', $row['setting_key']);
        $country_sync_times[$sid] = $row['setting_value'];
    }
} catch (PDOException $e) {}

// Service counts per country
$service_counts = [];
try {
    $sc_rows = $pdo->query("SELECT server_id, COUNT(*) as cnt FROM service GROUP BY server_id")->fetchAll(PDO::FETCH_ASSOC);
    foreach ($sc_rows as $row) {
        $service_counts[(int)$row['server_id']] = (int)$row['cnt'];
    }
} catch (PDOException $e) {}

// Split countries by provider
$smscodes_countries = [];
$smspva_countries   = [];
foreach ($countries as $c) {
    if (($c['api_type'] ?? 'smscodes') === 'smspva') {
        $smspva_countries[] = $c;
    } else {
        $smscodes_countries[] = $c;
    }
}
?>
<title>Sync Services - <?php echo htmlspecialchars($site_data['web_name'] ?? ''); ?></title>

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

<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">Sync Services</h1>
    <ol class="breadcrumb">
      <li class="breadcrumb-item"><a href="dashboard.php">Home</a></li>
      <li class="breadcrumb-item"><a href="sms-services.php">SMS Services</a></li>
      <li class="breadcrumb-item active">Sync Services</li>
    </ol>
  </div>

  <!-- ── Info Cards ── -->
  <div class="row mb-4">
    <div class="col-xl-3 col-md-6 mb-3">
      <div class="card border-left-primary shadow h-100 py-2">
        <div class="card-body">
          <div class="row no-gutters align-items-center">
            <div class="col mr-2">
              <div class="text-xs font-weight-bold text-primary text-uppercase mb-1">USD → NGN Rate <span class="badge badge-success" style="font-size:.6rem;text-transform:none;">Set by Admin</span></div>
              <div class="h5 mb-0 font-weight-bold text-gray-800">₦<?php echo number_format($usd_to_ngn, 2); ?></div>
            </div>
            <div class="col-auto"><i class="fas fa-dollar-sign fa-2x text-gray-300"></i></div>
          </div>
        </div>
      </div>
    </div>
    <div class="col-xl-3 col-md-6 mb-3">
      <div class="card border-left-success shadow h-100 py-2">
        <div class="card-body">
          <div class="row no-gutters align-items-center">
            <div class="col mr-2">
              <div class="text-xs font-weight-bold text-success text-uppercase mb-1">Markup (Server2)</div>
              <div class="h5 mb-0 font-weight-bold text-gray-800"><?php echo $markup_pct; ?>%</div>
              <div class="text-xs text-muted">Server1: <?php echo $smspva_markup_pct; ?>%
                <a href="#smspvaMarkupCard" class="ml-1">Edit</a>
              </div>
            </div>
            <div class="col-auto"><i class="fas fa-percentage fa-2x text-gray-300"></i></div>
          </div>
        </div>
      </div>
    </div>
    <div class="col-xl-3 col-md-6 mb-3">
      <div class="card border-left-info shadow h-100 py-2">
        <div class="card-body">
          <div class="row no-gutters align-items-center">
            <div class="col mr-2">
              <div class="text-xs font-weight-bold text-info text-uppercase mb-1">Countries</div>
              <div class="h5 mb-0 font-weight-bold text-gray-800"><?php echo count($countries); ?></div>
              <div class="text-xs text-muted">
                <span class="badge badge-success"><?php echo count($smscodes_countries); ?> Server2</span>
                <span class="badge badge-primary ml-1"><?php echo count($smspva_countries); ?> Server1</span>
              </div>
            </div>
            <div class="col-auto"><i class="fas fa-globe fa-2x text-gray-300"></i></div>
          </div>
        </div>
      </div>
    </div>
    <div class="col-xl-3 col-md-6 mb-3">
      <div class="card border-left-warning shadow h-100 py-2">
        <div class="card-body">
          <div class="row no-gutters align-items-center">
            <div class="col mr-2">
              <div class="text-xs font-weight-bold text-warning text-uppercase mb-1">Cron Last Run</div>
              <div class="h6 mb-0 font-weight-bold text-gray-800">S2: <?php echo htmlspecialchars($cron_last_run); ?></div>
              <div class="h6 mb-0 font-weight-bold text-gray-800">S1: <?php echo htmlspecialchars($smspva_cron_run); ?></div>
            </div>
            <div class="col-auto"><i class="fas fa-clock fa-2x text-gray-300"></i></div>
          </div>
        </div>
      </div>
    </div>
  </div>

  <!-- ── smspva Settings Card ── -->
  <div class="row mb-4" id="smspvaMarkupCard">
    <div class="col-lg-12">
      <div class="card shadow mb-0">
        <div class="card-header py-3 d-flex flex-row align-items-center justify-content-between"
             data-toggle="collapse" data-target="#smspvaSettingsBody" style="cursor:pointer;">
          <h6 class="m-0 font-weight-bold text-primary">
            <i class="fas fa-sliders-h mr-2"></i>Server1 (smspva.com) Settings
            <span class="badge <?php echo $smspva_enabled ? 'badge-success' : 'badge-secondary'; ?> ml-2">
              <?php echo $smspva_enabled ? 'Enabled' : 'Disabled'; ?>
            </span>
          </h6>
          <i class="fas fa-chevron-down text-muted"></i>
        </div>
        <div class="collapse" id="smspvaSettingsBody">
          <div class="card-body">
            <div class="row">
              <div class="col-md-4">
                <label class="font-weight-bold">Server1 Markup %</label>
                <div class="input-group">
                  <input type="number" class="form-control" id="smspvaMarkupInput"
                         value="<?php echo $smspva_markup_pct; ?>" min="0" max="500" step="0.5">
                  <div class="input-group-append">
                    <button class="btn btn-success" onclick="saveSmspvaMarkup()">Save</button>
                  </div>
                </div>
                <small class="text-muted">Separate from Server2 markup. Applied to all smspva prices.</small>
              </div>
              <div class="col-md-4">
                <label class="font-weight-bold">Server1 Status</label><br>
                <button class="btn btn-<?php echo $smspva_enabled ? 'danger' : 'success'; ?>"
                        onclick="toggleSmspva(<?php echo $smspva_enabled ? 0 : 1; ?>)">
                  <i class="fas fa-<?php echo $smspva_enabled ? 'ban' : 'check'; ?> mr-1"></i>
                  <?php echo $smspva_enabled ? 'Disable smspva' : 'Enable smspva'; ?>
                </button>
              </div>
              <div class="col-md-4">
                <label class="font-weight-bold">Auto-Sync Countries</label><br>
                <button class="btn btn-primary" onclick="syncSmspvaCountries()">
                  <i class="fas fa-globe mr-1"></i>Sync smspva Countries
                </button>
                <small class="text-muted d-block mt-1">Discovers all countries available on smspva.com.</small>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>

  <!-- ── Cron Job Setup ── -->
  <div class="row mb-4">
    <div class="col-lg-12">
      <div class="card shadow mb-0">
        <div class="card-header py-3 d-flex flex-row align-items-center justify-content-between"
             data-toggle="collapse" data-target="#cronSetupBody" style="cursor:pointer;">
          <h6 class="m-0 font-weight-bold text-warning">
            <i class="fas fa-terminal mr-2"></i>Cron Job Setup (every 30 minutes)
          </h6>
          <i class="fas fa-chevron-down text-muted"></i>
        </div>
        <div class="collapse" id="cronSetupBody">
          <div class="card-body">
            <p class="mb-1 font-weight-bold">Server2 (smscodes.io):</p>
            <div class="bg-dark text-white p-3 rounded mb-3" style="font-family:monospace;font-size:.9rem;word-break:break-all;">
              <code class="text-warning" id="cronCmd1">/usr/local/bin/php /home/softombe/public_html/cron/sync_services_cron.php</code>
              <button class="btn btn-sm btn-outline-light ml-2 float-right" onclick="copyText('cronCmd1')" title="Copy">
                <i class="fas fa-copy"></i>
              </button>
            </div>
            <p class="mb-1 font-weight-bold">Server1 (smspva.com):</p>
            <div class="bg-dark text-white p-3 rounded mb-3" style="font-family:monospace;font-size:.9rem;word-break:break-all;">
              <code class="text-primary" id="cronCmd2">/usr/local/bin/php /home/softombe/public_html/cron/sync_smspva_cron.php</code>
              <button class="btn btn-sm btn-outline-light ml-2 float-right" onclick="copyText('cronCmd2')" title="Copy">
                <i class="fas fa-copy"></i>
              </button>
            </div>
            <div class="alert alert-info mb-0">
              <i class="fas fa-info-circle mr-2"></i>
              <strong>cPanel Settings:</strong> Minute: <code>*/30</code> | Hour: <code>*</code> | Day: <code>*</code> | Month: <code>*</code> | Weekday: <code>*</code>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>

  <!-- ── Rate Controls ── -->
  <div class="row mb-4">
    <div class="col-lg-12">
      <div class="card shadow mb-0">
        <div class="card-header py-3 d-flex flex-row align-items-center justify-content-between"
             data-toggle="collapse" data-target="#rateBody" style="cursor:pointer;">
          <h6 class="m-0 font-weight-bold text-info">
            <i class="fas fa-dollar-sign mr-2"></i>Exchange Rate &amp; Markup Controls
          </h6>
          <i class="fas fa-chevron-down text-muted"></i>
        </div>
        <div class="collapse" id="rateBody">
          <div class="card-body">
            <div class="row align-items-end">
              <div class="col-md-3 mb-2">
                <label class="font-weight-bold">USD → NGN Rate</label>
                <input type="number" class="form-control" id="manualUsdRate"
                       value="<?php echo $usd_to_ngn; ?>" min="1" step="0.01">
              </div>
              <div class="col-md-3 mb-2">
                <label class="font-weight-bold">Server2 Markup %</label>
                <input type="number" class="form-control" id="markupInput"
                       value="<?php echo $markup_pct; ?>" min="0" max="500" step="0.5">
              </div>
              <div class="col-md-6 mb-2 d-flex flex-wrap gap-2 align-items-end" style="gap:8px;">
                <button class="btn btn-secondary" onclick="saveManualRate()">
                  <i class="fas fa-save mr-1"></i>Save Rate
                </button>
                <button class="btn btn-warning" onclick="resyncPrices()">
                  <i class="fas fa-redo mr-1"></i>Resync All Prices
                </button>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>

  <!-- ── Cron Logs ── -->
  <div class="row mb-4">
    <div class="col-lg-6">
      <div class="card shadow mb-0">
        <div class="card-header py-3 d-flex flex-row align-items-center justify-content-between">
          <h6 class="m-0 font-weight-bold text-success">
            <i class="fas fa-history mr-2"></i>Server2 Cron Logs (smscodes)
          </h6>
          <button class="btn btn-sm btn-outline-success" onclick="loadCronLogs()">
            <i class="fas fa-refresh mr-1"></i>Refresh
          </button>
        </div>
        <div class="card-body p-0">
          <div class="table-responsive" style="max-height:280px;overflow-y:auto;">
            <table class="table table-sm table-hover mb-0">
              <thead><tr><th>Time</th><th>Countries</th><th>Services</th><th>Duration</th><th>Status</th></tr></thead>
              <tbody id="cronLogBody">
                <tr><td colspan="5" class="text-center py-3 text-muted">Loading...</td></tr>
              </tbody>
            </table>
          </div>
        </div>
      </div>
    </div>
    <div class="col-lg-6">
      <div class="card shadow mb-0">
        <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-history mr-2"></i>Server1 Cron Logs (smspva)
          </h6>
          <button class="btn btn-sm btn-outline-primary" onclick="loadSmspvaCronLogs()">
            <i class="fas fa-refresh mr-1"></i>Refresh
          </button>
        </div>
        <div class="card-body p-0">
          <div class="table-responsive" style="max-height:280px;overflow-y:auto;">
            <table class="table table-sm table-hover mb-0">
              <thead><tr><th>Time</th><th>Countries</th><th>Services</th><th>Duration</th><th>Status</th></tr></thead>
              <tbody id="smspvaCronLogBody">
                <tr><td colspan="5" class="text-center py-3 text-muted">Loading...</td></tr>
              </tbody>
            </table>
          </div>
        </div>
      </div>
    </div>
  </div>

  <!-- ── Server2 Country Table ── -->
  <div class="row mb-4">
    <div class="col-lg-12">
      <div class="card shadow mb-0">
        <div class="card-header py-3 d-flex flex-row align-items-center justify-content-between">
          <h6 class="m-0 font-weight-bold text-success">
            <i class="fas fa-server mr-2"></i>Server2 Countries (smscodes.io)
            <span class="badge badge-success ml-2"><?php echo count($smscodes_countries); ?></span>
          </h6>
          <div>
            <button class="btn btn-sm btn-success" onclick="syncAllCountries('smscodes')">
              <i class="fas fa-sync-alt mr-1"></i>Sync All Server2
            </button>
          </div>
        </div>
        <div class="card-body p-0">
          <?php echo renderCountryTable($smscodes_countries, $country_sync_times, $service_counts, 'smscodes'); ?>
        </div>
      </div>
    </div>
  </div>

  <!-- ── Server1 Country Table ── -->
  <div class="row mb-4">
    <div class="col-lg-12">
      <div class="card shadow mb-0">
        <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-server mr-2"></i>Server1 Countries (smspva.com)
            <span class="badge badge-primary ml-2"><?php echo count($smspva_countries); ?></span>
          </h6>
          <div>
            <button class="btn btn-sm btn-primary" onclick="syncSmspvaCountries(this)">
              <i class="fas fa-globe mr-1"></i>Discover Countries
            </button>
            <button class="btn btn-sm btn-info ml-2" onclick="syncAllCountries('smspva')">
              <i class="fas fa-sync-alt mr-1"></i>Sync All Server1
            </button>
            <button class="btn btn-sm btn-secondary ml-2" onclick="debugSmspvaApi(this)" title="Debug: test what smspva endpoints return">
              <i class="fas fa-bug mr-1"></i>Debug API
            </button>
          </div>
        </div>
        <div class="card-body p-0">
          <?php if (empty($smspva_countries)): ?>
            <div class="text-center py-4 text-muted">
              <i class="fas fa-info-circle mr-2"></i>
              No Server1 countries yet. Click <strong>Discover Countries</strong> to auto-add them from smspva.com.
            </div>
          <?php else: ?>
            <?php echo renderCountryTable($smspva_countries, $country_sync_times, $service_counts, 'smspva'); ?>
          <?php endif; ?>
        </div>
      </div>
    </div>
  </div>
</div>

<!-- smspva Debug Modal -->
<div class="modal fade" id="smspvaDebugModal" tabindex="-1">
  <div class="modal-dialog modal-xl"><div class="modal-content">
    <div class="modal-header bg-dark text-white">
      <h5 class="modal-title"><i class="fas fa-bug mr-2"></i>smspva API Debug — Endpoint Test Results</h5>
      <button type="button" class="close text-white" data-dismiss="modal"><span>&times;</span></button>
    </div>
    <div class="modal-body p-0">
      <div id="smspvaDebugBody" style="padding:16px;">
        <div class="text-center py-4"><i class="fas fa-spinner fa-spin fa-2x text-muted"></i><br><small class="text-muted mt-2 d-block">Testing endpoints...</small></div>
      </div>
    </div>
    <div class="modal-footer">
      <small class="text-muted mr-auto">Share this output when reporting issues.</small>
      <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
    </div>
  </div></div>
</div>

<!-- Sync All Modal -->
<div class="modal fade" id="syncAllModal" tabindex="-1" data-backdrop="static">
  <div class="modal-dialog modal-lg"><div class="modal-content">
    <div class="modal-header">
      <h5 class="modal-title"><i class="fas fa-sync-alt fa-spin mr-2 text-primary"></i>Bulk Sync Progress</h5>
    </div>
    <div class="modal-body">
      <div class="progress mb-3" style="height:22px;border-radius:11px;">
        <div id="syncAllBar" class="progress-bar progress-bar-striped progress-bar-animated bg-primary"
             style="width:0%;transition:width .4s ease;border-radius:11px;">
          <span id="syncAllPercent" class="font-weight-bold">0%</span>
        </div>
      </div>
      <p id="syncAllLabel" class="text-center text-muted mb-2">Preparing...</p>
      <div id="syncAllLog" style="max-height:260px;overflow-y:auto;font-size:.82rem;padding:8px;background:#f8f9fc;border-radius:8px;"></div>
    </div>
    <div class="modal-footer d-none" id="syncAllFooter">
      <button class="btn btn-danger" onclick="abortSync()"><i class="fas fa-stop mr-1"></i>Stop</button>
      <button class="btn btn-secondary" data-dismiss="modal">Close</button>
    </div>
  </div></div>
</div>

<?php
function renderCountryTable(array $countries, array $sync_times, array $svc_counts, string $provider): string
{
    if (empty($countries)) return '';
    $badge    = $provider === 'smspva' ? 'badge-primary' : 'badge-success';
    $label    = $provider === 'smspva' ? 'Server1' : 'Server2';
    $btn_cls  = $provider === 'smspva' ? 'btn-info' : 'btn-success';

    $html  = '<div class="table-responsive"><table class="table table-hover mb-0">';
    $html .= '<thead class="bg-light"><tr><th></th><th>Country</th><th>ISO</th>';
    $html .= '<th>Services</th><th>Last Sync</th><th>Status</th><th>Action</th></tr></thead><tbody>';

    foreach ($countries as $c) {
        $sid       = $c['id'];
        $svc_count = $svc_counts[$sid] ?? 0;
        $last_sync = $sync_times[$sid] ?? 'Never';
        $status    = $c['status'] === '1' ? '<span class="badge badge-success">Active</span>' : '<span class="badge badge-secondary">Inactive</span>';
        $flag      = $c['flag_url'] ? "<img src=\"".htmlspecialchars($c['flag_url'])."\" class=\"flag-img-sm mr-2\" onerror=\"this.style.display='none'\">" : '';

        $html .= "<tr id=\"row_{$sid}\">";
        $html .= "<td style=\"width:40px\">{$flag}</td>";
        $html .= "<td><strong>".htmlspecialchars($c['server_name'])."</strong><br><small class=\"text-muted\"><span class=\"badge {$badge}\">{$label}</span></small></td>";
        $html .= "<td><code>".htmlspecialchars($c['server_code'])."</code></td>";
        $html .= "<td><span id=\"svcCount_{$sid}\">".number_format($svc_count)."</span> services</td>";
        $html .= "<td><small id=\"lastSync_{$sid}\">".htmlspecialchars($last_sync)."</small></td>";
        $html .= "<td>{$status}</td>";
        $html .= "<td>
            <button id=\"syncBtn_{$sid}\" class=\"btn btn-sm {$btn_cls}\"
              onclick=\"syncCountry({$sid}, {$c['api_id']}, '".addslashes(htmlspecialchars($c['server_name']))."')\"
              data-server-id=\"{$sid}\" data-api-id=\"{$c['api_id']}\" data-server-name=\"".htmlspecialchars($c['server_name'])."\">
              <i class=\"fas fa-sync-alt mr-1\"></i>Sync
            </button>
          </td>";
        $html .= '</tr>';
    }

    $html .= '</tbody></table></div>';
    return $html;
}
?>

<script>
var syncAllAborted = false;

// ── Sync single country ───────────────────────────────────────────────────────
function syncCountry(serverId, apiId, serverName) {
  var btn = $('#syncBtn_' + serverId);
  btn.prop('disabled', true).html('<i class="fas fa-spinner fa-spin mr-1"></i>Syncing...');

  $.ajax({
    url:      'ajax/sync_data.php',
    type:     'POST',
    data:     { action: 'sync_services', server_id: serverId, api_id: apiId },
    dataType: 'json',
    timeout:  120000,
    success: function(data) {
      btn.prop('disabled', false).html('<i class="fas fa-sync-alt mr-1"></i>Sync');
      if (data.status == '1') {
        $('#lastSync_' + serverId).html(new Date().toLocaleString());
        refreshServiceCount(serverId);
        Swal.fire({ toast:true, position:'top-end', icon:'success', title: serverName + ' synced!',
          html: data.msg, showConfirmButton: false, timer: 3000 });
      } else {
        Swal.fire('Sync Failed', data.msg || 'Unknown error.', 'error');
      }
    },
    error: function() {
      btn.prop('disabled', false).html('<i class="fas fa-sync-alt mr-1"></i>Sync');
      Swal.fire('Error', 'Request timed out or failed for ' + serverName + '.', 'error');
    }
  });
}

// ── Refresh service count display ─────────────────────────────────────────────
function refreshServiceCount(serverId) {
  $.post('ajax/sync_data.php', { action: 'get_service_count', server_id: serverId }, function(data) {
    if (data.status == '1') {
      $('#svcCount_' + serverId).text(parseInt(data.count).toLocaleString());
    }
  }, 'json').fail(function() {
    // non-critical — ignore
  });
}

// ── Sync all countries (filtered by provider) ─────────────────────────────────
function syncAllCountries(provider) {
  var rows = [];
  $('button[id^="syncBtn_"]').each(function() {
    var sid    = $(this).data('server-id');
    var apiId  = $(this).data('api-id');
    var sname  = $(this).data('server-name');
    if (!sid || !apiId) return;
    // Only include buttons that are in the right table (check badge label)
    var rowBadge = $('#row_' + sid + ' .badge');
    var label    = rowBadge.text().trim();
    var match    = (provider === 'smspva' && label.includes('Server1')) ||
                   (provider === 'smscodes' && label.includes('Server2'));
    if (match) rows.push({ serverId: sid, apiId: apiId, serverName: sname });
  });

  if (rows.length === 0) {
    Swal.fire('Nothing to sync', 'No ' + (provider === 'smspva' ? 'Server1' : 'Server2') + ' countries found.', 'info');
    return;
  }

  syncAllAborted = false;
  $('#syncAllBar').css('width', '0%');
  $('#syncAllPercent').text('0%');
  $('#syncAllLabel').text('Starting...');
  $('#syncAllLog').html('');
  $('#syncAllFooter').removeClass('d-none');
  $('#syncAllModal').modal('show');

  processSyncQueue(rows, 0, rows.length, 0, 0, 0);
}

function processSyncQueue(queue, index, total, totalIns, totalUpd, totalSkp) {
  if (syncAllAborted || index >= total) {
    $('#syncAllBar').css('width','100%').removeClass('progress-bar-animated');
    $('#syncAllPercent').text('100%');
    $('#syncAllLabel').text('Done! ' + total + ' countries processed.');
    appendSyncLog('✅ <strong>All done!</strong> +' + totalIns + ' new, ' + totalUpd + ' updated, ' + totalSkp + ' skipped.', 'text-success');
    return;
  }

  var item = queue[index];
  var pct  = Math.round((index / total) * 100);
  $('#syncAllBar').css('width', pct + '%');
  $('#syncAllPercent').text(pct + '%');
  $('#syncAllLabel').text('Syncing ' + (index + 1) + ' of ' + total + ': ' + item.serverName + '...');
  appendSyncLog('🔄 Syncing <strong>' + escapeHtml(item.serverName) + '</strong>...', 'text-primary');

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

  $.ajax({
    url:     'ajax/sync_data.php',
    type:    'POST',
    data:    { action: 'sync_services', server_id: item.serverId, api_id: item.apiId },
    dataType:'json',
    timeout: 120000,
    success: function(data) {
      $('#syncBtn_' + item.serverId).prop('disabled', false).html('<i class="fas fa-sync-alt mr-1"></i>Sync');
      if (data.status == '1') {
        var ins = parseInt(data.inserted) || 0;
        var upd = parseInt(data.updated)  || 0;
        var skp = parseInt(data.skipped)  || 0;
        totalIns += ins; totalUpd += upd; totalSkp += skp;
        $('#lastSync_' + item.serverId).html(new Date().toLocaleString());
        refreshServiceCount(item.serverId);
        appendSyncLog('✅ ' + escapeHtml(item.serverName) + ': +' + ins + ' new, ' + upd + ' updated.', 'text-success');
      } else {
        appendSyncLog('⚠️ ' + escapeHtml(item.serverName) + ': ' + (data.msg || 'Failed'), 'text-warning');
      }
      setTimeout(function() {
        processSyncQueue(queue, index + 1, total, totalIns, totalUpd, totalSkp);
      }, 800);
    },
    error: function() {
      $('#syncBtn_' + item.serverId).prop('disabled', false).html('<i class="fas fa-sync-alt mr-1"></i>Sync');
      appendSyncLog('❌ ' + escapeHtml(item.serverName) + ': Request failed / timeout.', 'text-danger');
      setTimeout(function() {
        processSyncQueue(queue, index + 1, total, totalIns, totalUpd, totalSkp);
      }, 800);
    }
  });
}

function abortSync() { syncAllAborted = true; }

function appendSyncLog(html, cls) {
  var log = $('#syncAllLog');
  log.append('<div class="' + (cls||'') + '">' + html + '</div>');
  log.scrollTop(log[0].scrollHeight);
}

// ── Sync smspva countries (auto-discover) ─────────────────────────────────────
function syncSmspvaCountries(btn) {
  btn = btn || (event && event.target ? event.target : null);
  var origHtml = btn ? btn.innerHTML : '';
  if (btn) { btn.disabled = true; btn.innerHTML = '<i class="fas fa-spinner fa-spin mr-1"></i>Syncing...'; }

  $.ajax({
    url:     'ajax/sync_data.php',
    type:    'POST',
    data:    { action: 'smspva_sync_countries' },
    dataType:'json',
    timeout: 120000,
    success: function(data) {
      if (btn) { btn.disabled = false; btn.innerHTML = origHtml; }
      if (data.status == '1') {
        Swal.fire('Done!', data.msg, 'success').then(() => location.reload());
      } else {
        // On failure, offer to run the debug tool so the admin can see raw output
        Swal.fire({
          title: 'Sync Failed',
          html: '<p>' + (data.msg || 'Unknown error.') + '</p>'
              + '<p class="text-muted" style="font-size:.82rem;">Click <strong>Debug API</strong> to see what smspva is returning.</p>',
          icon: 'error',
          showCancelButton: true,
          confirmButtonText: '<i class="fas fa-bug mr-1"></i>Debug API',
          cancelButtonText:  'Close',
          confirmButtonColor: '#6c757d',
        }).then(function(r) {
          if (r.isConfirmed) debugSmspvaApi();
        });
      }
    },
    error: function() {
      if (btn) { btn.disabled = false; btn.innerHTML = origHtml; }
      Swal.fire('Error', 'Ajax request failed. Check your server error log.', 'error');
    }
  });
}

// ── Debug smspva API — test all endpoints and show raw results ────────────────
function debugSmspvaApi(btn) {
  btn = btn || null;
  var origHtml = btn ? btn.innerHTML : '';
  if (btn) { btn.disabled = true; btn.innerHTML = '<i class="fas fa-spinner fa-spin mr-1"></i>Testing...'; }

  $('#smspvaDebugBody').html(
    '<div class="text-center py-4"><i class="fas fa-spinner fa-spin fa-2x text-muted"></i>' +
    '<br><small class="text-muted mt-2 d-block">Calling smspva endpoints — please wait up to 30 seconds...</small></div>'
  );
  $('#smspvaDebugModal').modal('show');

  $.ajax({
    url:     'ajax/sync_data.php',
    type:    'POST',
    data:    { action: 'smspva_debug' },
    dataType:'json',
    timeout: 60000,
    success: function(data) {
      if (btn) { btn.disabled = false; btn.innerHTML = origHtml; }
      if (data.status != '1') {
        $('#smspvaDebugBody').html('<div class="alert alert-danger m-3">' + (data.msg || 'Debug failed.') + '</div>');
        return;
      }

      var html = '<table class="table table-sm table-bordered mb-0" style="font-size:.78rem;">';
      html += '<thead class="thead-dark"><tr>'
            + '<th style="width:160px">Endpoint</th>'
            + '<th style="width:70px">HTTP</th>'
            + '<th style="width:90px">Type</th>'
            + '<th style="width:80px">1st Key</th>'
            + '<th style="width:80px">Numeric?</th>'
            + '<th>Raw Snippet (400 chars)</th>'
            + '</tr></thead><tbody>';

      $.each(data.results, function(label, r) {
        var httpClass = r.http_code === 200 ? 'text-success font-weight-bold'
                      : r.http_code === 0   ? 'text-danger'
                      : 'text-warning';
        var raw = r.raw_snippet || '(empty)';
        var numeric = r.is_numeric_key === null ? '—'
                    : (r.is_numeric_key ? '<span class="badge badge-warning">YES — numeric IDs</span>'
                                        : '<span class="badge badge-success">NO — string keys</span>');
        html += '<tr>'
              + '<td><strong>' + escapeHtml(label) + '</strong><br><small class="text-muted">' + escapeHtml(r.url) + '</small></td>'
              + '<td class="' + httpClass + '">' + r.http_code + (r.curl_error ? '<br><small>'+escapeHtml(r.curl_error)+'</small>' : '') + '</td>'
              + '<td>' + escapeHtml(r.decoded_type || '?') + '<br><small>' + r.raw_length + ' bytes</small></td>'
              + '<td><code>' + escapeHtml(String(r.first_key ?? '—')) + '</code></td>'
              + '<td>' + numeric + '</td>'
              + '<td><pre style="max-height:120px;overflow:auto;font-size:.7rem;margin:0;white-space:pre-wrap;">'
              + escapeHtml(raw) + '</pre></td>'
              + '</tr>';
      });

      html += '</tbody></table>';

      // Show what the sync will do based on what we found
      var gcResult  = data.results['getcountries'];
      var spResult  = data.results['servicesprices'];
      var advice    = '';

      if (gcResult && gcResult.http_code === 200 && gcResult.decoded_type === 'array') {
        advice = '<div class="alert alert-success mt-3 mb-0"><i class="fas fa-check-circle mr-2"></i>'
               + '<strong>/activation/getcountries</strong> returned valid data. '
               + '"Discover Countries" should work — try again.</div>';
      } else if (spResult && spResult.http_code === 200 && spResult.is_numeric_key) {
        advice = '<div class="alert alert-info mt-3 mb-0"><i class="fas fa-info-circle mr-2"></i>'
               + '<strong>servicesprices</strong> returned numeric IDs. '
               + 'The code will use the built-in ID map. Try "Discover Countries" again.</div>';
      } else if (spResult && spResult.http_code === 200 && spResult.is_numeric_key === false) {
        advice = '<div class="alert alert-info mt-3 mb-0"><i class="fas fa-info-circle mr-2"></i>'
               + '<strong>servicesprices</strong> returned string keys. '
               + 'The code will parse them as ISO codes. Try "Discover Countries" again.</div>';
      } else if (gcResult && gcResult.http_code === 401 || (spResult && spResult.http_code === 401)) {
        advice = '<div class="alert alert-danger mt-3 mb-0"><i class="fas fa-key mr-2"></i>'
               + '<strong>HTTP 401</strong> — API key is invalid or not authorised. '
               + 'Check the key in API Management.</div>';
      } else if (gcResult && gcResult.http_code === 0) {
        advice = '<div class="alert alert-danger mt-3 mb-0"><i class="fas fa-wifi mr-2"></i>'
               + '<strong>Connection failed</strong> — could not reach api.smspva.com. '
               + 'Check your server outbound connectivity and the API URL.</div>';
      } else {
        advice = '<div class="alert alert-warning mt-3 mb-0"><i class="fas fa-exclamation-triangle mr-2"></i>'
               + 'Unexpected response shape. Share the table above with the developer.</div>';
      }

      $('#smspvaDebugBody').html(html + advice);
    },
    error: function() {
      if (btn) { btn.disabled = false; btn.innerHTML = origHtml; }
      $('#smspvaDebugBody').html('<div class="alert alert-danger m-3">Ajax request failed. Check your server error log.</div>');
    }
  });
}

// ── Exchange rate helpers ─────────────────────────────────────────────────────
function saveManualRate() {
  var rate = $('#manualUsdRate').val();
  if (!rate || parseFloat(rate) <= 0) { Swal.fire('Validation', 'Enter a valid rate.', 'warning'); return; }
  $.post('ajax/sync_data.php', { action: 'save_rates_manual', usd_to_ngn: rate }, function(data) {
    if (data.status == '1') {
      Swal.fire({ toast:true, position:'top-end', icon:'success', title:'Rate saved!', showConfirmButton:false, timer:2000 });
    } else {
      Swal.fire('Error', data.msg, 'error');
    }
  }, 'json');
}

function resyncPrices() {
  Swal.fire({
    title: 'Resync All Prices?',
    html: 'This will re-fetch live USD prices from <strong>both providers</strong> and recalculate NGN prices.<br>May take several minutes.',
    icon: 'warning',
    showCancelButton: true,
    confirmButtonColor: '#f6c23e',
    confirmButtonText: 'Yes, resync!'
  }).then(function(r) {
    if (!r.isConfirmed) return;
    Swal.fire({ title: 'Resyncing...', html: 'Please wait. This may take a few minutes.', allowOutsideClick: false, didOpen: () => Swal.showLoading() });
    $.ajax({ url:'ajax/sync_data.php', type:'POST', data:{ action:'resync_prices' }, dataType:'json', timeout:600000,
      success: function(data) {
        Swal.fire(data.status=='1' ? 'Done!' : 'Warning', data.msg, data.status=='1'?'success':'warning');
      },
      error: function() { Swal.fire('Error','Request timed out.','error'); }
    });
  });
}

// ── smspva settings ───────────────────────────────────────────────────────────
function saveSmspvaMarkup() {
  var val = $('#smspvaMarkupInput').val();
  if (!val || parseFloat(val) < 0) { Swal.fire('Validation', 'Enter a valid markup.', 'warning'); return; }
  $.post('ajax/sync_data.php', { action: 'save_smspva_markup', markup: val }, function(data) {
    if (data.status == '1') {
      Swal.fire({ toast:true, position:'top-end', icon:'success', title:data.msg, showConfirmButton:false, timer:2000 });
    } else {
      Swal.fire('Error', data.msg, 'error');
    }
  }, 'json');
}

function toggleSmspva(enable) {
  $.post('ajax/sync_data.php', { action: 'toggle_smspva', enabled: enable }, function(data) {
    if (data.status == '1') {
      Swal.fire({ toast:true, position:'top-end', icon:'success', title:data.msg, showConfirmButton:false, timer:2000 })
          .then(() => location.reload());
    } else {
      Swal.fire('Error', data.msg, 'error');
    }
  }, 'json');
}

// ── Cron log loaders ──────────────────────────────────────────────────────────
function renderCronLogRows(logs, tbodyId) {
  var tbody = $('#' + tbodyId);
  tbody.empty();
  if (!logs || logs.length === 0) {
    tbody.append('<tr><td colspan="5" class="text-center text-muted py-3"><i class="fas fa-inbox mr-1"></i>No logs yet.</td></tr>');
    return;
  }
  $.each(logs, function(i, log) {
    var badge = log.status === 'success'
      ? '<span class="badge badge-success">Success</span>'
      : '<span class="badge badge-danger">Failed</span>';
    tbody.append(
      '<tr><td><small>' + escapeHtml(log.run_time) + '</small></td>' +
      '<td>' + (log.countries_processed||0) + '</td>' +
      '<td>' + (log.services_updated||0) + '</td>' +
      '<td><small>' + escapeHtml(log.duration||'N/A') + '</small></td>' +
      '<td>' + badge + '</td></tr>'
    );
  });
}

function loadCronLogs() {
  $.post('ajax/sync_data.php', { action: 'get_cron_logs' }, function(data) {
    renderCronLogRows(data.status=='1' ? data.logs : [], 'cronLogBody');
  }, 'json').fail(function() {
    $('#cronLogBody').html('<tr><td colspan="5" class="text-center text-danger py-3">Failed to load logs.</td></tr>');
  });
}

function loadSmspvaCronLogs() {
  $.post('ajax/sync_data.php', { action: 'get_smspva_cron_logs' }, function(data) {
    renderCronLogRows(data.status=='1' ? data.logs : [], 'smspvaCronLogBody');
  }, 'json').fail(function() {
    $('#smspvaCronLogBody').html('<tr><td colspan="5" class="text-center text-danger py-3">Failed to load logs.</td></tr>');
  });
}

function copyText(id) {
  var text = document.getElementById(id).textContent;
  navigator.clipboard.writeText(text).then(function() {
    Swal.fire({ toast:true, position:'top-end', icon:'success', title:'Copied!', showConfirmButton:false, timer:1500 });
  });
}

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

$(document).ready(function() {
  loadCronLogs();
  loadSmspvaCronLogs();
});
</script>

<style>
.flag-img-sm { width:36px;height:22px;object-fit:contain;border:1px solid #e3e6f0;border-radius:3px;padding:1px;background:#fff; }
code { color:#e83e8c;background:#f8f9fc;padding:2px 5px;border-radius:3px;font-size:.85em; }
#syncAllLog div { padding:2px 0;border-bottom:1px solid #eee; }
#syncAllLog div:last-child { border-bottom:none; }
</style>

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