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

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

// Fetch all API JSONs including SMTP
$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 = '';

// ---------------- TNG Update ----------------
if(isset($_POST['update_tng'])){
    $new_apikey = trim($_POST['tng_apikey'] ?? '');
    if($new_apikey != ''){
        $tnx_json['tng_apikey'] = $new_apikey;
        $update = update_api_json($tng_conn, 'tng', $tnx_json);
        $alert_msg = $update ? "✅ TheNextGenAPI Apikey Updated Successfully!" : "❌ SQL Error: ".mysqli_error($tng_conn);
        $alert_type = $update ? 'success' : 'danger';
    } else {
        $alert_msg = "❌ Please enter a TheNextGenAPI Apikey!";
        $alert_type = "warning";
    }
}

// ---------------- Gateway Update ----------------
if(isset($_POST['update_gateway'])){
    $new_gateway_apikey = trim($_POST['gateway_apikey'] ?? '');
    if($new_gateway_apikey != ''){
        $payment_json['gateway_apikey'] = $new_gateway_apikey;
        $update = update_api_json($tng_conn, 'gateway', $payment_json);
        $alert_msg = $update ? "✅ Gateway Apikey Updated Successfully!" : "❌ SQL Error: ".mysqli_error($tng_conn);
        $alert_type = $update ? 'success' : 'danger';
    } else {
        $alert_msg = "❌ Please enter a Gateway Apikey!";
        $alert_type = "warning";
    }
}

// ---------------- WhatsApp Update ----------------
if(isset($_POST['update_whatsapp'])){
    $new_whatsapp_apikey = trim($_POST['whatsapp_apikey'] ?? '');
    $new_sender_no = trim($_POST['whatsapp_sender_no'] ?? '');
    if($new_whatsapp_apikey != '' && $new_sender_no != ''){
        $whatsapp_json['whatsapp_apikey'] = $new_whatsapp_apikey;
        $whatsapp_json['whatsapp_sender_no'] = $new_sender_no;
        $update = update_api_json($tng_conn, 'whatsapp', $whatsapp_json);
        $alert_msg = $update ? "✅ WhatsApp API Updated Successfully!" : "❌ SQL Error: ".mysqli_error($tng_conn);
        $alert_type = $update ? 'success' : 'danger';
    } else {
        $alert_msg = "❌ Please enter both WhatsApp Apikey and Sender No!";
        $alert_type = "warning";
    }
}

// ---------------- SMTP Update ----------------
if(isset($_POST['update_smtp'])){
    $smtp_fields = ['host','port','username','password','secure'];
    foreach($smtp_fields as $field){
        $smtp_json[$field] = trim($_POST[$field] ?? '');
    }

    // Validate required fields
    if(!empty($smtp_json['host']) && !empty($smtp_json['port']) && !empty($smtp_json['username'])){
        $update = update_api_json($tng_conn, 'smtp', $smtp_json);
        $alert_msg = $update ? "✅ SMTP Settings Updated Successfully!" : "❌ SQL Error: ".mysqli_error($tng_conn);
        $alert_type = $update ? 'success' : 'danger';
    } else {
        $alert_msg = "❌ Please fill at least Host, Port, and Username!";
        $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">
        <!-- Back Button -->
        <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(!empty($alert_msg)): ?>
        <script>
        Swal.fire({
            html: `<?= $alert_msg ?>`,
            icon: '<?= $alert_type ?>',
            showConfirmButton: false,
            showCloseButton: true
        });
        </script>
        <?php endif; ?>

        <div class="row">
            <!-- TheNextGenAPI Form -->
            <div class="col-md-6">
                <div class="card mb-4">
                    <div class="card-header bg-primary text-white">TheNextGenAPI</div>
                    <div class="card-body">
                        <form method="POST">
                            <div class="mb-3">
                                <label class="form-label">Apikey</label>
                                <input type="text" class="form-control" name="tng_apikey" value="<?= htmlspecialchars($tnx_json['tng_apikey'] ?? '') ?>" placeholder="Enter new TNG Apikey">
                            </div>
                            <button type="submit" class="btn btn-primary w-100" name="update_tng">💾 Update TheNextGenAPI</button>
                        </form>
                    </div>
                </div>
            </div>

            <!-- Gateway Form -->
            <div class="col-md-6">
                <div class="card mb-4">
                    <div class="card-header bg-warning text-dark">Gateway / PaymentAPI</div>
                    <div class="card-body">
                        <form method="POST">
                            <div class="mb-3">
                                <label class="form-label">Apikey</label>
                                <input type="text" class="form-control" name="gateway_apikey" value="<?= htmlspecialchars($payment_json['gateway_apikey'] ?? '') ?>" placeholder="Enter new Gateway Apikey">
                            </div>
                            <button type="submit" class="btn btn-warning w-100" name="update_gateway">💾 Update Gateway</button>
                        </form>
                    </div>
                </div>
            </div>

            <!-- WhatsApp Form -->
            <div class="col-md-6">
                <div class="card mb-4">
                    <div class="card-header bg-success text-white">WhatsApp API</div>
                    <div class="card-body">
                        <form method="POST">
                            <div class="mb-3">
                                <label class="form-label">WhatsApp Apikey</label>
                                <input type="text" class="form-control" name="whatsapp_apikey" value="<?= htmlspecialchars($whatsapp_json['whatsapp_apikey'] ?? '') ?>" placeholder="Enter WhatsApp Apikey">
                            </div>
                            <div class="mb-3">
                                <label class="form-label">Sender Number</label>
                                <input type="text" class="form-control" name="whatsapp_sender_no" value="<?= htmlspecialchars($whatsapp_json['whatsapp_sender_no'] ?? '') ?>" placeholder="Enter WhatsApp Sender Number">
                            </div>
                            <button type="submit" class="btn btn-success w-100" name="update_whatsapp">💾 Update WhatsApp API</button>
                        </form>
                    </div>
                </div>
            </div>

            <!-- SMTP Form -->
            <div class="col-md-6">
                <div class="card mb-4">
                    <div class="card-header bg-info text-white">SMTP Settings</div>
                    <div class="card-body">
                        <form method="POST">
                            <?php 
                            $smtp_fields = ['host'=>'Host','port'=>'Port','username'=>'Username','password'=>'Password','secure'=>'Secure'];
                            foreach($smtp_fields as $field=>$label): ?>
                            <div class="mb-3">
                                <label class="form-label"><?= $label ?></label>
                                <input type="text" class="form-control" name="<?= $field ?>" value="<?= htmlspecialchars($smtp_json[$field] ?? '') ?>" placeholder="<?= $label ?>">
                            </div>
                            <?php endforeach; ?>
                            <button type="submit" class="btn btn-info w-100" name="update_smtp">💾 Update SMTP</button>
                        </form>
                    </div>
                </div>
            </div>

        </div> <!-- row end -->
      </div> <!-- container end -->
     </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>