<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);

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

try {
    require_once __DIR__ . '/../classes/Customer.php';
} catch (\Throwable $e) {
    die('Error loading classes: ' . $e->getMessage());
}

requireRole('super_admin');
$pageTitle = 'Broadcast WhatsApp';

$db = db();
$success = '';
$error = '';
$broadcastResult = null;
$debugLogs = [];
$sentMessages = [];

// ============================================================================
// CREATE TEMPLATES TABLE IF NOT EXISTS
// ============================================================================
try {
    $db->exec("CREATE TABLE IF NOT EXISTS broadcast_templates (
        id INT AUTO_INCREMENT PRIMARY KEY,
        name VARCHAR(100) NOT NULL,
        icon VARCHAR(10) DEFAULT '📝',
        content TEXT NOT NULL,
        created_by INT,
        created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
        updated_at DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
    )");
    
    $count = $db->query("SELECT COUNT(*) FROM broadcast_templates")->fetchColumn();
    if ($count == 0) {
        $defaultTemplates = [
            ['📅', 'Reminder Tagihan', "🔔 REMINDER TAGIHAN INTERNET\n\nYth. Pelanggan,\n\nTagihan internet Anda akan segera jatuh tempo. Mohon segera melakukan pembayaran untuk menghindari gangguan layanan.\n\nSilakan cek tagihan Anda atau hubungi kami untuk informasi lebih lanjut.\n\nTerima kasih 🙏"],
            ['🔧', 'Info Maintenance', "🔧 INFO MAINTENANCE\n\nYth. Pelanggan,\n\nAkan dilakukan maintenance jaringan pada:\n📅 Tanggal: [ISI TANGGAL]\n⏰ Waktu: [ISI WAKTU]\n⏱️ Estimasi: [ISI DURASI]\n\nSelama maintenance, layanan mungkin terganggu sementara. Mohon maaf atas ketidaknyamanannya.\n\nTerima kasih 🙏"],
            ['🎉', 'Promo Paket', "🎉 PROMO SPESIAL!\n\nYth. Pelanggan,\n\nDapatkan penawaran spesial untuk upgrade paket internet Anda:\n\n✨ [NAMA PAKET]\n💰 Harga: [HARGA]/bulan\n🚀 Speed: [SPEED] Mbps\n\nPromo berlaku sampai [TANGGAL]. Hubungi kami untuk info lebih lanjut!\n\nTerima kasih 🙏"],
            ['🙏', 'Ucapan Terima Kasih', "🙏 TERIMA KASIH\n\nYth. Pelanggan,\n\nTerima kasih telah menjadi pelanggan setia kami. Pembayaran Anda telah kami terima.\n\nLayanan internet Anda akan tetap aktif dan berjalan normal.\n\nJika ada kendala, silakan hubungi kami.\n\nSalam hangat 🙏"],
        ];
        foreach ($defaultTemplates as $t) {
            $db->prepare("INSERT INTO broadcast_templates (icon, name, content, created_by) VALUES (?, ?, ?, ?)")
               ->execute([$t[0], $t[1], $t[2], currentUserId()]);
        }
    }
} catch (\Throwable $e) {}

// ============================================================================
// HANDLE TEMPLATE CRUD
// ============================================================================
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && verifyCsrf($_POST['csrf_token'] ?? '')) {
    $action = $_POST['action'];
    
    if ($action === 'create_template') {
        $name = trim($_POST['template_name'] ?? '');
        $icon = trim($_POST['template_icon'] ?? '📝');
        $content = trim($_POST['template_content'] ?? '');
        
        if (empty($name) || empty($content)) {
            $_SESSION['flash_error'] = '❌ Nama dan isi template wajib diisi';
        } else {
            try {
                $db->prepare("INSERT INTO broadcast_templates (name, icon, content, created_by) VALUES (?, ?, ?, ?)")
                   ->execute([$name, $icon, $content, currentUserId()]);
                redirect('/admin/broadcast.php', '✅ Template berhasil ditambahkan');
            } catch (\Throwable $e) {
                $_SESSION['flash_error'] = '❌ Error: ' . $e->getMessage();
            }
        }
    }
    
    if ($action === 'update_template') {
        $id = (int)($_POST['template_id'] ?? 0);
        $name = trim($_POST['template_name'] ?? '');
        $icon = trim($_POST['template_icon'] ?? '📝');
        $content = trim($_POST['template_content'] ?? '');
        
        if ($id <= 0 || empty($name) || empty($content)) {
            $_SESSION['flash_error'] = '❌ Data tidak valid';
        } else {
            try {
                $db->prepare("UPDATE broadcast_templates SET name = ?, icon = ?, content = ? WHERE id = ?")
                   ->execute([$name, $icon, $content, $id]);
                redirect('/admin/broadcast.php', '✅ Template berhasil diupdate');
            } catch (\Throwable $e) {
                $_SESSION['flash_error'] = '❌ Error: ' . $e->getMessage();
            }
        }
    }
    
    if ($action === 'delete_template') {
        $id = (int)($_POST['template_id'] ?? 0);
        try {
            $db->prepare("DELETE FROM broadcast_templates WHERE id = ?")->execute([$id]);
            redirect('/admin/broadcast.php', '✅ Template berhasil dihapus');
        } catch (\Throwable $e) {
            $_SESSION['flash_error'] = '❌ Error: ' . $e->getMessage();
        }
    }
}

$flashError = $_SESSION['flash_error'] ?? '';
unset($_SESSION['flash_error']);

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

$wablasToken = $config['wablas_token'] ?? '';
$wablasBaseUrl = rtrim($config['wablas_base_url'] ?? 'https://tegal.wablas.com/api', '/');

function sendWablasMessage($phone, $message, $baseUrl, $token) {
    $params = ['phone' => $phone, 'message' => $message, 'token' => $token];
    $queryString = http_build_query($params);
    $url = $baseUrl . '/send-message?' . $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);
    
    $decoded = json_decode($result, true);
    
    return [
        'success' => ($httpCode == 200 && isset($decoded['status']) && $decoded['status'] === true),
        'http_code' => $httpCode,
        'response' => $decoded ?: ['raw' => $result],
        'error' => $curlError ?: ($decoded['message'] ?? ($decoded['error'] ?? 'Unknown error')),
        'url_called' => $url
    ];
}

try {
    $customers = Customer::all();
} catch (\Throwable $e) {
    $customers = [];
    $error = 'Error loading customers: ' . $e->getMessage();
}

try {
    $branches = $db->query("SELECT id, name FROM branches ORDER BY name")->fetchAll();
} catch (\Throwable $e) {
    $branches = [];
}

try {
    $templates = $db->query("SELECT * FROM broadcast_templates ORDER BY created_at DESC")->fetchAll();
} catch (\Throwable $e) {
    $templates = [];
}

$isConfigured = !empty($wablasToken) && !empty($wablasBaseUrl);

$totalBroadcasts = 0;
$totalMessagesSent = 0;
try {
    $totalBroadcasts = $db->query("SELECT COUNT(*) FROM broadcast_logs")->fetchColumn();
    $totalMessagesSent = $db->query("SELECT COALESCE(SUM(sent_count), 0) FROM broadcast_logs")->fetchColumn();
} catch (\Throwable $e) {}

// Handle broadcast
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'send_broadcast') {
    if (verifyCsrf($_POST['csrf_token'] ?? '')) {
        $title = trim($_POST['title'] ?? '');
        $message = trim($_POST['message']);
        
        $message = preg_replace('%(?:
              \xF0[\x90-\xBF][\x80-\xBF]{2}
            | [\xF1-\xF3][\x80-\xBF]{3}
            | \xF4[\x80-\x8F][\x80-\xBF]{2}
        )%xs', '', $message);

        $targetType = $_POST['target_type'] ?? 'all_customers';
        $targetNumbers = [];
        
        if (empty($message)) {
            $error = 'Pesan tidak boleh kosong';
        } elseif (empty($title)) {
            $error = 'Judul broadcast wajib diisi';
        } elseif (!$isConfigured) {
            $error = 'Wablas belum dikonfigurasi. Silakan isi Token dan Base URL di <a href="/admin/wablas_settings.php">Wablas Settings</a>.';
        } else {
            switch ($targetType) {
                case 'all_customers':
                    foreach ($customers as $c) {
                        if (!empty($c['phone'])) {
                            $phone = preg_replace('/[^0-9]/', '', $c['phone']);
                            if (substr($phone, 0, 1) === '0') $phone = '62' . substr($phone, 1);
                            elseif (substr($phone, 0, 2) !== '62') $phone = '62' . $phone;
                            $targetNumbers[] = ['phone' => $phone, 'name' => $c['name'], 'customer_number' => $c['customer_number'] ?? '-'];
                        }
                    }
                    break;
                    
                case 'selected_customers':
                    $selectedIds = $_POST['customers'] ?? [];
                    if (empty($selectedIds)) {
                        $error = 'Pilih minimal 1 customer';
                    } else {
                        foreach ($customers as $c) {
                            if (in_array($c['id'], $selectedIds) && !empty($c['phone'])) {
                                $phone = preg_replace('/[^0-9]/', '', $c['phone']);
                                if (substr($phone, 0, 1) === '0') $phone = '62' . substr($phone, 1);
                                elseif (substr($phone, 0, 2) !== '62') $phone = '62' . $phone;
                                $targetNumbers[] = ['phone' => $phone, 'name' => $c['name'], 'customer_number' => $c['customer_number'] ?? '-'];
                            }
                        }
                    }
                    break;
                    
                case 'branch':
                    $branchId = (int)($_POST['target_branch'] ?? 0);
                    if ($branchId <= 0) {
                        $error = 'Pilih cabang target';
                    } else {
                        foreach ($customers as $c) {
                            if (isset($c['branch_id']) && $c['branch_id'] == $branchId && !empty($c['phone'])) {
                                $phone = preg_replace('/[^0-9]/', '', $c['phone']);
                                if (substr($phone, 0, 1) === '0') $phone = '62' . substr($phone, 1);
                                elseif (substr($phone, 0, 2) !== '62') $phone = '62' . $phone;
                                $targetNumbers[] = ['phone' => $phone, 'name' => $c['name'], 'customer_number' => $c['customer_number'] ?? '-'];
                            }
                        }
                    }
                    break;
                    
                case 'custom_numbers':
                    $numbersText = $_POST['custom_numbers'] ?? '';
                    $numbers = array_filter(array_map('trim', preg_split('/[\s,;]+/', $numbersText)));
                    if (empty($numbers)) {
                        $error = 'Masukkan minimal 1 nomor';
                    } else {
                        foreach ($numbers as $num) {
                            $phone = preg_replace('/[^0-9]/', '', $num);
                            if (substr($phone, 0, 1) === '0') $phone = '62' . substr($phone, 1);
                            elseif (substr($phone, 0, 2) !== '62') $phone = '62' . $phone;
                            $targetNumbers[] = ['phone' => $phone, 'name' => 'Custom Number', 'customer_number' => '-'];
                        }
                    }
                    break;
            }
            
            if (empty($error) && empty($targetNumbers)) {
                $error = 'Tidak ada nomor telepon yang valid untuk dikirim';
            }
            
            if (empty($error)) {
                $totalSent = 0;
                $totalFailed = 0;
                
                foreach ($targetNumbers as $target) {
                    $result = sendWablasMessage($target['phone'], $message, $wablasBaseUrl, $wablasToken);
                    
                    if ($result['success']) {
                        $totalSent++;
                        $sentMessages[] = [
                            'phone' => $target['phone'],
                            'name' => $target['name'],
                            'customer_number' => $target['customer_number'],
                            'message' => $message,
                            'timestamp' => date('H:i:s')
                        ];
                    } else {
                        $totalFailed++;
                        $debugLogs[] = [
                            'phone' => $target['phone'],
                            'name' => $target['name'],
                            'customer_number' => $target['customer_number'],
                            'success' => false,
                            'http_code' => $result['http_code'],
                            'error_message' => $result['error'],
                            'url_called' => $result['url_called']
                        ];
                    }
                    
                    usleep(500000);
                }
                
                try {
                    $db->prepare("INSERT INTO broadcast_logs (title, message, target_type, total_targets, sent_count, failed_count, status, created_by, created_at) 
                                 VALUES (?, ?, ?, ?, ?, ?, ?, ?, NOW())")
                       ->execute([$title, $message, $targetType, count($targetNumbers), $totalSent, $totalFailed, $totalFailed > 0 ? 'partial' : 'success', currentUserId()]);
                } catch (\Throwable $e) {}
                
                $broadcastResult = ['total' => count($targetNumbers), 'sent' => $totalSent, 'failed' => $totalFailed];
                
                if ($totalSent > 0) {
                    $success = "✅ Broadcast selesai!<br>Total Target: {$broadcastResult['total']} | Berhasil: <span class='text-success'>{$broadcastResult['sent']}</span> | Gagal: <span class='text-danger'>{$broadcastResult['failed']}</span>";
                } else {
                    $error = "❌ Semua pesan gagal dikirim!<br>Total Target: {$broadcastResult['total']} | Gagal: <span class='text-danger'>{$broadcastResult['failed']}</span>";
                }
            }
        }
    }
}

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

<style>
/* ============================================
   PAGE HEADER
   ============================================ */
.page-header {
    margin-bottom: 25px;
    display: flex;
    justify-content: space-between;
    align-items: center;
    flex-wrap: wrap;
    gap: 15px;
}

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

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

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

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

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

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

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

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

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

.summary-card-title {
    color: #666;
    font-size: 0.85rem;
    font-weight: 600;
    margin: 0;
}

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

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

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

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

.summary-card-footer {
    font-size: 0.8rem;
    color: #999;
}

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

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

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

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

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

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

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

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

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

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

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

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

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

.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.6;
    cursor: not-allowed;
}

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

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

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

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

.btn-modern.danger {
    background: linear-gradient(135deg, #DC3545 0%, #FF6B7A 100%);
    color: white;
    box-shadow: 0 4px 12px rgba(220, 53, 69, 0.3);
}

.btn-modern.success {
    background: linear-gradient(135deg, #00C853 0%, #69F0AE 100%);
    color: white;
}

.btn-modern.outline {
    background: white;
    color: #0066CC;
    border: 2px solid #0066CC;
}

.btn-modern.outline:hover {
    background: #0066CC;
    color: white;
}

.btn-sm-modern {
    padding: 8px 14px;
    font-size: 0.85rem;
    border-radius: 10px;
}

/* ============================================
   TEMPLATE CARDS
   ============================================ */
.templates-grid {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(260px, 1fr));
    gap: 16px;
}

.template-card {
    background: white;
    border: 2px solid #f0f0f0;
    border-radius: 14px;
    padding: 16px;
    transition: all 0.3s ease;
    cursor: pointer;
    position: relative;
}

.template-card:hover {
    border-color: #25D366;
    transform: translateY(-3px);
    box-shadow: 0 8px 20px rgba(37, 211, 102, 0.15);
}

.template-card-header {
    display: flex;
    align-items: center;
    gap: 10px;
    margin-bottom: 10px;
}

.template-icon {
    width: 40px;
    height: 40px;
    border-radius: 10px;
    background: linear-gradient(135deg, #e8f5e9 0%, #c8e6c9 100%);
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 1.3rem;
    flex-shrink: 0;
}

.template-name {
    font-weight: 700;
    color: #003D7A;
    font-size: 0.95rem;
    margin: 0;
    flex: 1;
    min-width: 0;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
}

.template-preview {
    font-size: 0.82rem;
    color: #666;
    line-height: 1.5;
    margin-bottom: 12px;
    display: -webkit-box;
    -webkit-line-clamp: 3;
    -webkit-box-orient: vertical;
    overflow: hidden;
    min-height: 60px;
    white-space: pre-wrap;
}

.template-actions {
    display: flex;
    gap: 6px;
    padding-top: 10px;
    border-top: 1px dashed #e8f4f8;
}

.btn-template {
    flex: 1;
    padding: 7px;
    border: none;
    border-radius: 8px;
    font-size: 0.78rem;
    font-weight: 600;
    cursor: pointer;
    transition: all 0.3s ease;
    display: inline-flex;
    align-items: center;
    justify-content: center;
    gap: 4px;
}

.btn-template.use {
    background: #d1e7dd;
    color: #0f5132;
}

.btn-template.use:hover {
    background: #25D366;
    color: white;
}

.btn-template.edit {
    background: #cfe2ff;
    color: #084298;
}

.btn-template.edit:hover {
    background: #0066CC;
    color: white;
}

.btn-template.delete {
    background: #f8d7da;
    color: #842029;
}

.btn-template.delete:hover {
    background: #DC3545;
    color: white;
}

/* ============================================
   MESSAGE SENT LIST
   ============================================ */
.message-list {
    max-height: 500px;
    overflow-y: auto;
}

.message-item {
    display: flex;
    align-items: flex-start;
    gap: 12px;
    padding: 14px;
    border-bottom: 1px solid #f0f0f0;
    transition: all 0.2s ease;
    cursor: pointer;
}

.message-item:hover {
    background: #f8fafc;
}

.message-item:last-child {
    border-bottom: none;
}

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

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

.message-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 4px;
    gap: 8px;
}

.message-name {
    font-weight: 700;
    color: #003D7A;
    font-size: 0.9rem;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
}

.message-time {
    font-size: 0.75rem;
    color: #999;
    flex-shrink: 0;
}

.message-phone {
    font-size: 0.8rem;
    color: #666;
    margin-bottom: 4px;
    display: flex;
    align-items: center;
    gap: 6px;
}

.message-phone code {
    background: #f0f0f0;
    padding: 2px 6px;
    border-radius: 4px;
    font-size: 0.75rem;
}

.message-preview {
    font-size: 0.82rem;
    color: #666;
    line-height: 1.4;
    display: -webkit-box;
    -webkit-line-clamp: 2;
    -webkit-box-orient: vertical;
    overflow: hidden;
    white-space: pre-wrap;
}

.message-status {
    display: inline-flex;
    align-items: center;
    gap: 4px;
    padding: 2px 8px;
    border-radius: 10px;
    font-size: 0.7rem;
    font-weight: 700;
    background: #d1e7dd;
    color: #0f5132;
}

/* ============================================
   EMPTY STATE
   ============================================ */
.empty-state {
    text-align: center;
    padding: 40px 20px;
}

.empty-state-icon {
    width: 70px;
    height: 70px;
    margin: 0 auto 16px;
    background: #f8fafc;
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 2rem;
    color: #ccc;
}

.empty-state-title {
    color: #666;
    font-weight: 600;
    margin-bottom: 6px;
    font-size: 1rem;
}

.empty-state-subtitle {
    color: #999;
    font-size: 0.85rem;
    margin: 0;
}

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

.alert-modern.success { background: #e8f5e9; border-color: #a5d6a7; color: #2e7d32; }
.alert-modern.danger { background: #ffebee; border-color: #ef9a9a; color: #c62828; }
.alert-modern.info { background: #e3f2fd; border-color: #90caf9; color: #1565c0; }
.alert-modern.warning { background: #fff8e1; border-color: #ffe082; color: #f57c00; }

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

/* ============================================
   MODAL MODERN
   ============================================ */
.modal-modern .modal-content {
    border: none;
    border-radius: 16px;
    overflow: hidden;
    box-shadow: 0 20px 60px rgba(0,0,0,0.2);
}

.modal-modern .modal-header {
    color: white;
    padding: 18px 24px;
    border: none;
}

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

.modal-modern .modal-title {
    font-weight: 700;
    display: flex;
    align-items: center;
    gap: 10px;
    font-size: 1.1rem;
}

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

.modal-modern .modal-footer {
    padding: 16px 24px;
    border-top: 1px solid #f0f0f0;
    background: #f8fafc;
    display: flex;
    gap: 10px;
    justify-content: flex-end;
    flex-wrap: wrap;
}

/* ============================================
   CUSTOMER TABLE
   ============================================ */
.customer-table-wrapper {
    max-height: 500px;
    overflow-y: auto;
}

.customer-item {
    display: flex;
    align-items: center;
    gap: 12px;
    padding: 12px 16px;
    border-bottom: 1px solid #f0f0f0;
    transition: all 0.2s ease;
}

.customer-item:hover {
    background: #f8fafc;
}

.customer-item.selected {
    background: #e8f5e9;
}

.customer-checkbox-modern {
    width: 20px;
    height: 20px;
    cursor: pointer;
    accent-color: #25D366;
}

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

.customer-name {
    font-weight: 600;
    color: #003D7A;
    font-size: 0.9rem;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
}

.customer-meta {
    font-size: 0.78rem;
    color: #999;
    display: flex;
    gap: 10px;
    flex-wrap: wrap;
    margin-top: 2px;
}

.customer-phone-link {
    color: #25D366;
    text-decoration: none;
    font-weight: 600;
    font-size: 0.82rem;
    display: inline-flex;
    align-items: center;
    gap: 4px;
}

.customer-phone-link:hover {
    color: #128C7E;
}

/* ============================================
   TABS
   ============================================ */
.tabs-modern {
    display: flex;
    gap: 4px;
    background: #f8fafc;
    padding: 6px;
    border-radius: 12px;
    margin-bottom: 20px;
    overflow-x: auto;
}

.tab-modern {
    flex: 1;
    padding: 10px 16px;
    border: none;
    background: transparent;
    color: #666;
    font-weight: 600;
    font-size: 0.88rem;
    border-radius: 8px;
    cursor: pointer;
    transition: all 0.3s ease;
    display: flex;
    align-items: center;
    justify-content: center;
    gap: 6px;
    white-space: nowrap;
}

.tab-modern.active {
    background: white;
    color: #128C7E;
    box-shadow: 0 2px 8px rgba(0,0,0,0.08);
}

.tab-modern:hover:not(.active) {
    background: rgba(255,255,255,0.5);
}

.tab-content {
    display: none;
}

.tab-content.active {
    display: block;
}

/* ============================================
   CHAR COUNTER
   ============================================ */
.char-counter {
    display: inline-flex;
    align-items: center;
    gap: 6px;
    padding: 4px 10px;
    background: #f0f0f0;
    border-radius: 12px;
    font-size: 0.78rem;
    color: #666;
    font-weight: 600;
}

/* ============================================
   DIVIDER
   ============================================ */
.divider-modern {
    border: none;
    border-top: 2px dashed #e8f4f8;
    margin: 20px 0;
}

/* ============================================
   SELECTED COUNT BADGE
   ============================================ */
.selected-badge {
    display: inline-flex;
    align-items: center;
    gap: 5px;
    padding: 4px 12px;
    background: #25D366;
    color: white;
    border-radius: 20px;
    font-size: 0.8rem;
    font-weight: 700;
}

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

@media (max-width: 768px) {
    .page-header {
        flex-direction: column;
        align-items: stretch;
    }
    
    .page-title {
        font-size: 1.4rem;
    }
    
    .page-title i {
        font-size: 1.6rem;
    }
    
    .summary-row {
        grid-template-columns: repeat(2, 1fr);
        gap: 12px;
    }
    
    .summary-card {
        padding: 14px;
    }
    
    .summary-card-value {
        font-size: 1.2rem;
    }
    
    .summary-card-title {
        font-size: 0.75rem;
    }
    
    .summary-card-icon {
        width: 34px;
        height: 34px;
        font-size: 1rem;
    }
    
    .card-header-modern {
        padding: 15px 18px;
        font-size: 1rem;
    }
    
    .card-body-modern {
        padding: 16px;
    }
    
    .templates-grid {
        grid-template-columns: 1fr;
    }
    
    .tabs-modern {
        flex-wrap: nowrap;
        overflow-x: auto;
    }
    
    .tab-modern {
        flex: 0 0 auto;
        padding: 8px 14px;
        font-size: 0.82rem;
    }
    
    .modal-modern .modal-dialog {
        margin: 0;
        max-width: 100%;
        min-height: 100vh;
    }
    
    .modal-modern .modal-content {
        border-radius: 0;
        min-height: 100vh;
    }
    
    .btn-modern {
        padding: 11px 18px;
        font-size: 0.9rem;
    }
}

@media (max-width: 480px) {
    .page-title {
        font-size: 1.2rem;
        gap: 8px;
    }
    
    .summary-row {
        grid-template-columns: 1fr 1fr;
        gap: 10px;
    }
    
    .summary-card {
        padding: 12px;
    }
    
    .summary-card-value {
        font-size: 1.05rem;
    }
    
    .summary-card-footer {
        font-size: 0.7rem;
    }
    
    .card-header-modern {
        padding: 12px 15px;
        font-size: 0.95rem;
    }
    
    .card-body-modern {
        padding: 14px;
    }
    
    .template-card {
        padding: 14px;
    }
    
    .message-item {
        padding: 12px;
    }
    
    .customer-item {
        padding: 10px 12px;
    }
}
</style>

<div class="main-content">
    <!-- ============================================
         CONTENT WRAPPER
         ============================================ -->
    <div class="content-wrapper">
        <!-- Page Header -->
        <div class="page-header">
            <div>
                <h2 class="page-title">
                    <i class="bi bi-megaphone-fill"></i>
                    <span>Broadcast WhatsApp</span>
                </h2>
                <p class="page-subtitle">Kirim pesan massal ke pelanggan via WhatsApp</p>
            </div>
        </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; ?>
        
        <?php if ($flashError): ?>
            <div class="alert-modern danger">
                <i class="bi bi-exclamation-circle-fill"></i>
                <div><?= htmlspecialchars($flashError) ?></div>
            </div>
        <?php endif; ?>
        
        <?php if (!$isConfigured): ?>
            <div class="alert-modern warning">
                <i class="bi bi-exclamation-triangle-fill"></i>
                <div>
                    <strong>Wablas belum dikonfigurasi!</strong><br>
                    Silakan isi Token dan Base URL di 
                    <a href="/admin/wablas_settings.php" style="color: #f57c00; font-weight: 700;">Wablas Settings</a>.
                </div>
            </div>
        <?php endif; ?>

        <!-- Summary Cards -->
        <div class="summary-row">
            <div class="summary-card success">
                <div class="summary-card-header">
                    <h6 class="summary-card-title">📨 Pesan Terkirim</h6>
                    <div class="summary-card-icon">
                        <i class="bi bi-send-fill"></i>
                    </div>
                </div>
                <div class="summary-card-value"><?= number_format($totalMessagesSent) ?></div>
                <div class="summary-card-footer">Total keseluruhan</div>
            </div>
            <div class="summary-card primary">
                <div class="summary-card-header">
                    <h6 class="summary-card-title">📊 Total Broadcast</h6>
                    <div class="summary-card-icon">
                        <i class="bi bi-graph-up"></i>
                    </div>
                </div>
                <div class="summary-card-value"><?= number_format($totalBroadcasts) ?></div>
                <div class="summary-card-footer">Sesi broadcast</div>
            </div>
            <div class="summary-card warning">
                <div class="summary-card-header">
                    <h6 class="summary-card-title">👥 Total Customer</h6>
                    <div class="summary-card-icon">
                        <i class="bi bi-people-fill"></i>
                    </div>
                </div>
                <div class="summary-card-value"><?= count($customers) ?></div>
                <div class="summary-card-footer">Pelanggan terdaftar</div>
            </div>
            <div class="summary-card info">
                <div class="summary-card-header">
                    <h6 class="summary-card-title">📝 Template</h6>
                    <div class="summary-card-icon">
                        <i class="bi bi-file-earmark-text-fill"></i>
                    </div>
                </div>
                <div class="summary-card-value"><?= count($templates) ?></div>
                <div class="summary-card-footer">Template tersedia</div>
            </div>
        </div>

        <!-- Tabs -->
        <div class="tabs-modern">
            <button class="tab-modern active" onclick="switchTab('compose', this)">
                <i class="bi bi-chat-text-fill"></i> Compose
            </button>
            <button class="tab-modern" onclick="switchTab('templates', this)">
                <i class="bi bi-file-earmark-text"></i> Template (<?= count($templates) ?>)
            </button>
            <button class="tab-modern" onclick="switchTab('sent', this)">
                <i class="bi bi-check-circle"></i> Terkirim 
                <?php if (!empty($sentMessages)): ?>
                    <span class="selected-badge"><?= count($sentMessages) ?></span>
                <?php endif; ?>
            </button>
            <button class="tab-modern" onclick="switchTab('customers', this)">
                <i class="bi bi-people"></i> Customer
            </button>
        </div>

        <!-- TAB 1: COMPOSE -->
        <div class="tab-content active" id="tab-compose">
            <div class="row g-4">
                <div class="col-lg-7">
                    <div class="card-modern">
                        <div class="card-header-modern whatsapp">
                            <div class="title-left">
                                <i class="bi bi-chat-text-fill"></i>
                                <span>Compose Broadcast</span>
                            </div>
                        </div>
                        <div class="card-body-modern">
                            <form method="POST" id="broadcastForm">
                                <?= csrfField() ?>
                                <input type="hidden" name="action" value="send_broadcast">
                                
                                <div class="form-group-modern">
                                    <label class="form-label-modern">
                                        <i class="bi bi-tag-fill"></i> Judul Broadcast *
                                    </label>
                                    <input type="text" name="title" id="broadcastTitle" class="form-control-modern" 
                                           required placeholder="Contoh: Pengumuman Maintenance">
                                </div>
                                
                                <div class="form-group-modern">
                                    <label class="form-label-modern">
                                        <i class="bi bi-bullseye"></i> Target Penerima *
                                    </label>
                                    <select name="target_type" id="targetType" class="form-select-modern" onchange="toggleTargetOptions()">
                                        <option value="all_customers">👥 Semua Customer</option>
                                        <option value="selected_customers">✅ Customer Terpilih</option>
                                        <option value="branch">🏢 Cabang Tertentu</option>
                                        <option value="custom_numbers">📱 Nomor Custom</option>
                                    </select>
                                </div>
                                
                                <div id="targetBranchOption" style="display: none;" class="form-group-modern">
                                    <label class="form-label-modern">Pilih Cabang</label>
                                    <select name="target_branch" class="form-select-modern">
                                        <option value="">-- Pilih Cabang --</option>
                                        <?php foreach ($branches as $b): ?>
                                            <option value="<?= $b['id'] ?>"><?= htmlspecialchars($b['name']) ?></option>
                                        <?php endforeach; ?>
                                    </select>
                                </div>
                                
                                <div id="targetNumbersOption" style="display: none;" class="form-group-modern">
                                    <label class="form-label-modern">Nomor WhatsApp</label>
                                    <textarea name="custom_numbers" class="form-control-modern" rows="3" 
                                              placeholder="6281234567890, 6289876543210"></textarea>
                                    <small class="form-hint">Pisahkan dengan koma, spasi, atau baris baru</small>
                                </div>
                                
                                <div id="selectedCustomersInfo" style="display: none;" class="alert-modern info">
                                    <i class="bi bi-info-circle-fill"></i>
                                    <div>
                                        <strong id="selectedCountDisplay">0</strong> customer terpilih. 
                                        <a href="#" onclick="switchTabByName('customers'); return false;" style="color: #1565c0; font-weight: 700;">Pilih di tab Customer</a>
                                    </div>
                                </div>
                                
                                <div class="form-group-modern">
                                    <label class="form-label-modern">
                                        <i class="bi bi-chat-left-text-fill"></i> Pesan Broadcast *
                                    </label>
                                    <textarea name="message" id="messageInput" class="form-control-modern" rows="8" required 
                                              placeholder="Ketik pesan broadcast di sini..."></textarea>
                                    <div style="display: flex; justify-content: space-between; align-items: center; margin-top: 6px;">
                                        <small class="form-hint" style="margin: 0;">Gunakan template untuk mempercepat</small>
                                        <span class="char-counter">
                                            <i class="bi bi-type"></i>
                                            <span id="charCount">0</span> karakter
                                        </span>
                                    </div>
                                </div>
                                
                                <button type="submit" class="btn-modern whatsapp" <?= !$isConfigured ? 'disabled' : '' ?>
                                        onclick="return confirmBroadcast()">
                                    <i class="bi bi-send-fill"></i>
                                    <span>Kirim Broadcast Sekarang</span>
                                </button>
                            </form>
                        </div>
                    </div>
                </div>
                
                <div class="col-lg-5">
                    <div class="card-modern">
                        <div class="card-header-modern primary">
                            <div class="title-left">
                                <i class="bi bi-lightning-fill"></i>
                                <span>Quick Templates</span>
                            </div>
                        </div>
                        <div class="card-body-modern">
                            <?php if (empty($templates)): ?>
                                <div class="empty-state">
                                    <div class="empty-state-icon">
                                        <i class="bi bi-file-earmark-text"></i>
                                    </div>
                                    <h5 class="empty-state-title">Belum ada template</h5>
                                    <p class="empty-state-subtitle">Buat template di tab Template</p>
                                </div>
                            <?php else: ?>
                                <div style="display: grid; gap: 10px;">
                                    <?php foreach (array_slice($templates, 0, 5) as $t): ?>
                                        <button type="button" class="template-card" style="cursor: pointer; margin: 0;"
                                                onclick='useTemplate(<?= json_encode($t) ?>)'>
                                            <div class="template-card-header">
                                                <div class="template-icon"><?= htmlspecialchars($t['icon'] ?? '📝') ?></div>
                                                <h6 class="template-name"><?= htmlspecialchars($t['name']) ?></h6>
                                            </div>
                                            <div class="template-preview"><?= htmlspecialchars($t['content']) ?></div>
                                        </button>
                                    <?php endforeach; ?>
                                </div>
                                <?php if (count($templates) > 5): ?>
                                    <button type="button" class="btn-modern outline btn-sm-modern" style="width: 100%; margin-top: 12px;"
                                            onclick="switchTabByName('templates')">
                                        <i class="bi bi-arrow-right"></i> Lihat Semua Template
                                    </button>
                                <?php endif; ?>
                            <?php endif; ?>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- TAB 2: TEMPLATES -->
        <div class="tab-content" id="tab-templates">
            <div class="card-modern">
                <div class="card-header-modern primary">
                    <div class="title-left">
                        <i class="bi bi-file-earmark-text-fill"></i>
                        <span>Template Pesan</span>
                    </div>
                    <button class="btn-modern success btn-sm-modern" data-bs-toggle="modal" data-bs-target="#templateModal" onclick="resetTemplateForm()">
                        <i class="bi bi-plus-circle-fill"></i> Tambah
                    </button>
                </div>
                <div class="card-body-modern">
                    <?php if (empty($templates)): ?>
                        <div class="empty-state">
                            <div class="empty-state-icon">
                                <i class="bi bi-file-earmark-text"></i>
                            </div>
                            <h5 class="empty-state-title">Belum ada template</h5>
                            <p class="empty-state-subtitle">Klik tombol "Tambah" untuk membuat template pertama</p>
                        </div>
                    <?php else: ?>
                        <div class="templates-grid">
                            <?php foreach ($templates as $t): ?>
                                <div class="template-card" style="cursor: default;">
                                    <div class="template-card-header">
                                        <div class="template-icon"><?= htmlspecialchars($t['icon'] ?? '📝') ?></div>
                                        <h6 class="template-name"><?= htmlspecialchars($t['name']) ?></h6>
                                    </div>
                                    <div class="template-preview"><?= htmlspecialchars($t['content']) ?></div>
                                    <div class="template-actions">
                                        <button type="button" class="btn-template use" onclick='useTemplate(<?= json_encode($t) ?>)'>
                                            <i class="bi bi-check-lg"></i> Pakai
                                        </button>
                                        <button type="button" class="btn-template edit" onclick='editTemplate(<?= json_encode($t) ?>)'>
                                            <i class="bi bi-pencil-fill"></i>
                                        </button>
                                        <button type="button" class="btn-template delete" onclick="confirmDeleteTemplate(<?= $t['id'] ?>, '<?= htmlspecialchars(addslashes($t['name'])) ?>')">
                                            <i class="bi bi-trash-fill"></i>
                                        </button>
                                    </div>
                                </div>
                            <?php endforeach; ?>
                        </div>
                    <?php endif; ?>
                </div>
            </div>
        </div>

        <!-- TAB 3: SENT MESSAGES -->
        <div class="tab-content" id="tab-sent">
            <div class="card-modern">
                <div class="card-header-modern success">
                    <div class="title-left">
                        <i class="bi bi-check-circle-fill"></i>
                        <span>Pesan Terkirim</span>
                        <?php if (!empty($sentMessages)): ?>
                            <span class="selected-badge"><?= count($sentMessages) ?></span>
                        <?php endif; ?>
                    </div>
                </div>
                <?php if (empty($sentMessages)): ?>
                    <div class="empty-state">
                        <div class="empty-state-icon">
                            <i class="bi bi-inbox"></i>
                        </div>
                        <h5 class="empty-state-title">Belum ada pesan terkirim</h5>
                        <p class="empty-state-subtitle">Kirim broadcast terlebih dahulu</p>
                    </div>
                <?php else: ?>
                    <div class="message-list">
                        <?php foreach ($sentMessages as $index => $msg): ?>
                            <div class="message-item" data-bs-toggle="modal" data-bs-target="#messageModal<?= $index ?>">
                                <div class="message-avatar">
                                    <?= strtoupper(substr($msg['name'], 0, 1)) ?>
                                </div>
                                <div class="message-content">
                                    <div class="message-header">
                                        <div class="message-name"><?= htmlspecialchars($msg['name']) ?></div>
                                        <div class="message-time"><?= htmlspecialchars($msg['timestamp']) ?></div>
                                    </div>
                                    <div class="message-phone">
                                        <i class="bi bi-telephone-fill" style="color: #25D366;"></i>
                                        <code><?= htmlspecialchars($msg['phone']) ?></code>
                                        <span class="message-status">
                                            <i class="bi bi-check-all"></i> Terkirim
                                        </span>
                                    </div>
                                    <div class="message-preview"><?= htmlspecialchars(substr($msg['message'], 0, 100)) ?><?= strlen($msg['message']) > 100 ? '...' : '' ?></div>
                                </div>
                                <i class="bi bi-chevron-right" style="color: #ccc; margin-top: 10px;"></i>
                            </div>
                        <?php endforeach; ?>
                    </div>
                <?php endif; ?>
            </div>
        </div>

        <!-- TAB 4: CUSTOMERS -->
        <div class="tab-content" id="tab-customers">
            <div class="card-modern">
                <div class="card-header-modern whatsapp">
                    <div class="title-left">
                        <i class="bi bi-people-fill"></i>
                        <span>Pilih Customer</span>
                        <span class="selected-badge" id="selectedCountBadge">0 dipilih</span>
                    </div>
                    <div style="display: flex; gap: 6px;">
                        <button type="button" class="btn-modern success btn-sm-modern" onclick="selectAllCustomers()">
                            <i class="bi bi-check-all"></i> Semua
                        </button>
                        <button type="button" class="btn-modern secondary btn-sm-modern" onclick="deselectAllCustomers()">
                            <i class="bi bi-x-lg"></i> Reset
                        </button>
                    </div>
                </div>
                
                <?php if (empty($customers)): ?>
                    <div class="empty-state">
                        <div class="empty-state-icon">
                            <i class="bi bi-inbox"></i>
                        </div>
                        <h5 class="empty-state-title">Tidak ada customer</h5>
                        <p class="empty-state-subtitle">Tambahkan customer terlebih dahulu</p>
                    </div>
                <?php else: ?>
                    <div style="padding: 12px 16px; background: #f8fafc; border-bottom: 1px solid #f0f0f0;">
                        <input type="text" id="customerSearch" class="form-control-modern" 
                               placeholder="🔍 Cari nama, nomor HP, atau nomor pelanggan..." 
                               oninput="filterCustomers()" style="padding: 10px 14px; font-size: 0.9rem;">
                    </div>
                    <div class="customer-table-wrapper" id="customerList">
                        <?php foreach ($customers as $c): ?>
                            <?php if (!empty($c['phone'])): ?>
                                <div class="customer-item" data-name="<?= htmlspecialchars(strtolower($c['name'])) ?>" 
                                     data-phone="<?= htmlspecialchars($c['phone']) ?>" 
                                     data-number="<?= htmlspecialchars($c['customer_number'] ?? '') ?>">
                                    <input type="checkbox" class="customer-checkbox-modern" 
                                           data-customer-id="<?= $c['id'] ?>"
                                           onchange="updateSelectedCount()">
                                    <div class="customer-info">
                                        <div class="customer-name"><?= htmlspecialchars($c['name']) ?></div>
                                        <div class="customer-meta">
                                            <span>📋 <?= htmlspecialchars($c['customer_number'] ?? '-') ?></span>
                                            <a href="https://wa.me/<?= preg_replace('/^0/', '62', $c['phone']) ?>" 
                                               target="_blank" class="customer-phone-link">
                                                <i class="bi bi-whatsapp"></i>
                                                <?= htmlspecialchars($c['phone']) ?>
                                            </a>
                                            <?php if (!empty($c['branch_name'])): ?>
                                                <span>🏢 <?= htmlspecialchars($c['branch_name']) ?></span>
                                            <?php endif; ?>
                                        </div>
                                    </div>
                                </div>
                            <?php endif; ?>
                        <?php endforeach; ?>
                    </div>
                <?php endif; ?>
            </div>
        </div>

        <!-- DEBUG INFORMATION -->
        <?php if (!empty($debugLogs)): ?>
            <div class="card-modern" style="margin-top: 20px;">
                <div class="card-header-modern warning">
                    <div class="title-left">
                        <i class="bi bi-bug-fill"></i>
                        <span>Debug Information (Pesan Gagal)</span>
                    </div>
                </div>
                <div class="card-body-modern" style="padding: 0;">
                    <div style="overflow-x: auto;">
                        <table style="width: 100%; border-collapse: collapse; font-size: 0.85rem;">
                            <thead style="background: #fff8e1;">
                                <tr>
                                    <th style="padding: 12px; text-align: left; font-weight: 700; color: #f57c00;">No. Pelanggan</th>
                                    <th style="padding: 12px; text-align: left; font-weight: 700; color: #f57c00;">Nama</th>
                                    <th style="padding: 12px; text-align: left; font-weight: 700; color: #f57c00;">No. HP</th>
                                    <th style="padding: 12px; text-align: left; font-weight: 700; color: #f57c00;">HTTP</th>
                                    <th style="padding: 12px; text-align: left; font-weight: 700; color: #f57c00;">Error</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php foreach ($debugLogs as $log): ?>
                                    <tr style="border-top: 1px solid #f0f0f0; background: #ffebee;">
                                        <td style="padding: 10px 12px;"><code><?= htmlspecialchars($log['customer_number']) ?></code></td>
                                        <td style="padding: 10px 12px;"><?= htmlspecialchars($log['name']) ?></td>
                                        <td style="padding: 10px 12px;"><code><?= htmlspecialchars($log['phone']) ?></code></td>
                                        <td style="padding: 10px 12px;"><code><?= $log['http_code'] ?></code></td>
                                        <td style="padding: 10px 12px; font-size: 0.8rem;"><?= htmlspecialchars($log['error_message']) ?></td>
                                    </tr>
                                <?php endforeach; ?>
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        <?php endif; ?>
    </div>
    <!-- End Content Wrapper -->
</div>

<!-- Modal Add/Edit Template -->
<div class="modal fade modal-modern" id="templateModal" tabindex="-1">
    <div class="modal-dialog modal-lg modal-dialog-centered">
        <form method="POST" id="templateForm">
            <?= csrfField() ?>
            <input type="hidden" name="template_id" id="templateId">
            <input type="hidden" name="action" id="templateAction" value="create_template">
            <div class="modal-content">
                <div class="modal-header primary">
                    <h5 class="modal-title" id="templateModalTitle">
                        <i class="bi bi-plus-circle-fill"></i>
                        <span>Tambah Template Baru</span>
                    </h5>
                    <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    <div style="display: grid; grid-template-columns: 100px 1fr; gap: 16px;">
                        <div class="form-group-modern">
                            <label class="form-label-modern">
                                <i class="bi bi-emoji-smile"></i> Icon
                            </label>
                            <input type="text" name="template_icon" id="templateIcon" class="form-control-modern" 
                                   maxlength="2" value="📝" style="text-align: center; font-size: 1.5rem;">
                        </div>
                        <div class="form-group-modern">
                            <label class="form-label-modern">
                                <i class="bi bi-tag-fill"></i> Nama Template *
                            </label>
                            <input type="text" name="template_name" id="templateName" class="form-control-modern" 
                                   required placeholder="Contoh: Reminder Tagihan">
                        </div>
                    </div>
                    
                    <div class="form-group-modern">
                        <label class="form-label-modern">
                            <i class="bi bi-chat-left-text-fill"></i> Isi Pesan *
                        </label>
                        <textarea name="template_content" id="templateContent" class="form-control-modern" rows="10" 
                                  required placeholder="Ketik isi template pesan di sini..."></textarea>
                        <small class="form-hint">Gunakan emoji untuk pesan yang lebih menarik</small>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn-modern secondary" data-bs-dismiss="modal">Batal</button>
                    <button type="submit" class="btn-modern primary">
                        <i class="bi bi-save-fill"></i> Simpan Template
                    </button>
                </div>
            </div>
        </form>
    </div>
</div>

<!-- Modal Delete Template -->
<div class="modal fade modal-modern" id="deleteTemplateModal" tabindex="-1">
    <div class="modal-dialog modal-dialog-centered">
        <form method="POST">
            <?= csrfField() ?>
            <input type="hidden" name="action" value="delete_template">
            <input type="hidden" name="template_id" id="deleteTemplateId">
            <div class="modal-content">
                <div class="modal-header danger">
                    <h5 class="modal-title">
                        <i class="bi bi-exclamation-triangle-fill"></i>
                        Hapus Template
                    </h5>
                    <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    <div style="background: #ffebee; border: 2px solid #ef9a9a; border-radius: 12px; padding: 16px; margin-bottom: 16px; display: flex; align-items: center; gap: 12px;">
                        <i class="bi bi-exclamation-triangle-fill" style="color: #c62828; font-size: 1.5rem;"></i>
                        <div style="color: #842029;">
                            <strong>Peringatan!</strong><br>
                            <small>Tindakan ini tidak dapat dibatalkan.</small>
                        </div>
                    </div>
                    <p style="color: #333; margin: 0;">
                        Apakah Anda yakin ingin menghapus template <strong id="deleteTemplateName"></strong>?
                    </p>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn-modern secondary" data-bs-dismiss="modal">Batal</button>
                    <button type="submit" class="btn-modern danger">
                        <i class="bi bi-trash-fill"></i> Hapus
                    </button>
                </div>
            </div>
        </form>
    </div>
</div>

<!-- Modal Message Detail -->
<?php foreach ($sentMessages as $index => $msg): ?>
<div class="modal fade modal-modern" id="messageModal<?= $index ?>" tabindex="-1">
    <div class="modal-dialog modal-dialog-centered modal-lg">
        <div class="modal-content">
            <div class="modal-header whatsapp">
                <h5 class="modal-title">
                    <i class="bi bi-whatsapp"></i>
                    Detail Pesan Terkirim
                </h5>
                <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 16px; margin-bottom: 16px;">
                    <div>
                        <small style="color: #999; display: block; margin-bottom: 4px;">Nama Penerima</small>
                        <strong style="color: #003D7A;"><?= htmlspecialchars($msg['name']) ?></strong>
                    </div>
                    <div>
                        <small style="color: #999; display: block; margin-bottom: 4px;">No. Pelanggan</small>
                        <strong style="color: #003D7A;"><code><?= htmlspecialchars($msg['customer_number']) ?></code></strong>
                    </div>
                </div>
                <div style="margin-bottom: 16px;">
                    <small style="color: #999; display: block; margin-bottom: 4px;">Nomor WhatsApp</small>
                    <a href="https://wa.me/<?= $msg['phone'] ?>" target="_blank" style="color: #25D366; font-weight: 700; text-decoration: none; display: inline-flex; align-items: center; gap: 6px;">
                        <i class="bi bi-whatsapp"></i>
                        <strong><?= htmlspecialchars($msg['phone']) ?></strong>
                    </a>
                </div>
                <div style="margin-bottom: 16px;">
                    <small style="color: #999; display: block; margin-bottom: 4px;">Waktu Kirim</small>
                    <strong style="color: #003D7A;"><?= date('d M Y') ?> <?= htmlspecialchars($msg['timestamp']) ?></strong>
                </div>
                <hr class="divider-modern">
                <div>
                    <small style="color: #999; display: block; margin-bottom: 8px;">Isi Pesan:</small>
                    <div style="background: #f8fafc; border: 2px solid #e8f4f8; border-radius: 12px; padding: 16px; white-space: pre-wrap; font-family: inherit; max-height: 400px; overflow-y: auto; color: #333;">
                        <?= htmlspecialchars($msg['message']) ?>
                    </div>
                </div>
            </div>
            <div class="modal-footer">
                <a href="https://wa.me/<?= $msg['phone'] ?>" target="_blank" class="btn-modern success">
                    <i class="bi bi-whatsapp"></i> Chat di WhatsApp
                </a>
                <button type="button" class="btn-modern secondary" data-bs-dismiss="modal">Tutup</button>
            </div>
        </div>
    </div>
</div>
<?php endforeach; ?>

<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' : '';
    }
}

function switchTab(tabName, btn) {
    document.querySelectorAll('.tab-content').forEach(el => el.classList.remove('active'));
    document.querySelectorAll('.tab-modern').forEach(el => el.classList.remove('active'));
    document.getElementById('tab-' + tabName).classList.add('active');
    if (btn) btn.classList.add('active');
}

function switchTabByName(tabName) {
    const tabs = document.querySelectorAll('.tab-modern');
    const tabMap = { compose: 0, templates: 1, sent: 2, customers: 3 };
    if (tabMap[tabName] !== undefined) {
        switchTab(tabName, tabs[tabMap[tabName]]);
    }
}

function toggleTargetOptions() {
    const targetType = document.getElementById('targetType').value;
    document.getElementById('targetBranchOption').style.display = targetType === 'branch' ? 'block' : 'none';
    document.getElementById('targetNumbersOption').style.display = targetType === 'custom_numbers' ? 'block' : 'none';
    document.getElementById('selectedCustomersInfo').style.display = targetType === 'selected_customers' ? 'block' : 'none';
}

document.getElementById('messageInput').addEventListener('input', function() {
    document.getElementById('charCount').textContent = this.value.length;
});

function useTemplate(t) {
    document.getElementById('messageInput').value = t.content;
    document.getElementById('charCount').textContent = t.content.length;
    if (!document.getElementById('broadcastTitle').value) {
        document.getElementById('broadcastTitle').value = t.name;
    }
    switchTabByName('compose');
    document.getElementById('messageInput').focus();
    window.scrollTo({ top: 0, behavior: 'smooth' });
}

function resetTemplateForm() {
    document.getElementById('templateForm').reset();
    document.getElementById('templateId').value = '';
    document.getElementById('templateAction').value = 'create_template';
    document.getElementById('templateIcon').value = '📝';
    document.getElementById('templateModalTitle').innerHTML = '<i class="bi bi-plus-circle-fill"></i><span>Tambah Template Baru</span>';
}

function editTemplate(t) {
    document.getElementById('templateId').value = t.id;
    document.getElementById('templateAction').value = 'update_template';
    document.getElementById('templateIcon').value = t.icon || '📝';
    document.getElementById('templateName').value = t.name;
    document.getElementById('templateContent').value = t.content;
    document.getElementById('templateModalTitle').innerHTML = '<i class="bi bi-pencil-fill"></i><span>Edit Template: ' + t.name + '</span>';
    new bootstrap.Modal(document.getElementById('templateModal')).show();
}

function confirmDeleteTemplate(id, name) {
    document.getElementById('deleteTemplateId').value = id;
    document.getElementById('deleteTemplateName').textContent = name;
    new bootstrap.Modal(document.getElementById('deleteTemplateModal')).show();
}

function selectAllCustomers() {
    document.querySelectorAll('.customer-checkbox-modern').forEach(cb => {
        if (cb.closest('.customer-item').style.display !== 'none') {
            cb.checked = true;
        }
    });
    updateSelectedCount();
}

function deselectAllCustomers() {
    document.querySelectorAll('.customer-checkbox-modern').forEach(cb => cb.checked = false);
    updateSelectedCount();
}

function updateSelectedCount() {
    const count = document.querySelectorAll('.customer-checkbox-modern:checked').length;
    document.getElementById('selectedCountBadge').textContent = count + ' dipilih';
    document.getElementById('selectedCountDisplay').textContent = count;
    
    document.querySelectorAll('input[name="customers[]"]').forEach(el => el.remove());
    const form = document.getElementById('broadcastForm');
    document.querySelectorAll('.customer-checkbox-modern:checked').forEach(cb => {
        const input = document.createElement('input');
        input.type = 'hidden';
        input.name = 'customers[]';
        input.value = cb.dataset.customerId;
        form.appendChild(input);
    });
}

function filterCustomers() {
    const query = document.getElementById('customerSearch').value.toLowerCase();
    document.querySelectorAll('.customer-item').forEach(item => {
        const name = item.dataset.name || '';
        const phone = item.dataset.phone || '';
        const number = item.dataset.number || '';
        const match = name.includes(query) || phone.includes(query) || number.includes(query);
        item.style.display = match ? 'flex' : 'none';
    });
}

function confirmBroadcast() {
    const targetType = document.getElementById('targetType').value;
    let message = 'Apakah Anda yakin ingin mengirim broadcast ini?';
    
    if (targetType === 'all_customers') {
        message = `Kirim ke SEMUA customer (${<?= count($customers) ?>} nomor)?`;
    } else if (targetType === 'selected_customers') {
        const count = document.querySelectorAll('.customer-checkbox-modern:checked').length;
        if (count === 0) {
            alert('Pilih minimal 1 customer terlebih dahulu!');
            return false;
        }
        message = `Kirim ke ${count} customer yang dipilih?`;
    }
    
    return confirm(message + '\n\nPastikan pesan sudah benar sebelum dikirim.');
}

function adjustModalGrid() {
    const grids = document.querySelectorAll('.modal-body > div[style*="grid-template-columns"]');
    if (window.innerWidth < 576) {
        grids.forEach(grid => {
            if (grid.style.gridTemplateColumns.includes('100px')) {
                grid.style.gridTemplateColumns = '1fr';
            }
        });
    }
}

window.addEventListener('resize', adjustModalGrid);
window.addEventListener('load', adjustModalGrid);

document.querySelectorAll('.customer-item').forEach(item => {
    item.addEventListener('click', function(e) {
        if (e.target.type === 'checkbox' || e.target.tagName === 'A') return;
        const cb = this.querySelector('.customer-checkbox-modern');
        cb.checked = !cb.checked;
        updateSelectedCount();
    });
});
</script>

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