<?php
require_once __DIR__ . '/../includes/auth.php';
require_once __DIR__ . '/../includes/functions.php';
require_once __DIR__ . '/../classes/Customer.php';
require_once __DIR__ . '/../classes/Bill.php';
require_once __DIR__ . '/../classes/MikroTik.php';

requireRole('branch_admin');
$pageTitle = 'Data Pelanggan';

$db = db();

// Ambil info 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');
}

// ============================================================================
// ⭐ EXPORT CSV HANDLER (DIPERBAIKI: Delimiter KOMA + Sanitasi Proper)
// ============================================================================
if (isset($_GET['action']) && $_GET['action'] === 'export' && verifyCsrf($_GET['token'] ?? '')) {
    try {
        $stmt = $db->prepare("
            SELECT c.*, p.name as package_name
            FROM customers c
            LEFT JOIN packages p ON c.package_id = p.id
            WHERE c.branch_id = ?
            ORDER BY c.name ASC
        ");
        $stmt->execute([$userBranchId]);
        $customers = $stmt->fetchAll();
        
        if (empty($customers)) {
            redirect('/branch/customers.php', '❌ Tidak ada data pelanggan untuk diexport', 'error');
        }
        
        // ⭐ File .csv dengan delimiter KOMA - Excel akan auto-detect per kolom
        $filename = 'pelanggan_' . preg_replace('/[^a-z0-9]/i', '_', $userBranchName) . '_' . date('Y-m-d_His') . '.csv';
        
        // ⭐ HEADER WAJIB: text/csv + charset UTF-8
        header('Content-Type: text/csv; charset=utf-8');
        header('Content-Disposition: attachment; filename="' . $filename . '"');
        header('Pragma: no-cache');
        header('Expires: 0');
        
        $output = fopen('php://output', 'w');
        
        // ⭐ BOM UTF-8 - WAJIB agar Excel membaca karakter Indonesia dengan benar
        fprintf($output, chr(0xEF).chr(0xBB).chr(0xBF));
        
        // ⭐ DELIMITER: KOMA (Standar CSV - Excel auto-detect per kolom)
        $delimiter = ',';
        $enclosure = '"';
        
        // Header - setiap nama kolom jadi judul kolom di Excel
        fputcsv($output, [
            'customer_number', 
            'nama', 
            'no_hp', 
            'email', 
            'alamat',
            'pppoe_username', 
            'pppoe_password', 
            'pppoe_service', 
            'pppoe_profile',
            'paket', 
            'ip_address', 
            'tanggal_instalasi', 
            'status', 
            'masa_aktif_sampai'
        ], $delimiter, $enclosure);
        
        // Data rows - setiap field masuk ke cell masing-masing
        foreach ($customers as $c) {
            // ⭐ Sanitasi: hilangkan newline & tab yang bisa merusak struktur CSV
            $sanitize = function($val) {
                $val = $val ?? '';
                // Ganti newline, carriage return, tab dengan spasi
                $val = str_replace(["\r\n", "\r", "\n", "\t"], ' ', $val);
                // Hapus karakter kontrol ASCII 0-31 (kecuali spasi)
                $val = preg_replace('/[\x00-\x08\x0B\x0C\x0E-\x1F]/', '', $val);
                return trim($val);
            };
            
            fputcsv($output, [
                $sanitize($c['customer_number']),
                $sanitize($c['name']),
                $sanitize($c['phone']),
                $sanitize($c['email']),
                $sanitize($c['address']),
                $sanitize($c['pppoe_username']),
                $sanitize($c['pppoe_password']),
                $sanitize($c['pppoe_service'] ?? 'pppoe'),
                $sanitize($c['pppoe_profile'] ?? 'default'),
                $sanitize($c['package_name']),
                $sanitize($c['ip_address']),
                $c['installation_date'] ?? date('Y-m-d', strtotime($c['created_at'] ?? 'now')),
                $sanitize($c['status']),
                !empty($c['active_until']) ? date('Y-m-d', strtotime($c['active_until'])) : ''
            ], $delimiter, $enclosure);
        }
        
        fclose($output);
        logActivity($currentUserId, 'export_customers', "[{$userBranchName}] Export " . count($customers) . " pelanggan");
        exit;
        
    } catch (\Throwable $e) {
        redirect('/branch/customers.php', '❌ Error export: ' . $e->getMessage(), 'error');
    }
}

// ============================================================================
// ⭐ DOWNLOAD TEMPLATE CSV (DIPERBAIKI: Konsisten dengan format export)
// ============================================================================
if (isset($_GET['action']) && $_GET['action'] === 'download_template') {
    $filename = 'template_import_pelanggan_' . date('Y-m-d') . '.csv';
    
    // ⭐ HEADER SAMA DENGAN EXPORT
    header('Content-Type: text/csv; charset=utf-8');
    header('Content-Disposition: attachment; filename="' . $filename . '"');
    header('Pragma: no-cache');
    header('Expires: 0');
    
    $output = fopen('php://output', 'w');
    fprintf($output, chr(0xEF).chr(0xBB).chr(0xBF));
    
    // ⭐ DELIMITER: KOMA (sama dengan export)
    $delimiter = ',';
    $enclosure = '"';
    
    // Header template
    fputcsv($output, [
        'nama', 'no_hp', 'email', 'alamat',
        'pppoe_username', 'pppoe_password', 'pppoe_profile',
        'paket', 'ip_address', 'tanggal_instalasi'
    ], $delimiter, $enclosure);
    
    // Contoh data 1
    fputcsv($output, [
        'Budi Santoso', 
        '081234567890', 
        'budi@email.com', 
        'Jl. Merdeka No. 10',
        'budi001', 
        'password123', 
        '20Mbps',
        'Paket 20 Mbps', 
        '', 
        date('Y-m-d')
    ], $delimiter, $enclosure);
    
    // Contoh data 2
    fputcsv($output, [
        'Siti Aminah', 
        '082345678901', 
        'siti@email.com', 
        'Jl. Sudirman No. 5',
        'siti001', 
        'password456', 
        '10Mbps',
        'Paket 10 Mbps', 
        '192.168.1.100', 
        date('Y-m-d')
    ], $delimiter, $enclosure);
    
    fclose($output);
    exit;
}

// ============================================================================
// ⭐ IMPORT CSV HANDLER (DIPERBAIKI: Auto-detect delimiter lebih akurat)
// ============================================================================
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['submit_import']) && verifyCsrf($_POST['csrf_token'] ?? '')) {
    if (!isset($_FILES['csv_file']) || $_FILES['csv_file']['error'] !== UPLOAD_ERR_OK) {
        redirect('/branch/customers.php', '❌ File tidak valid atau belum dipilih', 'error');
    }
    
    $file = $_FILES['csv_file'];
    
    $ext = strtolower(pathinfo($file['name'], PATHINFO_EXTENSION));
    if (!in_array($ext, ['csv', 'txt', 'tsv'])) {
        redirect('/branch/customers.php', '❌ Format file harus CSV/TSV/TXT', 'error');
    }
    
    if ($file['size'] > 5 * 1024 * 1024) {
        redirect('/branch/customers.php', '❌ Ukuran file maksimal 5MB', 'error');
    }
    
    try {
        $packages = [];
        $stmt = $db->prepare("SELECT id, name FROM packages WHERE status='active'");
        $stmt->execute();
        foreach ($stmt->fetchAll() as $p) {
            $packages[strtolower($p['name'])] = $p['id'];
        }
        
        $pppProfiles = [];
        try {
            $mt = new MikroTik($userBranchId);
            $profilesRaw = $mt->getPPPProfiles();
            foreach ($profilesRaw as $p) {
                if (isset($p['name']) && !empty($p['name'])) {
                    $pppProfiles[] = strtolower($p['name']);
                }
            }
        } catch (\Throwable $e) {}
        
        $content = file_get_contents($file['tmp_name']);
        
        // Skip BOM UTF-8
        if (substr($content, 0, 3) === "\xEF\xBB\xBF") {
            $content = substr($content, 3);
        }
        
        // ⭐ DETEKSI DELIMITER LEBIH AKURAT dengan substr_count
        $firstLine = strtok($content, "\n");
        
        // Hitung jumlah masing-masing delimiter di baris pertama
        $counts = [
            ','  => substr_count($firstLine, ','),
            '|'  => substr_count($firstLine, '|'),
            ';'  => substr_count($firstLine, ';'),
            "\t" => substr_count($firstLine, "\t")
        ];
        
        // Ambil delimiter dengan count tertinggi (minimal harus > 0)
        $delimiter = ','; // Default: koma
        $maxCount = 0;
        foreach ($counts as $delim => $count) {
            if ($count > $maxCount) {
                $maxCount = $count;
                $delimiter = $delim;
            }
        }
        
        // Split content jadi baris-baris
        $lines = preg_split('/\r\n|\r|\n/', trim($content));
        
        if (empty($lines)) {
            redirect('/branch/customers.php', '❌ File kosong', 'error');
        }
        
        // Parse header
        $header = str_getcsv(array_shift($lines), $delimiter);
        $header = array_map(function($h) {
            return strtolower(trim(trim($h, "\"'")));
        }, $header);
        
        // Mapping kolom
        $columnMap = [
            'nama' => ['nama', 'name', 'nama lengkap'],
            'no_hp' => ['no_hp', 'no hp', 'phone', 'hp', 'no_telp', 'telepon'],
            'email' => ['email', 'mail'],
            'alamat' => ['alamat', 'address'],
            'pppoe_username' => ['pppoe_username', 'username', 'user'],
            'pppoe_password' => ['pppoe_password', 'password', 'pass'],
            'pppoe_profile' => ['pppoe_profile', 'profile'],
            'paket' => ['paket', 'package', 'package_name', 'nama paket'],
            'ip_address' => ['ip_address', 'ip'],
            'tanggal_instalasi' => ['tanggal_instalasi', 'installation_date', 'tgl_instalasi', 'tanggal install']
        ];
        
        $fieldIndex = [];
        foreach ($columnMap as $field => $aliases) {
            foreach ($aliases as $alias) {
                $idx = array_search($alias, $header);
                if ($idx !== false) {
                    $fieldIndex[$field] = $idx;
                    break;
                }
            }
        }
        
        $requiredFields = ['nama', 'no_hp', 'pppoe_username', 'pppoe_password', 'paket'];
        $missingFields = [];
        foreach ($requiredFields as $f) {
            if (!isset($fieldIndex[$f])) $missingFields[] = $f;
        }
        
        if (!empty($missingFields)) {
            redirect('/branch/customers.php', 
                '❌ Kolom wajib tidak ditemukan: ' . implode(', ', $missingFields) . 
                '. Download template untuk format yang benar.', 'error');
        }
        
        $successCount = 0;
        $failCount = 0;
        $errors = [];
        $lineNumber = 1;
        
        foreach ($lines as $line) {
            $lineNumber++;
            $line = trim($line);
            if (empty($line)) continue;
            
            try {
                $row = str_getcsv($line, $delimiter);
                
                $data = [];
                foreach ($fieldIndex as $field => $idx) {
                    $data[$field] = isset($row[$idx]) ? trim(trim($row[$idx], "\"'")) : '';
                }
                
                if (empty($data['nama'])) throw new Exception('Nama kosong');
                if (empty($data['no_hp'])) throw new Exception('No HP kosong');
                if (empty($data['pppoe_username'])) throw new Exception('Username PPPoE kosong');
                if (empty($data['pppoe_password'])) throw new Exception('Password PPPoE kosong');
                if (empty($data['paket'])) throw new Exception('Paket kosong');
                
                $stmt = $db->prepare("SELECT id FROM customers WHERE pppoe_username = ?");
                $stmt->execute([$data['pppoe_username']]);
                if ($stmt->fetch()) {
                    throw new Exception("Username '{$data['pppoe_username']}' sudah digunakan");
                }
                
                $packageName = strtolower($data['paket']);
                if (!isset($packages[$packageName])) {
                    $found = false;
                    foreach ($packages as $pName => $pId) {
                        if (strpos($pName, $packageName) !== false || strpos($packageName, $pName) !== false) {
                            $data['package_id'] = $pId;
                            $found = true;
                            break;
                        }
                    }
                    if (!$found) {
                        throw new Exception("Paket '{$data['paket']}' tidak ditemukan");
                    }
                } else {
                    $data['package_id'] = $packages[$packageName];
                }
                
                if (!empty($data['pppoe_profile']) && !empty($pppProfiles)) {
                    $profileLower = strtolower($data['pppoe_profile']);
                    if (!in_array($profileLower, $pppProfiles)) {
                        $found = false;
                        foreach ($pppProfiles as $p) {
                            if (strpos($p, $profileLower) !== false || strpos($profileLower, $p) !== false) {
                                $data['pppoe_profile'] = $p;
                                $found = true;
                                break;
                            }
                        }
                        if (!$found) {
                            throw new Exception("PPP Profile '{$data['pppoe_profile']}' tidak ditemukan");
                        }
                    }
                }
                
                $data['pppoe_service'] = 'pppoe';
                if (empty($data['pppoe_profile'])) $data['pppoe_profile'] = 'default';
                
                if (empty($data['tanggal_instalasi'])) {
                    $data['installation_date'] = date('Y-m-d');
                } else {
                    $ts = strtotime($data['tanggal_instalasi']);
                    if ($ts === false) {
                        $parts = preg_split('/[\/\-\.]/', $data['tanggal_instalasi']);
                        if (count($parts) === 3 && strlen($parts[0]) <= 2 && strlen($parts[1]) <= 2) {
                            $ts = strtotime("{$parts[2]}-{$parts[1]}-{$parts[0]}");
                        }
                    }
                    if ($ts === false || $ts > time()) {
                        throw new Exception("Format tanggal tidak valid: '{$data['tanggal_instalasi']}'");
                    }
                    $data['installation_date'] = date('Y-m-d', $ts);
                }
                
                $createData = [
                    'branch_id' => $userBranchId,
                    'name' => $data['nama'],
                    'phone' => $data['no_hp'],
                    'email' => $data['email'] ?? null,
                    'address' => $data['alamat'] ?? null,
                    'pppoe_username' => $data['pppoe_username'],
                    'pppoe_password' => $data['pppoe_password'],
                    'pppoe_service' => $data['pppoe_service'],
                    'pppoe_profile' => $data['pppoe_profile'],
                    'package_id' => $data['package_id'],
                    'ip_address' => $data['ip_address'] ?? null,
                    'installation_date' => $data['installation_date'],
                    'use_existing_secret' => 0
                ];
                
                $result = Customer::create($createData);
                
                if ($result['success']) {
                    $successCount++;
                } else {
                    $failCount++;
                    $errors[] = "Baris $lineNumber ({$data['nama']}): " . ($result['error'] ?? 'Unknown error');
                }
                
            } catch (\Throwable $e) {
                $failCount++;
                $errors[] = "Baris $lineNumber: " . $e->getMessage();
            }
        }
        
        logActivity($currentUserId, 'import_customers', 
            "[{$userBranchName}] Import: $successCount berhasil, $failCount gagal");
        
        $message = "✅ Import selesai: <strong>$successCount berhasil</strong>, $failCount gagal";
        if (!empty($errors)) {
            $_SESSION['import_errors'] = array_slice($errors, 0, 20);
            if (count($errors) > 20) {
                $_SESSION['import_errors'][] = "... dan " . (count($errors) - 20) . " error lainnya";
            }
        }
        
        redirect('/branch/customers.php', $message, $failCount > 0 ? 'warning' : 'success');
        
    } catch (\Throwable $e) {
        redirect('/branch/customers.php', '❌ Error import: ' . $e->getMessage(), 'error');
    }
}

// ============================================================================
// HANDLE ACTIONS (GET)
// ============================================================================
if (isset($_GET['action']) && isset($_GET['id']) && verifyCsrf($_GET['token'] ?? '')) {
    $action = $_GET['action'];
    $customerId = (int) $_GET['id'];
    
    $customer = Customer::find($customerId);
    if (!$customer || (int)$customer['branch_id'] !== $userBranchId) {
        redirect('/branch/customers.php', '❌ Pelanggan tidak ditemukan atau bukan milik cabang Anda', 'error');
    }
    
    switch ($action) {
        case 'generate_bill':
            $result = Bill::generate($customerId);
            if ($result['success']) {
                logActivity($currentUserId, 'generate_bill', "[{$userBranchName}] Generate tagihan #{$result['bill_number']} untuk {$customer['name']}");
                redirect('/branch/customers.php', "✅ Tagihan berhasil: {$result['bill_number']} - Rp " . number_format($result['amount']));
            } else {
                redirect('/branch/customers.php', '❌ ' . $result['error'], 'error');
            }
            break;
            
        case 'suspend':
            try {
                $mt = new MikroTik($userBranchId);
                $result = $mt->suspendCustomer($customer['pppoe_username']);
                if ($result['success']) {
                    Customer::update($customerId, ['status' => 'suspended']);
                    logActivity($currentUserId, 'suspend', "[{$userBranchName}] Suspend: {$customer['name']}");
                    redirect('/branch/customers.php', '✅ Pelanggan di-suspend');
                } else {
                    redirect('/branch/customers.php', '❌ Gagal: ' . $result['error'], 'error');
                }
            } catch (\Throwable $e) {
                redirect('/branch/customers.php', '❌ Error: ' . $e->getMessage(), 'error');
            }
            break;
            
        case 'restore':
            try {
                $mt = new MikroTik($userBranchId);
                $result = $mt->restoreCustomer($customer['pppoe_username']);
                if ($result['success']) {
                    Customer::update($customerId, ['status' => 'active']);
                    logActivity($currentUserId, 'restore', "[{$userBranchName}] Restore: {$customer['name']}");
                    redirect('/branch/customers.php', '✅ Pelanggan di-restore');
                } else {
                    redirect('/branch/customers.php', '❌ Gagal: ' . $result['error'], 'error');
                }
            } catch (\Throwable $e) {
                redirect('/branch/customers.php', '❌ Error: ' . $e->getMessage(), 'error');
            }
            break;
            
        case 'delete':
            try {
                $mt = new MikroTik($userBranchId);
                $mt->removeSecret($customer['pppoe_username']);
            } catch (\Throwable $e) {}
            Customer::delete($customerId);
            logActivity($currentUserId, 'delete', "[{$userBranchName}] Hapus: {$customer['name']}");
            redirect('/branch/customers.php', '✅ Pelanggan dihapus');
            break;
    }
}

// ============================================================================
// 💰 HANDLE MANUAL PAYMENT (POST FROM MODAL) - DIPERBAIKI + NOTIFIKASI WA
// ============================================================================
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['submit_pay']) && verifyCsrf($_POST['csrf_token'] ?? '')) {
    $billId = (int) $_POST['bill_id'];
    $customerId = (int) ($_POST['customer_id'] ?? 0);
    $paymentMethod = $_POST['payment_method'] ?? 'Tunai';
    $category = $_POST['category'] ?? 'Pelunasan Tagihan';
    
    if (!Bill::hasAccess($billId, $userBranchId)) {
        redirect('/branch/customers.php', '❌ Tagihan bukan milik cabang Anda', 'error');
    }
    
    // Proses pembayaran
   $result = Bill::pay($billId, $paymentMethod, $category, 'cash');
    $bill = Bill::find($billId);
    
    if ($result['success']) {
        if ($customerId === 0 && isset($result['customer_id'])) {
            $customerId = (int) $result['customer_id'];
        }
        $customer = Customer::find($customerId);
        
        if ($customer) {
            // 1. Update status customer ke 'active' jika sebelumnya 'suspended'
            if ($customer['status'] === 'suspended') {
                Customer::update($customerId, ['status' => 'active']);
            }
            
            // 2. SELALU trigger restore/enable secret di MikroTik
            try {
                $mt = new MikroTik($userBranchId);
                $mt->restoreCustomer($customer['pppoe_username']);
            } catch (\Throwable $e) {
                // Log error tapi jangan gagalkan proses
            }
            
            // 3. ⭐ KIRIM NOTIFIKASI WHATSAPP SUKSES BAYAR
            $wablasToken = '';
            $wablasBaseUrl = '';
            try {
                $hasBranchCol = $db->query("SHOW COLUMNS FROM wa_config LIKE 'branch_id'")->fetch();
                if ($hasBranchCol) {
                    $stmtWa = $db->prepare("SELECT setting_key, setting_value FROM wa_config WHERE branch_id = ? AND setting_key IN ('wablas_token', 'wablas_base_url')");
                    $stmtWa->execute([$userBranchId]);
                } else {
                    $stmtWa = $db->prepare("SELECT setting_key, setting_value FROM wa_config WHERE setting_key IN (?, ?)");
                    $stmtWa->execute(['wablas_token_branch_' . $userBranchId, 'wablas_base_url_branch_' . $userBranchId]);
                }
                
                while ($rowWa = $stmtWa->fetch()) {
                    $key = $rowWa['setting_key'];
                    if (!$hasBranchCol) $key = str_replace('_branch_' . $userBranchId, '', $key);
                    if ($key === 'wablas_token') $wablasToken = $rowWa['setting_value'];
                    if ($key === 'wablas_base_url') $wablasBaseUrl = rtrim($rowWa['setting_value'], '/');
                }
            } catch (\Throwable $e) {}
            
            // Kirim WA jika token ada dan nomor HP ada
            if (!empty($wablasToken) && !empty($wablasBaseUrl) && !empty($customer['phone'])) {
                $phone = preg_replace('/[^0-9]/', '', $customer['phone']);
                if (substr($phone, 0, 1) === '0') $phone = '62' . substr($phone, 1);
                elseif (substr($phone, 0, 2) !== '62') $phone = '62' . $phone;
                
                // Ambil nama paket
                $packageName = '-';
                if (!empty($customer['package_id'])) {
                    $stmtPkg = $db->prepare("SELECT name FROM packages WHERE id = ?");
                    $stmtPkg->execute([$customer['package_id']]);
                    $pkg = $stmtPkg->fetch();
                    if ($pkg) $packageName = $pkg['name'];
                }
                
                // Default message
                $waMessage = "✅ *PEMBAYARAN BERHASIL*\n\nHalo {$customer['name']},\nPembayaran tagihan internet Anda telah kami terima.\n\n👤 No. Pelanggan : {$customer['customer_number']}\n📦 Paket : {$packageName}\n💰 Metode : {$paymentMethod}\n📅 Masa Aktif s/d : " . ($result['active_until'] ? date('d/m/Y', strtotime($result['active_until'])) : '-') . "\n\nTerima kasih telah berlangganan!";
                
                // Coba ambil template dari database (slug: payment_success)
                // Coba ambil template dari database (slug: payment_success)
try {
    $tableExists = $db->query("SHOW TABLES LIKE 'wa_templates'")->fetch();
    if ($tableExists) {
        $stmtTpl = $db->prepare("SELECT message FROM wa_templates WHERE slug = 'payment_success' AND (branch_id IS NULL OR branch_id = ?) LIMIT 1");
        $stmtTpl->execute([$userBranchId]);
        $tpl = $stmtTpl->fetchColumn();
        if ($tpl) {
            // ⭐ DIPERBAIKI: Tambahkan placeholder {date}, {due_date}, {bill_number}
            $waMessage = str_replace(
                // Placeholder (bisa pakai kurung siku [] atau kurung kurawal {})
                ['[nama]', '[Nama]', '{name}', 
                 '[customer_number]', 
                 '[paket]', '[Paket]', 
                 '{method}', 
                 '{amount}', '[amount]', 
                 '{active_until}', 
                 '{date}', '[date]', 
                 '{due_date}', '[due_date]',
                 '{bill_number}', '[bill_number]'],
                // Nilai pengganti
                [
                    $customer['name'],
                    $customer['name'],
                    $customer['name'],
                    $customer['customer_number'] ?? '-',
                    $packageName,
                    $packageName,
                    $paymentMethod,
                    number_format($result['amount'] ?? 0, 0, ',', '.'),
                    number_format($result['amount'] ?? 0, 0, ',', '.'),
                    $result['active_until'] ? date('d/m/Y', strtotime($result['active_until'])) : '-',
                    date('d/m/Y'),                                    // {date} = hari ini
                    date('d/m/Y'),                                    // [date] = hari ini
                    !empty($bill['due_date']) ? date('d/m/Y', strtotime($bill['due_date'])) : '-', // {due_date}
                    !empty($bill['due_date']) ? date('d/m/Y', strtotime($bill['due_date'])) : '-', // [due_date]
                    $bill['bill_number'] ?? '-',                      // {bill_number}
                    $bill['bill_number'] ?? '-'                       // [bill_number}
                ],
                $tpl
            );
        }
    }
} catch (\Throwable $e) {}
                
               // Kirim via Wablas API
try {
    $url = $wablasBaseUrl . '/send-message?' . http_build_query([
        'phone' => $phone, 
        'message' => $waMessage, 
        'token' => $wablasToken
    ]);
    $curl = curl_init();
    curl_setopt_array($curl, [
        CURLOPT_URL => $url,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_TIMEOUT => 10,
        CURLOPT_SSL_VERIFYHOST => 0,
        CURLOPT_SSL_VERIFYPEER => 0
    ]);
    $result = curl_exec($curl);
    $httpCode = curl_getinfo($curl, CURLINFO_HTTP_CODE);
    curl_close($curl);
    
    $decoded = json_decode($result, true);
    $waSuccess = ($httpCode == 200 && isset($decoded['status']) && $decoded['status'] === true);
    
    // ⭐ CATAT LOG KE broadcast_logs
    if ($waSuccess || true) { // Catat baik sukses maupun gagal
        try {
            $checkCol = $db->query("SHOW COLUMNS FROM broadcast_logs LIKE 'source'")->fetch();
            $hasSource = !empty($checkCol);
            
            if ($hasSource) {
                $stmtLog = $db->prepare("
                    INSERT INTO broadcast_logs 
                    (title, message, target_type, source, total_targets, sent_count, failed_count, status, branch_id, created_by, created_at) 
                    VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, NOW())
                ");
                $stmtLog->execute([
                    '✅ Notifikasi Sukses Bayar - ' . $customer['name'],
                    $waMessage,
                    'single_customer',
                    'payment_success',
                    1,
                    $waSuccess ? 1 : 0,
                    $waSuccess ? 0 : 1,
                    $waSuccess ? 'completed' : 'failed',
                    $userBranchId,
                    $currentUserId
                ]);
            }
        } catch (\Throwable $logErr) {
            error_log("Log broadcast error: " . $logErr->getMessage());
        }
    }
} catch (\Throwable $e) {
    error_log("WA notification error: " . $e->getMessage());
}
            }
        }
        
        // 4. Generate tagihan bulan depan
        if (method_exists('Bill', 'generateNextMonth')) {
            Bill::generateNextMonth($customerId);
        } else {
            Bill::generate($customerId);
        }
        
        $activeUntilInfo = '';
        if (!empty($result['active_until'])) {
            $activeUntilInfo = " | 📅 Masa aktif sampai: " . date('d/m/Y', strtotime($result['active_until']));
        }
        
        logActivity(
            $currentUserId, 
            'pay_bill', 
            "[{$userBranchName}] 💰 Pembayaran cash - Tagihan #$billId via $paymentMethod ($category) - Aktif sampai " . ($result['active_until'] ?? '-')
        );
        
        redirect('/branch/customers.php', '✅ Pembayaran berhasil!' . $activeUntilInfo . ' & tagihan bulan depan sudah digenerate');
    } else {
        redirect('/branch/customers.php', '❌ ' . $result['error'], 'error');
    }
}
// Bulk actions
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['bulk_action']) && verifyCsrf($_POST['csrf_token'] ?? '')) {
    $action = $_POST['bulk_action'];
    $selectedIds = $_POST['selected_customers'] ?? [];
    $successCount = $failCount = 0;
    
    foreach ($selectedIds as $id) {
        $customer = Customer::find((int)$id);
        if (!$customer || (int)$customer['branch_id'] !== $userBranchId) {
            $failCount++;
            continue;
        }
        
        try {
            switch ($action) {
                case 'generate_bill':
                    if (Bill::generate($id)['success']) $successCount++; else $failCount++;
                    break;
                case 'suspend':
                    $mt = new MikroTik($userBranchId);
                    if ($mt->suspendCustomer($customer['pppoe_username'])['success']) {
                        Customer::update($id, ['status' => 'suspended']);
                        $successCount++;
                    } else $failCount++;
                    break;
                case 'restore':
                    $mt = new MikroTik($userBranchId);
                    if ($mt->restoreCustomer($customer['pppoe_username'])['success']) {
                        Customer::update($id, ['status' => 'active']);
                        $successCount++;
                    } else $failCount++;
                    break;
            }
        } catch (\Throwable $e) {
            $failCount++;
        }
    }
    
    logActivity($currentUserId, 'bulk', "[{$userBranchName}] Bulk $action: $successCount berhasil, $failCount gagal");
    redirect('/branch/customers.php', "Bulk action: Berhasil $successCount, Gagal $failCount");
}

// ============================================================================
// HELPER FUNCTIONS
// ============================================================================
function formatDueDateInfo($dueDate) {
    $hariIndonesia = ['Minggu', 'Senin', 'Selasa', 'Rabu', 'Kamis', 'Jumat', 'Sabtu'];
    $bulanIndonesia = [
        1 => 'Januari', 'Februari', 'Maret', 'April', 'Mei', 'Juni',
        'Juli', 'Agustus', 'September', 'Oktober', 'November', 'Desember'
    ];
    
    $timestamp = strtotime($dueDate);
    $hari = $hariIndonesia[date('w', $timestamp)];
    $tanggal = date('j', $timestamp);
    $bulan = $bulanIndonesia[(int)date('n', $timestamp)];
    $tahun = date('Y', $timestamp);
    
    $today = strtotime('today');
    $dueDay = strtotime(date('Y-m-d', $timestamp));
    $daysDiff = floor(($dueDay - $today) / 86400);
    
    if ($daysDiff > 0) {
        $countdown = "($daysDiff hari lagi)";
        $statusClass = 'warning';
        $statusIcon = '⏳';
    } elseif ($daysDiff == 0) {
        $countdown = '(HARI INI!)';
        $statusClass = 'danger';
        $statusIcon = '🔥';
    } else {
        $daysOverdue = abs($daysDiff);
        $countdown = "(Terlambat $daysOverdue hari)";
        $statusClass = 'danger';
        $statusIcon = '⚠️';
    }
    
    return [
        'full' => "$hari, $tanggal $bulan $tahun",
        'short' => "$tanggal $bulan $tahun",
        'countdown' => $countdown,
        'status_class' => $statusClass,
        'status_icon' => $statusIcon,
        'days_diff' => $daysDiff
    ];
}

function formatActiveUntilInfo($activeUntil) {
    if (empty($activeUntil)) {
        return ['status' => 'unknown', 'text' => 'Belum ada data', 'class' => 'secondary'];
    }
    
    $bulanShort = [
        1 => 'Jan', 'Feb', 'Mar', 'Apr', 'Mei', 'Jun',
        'Jul', 'Agu', 'Sep', 'Okt', 'Nov', 'Des'
    ];
    
    $timestamp = strtotime($activeUntil);
    $tanggal = date('j', $timestamp);
    $bulan = $bulanShort[(int)date('n', $timestamp)];
    $tahun = date('Y', $timestamp);
    
    $now = time();
    $untilTs = strtotime($activeUntil);
    $daysLeft = floor(($untilTs - $now) / 86400);
    
    if ($daysLeft > 7) {
        $status = 'active';
        $text = "Aktif $daysLeft hari lagi";
        $class = 'success';
    } elseif ($daysLeft > 0) {
        $status = 'expiring';
        $text = "Segera habis ($daysLeft hari)";
        $class = 'warning';
    } elseif ($daysLeft == 0) {
        $status = 'expiring';
        $text = "Habis HARI INI";
        $class = 'danger';
    } else {
        $status = 'expired';
        $text = "Expired " . abs($daysLeft) . " hari lalu";
        $class = 'danger';
    }
    
    return [
        'status' => $status,
        'short' => "$tanggal $bulan $tahun",
        'text' => $text,
        'class' => $class,
        'days_left' => $daysLeft
    ];
}

// Load customers
$customers = [];
try {
    $stmt = $db->prepare("
        SELECT c.*, p.name as package_name
        FROM customers c
        LEFT JOIN packages p ON c.package_id = p.id
        WHERE c.branch_id = ?
        ORDER BY c.name ASC
    ");
    $stmt->execute([$userBranchId]);
    $customers = $stmt->fetchAll();
} catch (\Throwable $e) {}

// MikroTik connections
$activeConnections = [];
$mtConnected = false;
try {
    $mt = new MikroTik($userBranchId);
    $actives = $mt->getActiveConnections();
    $mtConnected = empty($mt->lastError);
    foreach ($actives as $a) {
        $activeConnections[$a['name']] = ['uptime' => $a['uptime'] ?? '-'];
    }
} catch (\Throwable $e) {}

foreach ($customers as &$c) {
    $u = $c['pppoe_username'] ?? '';
    $c['internet_status'] = isset($activeConnections[$u]) ? 'connected' : 'disconnected';
    $c['uptime'] = $activeConnections[$u]['uptime'] ?? '-';
    $unpaid = Bill::getLatestUnpaid($c['id']);
    $c['has_unpaid_bill'] = !empty($unpaid);
    $c['unpaid_bill'] = $unpaid;
    
    if ($unpaid) {
        $c['due_date_info'] = formatDueDateInfo($unpaid['due_date']);
    }
    $c['active_until_info'] = formatActiveUntilInfo($c['active_until'] ?? null);
}
unset($c);

// Filter
$filterStatus = $_GET['status'] ?? '';
$filterInternet = $_GET['internet'] ?? '';
$filterBill = $_GET['bill'] ?? '';
$search = $_GET['search'] ?? '';

if ($filterStatus || $filterInternet || $filterBill || $search) {
    $filtered = [];
    foreach ($customers as $c) {
        if ($filterStatus && $c['status'] !== $filterStatus) continue;
        if ($filterInternet && $c['internet_status'] !== $filterInternet) continue;
        if ($filterBill === 'unpaid' && empty($c['has_unpaid_bill'])) continue;
        if ($filterBill === 'paid' && !empty($c['has_unpaid_bill'])) continue;
        if ($search && stripos($c['name'] . ' ' . $c['customer_number'] . ' ' . $c['phone'] . ' ' . $c['pppoe_username'], $search) === false) continue;
        $filtered[] = $c;
    }
    $customers = $filtered;
}

// Stats
$totalCustomers = count($customers);
$totalActive = count(array_filter($customers, fn($c) => $c['status'] === 'active'));
$totalSuspended = count(array_filter($customers, fn($c) => $c['status'] === 'suspended'));
$totalOnline = count(array_filter($customers, fn($c) => $c['internet_status'] === 'connected'));
$totalUnpaid = count(array_filter($customers, fn($c) => $c['has_unpaid_bill']));
$totalExpiring = count(array_filter($customers, fn($c) => ($c['active_until_info']['days_left'] ?? 999) <= 7 && ($c['active_until_info']['days_left'] ?? 999) >= 0));

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

<style>
/* === NAVBAR MODERN === */
.navbar-modern { background: linear-gradient(135deg, #0066CC 0%, #00B4FF 100%); padding: 15px 20px; display: flex; align-items: center; justify-content: space-between; box-shadow: 0 2px 10px rgba(0,0,0,0.1); position: sticky; top: 0; z-index: 1000; }
.navbar-left { display: flex; align-items: center; gap: 15px; }
.burger-btn { background: rgba(255,255,255,0.15); border: none; color: white; width: 40px; height: 40px; border-radius: 10px; cursor: pointer; display: flex; align-items: center; justify-content: center; font-size: 1.3rem; transition: all 0.3s ease; }
.burger-btn:hover { background: rgba(255,255,255,0.25); transform: scale(1.05); }
.navbar-title { color: white; font-size: 1.2rem; font-weight: 700; margin: 0; }
.navbar-subtitle { color: rgba(255,255,255,0.85); font-size: 0.78rem; margin: 0; }
.navbar-right { display: flex; align-items: center; gap: 10px; }
.navbar-badge { background: rgba(255,255,255,0.2); color: white; padding: 6px 12px; border-radius: 20px; font-size: 0.82rem; font-weight: 500; display: inline-flex; align-items: center; gap: 6px; }
.main-content { padding: 20px; max-width: 1400px; margin: 0 auto; }
.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: #0066CC; }
.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; }

/* === BUTTONS === */
.btn-add { padding: 12px 24px; background: linear-gradient(135deg, #0066CC 0%, #00B4FF 100%); color: white; 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; gap: 8px; text-decoration: none; box-shadow: 0 4px 15px rgba(0, 102, 204, 0.3); }
.btn-add:hover { transform: translateY(-2px); box-shadow: 0 6px 20px rgba(0, 102, 204, 0.4); color: white; }
.btn-export { padding: 12px 24px; background: linear-gradient(135deg, #00C853 0%, #69F0AE 100%); color: white; 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; gap: 8px; text-decoration: none; box-shadow: 0 4px 15px rgba(0, 200, 83, 0.3); }
.btn-export:hover { transform: translateY(-2px); box-shadow: 0 6px 20px rgba(0, 200, 83, 0.4); color: white; }
.btn-import { padding: 12px 24px; background: linear-gradient(135deg, #FF9900 0%, #FFB84D 100%); color: white; 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; gap: 8px; text-decoration: none; box-shadow: 0 4px 15px rgba(255, 153, 0, 0.3); }
.btn-import:hover { transform: translateY(-2px); box-shadow: 0 6px 20px rgba(255, 153, 0, 0.4); color: white; }
.header-actions { display: flex; gap: 10px; flex-wrap: wrap; }

/* === SUMMARY CARDS === */
.summary-row { display: grid; grid-template-columns: repeat(auto-fit, minmax(180px, 1fr)); gap: 14px; margin-bottom: 20px; }
.summary-card { background: white; border-radius: 14px; padding: 16px; box-shadow: 0 4px 15px rgba(0,0,0,0.06); position: relative; overflow: hidden; transition: all 0.3s ease; border-left: 4px solid; }
.summary-card:hover { transform: translateY(-3px); box-shadow: 0 8px 20px rgba(0,0,0,0.1); }
.summary-card.primary { border-left-color: #0066CC; }
.summary-card.success { border-left-color: #00C853; }
.summary-card.warning { border-left-color: #FF9900; }
.summary-card.danger { border-left-color: #DC3545; }
.summary-card.info { border-left-color: #00B8D4; }
.summary-card.purple { border-left-color: #7c3aed; }
.summary-card-header { display: flex; align-items: center; justify-content: space-between; margin-bottom: 8px; }
.summary-card-title { color: #666; font-size: 0.75rem; font-weight: 600; margin: 0; text-transform: uppercase; letter-spacing: 0.5px; }
.summary-card-icon { width: 36px; height: 36px; border-radius: 10px; display: flex; align-items: center; justify-content: center; color: white; font-size: 1rem; }
.summary-card.primary .summary-card-icon { background: linear-gradient(135deg, #0066CC 0%, #00B4FF 100%); }
.summary-card.success .summary-card-icon { background: linear-gradient(135deg, #00C853 0%, #69F0AE 100%); }
.summary-card.warning .summary-card-icon { background: linear-gradient(135deg, #FF9900 0%, #FFB84D 100%); }
.summary-card.danger .summary-card-icon { background: linear-gradient(135deg, #DC3545 0%, #FF6B7A 100%); }
.summary-card.info .summary-card-icon { background: linear-gradient(135deg, #00B8D4 0%, #26C6DA 100%); }
.summary-card.purple .summary-card-icon { background: linear-gradient(135deg, #7c3aed 0%, #a78bfa 100%); }
.summary-card-value { font-size: 1.5rem; font-weight: 800; margin-bottom: 2px; letter-spacing: -0.5px; }
.summary-card.primary .summary-card-value { color: #0066CC; }
.summary-card.success .summary-card-value { color: #00C853; }
.summary-card.warning .summary-card-value { color: #FF9900; }
.summary-card.danger .summary-card-value { color: #DC3545; }
.summary-card.info .summary-card-value { color: #00B8D4; }
.summary-card.purple .summary-card-value { color: #7c3aed; }
.summary-card-footer { font-size: 0.75rem; color: #999; }

/* === ALERTS === */
.alert-modern { padding: 14px 18px; border-radius: 12px; margin-bottom: 16px; display: flex; align-items: flex-start; gap: 12px; font-size: 0.9rem; 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 === */
.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.primary { background: linear-gradient(135deg, #0066CC 0%, #00B4FF 100%); }
.card-header-modern .title-left { display: flex; align-items: center; gap: 10px; }
.card-body-modern { padding: 20px; }

/* === FILTER === */
.filter-form { display: grid; grid-template-columns: repeat(auto-fit, minmax(150px, 1fr)); gap: 12px; align-items: end; }
.form-group-filter { margin-bottom: 0; }
.form-label-filter { display: block; font-weight: 600; color: #003D7A; margin-bottom: 6px; font-size: 0.8rem; }
.form-control-filter, .form-select-filter { width: 100%; padding: 10px 14px; border: 2px solid #e8f4f8; border-radius: 10px; font-size: 0.88rem; transition: all 0.3s ease; background: #f8fafc; font-family: inherit; }
.form-control-filter:focus, .form-select-filter:focus { outline: none; border-color: #0066CC; background: white; box-shadow: 0 0 0 4px rgba(0, 102, 204, 0.1); }
.btn-filter { padding: 10px 16px; border: none; border-radius: 10px; font-size: 0.88rem; font-weight: 600; cursor: pointer; transition: all 0.3s ease; display: inline-flex; align-items: center; justify-content: center; gap: 6px; text-decoration: none; white-space: nowrap; height: 42px; }
.btn-filter.primary { background: linear-gradient(135deg, #0066CC 0%, #00B4FF 100%); color: white; box-shadow: 0 4px 12px rgba(0, 102, 204, 0.3); }
.btn-filter.outline { background: white; color: #666; border: 2px solid #e8f4f8; }

/* === TABLE === */
.table-wrapper { background: white; border-radius: 16px; box-shadow: 0 4px 20px rgba(0,0,0,0.08); overflow: hidden; margin-bottom: 20px; }
.table-header { background: linear-gradient(135deg, #0066CC 0%, #00B4FF 100%); color: white; padding: 16px 20px; display: flex; align-items: center; justify-content: space-between; gap: 10px; flex-wrap: wrap; }
.table-header-title { display: flex; align-items: center; gap: 10px; font-weight: 600; font-size: 1rem; }
.table-header-count { background: rgba(255,255,255,0.2); padding: 4px 12px; border-radius: 20px; font-size: 0.82rem; font-weight: 600; }
.table-header-actions { display: flex; align-items: center; gap: 10px; }
.bulk-select-modern { padding: 8px 12px; border: 2px solid rgba(255,255,255,0.3); border-radius: 8px; background: rgba(255,255,255,0.1); color: white; font-size: 0.85rem; font-family: inherit; cursor: pointer; }
.bulk-select-modern option { background: white; color: #333; }
.table-scroll { overflow-x: auto; -webkit-overflow-scrolling: touch; }
.table-modern { width: 100%; border-collapse: separate; border-spacing: 0; font-size: 0.88rem; min-width: 1300px; }
.table-modern thead { background: #f8fafc; position: sticky; top: 0; z-index: 10; }
.table-modern th { padding: 12px 14px; text-align: left; font-weight: 700; color: #003D7A; border-bottom: 2px solid #e8f4f8; font-size: 0.78rem; text-transform: uppercase; letter-spacing: 0.5px; white-space: nowrap; }
.table-modern td { padding: 12px 14px; border-bottom: 1px solid #f0f0f0; vertical-align: middle; }
.table-modern tbody tr { transition: all 0.2s ease; }
.table-modern tbody tr:hover { background: #f8fafc; }
.table-modern tbody tr:last-child td { border-bottom: none; }
.table-modern tbody tr.row-suspended { background: #fff8f8; }
.table-modern tbody tr.row-suspended:hover { background: #fff0f0; }
.table-modern tbody tr.row-unpaid { background: #fffdf5; }
.table-modern tbody tr.row-unpaid:hover { background: #fffae8; }
.checkbox-modern { width: 18px; height: 18px; cursor: pointer; accent-color: #0066CC; }

.customer-cell { display: flex; align-items: center; gap: 10px; }
.customer-avatar { width: 36px; height: 36px; border-radius: 50%; display: flex; align-items: center; justify-content: center; font-weight: 700; color: white; font-size: 0.85rem; flex-shrink: 0; }
.customer-avatar.active { background: linear-gradient(135deg, #00C853 0%, #69F0AE 100%); }
.customer-avatar.suspended { background: linear-gradient(135deg, #DC3545 0%, #FF6B7A 100%); }
.customer-avatar.inactive { background: linear-gradient(135deg, #607D8B 0%, #90A4AE 100%); }
.customer-name { font-weight: 700; color: #003D7A; font-size: 0.88rem; margin: 0; line-height: 1.3; }
.customer-number { font-size: 0.75rem; color: #999; margin-top: 1px; }

.badge-modern { display: inline-flex; align-items: center; gap: 4px; padding: 4px 10px; border-radius: 20px; font-size: 0.72rem; font-weight: 700; text-transform: uppercase; letter-spacing: 0.5px; white-space: nowrap; }
.badge-modern.active { background: #d1e7dd; color: #0f5132; }
.badge-modern.suspended { background: #f8d7da; color: #842029; }
.badge-modern.inactive { background: #e9ecef; color: #41464b; }
.badge-modern.online { background: #d1e7dd; color: #0f5132; }
.badge-modern.offline { background: #e9ecef; color: #41464b; }
.badge-modern.unpaid { background: #fff3cd; color: #856404; }
.badge-modern.paid { background: #d1e7dd; color: #0f5132; }
.badge-modern.package { background: #cfe2ff; color: #084298; text-transform: none; }

.bill-info-block { background: #fffdf5; border: 1px solid #ffe082; border-radius: 8px; padding: 8px 10px; font-size: 0.75rem; line-height: 1.5; min-width: 180px; }
.bill-info-block.danger { background: #fff5f5; border-color: #ef9a9a; }
.bill-info-block .bill-amount { font-weight: 700; color: #003D7A; font-size: 0.85rem; display: block; margin-bottom: 4px; }
.bill-info-block .bill-duedate { color: #555; display: flex; align-items: center; gap: 4px; margin-bottom: 2px; }
.bill-info-block .bill-duedate strong { color: #003D7A; }
.bill-info-block .bill-countdown { display: inline-block; padding: 2px 8px; border-radius: 10px; font-size: 0.7rem; font-weight: 700; margin-top: 3px; }
.bill-info-block .bill-countdown.warning { background: #fff3cd; color: #856404; }
.bill-info-block .bill-countdown.danger { background: #f8d7da; color: #842029; }

.active-until-block { background: #f0fdf4; border: 1px solid #a5d6a7; border-radius: 8px; padding: 8px 10px; font-size: 0.75rem; line-height: 1.5; min-width: 160px; }
.active-until-block.warning { background: #fffdf5; border-color: #ffe082; }
.active-until-block.danger { background: #fff5f5; border-color: #ef9a9a; }
.active-until-block.unknown { background: #f5f5f5; border-color: #e0e0e0; }
.active-until-block .active-label { font-size: 0.7rem; color: #666; text-transform: uppercase; font-weight: 600; letter-spacing: 0.3px; display: block; margin-bottom: 3px; }
.active-until-block .active-date { font-weight: 700; color: #003D7A; font-size: 0.82rem; display: flex; align-items: center; gap: 4px; }
.active-until-block .active-status { display: inline-block; padding: 2px 8px; border-radius: 10px; font-size: 0.68rem; font-weight: 700; margin-top: 3px; }
.active-until-block .active-status.success { background: #d1e7dd; color: #0f5132; }
.active-until-block .active-status.warning { background: #fff3cd; color: #856404; }
.active-until-block .active-status.danger { background: #f8d7da; color: #842029; }

.action-buttons { display: flex; gap: 4px; flex-wrap: nowrap; }
.btn-action { width: 32px; height: 32px; border: none; border-radius: 8px; display: flex; align-items: center; justify-content: center; cursor: pointer; transition: all 0.3s ease; font-size: 0.88rem; text-decoration: none; flex-shrink: 0; }
.btn-action.pay { background: #d1e7dd; color: #0f5132; }
.btn-action.pay:hover { background: #00C853; color: white; transform: translateY(-2px); box-shadow: 0 4px 12px rgba(0, 200, 83, 0.3); }
.btn-action.generate { background: #cfe2ff; color: #084298; }
.btn-action.generate:hover { background: #0066CC; color: white; transform: translateY(-2px); box-shadow: 0 4px 12px rgba(0, 102, 204, 0.3); }
.btn-action.link { background: #cff4fc; color: #055160; }
.btn-action.link:hover { background: #00B8D4; color: white; transform: translateY(-2px); box-shadow: 0 4px 12px rgba(0, 184, 212, 0.3); }
.btn-action.edit { background: #fff3cd; color: #856404; }
.btn-action.edit:hover { background: #FF9900; color: white; transform: translateY(-2px); box-shadow: 0 4px 12px rgba(255, 153, 0, 0.3); }
.btn-action.wa { background: #d1e7dd; color: #0f5132; }
.btn-action.wa:hover { background: #25D366; color: white; transform: translateY(-2px); box-shadow: 0 4px 12px rgba(37, 211, 102, 0.3); }
.btn-action.suspend { background: #f8d7da; color: #842029; }
.btn-action.suspend:hover { background: #DC3545; color: white; transform: translateY(-2px); box-shadow: 0 4px 12px rgba(220, 53, 69, 0.3); }
.btn-action.restore { background: #cff4fc; color: #055160; }
.btn-action.restore:hover { background: #00B8D4; color: white; transform: translateY(-2px); box-shadow: 0 4px 12px rgba(0, 184, 212, 0.3); }
.btn-action.delete { background: #ffe5e5; color: #842029; }
.btn-action.delete:hover { background: #b02a37; color: white; transform: translateY(-2px); box-shadow: 0 4px 12px rgba(176, 42, 55, 0.3); }

.empty-state { text-align: center; padding: 50px 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 0 16px; }

/* === MODAL === */
.modal-overlay { position: fixed; top: 0; left: 0; right: 0; bottom: 0; background: rgba(0, 0, 0, 0.6); backdrop-filter: blur(4px); display: flex; align-items: center; justify-content: center; z-index: 9999; animation: fadeIn 0.2s ease; }
@keyframes fadeIn { from { opacity: 0; } to { opacity: 1; } }
.modal-content { background: white; border-radius: 16px; width: 90%; max-width: 550px; box-shadow: 0 10px 40px rgba(0,0,0,0.2); overflow: hidden; animation: slideDown 0.3s ease; max-height: 90vh; overflow-y: auto; }
@keyframes slideDown { from { opacity: 0; transform: translateY(-30px); } to { opacity: 1; transform: translateY(0); } }
.modal-header { background: linear-gradient(135deg, #0066CC 0%, #00B4FF 100%); color: white; padding: 16px 20px; display: flex; justify-content: space-between; align-items: center; position: sticky; top: 0; z-index: 10; }
.modal-header.import { background: linear-gradient(135deg, #FF9900 0%, #FFB84D 100%); }
.modal-header h3 { margin: 0; font-size: 1.1rem; display: flex; align-items: center; gap: 8px; font-weight: 700; }
.modal-close { background: rgba(255,255,255,0.2); border: none; color: white; font-size: 1.2rem; cursor: pointer; width: 32px; height: 32px; border-radius: 50%; display: flex; align-items: center; justify-content: center; transition: all 0.2s; }
.modal-close:hover { background: rgba(255,255,255,0.4); }
.modal-body { padding: 20px; }
.bill-summary { background: #f8fafc; padding: 12px; border-radius: 10px; margin-bottom: 16px; border-left: 4px solid #0066CC; }
.bill-summary p { margin: 4px 0; font-size: 0.85rem; color: #666; }
.bill-summary strong { color: #003D7A; }
.modal-body .form-group { margin-bottom: 15px; }
.modal-body label { display: flex; align-items: center; gap: 6px; font-weight: 600; color: #003D7A; margin-bottom: 6px; font-size: 0.85rem; }
.modal-footer { padding: 16px 20px; background: #f8fafc; display: flex; justify-content: flex-end; gap: 10px; border-top: 1px solid #e8f4f8; position: sticky; bottom: 0; }
.direct-payment-info { background: linear-gradient(135deg, #d4edda 0%, #c3e6cb 100%); color: #155724; padding: 10px 14px; border-radius: 10px; margin-bottom: 15px; font-size: 0.82rem; font-weight: 600; display: flex; align-items: center; gap: 8px; border: 1px solid #a3d9a5; }
.active-info-preview { background: linear-gradient(135deg, #e3f2fd 0%, #bbdefb 100%); color: #003D7A; padding: 10px 14px; border-radius: 10px; margin-bottom: 15px; font-size: 0.82rem; font-weight: 600; display: flex; align-items: center; gap: 8px; border: 1px solid #90caf9; }

/* === IMPORT MODAL SPECIFIC === */
.import-info {
    background: linear-gradient(135deg, #fff3e0 0%, #ffe0b2 100%);
    border: 2px solid #ffcc80;
    border-radius: 12px;
    padding: 14px;
    margin-bottom: 16px;
    font-size: 0.85rem;
    color: #e65100;
}
.import-info-title {
    display: flex;
    align-items: center;
    gap: 8px;
    font-weight: 700;
    margin-bottom: 8px;
    font-size: 0.9rem;
}
.import-info ul { margin: 8px 0 0 0; padding-left: 20px; }
.import-info li { margin-bottom: 4px; }

.file-upload-area {
    border: 2px dashed #0066CC;
    border-radius: 12px;
    padding: 30px 20px;
    text-align: center;
    background: #f8fafc;
    cursor: pointer;
    transition: all 0.3s ease;
    margin-bottom: 15px;
}
.file-upload-area:hover { background: #e3f2fd; border-color: #00B4FF; }
.file-upload-area.has-file { background: #e8f5e9; border-color: #00C853; border-style: solid; }
.file-upload-icon { font-size: 3rem; color: #0066CC; margin-bottom: 10px; }
.file-upload-text { font-size: 0.9rem; color: #666; margin-bottom: 8px; }
.file-upload-hint { font-size: 0.75rem; color: #999; }
.file-name-display {
    margin-top: 10px;
    padding: 8px 12px;
    background: white;
    border-radius: 8px;
    font-size: 0.85rem;
    color: #003D7A;
    font-weight: 600;
    display: none;
    align-items: center;
    gap: 8px;
}
.file-name-display i { color: #00C853; font-size: 1.2rem; }

.template-download-box {
    background: linear-gradient(135deg, #e3f2fd 0%, #bbdefb 100%);
    border: 2px solid #90caf9;
    border-radius: 12px;
    padding: 14px;
    margin-bottom: 16px;
    display: flex;
    align-items: center;
    justify-content: space-between;
    gap: 12px;
    flex-wrap: wrap;
}
.template-download-text {
    font-size: 0.85rem;
    color: #003D7A;
    font-weight: 600;
    display: flex;
    align-items: center;
    gap: 8px;
}
.btn-template {
    padding: 8px 16px;
    background: linear-gradient(135deg, #0066CC 0%, #00B4FF 100%);
    color: white;
    border: none;
    border-radius: 8px;
    font-size: 0.85rem;
    font-weight: 600;
    cursor: pointer;
    text-decoration: none;
    display: inline-flex;
    align-items: center;
    gap: 6px;
    transition: all 0.3s ease;
}
.btn-template:hover { transform: translateY(-2px); box-shadow: 0 4px 12px rgba(0, 102, 204, 0.3); color: white; }

.import-errors-box {
    background: #fff5f5;
    border: 2px solid #ef9a9a;
    border-radius: 12px;
    padding: 14px;
    margin-top: 16px;
    max-height: 200px;
    overflow-y: auto;
}
.import-errors-title {
    font-size: 0.85rem;
    font-weight: 700;
    color: #c62828;
    margin-bottom: 8px;
    display: flex;
    align-items: center;
    gap: 6px;
}
.main-content {
    padding: 16px;
    max-width: 900px;
    margin: 0 auto;

    display: flex;
    flex-direction: column;
    gap: 20px; /* jarak antar div */
}
.import-errors-list { list-style: none; padding: 0; margin: 0; font-size: 0.78rem; color: #555; }
.import-errors-list li { padding: 4px 0; border-bottom: 1px dashed #ef9a9a; }
.import-errors-list li:last-child { border-bottom: none; }

@media (max-width: 992px) { .filter-form { grid-template-columns: 1fr 1fr; } }
@media (max-width: 768px) {
    .navbar-modern { padding: 12px 15px; }
    .navbar-title { font-size: 1rem; }
    .navbar-subtitle, .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; }
    .header-actions { width: 100%; }
    .btn-add, .btn-export, .btn-import { flex: 1; justify-content: center; padding: 10px 12px; font-size: 0.85rem; }
    .summary-row { grid-template-columns: repeat(2, 1fr); gap: 10px; }
    .summary-card { padding: 12px; }
    .summary-card-value { font-size: 1.2rem; }
    .summary-card-title { font-size: 0.68rem; }
    .summary-card-icon { width: 32px; height: 32px; font-size: 0.9rem; }
    .card-header-modern { padding: 14px 16px; font-size: 0.95rem; }
    .card-body-modern { padding: 16px; }
    .filter-form { grid-template-columns: 1fr; }
    .btn-filter { width: 100%; }
    .table-header { padding: 14px 16px; }
    .table-header-title { font-size: 0.92rem; }
    .table-modern { font-size: 0.82rem; }
    .table-modern th, .table-modern td { padding: 10px 12px; }
    .customer-avatar { width: 32px; height: 32px; font-size: 0.8rem; }
    .customer-name { font-size: 0.82rem; }
    .btn-action { width: 30px; height: 30px; font-size: 0.82rem; }
    .bill-info-block, .active-until-block { min-width: 140px; padding: 6px 8px; }
    .modal-content { max-width: 95%; }
    .template-download-box { flex-direction: column; align-items: stretch; text-align: center; }
}
@media (max-width: 480px) {
    .navbar-modern { padding: 10px 12px; }
    .burger-btn { width: 36px; height: 36px; font-size: 1.1rem; }
    .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: 10px; }
    .summary-card-value { font-size: 1.05rem; }
    .summary-card-footer { font-size: 0.7rem; }
    .table-header { padding: 12px 14px; }
    .table-modern th, .table-modern td { padding: 8px 10px; }
    .customer-cell { gap: 8px; }
    .customer-avatar { width: 28px; height: 28px; font-size: 0.75rem; }
    .customer-name { font-size: 0.78rem; }
    .customer-number { font-size: 0.7rem; }
    .badge-modern { font-size: 0.68rem; padding: 3px 8px; }
    .btn-action { width: 28px; height: 28px; font-size: 0.78rem; }
    .action-buttons { gap: 3px; }
    .bill-info-block, .active-until-block { min-width: 120px; font-size: 0.7rem; }
    .header-actions { flex-direction: column; }
    .btn-add, .btn-export, .btn-import { width: 100%; }
}
</style>

<!-- Navbar -->

<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>
            <h1 class="navbar-title">Data Pelanggan</h1>
            <p class="navbar-subtitle"><i class="bi bi-building"></i> <?= htmlspecialchars($userBranchName) ?></p>
        </div>
    </div>
    <div class="navbar-right">
        <span class="navbar-badge"><i class="bi bi-building"></i> <?= htmlspecialchars($userBranchName) ?></span>
    </div>
</div>   
<div class="page-header">
       
        <div class="header-actions">
            <a href="/branch/customers.php?action=export&token=<?= csrfToken() ?>" class="btn-export" title="Export data pelanggan ke CSV">
                <i class="bi bi-download"></i>
                <span>Export</span>
            </a>
            <button type="button" class="btn-import" onclick="openImportModal()" title="Import data pelanggan dari CSV">
                <i class="bi bi-upload"></i>
                <span>Import</span>
            </button>
            <a href="/branch/customer_add.php" class="btn-add">
                <i class="bi bi-person-plus-fill"></i>
                <span>Tambah</span>
            </a>
        </div>
    </div>

    <?= flashMessage() ?>

    <?php if (!empty($_SESSION['import_errors'])): ?>
        <div class="import-errors-box">
            <div class="import-errors-title">
                <i class="bi bi-exclamation-triangle-fill"></i>
                <span>Detail Error Import:</span>
            </div>
            <ul class="import-errors-list">
                <?php foreach ($_SESSION['import_errors'] as $err): ?>
                    <li><?= htmlspecialchars($err) ?></li>
                <?php endforeach; ?>
            </ul>
        </div>
        <?php unset($_SESSION['import_errors']); ?>
    <?php endif; ?>

    <?php if (!$mtConnected): ?>
        <div class="alert-modern warning">
            <i class="bi bi-exclamation-triangle-fill"></i>
            <div><strong>MikroTik tidak terhubung.</strong> Status internet tidak dapat ditampilkan.</div>
        </div>
    <?php endif; ?>



    <!-- Summary Cards -->
    <div class="summary-row">
        <div class="summary-card primary">
            <div class="summary-card-header">
                <h6 class="summary-card-title">Total</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</div>
        </div>
        <div class="summary-card success">
            <div class="summary-card-header">
                <h6 class="summary-card-title">Aktif</h6>
                <div class="summary-card-icon"><i class="bi bi-check-circle-fill"></i></div>
            </div>
            <div class="summary-card-value"><?= number_format($totalActive) ?></div>
            <div class="summary-card-footer">✅ Pelanggan aktif</div>
        </div>
        <div class="summary-card danger">
            <div class="summary-card-header">
                <h6 class="summary-card-title">Suspended</h6>
                <div class="summary-card-icon"><i class="bi bi-pause-circle-fill"></i></div>
            </div>
            <div class="summary-card-value"><?= number_format($totalSuspended) ?></div>
            <div class="summary-card-footer">⏸️ Di-suspend</div>
        </div>
        <div class="summary-card info">
            <div class="summary-card-header">
                <h6 class="summary-card-title">Online</h6>
                <div class="summary-card-icon"><i class="bi bi-wifi"></i></div>
            </div>
            <div class="summary-card-value"><?= number_format($totalOnline) ?></div>
            <div class="summary-card-footer">🟢 Terhubung internet</div>
        </div>
        <div class="summary-card warning">
            <div class="summary-card-header">
                <h6 class="summary-card-title">Belum Bayar</h6>
                <div class="summary-card-icon"><i class="bi bi-exclamation-triangle-fill"></i></div>
            </div>
            <div class="summary-card-value"><?= number_format($totalUnpaid) ?></div>
            <div class="summary-card-footer">💰 Menunggu pembayaran</div>
        </div>
        <div class="summary-card purple">
            <div class="summary-card-header">
                <h6 class="summary-card-title">Segera Habis</h6>
                <div class="summary-card-icon"><i class="bi bi-hourglass-split"></i></div>
            </div>
            <div class="summary-card-value"><?= number_format($totalExpiring) ?></div>
            <div class="summary-card-footer">⏰ Masa aktif ≤ 7 hari</div>
        </div>
    </div>

    <!-- Filter -->
    <div class="card-modern">
        <div class="card-header-modern primary">
            <div class="title-left"><i class="bi bi-funnel-fill"></i><span>Filter & Pencarian</span></div>
        </div>
        <div class="card-body-modern">
            <form method="GET" class="filter-form">
                <div class="form-group-filter">
                    <label class="form-label-filter"><i class="bi bi-search"></i> Cari</label>
                    <input type="text" name="search" class="form-control-filter" value="<?= htmlspecialchars($search) ?>" placeholder="Nama, HP, username...">
                </div>
                <div class="form-group-filter">
                    <label class="form-label-filter"><i class="bi bi-circle"></i> Status</label>
                    <select name="status" class="form-select-filter">
                        <option value="">Semua</option>
                        <option value="active" <?= $filterStatus === 'active' ? 'selected' : '' ?>>Aktif</option>
                        <option value="suspended" <?= $filterStatus === 'suspended' ? 'selected' : '' ?>>Suspended</option>
                        <option value="inactive" <?= $filterStatus === 'inactive' ? 'selected' : '' ?>>Nonaktif</option>
                    </select>
                </div>
                <div class="form-group-filter">
                    <label class="form-label-filter"><i class="bi bi-wifi"></i> Internet</label>
                    <select name="internet" class="form-select-filter">
                        <option value="">Semua</option>
                        <option value="connected" <?= $filterInternet === 'connected' ? 'selected' : '' ?>>Online</option>
                        <option value="disconnected" <?= $filterInternet === 'disconnected' ? 'selected' : '' ?>>Offline</option>
                    </select>
                </div>
                <div class="form-group-filter">
                    <label class="form-label-filter"><i class="bi bi-receipt"></i> Tagihan</label>
                    <select name="bill" class="form-select-filter">
                        <option value="">Semua</option>
                        <option value="unpaid" <?= $filterBill === 'unpaid' ? 'selected' : '' ?>>Belum Bayar</option>
                        <option value="paid" <?= $filterBill === 'paid' ? 'selected' : '' ?>>Sudah Bayar</option>
                    </select>
                </div>
                <div style="display: flex; gap: 8px; grid-column: 1 / -1;">
                    <button type="submit" class="btn-filter primary" style="flex: 1;"><i class="bi bi-funnel"></i><span>Filter</span></button>
                    <a href="/branch/customers.php" class="btn-filter outline" style="flex: 1;"><i class="bi bi-arrow-counterclockwise"></i><span>Reset</span></a>
                </div>
            </form>
        </div>
    </div>

    <!-- Table -->
    <div class="table-wrapper">
        <div class="table-header">
            <div class="table-header-title">
                <i class="bi bi-people"></i>
                <span>Daftar Pelanggan</span>
                <span class="table-header-count"><?= count($customers) ?></span>
            </div>
            <?php if (count($customers) > 0): ?>
            <div class="table-header-actions">
                <form method="POST" id="bulkForm" style="margin: 0;">
                    <?= csrfField() ?>
                    <select name="bulk_action" class="bulk-select-modern" onchange="confirmBulkAction(this)">
                        <option value="">Bulk Action</option>
                        <option value="generate_bill">Generate Tagihan</option>
                        <option value="suspend">Suspend Selected</option>
                        <option value="restore">Restore Selected</option>
                    </select>
                </form>
            </div>
            <?php endif; ?>
        </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 pelanggan</h5>
                <p class="empty-state-subtitle">Belum ada data pelanggan yang sesuai filter</p>
                <a href="/branch/customer_add.php" class="btn-add"><i class="bi bi-person-plus-fill"></i><span>Tambah Pelanggan</span></a>
            </div>
        <?php else: ?>
            <form method="POST" id="bulkFormMain">
                <?= csrfField() ?>
                <div class="table-scroll">
                    <table class="table-modern">
                        <thead>
                            <tr>
                                <th style="width: 40px;"><input type="checkbox" id="selectAll" class="checkbox-modern" onchange="toggleSelectAll()"></th>
                                <th>Pelanggan</th>
                                <th>Paket</th>
                                <th>Username PPPoE</th>
                                <th>Kontak</th>
                                <th>Status</th>
                                <th>Internet</th>
                                <th>📅 Jatuh Tempo</th>
                                <th>✅ Masa Aktif</th>
                                <th class="text-center">Aksi</th>
                            </tr>
                        </thead>
                        <tbody>
                        <?php foreach ($customers as $c): 
                            $rowClass = '';
                            if ($c['status'] === 'suspended') $rowClass = 'row-suspended';
                            elseif ($c['has_unpaid_bill']) $rowClass = 'row-unpaid';
                        ?>
                            <tr class="<?= $rowClass ?>">
                                <td><input type="checkbox" name="selected_customers[]" value="<?= $c['id'] ?>" class="customer-checkbox checkbox-modern"></td>
                                <td>
                                    <div class="customer-cell">
                                        <div class="customer-avatar <?= $c['status'] ?>">
                                            <?= strtoupper(substr($c['name'], 0, 1)) ?>
                                        </div>
                                        <div>
                                            <div class="customer-name"><?= htmlspecialchars($c['name']) ?></div>
                                            <div class="customer-number">#<?= htmlspecialchars($c['customer_number']) ?></div>
                                        </div>
                                    </div>
                                </td>
                                <td>
                                    <span class="badge-modern package">
                                        <i class="bi bi-box"></i> <?= htmlspecialchars($c['package_name']) ?>
                                    </span>
                                </td>
                                <td>
                                    <code style="font-size: 0.78rem; background: #f8fafc; padding: 2px 6px; border-radius: 4px;">
                                        <?= htmlspecialchars($c['pppoe_username']) ?>
                                    </code>
                                </td>
                                <td>
                                    <a href="https://wa.me/<?= preg_replace('/^0/', '62', $c['phone']) ?>" target="_blank" 
                                       style="color: #25D366; text-decoration: none; font-weight: 600; font-size: 0.85rem;">
                                        <i class="bi bi-whatsapp"></i> <?= htmlspecialchars($c['phone']) ?>
                                    </a>
                                </td>
                                <td>
                                    <?php if ($c['status'] === 'active'): ?>
                                        <span class="badge-modern active"><i class="bi bi-check-circle"></i> Aktif</span>
                                    <?php elseif ($c['status'] === 'suspended'): ?>
                                        <span class="badge-modern suspended"><i class="bi bi-pause-circle"></i> Suspended</span>
                                    <?php else: ?>
                                        <span class="badge-modern inactive"><i class="bi bi-dash-circle"></i> Nonaktif</span>
                                    <?php endif; ?>
                                </td>
                                <td>
                                    <?php if ($c['internet_status'] === 'connected'): ?>
                                        <span class="badge-modern online" title="Uptime: <?= htmlspecialchars($c['uptime']) ?>">
                                            <i class="bi bi-wifi"></i> Online
                                        </span>
                                    <?php else: ?>
                                        <span class="badge-modern offline"><i class="bi bi-wifi-off"></i> Offline</span>
                                    <?php endif; ?>
                                </td>
                                <td>
                                    <?php if ($c['has_unpaid_bill']): 
                                        $bill = $c['unpaid_bill'];
                                        $dueInfo = $c['due_date_info'];
                                        $blockClass = ($dueInfo['days_diff'] <= 0) ? 'danger' : '';
                                    ?>
                                        <div class="bill-info-block <?= $blockClass ?>">
                                            <span class="bill-amount">Rp <?= number_format($bill['amount']) ?></span>
                                            <div class="bill-duedate">
                                                <i class="bi bi-calendar-event"></i>
                                                <strong><?= $dueInfo['full'] ?></strong>
                                            </div>
                                            <span class="bill-countdown <?= $dueInfo['status_class'] ?>">
                                                <?= $dueInfo['status_icon'] ?> <?= $dueInfo['countdown'] ?>
                                            </span>
                                        </div>
                                    <?php else: ?>
                                        <span class="badge-modern paid"><i class="bi bi-check-circle"></i> Lunas</span>
                                    <?php endif; ?>
                                </td>
                                <td>
                                    <?php $activeInfo = $c['active_until_info']; ?>
                                    <div class="active-until-block <?= $activeInfo['class'] ?>">
                                        <span class="active-label">
                                            <i class="bi bi-shield-check"></i> Masa Aktif
                                        </span>
                                        <?php if ($activeInfo['status'] === 'unknown'): ?>
                                            <div class="active-date" style="color: #999;">
                                                <i class="bi bi-question-circle"></i> Belum ada data
                                            </div>
                                        <?php else: ?>
                                            <div class="active-date">
                                                <i class="bi bi-calendar-check"></i>
                                                <strong><?= $activeInfo['short'] ?></strong>
                                            </div>
                                            <span class="active-status <?= $activeInfo['class'] ?>">
                                                <?= $activeInfo['text'] ?>
                                            </span>
                                        <?php endif; ?>
                                    </div>
                                </td>
                                <td>
                                    <div class="action-buttons" style="justify-content: center;">
                                        <?php if ($c['has_unpaid_bill']): ?>
                                            <button type="button" class="btn-action pay" 
                                               onclick="openPayModal(<?= $c['unpaid_bill']['id'] ?>, <?= $c['id'] ?>, '<?= htmlspecialchars($c['name'], ENT_QUOTES) ?>', '<?= htmlspecialchars($c['unpaid_bill']['bill_number'], ENT_QUOTES) ?>', 'Rp <?= number_format($c['unpaid_bill']['amount'], 0, ',', '.') ?>', '<?= date('d/m/Y', strtotime('+1 month', strtotime($c['unpaid_bill']['due_date']))) ?>')" 
                                               title="Bayar Cash Langsung (+1 Bulan)">
                                                <i class="bi bi-cash-coin"></i>
                                            </button>
                                            <a href="/public/pay.php?id=<?= urlencode($c['customer_number']) ?>" target="_blank" class="btn-action link" title="Link Pembayaran"><i class="bi bi-credit-card"></i></a>
                                        <?php else: ?>
                                            <a href="/branch/customers.php?action=generate_bill&id=<?= $c['id'] ?>&token=<?= csrfToken() ?>" class="btn-action generate" onclick="return confirm('Generate tagihan untuk <?= htmlspecialchars($c['name']) ?>?')" title="Generate Tagihan"><i class="bi bi-receipt-cutoff"></i></a>
                                        <?php endif; ?>
                                        <a href="/branch/customer_edit.php?id=<?= $c['id'] ?>" class="btn-action edit" title="Edit"><i class="bi bi-pencil-fill"></i></a>
                                        <a href="https://wa.me/<?= preg_replace('/^0/', '62', $c['phone']) ?>" target="_blank" class="btn-action wa" title="WhatsApp"><i class="bi bi-whatsapp"></i></a>
                                        <?php if ($c['status'] === 'active'): ?>
                                            <a href="/branch/customers.php?action=suspend&id=<?= $c['id'] ?>&token=<?= csrfToken() ?>" class="btn-action suspend" onclick="return confirm('Suspend pelanggan ini?')" title="Suspend"><i class="bi bi-pause-fill"></i></a>
                                        <?php elseif ($c['status'] === 'suspended'): ?>
                                            <a href="/branch/customers.php?action=restore&id=<?= $c['id'] ?>&token=<?= csrfToken() ?>" class="btn-action restore" onclick="return confirm('Restore pelanggan ini?')" title="Restore"><i class="bi bi-play-fill"></i></a>
                                        <?php endif; ?>
                                        <a href="/branch/customers.php?action=delete&id=<?= $c['id'] ?>&token=<?= csrfToken() ?>" class="btn-action delete" onclick="return confirm('Yakin hapus? Tindakan ini tidak bisa dibatalkan!')" title="Hapus"><i class="bi bi-trash-fill"></i></a>
                                    </div>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
            </form>
        <?php endif; ?>
    </div>

    <!-- Modal Pembayaran -->
    <div id="payModal" class="modal-overlay" style="display: none;">
        <div class="modal-content">
            <div class="modal-header">
                <h3><i class="bi bi-cash-coin"></i> Pembayaran Cash Langsung</h3>
                <button class="modal-close" onclick="closePayModal()">&times;</button>
            </div>
            <form method="POST">
                <?= csrfField() ?>
                <input type="hidden" name="bill_id" id="modal_bill_id">
                <input type="hidden" name="customer_id" id="modal_customer_id" value="0">
                <div class="modal-body">
                    <div class="direct-payment-info">
                        <i class="bi bi-lightning-charge-fill"></i>
                        <span>Pembayaran akan <strong>LANGSUNG DIPROSES</strong> tanpa approval pusat</span>
                    </div>
                    <div class="active-info-preview">
                        <i class="bi bi-calendar-plus"></i>
                        <span>Setelah bayar, masa aktif akan diperpanjang sampai: <strong id="modal_new_active_until"></strong></span>
                    </div>
                    <div class="bill-summary">
                        <p>Pelanggan: <strong id="modal_customer_name"></strong></p>
                        <p>No. Tagihan: <strong id="modal_bill_number"></strong></p>
                        <p>Jumlah: <strong id="modal_bill_amount" style="color: #00C853;"></strong></p>
                    </div>
                    <div class="form-group">
                        <label><i class="bi bi-credit-card"></i> Metode Pembayaran</label>
                        <select name="payment_method" class="form-control-filter" required>
                            <option value="Tunai">💵 Tunai / Cash</option>
                            <option value="Transfer Bank">🏦 Transfer Bank</option>
                            <option value="QRIS">📱 QRIS</option>
                            <option value="Edc">💳 EDC</option>
                            <option value="Lainnya">📋 Lainnya</option>
                        </select>
                    </div>
                    <div class="form-group">
                        <label><i class="bi bi-tag"></i> Kategori</label>
                        <select name="category" class="form-control-filter" required>
                            <option value="Pelunasan Tagihan">Pelunasan Tagihan</option>
                            <option value="Pemasukan Lainnya">Pemasukan Lainnya</option>
                            <option value="Denda">Denda</option>
                            <option value="Biaya Instalasi">Biaya Instalasi</option>
                        </select>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn-filter outline" onclick="closePayModal()">Batal</button>
                    <button type="submit" name="submit_pay" class="btn-filter primary">
                        <i class="bi bi-check-circle-fill"></i> Proses Pembayaran
                    </button>
                </div>
            </form>
        </div>
    </div>

    <!-- ⭐ Modal Import CSV (DIPERBAIKI: Hapus duplicate input, update instruksi) -->
    <div id="importModal" class="modal-overlay" style="display: none;">
        <div class="modal-content">
            <div class="modal-header import">
                <h3><i class="bi bi-upload"></i> Import Data Pelanggan</h3>
                <button class="modal-close" onclick="closeImportModal()">&times;</button>
            </div>
            <form method="POST" enctype="multipart/form-data">
                <?= csrfField() ?>
                <div class="modal-body">
                    <div class="import-info">
                        <div class="import-info-title">
                            <i class="bi bi-info-circle-fill"></i>
                            <span>Petunjuk Import</span>
                        </div>
                        <ul>
                            <li>File harus berformat <strong>CSV</strong> (pemisah koma, pipe, tab, atau titik koma - <strong>auto-detect</strong>)</li>
                            <li>Kolom wajib: <strong>nama, no_hp, pppoe_username, pppoe_password, paket</strong></li>
                            <li>Username PPPoE harus <strong>unik</strong> (tidak boleh sama)</li>
                            <li>Nama paket harus <strong>sama persis</strong> dengan di database</li>
                            <li>Setiap pelanggan akan otomatis <strong>sync ke MikroTik</strong> dan <strong>generate tagihan pertama</strong></li>
                            <li>Maksimal ukuran file: <strong>5MB</strong></li>
                            <li>Contoh format: <code style="background:#fff;padding:2px 6px;border-radius:4px;">nama,no_hp,email,alamat,pppoe_username,pppoe_password,pppoe_profile,paket,ip_address,tanggal_instalasi</code></li>
                        </ul>
                    </div>
                    
                    <div class="template-download-box">
                        <div class="template-download-text">
                            <i class="bi bi-file-earmark-spreadsheet"></i>
                            <span>Download template CSV untuk format yang benar</span>
                        </div>
                        <a href="/branch/customers.php?action=download_template" class="btn-template">
                            <i class="bi bi-download"></i>
                            <span>Download Template</span>
                        </a>
                    </div>
                    
                    <label class="form-label-modern" style="margin-bottom: 8px;">
                        <i class="bi bi-file-earmark-arrow-up"></i>
                        Pilih File CSV <span class="required" style="color: #DC3545;">*</span>
                    </label>
                    <div class="file-upload-area" id="fileUploadArea" onclick="document.getElementById('csv_file').click()">
                        <div class="file-upload-icon">
                            <i class="bi bi-cloud-arrow-up"></i>
                        </div>
                        <div class="file-upload-text">
                            <strong>Klik untuk pilih file</strong> atau drag & drop
                        </div>
                        <!-- ⭐ HANYA 1 INPUT FILE (duplicate dihapus) -->
                        <input type="file" name="csv_file" id="csv_file" accept=".csv,.txt,.tsv" style="display: none;" onchange="handleFileSelect(this)" required>

                        <div class="file-upload-hint">
                            Format: CSV/TSV/TXT • Auto-detect delimiter • Maks. 5MB
                        </div>
                        <div class="file-name-display" id="fileNameDisplay">
                            <i class="bi bi-check-circle-fill"></i>
                            <span id="fileName"></span>
                        </div>
                    </div>
                    
                    <div class="alert-modern warning" style="margin-top: 12px; margin-bottom: 0;">
                        <i class="bi bi-exclamation-triangle-fill"></i>
                        <div style="font-size: 0.82rem;">
                            <strong>Perhatian:</strong> Proses import tidak dapat dibatalkan. Pastikan data sudah benar sebelum mengupload.
                        </div>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn-filter outline" onclick="closeImportModal()">Batal</button>
                    <button type="submit" name="submit_import" class="btn-filter primary" style="background: linear-gradient(135deg, #FF9900 0%, #FFB84D 100%);">
                        <i class="bi bi-upload"></i>
                        <span>Mulai Import</span>
                    </button>
                </div>
            </form>
        </div>
    </div>
</div>
</div>
<script>
function toggleSidebar() {
    const sidebar = document.getElementById('sidebar');
    const overlay = document.getElementById('sidebarOverlay');
    if (sidebar && overlay) {
        sidebar.classList.toggle('active');
        overlay.classList.toggle('active');
        document.body.style.overflow = sidebar.classList.contains('active') ? 'hidden' : '';
    }
}

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

function confirmBulkAction(select) {
    if (select.value === '') return;
    const selected = document.querySelectorAll('.customer-checkbox:checked');
    if (selected.length === 0) { alert('Pilih minimal 1 pelanggan'); select.value = ''; return; }
    const actionText = { 'generate_bill': 'GENERATE TAGIHAN', 'suspend': 'SUSPEND', 'restore': 'RESTORE' };
    if (confirm(`${actionText[select.value]} untuk ${selected.length} pelanggan yang dipilih?`)) {
        const mainForm = document.getElementById('bulkFormMain');
        mainForm.querySelectorAll('input[name="selected_customers[]"]').forEach(el => el.remove());
        selected.forEach(cb => { const clone = cb.cloneNode(true); clone.style.display = 'none'; mainForm.appendChild(clone); });
        const input = document.createElement('input'); input.type = 'hidden'; input.name = 'bulk_action'; input.value = select.value; mainForm.appendChild(input);
        mainForm.submit();
    } else { select.value = ''; }
}

function openPayModal(billId, customerId, customerName, billNumber, billAmount, newActiveUntil) {
    document.getElementById('modal_bill_id').value = billId;
    document.getElementById('modal_customer_id').value = customerId || 0;
    document.getElementById('modal_customer_name').innerText = customerName;
    document.getElementById('modal_bill_number').innerText = billNumber;
    document.getElementById('modal_bill_amount').innerText = billAmount;
    document.getElementById('modal_new_active_until').innerText = newActiveUntil || '(+1 bulan dari jatuh tempo)';
    document.getElementById('payModal').style.display = 'flex';
}

function closePayModal() {
    document.getElementById('payModal').style.display = 'none';
}

function openImportModal() {
    document.getElementById('importModal').style.display = 'flex';
}

function closeImportModal() {
    document.getElementById('importModal').style.display = 'none';
    document.getElementById('csv_file').value = '';
    document.getElementById('fileNameDisplay').style.display = 'none';
    document.getElementById('fileUploadArea').classList.remove('has-file');
}

function handleFileSelect(input) {
    const file = input.files[0];
    const area = document.getElementById('fileUploadArea');
    const display = document.getElementById('fileNameDisplay');
    const nameEl = document.getElementById('fileName');
    
    if (file) {
        if (file.size > 5 * 1024 * 1024) {
            alert('❌ Ukuran file maksimal 5MB');
            input.value = '';
            return;
        }
        
        // ⭐ DIPERBAIKI: Support .tsv juga
        const ext = file.name.split('.').pop().toLowerCase();
        if (!['csv', 'txt', 'tsv'].includes(ext)) {
            alert('❌ Format file harus CSV, TXT, atau TSV');
            input.value = '';
            return;
        }
        
        nameEl.innerText = file.name + ' (' + formatFileSize(file.size) + ')';
        display.style.display = 'flex';
        area.classList.add('has-file');
    } else {
        display.style.display = 'none';
        area.classList.remove('has-file');
    }
}

function formatFileSize(bytes) {
    if (bytes < 1024) return bytes + ' B';
    if (bytes < 1024 * 1024) return (bytes / 1024).toFixed(1) + ' KB';
    return (bytes / (1024 * 1024)).toFixed(1) + ' MB';
}

const uploadArea = document.getElementById('fileUploadArea');
if (uploadArea) {
    ['dragenter', 'dragover'].forEach(eventName => {
        uploadArea.addEventListener(eventName, (e) => {
            e.preventDefault();
            e.stopPropagation();
            uploadArea.style.background = '#e3f2fd';
            uploadArea.style.borderColor = '#00B4FF';
        });
    });
    
    ['dragleave', 'drop'].forEach(eventName => {
        uploadArea.addEventListener(eventName, (e) => {
            e.preventDefault();
            e.stopPropagation();
            uploadArea.style.background = '';
            uploadArea.style.borderColor = '';
        });
    });
    
    uploadArea.addEventListener('drop', (e) => {
        const files = e.dataTransfer.files;
        if (files.length > 0) {
            document.getElementById('csv_file').files = files;
            handleFileSelect(document.getElementById('csv_file'));
        }
    });
}

window.onclick = function(event) {
    const payModal = document.getElementById('payModal');
    const importModal = document.getElementById('importModal');
    if (event.target === payModal) closePayModal();
    if (event.target === importModal) closeImportModal();
}
</script>

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