<?php
require_once __DIR__ . '/../includes/auth.php';
require_once __DIR__ . '/../includes/functions.php';
requireRole('super_admin');

$pageTitle = 'Wablas Gateway Settings';
$db = db();

// 1. Load Config dari database
$config = [];
try {
    $stmt = $db->query("SELECT setting_key, setting_value FROM wa_config WHERE setting_key IN ('wablas_token', 'wablas_base_url')");
    while ($row = $stmt->fetch()) {
        $config[$row['setting_key']] = $row['setting_value'];
    }
} catch (\Throwable $e) {}

$baseUrl = $config['wablas_base_url'] ?? 'https://tegal.wablas.com/api';
$token = $config['wablas_token'] ?? '';

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

// 2. Fungsi Helper cURL untuk Wablas
function wablasRequest($endpoint, $params = []) {
    global $baseUrl, $token;
    
    $params['token'] = $token;
    $queryString = http_build_query($params);
    $url = rtrim($baseUrl, '/') . '/' . ltrim($endpoint, '/') . '?' . $queryString;
    
    $curl = curl_init();
    curl_setopt($curl, CURLOPT_URL, $url);
    curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "GET"); 
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 0);
    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0);
    curl_setopt($curl, CURLOPT_TIMEOUT, 15);
    
    $result = curl_exec($curl);
    $httpCode = curl_getinfo($curl, CURLINFO_HTTP_CODE);
    $curlError = curl_error($curl);
    curl_close($curl);
    
    return [
        'http_code' => $httpCode,
        'data' => json_decode($result, true),
        'raw' => $result,
        'error' => $curlError,
        'url_called' => $url
    ];
}

// 3. Handle Save Settings
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'save_settings') {
    if (verifyCsrf($_POST['csrf_token'] ?? '')) {
        $newBaseUrl = trim($_POST['wablas_base_url'] ?? '');
        $newToken = trim($_POST['wablas_token'] ?? '');
        
        $endpointsToStrip = ['/send-message', '/send-image', '/send-document', '/device/info', '/token'];
        foreach ($endpointsToStrip as $ep) {
            if (substr($newBaseUrl, -strlen($ep)) === $ep) {
                $newBaseUrl = substr($newBaseUrl, 0, -strlen($ep));
            }
        }
        $newBaseUrl = rtrim($newBaseUrl, '/');

        if (empty($newBaseUrl) || empty($newToken)) {
            $error = 'Base URL dan Token wajib diisi';
        } else {
            $db->prepare("INSERT INTO wa_config (setting_key, setting_value) VALUES ('wablas_base_url', ?) ON DUPLICATE KEY UPDATE setting_value = ?")
               ->execute([$newBaseUrl, $newBaseUrl]);
            $db->prepare("INSERT INTO wa_config (setting_key, setting_value) VALUES ('wablas_token', ?) ON DUPLICATE KEY UPDATE setting_value = ?")
               ->execute([$newToken, $newToken]);
            
            $success = '✅ Konfigurasi Wablas berhasil disimpan';
            $baseUrl = $newBaseUrl;
            $token = $newToken;
        }
    }
}

// 4. Handle Check Status
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'check_status') {
    if (verifyCsrf($_POST['csrf_token'] ?? '')) {
        if (empty($token)) {
            $error = 'Token belum diisi. Silakan simpan konfigurasi terlebih dahulu.';
        } else {
            $res = wablasRequest('/device/info', []);
            $debugInfo = [
                'action' => 'Check Status Token',
                'url_called' => $res['url_called'],
                'http_code' => $res['http_code'],
                'response' => $res['data'] ?: $res['raw']
            ];
            
            if ($res['http_code'] == 200 && isset($res['data']['status']) && $res['data']['status'] === true) {
                $deviceStatus = $res['data']['data']['status'] ?? 'unknown';
                $deviceName = $res['data']['data']['name'] ?? 'N/A';
                $success = "✅ Token Valid! Device: <strong>{$deviceName}</strong> | Status: <strong>" . strtoupper($deviceStatus) . "</strong>";
                if ($deviceStatus === 'disconnected') {
                    $success .= " (Peringatan: Device terputus. Silakan scan QR di dashboard Wablas)";
                }
            } else {
                $errorMsg = $res['data']['message'] ?? $res['data']['error'] ?? 'Unknown error';
                $error = '❌ Status: ' . $errorMsg;
            }
        }
    }
}

// 5. Handle Send Test Message
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'send_test') {
    if (verifyCsrf($_POST['csrf_token'] ?? '')) {
        $phone = preg_replace('/[^0-9]/', '', $_POST['test_phone'] ?? '');
        if (substr($phone, 0, 1) === '0') $phone = '62' . substr($phone, 1);
        elseif (substr($phone, 0, 2) !== '62') $phone = '62' . $phone;
        
        $message = trim($_POST['test_message'] ?? '');
        
        if (empty($phone) || empty($message)) {
            $error = 'Nomor telepon dan pesan wajib diisi';
        } elseif (empty($token)) {
            $error = 'Token belum dikonfigurasi';
        } else {
            $params = ['phone' => $phone, 'message' => $message];
            $res = wablasRequest('/send-message', $params);
            
            $debugInfo = [
                'action' => 'Send Test Message',
                'url_called' => $res['url_called'],
                'http_code' => $res['http_code'],
                'response' => $res['data'] ?: $res['raw']
            ];
            
            if ($res['http_code'] == 200 && isset($res['data']['status']) && $res['data']['status'] === true) {
                $success = '✅ Pesan berhasil dikirim ke ' . $phone;
            } else {
                $errorMsg = $res['data']['message'] ?? $res['data']['error'] ?? 'Unknown error';
                $error = '❌ Gagal kirim: ' . $errorMsg;
            }
        }
    }
}

// Stats
$isConfigured = !empty($token) && !empty($baseUrl);
$tokenLength = strlen($token);
$serverName = 'Unknown';
if (strpos($baseUrl, 'tegal') !== false) $serverName = 'Tegal';
elseif (strpos($baseUrl, 'surabaya') !== false) $serverName = 'Surabaya';
elseif (strpos($baseUrl, 'solo') !== false) $serverName = 'Solo';

require __DIR__ . '/../includes/header.php';
require __DIR__ . '/../includes/sidebar.php';
?>

<style>
/* ============================================
   PAGE HEADER
   ============================================ */
.page-header {
    margin-bottom: 25px;
}

.page-title {
    font-size: 1.8rem;
    font-weight: 700;
    color: #003D7A;
    margin: 0 0 8px;
    display: flex;
    align-items: center;
    gap: 12px;
}

.page-title i {
    font-size: 2rem;
    color: #25D366;
}

.page-subtitle {
    color: #666;
    font-size: 0.95rem;
    margin: 0;
}

/* ============================================
   SUMMARY CARDS
   ============================================ */
.summary-row {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(220px, 1fr));
    gap: 16px;
    margin-bottom: 25px;
}

.summary-card {
    background: white;
    border-radius: 16px;
    padding: 20px;
    box-shadow: 0 4px 20px rgba(0,0,0,0.08);
    position: relative;
    overflow: hidden;
    transition: all 0.3s ease;
}

.summary-card:hover {
    transform: translateY(-3px);
    box-shadow: 0 8px 25px rgba(0,0,0,0.12);
}

.summary-card::before {
    content: '';
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    height: 4px;
}

.summary-card.success::before { background: linear-gradient(135deg, #25D366 0%, #128C7E 100%); }
.summary-card.primary::before { background: linear-gradient(135deg, #0066CC 0%, #00B4FF 100%); }
.summary-card.warning::before { background: linear-gradient(135deg, #FF9900 0%, #FFB84D 100%); }
.summary-card.info::before { background: linear-gradient(135deg, #00B8D4 0%, #26C6DA 100%); }
.summary-card.danger::before { background: linear-gradient(135deg, #DC3545 0%, #FF6B7A 100%); }

.summary-card-header {
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin-bottom: 12px;
}

.summary-card-title {
    color: #666;
    font-size: 0.85rem;
    font-weight: 600;
    margin: 0;
    display: flex;
    align-items: center;
    gap: 6px;
}

.summary-card-icon {
    width: 40px;
    height: 40px;
    border-radius: 12px;
    display: flex;
    align-items: center;
    justify-content: center;
    color: white;
    font-size: 1.2rem;
}

.summary-card.success .summary-card-icon { background: linear-gradient(135deg, #25D366 0%, #128C7E 100%); }
.summary-card.primary .summary-card-icon { background: linear-gradient(135deg, #0066CC 0%, #00B4FF 100%); }
.summary-card.warning .summary-card-icon { background: linear-gradient(135deg, #FF9900 0%, #FFB84D 100%); }
.summary-card.info .summary-card-icon { background: linear-gradient(135deg, #00B8D4 0%, #26C6DA 100%); }
.summary-card.danger .summary-card-icon { background: linear-gradient(135deg, #DC3545 0%, #FF6B7A 100%); }

.summary-card-value {
    font-size: 1.3rem;
    font-weight: 800;
    margin-bottom: 4px;
    letter-spacing: -0.5px;
    word-break: break-all;
}

.summary-card.success .summary-card-value { color: #128C7E; }
.summary-card.primary .summary-card-value { color: #0066CC; }
.summary-card.warning .summary-card-value { color: #FF9900; }
.summary-card.info .summary-card-value { color: #00B8D4; }
.summary-card.danger .summary-card-value { color: #DC3545; }

.summary-card-footer {
    font-size: 0.8rem;
    color: #999;
    display: flex;
    align-items: center;
    gap: 6px;
}

/* ============================================
   STATUS BADGE
   ============================================ */
.status-badge {
    display: inline-flex;
    align-items: center;
    gap: 6px;
    padding: 6px 14px;
    border-radius: 20px;
    font-size: 0.85rem;
    font-weight: 700;
    text-transform: uppercase;
    letter-spacing: 0.5px;
}

.status-badge.connected {
    background: #d1e7dd;
    color: #0f5132;
}

.status-badge.disconnected {
    background: #f8d7da;
    color: #842029;
}

.status-badge.not-checked {
    background: #e9ecef;
    color: #6c757d;
}

/* ============================================
   CARD MODERN
   ============================================ */
.card-modern {
    background: white;
    border-radius: 16px;
    box-shadow: 0 4px 20px rgba(0,0,0,0.08);
    overflow: hidden;
    margin-bottom: 20px;
    border: none;
}

.card-header-modern {
    color: white;
    padding: 18px 24px;
    font-size: 1.1rem;
    font-weight: 600;
    display: flex;
    align-items: center;
    justify-content: space-between;
    gap: 10px;
}

.card-header-modern.whatsapp { background: linear-gradient(135deg, #25D366 0%, #128C7E 100%); }
.card-header-modern.primary { background: linear-gradient(135deg, #0066CC 0%, #00B4FF 100%); }
.card-header-modern.success { background: linear-gradient(135deg, #00C853 0%, #69F0AE 100%); }
.card-header-modern.warning { background: linear-gradient(135deg, #FF9900 0%, #FFB84D 100%); }
.card-header-modern.danger { background: linear-gradient(135deg, #DC3545 0%, #FF6B7A 100%); }
.card-header-modern.info { background: linear-gradient(135deg, #00B8D4 0%, #26C6DA 100%); }

.card-header-modern .title-left {
    display: flex;
    align-items: center;
    gap: 10px;
}

.card-body-modern {
    padding: 24px;
}

/* ============================================
   FORM
   ============================================ */
.form-group-modern {
    margin-bottom: 20px;
}

.form-label-modern {
    display: block;
    font-weight: 600;
    color: #003D7A;
    margin-bottom: 8px;
    font-size: 0.9rem;
}

.form-control-modern,
.form-select-modern {
    width: 100%;
    padding: 12px 16px;
    border: 2px solid #e8f4f8;
    border-radius: 12px;
    font-size: 0.95rem;
    transition: all 0.3s ease;
    background: #f8fafc;
    font-family: inherit;
}

.form-control-modern:focus,
.form-select-modern:focus {
    outline: none;
    border-color: #25D366;
    background: white;
    box-shadow: 0 0 0 4px rgba(37, 211, 102, 0.1);
}

textarea.form-control-modern {
    resize: vertical;
    min-height: 100px;
}

.form-hint {
    display: block;
    margin-top: 6px;
    font-size: 0.82rem;
    color: #999;
}

/* ============================================
   BUTTONS
   ============================================ */
.btn-modern {
    padding: 12px 24px;
    border: none;
    border-radius: 12px;
    font-size: 0.95rem;
    font-weight: 600;
    cursor: pointer;
    transition: all 0.3s ease;
    display: inline-flex;
    align-items: center;
    justify-content: center;
    gap: 8px;
    text-decoration: none;
}

.btn-modern.whatsapp {
    background: linear-gradient(135deg, #25D366 0%, #128C7E 100%);
    color: white;
    box-shadow: 0 4px 15px rgba(37, 211, 102, 0.3);
}

.btn-modern.whatsapp:hover {
    transform: translateY(-2px);
    box-shadow: 0 6px 20px rgba(37, 211, 102, 0.4);
}

.btn-modern.primary {
    background: linear-gradient(135deg, #0066CC 0%, #00B4FF 100%);
    color: white;
    box-shadow: 0 4px 12px rgba(0, 102, 204, 0.3);
}

.btn-modern.primary:hover {
    transform: translateY(-2px);
    box-shadow: 0 6px 16px rgba(0, 102, 204, 0.4);
}

.btn-modern.info {
    background: linear-gradient(135deg, #00B8D4 0%, #26C6DA 100%);
    color: white;
    box-shadow: 0 4px 12px rgba(0, 184, 212, 0.3);
}

.btn-modern.info:hover {
    transform: translateY(-2px);
    box-shadow: 0 6px 16px rgba(0, 184, 212, 0.4);
}

.btn-modern.secondary {
    background: white;
    color: #666;
    border: 2px solid #e8f4f8;
}

.btn-modern.secondary:hover {
    background: #f8fafc;
}

.btn-group-modern {
    display: flex;
    gap: 10px;
    flex-wrap: wrap;
}

/* ============================================
   ALERT MODERN
   ============================================ */
.alert-modern {
    padding: 16px 20px;
    border-radius: 12px;
    margin-bottom: 20px;
    display: flex;
    align-items: flex-start;
    gap: 12px;
    font-size: 0.95rem;
    border: 2px solid;
}

.alert-modern.success {
    background: #e8f5e9;
    border-color: #a5d6a7;
    color: #2e7d32;
}

.alert-modern.danger {
    background: #ffebee;
    border-color: #ef9a9a;
    color: #c62828;
}

.alert-modern.info {
    background: #e3f2fd;
    border-color: #90caf9;
    color: #1565c0;
}

.alert-modern.warning {
    background: #fff8e1;
    border-color: #ffe082;
    color: #f57c00;
}

.alert-modern i {
    font-size: 1.3rem;
    margin-top: 2px;
    flex-shrink: 0;
}

/* ============================================
   DEBUG BOX
   ============================================ */
.debug-box {
    background: #1e293b;
    border-radius: 12px;
    padding: 16px;
    color: #e2e8f0;
    font-family: 'Courier New', monospace;
    font-size: 0.82rem;
    line-height: 1.5;
    overflow-x: auto;
    max-height: 400px;
    overflow-y: auto;
    white-space: pre-wrap;
    word-break: break-all;
}

.debug-box-header {
    display: flex;
    align-items: center;
    gap: 8px;
    padding-bottom: 10px;
    margin-bottom: 10px;
    border-bottom: 1px solid #334155;
    color: #94a3b8;
    font-size: 0.75rem;
    text-transform: uppercase;
    letter-spacing: 1px;
}

/* ============================================
   SERVER LIST
   ============================================ */
.server-list {
    display: grid;
    gap: 10px;
}

.server-item {
    display: flex;
    align-items: center;
    gap: 12px;
    padding: 12px 16px;
    background: #f8fafc;
    border-radius: 10px;
    border: 2px solid #e8f4f8;
    transition: all 0.3s ease;
}

.server-item:hover {
    border-color: #25D366;
    background: #e8f5e9;
}

.server-icon {
    width: 36px;
    height: 36px;
    border-radius: 10px;
    background: linear-gradient(135deg, #25D366 0%, #128C7E 100%);
    color: white;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 1rem;
    flex-shrink: 0;
}

.server-info {
    flex: 1;
    min-width: 0;
}

.server-name {
    font-weight: 700;
    color: #003D7A;
    font-size: 0.9rem;
    margin-bottom: 2px;
}

.server-url {
    font-size: 0.78rem;
    color: #666;
    font-family: 'Courier New', monospace;
    word-break: break-all;
}

/* ============================================
   TROUBLESHOOT LIST
   ============================================ */
.trouble-list {
    display: grid;
    gap: 10px;
}

.trouble-item {
    display: flex;
    align-items: flex-start;
    gap: 12px;
    padding: 12px 16px;
    background: #f8fafc;
    border-radius: 10px;
    border-left: 3px solid #DC3545;
}

.trouble-icon {
    color: #DC3545;
    font-size: 1.2rem;
    margin-top: 2px;
    flex-shrink: 0;
}

.trouble-content {
    flex: 1;
    min-width: 0;
}

.trouble-title {
    font-weight: 700;
    color: #003D7A;
    font-size: 0.88rem;
    margin-bottom: 4px;
    font-family: 'Courier New', monospace;
}

.trouble-desc {
    font-size: 0.82rem;
    color: #555;
    line-height: 1.5;
}

/* ============================================
   RESPONSIVE
   ============================================ */
@media (max-width: 992px) {
    .summary-row {
        grid-template-columns: repeat(2, 1fr);
    }
}

@media (max-width: 768px) {
    .page-title {
        font-size: 1.4rem;
    }
    
    .page-title i {
        font-size: 1.6rem;
    }
    
    .summary-row {
        grid-template-columns: 1fr 1fr;
        gap: 12px;
    }
    
    .summary-card {
        padding: 14px;
    }
    
    .summary-card-value {
        font-size: 1rem;
    }
    
    .summary-card-title {
        font-size: 0.75rem;
    }
    
    .summary-card-icon {
        width: 34px;
        height: 34px;
        font-size: 1rem;
    }
    
    .card-header-modern {
        padding: 15px 18px;
        font-size: 1rem;
    }
    
    .card-body-modern {
        padding: 16px;
    }
    
    .btn-modern {
        padding: 11px 18px;
        font-size: 0.9rem;
        flex: 1;
        justify-content: center;
    }
    
    .btn-group-modern {
        flex-direction: column;
    }
    
    .btn-group-modern .btn-modern {
        width: 100%;
    }
}

@media (max-width: 480px) {
    .page-title {
        font-size: 1.2rem;
        gap: 8px;
    }
    
    .summary-row {
        grid-template-columns: 1fr 1fr;
        gap: 10px;
    }
    
    .summary-card {
        padding: 12px;
    }
    
    .summary-card-value {
        font-size: 0.9rem;
    }
    
    .summary-card-footer {
        font-size: 0.7rem;
    }
    
    .card-header-modern {
        padding: 12px 15px;
        font-size: 0.95rem;
    }
    
    .card-body-modern {
        padding: 14px;
    }
    
    .form-control-modern {
        padding: 10px 14px;
        font-size: 0.9rem;
    }
    
    .form-label-modern {
        font-size: 0.85rem;
    }
    
    .debug-box {
        font-size: 0.72rem;
        padding: 12px;
    }
}
</style>

<div class="main-content">
    <!-- ============================================
         CONTENT WRAPPER
         ============================================ -->
    <div class="content-wrapper">
        <!-- Page Header -->
        <div class="page-header">
            <h2 class="page-title">
                <i class="bi bi-whatsapp"></i>
                <span>Wablas Gateway Settings</span>
            </h2>
            <p class="page-subtitle">Konfigurasi WhatsApp API untuk broadcast dan notifikasi</p>
        </div>

        <?= flashMessage() ?>
        
        <?php if ($success): ?>
            <div class="alert-modern success">
                <i class="bi bi-check-circle-fill"></i>
                <div><?= $success ?></div>
            </div>
        <?php endif; ?>
        
        <?php if ($error): ?>
            <div class="alert-modern danger">
                <i class="bi bi-exclamation-circle-fill"></i>
                <div><?= $error ?></div>
            </div>
        <?php endif; ?>

        <!-- Summary Cards -->
        <div class="summary-row">
            <div class="summary-card <?= $isConfigured ? 'success' : 'danger' ?>">
                <div class="summary-card-header">
                    <h6 class="summary-card-title">
                        <i class="bi bi-key-fill"></i> Status Konfigurasi
                    </h6>
                    <div class="summary-card-icon">
                        <i class="bi bi-<?= $isConfigured ? 'shield-fill-check' : 'shield-fill-x' ?>"></i>
                    </div>
                </div>
                <div class="summary-card-value">
                    <?= $isConfigured ? '✅ Terkonfigurasi' : '❌ Belum' ?>
                </div>
                <div class="summary-card-footer">
                    <?= $isConfigured ? 'Token & Base URL aktif' : 'Silakan isi konfigurasi' ?>
                </div>
            </div>
            
            <div class="summary-card info">
                <div class="summary-card-header">
                    <h6 class="summary-card-title">
                        <i class="bi bi-hdd-network-fill"></i> Server
                    </h6>
                    <div class="summary-card-icon">
                        <i class="bi bi-cloud-fill"></i>
                    </div>
                </div>
                <div class="summary-card-value">
                    <?= htmlspecialchars($serverName) ?>
                </div>
                <div class="summary-card-footer">
                    🌐 <?= htmlspecialchars($baseUrl) ?>
                </div>
            </div>
            
            <div class="summary-card primary">
                <div class="summary-card-header">
                    <h6 class="summary-card-title">
                        <i class="bi bi-fingerprint"></i> Token
                    </h6>
                    <div class="summary-card-icon">
                        <i class="bi bi-lock-fill"></i>
                    </div>
                </div>
                <div class="summary-card-value">
                    <?= $tokenLength > 0 ? substr($token, 0, 8) . '...' : 'Belum diisi' ?>
                </div>
                <div class="summary-card-footer">
                    🔐 <?= $tokenLength ?> karakter
                </div>
            </div>
            
            <div class="summary-card <?= $deviceStatus === 'connected' ? 'success' : ($deviceStatus === 'disconnected' ? 'danger' : 'warning') ?>">
                <div class="summary-card-header">
                    <h6 class="summary-card-title">
                        <i class="bi bi-phone-fill"></i> Device
                    </h6>
                    <div class="summary-card-icon">
                        <i class="bi bi-<?= $deviceStatus === 'connected' ? 'wifi' : ($deviceStatus === 'disconnected' ? 'wifi-off' : 'question-circle') ?>"></i>
                    </div>
                </div>
                <div class="summary-card-value">
                    <?php if ($deviceStatus === 'connected'): ?>
                        <span class="status-badge connected">
                            <i class="bi bi-circle-fill" style="font-size: 0.5rem;"></i> Connected
                        </span>
                    <?php elseif ($deviceStatus === 'disconnected'): ?>
                        <span class="status-badge disconnected">
                            <i class="bi bi-circle-fill" style="font-size: 0.5rem;"></i> Disconnected
                        </span>
                    <?php else: ?>
                        <span class="status-badge not-checked">
                            <i class="bi bi-dash-circle"></i> Belum Dicek
                        </span>
                    <?php endif; ?>
                </div>
                <div class="summary-card-footer">
                    <?= $deviceStatus ? 'Klik "Cek Status" untuk update' : 'Klik "Cek Status" untuk cek' ?>
                </div>
            </div>
        </div>

        <div class="row g-4">
            <!-- Kolom Kiri: Konfigurasi -->
            <div class="col-lg-6">
                <div class="card-modern">
                    <div class="card-header-modern primary">
                        <div class="title-left">
                            <i class="bi bi-gear-fill"></i>
                            <span>Konfigurasi Wablas</span>
                        </div>
                    </div>
                    <div class="card-body-modern">
                        <form method="POST">
                            <?= csrfField() ?>
                            <input type="hidden" name="action" value="save_settings">
                            
                            <div class="form-group-modern">
                                <label class="form-label-modern">
                                    <i class="bi bi-link-45deg"></i> Base URL Wablas *
                                </label>
                                <input type="text" name="wablas_base_url" class="form-control-modern" 
                                       value="<?= htmlspecialchars($baseUrl) ?>" required 
                                       placeholder="https://tegal.wablas.com/api">
                                <small class="form-hint">URL API Wablas (tanpa slash di akhir). Contoh: <code>https://tegal.wablas.com/api</code></small>
                            </div>
                            
                            <div class="form-group-modern">
                                <label class="form-label-modern">
                                    <i class="bi bi-key-fill"></i> Token Wablas *
                                </label>
                                <input type="text" name="wablas_token" class="form-control-modern" 
                                       value="<?= htmlspecialchars($token) ?>" required 
                                       placeholder="Paste token dari dashboard Wablas">
                                <small class="form-hint">Token autentikasi dari dashboard Wablas</small>
                            </div>
                            
                            <div class="btn-group-modern">
                                <button type="submit" class="btn-modern primary">
                                    <i class="bi bi-save-fill"></i>
                                    <span>Simpan Konfigurasi</span>
                                </button>
                                <button type="submit" name="action" value="check_status" class="btn-modern info">
                                    <i class="bi bi-arrow-repeat"></i>
                                    <span>Cek Status Token</span>
                                </button>
                            </div>
                        </form>
                    </div>
                </div>

                <!-- Server Info -->
                <div class="card-modern">
                    <div class="card-header-modern warning">
                        <div class="title-left">
                            <i class="bi bi-info-circle-fill"></i>
                            <span>Server Wablas yang Didukung</span>
                        </div>
                    </div>
                    <div class="card-body-modern">
                        <div class="server-list">
                            <div class="server-item">
                                <div class="server-icon">
                                    <i class="bi bi-geo-alt-fill"></i>
                                </div>
                                <div class="server-info">
                                    <div class="server-name">Server Tegal</div>
                                    <div class="server-url">https://tegal.wablas.com/api</div>
                                </div>
                            </div>
                            <div class="server-item">
                                <div class="server-icon">
                                    <i class="bi bi-geo-alt-fill"></i>
                                </div>
                                <div class="server-info">
                                    <div class="server-name">Server Surabaya</div>
                                    <div class="server-url">https://surabaya.wablas.com/api</div>
                                </div>
                            </div>
                            <div class="server-item">
                                <div class="server-icon">
                                    <i class="bi bi-geo-alt-fill"></i>
                                </div>
                                <div class="server-info">
                                    <div class="server-name">Server Solo</div>
                                    <div class="server-url">https://solo.wablas.com/api</div>
                                </div>
                            </div>
                        </div>
                        <div class="alert-modern info" style="margin-top: 16px; margin-bottom: 0;">
                            <i class="bi bi-lightbulb-fill"></i>
                            <div>
                                Sistem menggunakan metode <strong>GET</strong> dengan parameter di URL. Format: 
                                <code style="background: #bbdefb; padding: 2px 6px; border-radius: 4px;">?phone=...&message=...&token=...</code>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Kolom Kanan: Test Kirim + Troubleshooting -->
            <div class="col-lg-6">
                <div class="card-modern">
                    <div class="card-header-modern success">
                        <div class="title-left">
                            <i class="bi bi-send-fill"></i>
                            <span>Test Kirim Pesan</span>
                        </div>
                    </div>
                    <div class="card-body-modern">
                        <div class="alert-modern warning" style="margin-bottom: 20px;">
                            <i class="bi bi-exclamation-triangle-fill"></i>
                            <div>
                                Pastikan Base URL dan Token sudah disimpan sebelum mengirim test.
                            </div>
                        </div>
                        
                        <form method="POST">
                            <?= csrfField() ?>
                            <input type="hidden" name="action" value="send_test">
                            
                            <div class="form-group-modern">
                                <label class="form-label-modern">
                                    <i class="bi bi-telephone-fill"></i> Nomor Telepon *
                                </label>
                                <input type="text" name="test_phone" class="form-control-modern" 
                                       required placeholder="081234567890"
                                       value="<?= htmlspecialchars($_POST['test_phone'] ?? '') ?>">
                                <small class="form-hint">Format: 08xxx atau 62xxx (akan otomatis dikonversi ke 62xxx)</small>
                            </div>
                            
                            <div class="form-group-modern">
                                <label class="form-label-modern">
                                    <i class="bi bi-chat-left-text-fill"></i> Pesan Test *
                                </label>
                                <textarea name="test_message" class="form-control-modern" rows="5" required
                                          placeholder="Ini adalah pesan test dari sistem">Ini adalah pesan test dari sistem.

Jika Anda menerima pesan ini, berarti konfigurasi Wablas sudah benar. ✅</textarea>
                            </div>
                            
                            <button type="submit" class="btn-modern whatsapp" style="width: 100%;">
                                <i class="bi bi-whatsapp"></i>
                                <span>Kirim Pesan Test</span>
                            </button>
                        </form>
                    </div>
                </div>

                <!-- Troubleshooting -->
                <div class="card-modern">
                    <div class="card-header-modern danger">
                        <div class="title-left">
                            <i class="bi bi-tools"></i>
                            <span>Troubleshooting</span>
                        </div>
                    </div>
                    <div class="card-body-modern">
                        <div class="trouble-list">
                            <div class="trouble-item">
                                <i class="bi bi-exclamation-triangle-fill trouble-icon"></i>
                                <div class="trouble-content">
                                    <div class="trouble-title">"token is null"</div>
                                    <div class="trouble-desc">
                                        Terjadi jika metode POST digunakan. Sistem sekarang sudah diperbaiki menggunakan <strong>GET</strong> sesuai format URL.
                                    </div>
                                </div>
                            </div>
                            <div class="trouble-item">
                                <i class="bi bi-exclamation-triangle-fill trouble-icon"></i>
                                <div class="trouble-content">
                                    <div class="trouble-title">"token invalid"</div>
                                    <div class="trouble-desc">
                                        Token salah atau device di dashboard Wablas belum login/scan QR.
                                    </div>
                                </div>
                            </div>
                            <div class="trouble-item">
                                <i class="bi bi-exclamation-triangle-fill trouble-icon"></i>
                                <div class="trouble-content">
                                    <div class="trouble-title">"An error occurred" (404)</div>
                                    <div class="trouble-desc">
                                        Base URL salah atau ada tambahan path yang tidak perlu (seperti /send-message).
                                    </div>
                                </div>
                            </div>
                            <div class="trouble-item">
                                <i class="bi bi-exclamation-triangle-fill trouble-icon"></i>
                                <div class="trouble-content">
                                    <div class="trouble-title">"Device disconnected"</div>
                                    <div class="trouble-desc">
                                        Device WhatsApp terputus. Silakan scan QR ulang di dashboard Wablas.
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- Debug Info -->
        <?php if ($debugInfo): ?>
            <div class="card-modern" style="margin-top: 20px;">
                <div class="card-header-modern info">
                    <div class="title-left">
                        <i class="bi bi-bug-fill"></i>
                        <span>Debug Information (Raw Response)</span>
                    </div>
                </div>
                <div class="card-body-modern">
                    <div class="debug-box">
                        <div class="debug-box-header">
                            <i class="bi bi-terminal-fill"></i>
                            <span><?= htmlspecialchars($debugInfo['action']) ?> · HTTP <?= $debugInfo['http_code'] ?></span>
                        </div>
                        <?= htmlspecialchars(json_encode($debugInfo, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES)) ?>
                    </div>
                </div>
            </div>
        <?php endif; ?>
    </div>
    <!-- End Content Wrapper -->
</div>

<script>
function toggleSidebar() {
    const sidebar = document.getElementById('sidebar');
    const overlay = document.getElementById('sidebarOverlay');
    if (sidebar && overlay) {
        sidebar.classList.toggle('active');
        overlay.classList.toggle('active');
        document.body.style.overflow = sidebar.classList.contains('active') ? 'hidden' : '';
    }
}
</script>

<?php require __DIR__ . '/../includes/footer.php'; ?>