<?php
require_once __DIR__ . '/../includes/auth.php';
require_once __DIR__ . '/../includes/functions.php';
require_once __DIR__ . '/../classes/Wablas.php';
requireRole('super_admin');
$pageTitle = 'Wablas Settings';

$db = db();

// Load current config
$stmt = $db->query("SELECT * FROM wablas_config");
$config = [];
while ($row = $stmt->fetch()) {
    $config[$row['setting_key']] = $row['setting_value'];
}

$success = '';
$error = '';
$debugInfo = null;

// Handle save config
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'save_config') {
    if (verifyCsrf($_POST['csrf_token'] ?? '')) {
        $newBaseUrl = trim($_POST['base_url']);
        $newToken = trim($_POST['token']);
        
        if (empty($newBaseUrl) || empty($newToken)) {
            $error = 'Base URL dan Token wajib diisi';
        } else {
            $db->prepare("INSERT INTO wablas_config (setting_key, setting_value) VALUES ('base_url', ?) ON DUPLICATE KEY UPDATE setting_value = ?")
               ->execute([$newBaseUrl, $newBaseUrl]);
            $db->prepare("INSERT INTO wablas_config (setting_key, setting_value) VALUES ('token', ?) ON DUPLICATE KEY UPDATE setting_value = ?")
               ->execute([$newToken, $newToken]);
            
            $success = 'Konfigurasi Wablas berhasil disimpan';
            $config['base_url'] = $newBaseUrl;
            $config['token'] = $newToken;
        }
    }
}

// Handle send test message
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'send_test') {
    if (verifyCsrf($_POST['csrf_token'] ?? '')) {
        $testPhone = trim($_POST['test_phone']);
        $testMessage = trim($_POST['test_message']);
        
        if (empty($testPhone)) {
            $error = 'Nomor telepon wajib diisi';
        } else {
            $wablas = new Wablas();
            $result = $wablas->sendTest($testPhone, $testMessage);
            
            if ($result['success']) {
                $success = '✅ Pesan test berhasil dikirim ke ' . $testPhone;
                $debugInfo = [
                    'status' => 'SUCCESS',
                    'message_id' => $result['message_id'] ?? 'N/A',
                    'http_code' => $result['http_code']
                ];
            } else {
                $error = '❌ Gagal kirim: ' . ($result['error'] ?? 'Unknown error');
                $debugInfo = [
                    'status' => 'FAILED',
                    'error' => $result['error'] ?? 'Unknown',
                    'http_code' => $result['http_code'] ?? 'N/A',
                    'debug' => $result['debug'] ?? null,
                    'response' => $result['response'] ?? null
                ];
            }
        }
    }
}

require __DIR__ . '/../includes/header.php';
require __DIR__ . '/../includes/sidebar.php';
?>
<div class="main-content">
  <h3><i class="bi bi-whatsapp me-2"></i>Wablas Settings</h3>
  
  <?php if ($success): ?>
    <div class="alert alert-success alert-dismissible fade show">
      <?= htmlspecialchars($success) ?>
      <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
    </div>
  <?php endif; ?>
  
  <?php if ($error): ?>
    <div class="alert alert-danger alert-dismissible fade show">
      <?= htmlspecialchars($error) ?>
      <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
    </div>
  <?php endif; ?>

  <!-- Debug Info -->
  <?php if ($debugInfo): ?>
    <div class="card mb-3 border-info">
      <div class="card-header bg-info text-white">
        <i class="bi bi-bug me-2"></i>Debug Information
      </div>
      <div class="card-body">
        <pre class="bg-dark text-light p-3 rounded mb-0" style="font-size: 0.85rem; max-height: 400px; overflow-y: auto;"><?= htmlspecialchars(json_encode($debugInfo, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES)) ?></pre>
      </div>
    </div>
  <?php endif; ?>

  <div class="row g-4">
    <!-- Konfigurasi -->
    <div class="col-md-6">
      <div class="card">
        <div class="card-header bg-primary text-white">
          <i class="bi bi-gear me-2"></i>Konfigurasi Wablas
        </div>
        <div class="card-body">
          <form method="POST">
            <?= csrfField() ?>
            <input type="hidden" name="action" value="save_config">
            
            <div class="mb-3">
              <label class="form-label">Base URL Wablas *</label>
              <input type="url" name="base_url" class="form-control" 
                     value="<?= htmlspecialchars($config['base_url'] ?? 'https://tegal.wablas.com/api') ?>" 
                     required placeholder="https://tegal.wablas.com/api">
              <small class="text-muted">URL API Wablas (tanpa slash di akhir). Contoh: <code>https://tegal.wablas.com/api</code></small>
            </div>
            
            <div class="mb-3">
              <label class="form-label">Token Wablas *</label>
              <input type="text" name="token" class="form-control" 
                     value="<?= htmlspecialchars($config['token'] ?? '') ?>" 
                     required placeholder="Token dari dashboard Wablas">
              <small class="text-muted">Token autentikasi dari dashboard Wablas</small>
            </div>
            
            <button type="submit" class="btn btn-primary">
              <i class="bi bi-save"></i> Simpan Konfigurasi
            </button>
          </form>
        </div>
      </div>

      <!-- Info Card -->
      <div class="card mt-3">
        <div class="card-header bg-info text-white">
          <i class="bi bi-info-circle me-2"></i>Informasi
        </div>
        <div class="card-body">
          <h6>Cara Mendapatkan Token:</h6>
          <ol class="small mb-0">
            <li>Login ke dashboard Wablas</li>
            <li>Pilih device yang aktif</li>
            <li>Copy token dari menu "API" atau "Settings"</li>
            <li>Paste di form di atas</li>
          </ol>
          <hr>
          <h6>Format URL yang Didukung:</h6>
          <ul class="small mb-0">
            <li><code>https://tegal.wablas.com/api</code> (Server Tegal)</li>
            <li><code>https://surabaya.wablas.com/api</code> (Server Surabaya)</li>
            <li><code>https://solo.wablas.com/api</code> (Server Solo)</li>
            <li>atau server custom Anda</li>
          </ul>
        </div>
      </div>
    </div>

    <!-- Test Kirim Pesan -->
    <div class="col-md-6">
      <div class="card">
        <div class="card-header bg-success text-white">
          <i class="bi bi-send me-2"></i>Test Kirim Pesan
        </div>
        <div class="card-body">
          <div class="alert alert-warning">
            <small>
              <i class="bi bi-exclamation-triangle"></i> 
              Pastikan Base URL dan Token sudah disimpan sebelum mengirim test.
            </small>
          </div>
          
          <form method="POST">
            <?= csrfField() ?>
            <input type="hidden" name="action" value="send_test">
            
            <div class="mb-3">
              <label class="form-label">Nomor Telepon *</label>
              <input type="text" name="test_phone" class="form-control" 
                     required placeholder="081234567890"
                     value="<?= htmlspecialchars($_POST['test_phone'] ?? '') ?>">
              <small class="text-muted">Format: 08xxx atau 62xxx (akan otomatis dikonversi ke 62xxx)</small>
            </div>
            
            <div class="mb-3">
              <label class="form-label">Pesan Test *</label>
              <textarea name="test_message" class="form-control" rows="5" required
                        placeholder="Ini adalah pesan test dari sistem RT/RW Net">Ini adalah pesan test dari sistem RT/RW Net.

Jika Anda menerima pesan ini, berarti konfigurasi Wablas sudah benar.

Terima kasih.</textarea>
            </div>
            
            <button type="submit" class="btn btn-success">
              <i class="bi bi-send"></i> Kirim Pesan Test
            </button>
          </form>
        </div>
      </div>

      <!-- Status Connection -->
      <div class="card mt-3">
        <div class="card-header">
          <i class="bi bi-wifi me-2"></i>Status Koneksi
        </div>
        <div class="card-body">
          <?php
          $wablas = new Wablas();
          if ($wablas->isConfigured()):
          ?>
            <div class="alert alert-success mb-0">
              <i class="bi bi-check-circle"></i> Wablas sudah dikonfigurasi
              <hr class="my-2">
              <small>
                <strong>Base URL:</strong> <?= htmlspecialchars($config['base_url'] ?? '') ?><br>
                <strong>Token:</strong> <?= substr($config['token'] ?? '', 0, 10) ?>...<?= substr($config['token'] ?? '', -5) ?>
              </small>
            </div>
          <?php else: ?>
            <div class="alert alert-danger mb-0">
              <i class="bi bi-x-circle"></i> Wablas belum dikonfigurasi
              <br><small>Silakan isi Base URL dan Token di form sebelah kiri</small>
            </div>
          <?php endif; ?>
        </div>
      </div>

      <!-- Troubleshooting -->
      <div class="card mt-3">
        <div class="card-header bg-warning">
          <i class="bi bi-tools me-2"></i>Troubleshooting
        </div>
        <div class="card-body small">
          <strong>Error yang sering terjadi:</strong>
          <ul class="mb-0 mt-2">
            <li><strong>"Invalid token"</strong> → Token salah atau device belum login</li>
            <li><strong>"Phone number not valid"</strong> → Format nomor salah (harus 62xxx)</li>
            <li><strong>"Device not connected"</strong> → WhatsApp di HP belum connect</li>
            <li><strong>"Quota exceeded"</strong> → Paket Wablas habis</li>
            <li><strong>"Connection failed"</strong> → Server Wablas tidak bisa diakses</li>
          </ul>
        </div>
      </div>
    </div>
  </div>
</div>
<?php require __DIR__ . '/../includes/footer.php'; ?>