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

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

// ── Fetch smscodes (Server2) balance live per-row (original behaviour) ────────
// smscodes endpoint: GET {api_url}/GetBalance?key={api_key}
// Response: {"Status":"Success","Balance":0.05}
function fetch_smscodes_balance(string $api_url, string $api_key): string
{
    $url = rtrim($api_url, '/') . '/GetBalance?key=' . urlencode($api_key);
    $ch  = curl_init($url);
    curl_setopt_array($ch, [
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_TIMEOUT        => 10,
        CURLOPT_CONNECTTIMEOUT => 8,
        CURLOPT_SSL_VERIFYPEER => false,
        CURLOPT_SSL_VERIFYHOST => 0,
        CURLOPT_USERAGENT      => 'Mozilla/5.0 (compatible; Bot/1.0)',
    ]);
    $response = curl_exec($ch);
    $curl_err = curl_error($ch);
    curl_close($ch);

    $data = json_decode($response, true);
    if (is_array($data) && isset($data['Status']) && $data['Status'] === 'Success') {
        return '<span class="font-weight-bold text-success">$' . number_format((float)($data['Balance'] ?? 0), 4) . '</span>';
    }
    if ($curl_err) {
        return '<span class="badge badge-warning" title="' . htmlspecialchars($curl_err) . '">Connection Error</span>';
    }
    return '<span class="badge badge-secondary">Could not fetch</span>';
}

// ── smspva cached balance (refreshed via JS button) ───────────────────────────
$smspva_balance_cached = null;
try {
    $b = $pdo->query("SELECT setting_value FROM price_settings WHERE setting_key='smspva_balance_cached' LIMIT 1")->fetch(PDO::FETCH_ASSOC);
    if ($b) $smspva_balance_cached = (float)$b['setting_value'];
} catch (PDOException $e) {}

// Split by type for info cards
$smspva_api   = null;
$smscodes_api = null;
$fivesim_api  = null;
$smsbus_api   = null;
foreach ($apis as $a) {
    $t = $a['api_type'] ?? 'smscodes';
    if ($t === 'smspva'   && !$smspva_api)   $smspva_api   = $a;
    if ($t === 'smscodes' && !$smscodes_api) $smscodes_api = $a;
    if ($t === '5sim'     && !$fivesim_api)  $fivesim_api  = $a;
    if ($t === 'smsbus'   && !$smsbus_api)   $smsbus_api   = $a;
}

// ── Read enabled/disabled states ─────────────────────────────
$smspva_enabled   = 1;
$smscodes_enabled = 1;
$fivesim_enabled  = 1;
$smsbus_enabled   = 1;
try {
    // Ensure columns exist first
    $pdo->exec("ALTER TABLE settings
        ADD COLUMN IF NOT EXISTS smspva_enabled   TINYINT(1) NOT NULL DEFAULT 1,
        ADD COLUMN IF NOT EXISTS smscodes_enabled TINYINT(1) NOT NULL DEFAULT 1,
        ADD COLUMN IF NOT EXISTS fivesim_enabled  TINYINT(1) NOT NULL DEFAULT 1,
        ADD COLUMN IF NOT EXISTS smsbus_enabled   TINYINT(1) NOT NULL DEFAULT 1");
} catch (PDOException $e) {}
try {
    $en = $pdo->query("SELECT smspva_enabled, smscodes_enabled, fivesim_enabled, smsbus_enabled FROM settings WHERE id=1")->fetch(PDO::FETCH_ASSOC);
    if ($en) {
        $smspva_enabled   = (int)$en['smspva_enabled'];
        $smscodes_enabled = (int)$en['smscodes_enabled'];
        $fivesim_enabled  = (int)$en['fivesim_enabled'];
        $smsbus_enabled   = (int)$en['smsbus_enabled'];
    }
} catch (PDOException $e) {}

// ── Fetch 5SIM balance (live) ─────────────────────────────────
// Token lives in settings.fivesim_api_token (not api_detail.api_key).
// $api_url and $api_key are passed from api_detail, but we prefer
// the token from the settings table when available.
function fetch_fivesim_balance(string $api_url, string $api_key): string
{
    global $pdo;

    // Prefer the dedicated settings token; fall back to api_detail api_key
    $token = '';
    try {
        $cols = $pdo->query("SHOW COLUMNS FROM settings LIKE 'fivesim_api_token'")->fetchAll();
        if (!empty($cols)) {
            $row = $pdo->query("SELECT fivesim_api_token, fivesim_api_url FROM settings WHERE id=1")->fetch(PDO::FETCH_ASSOC);
            $token    = trim($row['fivesim_api_token'] ?? '');
            $saved_url = trim($row['fivesim_api_url']  ?? '');
            if (!empty($saved_url)) $api_url = $saved_url;
        }
    } catch (PDOException $e) {}

    // Fall back to api_detail.api_key if settings token is empty
    if (empty($token)) $token = $api_key;
    if (empty($token)) {
        return '<span class="badge badge-warning">No token saved</span>';
    }

    $url = rtrim($api_url ?: 'https://5sim.net/v1', '/') . '/user/profile';
    $ch  = curl_init($url);
    curl_setopt_array($ch, [
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_TIMEOUT        => 15,
        CURLOPT_CONNECTTIMEOUT => 10,
        CURLOPT_SSL_VERIFYPEER => false,
        CURLOPT_SSL_VERIFYHOST => 0,
        CURLOPT_USERAGENT      => 'Mozilla/5.0 (compatible; Bot/1.0)',
        CURLOPT_HTTPHEADER     => [
            'Authorization: Bearer ' . $token,
            'Accept: application/json',
        ],
    ]);
    $response = curl_exec($ch);
    $curl_err = curl_error($ch);
    $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);

    if ($curl_err) {
        return '<span class="badge badge-warning" title="' . htmlspecialchars($curl_err) . '">cURL Error</span>';
    }

    $data = json_decode($response, true);
    if (is_array($data) && isset($data['balance'])) {
        return '<span class="font-weight-bold text-success">$' . number_format((float)$data['balance'], 4) . '</span>';
    }

    // Show the actual error from 5SIM instead of a silent "Could not fetch"
    $err_msg = '';
    if (is_string($data) && $data !== '') {
        $err_msg = $data;
    } elseif (is_array($data) && !empty($data['message'])) {
        $err_msg = $data['message'];
    } elseif ($http_code > 0) {
        $err_msg = 'HTTP ' . $http_code;
    }

    return '<span class="badge badge-secondary" title="' . htmlspecialchars($err_msg ?: 'No balance field in response') . '">Could not fetch</span>';
}

// ── Fetch SMS-Bus balance (live) ──────────────────────────────
// Token lives in settings.smsbus_api_token (not api_detail.api_key).
function fetch_smsbus_balance(string $api_url, string $api_key): string
{
    global $pdo;

    // Prefer the dedicated settings token
    $token = '';
    try {
        $cols = $pdo->query("SHOW COLUMNS FROM settings LIKE 'smsbus_api_token'")->fetchAll();
        if (!empty($cols)) {
            $row = $pdo->query("SELECT smsbus_api_token, smsbus_api_url FROM settings WHERE id=1")->fetch(PDO::FETCH_ASSOC);
            $token     = trim($row['smsbus_api_token'] ?? '');
            $saved_url = trim($row['smsbus_api_url']   ?? '');
            if (!empty($saved_url)) $api_url = $saved_url;
        }
    } catch (PDOException $e) {}

    if (empty($token)) $token = $api_key;
    if (empty($token)) {
        return '<span class="badge badge-warning">No token saved</span>';
    }

    $url = rtrim($api_url ?: 'https://sms-bus.com/api/control', '/') . '/get/balance?token=' . urlencode($token);
    $ch  = curl_init($url);
    curl_setopt_array($ch, [
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_TIMEOUT        => 15,
        CURLOPT_CONNECTTIMEOUT => 10,
        CURLOPT_SSL_VERIFYPEER => false,
        CURLOPT_SSL_VERIFYHOST => 0,
        CURLOPT_USERAGENT      => 'Mozilla/5.0 (compatible; Bot/1.0)',
    ]);
    $response  = curl_exec($ch);
    $curl_err  = curl_error($ch);
    $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);

    if ($curl_err) {
        return '<span class="badge badge-warning" title="' . htmlspecialchars($curl_err) . '">cURL Error</span>';
    }

    $data = json_decode($response, true);
    if (is_array($data) && (int)($data['code'] ?? 0) === 200 && isset($data['data']['balance'])) {
        return '<span class="font-weight-bold text-success">$' . number_format((float)$data['data']['balance'], 4) . '</span>';
    }

    $api_code = (int)($data['code'] ?? 0);
    if ($api_code === 401) {
        return '<span class="badge badge-danger">Invalid Token (401)</span>';
    }
    $err_msg = $api_code > 0 ? 'API code ' . $api_code : 'HTTP ' . $http_code;
    return '<span class="badge badge-secondary" title="' . htmlspecialchars($err_msg) . '">Could not fetch</span>';
}
?>
<title>Manage APIs - <?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">Manage APIs</h1>
    <ol class="breadcrumb">
      <li class="breadcrumb-item"><a href="dashboard.php">Home</a></li>
      <li class="breadcrumb-item active">Manage APIs</li>
    </ol>
  </div>

  <!-- ── Provider Info Cards ── -->
  <div class="row mb-4">
    <!-- Server1 — smspva.com -->
    <div class="col-md-4 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="d-flex align-items-center justify-content-between mb-1">
                <div class="text-xs font-weight-bold text-primary text-uppercase">Server1 — smspva.com</div>
                <div class="custom-control custom-switch ml-2">
                  <input type="checkbox" class="custom-control-input" id="toggle_smspva"
                         <?php echo $smspva_enabled ? 'checked' : ''; ?>
                         onchange="toggleServer('smspva', this.checked)">
                  <label class="custom-control-label" for="toggle_smspva"></label>
                </div>
              </div>
              <div class="h6 mb-0 text-gray-700 mb-2">Per-operator pricing. Charges only when SMS is delivered.</div>
              <?php if (!$smspva_enabled): ?>
                <span class="badge badge-secondary"><i class="fas fa-ban mr-1"></i>Disabled</span>
              <?php elseif ($smspva_api): ?>
                <span class="badge badge-success">Configured</span>
                <button class="btn btn-xs btn-outline-info ml-2" onclick="checkSmspvaBalance(this)">
                  <i class="fas fa-wallet mr-1"></i>Check Balance
                </button>
                <span id="smspvaBalanceDisplay" class="ml-2 font-weight-bold text-success" style="font-size:.85rem;">
                  <?php echo $smspva_balance_cached !== null ? '$' . number_format($smspva_balance_cached, 4) : '—'; ?>
                </span>
              <?php else: ?>
                <span class="badge badge-warning">Not Configured</span>
                <small class="text-muted d-block mt-1">Add smspva.com API below.</small>
              <?php endif; ?>
            </div>
            <div class="col-auto"><i class="fas fa-server fa-2x text-gray-300"></i></div>
          </div>
        </div>
      </div>
    </div>

    <!-- Server2 — smscodes.io -->
    <div class="col-md-4 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="d-flex align-items-center justify-content-between mb-1">
                <div class="text-xs font-weight-bold text-success text-uppercase">Server2 — smscodes.io</div>
                <div class="custom-control custom-switch ml-2">
                  <input type="checkbox" class="custom-control-input" id="toggle_smscodes"
                         <?php echo $smscodes_enabled ? 'checked' : ''; ?>
                         onchange="toggleServer('smscodes', this.checked)">
                  <label class="custom-control-label" for="toggle_smscodes"></label>
                </div>
              </div>
              <div class="h6 mb-0 text-gray-700 mb-2">SecurityId-based number polling for 100+ services.</div>
              <?php if (!$smscodes_enabled): ?>
                <span class="badge badge-secondary"><i class="fas fa-ban mr-1"></i>Disabled</span>
              <?php elseif ($smscodes_api): ?>
                <span class="badge badge-success">Configured</span>
                <span class="ml-2 font-weight-bold" style="font-size:.85rem;">
                  <?php echo fetch_smscodes_balance($smscodes_api['api_url'], $smscodes_api['api_key']); ?>
                </span>
              <?php else: ?>
                <span class="badge badge-warning">Not Configured</span>
              <?php endif; ?>
            </div>
            <div class="col-auto"><i class="fas fa-satellite-dish fa-2x text-gray-300"></i></div>
          </div>
        </div>
      </div>
    </div>

    <!-- Server3 — 5sim.net -->
    <div class="col-md-4 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="d-flex align-items-center justify-content-between mb-1">
                <div class="text-xs font-weight-bold text-info text-uppercase">Server3 — 5sim.net</div>
                <div class="custom-control custom-switch ml-2">
                  <input type="checkbox" class="custom-control-input" id="toggle_fivesim"
                         <?php echo $fivesim_enabled ? 'checked' : ''; ?>
                         onchange="toggleServer('fivesim', this.checked)">
                  <label class="custom-control-label" for="toggle_fivesim"></label>
                </div>
              </div>
              <div class="h6 mb-0 text-gray-700 mb-2">500+ countries &amp; services. Bearer token auth.</div>
              <?php if (!$fivesim_enabled): ?>
                <span class="badge badge-secondary"><i class="fas fa-ban mr-1"></i>Disabled</span>
              <?php elseif ($fivesim_api): ?>
                <span class="badge badge-success">Configured</span>
                <span class="ml-2 font-weight-bold" style="font-size:.85rem;">
                  <?php echo fetch_fivesim_balance($fivesim_api['api_url'], $fivesim_api['api_key']); ?>
                </span>
                <div class="mt-2">
                  <a href="fivesim_settings" class="btn btn-xs btn-outline-info">
                    <i class="fas fa-cog mr-1"></i>Manage 5SIM
                  </a>
                </div>
              <?php else: ?>
                <span class="badge badge-warning">Not Configured</span>
                <small class="text-muted d-block mt-1">Add 5SIM API below (type: 5sim).</small>
              <?php endif; ?>
            </div>
            <div class="col-auto"><i class="fas fa-mobile-alt fa-2x text-gray-300"></i></div>
          </div>
        </div>
      </div>
    </div>

    <!-- Server4 — sms-bus.com -->
    <div class="col-md-4 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="d-flex align-items-center justify-content-between mb-1">
                <div class="text-xs font-weight-bold text-warning text-uppercase">Server4 — sms-bus.com</div>
                <div class="custom-control custom-switch ml-2">
                  <input type="checkbox" class="custom-control-input" id="toggle_smsbus"
                         <?php echo $smsbus_enabled ? 'checked' : ''; ?>
                         onchange="toggleServer('smsbus', this.checked)">
                  <label class="custom-control-label" for="toggle_smsbus"></label>
                </div>
              </div>
              <div class="h6 mb-0 text-gray-700 mb-2">Token-based auth, 100+ countries &amp; projects.</div>
              <?php if (!$smsbus_enabled): ?>
                <span class="badge badge-secondary"><i class="fas fa-ban mr-1"></i>Disabled</span>
              <?php elseif ($smsbus_api): ?>
                <span class="badge badge-success">Configured</span>
                <span class="ml-2 font-weight-bold" style="font-size:.85rem;">
                  <?php echo fetch_smsbus_balance($smsbus_api['api_url'], $smsbus_api['api_key']); ?>
                </span>
                <div class="mt-2">
                  <a href="smsbus_settings" class="btn btn-xs btn-outline-warning">
                    <i class="fas fa-cog mr-1"></i>Manage SMS-Bus
                  </a>
                </div>
              <?php else: ?>
                <span class="badge badge-warning">Not Configured</span>
                <div class="mt-2">
                  <a href="smsbus_settings" class="btn btn-xs btn-outline-warning">
                    <i class="fas fa-cog mr-1"></i>Configure SMS-Bus
                  </a>
                </div>
              <?php endif; ?>
            </div>
            <div class="col-auto"><i class="fas fa-bus fa-2x text-gray-300"></i></div>
          </div>
        </div>
      </div>
    </div>
  </div>

  <!-- ── API Table ── -->
  <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-plug mr-2"></i>All APIs</h6>
          <button class="btn btn-sm btn-primary" onclick="openAddApiModal()">
            <i class="fas fa-plus mr-1"></i>Add New API
          </button>
        </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>API Name</th>
                <th>Provider</th>
                <th>API Balance</th>
                <th>API URL</th>
                <th>API Key</th>
                <th>Actions</th>
              </tr>
            </thead>
            <tbody>
              <?php
              $i = 1;
              foreach ($apis as $data):
                $api_type  = $data['api_type'] ?? 'smscodes';
                $is_smspva = $api_type === 'smspva';
                $is_5sim   = $api_type === '5sim';
                $is_smsbus = $api_type === 'smsbus';

                // Balance cell
                if ($is_smspva) {
                    $cached_val = $smspva_balance_cached !== null
                        ? '<span class="font-weight-bold text-success">$' . number_format($smspva_balance_cached, 4) . '</span>'
                        : '<span class="text-muted">—</span>';
                    $bal_html = '<span id="smspvaBalRow_' . $data['id'] . '">' . $cached_val . '</span>'
                        . ' <button class="btn btn-xs btn-outline-info ml-1" title="Refresh"'
                        . ' onclick="checkSmspvaBalance(this, ' . $data['id'] . ')">'
                        . '<i class="fas fa-refresh"></i></button>';
                } elseif ($is_5sim) {
                    $bal_html = fetch_fivesim_balance($data['api_url'], $data['api_key']);
                } elseif ($is_smsbus) {
                    $bal_html = fetch_smsbus_balance($data['api_url'], $data['api_key']);
                } else {
                    $bal_html = fetch_smscodes_balance($data['api_url'], $data['api_key']);
                }
              ?>
              <tr>
                <td><?php echo $i; ?></td>
                <td><strong><?php echo htmlspecialchars($data['api_name']); ?></strong></td>
                <td>
                  <?php if ($is_smspva): ?>
                    <span class="badge badge-primary">Server1 — smspva.com</span>
                  <?php elseif ($is_5sim): ?>
                    <span class="badge badge-info">Server3 — 5sim.net</span>
                  <?php elseif ($is_smsbus): ?>
                    <span class="badge badge-warning">Server4 — sms-bus.com</span>
                  <?php else: ?>
                    <span class="badge badge-success">Server2 — smscodes.io</span>
                  <?php endif; ?>
                </td>
                <td><?php echo $bal_html; ?></td>
                <td><small><?php echo htmlspecialchars($data['api_url']); ?></small></td>
                <td>
                  <span class="text-muted" style="font-size:.85em;word-break:break-all;">
                    <?php echo htmlspecialchars(substr($data['api_key'], 0, 20)) . (strlen($data['api_key']) > 20 ? '…' : ''); ?>
                  </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="openEditApiModal(
                           <?php echo $data['id']; ?>,
                           '<?php echo addslashes(htmlspecialchars($data['api_name'], ENT_QUOTES)); ?>',
                           '<?php echo addslashes(htmlspecialchars($data['api_url'],  ENT_QUOTES)); ?>',
                           '<?php echo addslashes(htmlspecialchars($data['api_key'],  ENT_QUOTES)); ?>',
                           '<?php echo $api_type; ?>'
                         )">
                        <i class="fas fa-edit text-primary"></i> Edit API
                      </a>
                      <div class="dropdown-divider"></div>
                      <a class="dropdown-item" href="#"
                         onclick="deleteApi(<?php echo $data['id']; ?>, '<?php echo addslashes(htmlspecialchars($data['api_name'], ENT_QUOTES)); ?>')">
                        <i class="fas fa-trash text-danger"></i> Delete API
                      </a>
                    </div>
                  </div>
                </td>
              </tr>
              <?php $i++; endforeach; ?>
            </tbody>
          </table>
        </div>
      </div>
    </div>
  </div>
</div>

<!-- ── Add API Modal ── -->
<div class="modal fade" id="addApiModal" tabindex="-1" role="dialog">
  <div class="modal-dialog modal-dialog-centered"><div class="modal-content">
    <div class="modal-header">
      <h5 class="modal-title font-weight-bold text-primary"><i class="fas fa-plug mr-2"></i>Add New API</h5>
      <button type="button" class="close" data-dismiss="modal"><span>&times;</span></button>
    </div>
    <div class="modal-body">
      <div class="form-group">
        <label class="font-weight-bold">Provider Type</label>
        <select class="form-control" id="add_api_type" onchange="onAddTypeChange(this.value)">
          <option value="smscodes">Server2 — smscodes.io</option>
          <option value="smspva">Server1 — smspva.com</option>
          <option value="5sim">Server3 — 5sim.net</option>
          <option value="smsbus">Server4 — sms-bus.com</option>
        </select>
        <small class="text-muted" id="addTypeHint">API URL: https://code.smscodes.io/api/sms</small>
      </div>
      <div class="form-group">
        <label class="font-weight-bold">API Name</label>
        <input type="text" class="form-control" id="add_api_name" placeholder="e.g. SMSCodes">
      </div>
      <div class="form-group">
        <label class="font-weight-bold">API URL</label>
        <input type="text" class="form-control" id="add_api_url" placeholder="e.g. https://code.smscodes.io/api/sms">
      </div>
      <div class="form-group">
        <label class="font-weight-bold">API Key</label>
        <input type="text" class="form-control" id="add_api_key" placeholder="Enter your API key">
      </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="submitAddApi">
        <i class="fas fa-plus mr-1"></i>Add API
      </button>
    </div>
  </div></div>
</div>

<!-- ── Edit API Modal ── -->
<div class="modal fade" id="editApiModal" tabindex="-1" role="dialog">
  <div class="modal-dialog modal-dialog-centered"><div class="modal-content">
    <div class="modal-header">
      <h5 class="modal-title font-weight-bold text-primary"><i class="fas fa-edit mr-2"></i>Edit API</h5>
      <button type="button" class="close" data-dismiss="modal"><span>&times;</span></button>
    </div>
    <div class="modal-body">
      <input type="hidden" id="edit_api_id">
      <div class="form-group">
        <label class="font-weight-bold">Provider Type</label>
        <select class="form-control" id="edit_api_type">
          <option value="smscodes">Server2 — smscodes.io</option>
          <option value="smspva">Server1 — smspva.com</option>
          <option value="5sim">Server3 — 5sim.net</option>
          <option value="smsbus">Server4 — sms-bus.com</option>
        </select>
      </div>
      <div class="form-group">
        <label class="font-weight-bold">API Name</label>
        <input type="text" class="form-control" id="edit_api_name">
      </div>
      <div class="form-group">
        <label class="font-weight-bold">API URL</label>
        <input type="text" class="form-control" id="edit_api_url">
      </div>
      <div class="form-group">
        <label class="font-weight-bold">API Key</label>
        <input type="text" class="form-control" id="edit_api_key">
      </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="submitEditApi">
        <i class="fas fa-save mr-1"></i>Save Changes
      </button>
    </div>
  </div></div>
</div>

<script src="vendor/datatables/jquery.dataTables.min.js"></script>
<script src="vendor/datatables/dataTables.bootstrap4.min.js"></script>

<script>
$(document).ready(function () {
  $('#dataTable').DataTable({ ordering: true, pageLength: 25, order: [[0, 'asc']] });
});

// ── Toggle Server On/Off ──────────────────────────────────────────────────────
function toggleServer(server, enabled) {
  var label = {smspva:'Server1 (smspva)',smscodes:'Server2 (smscodes)',fivesim:'Server3 (5SIM)',smsbus:'Server4 (SMS-Bus)'}[server] || server;
  var action = enabled ? 'enable' : 'disable';
  Swal.fire({
    title: (enabled ? 'Enable ' : 'Disable ') + label + '?',
    html: enabled
      ? 'Users will see <strong>' + label + '</strong> tab on the SMS page.'
      : 'The <strong>' + label + '</strong> tab will be hidden from users.',
    icon: 'question', showCancelButton: true,
    confirmButtonColor: enabled ? '#1cc88a' : '#e74a3b',
    confirmButtonText: enabled ? 'Yes, Enable' : 'Yes, Disable',
  }).then(function(r) {
    if (!r.isConfirmed) {
      // Revert the toggle
      document.getElementById('toggle_' + server).checked = !enabled;
      return;
    }
    $.ajax({
      url: 'ajax/toggle_server.php', type: 'POST',
      data: { server: server, enabled: enabled ? 1 : 0 },
      dataType: 'json',
      success: function(d) {
        if (d.status == '1') {
          Swal.fire({ title: enabled ? 'Enabled!' : 'Disabled!', text: d.msg, icon: 'success', timer: 1800, showConfirmButton: false })
            .then(function() { location.reload(); });
        } else {
          document.getElementById('toggle_' + server).checked = !enabled;
          Swal.fire('Error', d.msg, 'error');
        }
      },
      error: function() {
        document.getElementById('toggle_' + server).checked = !enabled;
        Swal.fire('Error', 'Request failed.', 'error');
      }
    });
  });
}

// ── Add type hint / auto-fill ─────────────────────────────────────────────────
function onAddTypeChange(val) {
  var hints = {
    smscodes: 'API URL: https://code.smscodes.io/api/sms',
    smspva:   'API URL: https://api.smspva.com',
    '5sim':   'API URL: https://5sim.net/v1  |  Get token from https://5sim.net/settings/security',
    smsbus:   'API URL: https://sms-bus.com/api/control  |  Get token from sms-bus.com account'
  };
  document.getElementById('addTypeHint').textContent = hints[val] || '';
  if (val === 'smspva') {
    $('#add_api_url').val('https://api.smspva.com');
    $('#add_api_name').val('SMSPVA');
  } else if (val === '5sim') {
    $('#add_api_url').val('https://5sim.net/v1');
    $('#add_api_name').val('5SIM');
  } else if (val === 'smsbus') {
    $('#add_api_url').val('https://sms-bus.com/api/control');
    $('#add_api_name').val('SMS-Bus');
  } else {
    $('#add_api_url').val('');
    $('#add_api_name').val('');
  }
}

function openAddApiModal() {
  $('#add_api_name, #add_api_url, #add_api_key').val('');
  $('#add_api_type').val('smscodes');
  document.getElementById('addTypeHint').textContent = 'API URL: https://code.smscodes.io/api/sms';
  $('#addApiModal').modal('show');
}

// ── Add API ───────────────────────────────────────────────────────────────────
$('#submitAddApi').on('click', function () {
  var name = $.trim($('#add_api_name').val());
  var url  = $.trim($('#add_api_url').val());
  var key  = $.trim($('#add_api_key').val());
  var type = $('#add_api_type').val();
  if (!name || !url || !key) { Swal.fire('Validation', 'Please fill in all fields.', 'warning'); return; }
  $(this).prop('disabled', true).html('<i class="fas fa-spinner fa-spin mr-1"></i>Adding...');
  $.ajax({
    url: 'ajax/apis.php', type: 'POST',
    data: { action: 'add', api_name: name, api_url: url, api_key: key, api_type: type },
    dataType: 'json',
    success: function (d) {
      $('#submitAddApi').prop('disabled', false).html('<i class="fas fa-plus mr-1"></i>Add API');
      if (d.status == '1') { $('#addApiModal').modal('hide'); Swal.fire('Added!', d.msg, 'success').then(() => location.reload()); }
      else Swal.fire('Error!', d.msg, 'error');
    },
    error: function () {
      $('#submitAddApi').prop('disabled', false).html('<i class="fas fa-plus mr-1"></i>Add API');
      Swal.fire('Error!', 'Request failed. Please try again.', 'error');
    }
  });
});

// ── Edit API ──────────────────────────────────────────────────────────────────
function openEditApiModal(id, name, url, key, type) {
  $('#edit_api_id').val(id); $('#edit_api_name').val(name); $('#edit_api_url').val(url);
  $('#edit_api_key').val(key); $('#edit_api_type').val(type || 'smscodes');
  $('#editApiModal').modal('show');
}

$('#submitEditApi').on('click', function () {
  var id   = $('#edit_api_id').val();
  var name = $.trim($('#edit_api_name').val());
  var url  = $.trim($('#edit_api_url').val());
  var key  = $.trim($('#edit_api_key').val());
  var type = $('#edit_api_type').val();
  if (!name || !url || !key) { Swal.fire('Validation', 'Please fill in all fields.', 'warning'); return; }
  $(this).prop('disabled', true).html('<i class="fas fa-spinner fa-spin mr-1"></i>Saving...');
  $.ajax({
    url: 'ajax/apis.php', type: 'POST',
    data: { action: 'edit', id: id, api_name: name, api_url: url, api_key: key, api_type: type },
    dataType: 'json',
    success: function (d) {
      $('#submitEditApi').prop('disabled', false).html('<i class="fas fa-save mr-1"></i>Save Changes');
      if (d.status == '1') { $('#editApiModal').modal('hide'); Swal.fire('Updated!', d.msg, 'success').then(() => location.reload()); }
      else Swal.fire('Error!', d.msg, 'error');
    },
    error: function () {
      $('#submitEditApi').prop('disabled', false).html('<i class="fas fa-save mr-1"></i>Save Changes');
      Swal.fire('Error!', 'Request failed.', 'error');
    }
  });
});

// ── Delete API ────────────────────────────────────────────────────────────────
function deleteApi(id, name) {
  Swal.fire({
    title: 'Delete API?',
    html: 'Delete <strong>' + name + '</strong>?<br><small class="text-danger">This cannot be undone.</small>',
    icon: 'warning', showCancelButton: true,
    confirmButtonColor: '#e74a3b', cancelButtonColor: '#858796',
    confirmButtonText: 'Yes, Delete',
  }).then(function (r) {
    if (!r.isConfirmed) return;
    Swal.fire({ title: 'Processing...', allowOutsideClick: false, didOpen: () => Swal.showLoading() });
    $.ajax({
      url: 'ajax/apis.php', type: 'POST', data: { action: 'delete', id: id }, dataType: 'json',
      success: function (d) {
        Swal.close();
        if (d.status == '1') Swal.fire('Deleted!', d.msg, 'success').then(() => location.reload());
        else Swal.fire('Error!', d.msg, 'error');
      },
      error: function () { Swal.close(); Swal.fire('Error!', 'Request failed.', 'error'); }
    });
  });
}

// ── Check smspva (Server1) balance ────────────────────────────────────────────
// btn   = clicked button element
// rowId = optional api row id (for in-table refresh icon)
function checkSmspvaBalance(btn, rowId) {
  var $btn     = $(btn);
  var origHtml = $btn.html();
  $btn.prop('disabled', true).html('<i class="fas fa-spinner fa-spin"></i>');

  var $cardEl = $('#smspvaBalanceDisplay');
  var $rowEl  = rowId ? $('#smspvaBalRow_' + rowId) : null;
  $cardEl.text('Checking...');

  $.ajax({
    url: 'ajax/sync_data.php', type: 'POST',
    data: { action: 'smspva_balance' },
    dataType: 'json', timeout: 30000,
    success: function (data) {
      $btn.prop('disabled', false).html(origHtml);
      if (data.status == '1') {
        var formatted = '$' + parseFloat(data.balance).toFixed(4);
        $cardEl.text(formatted).removeClass('text-danger').addClass('text-success');
        if ($rowEl) $rowEl.html('<span class="font-weight-bold text-success">' + formatted + '</span>');
      } else {
        $cardEl.text('Error').removeClass('text-success').addClass('text-danger');
        if ($rowEl) $rowEl.html('<span class="text-danger font-weight-bold">Error</span>');
        // Show full debug so the problem is visible
        Swal.fire({
          title: 'smspva Balance Error',
          html: '<p class="text-left">' + (data.msg || 'Unknown error.') + '</p>'
              + (data.debug ? '<pre style="text-align:left;font-size:.72rem;max-height:200px;overflow:auto;background:#f8f9fc;padding:8px;border-radius:4px;">'
                            + JSON.stringify(data.debug, null, 2) + '</pre>' : ''),
          icon: 'warning',
        });
      }
    },
    error: function () {
      $btn.prop('disabled', false).html(origHtml);
      $cardEl.text('Request failed').addClass('text-danger');
      Swal.fire('Network Error', 'Ajax call to sync_data.php failed. Check your server logs.', 'error');
    }
  });
}
</script>

<style>
.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; }
</style>

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