<?= $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:400px 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); }
    table thead th { background:var(--bg-card2); 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:14px 16px; border-bottom:1px solid var(--border); color:#334155; font-size:14px; }
    .badge-status { padding:4px 10px; border-radius:20px; font-size:11px; font-weight:700; text-transform:uppercase; }
    .badge-aktif { background:var(--accent-soft); 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; }
    .btn-toggle:hover { border-color:var(--accent); color:var(--accent); background:var(--accent-soft); }
    .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; }
    .link-reseller { color:var(--accent); font-size:12px; text-decoration:none; }
    .link-reseller:hover { text-decoration:underline; }

    /* Product + harga row */
    .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; }
    .harga-input { width:130px; padding:6px 10px; border:1px solid var(--border); border-radius:8px; font-size:13px; background:#fff; display:none; }
    .harga-input.visible { display:block; }
    .harga-badge { display:inline-flex; align-items:center; gap:4px; font-size:10px; font-weight:600; padding:3px 8px; border-radius:6px; background:var(--accent-soft); color:var(--accent); }
</style>
<?= $this->endSection() ?>

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

<div class="page-header">
    <div class="page-title"><i class="bi bi-people-fill"></i> Master Reseller</div>
</div>

<?php if(session()->getFlashdata('success')): ?>
    <div class="alert alert-success border-0 shadow-sm mb-4" style="border-radius:12px">
        <?= 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">
        <?= session()->getFlashdata('error') ?>
    </div>
<?php endif; ?>
<?php if(session('errors')): ?>
    <div class="alert alert-danger border-0 shadow-sm mb-4" style="border-radius:12px">
        <ul class="mb-0">
            <?php foreach(session('errors') as $e): ?>
                <li><?= esc($e) ?></li>
            <?php endforeach; ?>
        </ul>
    </div>
<?php endif; ?>

<div class="grid">
    <!-- FORM -->
    <div class="card">
        <h2 id="form-title">Tambah Reseller</h2>
        <form action="<?= base_url('/master/reseller/store') ?>" method="post" id="form-reseller">
            <input type="hidden" name="id_reseller" id="reseller-id">

            <div class="form-group">
                <label>Nama Reseller</label>
                <input type="text" name="nama_reseller" id="nama_reseller"
                       class="form-control" placeholder="Contoh: Budi Store" required>
            </div>

            <div class="form-group">
                <label>Nomor WhatsApp</label>
                <input type="text" name="no_hp_reseller" id="no_hp_reseller"
                       class="form-control" placeholder="0812xxxx">
            </div>

            <div class="form-group">
                <label>Link Toko / Profil</label>
                <input type="url" name="link_reseller" id="link_reseller"
                       class="form-control" placeholder="https://shopee.co.id/...">
            </div>

            <div class="form-group">
                <label>Alamat Lengkap</label>
                <textarea name="alamat_reseller" id="alamat_reseller"
                          class="form-control" rows="2" placeholder="Alamat pengiriman..."></textarea>
            </div>

            <div class="form-group">
                <label>Produk & Harga Khusus</label>
                <div style="max-height:240px; overflow-y:auto; border:1px solid var(--border); border-radius:10px; padding:8px; background:#fff;">
                    <?php foreach($products as $p): ?>
                    <div class="product-row">
                        <div class="form-check flex-grow-1">
                            <input class="form-check-input product-cb"
                                   type="checkbox"
                                   name="product_ids[]"
                                   value="<?= $p['id_produk'] ?>"
                                   id="p-<?= $p['id_produk'] ?>"
                                   onchange="toggleHarga(this)">
                            <label class="form-check-label" for="p-<?= $p['id_produk'] ?>">
                                <?= esc($p['nama_produk']) ?>
                                <span style="color:var(--text-muted); font-size:11px">
                                    — Rp <?= number_format($p['harga_produk'], 0, ',', '.') ?>
                                </span>
                            </label>
                        </div>
                        <input type="number"
                               class="harga-input"
                               id="harga-<?= $p['id_produk'] ?>"
                               name="harga_produk[<?= $p['id_produk'] ?>]"
                               placeholder="Harga khusus"
                               min="0">
                    </div>
                    <?php endforeach; ?>
                </div>
                <small class="text-muted" style="font-size:11px">Centang produk lalu isi harga khusus untuk reseller ini.</small>
            </div>

            <button type="submit" class="btn btn-primary w-100 py-2 shadow-sm"
                    style="border-radius:10px; font-weight:700">Simpan Data Reseller</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()">Batal Edit</button>
        </form>
    </div>

    <!-- TABEL -->
    <div class="card">
        <h2>Daftar Reseller Terdaftar</h2>
        <div class="table-responsive">
            <table class="w-100">
                <thead>
                    <tr>
                        <th>Reseller</th>
                        <th>WhatsApp</th>
                        <th>Link</th>
                        <th>Produk & Harga Khusus</th>
                        <th>Status</th>
                        <th class="text-end">Aksi</th>
                    </tr>
                </thead>
                <tbody>
                    <?php if(empty($resellers)): ?>
                        <tr><td colspan="7" class="text-center py-4 text-muted">Belum ada data.</td></tr>
                    <?php endif; ?>
                    <?php foreach($resellers as $r): ?>
                    <tr>
                        <td>
                            <div style="font-weight:600; color:var(--text-main)"><?= esc($r['nama_reseller']) ?></div>
                            <div style="font-size:12px; color:var(--text-muted)"><?= esc($r['alamat_reseller']) ?: '-' ?></div>
                        </td>
                        <td><?= esc($r['no_hp_reseller']) ?: '-' ?></td>
                        <td>
                            <?php if(!empty($r['link_reseller'])): ?>
                                <a href="<?= esc($r['link_reseller']) ?>" target="_blank" class="link-reseller">
                                    <i class="bi bi-box-arrow-up-right"></i> Buka
                                </a>
                            <?php else: ?>
                                <span class="text-muted small">-</span>
                            <?php endif; ?>
                        </td>
                        <td>
                            <?php if(!empty($r['product_names'])): ?>
                                <div style="display:flex; flex-direction:column; gap:4px">
                                    <?php foreach($r['product_ids'] as $pid):
                                        $pName  = $r['product_names'][array_search($pid, $r['product_ids'])] ?? 'Unknown';
                                        $harga  = $r['harga_khusus'][$pid] ?? null;
                                    ?>
                                        <div style="display:flex; align-items:center; gap:6px; flex-wrap:wrap">
                                            <span style="font-size:12px; color:var(--text-main)"><?= esc($pName) ?></span>
                                            <?php if($harga): ?>
                                                <span class="harga-badge">
                                                    Rp <?= number_format($harga, 0, ',', '.') ?>
                                                </span>
                                            <?php else: ?>
                                                <span style="font-size:11px; color:var(--text-muted)">harga default</span>
                                            <?php endif; ?>
                                        </div>
                                    <?php endforeach; ?>
                                </div>
                            <?php else: ?>
                                <span class="text-muted small">Semua Produk</span>
                            <?php endif; ?>
                        </td>
                        <td>
                            <span class="badge-status <?= $r['status_reseller'] === 'Aktif' ? 'badge-aktif' : 'badge-non' ?>">
                                <?= $r['status_reseller'] ?>
                            </span>
                        </td>
                        <td class="text-end">
                            <button class="btn-toggle"
                                    onclick="editData(<?= htmlspecialchars(json_encode($r)) ?>)">
                                <i class="bi bi-pencil"></i>
                            </button>
                            <form action="<?= base_url('/master/reseller/toggle/' . $r['id_reseller']) ?>"
                                  method="post" style="display:inline">
                                <button type="submit" class="btn-toggle" title="Ubah Status">
                                    <i class="bi bi-power"></i>
                                </button>
                            </form>
                        </td>
                    </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>
    </div>
</div>

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

<?= $this->section('js') ?>
<script>
function toggleHarga(cb) {
    const hargaInput = document.getElementById('harga-' + cb.value);
    if (hargaInput) {
        hargaInput.classList.toggle('visible', cb.checked);
        if (!cb.checked) hargaInput.value = '';
    }
}

function editData(data) {
    document.getElementById('form-title').innerText             = 'Edit Reseller';
    document.getElementById('reseller-id').value                = data.id_reseller;
    document.getElementById('nama_reseller').value              = data.nama_reseller;
    document.getElementById('no_hp_reseller').value             = data.no_hp_reseller  ?? '';
    document.getElementById('link_reseller').value              = data.link_reseller   ?? '';
    document.getElementById('alamat_reseller').value            = data.alamat_reseller ?? '';

    // Reset semua checkbox & harga
    document.querySelectorAll('.product-cb').forEach(cb => {
        cb.checked = false;
        const h = document.getElementById('harga-' + cb.value);
        if (h) { h.classList.remove('visible'); h.value = ''; }
    });

    // Set produk terpilih + harga khusus
    if (data.product_ids) {
        data.product_ids.forEach(pid => {
            const cb = document.getElementById('p-' + pid);
            if (cb) {
                cb.checked = true;
                const h = document.getElementById('harga-' + pid);
                if (h) {
                    h.classList.add('visible');
                    h.value = data.harga_khusus && data.harga_khusus[pid] ? data.harga_khusus[pid] : '';
                }
            }
        });
    }

    document.getElementById('btn-cancel').style.display = 'block';
    window.scrollTo({ top: 0, behavior: 'smooth' });
}

function resetForm() {
    document.getElementById('form-title').innerText = 'Tambah Reseller';
    document.getElementById('form-reseller').reset();
    document.querySelectorAll('.product-cb').forEach(cb => {
        cb.checked = false;
        const h = document.getElementById('harga-' + cb.value);
        if (h) { h.classList.remove('visible'); h.value = ''; }
    });
    document.getElementById('reseller-id').value        = '';
    document.getElementById('btn-cancel').style.display = 'none';
}
</script>
<?= $this->endSection() ?>