<?php
include('../includes/session.php');
include('../includes/config.php');
include('../template/tngweb/header.php');

/* ==============================
   ADMIN CHECK
============================== */
if (!isset($udata['id']) || $udata['type'] !== 'admin') {
    echo '<script>alert("Access Denied");location.href="../includes/logout.php";</script>';
    exit;
}

/* ==============================
   FETCH STORED JSON
============================== */
$api_json      = get_api_json($tng_conn);
$tnx_json      = $api_json['tng_json'] ?? [];
$payment_json  = $api_json['payment_json'] ?? [];
$whatsapp_json = $api_json['whatsapp_json'] ?? [];
$smtp_json     = $api_json['smtp_json'] ?? [];

$alert_msg  = '';
$alert_type = '';

/* ==============================
   UPDATE TNG API
============================== */
if (isset($_POST['update_tng'])) {
    $apikey = trim($_POST['tng_apikey'] ?? '');
    $url    = trim($_POST['tng_apiurl'] ?? '');

    if ($apikey && $url) {
        $tnx_json = [
            'tng_apikey' => $apikey,
            'tng_apiurl' => $url
        ];
        $ok = update_api_json($tng_conn, 'tng', $tnx_json);
        $alert_msg  = $ok ? "✅ TheNextGenAPI Updated" : "❌ Database Error";
        $alert_type = $ok ? 'success' : 'error';
    } else {
        $alert_msg = "❌ API Key & URL required";
        $alert_type = "warning";
    }
}

/* ==============================
   UPDATE PAYMENT GATEWAY
============================== */
if (isset($_POST['update_gateway'])) {
    $apikey = trim($_POST['gateway_apikey'] ?? '');
    $url    = trim($_POST['gateway_url'] ?? '');

    if ($apikey && $url) {
        $payment_json = [
            'gateway_apikey' => $apikey,
            'gateway_Url'    => $url
        ];
        $ok = update_api_json($tng_conn, 'gateway', $payment_json);
        $alert_msg  = $ok ? "✅ Gateway API Updated" : "❌ Database Error";
        $alert_type = $ok ? 'success' : 'error';
    } else {
        $alert_msg  = "❌ Gateway Key & URL required";
        $alert_type = 'warning';
    }
}

/* ==============================
   UPDATE WHATSAPP (ONLY URL)
============================== */
if (isset($_POST['update_whatsapp'])) {
    $url = trim($_POST['whatsapp_url'] ?? '');

    if ($url) {
        $whatsapp_json = [
            'whatsapp_url' => $url
        ];
        $ok = update_api_json($tng_conn, 'whatsapp', $whatsapp_json);
        $alert_msg  = $ok ? "✅ WhatsApp API URL Updated" : "❌ Database Error";
        $alert_type = $ok ? 'success' : 'error';
    } else {
        $alert_msg  = "❌ WhatsApp API URL required";
        $alert_type = 'warning';
    }
}

/* ==============================
   UPDATE SMTP
============================== */
if (isset($_POST['update_smtp'])) {
    $smtp_json = [
        'host'     => trim($_POST['host'] ?? ''),
        'port'     => trim($_POST['port'] ?? ''),
        'username' => trim($_POST['username'] ?? ''),
        'password' => trim($_POST['password'] ?? ''),
        'secure'   => trim($_POST['secure'] ?? '')
    ];

    if ($smtp_json['host'] && $smtp_json['port'] && $smtp_json['username']) {
        $ok = update_api_json($tng_conn, 'smtp', $smtp_json);
        $alert_msg  = $ok ? "✅ SMTP Updated" : "❌ Database Error";
        $alert_type = $ok ? 'success' : 'error';
    } else {
        $alert_msg  = "❌ Host, Port & Username required";
        $alert_type = 'warning';
    }
}
?>

<!--start page wrapper -->
<div class="page-wrapper">
  <div class="page-content">
    <div class="card radius-15 shadow-lg border-0">
      <div class="card-body">
        <div class="d-flex align-items-center justify-content-between mb-3">
          <a href="javascript:void(0);" onclick="window.history.back();" class="btn btn-outline-primary rounded-pill px-4 py-2 fw-semibold">
            <i class="bi bi-arrow-left-circle me-2"></i> Go Back
          </a>
          <h5 class="mb-0 fw-bold text-primary">💰 Update API Keys & SMTP</h5>
        </div>

        <?php if($alert_msg): ?>
        <script>
        Swal.fire({
            html: `<?= $alert_msg ?>`,
            icon: '<?= $alert_type ?>',
            showConfirmButton: false,
            timer: 3000
        });
        </script>
        <?php endif; ?>

<div class="row g-4">

<!-- TNG -->
<div class="col-md-6">
<div class="card shadow">
<div class="card-header bg-primary text-white fw-bold">TheNextGenAPI</div>
<div class="card-body">
<form method="post">
<input class="form-control mb-3" name="tng_apikey" placeholder="API Key"
value="<?= htmlspecialchars($tnx_json['tng_apikey'] ?? '') ?>">
<input class="form-control mb-3" name="tng_apiurl" placeholder="API URL"
value="<?= htmlspecialchars($tnx_json['tng_apiurl'] ?? '') ?>">
<button class="btn btn-primary w-100" name="update_tng">Update</button>
</form>
</div>
</div>
</div>

<!-- Gateway -->
<div class="col-md-6">
<div class="card shadow">
<div class="card-header bg-warning fw-bold">Payment Gateway</div>
<div class="card-body">
<form method="post">
<input class="form-control mb-3" name="gateway_apikey" placeholder="Gateway API Key"
value="<?= htmlspecialchars($payment_json['gateway_apikey'] ?? '') ?>">
<input class="form-control mb-3" name="gateway_url" placeholder="Gateway API URL"
value="<?= htmlspecialchars($payment_json['gateway_Url'] ?? '') ?>">
<button class="btn btn-warning w-100" name="update_gateway">Update</button>
</form>
</div>
</div>
</div>

<!-- WhatsApp -->
<div class="col-md-6">
<div class="card shadow">
<div class="card-header bg-success text-white fw-bold">WhatsApp API</div>
<div class="card-body">
<form method="post">
<input
  class="form-control mb-3"
  name="whatsapp_url"
  placeholder="https://api.routemsg.in/send-text?api_key=XXXX&number={number}&msg={message}"
  value="<?= htmlspecialchars($whatsapp_json['whatsapp_url'] ?? '') ?>"
>
<button class="btn btn-success w-100" name="update_whatsapp">Update WhatsApp</button>
<small class="text-muted mt-2 d-block">
Use <b>{number}</b> & <b>{message}</b> placeholders
</small>
</form>
</div>
</div>
</div>

<!-- SMTP -->
<div class="col-md-6">
<div class="card shadow">
<div class="card-header bg-info text-white fw-bold">SMTP Settings</div>
<div class="card-body">
<form method="post">
<input class="form-control mb-2" name="host" placeholder="Host" value="<?= htmlspecialchars($smtp_json['host'] ?? '') ?>">
<input class="form-control mb-2" name="port" placeholder="Port" value="<?= htmlspecialchars($smtp_json['port'] ?? '') ?>">
<input class="form-control mb-2" name="username" placeholder="Username" value="<?= htmlspecialchars($smtp_json['username'] ?? '') ?>">
<input class="form-control mb-2" name="password" placeholder="Password" value="<?= htmlspecialchars($smtp_json['password'] ?? '') ?>">
<input class="form-control mb-2" name="secure" placeholder="SSL/TLS" value="<?= htmlspecialchars($smtp_json['secure'] ?? '') ?>">
<button class="btn btn-info w-100" name="update_smtp">Update SMTP</button>
</form>
</div>
</div>
</div>

</div>
</div>
</div>

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


<!-- ✅ DataTables CDN & Scripts -->
<script src="../template/tngweb/assets/plugins/simplebar/js/simplebar.min.js"></script>
<script src="../template/tngweb/assets/plugins/metismenu/js/metisMenu.min.js"></script>
<script src="../template/tngweb/assets/plugins/perfect-scrollbar/js/perfect-scrollbar.js"></script>
<script src="../template/tngweb/assets/js/app.js"></script>


<script>
  $(document).ready(function() {
    $('#walletTable').DataTable({
      lengthChange: false,
      pageLength: 10,
      order: [[0, "desc"]],
      buttons: ['copy', 'excel', 'pdf', 'print'],
      dom: '<"d-flex justify-content-between align-items-center mb-3"Bf>rt<"d-flex justify-content-between align-items-center"ip>'
    });
  });
</script>

<style>
  /* 🌟 Stylish Table */
  .table thead th {
    vertical-align: middle;
    font-weight: 600;
    letter-spacing: 0.3px;
  }

  .table tbody tr:hover {
    background: #f5f8ff;
    transition: 0.2s ease;
  }

  .card {
    background: #fff;
    border-radius: 15px;
  }

  .btn-outline-primary {
    border-color: #0055ff;
    color: #0055ff;
  }

  .btn-outline-primary:hover {
    background-color: #0055ff;
    color: #fff;
  }

  .dataTables_wrapper .dataTables_filter input {
    border-radius: 8px;
    padding: 5px 10px;
  }

  .dataTables_wrapper .dataTables_paginate .paginate_button {
    border-radius: 5px;
  }

  .dataTables_wrapper .dt-buttons .btn {
    border-radius: 20px !important;
    font-size: 0.85rem;
    margin-right: 6px;
  }

  .badge {
    font-size: 0.8rem;
    padding: 6px 10px;
  }
</style>