<?= $this->extend('layouts/main') ?>

<?= $this->section('css') ?>
<style>
    .page-header { display:flex; align-items:center; justify-content:space-between; margin-bottom:28px; }
    .page-title  { font-size:1.4rem; font-weight:700; color:var(--text-main); display:flex; align-items:center; gap:10px; }
    .page-title i { color:var(--accent); }
    .grid { display:grid; grid-template-columns:480px 1fr; gap:24px; align-items:start; }
    @media(max-width:992px){ .grid{ grid-template-columns:1fr; } }
    .card { background:var(--bg-side); border:1px solid var(--border); border-radius:16px; padding:24px; box-shadow:var(--shadow); }
    .card h2 { font-size:1.1rem; font-weight:700; margin-bottom:20px; color:var(--text-main); }
    .form-group { margin-bottom:16px; }
    .form-group label { display:block; font-size:13px; font-weight:600; color:var(--text-muted); margin-bottom:6px; }
    .form-control { width:100%; padding:10px 14px; border:1px solid var(--border); border-radius:10px; font-size:14px; background:#fff; box-sizing:border-box; }
    .form-control:focus { outline:none; border-color:var(--accent); box-shadow:0 0 0 3px rgba(59,130,246,.12); }
    .section-title { font-size:13px; font-weight:700; margin-bottom:10px; color:var(--accent); }

    /* produk rows */
    .produk-scroll { max-height:300px; overflow-y:auto; border:1px solid var(--border); border-radius:10px; padding:6px; background:#fff; }
    .product-row { display:flex; align-items:center; gap:8px; padding:8px 10px; border-radius:8px; transition:background .15s; }
    .product-row:hover { background:#f8fafc; }
    .product-row .form-check { flex:1; margin:0; }
    .product-row .form-check-label { font-size:13px; cursor:pointer; }

    /* harga + komisi — tersembunyi sampai dicentang */
    .hk-wrap { display:none; align-items:center; gap:6px; flex-shrink:0; }
    .hk-wrap.visible { display:flex; }
    .harga-input  { width:110px; padding:6px 10px; border:1px solid var(--border); border-radius:8px; font-size:13px; background:#fff; }
    .harga-input:focus { outline:none; border-color:var(--accent); }
    .komisi-wrap  { display:flex; align-items:center; gap:3px; }
    .komisi-input { width:52px; padding:6px 8px; border:1px solid var(--border); border-radius:8px; font-size:13px; background:#fff; text-align:center; }
    .komisi-input:focus { outline:none; border-color:var(--accent); }
    .komisi-label { font-size:11px; color:var(--text-muted); }
    .pot-badge { font-size:10px; font-weight:700; padding:2px 7px; border-radius:6px; background:rgba(59,130,246,.1); color:var(--accent); white-space:nowrap; min-width:38px; text-align:center; }

    /* tabel */
    .table-responsive { overflow:auto; }
    table { border-collapse:collapse; }
    table thead th { background:#f8fafc; color:var(--text-muted); font-size:11px; text-transform:uppercase; letter-spacing:.05em; padding:12px 16px; border-bottom:1px solid var(--border); }
    table tbody td { padding:12px 16px; border-bottom:1px solid var(--border); color:#334155; font-size:14px; vertical-align:middle; }
    .badge-status { padding:4px 10px; border-radius:20px; font-size:11px; font-weight:700; text-transform:uppercase; }
    .badge-aktif  { background:rgba(59,130,246,.1); color:var(--accent); }
    .badge-non    { background:#f1f5f9; color:var(--text-muted); }
    .btn-toggle   { background:transparent; border:1px solid var(--border); color:var(--text-muted); padding:6px 10px; border-radius:8px; font-size:12px; transition:all .2s; cursor:pointer; }
    .btn-toggle:hover { border-color:var(--accent); color:var(--accent); background:rgba(59,130,246,.06); }
    .btn-danger-soft { background:transparent; border:1px solid #fecaca; color:#ef4444; padding:6px 10px; border-radius:8px; font-size:12px; transition:all .2s; cursor:pointer; }
    .btn-danger-soft:hover { background:#fee2e2; border-color:#ef4444; }
    .harga-badge { display:inline-flex; align-items:center; font-size:10px; font-weight:600; padding:3px 8px; border-radius:6px; background:rgba(59,130,246,.1); color:var(--accent); }
    .komisi-tag  { font-size:10px; color:var(--text-muted); background:#f1f5f9; padding:2px 6px; border-radius:5px; }
</style>
<?= $this->endSection() ?>

<?= $this->section('content') ?>

<div class="page-header">
    <div class="page-title">
        <i class="bi bi-cart-fill"></i>
        Master Marketplace
    </div>
</div>

<?php if(session()->getFlashdata('success')): ?>
<div class="alert alert-success border-0 shadow-sm mb-4" style="border-radius:12px">
    <i class="bi bi-check-circle me-2"></i><?= session()->getFlashdata('success') ?>
</div>
<?php endif; ?>

<?php if(session()->getFlashdata('error')): ?>
<div class="alert alert-danger border-0 shadow-sm mb-4" style="border-radius:12px">
    <i class="bi bi-exclamation-circle me-2"></i><?= session()->getFlashdata('error') ?>
</div>
<?php endif; ?>

<div class="grid">

    <!-- ===== FORM KIRI ===== -->
    <div class="card">
        <h2 id="form-title"><i class="bi bi-plus-circle me-1"></i> Tambah Marketplace</h2>

        <form action="<?= base_url('/master/marketplace/store') ?>" method="post" id="form-marketplace">
            <?= csrf_field() ?>
            <input type="hidden" name="id_marketplace" id="mp-id">

            <div class="form-group">
                <label>Nama Marketplace</label>
                <input type="text" name="nama_marketplace" id="nama_marketplace"
                       class="form-control" placeholder="Shopee / TikTok Shop" required>
            </div>

            <div class="form-group">
                <label>Kontak PIC</label>
                <input type="text" name="kontak_marketplace" id="kontak_marketplace"
                       class="form-control" placeholder="0812xxxx">
            </div>

            <div class="form-group">
                <label>Catatan</label>
                <textarea name="catatan_marketplace" id="catatan_marketplace"
                          rows="2" class="form-control" placeholder="Catatan marketplace..."></textarea>
            </div>

            <!-- PRODUK & HARGA + KOMISI PER PRODUK -->
            <div class="form-group">
                <div class="section-title">
                    <i class="bi bi-tag me-1"></i> Pilih Produk &amp; Harga Marketplace
                </div>

                <?php if(!empty($produk)): ?>

                <div class="produk-scroll">
                    <?php foreach($produk as $p): ?>
                    <div class="product-row">

                        <!-- Checkbox + nama -->
                        <div class="form-check flex-grow-1">
                            <input class="form-check-input product-cb"
                                   type="checkbox"
                                   value="<?= $p['id_produk'] ?>"
                                   id="cb-<?= $p['id_produk'] ?>"
                                   onchange="toggleHK(this)">
                            <label class="form-check-label" for="cb-<?= $p['id_produk'] ?>">
                                <?= esc($p['nama_produk']) ?>
                                <span style="color:var(--text-muted);font-size:11px">
                                    &nbsp;Rp <?= number_format($p['harga_produk'],0,',','.') ?>
                                </span>
                            </label>
                        </div>

                        <!-- Harga + Komisi (tampil saat dicentang) -->
                        <div class="hk-wrap" id="hk-<?= $p['id_produk'] ?>">
                            <input type="number"
                                   class="harga-input"
                                   id="harga-<?= $p['id_produk'] ?>"
                                   name="produk[<?= $p['id_produk'] ?>][harga]"
                                   placeholder="Harga jual"
                                   min="0" step="100"
                                   data-ecer="<?= $p['harga_produk'] ?>"
                                   oninput="dariHarga(<?= $p['id_produk'] ?>)">

                            <div class="komisi-wrap">
                                <input type="number"
                                       class="komisi-input"
                                       id="komisi-<?= $p['id_produk'] ?>"
                                       name="produk[<?= $p['id_produk'] ?>][komisi]"
                                       placeholder="0"
                                       min="0" max="100" step="any"
                                       oninput="dariKomisi(<?= $p['id_produk'] ?>, <?= $p['harga_produk'] ?>)">
                                <span class="komisi-label">%</span>
                            </div>

                            <span class="pot-badge" id="pot-<?= $p['id_produk'] ?>">—</span>
                        </div>

                    </div>
                    <?php endforeach; ?>
                </div>

                <small class="text-muted d-block mt-2" style="font-size:11px">
                    Centang produk → isi <strong>harga jual</strong> atau <strong>komisi %</strong>, yang lain otomatis terhitung.
                </small>

                <?php else: ?>
                <div class="alert alert-warning" style="border-radius:10px">
                    <i class="bi bi-exclamation-triangle me-1"></i>
                    Data produk belum tersedia. Tambahkan produk di menu Master Produk.
                </div>
                <?php endif; ?>

            </div>

            <button type="submit" class="btn btn-primary w-100 py-2 shadow-sm"
                    style="border-radius:10px;font-weight:700">
                <i class="bi bi-save me-1"></i> Simpan Marketplace
            </button>

            <button type="button" id="btn-cancel"
                    class="btn btn-light w-100 mt-2 py-2"
                    style="border-radius:10px;display:none"
                    onclick="resetForm()">
                <i class="bi bi-x-circle me-1"></i> Batal Edit
            </button>
        </form>
    </div>

    <!-- ===== TABEL KANAN ===== -->
    <div class="card">
        <h2><i class="bi bi-list-ul me-1"></i> Daftar Marketplace</h2>

        <div class="table-responsive">
            <table class="w-100">
                <thead>
                    <tr>
                        <th>ID</th>
                        <th>Marketplace</th>
                        <th>Produk &amp; Harga</th>
                        <th>Status</th>
                        <th class="text-end">Aksi</th>
                    </tr>
                </thead>
                <tbody>

                <?php if(empty($marketplaces)): ?>
                <tr>
                    <td colspan="5" class="text-center py-4 text-muted">Belum ada data marketplace</td>
                </tr>
                <?php endif; ?>

                <?php foreach($marketplaces as $m): ?>
                <tr>
                    <td style="color:var(--text-muted)">#<?= $m['id_marketplace'] ?></td>

                    <td>
                        <div style="font-weight:700"><?= esc($m['nama_marketplace']) ?></div>
                        <?php if(!empty($m['kontak_marketplace'])): ?>
                            <small style="color:#64748b"><?= esc($m['kontak_marketplace']) ?></small>
                        <?php endif; ?>
                    </td>

                    <td>
                        <?php if(!empty($m['harga_produk'])): ?>
                            <div style="display:flex;flex-direction:column;gap:4px">
                                <?php foreach($m['harga_produk'] as $hp): ?>
                                <div style="display:flex;align-items:center;gap:6px;flex-wrap:wrap">
                                    <span style="font-size:12px"><?= esc($hp['nama_produk']) ?></span>
                                    <span class="harga-badge">Rp <?= number_format($hp['harga_marketplace'],0,',','.') ?></span>
                                    <?php if(!empty($hp['komisi_produk']) && $hp['komisi_produk'] > 0): ?>
                                        <span class="komisi-tag"><?= number_format($hp['komisi_produk'],1) ?>%</span>
                                    <?php endif; ?>
                                </div>
                                <?php endforeach; ?>
                            </div>
                        <?php else: ?>
                            <span class="text-muted small">Belum ada produk</span>
                        <?php endif; ?>
                    </td>

                    <td>
                        <span class="badge-status <?= $m['status_marketplace']=='Aktif' ? 'badge-aktif' : 'badge-non' ?>">
                            <?= $m['status_marketplace'] ?>
                        </span>
                    </td>

                    <td class="text-end">
                        <button class="btn-toggle" onclick='editData(<?= json_encode($m) ?>)'>
                            <i class="bi bi-pencil"></i>
                        </button>

                        <form action="<?= base_url('/master/marketplace/toggle/'.$m['id_marketplace']) ?>"
                              method="post" style="display:inline">
                            <?= csrf_field() ?>
                            <button type="submit" class="btn-toggle" title="Ubah Status">
                                <i class="bi bi-power"></i>
                            </button>
                        </form>

                        <form action="<?= base_url('/master/marketplace/delete/'.$m['id_marketplace']) ?>"
                              method="post" style="display:inline"
                              onsubmit="return confirm('Yakin hapus marketplace ini?')">
                            <?= csrf_field() ?>
                            <button type="submit" class="btn-danger-soft">
                                <i class="bi bi-trash"></i>
                            </button>
                        </form>
                    </td>
                </tr>
                <?php endforeach; ?>

                </tbody>
            </table>
        </div>
    </div>

</div>

<?= $this->endSection() ?>

<?= $this->section('js') ?>
<script>

// Centang / uncentang produk
function toggleHK(cb) {

    const wrap   = document.getElementById('hk-' + cb.value);
    const harga  = document.getElementById('harga-' + cb.value);
    const komisi = document.getElementById('komisi-' + cb.value);
    const pot    = document.getElementById('pot-' + cb.value);

    if (cb.checked) {

        wrap.classList.add('visible');

    } else {

        wrap.classList.remove('visible');

        harga.value = '';
        komisi.value = '';
        pot.textContent = '—';
    }
}

// Input KOMISI -> hitung harga otomatis
function dariKomisi(id, hargaEcer) {

    const komisiInput = document.getElementById('komisi-' + id);
    const hargaInput  = document.getElementById('harga-' + id);

    let komisi = parseFloat(komisiInput.value);

    if (isNaN(komisi)) {
        hargaInput.value = '';
        return;
    }

    // Batas nilai
    if (komisi < 0) komisi = 0;
    if (komisi > 100) komisi = 100;

    komisiInput.value = komisi;

    const hargaMarketplace =
        Math.round(hargaEcer * (1 - komisi / 100));

    hargaInput.value = hargaMarketplace;

    updatePot(id, hargaEcer, hargaMarketplace);
}

// Input HARGA -> hitung komisi otomatis
function dariHarga(id) {

    const hargaInput   = document.getElementById('harga-' + id);
    const komisiInput  = document.getElementById('komisi-' + id);

    const hargaEcer = parseFloat(hargaInput.dataset.ecer) || 0;
    const hargaMp   = parseFloat(hargaInput.value);

    if (isNaN(hargaMp) || hargaMp <= 0 || hargaEcer <= 0) {

        komisiInput.value = '';
        return;
    }

    let komisi =
        ((hargaEcer - hargaMp) / hargaEcer) * 100;

    // Bulatkan 2 angka desimal
    komisi = Math.round(komisi * 100) / 100;

    if (komisi < 0) komisi = 0;

    komisiInput.value = komisi;

    updatePot(id, hargaEcer, hargaMp);
}

// Badge potongan
function updatePot(id, hargaEcer, hargaMp) {

    const pot = document.getElementById('pot-' + id);

    if (hargaEcer > 0 && hargaMp >= 0) {

        let persen =
            ((hargaEcer - hargaMp) / hargaEcer) * 100;

        persen = Math.round(persen);

        if (persen < 0) persen = 0;

        pot.textContent = '-' + persen + '%';

    } else {

        pot.textContent = '—';
    }
}

// Edit data marketplace
function editData(data) {

    document.getElementById('form-title').innerHTML =
        '<i class="bi bi-pencil-square me-1"></i> Edit Marketplace';

    document.getElementById('mp-id').value =
        data.id_marketplace || '';

    document.getElementById('nama_marketplace').value =
        data.nama_marketplace || '';

    document.getElementById('kontak_marketplace').value =
        data.kontak_marketplace || '';

    document.getElementById('catatan_marketplace').value =
        data.catatan_marketplace || '';

    // Reset semua produk
    document.querySelectorAll('.product-cb').forEach(function(cb) {

        cb.checked = false;

        toggleHK(cb);
    });

    // Isi produk tersimpan
    if (data.harga_produk && data.harga_produk.length) {

        data.harga_produk.forEach(function(hp) {

            const cb =
                document.getElementById('cb-' + hp.id_produk);

            if (!cb) return;

            cb.checked = true;

            toggleHK(cb);

            const hargaInp =
                document.getElementById('harga-' + hp.id_produk);

            const komisiInp =
                document.getElementById('komisi-' + hp.id_produk);

            const hargaEcer =
                parseFloat(hargaInp.dataset.ecer) || 0;

            hargaInp.value =
                hp.harga_marketplace || '';

            komisiInp.value =
                hp.komisi_produk || '';

            updatePot(
                hp.id_produk,
                hargaEcer,
                parseFloat(hp.harga_marketplace) || 0
            );
        });
    }

    document.getElementById('btn-cancel').style.display = 'block';

    window.scrollTo({
        top: 0,
        behavior: 'smooth'
    });
}

// Reset form
function resetForm() {

    document.getElementById('form-marketplace').reset();

    document.getElementById('mp-id').value = '';

    document.getElementById('btn-cancel').style.display = 'none';

    document.getElementById('form-title').innerHTML =
        '<i class="bi bi-plus-circle me-1"></i> Tambah Marketplace';

    document.querySelectorAll('.product-cb').forEach(function(cb) {

        cb.checked = false;

        toggleHK(cb);
    });
}

</script>
<?= $this->endSection() ?>