<?php
// Set agar cookie session tidak mati saat browser ditutup
ini_set('session.cookie_lifetime', 2592000);
ini_set('session.gc_maxlifetime', 2592000);
session_start();

// PENGUNCI HALAMAN
if (!isset($_SESSION['user_id'])) {
    if (isset($_COOKIE['omni_uid']) && isset($_COOKIE['omni_role'])) {
        $_SESSION['user_id']  = $_COOKIE['omni_uid'];
        $_SESSION['role']     = $_COOKIE['omni_role'];
        $_SESSION['name']     = $_COOKIE['omni_name'];
        $_SESSION['username'] = isset($_COOKIE['omni_uname']) ? $_COOKIE['omni_uname'] : '';
    }
}

if (!isset($_SESSION['user_id']) || $_SESSION['role'] !== 'admin') {
    header("Location: dashboard.php");
    exit;
}

$host = 'localhost';
$user = 'majapahi_omnich';
$pass = 'A1b2c3d4.,@';
$db   = 'majapahi_omnich';
$conn = new mysqli($host, $user, $pass, $db);

// ==============================================================
// 🛠️ FITUR BARU: AJAX HANDLER UNTUK TEST KONEKSI MPWA (MULTI-NUMBER)
// ==============================================================
if (isset($_POST['action']) && $_POST['action'] == 'test_api') {
    header('Content-Type: application/json');
    
    $raw_numbers = explode(',', $_POST['test_number']);
    $sender_device = isset($_POST['sender_device']) ? trim($_POST['sender_device']) : '';

    // Ambil Konfigurasi
    $mpwa_api_url_base = '';
    $api_key = '';
    $default_bot = '';
    
    $res = $conn->query("SELECT setting_key, setting_value FROM settings WHERE setting_key IN ('mpwa_api_url', 'mpwa_api_key', 'default_bot_number')");
    while ($r = $res->fetch_assoc()) {
        if ($r['setting_key'] == 'mpwa_api_url') $mpwa_api_url_base = rtrim($r['setting_value'], '/');
        if ($r['setting_key'] == 'mpwa_api_key') $api_key = trim($r['setting_value']);
        if ($r['setting_key'] == 'default_bot_number') $default_bot = trim($r['setting_value']);
    }

    if (empty($sender_device)) $sender_device = $default_bot;

    if (empty($mpwa_api_url_base) || empty($api_key) || empty($sender_device)) {
        echo json_encode(['status' => 'error', 'html' => '<div class="alert alert-danger p-2 fs-6 mb-0">Konfigurasi API URL, API Key, atau Bot Utama belum diisi.</div>']);
        exit;
    }

    $base_domain = str_replace(['/send-message', '/send-media'], '', $mpwa_api_url_base);
    $target_api_url = $base_domain . '/send-message'; 
    
    $html_result = "<div style='font-size:0.8rem; color:#475569; margin-bottom:10px;'><b>Endpoint:</b> " . htmlspecialchars($target_api_url) . "</div>";
    
    foreach ($raw_numbers as $num) {
        $test_number = preg_replace('/[^0-9]/', '', trim($num));
        if (empty($test_number)) continue;
        if (substr($test_number, 0, 1) === '0') $test_number = '62' . substr($test_number, 1);

        $data_api = [
            'api_key' => $api_key,
            'sender'  => $sender_device,
            'number'  => $test_number,
            'message' => "🔧 *TEST KONEKSI OMNIDESK*\n\nSistem MPWA berhasil terhubung!\n\nBot Pengirim: {$sender_device}\nTarget: {$test_number}\nWaktu: " . date('Y-m-d H:i:s')
        ];
        
        $payload = http_build_query($data_api);

        $ch = curl_init($target_api_url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $payload);
        curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/x-www-form-urlencoded']);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_TIMEOUT, 15);
        
        $response  = curl_exec($ch);
        $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        $curl_err  = curl_error($ch);
        curl_close($ch);

        $html_result .= "<div class='border rounded p-2 mb-2 shadow-sm' style='background: " . ($http_code == 200 || $http_code == 201 ? '#f0fdf4' : '#fef2f2') . "; border-color: " . ($http_code == 200 || $http_code == 201 ? '#bbf7d0' : '#fecaca') . " !important;'>";
        $html_result .= "<div style='font-size:0.8rem; color:#334155; margin-bottom:4px;'><b>Dari Bot:</b> {$sender_device} ➔ <b>Ke:</b> {$test_number}</div>";
        
        if ($http_code == 200 || $http_code == 201) {
            $html_result .= "<div class='text-success' style='font-size:0.85rem;'><b>✅ BERHASIL (Code: $http_code)</b></div>";
        } else {
            $html_result .= "<div class='text-danger' style='font-size:0.85rem;'><b>❌ GAGAL (Code: $http_code)</b></div>";
            $html_result .= "<div class='p-1 mt-1 rounded' style='background:#fee2e2; font-size:0.7rem; word-break:break-all; color:#b91c1c;'>";
            $html_result .= "<b>Respon MPWA:</b> " . htmlspecialchars($response);
            if($curl_err) $html_result .= "<br><b>CURL Error:</b> $curl_err";
            $html_result .= "</div>";
        }
        $html_result .= "</div>";
    }

    echo json_encode(['status' => 'success', 'html' => $html_result]);
    exit;
}
// ==============================================================

// AUTO-CREATE TABEL SETTINGS & FORWARD CONTACTS JIKA BELUM ADA
$conn->query("CREATE TABLE IF NOT EXISTS settings (
    id INT AUTO_INCREMENT PRIMARY KEY,
    setting_key VARCHAR(50) UNIQUE,
    setting_value VARCHAR(255)
)");
$conn->query("INSERT IGNORE INTO settings (setting_key, setting_value) VALUES ('default_bot_number', '')");

$cek_url = $conn->query("SELECT setting_value FROM settings WHERE setting_key = 'mpwa_api_url'");
if($cek_url->num_rows == 0) $conn->query("INSERT INTO settings (setting_key, setting_value) VALUES ('mpwa_api_url', '')");

$cek_key = $conn->query("SELECT setting_value FROM settings WHERE setting_key = 'mpwa_api_key'");
if($cek_key->num_rows == 0) $conn->query("INSERT INTO settings (setting_key, setting_value) VALUES ('mpwa_api_key', '')");

$conn->query("CREATE TABLE IF NOT EXISTS forward_contacts (
    id INT AUTO_INCREMENT PRIMARY KEY,
    name VARCHAR(100),
    phone_number VARCHAR(50)
)");

$message = "";

// LOGIKA SIMPAN PENGATURAN BOT
if (isset($_POST['save_settings'])) {
    $bot_number = $conn->real_escape_string($_POST['bot_number']);
    $conn->query("UPDATE settings SET setting_value = '$bot_number' WHERE setting_key = 'default_bot_number'");
    $message = "Pengaturan Nomor Bot berhasil diperbarui!";
}

// LOGIKA SIMPAN API MPWA
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['update_api'])) {
    $new_url = $conn->real_escape_string($_POST['mpwa_api_url']);
    $new_key = $conn->real_escape_string($_POST['mpwa_api_key']);
    
    $conn->query("UPDATE settings SET setting_value = '$new_url' WHERE setting_key = 'mpwa_api_url'");
    $conn->query("UPDATE settings SET setting_value = '$new_key' WHERE setting_key = 'mpwa_api_key'");
    
    $message = "Konfigurasi API MPWA Berhasil Diperbarui!";
}

// LOGIKA TAMBAH USER
if (isset($_POST['add_user'])) {
    $uname = $conn->real_escape_string($_POST['username']);
    $upass = md5($_POST['password']);
    $unama = $conn->real_escape_string($_POST['name']);
    $urole = $_POST['role'];
    $conn->query("INSERT INTO users (username, password, name, role) VALUES ('$uname', '$upass', '$unama', '$urole')");
    $message = "Pengguna baru berhasil ditambahkan!";
}

// LOGIKA EDIT USER
if (isset($_POST['edit_user'])) {
    $id    = (int)$_POST['user_id'];
    $unama = $conn->real_escape_string($_POST['name']);
    $uname = $conn->real_escape_string($_POST['username']);
    $urole = $_POST['role'];
    
    $conn->query("UPDATE users SET name='$unama', username='$uname', role='$urole' WHERE id=$id");
    if (!empty($_POST['password'])) {
        $upass = md5($_POST['password']);
        $conn->query("UPDATE users SET password='$upass' WHERE id=$id");
    }
    $message = "Data pengguna berhasil diperbarui!";
}

// LOGIKA HAPUS USER
if (isset($_GET['delete'])) {
    $id = (int)$_GET['delete'];
    if ($id != $_SESSION['user_id']) { 
        $conn->query("DELETE FROM users WHERE id = $id");
        $message = "Pengguna telah dihapus permanen.";
    } else {
        $message = "Anda tidak bisa menghapus akun sendiri!";
    }
}

// LOGIKA QUICK REPLIES
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['qr_action'])) {
    $action = $_POST['qr_action'];
    if ($action == 'add') {
        $title = $conn->real_escape_string($_POST['title']);
        $content = $conn->real_escape_string($_POST['content']);
        $conn->query("INSERT INTO quick_replies (title, content) VALUES ('$title', '$content')");
        $message = "Template balasan berhasil ditambahkan!";
    } elseif ($action == 'edit') {
        $id = (int)$_POST['qr_id'];
        $title = $conn->real_escape_string($_POST['title']);
        $content = $conn->real_escape_string($_POST['content']);
        $conn->query("UPDATE quick_replies SET title='$title', content='$content' WHERE id=$id");
        $message = "Template balasan berhasil diperbarui!";
    } elseif ($action == 'delete') {
        $id = (int)$_POST['qr_id'];
        $conn->query("DELETE FROM quick_replies WHERE id=$id");
        $message = "Template balasan berhasil dihapus!";
    }
}

// LOGIKA KONTAK FORWARD INTERNAL
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['fc_action'])) {
    $action = $_POST['fc_action'];
    if ($action == 'add') {
        $name = $conn->real_escape_string($_POST['name']);
        $phone = $conn->real_escape_string($_POST['phone_number']);
        $conn->query("INSERT INTO forward_contacts (name, phone_number) VALUES ('$name', '$phone')");
        $message = "Kontak tujuan forward berhasil ditambahkan!";
    } elseif ($action == 'edit') {
        $id = (int)$_POST['fc_id'];
        $name = $conn->real_escape_string($_POST['name']);
        $phone = $conn->real_escape_string($_POST['phone_number']);
        $conn->query("UPDATE forward_contacts SET name='$name', phone_number='$phone' WHERE id=$id");
        $message = "Kontak forward berhasil diperbarui!";
    } elseif ($action == 'delete') {
        $id = (int)$_POST['fc_id'];
        $conn->query("DELETE FROM forward_contacts WHERE id=$id");
        $message = "Kontak forward berhasil dihapus!";
    }
}

// LOGIKA BUKU TELEPON PELANGGAN (ADDRESS BOOK)
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['ab_action'])) {
    $action = $_POST['ab_action'];
    if ($action == 'add') {
        $name = $conn->real_escape_string($_POST['name']);
        $phone = $conn->real_escape_string($_POST['phone_number']);
        $phone = preg_replace('/[^0-9]/', '', $phone); 
        if (substr($phone, 0, 1) === '0') $phone = '62' . substr($phone, 1);
        
        $cek = $conn->query("SELECT id FROM contacts WHERE phone_number = '$phone'");
        if($cek->num_rows > 0) {
            $message = "⚠️ Gagal: Nomor WhatsApp sudah ada di database!";
        } else {
            $conn->query("INSERT INTO contacts (phone_number, name, status) VALUES ('$phone', '$name', 'saved')");
            $message = "Kontak pelanggan berhasil ditambahkan!";
        }
    } elseif ($action == 'edit') {
        $id = (int)$_POST['ab_id'];
        $name = $conn->real_escape_string($_POST['name']);
        $phone = $conn->real_escape_string($_POST['phone_number']);
        $phone = preg_replace('/[^0-9]/', '', $phone);
        if (substr($phone, 0, 1) === '0') $phone = '62' . substr($phone, 1);
        
        $conn->query("UPDATE contacts SET name='$name', phone_number='$phone' WHERE id=$id");
        $message = "Data kontak berhasil diperbarui!";
    } elseif ($action == 'delete') {
        $id = (int)$_POST['ab_id'];
        $conn->query("DELETE FROM contacts WHERE id=$id");
        $message = "Kontak berhasil dihapus permanen!";
    }
}

// AMBIL DATA PENGATURAN SAAT INI
$res_setting = $conn->query("SELECT setting_value FROM settings WHERE setting_key = 'default_bot_number'");
$default_bot = ($res_setting && $res_setting->num_rows > 0) ? $res_setting->fetch_assoc()['setting_value'] : '';

$current_api_url = $conn->query("SELECT setting_value FROM settings WHERE setting_key = 'mpwa_api_url'")->fetch_assoc()['setting_value'] ?? '';
$current_api_key = $conn->query("SELECT setting_value FROM settings WHERE setting_key = 'mpwa_api_key'")->fetch_assoc()['setting_value'] ?? '';

// DATA UNTUK TABEL STATISTIK
$filter = isset($_GET['filter']) ? $_GET['filter'] : 'today';

if ($filter == 'week') {
    $where_msg = "m.created_at >= DATE_SUB(NOW(), INTERVAL 7 DAY)";
} elseif ($filter == 'month') {
    $where_msg = "m.created_at >= DATE_SUB(NOW(), INTERVAL 30 DAY)";
} elseif ($filter == 'all') {
    $where_msg = "1=1"; 
} else {
    $where_msg = "DATE(m.created_at) = CURDATE()"; 
}

$performance = $conn->query("SELECT u.*, 
    (SELECT COUNT(*) FROM messages m WHERE m.user_id = u.id AND m.type = 'out' AND $where_msg) as chat_count,
    (SELECT COUNT(*) FROM contacts c WHERE c.closed_by = u.id AND c.status = 'closed') as close_count
    FROM users u ORDER BY role ASC, name ASC");

$replies = $conn->query("SELECT * FROM quick_replies ORDER BY id DESC");
$fwd_contacts = $conn->query("SELECT * FROM forward_contacts ORDER BY name ASC");
$address_book = $conn->query("SELECT * FROM contacts ORDER BY name ASC");

$report_query = $conn->query("SELECT c.*, 
          (SELECT COUNT(*) FROM messages m WHERE m.phone_number = c.phone_number) as total_chat,
          (SELECT MAX(created_at) FROM messages m WHERE m.phone_number = c.phone_number) as last_active
          FROM contacts c WHERE status IN ('open', 'closed') ORDER BY last_active DESC LIMIT 100"); 

// Ambil list Sender Devices untuk Test API
$available_devices = [];
$dev_query = $conn->query("SELECT DISTINCT device_number FROM messages WHERE device_number IS NOT NULL AND device_number != ''");
if ($dev_query) { while($row = $dev_query->fetch_assoc()) { $available_devices[] = $row['device_number']; } }
?>

<!DOCTYPE html>
<html lang="id">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
    <title>SaaS Dashboard - Omni WA</title>
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700;800&display=swap" rel="stylesheet">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    
    <style>
        :root {
            --primary: #008069;
            --primary-light: #00a884;
            --bg-color: #f0f4f8; 
            --text-main: #1e293b;
            --text-muted: #64748b;
            --card-bg: rgba(255, 255, 255, 0.9);
            --radius-lg: 24px;
            --radius-md: 16px;
        }

        body { 
            background-color: var(--bg-color); 
            background-image: radial-gradient(circle at 100% 0%, rgba(0,168,132,0.08) 0%, transparent 50%), radial-gradient(circle at 0% 100%, rgba(13,110,253,0.05) 0%, transparent 50%);
            background-attachment: fixed;
            color: var(--text-main); 
            font-family: 'Inter', sans-serif; 
            padding-bottom: 60px; 
            overflow-x: hidden;
        }

        .dashboard-header { 
            background: linear-gradient(135deg, #0f172a 0%, #1e293b 100%); 
            padding: 35px 45px; border-radius: var(--radius-lg); color: white; 
            margin-bottom: 35px; box-shadow: 0 20px 40px rgba(15, 23, 42, 0.15); 
            position: relative; overflow: hidden; display: flex;
            justify-content: space-between; align-items: center; flex-wrap: wrap; gap: 20px;
        }
        .dashboard-header::after { 
            content: ''; position: absolute; right: -50px; top: -100px; 
            width: 300px; height: 300px; background: radial-gradient(circle, rgba(0,168,132,0.2) 0%, transparent 70%); 
            border-radius: 50%; pointer-events: none;
        }
        .header-title { font-weight: 800; font-size: 2.2rem; letter-spacing: -0.5px; margin-bottom: 5px; }
        .header-subtitle { font-weight: 400; color: #94a3b8; font-size: 1rem; margin: 0; letter-spacing: 0.5px;}

        .glass-card { 
            background: var(--card-bg); backdrop-filter: blur(12px); -webkit-backdrop-filter: blur(12px);
            border-radius: var(--radius-lg); padding: 30px; border: 1px solid rgba(255, 255, 255, 0.6); 
            box-shadow: 0 10px 30px rgba(0,0,0,0.03), inset 0 1px 0 rgba(255,255,255,0.5); 
            transition: all 0.3s ease; margin-bottom: 30px;
        }
        .glass-card:hover { box-shadow: 0 20px 40px rgba(0,0,0,0.06); transform: translateY(-3px); }
        .section-title { font-weight: 800; font-size: 1.25rem; color: #0f172a; margin-bottom: 25px; display: flex; align-items: center; gap: 10px;}

        .table-wrapper { max-height: 450px; overflow-y: auto; padding-right: 5px; }
        .table-wrapper::-webkit-scrollbar { width: 6px; height: 6px; }
        .table-wrapper::-webkit-scrollbar-thumb { background: #cbd5e1; border-radius: 10px; }
        .table-wrapper::-webkit-scrollbar-track { background: transparent; }
        
        .table-modern { border-collapse: separate; border-spacing: 0 10px; width: 100%; white-space: nowrap; }
        .table-modern thead th { border: none; color: var(--text-muted); font-size: 0.75rem; text-transform: uppercase; letter-spacing: 1px; padding: 0 20px 10px 20px; font-weight: 700; background: transparent; }
        .table-modern tbody tr { background: #fff; transition: all 0.2s; box-shadow: 0 2px 8px rgba(0,0,0,0.02); }
        .table-modern tbody tr:hover { transform: scale(1.005) translateY(-2px); box-shadow: 0 10px 20px rgba(0,0,0,0.06); z-index: 10; position: relative; }
        .table-modern tbody td { border: none; padding: 15px 20px; vertical-align: middle; color: #334155; }
        .table-modern tbody td:first-child { border-top-left-radius: var(--radius-md); border-bottom-left-radius: var(--radius-md); border-left: 1px solid #f1f5f9; border-top: 1px solid #f1f5f9; border-bottom: 1px solid #f1f5f9; }
        .table-modern tbody td:last-child { border-top-right-radius: var(--radius-md); border-bottom-right-radius: var(--radius-md); border-right: 1px solid #f1f5f9; border-top: 1px solid #f1f5f9; border-bottom: 1px solid #f1f5f9; }
        .table-modern tbody td:not(:first-child):not(:last-child) { border-top: 1px solid #f1f5f9; border-bottom: 1px solid #f1f5f9; }

        .text-wrap-mobile { white-space: normal; word-break: break-word; min-width: 200px; }

        .form-control, .form-select { border-radius: 12px; padding: 12px 15px; border: 1px solid #e2e8f0; background-color: #f8fafc; font-size: 0.95rem; font-weight: 500; transition: all 0.2s; color: #334155; }
        .form-control:focus, .form-select:focus { background-color: #fff; border-color: var(--primary-light); box-shadow: 0 0 0 4px rgba(0,168,132,0.1); outline: none; }
        .form-label { font-weight: 600; color: #475569; font-size: 0.85rem; margin-bottom: 8px; }

        .btn { border-radius: 12px; font-weight: 600; letter-spacing: 0.3px; transition: all 0.25s ease; }
        .btn:active { transform: scale(0.95); }
        .btn-gradient { background: linear-gradient(135deg, var(--primary) 0%, var(--primary-light) 100%); border: none; color: white; padding: 10px 20px; box-shadow: 0 4px 12px rgba(0,128,105,0.25); }
        .btn-gradient:hover { box-shadow: 0 8px 20px rgba(0,128,105,0.35); color: white; transform: translateY(-2px); }
        
        .btn-light-custom { background: #ffffff; border: 1px solid #e2e8f0; color: #475569; padding: 10px 20px; }
        .btn-light-custom:hover { background: #f8fafc; color: #0f172a; border-color: #cbd5e1; transform: translateY(-2px); }

        .btn-google { background: #ffffff; border: 1px solid #e2e8f0; color: #4285f4; padding: 10px 20px; box-shadow: 0 2px 4px rgba(0,0,0,0.05); }
        .btn-google:hover { background: #f8fafc; border-color: #4285f4; box-shadow: 0 4px 12px rgba(66,133,244,0.15); transform: translateY(-2px); }

        .badge-soft-primary { background-color: rgba(13, 110, 253, 0.1); color: #0d6efd; padding: 6px 12px; border-radius: 8px; }
        .badge-soft-success { background-color: rgba(25, 135, 84, 0.1); color: #198754; padding: 6px 12px; border-radius: 8px; }
        .badge-soft-danger { background-color: rgba(220, 53, 69, 0.1); color: #dc3545; padding: 6px 12px; border-radius: 8px; }
        .badge-soft-warning { background-color: rgba(255, 193, 7, 0.15); color: #b48600; padding: 6px 12px; border-radius: 8px; }
        .badge-soft-dark { background-color: #f1f5f9; color: #475569; padding: 6px 16px; border-radius: 20px; border: 1px solid #e2e8f0;}
        .badge-soft-info { background-color: rgba(13, 202, 240, 0.1); color: #0dcaf0; padding: 6px 12px; border-radius: 8px; }
        
        .avatar-box { width: 40px; height: 40px; border-radius: 12px; background: #f1f5f9; color: var(--primary); display: flex; justify-content: center; align-items: center; font-weight: 800; font-size: 1.1rem; margin-right: 15px; flex-shrink: 0; }

        @media (max-width: 768px) {
            .dashboard-header { padding: 25px 20px; flex-direction: column; text-align: center; border-radius: 20px; gap: 15px;}
            .header-title { font-size: 1.8rem; }
            .header-subtitle { font-size: 0.9rem; }
            .dashboard-header .d-flex { justify-content: center; width: 100%; gap: 10px !important; }
            .dashboard-header .btn { flex: 1; padding: 10px; font-size: 0.85rem; justify-content: center; }
            .glass-card { padding: 20px; border-radius: 20px; margin-bottom: 20px; }
            .section-title { font-size: 1.1rem; flex-wrap: wrap; justify-content: space-between; }
            .section-title button { margin-top: 10px; width: 100%; }
            .table-modern { font-size: 0.85rem; }
            .table-modern tbody td { padding: 12px 10px; }
            .avatar-box { width: 35px; height: 35px; font-size: 1rem; margin-right: 10px; }
            .table-modern td.text-end { text-align: left !important; display: flex; gap: 5px; flex-direction: column; }
            .table-modern td.text-end .btn { width: 100%; justify-content: center; }
        }
    </style>
</head>
<body>

<div class="container py-4">
    
    <div class="dashboard-header">
        <div style="z-index: 1; position: relative;">
            <h1 class="header-title">Command Center</h1>
            <p class="header-subtitle">OmniChannel System Operations & Analytics</p>
        </div>
        <div style="z-index: 1; position: relative;" class="d-flex gap-3 flex-wrap">
            <a href="sync_google.php" class="btn btn-google d-flex align-items-center gap-2">
                <svg viewBox="0 0 24 24" width="18" height="18" fill="currentColor"><path d="M12.545,10.239v3.821h5.445c-0.712,2.315-2.647,3.972-5.445,3.972c-3.332,0-6.033-2.701-6.033-6.032s2.701-6.032,6.033-6.032c1.498,0,2.866,0.549,3.921,1.453l2.814-2.814C17.503,2.988,15.139,2,12.545,2C7.021,2,2.543,6.477,2.543,12s4.478,10,10.002,10c8.396,0,10.249-7.85,9.426-11.748L12.545,10.239z"/></svg> 
                <span class="d-none d-sm-inline">Sync</span> Contacts
            </a>
            
            <a href="backup_db.php" class="btn btn-light-custom shadow-sm d-flex align-items-center gap-2">
                <span>💾</span> <span class="d-none d-sm-inline">Backup</span>
            </a>
            <a href="dashboard.php" class="btn btn-gradient d-flex align-items-center gap-2">
                <span>💬</span> Chat
            </a>
        </div>
    </div>

    <?php if($message): ?>
        <div class="alert alert-success alert-dismissible fade show border-0 d-flex align-items-center mb-4 shadow-sm" style="border-radius: var(--radius-md); background: #d1fae5; color: #166534; padding: 20px;" role="alert">
            <span class="fs-4 me-3">✅</span>
            <div><strong class="fw-bold">Berhasil!</strong> <?= $message ?></div>
            <button type="button" class="btn-close mt-1" data-bs-dismiss="alert"></button>
        </div>
    <?php endif; ?>

    <div class="row">
        <div class="col-lg-8">
            
            <div class="glass-card">
                <div class="d-flex justify-content-between align-items-center mb-2 flex-wrap gap-2">
                    <h5 class="section-title mb-0"><span>👥</span> Kinerja & Akses Tim</h5>
                    
                    <select class="form-select bg-white shadow-sm" style="width: auto; border-radius: 8px; font-weight: 600; font-size: 0.85rem; padding: 6px 30px 6px 12px; cursor: pointer;" onchange="window.location.href='?filter='+this.value">
                        <option value="today" <?= $filter=='today'?'selected':'' ?>>📅 Hari Ini</option>
                        <option value="week" <?= $filter=='week'?'selected':'' ?>>📅 7 Hari Terakhir</option>
                        <option value="month" <?= $filter=='month'?'selected':'' ?>>📅 30 Hari Terakhir</option>
                        <option value="all" <?= $filter=='all'?'selected':'' ?>>📊 Semua Waktu</option>
                    </select>
                </div>
                <div class="table-responsive table-wrapper mt-3">
                    <table class="table-modern">
                        <thead>
                            <tr>
                                <th>Informasi Akun</th>
                                <th class="text-center">Pesan Keluar</th>
                                <th class="text-center">Tiket Selesai</th>
                                <th class="text-end">Tindakan</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php while($row = $performance->fetch_assoc()): ?>
                            <tr>
                                <td>
                                    <div class="d-flex align-items-center">
                                        <div class="avatar-box"><?= strtoupper(substr($row['name'],0,1)) ?></div>
                                        <div>
                                            <strong class="text-wrap-mobile d-inline-block" style="font-size: 1.05rem;"><?= htmlspecialchars($row['name']) ?></strong> 
                                            <span class="badge-soft-<?= $row['role']=='admin'?'danger':'primary' ?> ms-sm-2 mt-1 mt-sm-0 d-inline-block" style="font-size:0.65rem"><?= strtoupper($row['role']) ?></span><br>
                                            <small class="text-muted fw-medium mt-1 d-inline-block">@<?= htmlspecialchars($row['username']) ?></small>
                                        </div>
                                    </div>
                                </td>
                                <td class="text-center"><span class="badge-soft-primary px-3 fs-6"><?= $row['chat_count'] ?></span></td>
                                <td class="text-center"><span class="badge-soft-success px-3 fs-6"><?= $row['close_count'] ?></span></td>
                                <td class="text-end">
                                    <button class="btn btn-sm btn-light fw-bold px-3 py-2 text-warning border shadow-sm rounded-3 me-sm-1" onclick='openEditModal(<?= json_encode($row) ?>)'>Edit</button>
                                    <?php if($row['id'] != $_SESSION['user_id']): ?>
                                        <a href="?delete=<?= $row['id'] ?>" class="btn btn-sm btn-light fw-bold px-3 py-2 text-danger border shadow-sm rounded-3" onclick="return confirm('Hapus user ini secara permanen?')">Hapus</a>
                                    <?php endif; ?>
                                </td>
                            </tr>
                            <?php endwhile; ?>
                        </tbody>
                    </table>
                </div>
            </div>

            <div class="glass-card">
                <div class="d-flex justify-content-between align-items-center flex-wrap mb-2">
                    <h5 class="section-title mb-0"><span>📞</span> Kontak Forward Internal</h5>
                    <button class="btn btn-dark fw-bold btn-sm px-3 shadow-sm" data-bs-toggle="modal" data-bs-target="#modalAddFC" style="border-radius: 8px;">+ Tambah Kontak</button>
                </div>
                <div class="table-responsive table-wrapper mt-3">
                    <table class="table-modern">
                        <thead>
                            <tr>
                                <th width="35%">Nama Divisi / Orang</th>
                                <th width="40%">Nomor WhatsApp / Grup</th>
                                <th width="25%" class="text-end">Tindakan</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php if($fwd_contacts && $fwd_contacts->num_rows > 0): ?>
                                <?php mysqli_data_seek($fwd_contacts, 0); ?>
                                <?php while($fc = $fwd_contacts->fetch_assoc()): ?>
                                    <tr>
                                        <td><span class="badge-soft-info fs-6 border-0 text-dark fw-bold"><?= htmlspecialchars($fc['name']) ?></span></td>
                                        <td><div style="color: #475569; font-weight: 600;"><?= htmlspecialchars($fc['phone_number']) ?></div></td>
                                        <td class="text-end">
                                            <button class="btn btn-sm btn-light fw-bold px-2 py-1 text-warning border shadow-sm rounded-3 me-sm-1" onclick='openEditFCModal(<?= json_encode($fc) ?>)'>Edit</button>
                                            <form action="" method="POST" class="d-inline" onsubmit="return confirm('Hapus kontak internal ini?');">
                                                <input type="hidden" name="fc_action" value="delete">
                                                <input type="hidden" name="fc_id" value="<?= $fc['id'] ?>">
                                                <button type="submit" class="btn btn-sm btn-light fw-bold px-2 py-1 text-danger border shadow-sm rounded-3">Hapus</button>
                                            </form>
                                        </td>
                                    </tr>
                                <?php endwhile; ?>
                            <?php else: ?>
                                <tr><td colspan="3"><div class="text-center py-4"><h6 class="fw-bold text-muted">Belum ada kontak internal.</h6><p class="text-muted small">Tambahkan kontak untuk mempercepat CS melakukan *forward* pesan.</p></div></td></tr>
                            <?php endif; ?>
                        </tbody>
                    </table>
                </div>
            </div>

            <div class="glass-card">
                <div class="d-flex justify-content-between align-items-center flex-wrap mb-2">
                    <h5 class="section-title mb-0"><span>⚡</span> Template Balasan Cepat</h5>
                    <button class="btn btn-gradient btn-sm px-4 shadow-sm" data-bs-toggle="modal" data-bs-target="#modalAddQR">+ Buat Baru</button>
                </div>
                <div class="table-responsive table-wrapper mt-3">
                    <table class="table-modern">
                        <thead>
                            <tr>
                                <th width="25%">Label Tombol</th>
                                <th width="55%">Isi Otomatis</th>
                                <th width="20%" class="text-end">Tindakan</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php if($replies && $replies->num_rows > 0): ?>
                                <?php while($row = $replies->fetch_assoc()): ?>
                                    <tr>
                                        <td><span class="badge-soft-dark"><?= htmlspecialchars($row['title']) ?></span></td>
                                        <td><div class="text-wrap-mobile" style="color: #475569; line-height: 1.6; font-size: 0.85rem; font-weight: 500; min-width: 250px;"><?= nl2br(htmlspecialchars($row['content'])) ?></div></td>
                                        <td class="text-end">
                                            <button class="btn btn-sm btn-light fw-bold px-3 py-2 text-warning border shadow-sm rounded-3 mb-1" onclick='openEditQRModal(<?= json_encode($row) ?>)'>Edit</button>
                                            <form action="" method="POST" class="d-inline" onsubmit="return confirm('Yakin ingin menghapus template ini?');">
                                                <input type="hidden" name="qr_action" value="delete">
                                                <input type="hidden" name="qr_id" value="<?= $row['id'] ?>">
                                                <button type="submit" class="btn btn-sm btn-light fw-bold px-3 py-2 text-danger border shadow-sm rounded-3 mb-1">Hapus</button>
                                            </form>
                                        </td>
                                    </tr>
                                <?php endwhile; ?>
                            <?php else: ?>
                                <tr>
                                    <td colspan="3">
                                        <div class="text-center py-5">
                                            <div class="fs-1 mb-3">👻</div>
                                            <h6 class="fw-bold text-muted">Belum ada template balasan.</h6>
                                            <p class="text-muted small">Buat template untuk mempercepat kerja tim CS Anda.</p>
                                        </div>
                                    </td>
                                </tr>
                            <?php endif; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>

        <div class="col-lg-4">
            
            <div class="glass-card" style="border-top: 4px solid var(--primary);">
                <h5 class="section-title text-success mb-4"><span>⚙️</span> Konfigurasi Sistem</h5>
                
                <!-- PENGATURAN BOT -->
                <form method="POST" class="mb-4 pb-4 border-bottom">
                    <div class="mb-3">
                        <label class="form-label text-muted">Nomor Bot Utama (Grup WA)</label>
                        <div class="input-group shadow-sm" style="border-radius: 12px; overflow: hidden;">
                            <span class="input-group-text bg-white border-end-0 fs-5 text-muted px-3">📱</span>
                            <input type="text" name="bot_number" class="form-control border-start-0 ps-0" placeholder="62812xxx" value="<?= htmlspecialchars($default_bot) ?>" required>
                        </div>
                        <small class="text-muted mt-2 d-block" style="font-size: 0.75rem; line-height: 1.5;">Hanya nomor ini yang diizinkan sistem untuk mengirim pesan Broadcast ke Grup WA.</small>
                    </div>
                    <button type="submit" name="save_settings" class="btn btn-gradient w-100 shadow-sm">Simpan Bot Utama</button>
                </form>

                <!-- PENGATURAN API MPWA BARU -->
                <form method="POST" class="mb-4 pb-4 border-bottom">
                    <div class="mb-3">
                        <label class="form-label text-muted">URL Endpoint MPWA</label>
                        <input type="url" name="mpwa_api_url" class="form-control" value="<?= htmlspecialchars($current_api_url) ?>" placeholder="https://wa.domainanda.com/send-message" required>
                    </div>
                    <div class="mb-3">
                        <label class="form-label text-muted">API Key MPWA</label>
                        <input type="text" name="mpwa_api_key" class="form-control" value="<?= htmlspecialchars($current_api_key) ?>" placeholder="API Key Anda" required>
                        <small class="text-muted mt-2 d-block" style="font-size: 0.75rem; line-height: 1.5;">Akan digunakan otomatis oleh semua file pengirim pesan.</small>
                    </div>
                    <button type="submit" name="update_api" class="btn btn-dark w-100 shadow-sm mb-2">Simpan API MPWA</button>
                    
                    <!-- TOMBOL TEST API -->
                    <button type="button" class="btn btn-outline-primary w-100 fw-bold mt-2" data-bs-toggle="modal" data-bs-target="#modalTestAPI" style="border-radius: 12px;">
                        🧪 Test Koneksi Server
                    </button>
                </form>

            </div>

            <div class="glass-card position-sticky" style="top: 20px; border-top: 4px solid #0d6efd;">
                <h5 class="section-title mb-4" style="color: #0f172a;"><span>👤</span> Buat Akses Baru</h5>
                <form method="POST">
                    <div class="mb-3">
                        <label class="form-label">Nama Lengkap</label>
                        <input type="text" name="name" class="form-control" placeholder="Cth: Budi Santoso" required>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Username Login</label>
                        <input type="text" name="username" class="form-control" placeholder="Cth: budi_cs" required>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Password</label>
                        <input type="password" name="password" class="form-control" placeholder="••••••••" required>
                    </div>
                    <div class="mb-4">
                        <label class="form-label">Level Akses (Role)</label>
                        <select name="role" class="form-select bg-white">
                            <option value="cs">Customer Service (CS)</option>
                            <option value="admin">Administrator (Admin)</option>
                        </select>
                    </div>
                    <button type="submit" name="add_user" class="btn w-100 fw-bold py-3 shadow-sm text-white" style="background: #0f172a; border-radius: 12px;">Daftarkan Akun</button>
                </form>
            </div>

        </div>
    </div>

    <div class="row mt-2">
        <div class="col-12">
            <div class="glass-card mb-5" style="border-top: 4px solid #8b5cf6;">
                <div class="d-flex justify-content-between align-items-center mb-4 flex-wrap gap-3">
                    <div>
                        <h5 class="section-title mb-1"><span>📇</span> Buku Telepon Pelanggan</h5>
                        <p class="text-muted m-0" style="font-size: 0.9rem;">Daftar seluruh kontak hasil sinkronisasi Google dan interaksi sistem.</p>
                    </div>
                    <div class="d-flex gap-2">
                        <input type="text" id="searchAddressBook" class="form-control shadow-sm" placeholder="Cari nama atau nomor..." style="max-width: 250px;" onkeyup="filterAddressBook()">
                        <button class="btn btn-dark fw-bold px-3 shadow-sm" data-bs-toggle="modal" data-bs-target="#modalAddAB" style="border-radius: 12px;">+ Tambah</button>
                    </div>
                </div>
                
                <div class="table-responsive table-wrapper">
                    <table class="table-modern" id="tableAddressBook">
                        <thead style="position: sticky; top: 0; z-index: 15; background: var(--card-bg);">
                            <tr>
                                <th width="5%">#</th>
                                <th width="35%">Nama Pelanggan</th>
                                <th width="30%">Nomor WhatsApp</th>
                                <th width="15%">Status</th>
                                <th width="15%" class="text-end">Tindakan</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php if($address_book && $address_book->num_rows > 0): ?>
                                <?php $no=1; while($ab = $address_book->fetch_assoc()): ?>
                                <tr>
                                    <td class="text-muted fw-bold"><?= $no++ ?></td>
                                    <td>
                                        <div class="fw-bold fs-6 ab-name" style="color: #0f172a;"><?= htmlspecialchars($ab['name']) ?></div>
                                    </td>
                                    <td>
                                        <div class="fw-medium ab-phone" style="font-size: 0.9rem; color: #475569;">+<?= htmlspecialchars($ab['phone_number']) ?></div>
                                    </td>
                                    <td>
                                        <?php if($ab['status'] == 'open'): ?>
                                            <span class="badge-soft-warning">CHAT AKTIF</span>
                                        <?php elseif($ab['status'] == 'closed'): ?>
                                            <span class="badge-soft-success">SELESAI</span>
                                        <?php else: ?>
                                            <span class="badge-soft-dark">TERSIMPAN</span>
                                        <?php endif; ?>
                                    </td>
                                    <td class="text-end">
                                        <button class="btn btn-sm btn-light fw-bold px-2 py-1 text-warning border shadow-sm rounded-3 me-sm-1" onclick='openEditABModal(<?= json_encode($ab) ?>)'>Edit</button>
                                        <form action="" method="POST" class="d-inline" onsubmit="return confirm('Menghapus kontak ini akan menghapus nama mereka di Dashboard chat. Yakin?');">
                                            <input type="hidden" name="ab_action" value="delete">
                                            <input type="hidden" name="ab_id" value="<?= $ab['id'] ?>">
                                            <button type="submit" class="btn btn-sm btn-light fw-bold px-2 py-1 text-danger border shadow-sm rounded-3">Hapus</button>
                                        </form>
                                    </td>
                                </tr>
                                <?php endwhile; ?>
                            <?php else: ?>
                                <tr>
                                    <td colspan="5">
                                        <div class="text-center py-5">
                                            <div class="fs-1 mb-3">📭</div>
                                            <h6 class="fw-bold text-muted">Buku telepon masih kosong.</h6>
                                            <p class="text-muted small">Gunakan tombol Sinkronisasi Google di atas untuk menarik data secara massal.</p>
                                        </div>
                                    </td>
                                </tr>
                            <?php endif; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>

    <div class="row mt-2">
        <div class="col-12">
            <div class="glass-card mb-5">
                <div class="d-flex justify-content-between align-items-center mb-4 flex-wrap gap-3">
                    <div>
                        <h5 class="section-title mb-1"><span>📈</span> Log Interaksi Terakhir</h5>
                        <p class="text-muted m-0" style="font-size: 0.9rem;">Menampilkan antrean tiket. Gunakan tombol unduh untuk laporan penuh.</p>
                    </div>
                    <a href="export_excel.php" class="btn btn-gradient shadow-sm d-flex align-items-center gap-2"><span>📥</span> Unduh (.CSV)</a>
                </div>
                
                <div class="table-responsive table-wrapper">
                    <table class="table-modern">
                        <thead style="position: sticky; top: 0; z-index: 15; background: var(--card-bg);">
                            <tr>
                                <th>#</th>
                                <th>Identitas Pelanggan</th>
                                <th>Status</th>
                                <th>Label / Kategori</th>
                                <th>PIC / Dilayani</th>
                                <th class="text-center">Jml Interaksi</th>
                                <th>Aktivitas Terakhir</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php if($report_query && $report_query->num_rows > 0): ?>
                                <?php $no=1; while($r = $report_query->fetch_assoc()): ?>
                                <tr>
                                    <td class="text-muted fw-bold"><?= $no++ ?></td>
                                    <td>
                                        <div class="fw-bold fs-6" style="color: #0f172a; min-width: 150px;"><?= htmlspecialchars($r['name']) ?></div>
                                        <div class="fw-medium mt-1" style="font-size: 0.8rem; color: #64748b;">+<?= htmlspecialchars($r['phone_number']) ?></div>
                                    </td>
                                    <td>
                                        <?php if($r['status'] == 'open'): ?>
                                            <span class="badge-soft-warning">AKTIF</span>
                                        <?php else: ?>
                                            <span class="badge-soft-dark">SELESAI</span>
                                        <?php endif; ?>
                                    </td>
                                    <td>
                                        <span class="badge-soft-dark border">
                                            <?= empty($r['label']) ? 'Tanpa Label' : htmlspecialchars($r['label']) ?>
                                        </span>
                                    </td>
                                    <td>
                                        <span class="fw-bold" style="color: var(--primary); font-size: 0.9rem;">
                                            <?= empty($r['assigned_to']) ? '— Sistem Bot —' : htmlspecialchars($r['assigned_to']) ?>
                                        </span>
                                    </td>
                                    <td class="text-center"><span class="badge-soft-dark fs-6"><?= $r['total_chat'] ?></span></td>
                                    <td>
                                        <div class="fw-bold text-nowrap" style="color: #475569; font-size: 0.9rem;"><?= date('d M Y', strtotime($r['last_active'])) ?></div>
                                        <div class="text-muted fw-medium mt-1" style="font-size: 0.8rem;"><?= date('H:i', strtotime($r['last_active'])) ?> WIB</div>
                                    </td>
                                </tr>
                                <?php endwhile; ?>
                            <?php else: ?>
                                <tr>
                                    <td colspan="7">
                                        <div class="text-center py-5">
                                            <div class="fs-1 mb-3">📭</div>
                                            <h6 class="fw-bold text-muted">Belum ada riwayat percakapan.</h6>
                                        </div>
                                    </td>
                                </tr>
                            <?php endif; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- ============================================================== -->
<!-- MODAL TEST API (BULK/MULTI-TEST)                               -->
<!-- ============================================================== -->
<div class="modal fade" id="modalTestAPI" tabindex="-1">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content border-0 shadow-lg p-3" style="border-radius: var(--radius-lg);">
            <div class="modal-header border-0">
                <h5 class="modal-title fw-bold text-primary">🧪 Bulk API Test Tool</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <p class="text-muted" style="font-size: 0.85rem;">Gunakan alat ini untuk mengecek apakah Bot Anda sedang offline atau apakah nomor tujuan Anda bermasalah.</p>
                
                <div class="mb-3">
                    <label class="form-label text-dark fw-bold" style="font-size: 0.85rem;">1. Pilih Bot Pengirim (Sender):</label>
                    <select id="test_sender" class="form-select bg-light">
                        <option value="">-- Gunakan Bot Utama (Default) --</option>
                        <?php
                           if(!empty($available_devices)){
                               foreach($available_devices as $dev){
                                   echo "<option value='".htmlspecialchars($dev)."'>".htmlspecialchars($dev)."</option>";
                               }
                           }
                        ?>
                    </select>
                </div>

                <div class="mb-3">
                    <label class="form-label text-dark fw-bold" style="font-size: 0.85rem;">2. Pilih dari Kontak Internal (Pintasan):</label>
                    <div class="d-flex flex-wrap gap-2 p-2 bg-light border rounded" style="max-height: 100px; overflow-y: auto;">
                        <?php
                           if(isset($fwd_contacts) && $fwd_contacts->num_rows > 0){
                               mysqli_data_seek($fwd_contacts, 0);
                               while($fc = $fwd_contacts->fetch_assoc()){
                                   echo "<button type='button' class='btn btn-sm btn-outline-secondary py-1 px-2' style='font-size: 0.75rem; border-radius: 8px;' onclick='addTestNumber(\"".htmlspecialchars($fc['phone_number'])."\")'>".htmlspecialchars($fc['name'])."</button>";
                               }
                           } else {
                               echo "<span class='text-muted small'>Belum ada Kontak Internal.</span>";
                           }
                        ?>
                    </div>
                </div>
                
                <div class="mb-3">
                    <label class="form-label text-dark fw-bold" style="font-size: 0.85rem;">3. Nomor Target Uji Coba:</label>
                    <textarea id="test_api_number" class="form-control bg-white" rows="2" placeholder="Cth: 628123456789, 6281554311420" required></textarea>
                    <small class="text-primary mt-1 d-block" style="font-size: 0.75rem; font-weight: 500;">💡 Pisahkan dengan koma (,) jika ingin mengirim tes ke beberapa nomor sekaligus.</small>
                </div>
                
                <button type="button" id="btnTestApi" class="btn btn-primary w-100 fw-bold mt-2 py-2" onclick="testApiConnection()" style="border-radius: 12px; font-size: 1rem;">Mulai Ping (Uji Coba)</button>
                
                <!-- Hasil Test akan muncul di sini -->
                <div id="testApiResult" class="mt-4" style="max-height: 250px; overflow-y: auto;"></div>
            </div>
        </div>
    </div>
</div>

<div class="modal fade" id="editModal" tabindex="-1">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content border-0 shadow-lg p-3" style="border-radius: var(--radius-lg);">
            <form method="POST">
                <div class="modal-header border-0">
                    <h5 class="modal-title fw-bold">⚙️ Edit Detail Akun</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    <input type="hidden" name="user_id" id="edit_id">
                    <div class="mb-4">
                        <label class="form-label">Nama Lengkap</label>
                        <input type="text" name="name" id="edit_name" class="form-control" required>
                    </div>
                    <div class="mb-4">
                        <label class="form-label">Username</label>
                        <input type="text" name="username" id="edit_username" class="form-control" required>
                    </div>
                    <div class="mb-4">
                        <label class="form-label">Password Baru <small class="text-danger fw-normal ms-1">(Kosongkan jika tidak diganti)</small></label>
                        <input type="password" name="password" class="form-control" placeholder="••••••••">
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Level Akses</label>
                        <select name="role" id="edit_role" class="form-select bg-white">
                            <option value="cs">Customer Service (CS)</option>
                            <option value="admin">Administrator (Admin)</option>
                        </select>
                    </div>
                </div>
                <div class="modal-footer border-0">
                    <button type="submit" name="edit_user" class="btn btn-gradient w-100">Simpan Perubahan</button>
                </div>
            </form>
        </div>
    </div>
</div>

<div class="modal fade" id="modalEditAB" tabindex="-1">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content border-0 shadow-lg p-3" style="border-radius: var(--radius-lg);">
            <form action="" method="POST">
                <div class="modal-header border-0">
                    <h5 class="modal-title fw-bold">✏️ Edit Kontak</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body text-start">
                    <input type="hidden" name="ab_action" value="edit">
                    <input type="hidden" name="ab_id" id="edit_ab_id">
                    <div class="mb-4">
                        <label class="form-label">Nama Pelanggan</label>
                        <input type="text" name="name" id="edit_ab_name" class="form-control" required>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Nomor WhatsApp</label>
                        <input type="text" name="phone_number" id="edit_ab_phone" class="form-control" required>
                    </div>
                </div>
                <div class="modal-footer border-0">
                    <button type="submit" class="btn btn-gradient w-100">Simpan Perubahan</button>
                </div>
            </form>
        </div>
    </div>
</div>

<div class="modal fade" id="modalEditQR" tabindex="-1">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content border-0 shadow-lg p-3" style="border-radius: var(--radius-lg);">
            <form action="" method="POST">
                <div class="modal-header border-0">
                    <h5 class="modal-title fw-bold">✏️ Edit Template</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body text-start">
                    <input type="hidden" name="qr_action" value="edit">
                    <input type="hidden" name="qr_id" id="edit_qr_id">
                    <div class="mb-4">
                        <label class="form-label">Nama Tombol</label>
                        <input type="text" name="title" id="edit_qr_title" class="form-control" required>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Teks Balasan</label>
                        <textarea name="content" id="edit_qr_content" class="form-control" rows="6" required></textarea>
                    </div>
                </div>
                <div class="modal-footer border-0">
                    <button type="submit" class="btn btn-gradient w-100">Simpan Perubahan</button>
                </div>
            </form>
        </div>
    </div>
</div>

<div class="modal fade" id="modalEditFC" tabindex="-1">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content border-0 shadow-lg p-3" style="border-radius: var(--radius-lg);">
            <form action="" method="POST">
                <div class="modal-header border-0">
                    <h5 class="modal-title fw-bold">✏️ Edit Kontak Internal</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body text-start">
                    <input type="hidden" name="fc_action" value="edit">
                    <input type="hidden" name="fc_id" id="edit_fc_id">
                    <div class="mb-4">
                        <label class="form-label">Nama Divisi / Orang</label>
                        <input type="text" name="name" id="edit_fc_name" class="form-control" required>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Nomor WhatsApp / ID Grup</label>
                        <input type="text" name="phone_number" id="edit_fc_phone" class="form-control" required>
                    </div>
                </div>
                <div class="modal-footer border-0">
                    <button type="submit" class="btn btn-gradient w-100">Simpan Perubahan</button>
                </div>
            </form>
        </div>
    </div>
</div>

<div class="modal fade" id="modalAddAB" tabindex="-1">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content border-0 shadow-lg p-3" style="border-radius: var(--radius-lg);">
            <form action="" method="POST">
                <div class="modal-header border-0">
                    <h5 class="modal-title fw-bold text-dark">📇 Tambah Kontak Manual</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    <input type="hidden" name="ab_action" value="add">
                    <div class="mb-4">
                        <label class="form-label">Nama Pelanggan</label>
                        <input type="text" name="name" class="form-control" placeholder="Cth: Budi Santoso" required>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Nomor WhatsApp</label>
                        <input type="text" name="phone_number" class="form-control" placeholder="Cth: 0812xxx atau 62812xxx" required>
                        <small class="text-muted d-block mt-2">Sistem akan otomatis menyesuaikan format awalan menjadi 62.</small>
                    </div>
                </div>
                <div class="modal-footer border-0">
                    <button type="submit" class="btn btn-dark w-100 fw-bold py-2" style="border-radius: 12px;">Simpan Kontak</button>
                </div>
            </form>
        </div>
    </div>
</div>

<div class="modal fade" id="modalAddQR" tabindex="-1">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content border-0 shadow-lg p-3" style="border-radius: var(--radius-lg);">
            <form action="" method="POST">
                <div class="modal-header border-0">
                    <h5 class="modal-title fw-bold text-success">✨ Buat Template Baru</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    <input type="hidden" name="qr_action" value="add">
                    <div class="mb-4">
                        <label class="form-label">Label Tombol (Singkat)</label>
                        <input type="text" name="title" class="form-control" placeholder="Cth: 💵 Info Rekening" required>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Isi Pesan Lengkap</label>
                        <textarea name="content" class="form-control" rows="6" placeholder="Ketik pesan panjang di sini..." required></textarea>
                        
                        <div class="mt-3 p-3 rounded-3" style="background: rgba(13, 110, 253, 0.05); border: 1px dashed rgba(13, 110, 253, 0.3);">
                            <h6 class="fw-bold" style="font-size: 0.8rem; color: #0d6efd;">💡 KODE OTOMATIS:</h6>
                            <div style="font-size: 0.8rem; color: #475569; line-height: 1.6;">
                                <span class="badge bg-white text-dark border me-1">[WAKTU]</span> Sapaan Pagi/Siang/Malam.<br>
                                <span class="badge bg-white text-dark border me-1">[NAMA]</span> Nama asli pelanggan.<br>
                                <span class="badge bg-white text-dark border me-1">[CS]</span> Nama staf yang membalas.
                            </div>
                        </div>
                    </div>
                </div>
                <div class="modal-footer border-0">
                    <button type="submit" class="btn btn-gradient w-100">Simpan Template</button>
                </div>
            </form>
        </div>
    </div>
</div>

<div class="modal fade" id="modalAddFC" tabindex="-1">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content border-0 shadow-lg p-3" style="border-radius: var(--radius-lg);">
            <form action="" method="POST">
                <div class="modal-header border-0">
                    <h5 class="modal-title fw-bold text-dark">📞 Tambah Kontak Internal</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    <input type="hidden" name="fc_action" value="add">
                    <div class="mb-4">
                        <label class="form-label">Nama Divisi / Orang</label>
                        <input type="text" name="name" class="form-control" placeholder="Cth: Finance / Teknisi Budi" required>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Nomor WhatsApp / ID Grup</label>
                        <input type="text" name="phone_number" class="form-control" placeholder="Cth: 62812xxx atau 123@g.us" required>
                        <small class="text-muted d-block mt-2">Nomor ini akan muncul sebagai tombol pintasan saat CS meneruskan pesan (Forward).</small>
                    </div>
                </div>
                <div class="modal-footer border-0">
                    <button type="submit" class="btn btn-dark w-100 fw-bold py-2" style="border-radius: 12px;">Simpan Kontak</button>
                </div>
            </form>
        </div>
    </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
<script>
// ==============================================================
// JS UNTUK FITUR TEST KONEKSI API MPWA MULTI-NUMBER
// ==============================================================
function addTestNumber(num) {
    let inputField = document.getElementById('test_api_number');
    let currentVal = inputField.value.trim();
    
    // Jangan tambahkan jika sudah ada di dalam input (mencegah duplikat)
    if(currentVal.includes(num)) return; 
    
    if(currentVal === '') {
        inputField.value = num;
    } else {
        // Hilangkan koma di akhir jika ada, lalu tambahkan koma baru
        if(currentVal.endsWith(',')) {
            inputField.value = currentVal + ' ' + num;
        } else {
            inputField.value = currentVal + ', ' + num;
        }
    }
}

function testApiConnection() {
    let btn = document.getElementById('btnTestApi');
    let resultDiv = document.getElementById('testApiResult');
    let testNum = document.getElementById('test_api_number').value;
    let testSender = document.getElementById('test_sender').value;
    
    if(testNum.trim() === '') {
        alert('Masukkan minimal 1 nomor tujuan tes!');
        return;
    }

    btn.disabled = true;
    btn.innerHTML = 'Sedang menguji ping...';
    resultDiv.innerHTML = '<div class="text-center mt-3"><div class="spinner-border text-primary spinner-border-sm"></div> Menghubungi Server MPWA...</div>';

    let formData = new FormData();
    formData.append('action', 'test_api');
    formData.append('test_number', testNum);
    formData.append('sender_device', testSender);

    fetch('admin_panel.php', {
        method: 'POST',
        body: formData
    })
    .then(res => res.json())
    .then(data => {
        resultDiv.innerHTML = data.html;
        btn.disabled = false;
        btn.innerHTML = 'Uji Coba Ulang';
    })
    .catch(err => {
        resultDiv.innerHTML = '<div class="alert alert-danger p-2 fs-6 mt-2 mb-0"><b>Gagal Terhubung!</b><br>Terjadi kesalahan pada server OmniDesk saat memproses request AJAX. Cek koneksi internet server Anda.</div>';
        btn.disabled = false;
        btn.innerHTML = 'Mulai Ping (Uji Coba)';
    });
}

// JS UNTUK MEMBUKA MODAL EDIT DAN MENGISI DATA
function openEditModal(user) {
    document.getElementById('edit_id').value = user.id;
    document.getElementById('edit_name').value = user.name;
    document.getElementById('edit_username').value = user.username;
    document.getElementById('edit_role').value = user.role;
    var myModal = new bootstrap.Modal(document.getElementById('editModal'));
    myModal.show();
}

function openEditABModal(ab) {
    document.getElementById('edit_ab_id').value = ab.id;
    document.getElementById('edit_ab_name').value = ab.name;
    document.getElementById('edit_ab_phone').value = ab.phone_number;
    var myModal = new bootstrap.Modal(document.getElementById('modalEditAB'));
    myModal.show();
}

function openEditQRModal(qr) {
    document.getElementById('edit_qr_id').value = qr.id;
    document.getElementById('edit_qr_title').value = qr.title;
    document.getElementById('edit_qr_content').value = qr.content;
    var myModal = new bootstrap.Modal(document.getElementById('modalEditQR'));
    myModal.show();
}

function openEditFCModal(fc) {
    document.getElementById('edit_fc_id').value = fc.id;
    document.getElementById('edit_fc_name').value = fc.name;
    document.getElementById('edit_fc_phone').value = fc.phone_number;
    var myModal = new bootstrap.Modal(document.getElementById('modalEditFC'));
    myModal.show();
}

// LOGIKA UNTUK FILTER PENCARIAN BUKU TELEPON SECARA REAL-TIME
function filterAddressBook() {
    var input, filter, table, tr, tdName, tdPhone, i, txtValueName, txtValuePhone;
    input = document.getElementById("searchAddressBook");
    filter = input.value.toLowerCase();
    table = document.getElementById("tableAddressBook");
    tr = table.getElementsByTagName("tr");

    for (i = 1; i < tr.length; i++) { 
        tdName = tr[i].querySelector(".ab-name");
        tdPhone = tr[i].querySelector(".ab-phone");
        if (tdName || tdPhone) {
            txtValueName = tdName.textContent || tdName.innerText;
            txtValuePhone = tdPhone.textContent || tdPhone.innerText;
            
            if (txtValueName.toLowerCase().indexOf(filter) > -1 || txtValuePhone.toLowerCase().indexOf(filter) > -1) {
                tr[i].style.display = "";
            } else {
                tr[i].style.display = "none";
            }
        }       
    }
}
</script>
</body>
</html>