<?php
ob_start();
include 'config.php';
checkLogin();

$page_title  = "Menu Pembayaran";
$active_page = "pembayaran";
include 'layout.php';

// ─── Ambil setting metode pembayaran ───
$metode_list = json_decode(get_setting($conn, 'payment_methods') ?: '[]', true);
if (empty($metode_list)) {
    $metode_list = [
        ['id'=>1,'nama'=>'Cash','icon'=>'bx-money','aktif'=>true,'ket'=>'Pembayaran tunai langsung'],
        ['id'=>2,'nama'=>'Transfer Bank','icon'=>'bx-transfer','aktif'=>true,'ket'=>'BCA / BRI / Mandiri / BNI'],
        ['id'=>3,'nama'=>'QRIS','icon'=>'bx-qr','aktif'=>true,'ket'=>'GoPay, OVO, Dana, ShopeePay, dll'],
        ['id'=>4,'nama'=>'Member Saldo','icon'=>'bx-wallet','aktif'=>true,'ket'=>'Potong saldo member VIP'],
        ['id'=>5,'nama'=>'Voucher','icon'=>'bx-gift','aktif'=>false,'ket'=>'Kode voucher diskon'],
    ];
}

// ─── Handle: simpan konfigurasi metode ───
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['save_methods'])) {
    $aktif_ids = $_POST['aktif'] ?? [];
    foreach ($metode_list as &$m) {
        $m['aktif'] = in_array($m['id'], $aktif_ids);
    }
    unset($m);
    $json = json_encode($metode_list);
    $stmt = $conn->prepare("INSERT INTO system_settings (setting_name, setting_value) VALUES ('payment_methods', ?) ON DUPLICATE KEY UPDATE setting_value = VALUES(setting_value)");
    $stmt->bind_param("s", $json);
    $stmt->execute();
    $stmt->close();
    get_setting($conn, 'payment_methods', true);
    $save_ok = true;
}

// ─── Handle: tambah metode baru ───
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['add_method'])) {
    $nama_baru = trim($_POST['nama_baru'] ?? '');
    $ket_baru  = trim($_POST['ket_baru'] ?? '');
    if (!empty($nama_baru)) {
        $new_id = max(array_column($metode_list, 'id') ?: [0]) + 1;
        $metode_list[] = ['id'=>$new_id,'nama'=>$nama_baru,'icon'=>'bx-credit-card','aktif'=>true,'ket'=>$ket_baru];
        $json = json_encode($metode_list);
        $stmt = $conn->prepare("INSERT INTO system_settings (setting_name, setting_value) VALUES ('payment_methods', ?) ON DUPLICATE KEY UPDATE setting_value = VALUES(setting_value)");
        $stmt->bind_param("s", $json);
        $stmt->execute();
        $stmt->close();
        get_setting($conn, 'payment_methods', true);
        $save_ok = true;
        write_log($conn, 'ADD_PAYMENT_METHOD', "Tambah metode: $nama_baru");
    }
}

// ─── Handle: hapus metode ───
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['hapus_id'])) {
    $hapus_id = (int)$_POST['hapus_id'];
    $metode_list = array_values(array_filter($metode_list, fn($m) => $m['id'] !== $hapus_id));
    $json = json_encode($metode_list);
    $stmt = $conn->prepare("INSERT INTO system_settings (setting_name, setting_value) VALUES ('payment_methods', ?) ON DUPLICATE KEY UPDATE setting_value = VALUES(setting_value)");
    $stmt->bind_param("s", $json);
    $stmt->execute();
    $stmt->close();
    get_setting($conn, 'payment_methods', true);
    $save_ok = true;
}

// ─── Rekap transaksi per metode (dari kolom payment_method di transactions) ───
$rekap_metode = [];
$check = $conn->query("SHOW COLUMNS FROM transactions LIKE 'payment_method'");
if ($check && $check->num_rows > 0) {
    $rq = $conn->query("SELECT COALESCE(payment_method,'Cash') AS met, COUNT(*) AS jml, COALESCE(SUM(total_bayar),0) AS tot FROM transactions WHERE status='completed' AND DATE(end_time)=CURDATE() GROUP BY payment_method");
    while ($row = $rq->fetch_assoc()) {
        $rekap_metode[$row['met']] = ['jml'=>$row['jml'], 'tot'=>$row['tot']];
    }
}
?>

<style>
.pay-wrap { display:flex; flex-direction:column; gap:28px; max-width:960px; }
.pay-card { background:var(--card-bg); border:1px solid var(--border); border-radius:20px; padding:32px; }
.pay-card h3 { font-size:1.1rem; font-weight:800; color:#fff; display:flex; align-items:center; gap:10px; margin-bottom:22px; }
.pay-card h3 i { color:var(--primary); font-size:1.4rem; }

.method-grid { display:grid; grid-template-columns:repeat(auto-fill,minmax(260px,1fr)); gap:16px; }
.method-item {
    background:#0f172a;
    border:1px solid var(--border);
    border-radius:16px;
    padding:20px;
    display:flex;
    align-items:flex-start;
    gap:14px;
    transition:.3s;
    position:relative;
}
.method-item.aktif { border-color:rgba(6,182,212,.35); background:rgba(6,182,212,.04); }
.method-item:hover { border-color:var(--primary); }
.method-icon {
    width:48px; height:48px; border-radius:12px;
    background:linear-gradient(135deg,rgba(6,182,212,.2),rgba(139,92,246,.2));
    display:flex; align-items:center; justify-content:center;
    font-size:1.5rem; color:var(--primary); min-width:48px;
}
.method-info { flex:1; }
.method-name { font-weight:800; font-size:.95rem; color:#fff; margin-bottom:3px; }
.method-ket { font-size:.78rem; color:var(--text-muted); }
.method-toggle { position:absolute; top:14px; right:14px; }

.toggle-sw { position:relative; display:inline-block; width:44px; height:24px; }
.toggle-sw input { opacity:0; width:0; height:0; }
.slider-sw {
    position:absolute; cursor:pointer; top:0; left:0; right:0; bottom:0;
    background:#334155; border-radius:24px; transition:.3s;
}
.slider-sw:before {
    content:''; position:absolute; height:18px; width:18px; left:3px; bottom:3px;
    background:#fff; border-radius:50%; transition:.3s;
}
input:checked + .slider-sw { background:var(--primary); }
input:checked + .slider-sw:before { transform:translateX(20px); }

.badge-ok { background:rgba(16,185,129,.15); color:#10b981; padding:6px 14px; border-radius:8px; font-size:.82rem; font-weight:700; display:inline-flex; align-items:center; gap:6px; margin-bottom:16px; }

.rekap-table { width:100%; border-collapse:collapse; }
.rekap-table th { text-align:left; padding:12px 16px; font-size:.75rem; text-transform:uppercase; color:var(--text-muted); font-weight:700; border-bottom:1px solid var(--border); }
.rekap-table td { padding:14px 16px; font-size:.9rem; border-bottom:1px solid rgba(255,255,255,.04); }
.rekap-table tr:last-child td { border-bottom:none; }
.rekap-table tr:hover td { background:rgba(6,182,212,.04); }

.add-form-row { display:flex; gap:12px; align-items:center; flex-wrap:wrap; }
.add-form-row input { flex:1; min-width:160px; }
.btn-del { background:rgba(239,68,68,.12)!important; color:#ef4444!important; border:1px solid rgba(239,68,68,.2)!important; padding:6px 12px!important; font-size:.75rem!important; border-radius:8px!important; }
.btn-del:hover { background:rgba(239,68,68,.25)!important; }

.status-badge { display:inline-block; padding:4px 10px; border-radius:6px; font-size:.72rem; font-weight:700; }
.status-aktif { background:rgba(16,185,129,.15); color:#10b981; }
.status-nonaktif { background:rgba(100,116,139,.15); color:#64748b; }
</style>

<div class="pay-wrap">

<?php if (!empty($save_ok)): ?>
<div class="badge-ok"><i class='bx bx-check-circle'></i> Pengaturan berhasil disimpan!</div>
<?php endif; ?>

<!-- CARD: Metode Pembayaran -->
<div class="pay-card">
    <h3><i class='bx bx-credit-card-alt'></i> Metode Pembayaran Tersedia</h3>

    <form method="POST" id="form-methods">
        <input type="hidden" name="save_methods" value="1">
        <div class="method-grid" id="method-grid">
            <?php foreach ($metode_list as $m): ?>
            <div class="method-item <?= $m['aktif'] ? 'aktif' : '' ?>" id="item-<?= $m['id'] ?>">
                <div class="method-icon"><i class='bx <?= htmlspecialchars($m['icon']) ?>'></i></div>
                <div class="method-info">
                    <div class="method-name"><?= htmlspecialchars($m['nama']) ?></div>
                    <div class="method-ket"><?= htmlspecialchars($m['ket']) ?></div>
                    <div style="margin-top:8px;">
                        <span class="status-badge <?= $m['aktif'] ? 'status-aktif' : 'status-nonaktif' ?>">
                            <?= $m['aktif'] ? 'Aktif' : 'Nonaktif' ?>
                        </span>
                    </div>
                </div>
                <div class="method-toggle">
                    <label class="toggle-sw">
                        <input type="checkbox" name="aktif[]" value="<?= $m['id'] ?>"
                            <?= $m['aktif'] ? 'checked' : '' ?>
                            onchange="updateItem(this, <?= $m['id'] ?>)">
                        <span class="slider-sw"></span>
                    </label>
                </div>
            </div>
            <?php endforeach; ?>
        </div>
        <div style="margin-top:20px;">
            <button type="submit" class="btn btn-primary"><i class='bx bx-save'></i> Simpan Perubahan</button>
        </div>
    </form>
</div>

<!-- CARD: Tambah Metode Baru -->
<div class="pay-card">
    <h3><i class='bx bx-plus-circle'></i> Tambah Metode Pembayaran</h3>
    <form method="POST">
        <input type="hidden" name="add_method" value="1">
        <div class="add-form-row">
            <input type="text" name="nama_baru" placeholder="Nama metode (contoh: E-Money)" required>
            <input type="text" name="ket_baru" placeholder="Keterangan (opsional)">
            <button type="submit" class="btn btn-primary"><i class='bx bx-plus'></i> Tambah</button>
        </div>
    </form>

    <?php if (count($metode_list) > 0): ?>
    <div style="margin-top:24px;border-top:1px solid var(--border);padding-top:20px;">
        <div style="font-size:.82rem;color:var(--text-muted);font-weight:700;text-transform:uppercase;margin-bottom:14px;">Hapus Metode</div>
        <div style="display:flex;flex-wrap:wrap;gap:10px;">
            <?php foreach ($metode_list as $m): ?>
            <form method="POST" style="display:inline;" onsubmit="return confirm('Hapus metode <?= htmlspecialchars(addslashes($m['nama'])) ?>?')">
                <input type="hidden" name="hapus_id" value="<?= $m['id'] ?>">
                <button type="submit" class="btn btn-del"><i class='bx bx-trash'></i> <?= htmlspecialchars($m['nama']) ?></button>
            </form>
            <?php endforeach; ?>
        </div>
    </div>
    <?php endif; ?>
</div>

<!-- CARD: Rekap Pembayaran Hari Ini -->
<div class="pay-card">
    <h3><i class='bx bx-bar-chart-alt-2'></i> Rekap Pembayaran Hari Ini</h3>
    <?php if (!empty($rekap_metode)): ?>
    <table class="rekap-table">
        <thead>
            <tr>
                <th>Metode Pembayaran</th>
                <th>Jumlah Transaksi</th>
                <th>Total Pendapatan</th>
            </tr>
        </thead>
        <tbody>
            <?php
            $total_all_jml = 0;
            $total_all_tot = 0;
            foreach ($rekap_metode as $met => $data):
                $total_all_jml += $data['jml'];
                $total_all_tot += $data['tot'];
            ?>
            <tr>
                <td><strong><?= htmlspecialchars($met) ?></strong></td>
                <td><?= $data['jml'] ?> transaksi</td>
                <td style="color:var(--primary);font-weight:700;">Rp <?= number_format($data['tot'], 0, ',', '.') ?></td>
            </tr>
            <?php endforeach; ?>
            <tr style="border-top:2px solid var(--border);">
                <td style="font-weight:800;color:#fff;">TOTAL</td>
                <td style="font-weight:700;"><?= $total_all_jml ?> transaksi</td>
                <td style="color:#10b981;font-weight:800;">Rp <?= number_format($total_all_tot, 0, ',', '.') ?></td>
            </tr>
        </tbody>
    </table>
    <?php else: ?>
    <div style="text-align:center;padding:40px;color:var(--text-muted);">
        <i class='bx bx-receipt' style="font-size:3rem;display:block;margin-bottom:10px;"></i>
        Belum ada transaksi hari ini atau kolom <code>payment_method</code> belum tersedia di tabel transactions.
        <br><small style="margin-top:8px;display:block;">Kolom ini akan terisi otomatis saat proses billing dilakukan.</small>
    </div>
    <?php endif; ?>
</div>

</div>

<script>
function updateItem(cb, id) {
    const item = document.getElementById('item-' + id);
    const badge = item.querySelector('.status-badge');
    if (cb.checked) {
        item.classList.add('aktif');
        badge.className = 'status-badge status-aktif';
        badge.textContent = 'Aktif';
    } else {
        item.classList.remove('aktif');
        badge.className = 'status-badge status-nonaktif';
        badge.textContent = 'Nonaktif';
    }
}
</script>
