<?php
require_once __DIR__ . '/../includes/auth.php';
require_once __DIR__ . '/../includes/functions.php';

requireRole('branch_admin');
$pageTitle = 'Wablas Gateway - Cabang';

$db = db();

// ============================================================================
// 1. DETEKSI CABANG USER
// ============================================================================
$currentUserId = currentUserId();
$userBranchId = null;
$userBranchName = 'Unknown';

try {
    $stmt = $db->prepare("SELECT u.branch_id, b.name as branch_name 
                          FROM users u LEFT JOIN branches b ON u.branch_id = b.id 
                          WHERE u.id = ?");
    $stmt->execute([$currentUserId]);
    $row = $stmt->fetch();
    $userBranchId = $row ? (int)$row['branch_id'] : null;
    $userBranchName = $row['branch_name'] ?? 'Unknown';
} catch (\Throwable $e) {}

if (!$userBranchId) {
    redirect('/branch/dashboard.php', '❌ Akun Anda tidak terdaftar di cabang manapun.', 'error');
}

// ============================================================================
// 2. FUNGSI LOAD CONFIG (Dipisah agar bisa dipanggil ulang)
// ============================================================================
function loadWablasConfig($db, $branchId) {
    $config = [];
    $hasBranchColumn = false;
    
    try {
        $checkCol = $db->query("SHOW COLUMNS FROM wa_config LIKE 'branch_id'")->fetch();
        $hasBranchColumn = !empty($checkCol);
    } catch (\Throwable $e) {
        $hasBranchColumn = false;
    }
    
    try {
        if ($hasBranchColumn) {
            $stmt = $db->prepare("
                SELECT setting_key, setting_value 
                FROM wa_config 
                WHERE branch_id = ? AND setting_key IN ('wablas_token', 'wablas_base_url')
            ");
            $stmt->execute([$branchId]);
        } else {
            $stmt = $db->prepare("
                SELECT setting_key, setting_value 
                FROM wa_config 
                WHERE setting_key IN (?, ?)
            ");
            $stmt->execute([
                'wablas_token_branch_' . $branchId,
                'wablas_base_url_branch_' . $branchId
            ]);
        }
        
        while ($row = $stmt->fetch()) {
            $key = $row['setting_key'];
            if (!$hasBranchColumn) {
                $key = str_replace('_branch_' . $branchId, '', $key);
            }
            $config[$key] = $row['setting_value'];
        }
    } catch (\Throwable $e) {}
    
    return [
        'config' => $config,
        'hasBranchColumn' => $hasBranchColumn
    ];
}

// ============================================================================
// 3. FUNGSI SIMPAN CONFIG (DIPERBAIKI: DELETE + INSERT agar lebih reliable)
// ============================================================================
function saveWablasConfig($db, $branchId, $key, $value, $hasBranchColumn) {
    if ($hasBranchColumn) {
        // Hapus dulu yang lama (jika ada), lalu insert baru
        $stmt = $db->prepare("DELETE FROM wa_config WHERE branch_id = ? AND setting_key = ?");
        $stmt->execute([$branchId, $key]);
        
        $stmt = $db->prepare("INSERT INTO wa_config (branch_id, setting_key, setting_value) VALUES (?, ?, ?)");
        $stmt->execute([$branchId, $key, $value]);
    } else {
        $fullKey = $key . '_branch_' . $branchId;
        
        // Hapus dulu yang lama (jika ada), lalu insert baru
        $stmt = $db->prepare("DELETE FROM wa_config WHERE setting_key = ?");
        $stmt->execute([$fullKey]);
        
        $stmt = $db->prepare("INSERT INTO wa_config (setting_key, setting_value) VALUES (?, ?)");
        $stmt->execute([$fullKey, $value]);
    }
}

// ============================================================================
// 4. LOAD CONFIG AWAL
// ============================================================================
$result = loadWablasConfig($db, $userBranchId);
$config = $result['config'];
$hasBranchColumn = $result['hasBranchColumn'];

$baseUrl = $config['wablas_base_url'] ?? '';
$token = $config['wablas_token'] ?? '';
$isConfigured = !empty($baseUrl) && !empty($token);

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

// ============================================================================
// 5. FUNGSI HELPER CURL
// ============================================================================
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
    ];
}

// ============================================================================
// 6. HANDLE SAVE SETTINGS (DIPERBAIKI: Reload config setelah save)
// ============================================================================
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'] ?? '');
        
        // Bersihkan URL dari endpoint yang tidak perlu
        $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 {
            try {
                // Simpan ke database
                saveWablasConfig($db, $userBranchId, 'wablas_base_url', $newBaseUrl, $hasBranchColumn);
                saveWablasConfig($db, $userBranchId, 'wablas_token', $newToken, $hasBranchColumn);
                
                // ✅ DIPERBAIKI: Reload config dari database untuk memastikan tersimpan
                $result = loadWablasConfig($db, $userBranchId);
                $config = $result['config'];
                $baseUrl = $config['wablas_base_url'] ?? '';
                $token = $config['wablas_token'] ?? '';
                $isConfigured = !empty($baseUrl) && !empty($token);
                
                if ($isConfigured) {
                    $success = '✅ Konfigurasi Wablas untuk cabang <strong>' . htmlspecialchars($userBranchName) . '</strong> berhasil disimpan';
                    logActivity($currentUserId, 'save_wablas_config', 
                        "Update konfigurasi Wablas cabang {$userBranchName}");
                } else {
                    $error = '❌ Konfigurasi tersimpan tapi gagal dimuat ulang. Cek struktur tabel wa_config.';
                }
            } catch (\Throwable $e) {
                $error = '❌ Gagal menyimpan: ' . $e->getMessage();
            }
        }
    }
}

// ============================================================================
// 7. HANDLE CHECK STATUS
// ============================================================================
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'check_status') {
    if (verifyCsrf($_POST['csrf_token'] ?? '')) {
        // ✅ DIPERBAIKI: Reload config dulu untuk memastikan token terbaru
        $result = loadWablasConfig($db, $userBranchId);
        $config = $result['config'];
        $baseUrl = $config['wablas_base_url'] ?? '';
        $token = $config['wablas_token'] ?? '';
        $isConfigured = !empty($baseUrl) && !empty($token);
        
        if (!$isConfigured) {
            $error = 'Token belum diisi. Silakan simpan konfigurasi terlebih dahulu.';
        } else {
            $res = wablasRequest('/device/info', []);
            $debugInfo = [
                'action' => 'Check Status Token',
                'branch' => $userBranchName,
                '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';
                $quota = $res['data']['data']['quota'] ?? 'N/A';
                $expiredDate = $res['data']['data']['expired_date'] ?? 'N/A';
                
                $success = "✅ Token Valid! Device: <strong>{$deviceName}</strong> | Status: <strong>" . strtoupper($deviceStatus) . "</strong>";
                $success .= "<br><small>Quota: {$quota} | Expired: {$expiredDate}</small>";
                
                if ($deviceStatus === 'disconnected') {
                    $success .= " <span class='badge bg-danger'>Peringatan: Device terputus. Scan QR di dashboard Wablas</span>";
                }
            } else {
                $errorMsg = $res['data']['message'] ?? $res['data']['error'] ?? 'Unknown error';
                $error = '❌ Status: ' . $errorMsg;
            }
        }
    }
}

// ============================================================================
// 8. HANDLE SEND TEST MESSAGE
// ============================================================================
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'send_test') {
    if (verifyCsrf($_POST['csrf_token'] ?? '')) {
        // ✅ DIPERBAIKI: Reload config dulu
        $result = loadWablasConfig($db, $userBranchId);
        $config = $result['config'];
        $baseUrl = $config['wablas_base_url'] ?? '';
        $token = $config['wablas_token'] ?? '';
        $isConfigured = !empty($baseUrl) && !empty($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 (!$isConfigured) {
            $error = 'Token belum dikonfigurasi';
        } else {
            $params = ['phone' => $phone, 'message' => $message];
            $res = wablasRequest('/send-message', $params);
            
            $debugInfo = [
                'action' => 'Send Test Message',
                'branch' => $userBranchName,
                '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;
                logActivity($currentUserId, 'test_wablas', 
                    "Test kirim WA dari cabang {$userBranchName} ke {$phone}");
            } else {
                $errorMsg = $res['data']['message'] ?? $res['data']['error'] ?? 'Unknown error';
                $error = '❌ Gagal kirim: ' . $errorMsg;
            }
        }
    }
}

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

<style>
/* === NAVBAR MODERN === */
.navbar-modern { background: linear-gradient(135deg, #25D366 0%, #128C7E 100%); padding: 12px 20px; display: flex; align-items: center; justify-content: space-between; box-shadow: 0 4px 15px rgba(0,0,0,0.15); position: sticky; top: 0; z-index: 1000; }
.navbar-left { display: flex; align-items: center; gap: 14px; flex: 1; min-width: 0; }
.burger-btn { background: rgba(255,255,255,0.2); border: 2px solid rgba(255,255,255,0.3); color: white; width: 42px; height: 42px; border-radius: 12px; cursor: pointer; display: flex; align-items: center; justify-content: center; font-size: 1.3rem; transition: all 0.3s ease; flex-shrink: 0; }
.burger-btn:hover, .burger-btn:active { background: rgba(255,255,255,0.35); transform: scale(1.05); }
.navbar-info { min-width: 0; flex: 1; }
.navbar-greeting { color: rgba(255,255,255,0.85); font-size: 0.75rem; margin: 0; }
.navbar-title { color: white; font-size: 1.15rem; font-weight: 700; margin: 2px 0 0; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
.navbar-right { display: flex; align-items: center; gap: 10px; flex-shrink: 0; }
.navbar-badge { background: rgba(255,255,255,0.2); color: white; padding: 6px 12px; border-radius: 20px; font-size: 0.8rem; font-weight: 500; display: inline-flex; align-items: center; gap: 6px; white-space: nowrap; }
.main-content { padding: 16px; max-width: 900px; margin: 0 auto; display: flex; flex-direction: column; gap: 20px; }
.page-header { margin-bottom: 20px; display: flex; justify-content: space-between; align-items: center; flex-wrap: wrap; gap: 15px; }
.page-title { font-size: 1.6rem; font-weight: 700; color: #003D7A; margin: 0; display: flex; align-items: center; gap: 10px; flex-wrap: wrap; }
.page-title i { font-size: 1.8rem; color: #25D366; }
.branch-badge { background: linear-gradient(135deg, #e3f2fd 0%, #bbdefb 100%); color: #003D7A; padding: 4px 12px; border-radius: 20px; font-size: 0.8rem; font-weight: 600; display: inline-flex; align-items: center; gap: 5px; }
.alert-modern { padding: 14px 18px; border-radius: 12px; margin-bottom: 16px; display: flex; align-items: flex-start; gap: 12px; font-size: 0.92rem; 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.warning { background: #fff8e1; border-color: #ffe082; color: #f57c00; }
.alert-modern.info { background: #e3f2fd; border-color: #90caf9; color: #1565c0; }
.alert-modern i { font-size: 1.2rem; margin-top: 2px; flex-shrink: 0; }
.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: 16px 20px; font-size: 1rem; font-weight: 600; display: flex; align-items: center; justify-content: space-between; gap: 10px; flex-wrap: wrap; }
.card-header-modern.whatsapp { background: linear-gradient(135deg, #25D366 0%, #128C7E 100%); }
.card-header-modern.success { background: linear-gradient(135deg, #00C853 0%, #69F0AE 100%); }
.card-header-modern.danger { background: linear-gradient(135deg, #DC3545 0%, #FF6B7A 100%); }
.card-header-modern.warning { background: linear-gradient(135deg, #FF9900 0%, #FFB84D 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: 20px; }
.status-card { border-radius: 14px; padding: 18px; margin-bottom: 20px; display: flex; align-items: center; gap: 14px; }
.status-card.configured { background: linear-gradient(135deg, #e8f5e9 0%, #c8e6c9 100%); border: 2px solid #a5d6a7; }
.status-card.not-configured { background: linear-gradient(135deg, #fff8e1 0%, #ffecb3 100%); border: 2px solid #ffe082; }
.status-icon-large { width: 50px; height: 50px; border-radius: 14px; display: flex; align-items: center; justify-content: center; font-size: 1.5rem; color: white; flex-shrink: 0; }
.status-card.configured .status-icon-large { background: linear-gradient(135deg, #00C853 0%, #69F0AE 100%); }
.status-card.not-configured .status-icon-large { background: linear-gradient(135deg, #FF9900 0%, #FFB84D 100%); }
.status-content { flex: 1; min-width: 0; }
.status-title { font-weight: 700; font-size: 0.95rem; margin-bottom: 2px; }
.status-card.configured .status-title { color: #1b5e20; }
.status-card.not-configured .status-title { color: #f57c00; }
.status-subtitle { font-size: 0.78rem; color: #666; margin-bottom: 6px; }
.status-details { display: flex; gap: 12px; flex-wrap: wrap; font-size: 0.75rem; }
.status-details code { background: rgba(255,255,255,0.7); padding: 2px 6px; border-radius: 4px; font-size: 0.72rem; color: #333; }
.form-section { margin-bottom: 16px; padding-bottom: 16px; border-bottom: 1px dashed #e8f4f8; }
.form-section:last-child { border-bottom: none; margin-bottom: 0; padding-bottom: 0; }
.section-title { display: flex; align-items: center; gap: 8px; font-size: 0.92rem; font-weight: 700; color: #003D7A; margin: 0 0 12px; }
.section-title i { color: #25D366; font-size: 1rem; }
.form-grid { display: grid; grid-template-columns: 1fr; gap: 12px; }
.form-group-modern { margin-bottom: 0; }
.form-label-modern { display: flex; align-items: center; gap: 6px; font-weight: 600; color: #003D7A; margin-bottom: 6px; font-size: 0.85rem; }
.form-label-modern i { color: #25D366; }
.form-label-modern .required { color: #DC3545; margin-left: 2px; }
.form-control-modern { width: 100%; padding: 11px 14px; border: 2px solid #e8f4f8; border-radius: 10px; font-size: 0.9rem; transition: all 0.3s ease; background: #f8fafc; font-family: inherit; box-sizing: border-box; }
.form-control-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: 80px; }
.form-hint { display: flex; align-items: center; gap: 4px; margin-top: 6px; font-size: 0.75rem; color: #999; }
.btn-modern { padding: 11px 20px; border: none; border-radius: 10px; font-size: 0.9rem; 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:not(:disabled) { transform: translateY(-2px); box-shadow: 0 6px 20px rgba(37, 211, 102, 0.4); }
.btn-modern.whatsapp:disabled { opacity: 0.5; cursor: not-allowed; }
.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:not(:disabled) { transform: translateY(-2px); box-shadow: 0 6px 16px rgba(0, 184, 212, 0.4); }
.btn-modern.info:disabled { opacity: 0.5; cursor: not-allowed; }
.btn-modern.outline { background: white; color: #666; border: 2px solid #e8f4f8; }
.btn-modern.outline:hover { background: #f8fafc; border-color: #25D366; color: #25D366; }
.btn-modern.full-width { width: 100%; }
.btn-group-modern { display: flex; gap: 10px; margin-top: 16px; flex-wrap: wrap; }
.trouble-list { display: grid; gap: 8px; }
.trouble-item { display: flex; align-items: flex-start; gap: 10px; padding: 10px 12px; background: #f8fafc; border-radius: 10px; border-left: 3px solid #DC3545; font-size: 0.85rem; }
.trouble-item i { color: #DC3545; margin-top: 2px; flex-shrink: 0; }
.trouble-item code { background: #fff3cd; padding: 1px 6px; border-radius: 4px; font-size: 0.78rem; color: #856404; font-weight: 700; }
.quick-actions-grid { display: grid; grid-template-columns: 1fr 1fr; gap: 10px; }
.quick-action-card { background: white; border: 2px solid #f0f0f0; border-radius: 12px; padding: 14px; text-align: center; text-decoration: none; transition: all 0.3s ease; color: inherit; display: block; }
.quick-action-card:hover { border-color: #25D366; transform: translateY(-2px); box-shadow: 0 6px 16px rgba(37, 211, 102, 0.12); color: inherit; }
.quick-action-icon { width: 42px; height: 42px; border-radius: 12px; display: flex; align-items: center; justify-content: center; font-size: 1.2rem; color: white; margin: 0 auto 8px; }
.quick-action-icon.whatsapp { background: linear-gradient(135deg, #25D366 0%, #128C7E 100%); }
.quick-action-icon.primary { background: linear-gradient(135deg, #0066CC 0%, #00B4FF 100%); }
.quick-action-title { font-weight: 700; color: #003D7A; font-size: 0.82rem; }
.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; }
@media (max-width: 768px) {
    .navbar-modern { padding: 10px 15px; }
    .navbar-title { font-size: 1rem; }
    .navbar-greeting, .navbar-badge { display: none; }
    .main-content { padding: 15px; }
    .page-header { flex-direction: column; align-items: stretch; }
    .page-title { font-size: 1.3rem; }
    .page-title i { font-size: 1.5rem; }
    .card-header-modern { padding: 14px 16px; font-size: 0.95rem; }
    .card-body-modern { padding: 16px; }
    .status-card { flex-direction: column; text-align: center; padding: 16px; }
    .status-details { justify-content: center; }
    .btn-group-modern { flex-direction: column; }
    .btn-modern { width: 100%; padding: 12px; }
    .quick-actions-grid { grid-template-columns: 1fr 1fr; }
}
@media (max-width: 480px) {
    .navbar-modern { padding: 8px 12px; }
    .burger-btn { width: 38px; height: 38px; font-size: 1.15rem; }
    .navbar-title { font-size: 0.95rem; }
    .main-content { padding: 12px; }
    .page-title { font-size: 1.15rem; gap: 8px; }
    .card-header-modern { padding: 12px 14px; font-size: 0.9rem; }
    .card-body-modern { padding: 14px; }
    .form-control-modern { padding: 10px 12px; font-size: 0.88rem; }
    .status-icon-large { width: 44px; height: 44px; font-size: 1.3rem; }
    .status-title { font-size: 0.88rem; }
    .quick-action-card { padding: 12px; }
    .quick-action-icon { width: 38px; height: 38px; font-size: 1.1rem; }
    .quick-action-title { font-size: 0.78rem; }
    .trouble-item { font-size: 0.8rem; padding: 8px 10px; }
}
</style>

<div class="content-wrapper">
<div class="main-content">
<div class="navbar-modern">
    <div class="navbar-left">
        <button class="burger-btn" onclick="toggleSidebar()"><i class="bi bi-list"></i></button>
        <div class="navbar-info">
            <p class="navbar-greeting">Pengaturan WhatsApp Gateway</p>
            <h1 class="navbar-title">Wablas - <?= htmlspecialchars($userBranchName) ?></h1>
        </div>
    </div>
    <div class="navbar-right">
        <span class="navbar-badge"><i class="bi bi-whatsapp"></i> Wablas</span>
    </div>
</div>

<div class="page-header"></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; ?>

<!-- Debug Info -->
<?php if ($debugInfo): ?>
    <div class="card-modern">
        <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; ?>

<!-- Status Card -->
<div class="status-card <?= $isConfigured ? 'configured' : 'not-configured' ?>">
    <div class="status-icon-large">
        <i class="bi bi-<?= $isConfigured ? 'check-circle-fill' : 'exclamation-triangle-fill' ?>"></i>
    </div>
    <div class="status-content">
        <div class="status-title">
            <?= $isConfigured ? '✅ Terkonfigurasi' : '⚠️ Belum Dikonfigurasi' ?>
        </div>
        <div class="status-subtitle">
            <?= $isConfigured ? 'Cabang: ' . htmlspecialchars($userBranchName) : 'Silakan isi Base URL dan Token di bawah' ?>
        </div>
        <?php if ($isConfigured): ?>
            <div class="status-details">
                <span><strong>URL:</strong> <code><?= htmlspecialchars($baseUrl) ?></code></span>
                <span><strong>Token:</strong> <code><?= htmlspecialchars(substr($token, 0, 15)) ?>...</code></span>
            </div>
        <?php endif; ?>
    </div>
</div>

<!-- Main Content Grid -->
<div class="row g-3">
    <!-- Kolom Kiri: Konfigurasi + Test -->
    <div class="col-lg-6">
        <!-- Form Konfigurasi -->
        <div class="card-modern">
            <div class="card-header-modern whatsapp">
                <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-section">
                        <h3 class="section-title">
                            <i class="bi bi-link-45deg"></i>
                            <span>Koneksi API</span>
                        </h3>
                        
                        <div class="form-grid">
                            <div class="form-group-modern">
                                <label class="form-label-modern">
                                    <i class="bi bi-globe"></i>
                                    Base URL Wablas <span class="required">*</span>
                                </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">
                                    <i class="bi bi-info-circle"></i>
                                    URL API Wablas (tanpa slash di akhir)
                                </small>
                            </div>
                            
                            <div class="form-group-modern">
                                <label class="form-label-modern">
                                    <i class="bi bi-key-fill"></i>
                                    Token Wablas <span class="required">*</span>
                                </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">
                                    <i class="bi bi-info-circle"></i>
                                    Dapatkan di dashboard Wablas Anda
                                </small>
                            </div>
                        </div>
                    </div>
                    
                    <div class="btn-group-modern">
                        <button type="submit" class="btn-modern whatsapp">
                            <i class="bi bi-save-fill"></i>
                            <span>Simpan Konfigurasi</span>
                        </button>
                        <button type="submit" name="action" value="check_status" class="btn-modern info"
                                <?= !$isConfigured ? 'disabled' : '' ?>>
                            <i class="bi bi-arrow-repeat"></i>
                            <span>Cek Status</span>
                        </button>
                    </div>
                </form>
            </div>
        </div>

        <!-- Test Kirim Pesan -->
        <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">
                <?php if (!$isConfigured): ?>
                    <div class="alert-modern warning" style="margin: 0;">
                        <i class="bi bi-exclamation-triangle-fill"></i>
                        <div>
                            Silakan simpan konfigurasi terlebih dahulu sebelum melakukan test.
                        </div>
                    </div>
                <?php else: ?>
                    <div class="alert-modern info" style="margin-bottom: 12px;">
                        <i class="bi bi-info-circle-fill"></i>
                        <div>
                            Test menggunakan token dari cabang <strong><?= htmlspecialchars($userBranchName) ?></strong>.
                        </div>
                    </div>
                    
                    <form method="POST">
                        <?= csrfField() ?>
                        <input type="hidden" name="action" value="send_test">
                        
                        <div class="form-grid">
                            <div class="form-group-modern">
                                <label class="form-label-modern">
                                    <i class="bi bi-telephone-fill"></i>
                                    Nomor Telepon <span class="required">*</span>
                                </label>
                                <input type="text" name="test_phone" class="form-control-modern" 
                                       required placeholder="081234567890"
                                       value="<?= htmlspecialchars($_POST['test_phone'] ?? '') ?>">
                                <small class="form-hint">
                                    <i class="bi bi-info-circle"></i>
                                    Format: 08xxx atau 62xxx (otomatis dikonversi)
                                </small>
                            </div>
                            
                            <div class="form-group-modern">
                                <label class="form-label-modern">
                                    <i class="bi bi-chat-left-text-fill"></i>
                                    Pesan Test <span class="required">*</span>
                                </label>
                                <textarea name="test_message" class="form-control-modern" rows="4" required
                                          placeholder="Test pesan dari sistem...">Test pesan dari cabang <?= htmlspecialchars($userBranchName) ?>.

Jika Anda menerima pesan ini, berarti konfigurasi Wablas cabang sudah benar.</textarea>
                            </div>
                        </div>
                        
                        <button type="submit" class="btn-modern whatsapp full-width" style="margin-top: 12px;">
                            <i class="bi bi-send-fill"></i>
                            <span>Kirim Pesan Test</span>
                        </button>
                    </form>
                <?php endif; ?>
            </div>
        </div>
    </div>

    <!-- Kolom Kanan: Troubleshooting + Quick Actions -->
    <div class="col-lg-6">
        <!-- 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"></i>
                        <div>
                            <code>"token invalid"</code><br>
                            Token salah atau device belum login/scan QR.
                        </div>
                    </div>
                    <div class="trouble-item">
                        <i class="bi bi-exclamation-triangle-fill"></i>
                        <div>
                            <code>"token is null"</code><br>
                            Sistem menggunakan metode <strong>GET</strong>, bukan POST.
                        </div>
                    </div>
                    <div class="trouble-item">
                        <i class="bi bi-exclamation-triangle-fill"></i>
                        <div>
                            <code>"404 error"</code><br>
                            Base URL salah atau ada tambahan path.
                        </div>
                    </div>
                    <div class="trouble-item">
                        <i class="bi bi-exclamation-triangle-fill"></i>
                        <div>
                            <code>"device disconnected"</code><br>
                            WhatsApp di HP logout. Scan QR ulang di dashboard Wablas.
                        </div>
                    </div>
                </div>
                
                <div class="alert-modern info" style="margin-top: 12px; margin-bottom: 0;">
                    <i class="bi bi-person-fill"></i>
                    <div>
                        <strong>Hubungi Super Admin jika:</strong><br>
                        Belum punya akun/device Wablas atau perlu bantuan konfigurasi.
                    </div>
                </div>
            </div>
        </div>

        <!-- Quick Actions -->
        <div class="card-modern">
            <div class="card-header-modern whatsapp">
                <div class="title-left">
                    <i class="bi bi-lightning-fill"></i>
                    <span>Aksi Cepat</span>
                </div>
            </div>
            <div class="card-body-modern">
                <div class="quick-actions-grid">
                    <a href="/branch/broadcast.php" class="quick-action-card">
                        <div class="quick-action-icon whatsapp">
                            <i class="bi bi-megaphone-fill"></i>
                        </div>
                        <div class="quick-action-title">Kirim Broadcast</div>
                    </a>
                    <a href="/branch/customers.php" class="quick-action-card">
                        <div class="quick-action-icon primary">
                            <i class="bi bi-people-fill"></i>
                        </div>
                        <div class="quick-action-title">Daftar Pelanggan</div>
                    </a>
                </div>
            </div>
        </div>
    </div>
</div>
</div>
</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'; ?>