<?= $this->extend('layouts/main') ?>
<?= $this->section('head_extra') ?>
<style>
.stats-card { border-radius: .75rem; padding: 1rem 1.25rem; }
.import-drop { border: 2px dashed #cbd5e1; border-radius: .5rem; padding: 1.5rem; text-align:center; cursor:pointer; transition:.2s; }
.import-drop:hover { border-color: #3b82f6; background: #eff6ff; }
.dual-section { border: 1px solid #e2e8f0; border-radius: .75rem; margin-top:1.5rem; }
.dual-section-header { background: #f8fafc; padding: .75rem 1rem; border-bottom: 1px solid #e2e8f0; border-radius: .75rem .75rem 0 0; font-weight:600; }
.table-sm td, .table-sm th { padding: .35rem .5rem; }
.edit-cell input { width:100%; border:1px solid #3b82f6; border-radius:.25rem; padding:.15rem .4rem; font-size:.8rem; }
</style>
<?= $this->endSection() ?>

<?= $this->section('content') ?>
<?php
$catKey  = $catKey ?? 'edc';
$cat     = $cat    ?? [];
$isDual  = $isDual ?? false;
$subKeys = $subKeys ?? [];
$dispCols= $dispCols ?? [];
$isAdmin = $isAdmin ?? false;
?>

<!-- Header row -->
<div class="d-flex flex-wrap align-items-center gap-2 mb-3">
    <h5 class="mb-0 fw-bold flex-grow-1">
        <?= esc($cat['group'] ? $cat['group'] . ' — ' . $cat['label'] : $cat['label']) ?>
    </h5>
    <a href="<?= base_url('dashboard/export?cat=' . $catKey) ?>" class="btn btn-sm btn-outline-success">
        <i class="bi bi-file-earmark-excel me-1"></i> Export Excel
    </a>
    <?php if ($isAdmin): ?>
    <button class="btn btn-sm btn-outline-primary" onclick="$('#importModal').modal('show')">
        <i class="bi bi-upload me-1"></i> Import Excel
    </button>
    <button class="btn btn-sm btn-outline-danger" onclick="confirmDeleteAll()">
        <i class="bi bi-trash3 me-1"></i> Hapus Semua
    </button>
    <?php endif; ?>
</div>

<!-- Stats -->
<div class="row g-2 mb-3" id="statsRow">
    <div class="col-auto">
        <div class="stats-card bg-white border d-inline-flex align-items-center gap-2">
            <div style="width:36px;height:36px;background:#dbeafe;border-radius:.5rem;display:flex;align-items:center;justify-content:center;">
                <i class="bi bi-table text-primary"></i>
            </div>
            <div>
                <div class="text-muted" style="font-size:.7rem;font-weight:600;text-transform:uppercase;">Total Data</div>
                <div class="fw-bold fs-5" id="statTotal">–</div>
            </div>
        </div>
    </div>
</div>

<!-- Main DataTable -->
<div class="card">
    <div class="card-body p-0">
        <table id="mainTable" class="table table-hover table-sm align-middle mb-0 w-100">
            <thead class="table-light">
                <tr>
                    <th style="width:50px">ID</th>
                    <?php foreach ($dispCols as $col): ?>
                    <th><?= esc($col['label']) ?></th>
                    <?php endforeach; ?>
                    <?php if ($isAdmin): ?>
                    <th style="width:70px">Aksi</th>
                    <?php endif; ?>
                </tr>
            </thead>
        </table>
    </div>
</div>

<?php if ($isDual): ?>
<!-- Dual sub-tables (penurunan / kenaikan) -->
<?php
use App\Libraries\Categories;
$dualSubCats = array_map(fn($k) => Categories::resolve($k), $subKeys);
$dualLabels  = ['Penurunan', 'Kenaikan'];
foreach ($dualSubCats as $si => $sub):
    if (!$sub) continue;
    $subDispCols = Categories::getDisplayColumns($sub);
?>
<div class="dual-section">
    <div class="dual-section-header d-flex align-items-center justify-content-between">
        <span><i class="bi bi-table me-1 text-primary"></i> <?= esc($dualLabels[$si] ?? $sub['label']) ?></span>
        <div class="d-flex gap-2">
            <a href="<?= base_url('dashboard/export?cat=' . $sub['key']) ?>" class="btn btn-sm btn-outline-success py-0">
                <i class="bi bi-file-earmark-excel"></i> Export
            </a>
            <?php if ($isAdmin): ?>
            <button class="btn btn-sm btn-outline-primary py-0" onclick="openDualImport('<?= $sub['key'] ?>')">
                <i class="bi bi-upload"></i> Import
            </button>
            <button class="btn btn-sm btn-outline-danger py-0" onclick="confirmDeleteAll('<?= $sub['key'] ?>')">
                <i class="bi bi-trash3"></i> Hapus
            </button>
            <?php endif; ?>
        </div>
    </div>
    <div class="p-0">
        <div class="table-responsive">
            <table id="subTable_<?= $si ?>" class="table table-hover table-sm align-middle mb-0 w-100"
                data-cat="<?= $sub['key'] ?>">
                <thead class="table-light">
                    <tr>
                        <th>ID</th>
                        <?php foreach ($subDispCols as $sc): ?><th><?= esc($sc['label']) ?></th><?php endforeach; ?>
                        <?php if ($isAdmin): ?>
                        <th style="width:80px">Aksi</th>
                        <?php endif; ?>
                    </tr>
                </thead>
            </table>
        </div>
    </div>
</div>
<?php endforeach; ?>
<?php endif; ?>

<!-- Import Modal -->
<?php if ($isAdmin): ?>
<div class="modal fade" id="importModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">Import Excel</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <input type="hidden" id="importCat" value="<?= $catKey ?>">
                <div class="import-drop" id="importDrop" onclick="document.getElementById('importFile').click()">
                    <i class="bi bi-file-earmark-excel fs-2 text-success mb-2 d-block"></i>
                    <p class="mb-1 fw-semibold">Klik atau seret file Excel di sini</p>
                    <p class="text-muted small mb-0">Hanya file <strong>.xlsx</strong> yang didukung</p>
                </div>
                <input type="file" id="importFile" accept=".xlsx" class="d-none" onchange="handleFileSelect(this)">
                <div id="selectedFileName" class="mt-2 text-muted small"></div>
                <div class="mt-2 text-muted" style="font-size:.78rem;">
                    <i class="bi bi-info-circle me-1"></i>
                    Baris header akan dideteksi otomatis. Hanya <strong>.xlsx</strong> yang didukung (bukan .xls).
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Batal</button>
                <button type="button" class="btn btn-primary" id="doImportBtn" onclick="doImport()" disabled>
                    <i class="bi bi-upload me-1"></i> Import
                </button>
            </div>
        </div>
    </div>
</div>
<?php endif; ?>

<!-- Edit Row Modal (for dual tables) -->
<?php if ($isAdmin && $isDual): ?>
<div class="modal fade" id="editRowModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">Edit Baris</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body" id="editRowBody"></div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Batal</button>
                <button type="button" class="btn btn-primary" onclick="saveRow()">Simpan</button>
            </div>
        </div>
    </div>
</div>
<?php endif; ?>

<?= $this->endSection() ?>
<?= $this->section('scripts') ?>
<script>
const CAT_KEY   = '<?= $catKey ?>';
const IS_ADMIN  = <?= $isAdmin ? 'true' : 'false' ?>;
const IS_DUAL   = <?= $isDual  ? 'true' : 'false' ?>;
const SUB_KEYS  = <?= json_encode($subKeys) ?>;
var dtMain, dtSubs = {}, editRowCat, editRowId;

// Column defs for main table
const MAIN_COLS = [
    { data: 'id', title: 'ID' },
    <?php foreach ($dispCols as $col): ?>
    { data: <?= json_encode($col['field']) ?>, title: <?= json_encode($col['label']) ?>, defaultContent: '' },
    <?php endforeach; ?>
];
if (IS_ADMIN) {
    MAIN_COLS.push({ data: null, title: 'Aksi', orderable: false, searchable: false, render: function(d,t,r) {
        return `<button class="btn btn-sm btn-outline-danger py-0 px-1" onclick="deleteRow('${CAT_KEY}',${r.id})"><i class="bi bi-trash" style="font-size:.7rem"></i></button>`;
    }});
}

// Sub-table column defs
const SUB_COL_DEFS = <?php
    $subColDefs = [];
    foreach ($subKeys as $si => $sk) {
        $sub = Categories::resolve($sk);
        if (!$sub) { $subColDefs[$si] = []; continue; }
        $sc = Categories::getDisplayColumns($sub);
        $subColDefs[$si] = array_map(fn($c) => ['data' => $c['field'], 'title' => $c['label']], $sc);
    }
    echo json_encode($subColDefs);
?>;

// -----------------------------------------------------------------------
// Init datatables
// -----------------------------------------------------------------------
$(function() {
    dtMain = initDT('mainTable', CAT_KEY, MAIN_COLS, false);
    loadStats(CAT_KEY);

    if (IS_DUAL) {
        SUB_KEYS.forEach(function(sk, si) {
            var cols = (SUB_COL_DEFS[si] || []).map(c => ({...c, defaultContent:''}));
            cols.unshift({ data: 'id', title: 'ID' });
            if (IS_ADMIN) {
                cols.push({ data: null, title: 'Aksi', orderable: false, searchable: false,
                    render: function(d,t,r) {
                        return `<button class="btn btn-sm btn-outline-primary py-0 px-1 me-1" onclick="openEditRow('${sk}',${r.id},'${si}')"><i class="bi bi-pencil" style="font-size:.7rem"></i></button>`
                             + `<button class="btn btn-sm btn-outline-danger py-0 px-1" onclick="deleteRow('${sk}',${r.id})"><i class="bi bi-trash" style="font-size:.7rem"></i></button>`;
                    }
                });
            }
            dtSubs[si] = initDT('subTable_'+si, sk, cols, true);
        });
    }
});

function initDT(tableId, catKey, cols, isSmall) {
    return $('#' + tableId).DataTable({
        processing: true, serverSide: true,
        ajax: {
            url: BASE_URL + 'dashboard/list', type: 'POST',
            data: function(d) { d.cat = catKey; d[csrfToken()] = csrfHash(); }
        },
        columns: cols,
        order: [[0, 'desc']],
        pageLength: 25,
        scrollX: true,
        language: {
            processing: 'Memuat data...', search: 'Cari:',
            lengthMenu: 'Tampilkan _MENU_ baris',
            info: 'Menampilkan _START_–_END_ dari _TOTAL_ baris',
            infoEmpty: 'Tidak ada data',
            infoFiltered: '(difilter dari _MAX_ total)',
            paginate: { first:'«', last:'»', previous:'‹', next:'›' }
        },
        drawCallback: function() {
            if (!isSmall) loadStats(catKey);
        }
    });
}

function loadStats(catKey) {
    $.get(BASE_URL + 'dashboard/stats?cat=' + catKey, function(r) {
        if (r.success) {
            document.getElementById('statTotal').textContent = Number(r.data.total).toLocaleString('id-ID');
        }
    });
}

// -----------------------------------------------------------------------
// Delete row
// -----------------------------------------------------------------------
function deleteRow(cat, id) {
    Swal.fire({
        title: 'Hapus baris?', text: 'Baris ID ' + id + ' akan dihapus.',
        icon: 'warning', showCancelButton: true,
        confirmButtonColor: '#ef4444', confirmButtonText: 'Ya, Hapus', cancelButtonText: 'Batal'
    }).then(r => {
        if (r.isConfirmed) {
            postData('dashboard/delete-row', {cat, id}, function() {
                Swal.fire({icon:'success', title:'Terhapus', timer:1000, showConfirmButton:false});
                if (cat === CAT_KEY && dtMain) dtMain.draw(false);
                Object.values(dtSubs).forEach(dt => dt.draw(false));
            });
        }
    });
}

// -----------------------------------------------------------------------
// Delete all
// -----------------------------------------------------------------------
function confirmDeleteAll(cat) {
    const c = cat || CAT_KEY;
    Swal.fire({
        title: 'Hapus Semua Data?', html: '<b>Seluruh data</b> pada tabel ini akan dihapus permanen.<br>Proses ini tidak dapat dibatalkan.',
        icon: 'warning', showCancelButton: true,
        confirmButtonColor: '#ef4444', confirmButtonText: 'Ya, Hapus Semua', cancelButtonText: 'Batal',
        input: 'text', inputPlaceholder: 'Ketik HAPUS untuk konfirmasi',
        preConfirm: (val) => { if (val !== 'HAPUS') { Swal.showValidationMessage('Ketik HAPUS untuk melanjutkan'); return false; } }
    }).then(r => {
        if (r.isConfirmed) {
            postData('dashboard/delete-all', {cat: c}, function() {
                Swal.fire({icon:'success', title:'Data dihapus', timer:1200, showConfirmButton:false});
                if (c === CAT_KEY && dtMain) dtMain.draw(false);
                Object.values(dtSubs).forEach(dt => dt.draw(false));
            });
        }
    });
}

// -----------------------------------------------------------------------
// Edit row (dual tables)
// -----------------------------------------------------------------------
var editRowFields = [];

function openEditRow(catKey, id, si) {
    editRowCat = catKey;
    editRowId  = id;
    const cols = SUB_COL_DEFS[si] || [];
    // Fetch current row data
    $.ajax({
        url: BASE_URL + 'dashboard/list', type: 'POST',
        data: { cat: catKey, draw: 1, start: 0, length: 1, 'search[value]': '', 'order[0][column]': 0, 'order[0][dir]': 'asc', [csrfToken()]: csrfHash() },
        success: function(r) {
            const row = r.data ? r.data.find(d => d.id == id) : null;
            let html = '';
            cols.forEach(function(c) {
                const val = row ? (row[c.data] || '') : '';
                html += `<div class="mb-2">
                    <label class="form-label fw-semibold mb-1" style="font-size:.8rem">${c.title}</label>
                    <input type="text" class="form-control form-control-sm" name="${c.data}" value="${String(val).replace(/"/g,'&quot;')}">
                </div>`;
            });
            document.getElementById('editRowBody').innerHTML = html;
            editRowFields = cols.map(c => c.data);
            new bootstrap.Modal(document.getElementById('editRowModal')).show();
        }
    });
}

function saveRow() {
    const inputs = document.querySelectorAll('#editRowBody input[name]');
    const fields = {};
    inputs.forEach(inp => { fields[inp.name] = inp.value; });

    postData('dashboard/update-row', { cat: editRowCat, id: editRowId, fields: fields }, function() {
        Swal.fire({icon:'success', title:'Berhasil', text:'Baris diperbarui.', timer:1200, showConfirmButton:false});
        bootstrap.Modal.getInstance(document.getElementById('editRowModal')).hide();
        Object.values(dtSubs).forEach(dt => dt.draw(false));
    });
}

// -----------------------------------------------------------------------
// Import
// -----------------------------------------------------------------------
var importFile = null;

function openDualImport(catKey) {
    document.getElementById('importCat').value = catKey;
    document.getElementById('selectedFileName').textContent = '';
    document.getElementById('doImportBtn').disabled = true;
    importFile = null;
    const fileInput = document.getElementById('importFile');
    if (fileInput) fileInput.value = '';
    new bootstrap.Modal(document.getElementById('importModal')).show();
}

function handleFileSelect(input) {
    if (input.files && input.files[0]) {
        importFile = input.files[0];
        document.getElementById('selectedFileName').innerHTML =
            '<i class="bi bi-file-earmark-excel text-success me-1"></i> ' +
            '<strong>' + importFile.name + '</strong> (' + (importFile.size/1024).toFixed(1) + ' KB)';
        document.getElementById('doImportBtn').disabled = false;
    }
}

function doImport() {
    if (!importFile) { Swal.fire('Perhatian', 'Pilih file Excel (.xlsx) terlebih dahulu.', 'warning'); return; }
    const cat = document.getElementById('importCat').value;

    const btn = document.getElementById('doImportBtn');
    btn.disabled = true;
    btn.innerHTML = '<span class="spinner-border spinner-border-sm me-1"></span> Mengimpor...';

    const fd = new FormData();
    fd.append('file', importFile);
    fd.append('cat', cat);
    fd.append(csrfToken(), csrfHash());

    $.ajax({
        url: BASE_URL + 'dashboard/import', type: 'POST',
        data: fd, processData: false, contentType: false,
        success: function(r) {
            btn.disabled = false;
            btn.innerHTML = '<i class="bi bi-upload me-1"></i> Import';
            if (r && r.success) {
                Swal.fire({
                    icon:'success', title:'Import Berhasil',
                    text: 'Berhasil mengimpor ' + r.imported + ' baris data.',
                    timer: 2000, showConfirmButton: false
                });
                bootstrap.Modal.getInstance(document.getElementById('importModal')).hide();
                if (cat === CAT_KEY && dtMain) dtMain.draw(false);
                Object.values(dtSubs).forEach(dt => dt.draw(false));
            } else {
                Swal.fire('Gagal', (r && r.message) ? r.message : 'Import gagal.', 'error');
            }
        },
        error: function(xhr) {
            btn.disabled = false;
            btn.innerHTML = '<i class="bi bi-upload me-1"></i> Import';
            const r = xhr.responseJSON;
            Swal.fire('Error', (r && r.message) ? r.message : 'Request gagal.', 'error');
        }
    });
}

// Drag & drop
$(function() {
    const drop = document.getElementById('importDrop');
    if (!drop) return;
    drop.addEventListener('dragover', function(e) { e.preventDefault(); drop.style.borderColor='#3b82f6'; });
    drop.addEventListener('dragleave', function() { drop.style.borderColor=''; });
    drop.addEventListener('drop', function(e) {
        e.preventDefault(); drop.style.borderColor='';
        const f = e.dataTransfer.files[0];
        if (f) { document.getElementById('importFile').files; handleFileSelect({files:[f]}); }
    });
});
</script>
<?= $this->endSection() ?>
