<?php
require_once __DIR__ . '/../includes/db.php';
require_once __DIR__ . '/../classes/Bill.php';
require_once __DIR__ . '/../classes/Customer.php';
require_once __DIR__ . '/../classes/iPaymu.php';
require_once __DIR__ . '/../classes/Violet.php';

error_reporting(E_ALL);
ini_set('display_errors', 0);
ini_set('log_errors', 1);
ini_set('error_log', __DIR__ . '/pay_error.log');

$customerNumber = $_GET['id'] ?? '';

if (empty($customerNumber)) {
    die('<!DOCTYPE html><html><head><title>Error</title></head><body style="font-family:Arial;padding:40px;text-align:center;"><h1>❌ Link tidak valid</h1></body></html>');
}

$customer = Customer::findByNumber($customerNumber);

if (!$customer) {
    die('<!DOCTYPE html><html><head><title>Error</title></head><body style="font-family:Arial;padding:40px;text-align:center;"><h1>❌ Pelanggan tidak ditemukan</h1></body></html>');
}

$bill = Bill::getLatestUnpaid($customer['id']);

// ⭐ AMBIL DATA PAKET & MASA AKTIF
$packageInfo = null;
$activeUntilInfo = null;
try {
    $db = db();
    if (!empty($customer['package_id'])) {
        $stmt = $db->prepare("SELECT name, speed, price FROM packages WHERE id = ?");
        $stmt->execute([$customer['package_id']]);
        $packageInfo = $stmt->fetch();
    }
    
    if (!empty($customer['active_until'])) {
        $activeUntilTs = strtotime($customer['active_until']);
        $now = time();
        $daysLeft = floor(($activeUntilTs - $now) / 86400);
        $totalPeriod = 30;
        $daysUsed = max(0, $totalPeriod - $daysLeft);
        $progressPercent = min(100, max(0, ($daysUsed / $totalPeriod) * 100));
        
        $activeUntilInfo = [
            'date' => $customer['active_until'],
            'date_formatted' => date('d F Y', $activeUntilTs),
            'days_left' => $daysLeft,
            'progress' => round($progressPercent),
            'status' => $daysLeft > 7 ? 'safe' : ($daysLeft > 0 ? 'warning' : 'expired'),
            'status_text' => $daysLeft > 7 ? 'Aktif' : ($daysLeft > 0 ? 'Segera Habis' : ($daysLeft == 0 ? 'Habis Hari Ini' : 'Expired'))
        ];
    }
} catch (\Throwable $e) {}

if (!$bill) {
    $isPaid = true;
} else {
    $isPaid = ($bill['status'] === 'paid');
}

// ====================================================================
// AMBIL GATEWAY AKTIF
// ====================================================================
$db = db();
$stmt = $db->prepare("SELECT setting_value FROM payment_config WHERE setting_key = 'active_gateway' LIMIT 1");
$stmt->execute();
$activeGateway = $stmt->fetchColumn() ?: 'ipaymu';

// ====================================================================
// ⭐ DAFTAR CHANNEL YANG DITAMPILKAN (WHITELIST)
// ====================================================================
$allowedChannels = [
    // Virtual Account - fee flat dari API Violet
    'BCAVA'     => [
        'category' => 'va', 
        'label' => 'BCA Virtual Account', 
        'icon' => 'BCA', 
        'color' => '#0066cc', 
        'popular' => true,
        'fee_flat' => 4500  // ⭐ Fee flat Rp 4.500
    ],
    'BNIVA'     => [
        'category' => 'va', 
        'label' => 'BNI Virtual Account', 
        'icon' => 'BNI', 
        'color' => '#f37021', 
        'popular' => true,
        'fee_flat' => 3500  // ⭐ Fee flat Rp 3.500
    ],
    'BRIVA'     => [
        'category' => 'va', 
        'label' => 'BRI Virtual Account', 
        'icon' => 'BRI', 
        'color' => '#e31837', 
        'popular' => true,
        'fee_flat' => 3000  // ⭐ Fee flat Rp 3.000
    ],
    'BSI'       => [
        'category' => 'va', 
        'label' => 'BSI Virtual Account', 
        'icon' => 'BSI', 
        'color' => '#00a651', 
        'popular' => false,
        'fee_flat' => 3500  // ⭐ Fee flat Rp 3.500
    ],

    'QRIS1'     => [
        'category' => 'va', 
        'label' => 'QRIS', 
        'icon' => 'QRIS', 
        'color' => '#2e7d32', 
        'popular' => true, 
        'fee_type' => 'percent_plus_fixed', 
        'fee_percent' => 0.7, 
        'fee_fixed' => 1000
    ],
    // QRIS - fee persentase + fixed
    'QRISC'     => [
        'category' => 'qris', 
        'label' => 'QRIS', 
        'icon' => 'QRIS', 
        'color' => '#2e7d32', 
        'popular' => false, 
        'fee_type' => 'percent_plus_fixed', 
        'fee_percent' => 0.7, 
        'fee_fixed' => 1000
    ],
    
    // Retail - fee flat
    'ALFAMART'  => [
        'category' => 'retail', 
        'label' => 'Alfamart', 
        'icon' => 'ALFA', 
        'color' => '#e31837', 
        'popular' => false,
        'fee_flat' => 3500  // ⭐ Fee flat Rp 3.500
    ],
];

// ====================================================================
// ⭐ FETCH CHANNEL DARI API VIOLET & FILTER
// ====================================================================
$paymentChannels = [];
$violetApiError = '';

function fetchVioletChannels($db) {
    global $violetApiError, $allowedChannels;
    
    // Cache 1 jam
    $cacheFile = __DIR__ . '/channel_cache.json';
    if (file_exists($cacheFile) && (time() - filemtime($cacheFile)) < 3600) {
        $cached = json_decode(file_get_contents($cacheFile), true);
        if (is_array($cached) && !empty($cached)) {
            // Filter hanya channel yang di-whitelist
            return array_filter($cached, fn($c) => isset($allowedChannels[strtoupper($c['nama'] ?? '')]));
        }
    }
    
    // Ambil credential
    try {
        $stmt = $db->prepare("SELECT setting_key, setting_value FROM payment_config WHERE setting_key IN ('violet_api_key', 'violet_secret_key', 'violet_mode')");
        $stmt->execute();
        $config = [];
        while ($row = $stmt->fetch()) {
            $config[$row['setting_key']] = $row['setting_value'];
        }
        $apiKey = $config['violet_api_key'] ?? null;
        $secretKey = $config['violet_secret_key'] ?? null;
        $mode = $config['violet_mode'] ?? 'live';
    } catch (\Throwable $e) {
        $violetApiError = 'Gagal konfigurasi: ' . $e->getMessage();
        return [];
    }
    
    if (!$apiKey || !$secretKey) {
        $violetApiError = 'API Key Violet belum dikonfigurasi';
        return [];
    }
    
    $url = ($mode === 'sandbox') 
        ? 'https://violetmediapay.com/api/sanbox/channel-payment'
        : 'https://violetmediapay.com/api/live/channel-payment';
    
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, [
        'api_key' => $apiKey,
        'secret_key' => $secretKey,
        'channel_payment' => 'list'
    ]);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_TIMEOUT, 10);
    
    $response = curl_exec($ch);
    $error = curl_error($ch);
    curl_close($ch);
    
    if ($error) {
        $violetApiError = 'Connection error: ' . $error;
        return [];
    }
    
    $data = json_decode($response, true);
    
    if (!$data || !isset($data['status']) || !$data['status']) {
        $violetApiError = 'API response invalid';
        return [];
    }
    
    $channels = $data['data'] ?? [];
    $channels = array_filter($channels, fn($c) => isset($c['status']) && $c['status'] === 'Aktif');
    
    // Filter hanya channel yang di-whitelist
    $channels = array_filter($channels, fn($c) => isset($allowedChannels[strtoupper($c['nama'] ?? '')]));
    
    // Save cache
    file_put_contents($cacheFile, json_encode(array_values($channels)));
    
    return array_values($channels);
}

if ($activeGateway === 'violet' && !$isPaid) {
    $paymentChannels = fetchVioletChannels($db);
    
    // Filter berdasarkan min/max amount
    if ($bill && !empty($paymentChannels)) {
        $billAmount = (float)$bill['amount'];
        $paymentChannels = array_values(array_filter($paymentChannels, function($c) use ($billAmount) {
            $min = (float)($c['min_amount'] ?? 0);
            $max = (float)($c['max_amount'] ?? PHP_FLOAT_MAX);
            return $billAmount >= $min && $billAmount <= $max;
        }));
    }
}

function calculateChannelFee($channelCode, $amount) {
    global $allowedChannels;
    
    $info = $allowedChannels[$channelCode] ?? null;
    if (!$info) return ['fee' => 0, 'text' => 'Rp 0', 'breakdown' => '', 'is_percent' => false];
    
    // ⭐ TIPE 1: QRIS (persentase + fixed)
    if (isset($info['fee_type']) && $info['fee_type'] === 'percent_plus_fixed') {
        $percent = $info['fee_percent'];
        $fixed = $info['fee_fixed'];
        $feeFromPercent = $amount * $percent / 100;
        $totalFee = $feeFromPercent + $fixed;
        
        return [
            'fee' => $totalFee,
            'text' => 'Rp ' . number_format($totalFee, 0, ',', '.'),
            'breakdown' => number_format($percent, 2) . '% (Rp ' . number_format($feeFromPercent, 0, ',', '.') . ') + Rp ' . number_format($fixed, 0, ',', '.'),
            'is_percent' => true,
            'percent' => $percent
        ];
    }
    
    // ⭐ TIPE 2: VA & Retail (fee flat dari whitelist)
    if (isset($info['fee_flat'])) {
        $fee = (float)$info['fee_flat'];
        return [
            'fee' => $fee,
            'text' => 'Rp ' . number_format($fee, 0, ',', '.'),
            'breakdown' => 'Flat',
            'is_percent' => false,
            'percent' => 0
        ];
    }
    
    // Fallback: tidak ada fee
    return [
        'fee' => 0,
        'text' => 'GRATIS',
        'breakdown' => 'Tidak ada biaya',
        'is_percent' => false,
        'percent' => 0
    ];
}

// Group channels by kategori
$groupedChannels = [
    'va'     => ['label' => 'Virtual Account', 'icon' => 'bi-bank', 'channels' => []],
    'qris'   => ['label' => 'QRIS', 'icon' => 'bi-qr-code-scan', 'channels' => []],
    'retail' => ['label' => 'Gerai Retail', 'icon' => 'bi-shop', 'channels' => []],
];

foreach ($paymentChannels as $ch) {
    $kode = strtoupper($ch['nama'] ?? '');
    if (isset($allowedChannels[$kode])) {
        $cat = $allowedChannels[$kode]['category'];
        $groupedChannels[$cat]['channels'][] = $ch;
    }
}

$paymentError = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && !$isPaid) {
    $token = $_POST['token'] ?? '';
    $expectedToken = md5($bill['id'] . $bill['bill_number'] . 'gateway_secret_2026');
    $selectedChannel = $_POST['selected_channel'] ?? 'QRIS1';
    
    if ($token !== $expectedToken) {
        $paymentError = 'Token tidak valid. Silakan refresh halaman.';
    } elseif (empty($selectedChannel)) {
        $paymentError = 'Silakan pilih metode pembayaran terlebih dahulu.';
    } else {
        if ($_POST['action'] === 'pay_now') {
            try {
                $baseUrl = 'https://' . $_SERVER['HTTP_HOST'];
                $result = null;
                
                if ($activeGateway === 'violet') {
                    $violet = new Violet();
                    
                    if (!$violet->isConfigured()) {
                        $paymentError = 'Payment gateway Violet belum dikonfigurasi.';
                    } else {
                        $result = $violet->createPayment([
                            'referenceId'   => $bill['bill_number'],
                            'amount'        => (int) $bill['amount'],
                            'channel'       => $selectedChannel,
                            'customerName'  => $customer['name'],
                            'customerEmail' => $customer['email'] ?? $customerNumber . '@customer.lintasfiber.my.id',
                            'customerPhone' => $customer['phone'] ?? '081234567890',
                            'productName'   => 'Tagihan Internet - ' . ($packageInfo['name'] ?? 'Internet'),
                            'returnUrl'     => $baseUrl . '/public/pay.php?id=' . urlencode($customerNumber) . '&success=1',
                            'notifyUrl'     => $baseUrl . '/public/violet_callback.php'
                        ]);
                        
                        if ($result['success']) {
                            $stmt = $db->prepare("UPDATE bills SET payment_session_id = ?, payment_url = ?, payment_gateway = 'violet', payment_channel = ?, updated_at = NOW() WHERE id = ?");
                            $stmt->execute([$result['session_id'] ?? '', $result['payment_url'] ?? '', $selectedChannel, $bill['id']]);
                            
                            if (!empty($result['payment_url'])) {
                                header('Location: ' . $result['payment_url']);
                                exit;
                            } else {
                                $paymentError = 'URL pembayaran kosong.';
                            }
                        } else {
                            $paymentError = $result['error'] ?? 'Gagal membuat sesi pembayaran';
                        }
                    }
                } else {
                    $ipaymu = new iPaymu();
                    if (!$ipaymu->isConfigured()) {
                        $paymentError = 'Payment gateway iPaymu belum dikonfigurasi.';
                    } else {
                        $result = $ipaymu->createPayment([
                            'referenceId' => $bill['bill_number'],
                            'products' => [['name' => 'Tagihan Internet', 'qty' => 1, 'price' => (float) $bill['amount']]],
                            'returnUrl' => $baseUrl . '/public/pay.php?id=' . urlencode($customerNumber) . '&success=1',
                            'cancelUrl' => $baseUrl . '/public/pay.php?id=' . urlencode($customerNumber),
                            'notifyUrl' => $baseUrl . '/public/payment_callback.php',
                            'customerName' => $customer['name'],
                            'customerEmail' => $customer['email'] ?? $customerNumber . '@customer.lintasfiber.my.id',
                            'customerPhone' => $customer['phone'] ?? '081234567890'
                        ]);
                        
                        if ($result['success']) {
                            $stmt = $db->prepare("UPDATE bills SET payment_session_id = ?, payment_url = ?, payment_gateway = 'ipaymu', updated_at = NOW() WHERE id = ?");
                            $stmt->execute([$result['session_id'] ?? '', $result['payment_url'] ?? '', $bill['id']]);
                            
                            if (!empty($result['payment_url'])) {
                                header('Location: ' . $result['payment_url']);
                                exit;
                            } else {
                                $paymentError = 'URL pembayaran kosong.';
                            }
                        } else {
                            $paymentError = $result['error'] ?? 'Gagal membuat sesi pembayaran';
                        }
                    }
                }
            } catch (\Throwable $e) {
                $paymentError = 'Error: ' . $e->getMessage();
            }
        }
    }
}

$showSuccess = isset($_GET['success']) && $_GET['success'] == '1';

if (!$isPaid) {
    $bill = Bill::find($bill['id']);
    $isPaid = ($bill['status'] === 'paid');
}

if (!$isPaid && $bill) {
    $dueDate = strtotime($bill['due_date']);
    $today = strtotime('today');
    $daysDiff = floor(($dueDate - $today) / 86400);

    if ($daysDiff > 0) {
        $dueInfo = "Jatuh tempo dalam $daysDiff hari";
        $dueIcon = 'bi-clock-history';
    } elseif ($daysDiff == 0) {
        $dueInfo = 'Jatuh tempo HARI INI';
        $dueIcon = 'bi-exclamation-triangle-fill';
    } else {
        $dueInfo = "Terlambat " . abs($daysDiff) . " hari";
        $dueIcon = 'bi-exclamation-octagon-fill';
    }
    
    $formToken = md5($bill['id'] . $bill['bill_number'] . 'gateway_secret_2026');
}

$gatewayLabel = $activeGateway === 'violet' ? 'Violet MediaPay' : 'iPaymu';
$gatewayIcon  = $activeGateway === 'violet' ? 'bi-gem' : 'bi-wallet2';
?>
<!DOCTYPE html>
<html lang="id">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Pembayaran Tagihan - <?= htmlspecialchars($customer['name']) ?></title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.0/font/bootstrap-icons.css">
    <link href="https://fonts.googleapis.com/css2?family=Plus+Jakarta+Sans:wght@400;500;600;700;800&display=swap" rel="stylesheet">
    <style>
        :root {
            --primary-gradient: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            --success-gradient: linear-gradient(135deg, #11998e 0%, #38ef7d 100%);
            --warning-gradient: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
        }
        
        * { font-family: 'Plus Jakarta Sans', sans-serif; }
        
        body {
            background: var(--primary-gradient);
            min-height: 100vh;
            padding: 20px;
            position: relative;
        }
        
        body::before, body::after {
            content: '';
            position: fixed;
            border-radius: 50%;
            filter: blur(80px);
            opacity: 0.4;
            z-index: 0;
            animation: float 8s ease-in-out infinite;
        }
        body::before { width: 400px; height: 400px; background: #f093fb; top: -100px; left: -100px; }
        body::after { width: 500px; height: 500px; background: #38ef7d; bottom: -150px; right: -150px; animation-delay: 4s; }
        
        @keyframes float {
            0%, 100% { transform: translate(0, 0) scale(1); }
            50% { transform: translate(30px, -30px) scale(1.1); }
        }
        
        .payment-card {
            background: rgba(255, 255, 255, 0.98);
            backdrop-filter: blur(20px);
            border-radius: 28px;
            box-shadow: 0 30px 80px rgba(0,0,0,0.25);
            max-width: 680px;
            margin: 0 auto;
            width: 100%;
            overflow: hidden;
            position: relative;
            z-index: 1;
            animation: slideUp 0.6s cubic-bezier(0.16, 1, 0.3, 1);
        }
        
        @keyframes slideUp {
            from { opacity: 0; transform: translateY(30px); }
            to { opacity: 1; transform: translateY(0); }
        }
        
        .card-header-custom {
            background: var(--primary-gradient);
            color: white;
            padding: 30px;
            text-align: center;
            position: relative;
            overflow: hidden;
        }
        
        .card-header-custom .logo-icon {
            width: 70px; height: 70px;
            background: rgba(255,255,255,0.2);
            border-radius: 20px;
            display: flex; align-items: center; justify-content: center;
            margin: 0 auto 15px;
            font-size: 36px;
            backdrop-filter: blur(10px);
            border: 2px solid rgba(255,255,255,0.3);
        }
        
        .card-header-custom h2 { margin: 0; font-size: 22px; font-weight: 700; }
        .card-header-custom .subtitle { opacity: 0.9; font-size: 14px; margin-top: 5px; }
        .card-body-custom { padding: 25px; }
        
        .bill-info {
            background: linear-gradient(135deg, #f8f9ff 0%, #eef2ff 100%);
            border-radius: 16px;
            padding: 18px;
            margin-bottom: 18px;
            border: 1px solid rgba(102, 126, 234, 0.1);
        }
        
        .bill-info-row {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 8px 0;
            border-bottom: 1px dashed rgba(0,0,0,0.08);
        }
        .bill-info-row:last-child { border-bottom: none; }
        .bill-info-label { color: #6c757d; font-size: 13px; font-weight: 500; display: flex; align-items: center; gap: 6px; }
        .bill-info-label i { color: #667eea; }
        .bill-info-value { font-weight: 600; color: #212529; font-size: 14px; }
        
        .amount-display {
            background: var(--warning-gradient);
            color: white;
            padding: 24px;
            border-radius: 18px;
            text-align: center;
            margin: 18px 0;
            box-shadow: 0 10px 30px rgba(245, 87, 108, 0.3);
        }
        .amount-display .label { font-size: 12px; opacity: 0.95; margin-bottom: 6px; text-transform: uppercase; letter-spacing: 1px; font-weight: 600; }
        .amount-display .amount { font-size: 38px; font-weight: 800; letter-spacing: -1px; }
        .amount-display .due-info { margin-top: 10px; display: inline-flex; align-items: center; gap: 6px; background: rgba(255,255,255,0.2); padding: 5px 12px; border-radius: 20px; font-size: 12px; font-weight: 600; }
        
        /* Channel Selection */
        .channel-section { margin: 20px 0; }
        
        .channel-section-title {
            font-size: 15px;
            font-weight: 700;
            color: #212529;
            margin-bottom: 14px;
            display: flex;
            align-items: center;
            gap: 8px;
        }
        
        .channel-section-title i { color: #667eea; font-size: 18px; }
        
        .channel-tabs {
            display: flex;
            gap: 6px;
            margin-bottom: 16px;
            overflow-x: auto;
            padding-bottom: 4px;
        }
        
        .channel-tab {
            padding: 8px 14px;
            border: 2px solid #e8f4f8;
            border-radius: 20px;
            background: white;
            color: #6c757d;
            font-size: 12px;
            font-weight: 600;
            cursor: pointer;
            white-space: nowrap;
            transition: all 0.2s;
            display: inline-flex;
            align-items: center;
            gap: 5px;
        }
        
        .channel-tab:hover { border-color: #667eea; color: #667eea; }
        
        .channel-tab.active {
            background: var(--primary-gradient);
            color: white;
            border-color: transparent;
        }
        
        .channel-group { display: none; }
        .channel-group.active { display: block; }
        
        .channel-grid {
            display: grid;
            grid-template-columns: repeat(2, 1fr);
            gap: 10px;
            margin-bottom: 12px;
        }
        
        @media (min-width: 576px) {
            .channel-grid { grid-template-columns: repeat(3, 1fr); }
        }
        
        .channel-card {
            background: white;
            border: 2px solid #e8f4f8;
            border-radius: 14px;
            padding: 12px;
            cursor: pointer;
            transition: all 0.2s;
            position: relative;
            display: flex;
            flex-direction: column;
            gap: 8px;
        }
        
        .channel-card:hover {
            border-color: #667eea;
            transform: translateY(-2px);
            box-shadow: 0 6px 20px rgba(102, 126, 234, 0.15);
        }
        
        .channel-card.selected {
            border-color: #11998e;
            background: linear-gradient(135deg, #ecfdf5 0%, #d1fae5 100%);
            box-shadow: 0 6px 20px rgba(17, 153, 142, 0.2);
        }
        
        .channel-card.selected::after {
            content: '✓';
            position: absolute;
            top: 8px;
            right: 8px;
            width: 22px;
            height: 22px;
            background: var(--success-gradient);
            color: white;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 12px;
            font-weight: 700;
        }
        
        .channel-header {
            display: flex;
            align-items: center;
            gap: 8px;
        }
        
        .channel-icon {
            width: 36px;
            height: 36px;
            border-radius: 10px;
            display: flex;
            align-items: center;
            justify-content: center;
            color: white;
            font-weight: 800;
            font-size: 10px;
            flex-shrink: 0;
            letter-spacing: -0.5px;
        }
        
        .channel-name {
            font-size: 12px;
            font-weight: 700;
            color: #212529;
            line-height: 1.2;
            flex: 1;
        }
        
        .channel-badge-popular {
            position: absolute;
            top: -6px;
            left: 10px;
            background: linear-gradient(135deg, #f59e0b 0%, #f97316 100%);
            color: white;
            font-size: 9px;
            font-weight: 700;
            padding: 2px 8px;
            border-radius: 10px;
            text-transform: uppercase;
            letter-spacing: 0.5px;
            box-shadow: 0 2px 6px rgba(245, 158, 11, 0.3);
        }
        
        .channel-fee {
            display: flex;
            justify-content: space-between;
            align-items: center;
            font-size: 11px;
            padding-top: 6px;
            border-top: 1px dashed #e8f4f8;
        }
        
        .channel-fee-label { color: #6c757d; }
        .channel-fee-value { color: #11998e; font-weight: 700; }
        
        /* Total Calculation */
        .total-calculation {
            background: linear-gradient(135deg, #f8f9ff 0%, #eef2ff 100%);
            border: 2px solid #667eea;
            border-radius: 16px;
            padding: 16px;
            margin: 16px 0;
            display: none;
        }
        
        .total-calculation.show { display: block; animation: slideDown 0.3s ease; }
        
        @keyframes slideDown {
            from { opacity: 0; transform: translateY(-10px); }
            to { opacity: 1; transform: translateY(0); }
        }
        
        .total-row {
            display: flex;
            justify-content: space-between;
            padding: 6px 0;
            font-size: 13px;
            color: #495057;
        }
        
        .total-row .fee-breakdown {
            font-size: 11px;
            color: #6c757d;
            font-style: italic;
        }
        
        .total-row.final {
            border-top: 2px dashed #667eea;
            margin-top: 8px;
            padding-top: 12px;
            font-size: 16px;
            font-weight: 800;
            color: #212529;
        }
        
        .total-row.final .value { color: #11998e; }
        
        .btn-pay {
            background: var(--success-gradient);
            border: none;
            color: white;
            padding: 16px 40px;
            font-size: 16px;
            font-weight: 700;
            border-radius: 50px;
            width: 100%;
            transition: all 0.3s;
            box-shadow: 0 10px 30px rgba(17, 153, 142, 0.3);
            display: flex;
            align-items: center;
            justify-content: center;
            gap: 10px;
        }
        
        .btn-pay:hover:not(:disabled) { transform: translateY(-3px); box-shadow: 0 15px 40px rgba(17, 153, 142, 0.4); color: white; }
        .btn-pay:disabled { opacity: 0.6; cursor: not-allowed; }
        
        .gateway-badge {
            display: inline-flex;
            align-items: center;
            gap: 6px;
            background: rgba(255,255,255,0.2);
            color: white;
            padding: 6px 16px;
            border-radius: 20px;
            font-size: 12px;
            font-weight: 600;
            margin-top: 12px;
            border: 1px solid rgba(255,255,255,0.3);
        }
        
        .error-box {
            background: linear-gradient(135deg, #fff5f5 0%, #ffe5e5 100%);
            border: 1px solid #ffcccc;
            border-left: 4px solid #dc3545;
            border-radius: 12px;
            padding: 14px;
            margin-bottom: 16px;
            display: flex;
            align-items: flex-start;
            gap: 10px;
        }
        .error-box i { color: #dc3545; font-size: 18px; margin-top: 2px; }
        
        .paid-state { text-align: center; padding: 10px 0; }
        .paid-icon-wrapper { position: relative; width: 120px; height: 120px; margin: 0 auto 20px; }
        .paid-icon {
            width: 120px; height: 120px;
            background: var(--success-gradient);
            border-radius: 50%;
            display: flex; align-items: center; justify-content: center;
            font-size: 60px; color: white;
            box-shadow: 0 15px 40px rgba(17, 153, 142, 0.4);
            position: relative; z-index: 2;
            animation: scaleIn 0.6s cubic-bezier(0.34, 1.56, 0.64, 1);
        }
        .paid-icon::before, .paid-icon::after {
            content: ''; position: absolute;
            top: -10px; left: -10px; right: -10px; bottom: -10px;
            border-radius: 50%;
            background: var(--success-gradient);
            opacity: 0.3;
            animation: ripple 2s ease-out infinite;
            z-index: 1;
        }
        .paid-icon::after { animation-delay: 1s; }
        
        @keyframes scaleIn { from { transform: scale(0); opacity: 0; } to { transform: scale(1); opacity: 1; } }
        @keyframes ripple { 0% { transform: scale(1); opacity: 0.4; } 100% { transform: scale(1.8); opacity: 0; } }
        
        .paid-title { font-size: 26px; font-weight: 800; color: #11998e; margin-bottom: 8px; }
        .paid-subtitle { color: #6c757d; font-size: 14px; margin-bottom: 25px; }
        
        .package-info-card {
            background: linear-gradient(135deg, #f8f9ff 0%, #eef2ff 100%);
            border-radius: 18px;
            padding: 20px;
            margin-bottom: 18px;
            border: 1px solid rgba(102, 126, 234, 0.15);
            text-align: left;
        }
        
        .package-info-header { display: flex; align-items: center; gap: 14px; margin-bottom: 16px; padding-bottom: 14px; border-bottom: 1px dashed rgba(0,0,0,0.08); }
        .package-icon { width: 50px; height: 50px; background: var(--primary-gradient); border-radius: 14px; display: flex; align-items: center; justify-content: center; color: white; font-size: 24px; flex-shrink: 0; }
        .package-title { font-size: 11px; color: #6c757d; text-transform: uppercase; letter-spacing: 1px; font-weight: 600; margin-bottom: 2px; }
        .package-name { font-size: 17px; font-weight: 700; color: #212529; margin: 0; }
        .package-speed { font-size: 12px; color: #667eea; font-weight: 600; margin-top: 2px; }
        
        .active-until-section { background: white; border-radius: 14px; padding: 16px; margin-bottom: 14px; border: 1px solid rgba(0,0,0,0.05); }
        .active-until-header { display: flex; justify-content: space-between; align-items: center; margin-bottom: 10px; }
        .active-until-label { font-size: 11px; color: #6c757d; text-transform: uppercase; letter-spacing: 0.5px; font-weight: 600; display: flex; align-items: center; gap: 6px; }
        .active-until-date { font-size: 15px; font-weight: 700; color: #212529; }
        
        .days-left-badge { display: inline-flex; align-items: center; gap: 4px; padding: 4px 10px; border-radius: 20px; font-size: 11px; font-weight: 700; }
        .days-left-badge.safe { background: #d1fae5; color: #065f46; }
        .days-left-badge.warning { background: #fef3c7; color: #92400e; }
        .days-left-badge.expired { background: #fee2e2; color: #991b1b; }
        
        .progress-bar-custom { height: 8px; background: #e9ecef; border-radius: 10px; overflow: hidden; }
        .progress-fill { height: 100%; border-radius: 10px; transition: width 1.5s cubic-bezier(0.16, 1, 0.3, 1); }
        .progress-fill.safe { background: var(--success-gradient); }
        .progress-fill.warning { background: linear-gradient(135deg, #f59e0b 0%, #f97316 100%); }
        .progress-fill.expired { background: linear-gradient(135deg, #ef4444 0%, #dc2626 100%); }
        
        .progress-info { display: flex; justify-content: space-between; margin-top: 6px; font-size: 10px; color: #6c757d; font-weight: 500; }
        
        .payment-summary { background: linear-gradient(135deg, #ecfdf5 0%, #d1fae5 100%); border-radius: 14px; padding: 14px; margin-top: 14px; border: 1px solid rgba(17, 153, 142, 0.15); }
        .payment-summary-row { display: flex; justify-content: space-between; padding: 5px 0; font-size: 12px; }
        .payment-summary-row .label { color: #065f46; font-weight: 500; }
        .payment-summary-row .value { color: #065f46; font-weight: 700; }
        
        .footer-info { text-align: center; padding: 18px; background: #f8f9ff; color: #6c757d; font-size: 11px; border-top: 1px solid rgba(0,0,0,0.05); }
        .footer-info a { color: #667eea; text-decoration: none; font-weight: 600; }
        
        .btn-secondary-custom { background: white; color: #667eea; border: 2px solid #667eea; padding: 10px 24px; border-radius: 50px; font-weight: 600; transition: all 0.3s; text-decoration: none; display: inline-flex; align-items: center; gap: 8px; }
        .btn-secondary-custom:hover { background: #667eea; color: white; }
        
        .no-channel-warning {
            background: linear-gradient(135deg, #fff3cd 0%, #ffe69c 100%);
            border: 1px solid #ffc107;
            border-radius: 12px;
            padding: 14px;
            margin: 16px 0;
            display: flex;
            align-items: flex-start;
            gap: 10px;
            font-size: 13px;
            color: #664d03;
        }
        
        @media (max-width: 576px) {
            .card-body-custom { padding: 18px; }
            .amount-display .amount { font-size: 30px; }
            .paid-title { font-size: 22px; }
            .paid-icon, .paid-icon-wrapper { width: 100px; height: 100px; }
            .paid-icon { font-size: 50px; }
            .channel-grid { gap: 8px; }
            .channel-card { padding: 10px; }
            .channel-icon { width: 32px; height: 32px; font-size: 9px; }
            .channel-name { font-size: 11px; }
        }
    </style>
</head>
<body>
    <div class="payment-card">
        <div class="card-header-custom">
            <div class="logo-icon"><i class="bi bi-receipt-cutoff"></i></div>
            <h2>Pembayaran Tagihan Internet</h2>
            <
            <span class="gateway-badge">
                <i class="bi <?= $gatewayIcon ?>"></i>
                Pembayaran via <?= htmlspecialchars($gatewayLabel) ?>
            </span>
        </div>
        
        <div class="card-body-custom">
            
            <?php if ($isPaid): ?>
                <!-- STATE: LUNAS -->
                <div class="paid-state">
                    <div class="paid-icon-wrapper">
                        <div class="paid-icon"><i class="bi bi-check-lg"></i></div>
                    </div>
                    <h1 class="paid-title">Pembayaran Berhasil!</h1>
                    <p class="paid-subtitle">
                        Terima kasih <strong><?= htmlspecialchars($customer['name']) ?></strong>, 
                        tagihan Anda telah lunas dan layanan internet aktif kembali.
                    </p>
                    
                    <?php if ($packageInfo): ?>
                    <div class="package-info-card">
                        <div class="package-info-header">
                            <div class="package-icon"><i class="bi bi-wifi"></i></div>
                            <div style="flex: 1;">
                                <div class="package-title">Paket Internet Anda</div>
                                <h3 class="package-name"><?= htmlspecialchars($packageInfo['name']) ?></h3>
                                <?php if (!empty($packageInfo['speed'])): ?>
                                    <div class="package-speed"><i class="bi bi-speedometer2"></i> <?= htmlspecialchars($packageInfo['speed']) ?></div>
                                <?php endif; ?>
                            </div>
                        </div>
                        
                        <?php if ($activeUntilInfo): ?>
                        <div class="active-until-section">
                            <div class="active-until-header">
                                <div>
                                    <div class="active-until-label"><i class="bi bi-calendar-check"></i> Masa Aktif Hingga</div>
                                    <div class="active-until-date"><?= $activeUntilInfo['date_formatted'] ?></div>
                                </div>
                                <div class="days-left-badge <?= $activeUntilInfo['status'] ?>">
                                    <?php if ($activeUntilInfo['days_left'] > 0): ?>
                                        <i class="bi bi-clock-fill"></i> <?= $activeUntilInfo['days_left'] ?> hari lagi
                                    <?php elseif ($activeUntilInfo['days_left'] == 0): ?>
                                        <i class="bi bi-exclamation-triangle-fill"></i> Hari ini
                                    <?php else: ?>
                                        <i class="bi bi-x-circle-fill"></i> Expired
                                    <?php endif; ?>
                                </div>
                            </div>
                            <div class="progress-bar-custom">
                                <div class="progress-fill <?= $activeUntilInfo['status'] ?>" style="width: <?= $activeUntilInfo['progress'] ?>%;"></div>
                            </div>
                            <div class="progress-info">
                                <span>Terpakai: <?= $activeUntilInfo['progress'] ?>%</span>
                                <span><?= $activeUntilInfo['status_text'] ?></span>
                            </div>
                        </div>
                        <?php endif; ?>
                        
                        <?php if ($bill): ?>
                        <div class="payment-summary">
                            <div class="payment-summary-row"><span class="label">No. Tagihan</span><span class="value"><?= htmlspecialchars($bill['bill_number']) ?></span></div>
                            <div class="payment-summary-row"><span class="label">Nominal Dibayar</span><span class="value">Rp <?= number_format($bill['amount'], 0, ',', '.') ?></span></div>
                            <div class="payment-summary-row"><span class="label">Status</span><span class="value" style="color: #11998e;"><i class="bi bi-check-circle-fill"></i> LUNAS</span></div>
                            <?php if (!empty($bill['paid_at'])): ?>
                            <div class="payment-summary-row"><span class="label">Dibayar pada</span><span class="value"><?= date('d/m/Y H:i', strtotime($bill['paid_at'])) ?> WIB</span></div>
                            <?php endif; ?>
                        </div>
                        <?php endif; ?>
                    </div>
                    <?php endif; ?>
                    
                    <a href="https://wa.me/<?= preg_replace('/^0/', '62', $customer['phone'] ?? '') ?>" class="btn-secondary-custom">
                        <i class="bi bi-headset"></i> Butuh Bantuan? Hubungi Kami
                    </a>
                </div>
                
            <?php else: ?>
                <!-- STATE: BELUM BAYAR -->
                <div class="bill-info">
                    <div class="bill-info-row">
                        <span class="bill-info-label"><i class="bi bi-person"></i> Nama</span>
                        <span class="bill-info-value"><?= htmlspecialchars($customer['name']) ?></span>
                    </div>
                    <div class="bill-info-row">
                        <span class="bill-info-label"><i class="bi bi-hash"></i> No. Pelanggan</span>
                        <span class="bill-info-value"><?= htmlspecialchars($customer['customer_number']) ?></span>
                    </div>
                    <div class="bill-info-row">
                        <span class="bill-info-label"><i class="bi bi-receipt"></i> No. Tagihan</span>
                        <span class="bill-info-value"><?= htmlspecialchars($bill['bill_number']) ?></span>
                    </div>
                    <?php if ($packageInfo): ?>
                    <div class="bill-info-row">
                        <span class="bill-info-label"><i class="bi bi-box-seam"></i> Paket</span>
                        <span class="bill-info-value"><?= htmlspecialchars($packageInfo['name']) ?></span>
                    </div>
                    <?php endif; ?>
                    <div class="bill-info-row">
                        <span class="bill-info-label"><i class="bi bi-calendar-event"></i> Jatuh Tempo</span>
                        <span class="bill-info-value"><?= date('d/m/Y', strtotime($bill['due_date'])) ?></span>
                    </div>
                </div>
                
                <div class="amount-display">
                    <div class="label">Total Tagihan</div>
                    <div class="amount">Rp <?= number_format($bill['amount'], 0, ',', '.') ?></div>
                    <div class="due-info"><i class="bi <?= $dueIcon ?>"></i> <?= $dueInfo ?></div>
                </div>
                
                <?php if ($paymentError): ?>
                    <div class="error-box">
                        <i class="bi bi-exclamation-triangle-fill"></i>
                        <div><strong>Error:</strong> <?= htmlspecialchars($paymentError) ?></div>
                    </div>
                <?php endif; ?>
                
                <!-- PILIH CHANNEL PEMBAYARAN -->
                <?php if ($activeGateway === 'violet'): ?>
                    <?php if (empty($paymentChannels)): ?>
                        <div class="no-channel-warning">
                            <i class="bi bi-exclamation-triangle-fill" style="font-size: 18px;"></i>
                            <div>
                                <strong>Tidak ada channel pembayaran tersedia.</strong><br>
                                <?php if ($violetApiError): ?>
                                    <small><?= htmlspecialchars($violetApiError) ?></small>
                                <?php else: ?>
                                    <small>Nominal tagihan di luar batas channel yang tersedia, atau API belum dikonfigurasi.</small>
                                <?php endif; ?>
                            </div>
                        </div>
                    <?php else: ?>
                        <div class="channel-section">
                            <div class="channel-section-title">
                                <i class="bi bi-credit-card-2-front"></i>
                                Pilih Metode Pembayaran
                            </div>
                            
                            <!-- Tabs Kategori -->
                            <div class="channel-tabs">
                                <?php 
                                $first = true;
                                foreach ($groupedChannels as $key => $group):
                                    if (empty($group['channels'])) continue;
                                ?>
                                    <button type="button" class="channel-tab <?= $first ? 'active' : '' ?>" data-target="<?= $key ?>">
                                        <i class="bi <?= $group['icon'] ?>"></i>
                                        <?= $group['label'] ?>
                                        <span style="opacity: 0.7; font-size: 10px;">(<?= count($group['channels']) ?>)</span>
                                    </button>
                                <?php 
                                    $first = false;
                                endforeach; 
                                ?>
                            </div>
                            
                            <!-- Channel Groups -->
                            <?php 
                            $first = true;
                            foreach ($groupedChannels as $key => $group):
                                if (empty($group['channels'])) continue;
                            ?>
                                <div class="channel-group <?= $first ? 'active' : '' ?>" data-group="<?= $key ?>">
                                    <div class="channel-grid">
                                        <?php foreach ($group['channels'] as $ch): 
                                            $kode = strtoupper($ch['nama'] ?? '');
                                            $info = $allowedChannels[$kode] ?? null;
                                            if (!$info) continue;
                                            
                                            $isPopular = $info['popular'] ?? false;
                                            $color = $info['color'] ?? '#6c757d';
                                            $iconText = $info['icon'] ?? $kode;
                                            $label = $info['label'] ?? $kode;
                                            
                                            // Hitung fee dengan fungsi yang sudah dikoreksi
                                            $feeInfo = calculateChannelFee($kode, $bill['amount']);
                                        ?>
                                            <div class="channel-card" 
                                                 data-channel="<?= htmlspecialchars($kode) ?>"
                                                 data-fee="<?= $feeInfo['fee'] ?>"
                                                 data-fee-text="<?= htmlspecialchars($feeInfo['text']) ?>"
                                                 data-fee-breakdown="<?= htmlspecialchars($feeInfo['breakdown']) ?>"
                                                 data-is-percent="<?= $feeInfo['is_percent'] ? '1' : '0' ?>">
                                                <?php if ($isPopular): ?>
                                                    <span class="channel-badge-popular">⭐ Populer</span>
                                                <?php endif; ?>
                                                <div class="channel-header">
                                                    <div class="channel-icon" style="background: <?= $color ?>;">
                                                        <?= htmlspecialchars($iconText) ?>
                                                    </div>
                                                    <div class="channel-name"><?= htmlspecialchars($label) ?></div>
                                                </div>
                                                <div class="channel-fee">
                                                    <span class="channel-fee-label">Biaya admin</span>
                                                    <span class="channel-fee-value"><?= htmlspecialchars($feeInfo['text']) ?></span>
                                                </div>
                                            </div>
                                        <?php endforeach; ?>
                                    </div>
                                </div>
                            <?php 
                                $first = false;
                            endforeach; 
                            ?>
                        </div>
                        
                        <!-- Total Calculation -->
                        <div class="total-calculation" id="totalCalculation">
                            <div class="total-row">
                                <span>Tagihan</span>
                                <span>Rp <?= number_format($bill['amount'], 0, ',', '.') ?></span>
                            </div>
                            <div class="total-row">
                                <div>
                                    <span>Biaya Admin (<span id="selectedChannelName">-</span>)</span>
                                    <div class="fee-breakdown" id="feeBreakdown"></div>
                                </div>
                                <span id="feeAmount">Rp 0</span>
                            </div>
                            <div class="total-row final">
                                <span>Total Bayar</span>
                                <span class="value" id="totalAmount">Rp 0</span>
                            </div>
                        </div>
                    <?php endif; ?>
                <?php endif; ?>
                
                <form method="POST" id="paymentForm">
                    <input type="hidden" name="token" value="<?= $formToken ?>">
                    <input type="hidden" name="action" value="pay_now">
                    <input type="hidden" name="selected_channel" id="selected_channel" value="<?= $activeGateway === 'violet' ? 'QRIS1' : '' ?>">
                    
                    <button type="submit" class="btn-pay" id="btnPay" <?= empty($paymentChannels) && $activeGateway === 'violet' ? 'disabled' : '' ?>>
                        <i class="bi bi-credit-card-2-front" id="btnIcon"></i>
                        <span id="btnText">Bayar Sekarang</span>
                    </button>
                </form>
                
                <div class="text-center mt-3">
                    <small class="text-muted">
                        <i class="bi bi-shield-lock"></i> Transaksi aman via <?= htmlspecialchars($gatewayLabel) ?>
                    </small>
                </div>
            <?php endif; ?>
        </div>
        
        <div class="footer-info">
           
        </div>
    </div>
    
    <script>
        // Tab switching
        document.querySelectorAll('.channel-tab').forEach(tab => {
            tab.addEventListener('click', function() {
                document.querySelectorAll('.channel-tab').forEach(t => t.classList.remove('active'));
                document.querySelectorAll('.channel-group').forEach(g => g.classList.remove('active'));
                
                this.classList.add('active');
                const target = this.dataset.target;
                document.querySelector(`.channel-group[data-group="${target}"]`).classList.add('active');
            });
        });
        
        // Channel selection dengan perhitungan fee yang benar
        const billAmount = <?= $bill['amount'] ?? 0 ?>;
        const formatRupiah = (num) => 'Rp ' + new Intl.NumberFormat('id-ID').format(Math.round(num));
        
        document.querySelectorAll('.channel-card').forEach(card => {
            card.addEventListener('click', function() {
                document.querySelectorAll('.channel-card').forEach(c => c.classList.remove('selected'));
                this.classList.add('selected');
                
                const channel = this.dataset.channel;
                const fee = parseFloat(this.dataset.fee);
                const feeText = this.dataset.feeText;
                const feeBreakdown = this.dataset.feeBreakdown;
                const isPercent = this.dataset.isPercent === '1';
                
                document.getElementById('selected_channel').value = channel;
                
                const totalCalc = document.getElementById('totalCalculation');
                totalCalc.classList.add('show');
                
                document.getElementById('selectedChannelName').textContent = channel;
                document.getElementById('feeAmount').textContent = feeText;
                
                // Tampilkan breakdown fee
                const breakdownEl = document.getElementById('feeBreakdown');
                if (isPercent) {
                    breakdownEl.textContent = `(${feeBreakdown})`;
                } else {
                    breakdownEl.textContent = '(Flat)';
                }
                
                const total = billAmount + fee;
                document.getElementById('totalAmount').textContent = formatRupiah(total);
            });
        });
        
        // Form submit handler
        const paymentForm = document.getElementById('paymentForm');
        const btnPay = document.getElementById('btnPay');
        const btnIcon = document.getElementById('btnIcon');
        const btnText = document.getElementById('btnText');
        
        if (paymentForm && btnPay) {
            paymentForm.addEventListener('submit', function(e) {
                const selectedChannel = document.getElementById('selected_channel').value;
                
                <?php if ($activeGateway === 'violet'): ?>
                if (!selectedChannel) {
                    e.preventDefault();
                    alert('Silakan pilih metode pembayaran terlebih dahulu');
                    return false;
                }
                <?php endif; ?>
                
                btnPay.disabled = true;
                btnIcon.className = 'bi bi-hourglass-split';
                btnIcon.style.animation = 'spin 1s linear infinite';
                btnText.textContent = 'Mengarahkan ke pembayaran...';
                
                const style = document.createElement('style');
                style.textContent = `@keyframes spin { from { transform: rotate(0deg); } to { transform: rotate(360deg); } }`;
                document.head.appendChild(style);
            });
        }
        
        // Confetti untuk state LUNAS
        <?php if ($isPaid): ?>
        function createConfetti() {
            const colors = ['#667eea', '#764ba2', '#11998e', '#38ef7d', '#f093fb', '#f5576c', '#fbbf24'];
            for (let i = 0; i < 50; i++) {
                const confetti = document.createElement('div');
                confetti.style.cssText = `
                    position: fixed;
                    width: 10px; height: 10px;
                    background: ${colors[Math.floor(Math.random() * colors.length)]};
                    left: ${Math.random() * 100}%;
                    top: -10px;
                    border-radius: ${Math.random() > 0.5 ? '50%' : '0'};
                    animation: confettiFall ${2 + Math.random() * 2}s ease-in forwards;
                    z-index: 9999;
                `;
                document.body.appendChild(confetti);
                setTimeout(() => confetti.remove(), 4000);
            }
        }
        
        const confettiStyle = document.createElement('style');
        confettiStyle.textContent = `
            @keyframes confettiFall {
                0% { transform: translateY(0) rotate(0deg); opacity: 1; }
                100% { transform: translateY(100vh) rotate(720deg); opacity: 0; }
            }
        `;
        document.head.appendChild(confettiStyle);
        
        window.addEventListener('load', () => setTimeout(createConfetti, 300));
        
        setTimeout(() => {
            const progressFill = document.querySelector('.progress-fill');
            if (progressFill) {
                const targetWidth = progressFill.style.width;
                progressFill.style.width = '0%';
                setTimeout(() => progressFill.style.width = targetWidth, 100);
            }
        }, 500);
        <?php endif; ?>
    </script>
</body>
</html>