<?php
session_start();

// 1. PENGECEKAN SESI PENGGUNA
if(!isset($_SESSION["loggedin"]) || $_SESSION["loggedin"] !== true){
    header("location: login");
    exit;
}

// 2. MEMANGGIL FILE KONEKSI DATABASE
require_once "../setting/database.php";

// 3. KONFIGURASI DAN INISIALISASI VARIABEL
$api_key = "2IlkUzIHCJNNVu4g5oRoCcNxeUTaxP3tJngs7uOf8x6pOqAGwoI72aQ3Vn3nhEuXfonu0kzmIm14RRge5xqPuDCQIq8icJvEaYFU"; // GANTI DENGAN API KEY ANDA
$user_id = $_SESSION["id"];
$pesan_notifikasi = "";

// Variabel untuk menampung detail pembayaran & memicu modal
$payment_details_for_modal = null;
$show_modal = false;

// 4. LOGIKA UTAMA: PROSES FORM SAAT DI-SUBMIT (METHOD POST)
if($_SERVER["REQUEST_METHOD"] == "POST"){
    $jumlah = (int)$_POST['jumlah'];
    $metode_pembayaran_gabungan = $_POST['metode_pembayaran']; 

    if(!empty($jumlah) && $jumlah > 0 && !empty($metode_pembayaran_gabungan)){
        
        $parts = explode('|', $metode_pembayaran_gabungan);
        if (count($parts) !== 2 || empty(trim($parts[0])) || empty(trim($parts[1]))) {
            $pesan_notifikasi = "<div class='alert alert-danger'><strong>Error:</strong> Data metode pembayaran tidak valid.</div>";
        } else {
            list($type, $method_code) = $parts;
            $reff_id = "INV-" . time() . "-" . $user_id;

            // =================================================================
            // TAHAP 1: BUAT TRANSAKSI AWAL DI DATABASE ANDA
            // =================================================================
            $sql_initial_insert = "INSERT INTO deposits (user_id, invoice_id, amount_initial, method_code, status, created_at) VALUES (?, ?, ?, ?, 'new', NOW())";
            $stmt_initial = mysqli_prepare($link, $sql_initial_insert);
            mysqli_stmt_bind_param($stmt_initial, "isds", $user_id, $reff_id, $jumlah, $method_code);
            
            if (mysqli_stmt_execute($stmt_initial)) {
                // =================================================================
                // TAHAP 2: HUBUNGI API PROVIDER
                // =================================================================
                $api_params = ['api_key' => $api_key, 'reff_id' => $reff_id, 'nominal' => $jumlah, 'type' => $type, 'method' => $method_code];
                $post_data = http_build_query($api_params);

                $curl = curl_init();
                curl_setopt_array($curl, array(
                    CURLOPT_URL => 'https://atlantich2h.com/deposit/create',
                    CURLOPT_RETURNTRANSFER => true, CURLOPT_POST => true, CURLOPT_POSTFIELDS => $post_data,
                ));
                $response = curl_exec($curl);
                curl_close($curl);
                $api_result = json_decode($response, true);

                // =================================================================
                // TAHAP 3: PROSES RESPONS API DAN UPDATE DATABASE
                // =================================================================
                if(isset($api_result['status']) && $api_result['status'] === true) {
                    // --- Jika API SUKSES ---
                    $data = $api_result['data'];
                    $sql_update_success = "UPDATE deposits SET provider_trx_id = ?, amount_final = ?, fee_provider = ?, payment_details = ?, status = ?, expired_at = ? WHERE invoice_id = ?";
                    $stmt_update = mysqli_prepare($link, $sql_update_success);
                    $payment_details_json = json_encode($data);
                    mysqli_stmt_bind_param($stmt_update, "sddssss", $data['id'], $data['nominal'], $data['fee'], $payment_details_json, $data['status'], $data['expired_at'], $reff_id);
                    
                    if(mysqli_stmt_execute($stmt_update)){
                        if (isset($data['url']) && !empty($data['url'])) {
                            header('Location: ' . $data['url']);
                            exit();
                        } else {
                            $payment_details_for_modal = $data;
                            $show_modal = true;
                        }
                    } else {
                         $pesan_notifikasi = "<div class='alert alert-danger'>Gagal mengupdate database dengan data API.</div>";
                    }

                } else {
                    // --- Jika API GAGAL ---
                    $api_message = $api_result['message'] ?? 'Terjadi kesalahan pada server provider.';
                    // Update status transaksi di database menjadi 'failed'
                    $sql_update_failed = "UPDATE deposits SET status = 'failed', payment_details = ? WHERE invoice_id = ?";
                    $stmt_update_fail = mysqli_prepare($link, $sql_update_failed);
                    mysqli_stmt_bind_param($stmt_update_fail, "ss", $api_message, $reff_id);
                    mysqli_stmt_execute($stmt_update_fail);

                    // Tampilkan pesan error yang informatif
                    $pesan_notifikasi = "<div class='alert alert-danger'><strong>Gagal Membuat Deposit!</strong><br>Pesan: " . htmlspecialchars($api_message) . "</div>";
                }
            } else {
                $pesan_notifikasi = "<div class='alert alert-danger'>Gagal membuat transaksi awal di database.</div>";
            }
        }
    } else {
        $pesan_notifikasi = "<div class='alert alert-warning'>Harap isi jumlah dan pilih metode pembayaran.</div>";
    }
}

// 5. PENGAMBILAN DATA UNTUK TAMPILAN HALAMAN
$saldo_user = 0;
$sql_user = "SELECT saldo FROM users WHERE id = ?";
if($stmt_user = mysqli_prepare($link, $sql_user)){
    mysqli_stmt_bind_param($stmt_user, "i", $user_id);
    if(mysqli_stmt_execute($stmt_user)){
        $result_user = mysqli_stmt_get_result($stmt_user);
        if($row_user = mysqli_fetch_assoc($result_user)){
            $saldo_user = $row_user['saldo'];
        }
    }
    mysqli_stmt_close($stmt_user);
}

$metode_terkelompok = [];
$sql_metode = "SELECT metode, nama, image, type, fee, fee_persen FROM metode_pembayaran WHERE status = 'Aktif' ORDER BY type, nama ASC";
if($result_metode = mysqli_query($link, $sql_metode)){
    while($row = mysqli_fetch_assoc($result_metode)){
        $type = $row['type'];
        if (!isset($metode_terkelompok[$type])) {
            $metode_terkelompok[$type] = [];
        }
        $metode_terkelompok[$type][] = $row;
    }
}

$riwayat_deposit = [];
// [DIPERBAIKI] Menambahkan `method_code` pada query
$sql_history = "SELECT invoice_id, amount_final, method_code, status, created_at FROM deposits WHERE user_id = ? ORDER BY created_at DESC LIMIT 10";
if($stmt_history = mysqli_prepare($link, $sql_history)){
    mysqli_stmt_bind_param($stmt_history, "i", $user_id);
    if(mysqli_stmt_execute($stmt_history)){
        $result_history = mysqli_stmt_get_result($stmt_history);
        while($row = mysqli_fetch_assoc($result_history)){
            $riwayat_deposit[] = $row;
        }
    }
    mysqli_stmt_close($stmt_history);
}

mysqli_close($link);

// 6. MEMANGGIL HEADER HALAMAN
require_once '../menu/header.php';
?>

<style>
    .payment-method-card { border: 1px solid #dee2e6; border-radius: 0.375rem; padding: 1rem; cursor: pointer; transition: all 0.2s ease-in-out; display: flex; align-items: center; margin-bottom: 0.75rem; background-color: #fff; }
    .payment-method-card:hover { border-color: #0d6efd; background-color: #f8f9fa; }
    .payment-method-card.selected { border-color: #0d6efd; background-color: #e7f1ff; box-shadow: 0 0 0 2px rgba(13, 110, 253, 0.25); }
    .payment-method-logo { width: 60px; height: 35px; margin-right: 1rem; object-fit: contain; }
    .payment-method-details { flex-grow: 1; }
    .accordion-button:not(.collapsed) { color: #fff; background-color: #0d6efd; }
    .modal-body .detail-item { display: flex; justify-content: space-between; padding: 10px 0; border-bottom: 1px solid #eee; }
    .modal-body .detail-item:last-child { border-bottom: none; }
    .modal-body .detail-item span:first-child { font-weight: bold; }
    .modal-body .total { font-size: 1.5em; font-weight: bold; color: #0d6efd; }
    .modal-body .qr-code { max-width: 250px; margin: 20px auto; }
</style>

<div class="container mt-5 mb-5">
    <div class="row">
        <div class="col-lg-5 mb-4">
            <div class="card shadow-sm h-100">
                <div class="card-header bg-primary text-white"><h5 class="mb-0">💰 Isi Saldo</h5></div>
                <div class="card-body">
                    <div class="alert alert-info">Saldo Anda: <strong>Rp <?php echo number_format($saldo_user, 0, ',', '.'); ?></strong></div>
                    <?php if(!empty($pesan_notifikasi)) echo $pesan_notifikasi; ?>
                    
                    <form action="deposit" method="post" id="depositForm">
                        <div class="mb-3">
                            <label for="jumlah" class="form-label fw-bold">Jumlah Deposit</label>
                            <input type="number" class="form-control form-control-lg" id="jumlah" name="jumlah" placeholder="Contoh: 50000" required>
                        </div>
                        
                        <div class="mb-4">
                            <label class="form-label fw-bold">Metode Pembayaran</label>
                            <div class="accordion" id="accordionMetodePembayaran">
                                <?php if (empty($metode_terkelompok)): ?>
                                    <div class="alert alert-warning">Tidak ada metode pembayaran yang tersedia saat ini.</div>
                                <?php else: ?>
                                    <?php $i = 0; foreach($metode_terkelompok as $type => $metode_list): ?>
                                        <div class="accordion-item">
                                            <h2 class="accordion-header" id="heading-<?php echo $i; ?>">
                                                <button class="accordion-button <?php if($i > 0) echo 'collapsed'; ?>" type="button" data-bs-toggle="collapse" data-bs-target="#collapse-<?php echo $i; ?>" aria-expanded="<?php echo ($i == 0) ? 'true' : 'false'; ?>">
                                                    <?php echo ucwords(str_replace('_', ' ', $type)); ?>
                                                </button>
                                            </h2>
                                            <div id="collapse-<?php echo $i; ?>" class="accordion-collapse collapse <?php if($i == 0) echo 'show'; ?>" data-bs-parent="#accordionMetodePembayaran">
                                                <div class="accordion-body bg-light">
                                                    <?php foreach($metode_list as $metode): ?>
                                                        <?php
                                                            $fee = (float)$metode['fee'];
                                                            $fee_persen = (float)$metode['fee_persen'];
                                                            $formatted_fee = "Rp " . number_format($fee, 0, ',', '.');
                                                            $formatted_persen = rtrim(rtrim($fee_persen, '0'), '.') . "%";

                                                            if ($fee > 0 && $fee_persen > 0) {
                                                                $fee_text = "Biaya: " . $formatted_fee . " + " . $formatted_persen;
                                                            } elseif ($fee > 0) {
                                                                $fee_text = "Biaya: " . $formatted_fee;
                                                            } elseif ($fee_persen > 0) {
                                                                $fee_text = "Biaya: " . $formatted_persen;
                                                            } else {
                                                                $fee_text = "<span class='text-success'>Gratis Biaya Admin</span>";
                                                            }
                                                        ?>
                                                        <div class="payment-method-card" onclick="selectPayment('<?php echo htmlspecialchars($metode['metode']); ?>')">
                                                            <img src="<?php echo htmlspecialchars($metode['image']); ?>" alt="Logo <?php echo htmlspecialchars($metode['nama']); ?>" class="payment-method-logo">
                                                            <div class="payment-method-details">
                                                                <span class="fw-bold"><?php echo htmlspecialchars($metode['nama']); ?></span>
                                                                <small class="d-block"><?php echo $fee_text; ?></small>
                                                            </div>
                                                            <input class="form-check-input payment-method-radio" type="radio" name="metode_pembayaran" id="metode_<?php echo htmlspecialchars($metode['metode']); ?>" value="<?php echo htmlspecialchars($metode['type']) . '|' . htmlspecialchars($metode['metode']); ?>" required>
                                                        </div>
                                                    <?php endforeach; ?>
                                                </div>
                                            </div>
                                        </div>
                                    <?php $i++; endforeach; ?>
                                <?php endif; ?>
                            </div>
                        </div>
                        <button type="submit" class="btn btn-primary w-100 btn-lg">Buat Deposit</button>
                    </form>
                </div>
            </div>
        </div>

        <div class="col-lg-7">
             <div class="card shadow-sm h-100">
                <div class="card-header bg-dark text-white"><h5 class="mb-0">📜 Riwayat Deposit Terakhir</h5></div>
                <div class="card-body p-0">
                    <div class="table-responsive">
                        <table class="table table-striped table-hover mb-0">
                           <thead class="table-light">
                                <tr><th>Invoice</th><th>Jumlah</th><th>Metode</th><th>Status</th><th>Tanggal</th></tr>
                            </thead>
                            <tbody>
                                <?php if(empty($riwayat_deposit)): ?>
                                    <tr><td colspan="5" class="text-center py-4">Belum ada riwayat deposit.</td></tr>
                                <?php else: ?>
                                    <?php foreach($riwayat_deposit as $deposit): ?>
                                    <tr>
                                        <td><small><?php echo htmlspecialchars($deposit['invoice_id']); ?></small></td>
                                        <td>Rp <?php echo number_format($deposit['amount_final'], 0, ',', '.'); ?></td>
                                        <td><?php echo htmlspecialchars($deposit['method_code']); ?></td>
                                        <td>
                                            <?php
                                                $status = htmlspecialchars($deposit['status']);
                                                $badge_class = 'bg-secondary';
                                                if ($status == 'Success' || $status == 'success') $badge_class = 'bg-success';
                                                elseif ($status == 'Pending' || $status == 'pending') $badge_class = 'bg-warning text-dark';
                                                elseif ($status == 'Failed' || $status == 'expired') $badge_class = 'bg-danger';
                                                echo "<span class='badge {$badge_class}'>{$status}</span>";
                                            ?>
                                        </td>
                                        <td><small><?php echo date("d M Y, H:i", strtotime($deposit['created_at'])); ?></small></td>
                                    </tr>
                                    <?php endforeach; ?>
                                <?php endif; ?>
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<div class="modal fade" id="paymentModal" data-bs-backdrop="static" data-bs-keyboard="false" tabindex="-1" aria-labelledby="paymentModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="paymentModalLabel">Instruksi Pembayaran</h5>
            </div>
            <div class="modal-body">
                <?php if ($payment_details_for_modal): ?>
                    <?php $details = $payment_details_for_modal; ?>
                    <?php if (isset($details['qr_string'])): ?>
                        <p class="text-center">Scan QR Code di bawah ini:</p>
                        <img src="<?php echo htmlspecialchars($details['qr_image']); ?>" alt="QR Code" class="d-block qr-code img-fluid">
                    <?php elseif (isset($details['bank'])): ?>
                        <p class="text-center">Silakan transfer ke rekening berikut:</p>
                        <div class="detail-item"><span>Bank</span> <span><?php echo htmlspecialchars($details['bank']); ?></span></div>
                        <?php if (isset($details['nomor_va'])): ?>
                            <div class="detail-item"><span>Nomor Virtual Account</span> <strong><?php echo htmlspecialchars($details['nomor_va']); ?></strong></div>
                        <?php endif; ?>
                        <?php if (isset($details['tujuan'])): ?>
                            <div class="detail-item"><span>Nomor Rekening</span> <strong><?php echo htmlspecialchars($details['tujuan']); ?></strong></div>
                            <div class="detail-item"><span>Atas Nama</span> <span><?php echo htmlspecialchars($details['atas_nama']); ?></span></div>
                        <?php endif; ?>
                    <?php endif; ?>
                    <hr>
                    <div class="detail-item">
                        <span>Total Pembayaran</span>
                        <span class="total">Rp <?php echo number_format($details['nominal'], 0, ',', '.'); ?></span>
                    </div>
                     <div class="alert alert-warning mt-3 text-center">
                        Bayar sebelum: <strong><?php echo date("d M Y H:i", strtotime($details['expired_at'])); ?></strong>
                    </div>
                <?php endif; ?>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-primary w-100" data-bs-dismiss="modal" onclick="location.reload();">Selesai</button>
            </div>
        </div>
    </div>
</div>

<script>
    function selectPayment(methodCode) {
        document.querySelectorAll('.payment-method-card').forEach(card => card.classList.remove('selected'));
        const radioBtn = document.getElementById('metode_' + methodCode);
        if (radioBtn) {
            radioBtn.checked = true;
            radioBtn.closest('.payment-method-card').classList.add('selected');
        }
    }

    <?php if (isset($show_modal) && $show_modal === true): ?>
    document.addEventListener('DOMContentLoaded', function() {
        var myModal = new bootstrap.Modal(document.getElementById('paymentModal'));
        myModal.show();
    });
    <?php endif; ?>
</script>

<?php require_once '../menu/footer.php'; ?>
