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

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

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

$db = db();

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

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

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

// ============================================================================
// 2. LOAD CONFIG WABLAS KHUSUS CABANG INI
// ============================================================================
$config = [];
$hasBranchColumn = false;

try {
    $checkCol = $db->query("SHOW COLUMNS FROM wa_config LIKE 'branch_id'")->fetch();
    $hasBranchColumn = !empty($checkCol);
} catch (\Throwable $e) {
    $hasBranchColumn = false;
}

try {
    if ($hasBranchColumn) {
        $stmt = $db->prepare("
            SELECT setting_key, setting_value 
            FROM wa_config 
            WHERE branch_id = ? AND setting_key IN ('wablas_token', 'wablas_base_url')
        ");
        $stmt->execute([$userBranchId]);
    } else {
        $stmt = $db->prepare("
            SELECT setting_key, setting_value 
            FROM wa_config 
            WHERE setting_key IN (?, ?)
        ");
        $stmt->execute([
            'wablas_token_branch_' . $userBranchId,
            'wablas_base_url_branch_' . $userBranchId
        ]);
    }
    
    while ($row = $stmt->fetch()) {
        $key = $row['setting_key'];
        if (!$hasBranchColumn) {
            $key = str_replace('_branch_' . $userBranchId, '', $key);
        }
        $config[$key] = $row['setting_value'];
    }
} catch (\Throwable $e) {}

$wablasToken = $config['wablas_token'] ?? '';
$wablasBaseUrl = rtrim($config['wablas_base_url'] ?? '', '/');
$isConfigured = !empty($wablasToken) && !empty($wablasBaseUrl);

// ============================================================================
// 3. FUNGSI KIRIM PESAN
// ============================================================================
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
    ];
}

// ============================================================================
// 4. LOAD TEMPLATE DARI DATABASE (Untuk Cron & Manual)
// ============================================================================
$dbTemplates = [];
try {
    $tableExists = $db->query("SHOW TABLES LIKE 'wa_templates'")->fetch();
    if ($tableExists) {
        $stmt = $db->prepare("SELECT slug, message FROM wa_templates WHERE branch_id IS NULL OR branch_id = ?");
        $stmt->execute([$userBranchId]);
        while ($row = $stmt->fetch()) {
            $dbTemplates[$row['slug']] = $row['message'];
        }
    }
} catch (\Throwable $e) {
    $dbTemplates = [];
}

// ============================================================================
// 5. LOAD CUSTOMER (DENGAN JOIN PAKET - DIPERBAIKI)
// ============================================================================
$customers = [];
try {
    // ✅ DIPERBAIKI: JOIN ke tabel packages untuk ambil nama paket
    $stmt = $db->prepare("
        SELECT c.id, c.customer_number, c.name, c.phone, c.branch_id, c.package_id, c.status,
               COALESCE(p.name, '-') as package_name
        FROM customers c
        LEFT JOIN packages p ON c.package_id = p.id
        WHERE c.branch_id = ? AND c.phone IS NOT NULL AND c.phone != ''
        ORDER BY c.name ASC
    ");
    $stmt->execute([$userBranchId]);
    $customers = $stmt->fetchAll();
} catch (\Throwable $e) {
    $customers = [];
}

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

// ============================================================================
// 6. HANDLE BROADCAST (DENGAN PLACEHOLDER REPLACEMENT)
// ============================================================================
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']);
        
        // Hapus emoji (Wablas tidak support)
        $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 Anda belum dikonfigurasi. Silakan isi Token dan Base URL di <a href="/branch/whatsapp_settings.php" style="color: #c62828; font-weight: 700;">halaman pengaturan WA cabang</a>.';
        } else {
            // ✅ Helper: Build target numbers dengan data lengkap (untuk placeholder)
            $buildTarget = function($c) {
                $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;
                
                return [
                    'phone' => $phone,
                    'name' => $c['name'],
                    'customer_number' => $c['customer_number'] ?? '-',
                    'package_name' => $c['package_name'] ?? '-',
                    'raw_phone' => $c['phone'] ?? ''
                ];
            };
            
            switch ($targetType) {
                case 'all_customers':
                    foreach ($customers as $c) {
                        $targetNumbers[] = $buildTarget($c);
                    }
                    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)) {
                                $targetNumbers[] = $buildTarget($c);
                            }
                        }
                    }
                    break;
                    
                case 'by_package':
                    $packageId = (int)($_POST['target_package'] ?? 0);
                    if ($packageId <= 0) {
                        $error = 'Pilih paket target';
                    } else {
                        foreach ($customers as $c) {
                            if ((int)($c['package_id'] ?? 0) === $packageId) {
                                $targetNumbers[] = $buildTarget($c);
                            }
                        }
                        if (empty($targetNumbers)) {
                            $error = 'Tidak ada pelanggan dengan paket tersebut di cabang Anda';
                        }
                    }
                    break;
                    
                case 'by_status':
                    $status = $_POST['target_status'] ?? 'active';
                    foreach ($customers as $c) {
                        if (($c['status'] ?? '') === $status) {
                            $targetNumbers[] = $buildTarget($c);
                        }
                    }
                    if (empty($targetNumbers)) {
                        $error = 'Tidak ada pelanggan dengan status tersebut di cabang Anda';
                    }
                    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' => '-',
                                'package_name' => '-',
                                'raw_phone' => $num
                            ];
                        }
                    }
                    break;
                    
                default:
                    $error = 'Tipe target tidak valid';
            }
            
            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) {
                    // ✅ DIPERBAIKI: Replace placeholder dengan data pelanggan
                    $personalizedMessage = str_replace(
                        ['[nama]', '[Nama]', '[NAME]', 
                         '[customer_number]', '[Customer Number]', 
                         '[paket]', '[Paket]', '[PACKAGE]', 
                         '[phone]', '[Phone]', '[no_hp]',
                         '[Link Pembayaran]', '[link_pembayaran]', '[link]'],
                        [
                            $target['name'],
                            $target['name'],
                            strtoupper($target['name']),
                            $target['customer_number'],
                            $target['customer_number'],
                            $target['package_name'],
                            $target['package_name'],
                            strtoupper($target['package_name']),
                            $target['raw_phone'],
                            $target['phone'],
                            $target['raw_phone'],
                            // ⚠️ GANTI URL DI BAWAH DENGAN DOMAIN ANDA!
                            'https://lintasfiber.my.id/public/pay.php?id=' . urlencode($target['customer_number']),
                            'https://lintasfiber.my.id/public/pay.php?id=' . urlencode($target['customer_number']),
                            'https://lintasfiber.my.id/public/pay.php?id=' . urlencode($target['customer_number'])
                        ],
                        $message
                    );
                    
                    $result = sendWablasMessage($target['phone'], $personalizedMessage, $wablasBaseUrl, $wablasToken);
                    
                    if ($result['success']) {
                        $totalSent++;
                        $sentMessages[] = [
                            'phone' => $target['phone'],
                            'name' => $target['name'],
                            'customer_number' => $target['customer_number'],
                            'message' => $personalizedMessage,
                            '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); // Delay 0.5 detik antar pesan (anti-banned)
                }
                
                // Log ke database
                try {
                    $checkColLog = $db->query("SHOW COLUMNS FROM broadcast_logs LIKE 'branch_id'")->fetch();
                    
                    if ($checkColLog) {
                        $db->prepare("INSERT INTO broadcast_logs (title, message, target_type, total_targets, sent_count, failed_count, status, branch_id, created_by, created_at) 
                                     VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, NOW())")
                           ->execute([
                               $title, $message, $targetType,
                               count($targetNumbers), $totalSent, $totalFailed,
                               $totalFailed > 0 ? 'partial' : 'success',
                               $userBranchId, currentUserId()
                           ]);
                    } else {
                        $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! Total Target: {$broadcastResult['total']} | Berhasil: {$broadcastResult['sent']} | Gagal: {$broadcastResult['failed']}";
                } else {
                    $error = "❌ Semua pesan gagal dikirim! Total: {$broadcastResult['total']} | Gagal: {$broadcastResult['failed']}";
                }
                
                logActivity($currentUserId, 'broadcast', 
                    "Broadcast '{$title}' dari cabang {$userBranchName} - Target: {$broadcastResult['total']}, Berhasil: {$totalSent}, Gagal: {$totalFailed}");
            }
        }
    }
}

// ============================================================================
// 7. LOAD PAKET
// ============================================================================
$packages = [];
try {
    $stmt = $db->prepare("
        SELECT id, name FROM packages 
        WHERE status = 'active' 
        AND (branch_id IS NULL OR branch_id = ?)
        ORDER BY name ASC
    ");
    $stmt->execute([$userBranchId]);
    $packages = $stmt->fetchAll();
} catch (\Throwable $e) {}

$totalCustomers = count($customers);
$customersWithPhone = count(array_filter($customers, fn($c) => !empty($c['phone'])));

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

<style>
/* === NAVBAR MODERN === */
.navbar-modern { background: linear-gradient(135deg, #25D366 0%, #128C7E 100%); padding: 12px 20px; display: flex; align-items: center; justify-content: space-between; box-shadow: 0 4px 15px rgba(0,0,0,0.15); position: sticky; top: 0; z-index: 1000; }
.navbar-left { display: flex; align-items: center; gap: 14px; flex: 1; min-width: 0; }
.burger-btn { background: rgba(255,255,255,0.2); border: 2px solid rgba(255,255,255,0.3); color: white; width: 42px; height: 42px; border-radius: 12px; cursor: pointer; display: flex; align-items: center; justify-content: center; font-size: 1.3rem; transition: all 0.3s ease; flex-shrink: 0; }
.burger-btn:hover, .burger-btn:active { background: rgba(255,255,255,0.35); transform: scale(1.05); }
.navbar-info { min-width: 0; flex: 1; }
.navbar-greeting { color: rgba(255,255,255,0.85); font-size: 0.75rem; margin: 0; }
.navbar-title { color: white; font-size: 1.15rem; font-weight: 700; margin: 2px 0 0; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
.navbar-right { display: flex; align-items: center; gap: 10px; flex-shrink: 0; }
.navbar-badge { background: rgba(255,255,255,0.2); color: white; padding: 6px 12px; border-radius: 20px; font-size: 0.8rem; font-weight: 500; display: inline-flex; align-items: center; gap: 6px; white-space: nowrap; }
.main-content { padding: 16px; max-width: 900px; margin: 0 auto; display: flex; flex-direction: column; gap: 20px; }
.page-header { margin-bottom: 20px; display: flex; justify-content: space-between; align-items: center; flex-wrap: wrap; gap: 15px; }
.page-title { font-size: 1.6rem; font-weight: 700; color: #003D7A; margin: 0; display: flex; align-items: center; gap: 10px; flex-wrap: wrap; }
.page-title i { font-size: 1.8rem; color: #25D366; }
.branch-badge { background: linear-gradient(135deg, #e3f2fd 0%, #bbdefb 100%); color: #003D7A; padding: 4px 12px; border-radius: 20px; font-size: 0.8rem; font-weight: 600; display: inline-flex; align-items: center; gap: 5px; }
.summary-row { display: grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); gap: 14px; margin-bottom: 22px; }
.summary-card { background: white; border-radius: 16px; padding: 18px; box-shadow: 0 4px 15px rgba(0,0,0,0.06); position: relative; overflow: hidden; transition: all 0.3s ease; border-left: 4px solid transparent; }
.summary-card:hover { transform: translateY(-4px); box-shadow: 0 12px 25px rgba(0,0,0,0.1); }
.summary-card.whatsapp { border-left-color: #25D366; }
.summary-card.success { border-left-color: #00C853; }
.summary-card.primary { border-left-color: #0066CC; }
.summary-card.danger { border-left-color: #DC3545; }
.summary-card-header { display: flex; align-items: center; justify-content: space-between; margin-bottom: 10px; }
.summary-card-title { color: #666; font-size: 0.78rem; font-weight: 600; margin: 0; text-transform: uppercase; letter-spacing: 0.5px; }
.summary-card-icon { width: 40px; height: 40px; border-radius: 12px; display: flex; align-items: center; justify-content: center; color: white; font-size: 1.15rem; }
.summary-card.whatsapp .summary-card-icon { background: linear-gradient(135deg, #25D366 0%, #128C7E 100%); }
.summary-card.success .summary-card-icon { background: linear-gradient(135deg, #00C853 0%, #69F0AE 100%); }
.summary-card.primary .summary-card-icon { background: linear-gradient(135deg, #0066CC 0%, #00B4FF 100%); }
.summary-card.danger .summary-card-icon { background: linear-gradient(135deg, #DC3545 0%, #FF6B7A 100%); }
.summary-card-value { font-size: 1.6rem; font-weight: 800; margin-bottom: 4px; letter-spacing: -0.5px; color: #003D7A; line-height: 1.1; }
.summary-card-footer { font-size: 0.78rem; color: #999; display: flex; align-items: center; gap: 5px; }
.alert-modern { padding: 14px 18px; border-radius: 12px; margin-bottom: 16px; display: flex; align-items: flex-start; gap: 12px; font-size: 0.92rem; border: 2px solid; }
.alert-modern.success { background: #e8f5e9; border-color: #a5d6a7; color: #2e7d32; }
.alert-modern.danger { background: #ffebee; border-color: #ef9a9a; color: #c62828; }
.alert-modern.warning { background: #fff8e1; border-color: #ffe082; color: #f57c00; }
.alert-modern.info { background: #e3f2fd; border-color: #90caf9; color: #1565c0; }
.alert-modern i { font-size: 1.2rem; margin-top: 2px; flex-shrink: 0; }
.card-modern { background: white; border-radius: 16px; box-shadow: 0 4px 20px rgba(0,0,0,0.08); overflow: hidden; margin-bottom: 20px; border: none; }
.card-header-modern { color: white; padding: 16px 20px; font-size: 1rem; font-weight: 600; display: flex; align-items: center; justify-content: space-between; gap: 10px; flex-wrap: wrap; }
.card-header-modern.whatsapp { background: linear-gradient(135deg, #25D366 0%, #128C7E 100%); }
.card-header-modern.success { background: linear-gradient(135deg, #00C853 0%, #69F0AE 100%); }
.card-header-modern.primary { background: linear-gradient(135deg, #0066CC 0%, #00B4FF 100%); }
.card-header-modern.info { background: linear-gradient(135deg, #00B8D4 0%, #26C6DA 100%); }
.card-header-modern.warning { background: linear-gradient(135deg, #FF9900 0%, #FFB84D 100%); }
.card-header-modern .title-left { display: flex; align-items: center; gap: 10px; }
.card-body-modern { padding: 20px; }
.form-group-modern { margin-bottom: 16px; }
.form-label-modern { display: flex; align-items: center; gap: 6px; font-weight: 600; color: #003D7A; margin-bottom: 8px; font-size: 0.88rem; }
.form-label-modern i { color: #25D366; }
.form-label-modern .required { color: #DC3545; margin-left: 2px; }
.form-control-modern, .form-select-modern { width: 100%; padding: 11px 14px; border: 2px solid #e8f4f8; border-radius: 10px; font-size: 0.9rem; transition: all 0.3s ease; background: #f8fafc; font-family: inherit; box-sizing: border-box; }
.form-control-modern:focus, .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: 120px; }
.form-hint { display: flex; align-items: center; gap: 4px; margin-top: 6px; font-size: 0.75rem; color: #999; }
.char-counter { display: inline-flex; align-items: center; gap: 6px; padding: 4px 10px; background: #f0f0f0; border-radius: 12px; font-size: 0.75rem; color: #666; font-weight: 600; margin-top: 6px; }
.btn-modern { padding: 11px 20px; border: none; border-radius: 10px; font-size: 0.9rem; font-weight: 600; cursor: pointer; transition: all 0.3s ease; display: inline-flex; align-items: center; justify-content: center; gap: 8px; text-decoration: none; }
.btn-modern.whatsapp { background: linear-gradient(135deg, #25D366 0%, #128C7E 100%); color: white; box-shadow: 0 4px 15px rgba(37, 211, 102, 0.3); 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.5; 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.secondary { background: white; color: #666; border: 2px solid #e8f4f8; }
.btn-modern.secondary:hover { background: #f8fafc; border-color: #0066CC; color: #0066CC; }
.template-grid { display: grid; grid-template-columns: 1fr; gap: 8px; }
.template-card { background: white; border: 2px solid #f0f0f0; border-radius: 12px; padding: 12px 14px; cursor: pointer; transition: all 0.3s ease; text-align: left; display: flex; align-items: center; gap: 12px; }
.template-card:hover { border-color: #25D366; background: #f0faf3; transform: translateX(2px); }
.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.2rem; flex-shrink: 0; }
.template-info { flex: 1; min-width: 0; }
.template-title { font-weight: 700; color: #003D7A; font-size: 0.88rem; margin-bottom: 2px; }
.template-desc { font-size: 0.72rem; color: #999; }
.message-list { max-height: 400px; overflow-y: auto; }
.message-item { display: flex; align-items: flex-start; gap: 12px; padding: 12px 16px; border-bottom: 1px solid #f0f0f0; transition: all 0.2s ease; cursor: pointer; text-decoration: none; color: inherit; }
.message-item:hover { background: #f8fafc; }
.message-item:last-child { border-bottom: none; }
.message-avatar { width: 38px; height: 38px; 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: 0.9rem; flex-shrink: 0; }
.message-content { flex: 1; min-width: 0; }
.message-header { display: flex; justify-content: space-between; align-items: center; gap: 8px; margin-bottom: 4px; }
.message-name { font-weight: 700; color: #003D7A; font-size: 0.88rem; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
.message-time { font-size: 0.72rem; color: #999; white-space: nowrap; display: flex; align-items: center; gap: 4px; }
.message-phone { font-size: 0.78rem; color: #666; margin-bottom: 4px; display: flex; align-items: center; gap: 6px; }
.message-phone code { background: #f0f0f0; padding: 1px 6px; border-radius: 4px; font-size: 0.72rem; }
.message-preview { font-size: 0.8rem; 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.68rem; font-weight: 700; background: #d1e7dd; color: #0f5132; }
.customer-table-wrapper { max-height: 400px; overflow-y: auto; }
.customer-table { width: 100%; border-collapse: collapse; font-size: 0.88rem; }
.customer-table thead { position: sticky; top: 0; background: #f8fafc; z-index: 5; }
.customer-table th { padding: 10px 12px; text-align: left; font-weight: 700; color: #003D7A; border-bottom: 2px solid #e8f4f8; font-size: 0.75rem; text-transform: uppercase; letter-spacing: 0.5px; }
.customer-table td { padding: 10px 12px; border-bottom: 1px solid #f0f0f0; vertical-align: middle; }
.customer-table tbody tr { transition: all 0.2s ease; }
.customer-table tbody tr:hover { background: #f8fafc; }
.customer-table tbody tr.selected { background: #e8f5e9; }
.customer-table tbody tr.selected:hover { background: #c8e6c9; }
.customer-checkbox { width: 18px; height: 18px; cursor: pointer; accent-color: #25D366; }
.customer-name-cell { display: flex; align-items: center; gap: 8px; }
.customer-avatar-small { width: 28px; height: 28px; 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: 0.75rem; flex-shrink: 0; }
.customer-name-text { font-weight: 600; color: #003D7A; font-size: 0.85rem; }
.customer-number-code { background: #f8fafc; padding: 2px 6px; border-radius: 4px; font-size: 0.72rem; color: #666; font-family: 'Courier New', monospace; }
.wa-link { color: #25D366; text-decoration: none; font-weight: 600; font-size: 0.82rem; display: inline-flex; align-items: center; gap: 4px; }
.wa-link:hover { color: #128C7E; }
.selected-badge { display: inline-flex; align-items: center; gap: 5px; padding: 4px 12px; background: #25D366; color: white; border-radius: 20px; font-size: 0.78rem; font-weight: 700; }
.btn-select { padding: 6px 12px; border: 2px solid #e8f4f8; border-radius: 8px; background: white; color: #666; font-size: 0.78rem; font-weight: 600; cursor: pointer; transition: all 0.3s ease; }
.btn-select:hover { border-color: #25D366; color: #25D366; }
.debug-table-wrapper { overflow-x: auto; margin-top: 12px; }
.debug-table { width: 100%; border-collapse: collapse; font-size: 0.82rem; min-width: 600px; }
.debug-table th { padding: 10px 12px; background: #fff8e1; color: #f57c00; font-weight: 700; text-align: left; font-size: 0.75rem; text-transform: uppercase; letter-spacing: 0.5px; }
.debug-table td { padding: 10px 12px; border-bottom: 1px solid #ffe082; background: #fffdf5; }
.debug-table tr:last-child td { border-bottom: none; }
.empty-state { text-align: center; padding: 40px 20px; }
.empty-state-icon { width: 60px; height: 60px; margin: 0 auto 12px; background: #f8fafc; border-radius: 50%; display: flex; align-items: center; justify-content: center; font-size: 1.7rem; color: #ccc; }
.empty-state-title { color: #666; font-weight: 600; margin-bottom: 4px; font-size: 0.95rem; }
.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 { background: linear-gradient(135deg, #25D366 0%, #128C7E 100%); color: white; padding: 18px 24px; border: none; }
.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; }
.detail-row { display: grid; grid-template-columns: 140px 1fr; gap: 12px; padding: 10px 0; border-bottom: 1px dashed #e8f4f8; align-items: flex-start; }
.detail-row:last-child { border-bottom: none; }
.detail-label { font-weight: 600; color: #666; font-size: 0.85rem; display: flex; align-items: center; gap: 6px; }
.detail-value { color: #333; font-size: 0.9rem; word-break: break-word; }
.detail-value strong { color: #003D7A; }
.message-content-box { 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; line-height: 1.6; margin-top: 8px; }
.btn-modal { padding: 10px 20px; border: none; border-radius: 10px; font-size: 0.9rem; font-weight: 600; cursor: pointer; transition: all 0.3s ease; display: inline-flex; align-items: center; gap: 6px; text-decoration: none; }
.btn-modal.whatsapp { background: linear-gradient(135deg, #25D366 0%, #128C7E 100%); color: white; box-shadow: 0 4px 12px rgba(37, 211, 102, 0.3); }
.btn-modal.secondary { background: white; color: #666; border: 2px solid #e8f4f8; }
.content-grid { display: grid; grid-template-columns: 5fr 7fr; gap: 20px; }

/* === PLACEHOLDER TAGS === */
.placeholder-info { background: linear-gradient(135deg, #e3f2fd 0%, #bbdefb 100%); border: 2px solid #90caf9; border-radius: 10px; padding: 12px; margin-top: 10px; }
.placeholder-info-title { font-size: 0.78rem; font-weight: 700; color: #003D7A; margin-bottom: 8px; display: flex; align-items: center; gap: 6px; }
.placeholder-tags { display: flex; flex-wrap: wrap; gap: 6px; }
.placeholder-tag { background: white; color: #0066CC; padding: 4px 10px; border-radius: 6px; font-size: 0.72rem; font-family: 'Courier New', monospace; font-weight: 700; border: 1px solid #90caf9; cursor: pointer; transition: all 0.2s ease; }
.placeholder-tag:hover { background: #0066CC; color: white; transform: translateY(-1px); }

@media (max-width: 992px) { .content-grid { grid-template-columns: 1fr; } }
@media (max-width: 768px) {
    .navbar-modern { padding: 10px 15px; }
    .navbar-title { font-size: 1rem; }
    .navbar-greeting, .navbar-badge { display: none; }
    .main-content { padding: 15px; }
    .page-header { flex-direction: column; align-items: stretch; }
    .page-title { font-size: 1.3rem; }
    .page-title i { font-size: 1.5rem; }
    .summary-row { grid-template-columns: repeat(2, 1fr); gap: 10px; }
    .summary-card { padding: 14px; }
    .summary-card-value { font-size: 1.2rem; }
    .summary-card-title { font-size: 0.68rem; }
    .summary-card-icon { width: 34px; height: 34px; font-size: 1rem; }
    .card-header-modern { padding: 14px 16px; font-size: 0.95rem; }
    .card-body-modern { padding: 16px; }
    .customer-table th, .customer-table td { padding: 8px 10px; font-size: 0.8rem; }
    .customer-avatar-small { width: 24px; height: 24px; font-size: 0.7rem; }
    .customer-name-text { font-size: 0.8rem; }
    .detail-row { grid-template-columns: 1fr; gap: 4px; }
    .modal-modern .modal-dialog { margin: 0; max-width: 100%; min-height: 100vh; }
    .modal-modern .modal-content { border-radius: 0; min-height: 100vh; }
}
@media (max-width: 480px) {
    .navbar-modern { padding: 8px 12px; }
    .burger-btn { width: 38px; height: 38px; font-size: 1.15rem; }
    .navbar-title { font-size: 0.95rem; }
    .main-content { padding: 12px; }
    .page-title { font-size: 1.15rem; gap: 8px; }
    .summary-row { grid-template-columns: 1fr 1fr; gap: 8px; }
    .summary-card { padding: 12px; }
    .summary-card-value { font-size: 1.05rem; }
    .summary-card-footer { font-size: 0.7rem; }
    .card-header-modern { padding: 12px 14px; font-size: 0.9rem; }
    .card-body-modern { padding: 14px; }
    .form-control-modern, .form-select-modern { padding: 10px 12px; font-size: 0.88rem; }
    .template-card { padding: 10px 12px; }
    .template-icon { width: 34px; height: 34px; font-size: 1rem; }
    .template-title { font-size: 0.82rem; }
    .message-item { padding: 10px 12px; }
    .message-avatar { width: 34px; height: 34px; font-size: 0.82rem; }
    .message-name { font-size: 0.82rem; }
    .customer-table th, .customer-table td { padding: 6px 8px; font-size: 0.75rem; }
    .customer-avatar-small { width: 22px; height: 22px; font-size: 0.65rem; }
    .customer-name-text { font-size: 0.75rem; }
    .customer-number-code { font-size: 0.68rem; }
}
</style>

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

<div class="page-header"></div>

<?= flashMessage() ?>

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

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

<?php if (!$isConfigured): ?>
    <div class="alert-modern danger">
        <i class="bi bi-exclamation-triangle-fill"></i>
        <div>
            <strong>Wablas Anda belum dikonfigurasi!</strong><br>
            Silakan isi Token dan Base URL di 
            <a href="/branch/whatsapp_settings.php" style="color: #c62828; font-weight: 700;">halaman pengaturan WA cabang</a> 
            sebelum melakukan broadcast.
        </div>
    </div>
<?php endif; ?>

<!-- Summary Cards -->
<div class="summary-row">
    <div class="summary-card whatsapp">
        <div class="summary-card-header">
            <h6 class="summary-card-title">Total Pelanggan</h6>
            <div class="summary-card-icon"><i class="bi bi-people-fill"></i></div>
        </div>
        <div class="summary-card-value"><?= number_format($totalCustomers) ?></div>
        <div class="summary-card-footer">👥 Seluruh pelanggan cabang</div>
    </div>
    <div class="summary-card success">
        <div class="summary-card-header">
            <h6 class="summary-card-title">Bisa Dihubungi</h6>
            <div class="summary-card-icon"><i class="bi bi-telephone-fill"></i></div>
        </div>
        <div class="summary-card-value"><?= number_format($customersWithPhone) ?></div>
        <div class="summary-card-footer">📱 Punya nomor HP</div>
    </div>
    <div class="summary-card primary">
        <div class="summary-card-header">
            <h6 class="summary-card-title">Paket Tersedia</h6>
            <div class="summary-card-icon"><i class="bi bi-box-seam"></i></div>
        </div>
        <div class="summary-card-value"><?= number_format(count($packages)) ?></div>
        <div class="summary-card-footer">📦 Paket internet aktif</div>
    </div>
    <div class="summary-card <?= $isConfigured ? 'success' : 'danger' ?>">
        <div class="summary-card-header">
            <h6 class="summary-card-title">Gateway WA</h6>
            <div class="summary-card-icon">
                <i class="bi bi-<?= $isConfigured ? 'check-circle-fill' : 'x-circle-fill' ?>"></i>
            </div>
        </div>
        <div class="summary-card-value" style="font-size: 1.1rem;">
            <?= $isConfigured ? '✅ Aktif' : '❌ Belum' ?>
        </div>
        <div class="summary-card-footer">
            <?= $isConfigured ? '🟢 Siap broadcast' : '🔴 Perlu konfigurasi' ?>
        </div>
    </div>
</div>

<!-- DEBUG INFORMATION -->
<?php if (!empty($debugLogs)): ?>
    <div class="card-modern">
        <div class="card-header-modern warning">
            <div class="title-left">
                <i class="bi bi-bug-fill"></i>
                <span>Debug Information (Pesan Gagal)</span>
                <span style="background: rgba(255,255,255,0.25); padding: 3px 10px; border-radius: 10px; font-size: 0.78rem;"><?= count($debugLogs) ?></span>
            </div>
        </div>
        <div class="card-body-modern" style="padding: 0;">
            <div class="debug-table-wrapper">
                <table class="debug-table">
                    <thead>
                        <tr>
                            <th>No. Pelanggan</th>
                            <th>Nama</th>
                            <th>No. HP</th>
                            <th>HTTP</th>
                            <th>Error</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($debugLogs as $log): ?>
                            <tr>
                                <td><code><?= htmlspecialchars($log['customer_number']) ?></code></td>
                                <td><?= htmlspecialchars($log['name']) ?></td>
                                <td><code><?= htmlspecialchars($log['phone']) ?></code></td>
                                <td><code><?= $log['http_code'] ?></code></td>
                                <td style="font-size: 0.78rem;"><?= htmlspecialchars($log['error_message']) ?></td>
                            </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>
<?php endif; ?>

<!-- Main Content Grid -->
<div class="content-grid">
    <!-- KOLOM KIRI: Compose + Templates -->
    <div>
        <!-- Compose Broadcast -->
        <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 <span class="required">*</span>
                        </label>
                        <input type="text" name="title" class="form-control-modern" required
                               placeholder="Contoh: Pengumuman Maintenance <?= htmlspecialchars($userBranchName) ?>">
                    </div>
                    
                    <div class="form-group-modern">
                        <label class="form-label-modern">
                            <i class="bi bi-bullseye"></i>
                            Target Penerima <span class="required">*</span>
                        </label>
                        <select name="target_type" id="targetType" class="form-select-modern" onchange="toggleTargetOptions()">
                            <option value="all_customers">📢 Semua Pelanggan (<?= $customersWithPhone ?> orang)</option>
                            <option value="selected_customers">☑️ Pelanggan Terpilih</option>
                            <option value="by_package">📦 Berdasarkan Paket</option>
                            <option value="by_status">🔖 Berdasarkan Status</option>
                            <option value="custom_numbers">🔢 Nomor Custom</option>
                        </select>
                    </div>
                    
                    <div id="targetPackageOption" style="display: none;" class="form-group-modern">
                        <label class="form-label-modern"><i class="bi bi-box"></i> Pilih Paket</label>
                        <select name="target_package" class="form-select-modern">
                            <option value="">-- Pilih Paket --</option>
                            <?php foreach ($packages as $p): ?>
                                <option value="<?= $p['id'] ?>"><?= htmlspecialchars($p['name']) ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    
                    <div id="targetStatusOption" style="display: none;" class="form-group-modern">
                        <label class="form-label-modern"><i class="bi bi-flag"></i> Pilih Status</label>
                        <select name="target_status" class="form-select-modern">
                            <option value="active">✅ Aktif</option>
                            <option value="suspended">⏸️ Suspended</option>
                            <option value="inactive">❌ Nonaktif</option>
                        </select>
                    </div>
                    
                    <div id="targetNumbersOption" style="display: none;" class="form-group-modern">
                        <label class="form-label-modern"><i class="bi bi-telephone"></i> Nomor WhatsApp</label>
                        <textarea name="custom_numbers" class="form-control-modern" rows="3" placeholder="6281234567890, 6289876543210"></textarea>
                    </div>
                    
                    <div class="form-group-modern">
                        <label class="form-label-modern">
                            <i class="bi bi-chat-left-text-fill"></i>
                            Pesan Broadcast <span class="required">*</span>
                        </label>
                        <textarea name="message" id="messageInput" class="form-control-modern" rows="8" required placeholder="Ketik pesan broadcast di sini... Gunakan [nama], [paket], dll untuk personalisasi"></textarea>
                        
                        <!-- ✅ INFO PLACEHOLDER -->
                        <div class="placeholder-info">
                            <div class="placeholder-info-title">
                                <i class="bi bi-braces"></i>
                                Placeholder (Klik untuk insert, otomatis diganti per pelanggan):
                            </div>
                            <div class="placeholder-tags">
                                <span class="placeholder-tag" onclick="insertPlaceholder('[nama]')">[nama]</span>
                                <span class="placeholder-tag" onclick="insertPlaceholder('[customer_number]')">[customer_number]</span>
                                <span class="placeholder-tag" onclick="insertPlaceholder('[paket]')">[paket]</span>
                                <span class="placeholder-tag" onclick="insertPlaceholder('[phone]')">[phone]</span>
                                <span class="placeholder-tag" onclick="insertPlaceholder('[Link Pembayaran]')">[Link Pembayaran]</span>
                            </div>
                        </div>
                        
                        <div style="display: flex; justify-content: space-between; align-items: center; flex-wrap: wrap; gap: 6px;">
                            <small class="form-hint" style="margin: 0;"><i class="bi bi-info-circle"></i> Emoji akan otomatis dihapus</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</span>
                    </button>
                </form>
            </div>
        </div>
        
        <!-- Template Pesan -->
        <div class="card-modern">
            <div class="card-header-modern info">
                <div class="title-left">
                    <i class="bi bi-lightning-fill"></i>
                    <span>Template Pesan Cepat</span>
                </div>
                <a href="/branch/templates.php" class="btn-modal secondary" style="padding: 6px 12px; font-size: 0.75rem; text-decoration: none; color: white; background: rgba(255,255,255,0.2); border: 1px solid rgba(255,255,255,0.3);">
                    <i class="bi bi-gear-fill"></i> Kelola
                </a>
            </div>
            <div class="card-body-modern">
                <div class="template-grid">
                    <button type="button" class="template-card" onclick="useTemplate('reminder_h3')">
                        <div class="template-icon">📅</div>
                        <div class="template-info">
                            <div class="template-title">Reminder H-3</div>
                            <div class="template-desc">Pengingat 3 hari sebelum jatuh tempo</div>
                        </div>
                    </button>
                    <button type="button" class="template-card" onclick="useTemplate('reminder_h1')">
                        <div class="template-icon">⏰</div>
                        <div class="template-info">
                            <div class="template-title">Reminder H-1</div>
                            <div class="template-desc">Pengingat 1 hari sebelum jatuh tempo</div>
                        </div>
                    </button>
                    <button type="button" class="template-card" onclick="useTemplate('reminder_due')">
                        <div class="template-icon">⚠️</div>
                        <div class="template-info">
                            <div class="template-title">Jatuh Tempo (Hari H)</div>
                            <div class="template-desc">Pemberitahuan batas akhir pembayaran</div>
                        </div>
                    </button>
                    <button type="button" class="template-card" onclick="useTemplate('maintenance')">
                        <div class="template-icon">🔧</div>
                        <div class="template-info">
                            <div class="template-title">Info Maintenance</div>
                            <div class="template-desc">Beritahu jadwal maintenance</div>
                        </div>
                    </button>
                    <button type="button" class="template-card" onclick="useTemplate('promo')">
                        <div class="template-icon">🎉</div>
                        <div class="template-info">
                            <div class="template-title">Promo Paket</div>
                            <div class="template-desc">Tawarkan promo spesial</div>
                        </div>
                    </button>
                    <button type="button" class="template-card" onclick="useTemplate('thanks')">
                        <div class="template-icon">🙏</div>
                        <div class="template-info">
                            <div class="template-title">Ucapan Terima Kasih</div>
                            <div class="template-desc">Apresiasi pelanggan setia</div>
                        </div>
                    </button>
                    <button type="button" class="template-card" onclick="useTemplate('payment')">
                        <div class="template-icon">💰</div>
                        <div class="template-info">
                            <div class="template-title">Konfirmasi Pembayaran</div>
                            <div class="template-desc">Info metode pembayaran</div>
                        </div>
                    </button>
                </div>
            </div>
        </div>
    </div>

    <!-- KOLOM KANAN: Pesan Terkirim + Pilih Customer -->
    <div>
        <!-- Pesan Terkirim -->
        <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>
                <?php if (!empty($sentMessages)): ?>
                    <small style="opacity: 0.9; font-size: 0.75rem;">Klik untuk detail</small>
                <?php endif; ?>
            </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>
                </div>
            <?php else: ?>
                <div class="message-list">
                    <?php foreach ($sentMessages as $index => $msg): ?>
                        <a href="#" 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"><i class="bi bi-clock"></i> <?= 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>
                        </a>
                    <?php endforeach; ?>
                </div>
            <?php endif; ?>
        </div>
        
        <!-- Pilih Customer -->
        <div class="card-modern" id="customerSelectionPanel">
            <div class="card-header-modern primary">
                <div class="title-left">
                    <i class="bi bi-people-fill"></i>
                    <span>Pilih Pelanggan</span>
                    <span class="selected-badge" id="selectedCount">0 dipilih</span>
                </div>
                <div style="display: flex; gap: 6px;">
                    <button type="button" class="btn-select" onclick="selectAll()"><i class="bi bi-check-all"></i> Semua</button>
                    <button type="button" class="btn-select" onclick="deselectAll()"><i class="bi bi-x-lg"></i> Reset</button>
                </div>
            </div>
            <div style="padding: 10px 14px; background: #f8fafc; border-bottom: 1px solid #e8f4f8; font-size: 0.78rem; color: #666;">
                <i class="bi bi-building"></i> Hanya pelanggan cabang <strong><?= htmlspecialchars($userBranchName) ?></strong>
            </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">Belum ada pelanggan di cabang ini</h5>
                </div>
            <?php else: ?>
                <div class="customer-table-wrapper">
                    <table class="customer-table">
                        <thead>
                            <tr>
                                <th style="width: 40px;"><input type="checkbox" id="selectAllCheckbox" class="customer-checkbox" onchange="toggleSelectAll()"></th>
                                <th>No.</th>
                                <th>Nama</th>
                                <th>No. HP</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach ($customers as $c): ?>
                                <?php if (!empty($c['phone'])): ?>
                                    <tr>
                                        <td>
                                            <input type="checkbox" name="customers[]" value="<?= $c['id'] ?>" class="customer-checkbox customer-row-checkbox" form="broadcastForm" onchange="updateSelectedCount()">
                                        </td>
                                        <td><span class="customer-number-code">#<?= htmlspecialchars($c['customer_number'] ?? '-') ?></span></td>
                                        <td>
                                            <div class="customer-name-cell">
                                                <div class="customer-avatar-small"><?= strtoupper(substr($c['name'], 0, 1)) ?></div>
                                                <span class="customer-name-text"><?= htmlspecialchars($c['name']) ?></span>
                                            </div>
                                        </td>
                                        <td>
                                            <a href="https://wa.me/<?= preg_replace('/^0/', '62', $c['phone']) ?>" target="_blank" class="wa-link">
                                                <i class="bi bi-whatsapp"></i> <?= htmlspecialchars($c['phone']) ?>
                                            </a>
                                        </td>
                                    </tr>
                                <?php endif; ?>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
            <?php endif; ?>
        </div>
    </div>
</div>
</div>
</div>

<!-- MODAL DETAIL PESAN TERKIRIM -->
<?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">
                <h5 class="modal-title"><i class="bi bi-whatsapp"></i> <span>Detail Pesan Terkirim</span></h5>
                <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <div class="detail-row">
                    <div class="detail-label"><i class="bi bi-person-fill"></i> Nama Penerima</div>
                    <div class="detail-value"><strong><?= htmlspecialchars($msg['name']) ?></strong></div>
                </div>
                <div class="detail-row">
                    <div class="detail-label"><i class="bi bi-hash"></i> No. Pelanggan</div>
                    <div class="detail-value"><code style="background: #f8fafc; padding: 3px 8px; border-radius: 6px; border-left: 3px solid #25D366;"><?= htmlspecialchars($msg['customer_number']) ?></code></div>
                </div>
                <div class="detail-row">
                    <div class="detail-label"><i class="bi bi-telephone-fill"></i> Nomor WhatsApp</div>
                    <div class="detail-value">
                        <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>
                <div class="detail-row">
                    <div class="detail-label"><i class="bi bi-clock-fill"></i> Waktu Kirim</div>
                    <div class="detail-value"><strong><?= date('d M Y') ?> <?= htmlspecialchars($msg['timestamp']) ?> WIB</strong></div>
                </div>
                <div style="margin-top: 16px;">
                    <div class="detail-label" style="margin-bottom: 8px;"><i class="bi bi-chat-left-text-fill"></i> Isi Pesan (Sudah dipersonalisasi):</div>
                    <div class="message-content-box"><?= htmlspecialchars($msg['message']) ?></div>
                </div>
            </div>
            <div class="modal-footer">
                <a href="https://wa.me/<?= $msg['phone'] ?>" target="_blank" class="btn-modal whatsapp"><i class="bi bi-whatsapp"></i> Chat di WhatsApp</a>
                <button type="button" class="btn-modal 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' : '';
    }
}

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

function toggleTargetOptions() {
    const targetType = document.getElementById('targetType').value;
    document.getElementById('targetPackageOption').style.display = targetType === 'by_package' ? 'block' : 'none';
    document.getElementById('targetStatusOption').style.display = targetType === 'by_status' ? 'block' : 'none';
    document.getElementById('targetNumbersOption').style.display = targetType === 'custom_numbers' ? 'block' : 'none';
    document.getElementById('customerSelectionPanel').style.display = targetType === 'selected_customers' ? 'block' : 'none';
}

// ✅ Fungsi insert placeholder ke textarea
function insertPlaceholder(placeholder) {
    const textarea = document.getElementById('messageInput');
    const start = textarea.selectionStart;
    const end = textarea.selectionEnd;
    const text = textarea.value;
    textarea.value = text.substring(0, start) + placeholder + text.substring(end);
    textarea.selectionStart = textarea.selectionEnd = start + placeholder.length;
    textarea.focus();
    textarea.dispatchEvent(new Event('input'));
}

// ============================================================================
// TEMPLATE MANAGEMENT
// ============================================================================
const dbTemplates = <?= json_encode($dbTemplates, JSON_UNESCAPED_UNICODE | JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_QUOT) ?>;

const defaultTemplates = {
    reminder_h3: `🔔 *PENGINGAT TAGIHAN (H-3)*

Yth. [nama],
Berikut adalah detail tagihan internet Anda:

👤 Nomor Pelanggan : [customer_number]
📝 Nama : [nama]
📦 Paket Internet : [paket]
💳 Link pembayaran : [Link Pembayaran]

Tagihan Anda akan jatuh tempo dalam 3 hari. Mohon segera melakukan pembayaran agar layanan internet Anda tetap aktif dan tidak terganggu.

Terima kasih atas kepercayaan Anda.`,
    
    reminder_h1: `⏰ *PENGINGAT TAGIHAN (H-1)*

Yth. [nama],
Mengingatkan kembali bahwa tagihan internet Anda akan jatuh tempo BESOK.

👤 Nomor Pelanggan : [customer_number]
📝 Nama : [nama]
📦 Paket Internet : [paket]
💳 Link pembayaran : [Link Pembayaran]

Segera lakukan pembayaran untuk menghindari pemblokiran layanan secara otomatis.

Terima kasih.`,
    
    reminder_due: `⚠️ *PEMBERITAHUAN JATUH TEMPO*

Yth. [nama],
Hari ini adalah batas akhir pembayaran tagihan internet Anda.

👤 Nomor Pelanggan : [customer_number]
📝 Nama : [nama]
📦 Paket Internet : [paket]
💳 Link pembayaran : [Link Pembayaran]

Mohon segera lakukan pembayaran hari ini. Jika belum melakukan pembayaran, layanan internet Anda akan otomatis kami suspensi sementara hingga tagihan dilunasi.

Terima kasih atas perhatian dan kerjasamanya.`,

    maintenance: `INFO MAINTENANCE

Yth. [nama],

Akan dilakukan maintenance jaringan pada:
Tanggal: [ISI TANGGAL]
Waktu: [ISI WAKTU]
Estimasi: [ISI DURASI]

Selama maintenance, layanan internet mungkin terganggu sementara.

Mohon maaf atas ketidaknyamanannya.
Terima kasih`,
    
    promo: `PROMO SPESIAL!

Yth. [nama],

Dapatkan penawaran spesial dari kami:
[ISI PROMO]
Harga: [ISI HARGA]
Periode: [ISI PERIODE]

Segera hubungi kami untuk mendapatkan promo ini!

Terima kasih`,
    
    thanks: `UCAPAN TERIMA KASIH

Yth. [nama],

Terima kasih telah menjadi pelanggan setia kami. Kami berkomitmen untuk terus memberikan layanan terbaik untuk Anda.

Jika ada kendala atau pertanyaan, jangan ragu untuk menghubungi kami.

Salam,
Tim <?= addslashes($userBranchName) ?>`,
    
    payment: `INFO PEMBAYARAN

Yth. [nama],

Untuk kemudahan pembayaran tagihan internet, Anda dapat melakukan pembayaran melalui:

1. Transfer Bank:
   - Bank: [NAMA BANK]
   - No. Rekening: [NO REK]
   - A/n: [NAMA]

2. E-Wallet:
   - [DAFTAR E-WALLET]

3. Langsung ke Kantor:
   - [ALAMAT KANTOR CABANG]

Konfirmasi pembayaran dapat dilakukan via WhatsApp ini.

Terima kasih`
};

const templates = { ...defaultTemplates, ...dbTemplates };

function useTemplate(key) {
    const template = templates[key] || '';
    document.getElementById('messageInput').value = template;
    document.getElementById('messageInput').dispatchEvent(new Event('input'));
    document.getElementById('messageInput').focus();
    window.scrollTo({ top: 0, behavior: 'smooth' });
}

function selectAll() {
    document.querySelectorAll('.customer-row-checkbox').forEach(cb => {
        if (cb.closest('tr').style.display !== 'none') cb.checked = true;
    });
    document.getElementById('selectAllCheckbox').checked = true;
    updateSelectedCount();
}

function deselectAll() {
    document.querySelectorAll('.customer-row-checkbox').forEach(cb => cb.checked = false);
    document.getElementById('selectAllCheckbox').checked = false;
    updateSelectedCount();
}

function toggleSelectAll() {
    const selectAll = document.getElementById('selectAllCheckbox');
    document.querySelectorAll('.customer-row-checkbox').forEach(cb => cb.checked = selectAll.checked);
    updateSelectedCount();
}

function updateSelectedCount() {
    const count = document.querySelectorAll('.customer-row-checkbox:checked').length;
    document.getElementById('selectedCount').textContent = count + ' dipilih';
    document.querySelectorAll('.customer-table tbody tr').forEach(tr => {
        const cb = tr.querySelector('.customer-row-checkbox');
        if (cb && cb.checked) tr.classList.add('selected');
        else tr.classList.remove('selected');
    });
}

function confirmBroadcast() {
    const targetType = document.getElementById('targetType').value;
    let targetCount = 0;
    let targetLabel = '';
    
    if (targetType === 'all_customers') {
        targetCount = <?= $customersWithPhone ?>;
        targetLabel = `semua pelanggan (${targetCount} orang)`;
    } else if (targetType === 'selected_customers') {
        targetCount = document.querySelectorAll('.customer-row-checkbox:checked').length;
        if (targetCount === 0) { alert('Pilih minimal 1 pelanggan!'); return false; }
        targetLabel = `${targetCount} pelanggan yang dipilih`;
    } else if (targetType === 'custom_numbers') {
        const numbers = document.querySelector('[name="custom_numbers"]').value.trim();
        if (!numbers) { alert('Masukkan minimal 1 nomor!'); return false; }
        targetCount = numbers.split(/[\s,;]+/).filter(n => n.trim()).length;
        targetLabel = `${targetCount} nomor custom`;
    } else if (targetType === 'by_package') {
        const pkg = document.querySelector('[name="target_package"]').value;
        if (!pkg) { alert('Pilih paket target!'); return false; }
        targetLabel = 'pelanggan dengan paket tertentu';
    } else if (targetType === 'by_status') {
        targetLabel = 'pelanggan dengan status tertentu';
    }
    
    return confirm(`Kirim broadcast ke ${targetLabel} di cabang <?= addslashes($userBranchName) ?>?\n\nPastikan pesan sudah benar sebelum dikirim.\n\n💡 Placeholder seperti [nama], [paket] akan otomatis diganti dengan data masing-masing pelanggan.`);
}

toggleTargetOptions();
</script>

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