<?php
// =================================================================
// Blok PHP (Tidak Ada Perubahan dari Sebelumnya)
// =================================================================

// MATIKAN JIKA SUDAH PRODUCTION
ini_set('display_errors', 1);
error_reporting(E_ALL);

// KONFIGURASI
$bukaolshop_secret_key = '27284b9e7047f18d8844572991d6eb4b';
$atlantic_api_key = '2IlkUzIHCJNNVu4g5oRoCcNxeUTaxP3tJngs7uOf8x6pOqAGwoI72aQ3Vn3nhEuXfonu0kzmIm14RRge5xqPuDCQIq8icJvEaYFU'; // <-- GANTI DENGAN API KEY ANDA

// FUNGSI & VALIDASI AWAL
function stop_process($message) {
    http_response_code(400);
    die("Error: " . htmlspecialchars($message));
}
if ($_SERVER['REQUEST_METHOD'] !== 'POST') { stop_process("Metode request tidak valid."); }
$secret_callback = $_POST['secret_callback'] ?? null;
if ($secret_callback !== $bukaolshop_secret_key) { stop_process("Secret Key tidak valid!"); }
if (($_POST['status'] ?? null) !== 'ok') { stop_process("Status callback tidak 'ok'."); }
$total_topup = (float) ($_POST['total_topup'] ?? 0);

// Ambil Metode Pembayaran dari API AtlanticH2H
$curl = curl_init();
curl_setopt_array($curl, array(
  CURLOPT_URL => 'https://atlantich2h.com/deposit/metode',
  CURLOPT_RETURNTRANSFER => true,
  CURLOPT_CUSTOMREQUEST => 'POST',
  CURLOPT_POSTFIELDS => 'api_key=' . urlencode($atlantic_api_key),
));
$response = curl_exec($curl);
curl_close($curl);
$metode_pembayaran_data = json_decode($response, true);

if (json_last_error() !== JSON_ERROR_NONE || ($metode_pembayaran_data['status'] ?? false) !== true) {
    stop_process("Gagal memproses response dari API Pembayaran. Response: " . htmlspecialchars($response));
}
$daftar_metode = $metode_pembayaran_data['data'];


// =================================================================
// Bagian HTML Baru dengan Bootstrap 5
// =================================================================
?>
<!DOCTYPE html>
<html lang="id">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Pilih Metode Pembayaran</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-QWTKZyjpPEjISv5WaRU9OFeRpok6YctnYmDr5pNlyT2bRjXh0JMhjY6hW+ALEwIH" crossorigin="anonymous">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.3/font/bootstrap-icons.min.css">
    
    <style>
        /* Sedikit kustomisasi untuk tampilan yang lebih baik */
        body {
            background-color: #f0f2f5; /* Warna latar yang lebih lembut */
        }
        .payment-button {
            transition: all 0.2s ease-in-out;
        }
        .payment-button:hover {
            transform: translateY(-2px);
            box-shadow: 0 4px 15px rgba(0,0,0,0.1) !important;
        }
    </style>
</head>
<body class="d-flex align-items-center py-4 bg-body-tertiary">
    
<main class="container">
    <div class="row justify-content-center">
        <div class="col-lg-6 col-md-8">

            <div class="card shadow-lg border-0 rounded-4">
                <div class="card-body p-4 p-md-5">

                    <div class="text-center mb-4">
                        <h3 class="fw-bold">Pilih Metode Deposit</h3>
                    </div>
                    
                    <form action="https://herideveloper.com/payment.php" method="post">
                        
                        <?php
                        // Menyembunyikan data dari BukaOlshop untuk diteruskan
                        foreach ($_POST as $key => $value) {
                            echo '<input type="hidden" name="' . htmlspecialchars($key) . '" value="' . htmlspecialchars($value) . '">';
                        }

                        // =================================================================
                        // ## LANGKAH 1: Mengelompokkan Metode Pembayaran ##
                        // =================================================================
                        
                        // Siapkan semua kategori yang mungkin
                        $grouped_methods = [
                            'qris' => [],
                            'ewallet' => [],
                            'va' => [],
                            'bank' => []
                        ];
                        
                        // Siapkan daftar nama/metode QRIS yang valid dalam huruf kecil
                        $qris_identifiers = ['qris instant', 'qris', 'qrisfast'];

                        foreach ($daftar_metode as $metode) {
                            // Filter hanya metode yang valid
                            if ($metode['status'] !== 'aktif' || $total_topup < (float)$metode['min'] || $total_topup > (float)$metode['max']) {
                                continue;
                            }
                            
                            // ## LOGIKA YANG DIPERBAIKI ##
                            $current_name = strtolower($metode['name']);
                            $current_method = strtolower($metode['metode']);

                            // Cek apakah nama atau metode ada di dalam daftar identifier QRIS
                            if (in_array($current_name, $qris_identifiers) || in_array($current_method, $qris_identifiers)) {
                                $grouped_methods['qris'][] = $metode;
                            } else {
                                // Jika bukan QRIS, kelompokkan berdasarkan 'type' seperti biasa.
                                $type = strtolower($metode['type']);
                                if (array_key_exists($type, $grouped_methods)) {
                                    $grouped_methods[$type][] = $metode;
                                }
                            }
                        }
                        ?>

                        <?php
                        // Definisikan nama heading untuk setiap grup
                        $group_headings = [
                            'qris' => 'QRIS',
                            'ewallet' => 'E-Wallet',
                            'va' => 'Virtual Account',
                            'bank' => 'Transfer Bank'
                        ];

                        // Looping melalui setiap grup untuk menampilkannya
                        foreach ($grouped_methods as $type => $methods_in_group):
                            // Hanya tampilkan grup jika ada isinya
                            if (!empty($methods_in_group)):
                        ?>
                                <h5 class="text-muted fw-bold mt-4 mb-3"><?php echo $group_headings[$type]; ?></h5>
                                <div class="d-grid gap-3">
                                    <?php foreach ($methods_in_group as $metode): ?>
                                        <?php
                                            // Logika validasi biaya (tidak ada perubahan)
                                            $fee_flat = (float) $metode['fee'];
                                            $fee_percent = (float) $metode['fee_persen'];
                                            $biaya_text = '';
                                            if ($fee_flat == 0 && $fee_percent == 0) {
                                                $biaya_text = '<span class="text-success fw-bold">Gratis</span>';
                                            } elseif ($fee_flat > 0 && $fee_percent == 0) {
                                                $biaya_text = 'Admin fee: Rp ' . number_format($fee_flat, 0, ',', '.');
                                            } elseif ($fee_flat == 0 && $fee_percent > 0) {
                                                $biaya_text = 'Admin fee: ' . $fee_percent . '%';
                                            } elseif ($fee_flat > 0 && $fee_percent > 0) {
                                                $biaya_text = 'Admin fee: Rp ' . number_format($fee_flat, 0, ',', '.') . ' + ' . $fee_percent . '%';
                                            }
                                        ?>
                                        <button type="submit" name="metode_pembayaran" value="<?php echo htmlspecialchars($metode['metode'] . '|' . $metode['type']); ?>"class="btn btn-light border p-3 text-start d-flex align-items-center payment-button shadow-sm">
                                            <img src="<?php echo htmlspecialchars($metode['img_url']); ?>" alt="Logo" class="me-3" style="width:45px;">
                                            <div class="flex-grow-1">
                                                <div class="fw-bold"><?php echo htmlspecialchars($metode['name']); ?></div>
                                                <small class="text-muted"><?php echo $biaya_text; ?></small>
                                            </div>
                                      <?php
                                          // Cek jika statusnya 'aktif'
                                          if (strtolower($metode['status']) == 'aktif') {
                                              // Jika ya, tampilkan ikon titik hijau
                                              echo '<i class="bi bi-circle-fill text-success"></i>';
                                          } else {
                                              // Jika tidak, tampilkan ikon titik merah
                                              echo '<i class="bi bi-circle-fill text-danger"></i>';
                                          }
                                      ?>
                                        </button>
                                    <?php endforeach; ?>
                                </div>
                        <?php 
                            endif; 
                        endforeach; 
                        ?>
                    </form>

                </div>
                <div class="card-footer text-center bg-transparent border-0 py-3">
                    <small class="text-muted">Transaksi aman dan terenkripsi</small>
                </div>
            </div>

        </div>
    </div>
</main>

</body>
</html>
