<?php
$session         = session();
$activeViewTable = $session->get('activeViewTable');
$isActiveView    = $isActiveView ?? false;
$targetTable     = $isActiveView ? $activeViewTable : $table;
$sessionTable    = $activeViewTable ?? $table;

// Cek status tombol ActiveView
$isActiveViewMode = $session->get('isActiveViewMode');
$isActiveButton   = $isActiveViewMode || ($activeViewTable === $table);
?>

<div id="crud-content">

    <!-- 🔹 Judul Tabel -->
    <div class="mb-2">
        <h4 class="fw-bold text-primary text-uppercase mb-1">
            <i class="fas <?= esc($icon ?? 'fa-database') ?> me-2"></i>
            Data <?= ucwords(str_replace('_', ' ', esc($table))) ?>
        </h4>




        <hr class="mt-3 mb-2">
    </div>


    <!-- 🔹 Dua kolom informasi (versi slim) -->
    <div class="row mb-2 align-items-stretch">
        <!-- Kolom kiri: info tentang tabel -->
        <div class="col-md-6 mb-1">
            <div class="card shadow-sm border-0 bg-light h-100">
                <div class="card-body p-1"> <!-- 🔸 padding minimal -->
                    <h6 class="card-title mb-1" style="font-size: 0.85rem;">
                        <i class="fas fa-info-circle text-primary mr-1"></i> Informasi Tabel
                    </h6>
                    <p class="card-text mb-0 text-muted" style="font-size: 0.75rem; line-height: 1;">
                        <?php
                        if (!empty($infoTabel)) {
                            echo strip_tags($infoTabel, '<p><b><i><u><strong><em><br><ul><ol><li><a>');
                        } else {
                            echo 'Tabel <strong>' . ucwords(str_replace("_", " ", esc($table))) . '</strong> berisi data penting yang digunakan untuk pengelolaan sistem.';
                        }
                        ?>
                    </p>
                </div>
            </div>
        </div>

        <!-- Kolom kanan: panduan untuk user -->
        <div class="col-md-6 mb-1">
            <div class="card shadow-sm border-0 bg-light h-100">
                <div class="card-body p-1">
                    <h6 class="card-title mb-1" style="font-size: 0.85rem;">
                        <i class="fas fa-lightbulb text-warning mr-1"></i> Panduan Pengguna
                    </h6>
                    <p class="card-text mb-0 text-muted" style="font-size: 0.75rem; line-height: 1;">
                        <?php
                        if (!empty($infoUser)) {
                            echo strip_tags($infoUser, '<p><b><i><u><strong><em><br><ul><ol><li><a>');
                        } else {
                            echo 'Gunakan tombol <strong>Tambah</strong> untuk menambah data baru, atau klik <strong>Edit</strong> untuk memperbarui data yang ada.';
                        }
                        ?>
                    </p>
                </div>
            </div>
        </div>
    </div>




    <div class="d-flex justify-content-between align-items-center mb-1">
        <div class="d-flex justify-content-end mb-1">
            <!-- 🔹 Tombol utama CRUD -->
            <div class="btn-group" role="group">
                <?php
                // ✅ Jika sedang ActiveView, pakai tabel dari session
                if (isset($isActiveView) && $isActiveView) {
                    $table = session()->get('activeViewTable') ?? $table;
                }
                ?>
                <?php

                if (!empty($buttons)): ?>
                    <?php if ($buttons['tambah'] === 'aktif'): ?>
                        <button id="btn-tambah-<?= esc($table) ?>" class="btn btn-sm btn-primary btn-add" data-table="<?= esc($table) ?>">
                            <i class="fas fa-plus mr-1"></i> Tambah
                        </button>
                    <?php endif; ?>

                    <?php if ($buttons['export'] === 'aktif'): ?>
                        <button id="btn-export-<?= esc($table) ?>" class="btn btn-sm btn-success btn-export" data-table="<?= esc($table) ?>">
                            <i class="fas fa-file-export mr-1"></i> Export
                        </button>
                    <?php endif; ?>

                    <?php if ($buttons['import'] === 'aktif'): ?>
                        <button id="btn-import-<?= esc($table) ?>" class="btn btn-sm btn-warning btn-import" data-table="<?= esc($table) ?>">
                            <i class="fas fa-file-import mr-1"></i> Import
                        </button>
                    <?php endif; ?>

                    <?php if ($buttons['print'] === 'aktif'): ?>
                        <button id="btn-print-<?= esc($table) ?>" class="btn btn-sm btn-secondary btn-print" data-table="<?= esc($table) ?>">
                            <i class="fas fa-print mr-1"></i> Print
                        </button>
                    <?php endif; ?>

                    <?php if ($buttons['generate'] === 'aktif'): ?>
                        <button id="btn-generate-<?= esc($table) ?>" class="btn btn-sm btn-info btn-generate" data-table="<?= esc($table) ?>">
                            <i class="fas fa-cogs mr-1"></i> Generate
                        </button>
                    <?php endif; ?>

                    <?php if ($buttons['delete_all'] === 'aktif'): ?>
                        <button id="btn-deleteall-<?= esc($table) ?>" class="btn btn-sm btn-danger btn-delete-all" data-table="<?= esc($table) ?>">
                            <i class="fas fa-trash-alt mr-1"></i> Delete All
                        </button>
                    <?php endif; ?>

                    <?php if ($buttons['activeView'] === 'aktif'): ?>
                        <?php $isActive = ($activeViewTable === $table); ?>
                        <button id="btn-activeview-<?= esc($table) ?>"
                            class="btn btn-sm <?= $isActive ? 'btn-success' : 'btn-secondary' ?> activeView"
                            data-table="<?= esc($table) ?>">
                            <i class="fas <?= $isActive ? 'fa-eye' : 'fa-check' ?> mr-1"></i> activeView
                        </button>
                    <?php endif; ?>
                <?php endif; ?>
            </div>



        </div>
    </div>


    <div class="table-responsive">
        <table id="datatable" class="table table-bordered table-striped table-hover">
            <thead class="table-secondary">
                <tr>
                    <th>No</th> <!-- Kolom Nomor -->
                    <?php foreach ($fields as $field): ?>
                        <th><?= ucfirst(esc($field)) ?></th>
                    <?php endforeach; ?>
                    <th>Aksi</th>
                </tr>
            </thead>
            <tbody>
                <?php if (!empty($rows)): ?>
                    <?php $no = 1; // counter nomor 
                    ?>
                    <?php
                    // ✅ Jika sedang ActiveView, pakai tabel dari session
                    if (isset($isActiveView) && $isActiveView) {
                        $table = session()->get('activeViewTable') ?? $table;
                    }
                    ?>
                    <?php foreach ($rows as $row): ?>
                        <tr data-id="<?= esc($row[$meta[0]['name']] ?? '') ?>">
                            <!-- Kolom Nomor -->
                            <td>
                                <div class="d-flex justify-content-center align-items-center" style="min-height:50px;">
                                    <?= $no++; ?>
                                </div>
                            </td>

                            <!-- Kolom Data -->
                            <?php foreach ($fields as $field): ?>
                                <td>
                                    <?php if (in_array($field, $toggleFields) && isset($row[$field]) && in_array($row[$field], ['aktif', 'nonaktif'])): ?>
                                        <!-- ✅ Kolom Toggle ON/OFF -->
                                        <div class="d-flex justify-content-center align-items-center gap-1" style="min-height:50px;">
                                            <div class="custom-control custom-switch">
                                                <input type="checkbox"
                                                    class="custom-control-input toggle-status"
                                                    id="switch_<?= esc($table) ?>_<?= esc($field) ?>_<?= esc($row[$meta[0]['name']] ?? '') ?>"
                                                    data-table="<?= esc($table) ?>"
                                                    data-field="<?= esc($row[$meta[0]['name']] ?? '') ?>"
                                                    data-column="<?= esc($field) ?>"
                                                    <?= $row[$field] === 'aktif' ? 'checked' : '' ?>>
                                                <label class="custom-control-label"
                                                    for="switch_<?= esc($table) ?>_<?= esc($field) ?>_<?= esc($row[$meta[0]['name']] ?? '') ?>">
                                                    <?= $row[$field] === 'aktif' ? 'ON' : 'OFF' ?>
                                                </label>
                                            </div>
                                        </div>
                                    <?php else: ?>
                                        <!-- ✅ Kolom Teks Biasa (rata kiri) -->
                                        <div class="d-flex justify-content-start align-items-center ps-2" style="min-height:50px;">
                                            <?= esc($row[$field] ?? '') ?>
                                        </div>
                                    <?php endif; ?>
                                </td>
                            <?php endforeach; ?>

                            <!-- ✅ Tombol Aksi -->
                            <td>
                                <div class="d-flex justify-content-center align-items-center gap-1" style="min-height:50px;">
                                    <?php if ($buttons['view'] === 'aktif'): ?>
                                        <button id="btn-view-<?= esc($table) ?>-<?= esc($row[$meta[0]['name']] ?? '') ?>"
                                            class="btn btn-sm btn-info view-btn"
                                            data-table="<?= esc($table) ?>"
                                            data-id="<?= esc($row[$meta[0]['name']] ?? '') ?>"
                                            title="Lihat Data">
                                            <i class="fas fa-eye"></i>
                                        </button>
                                    <?php endif; ?>

                                    <?php if ($buttons['edit'] === 'aktif'): ?>
                                        <button id="btn-edit-<?= esc($table) ?>-<?= esc($row[$meta[0]['name']] ?? '') ?>"
                                            class="btn btn-sm btn-warning edit-btn"
                                            data-table="<?= esc($table) ?>"
                                            data-id="<?= esc($row[$meta[0]['name']] ?? '') ?>"
                                            title="Edit Data">
                                            <i class="fas fa-edit"></i>
                                        </button>
                                    <?php endif; ?>

                                    <?php if ($buttons['delete'] === 'aktif'): ?>
                                        <button id="btn-delete-<?= esc($table) ?>-<?= esc($row[$meta[0]['name']] ?? '') ?>"
                                            class="btn btn-sm btn-danger delete-btn"
                                            data-table="<?= esc($table) ?>"
                                            data-id="<?= esc($row[$meta[0]['name']] ?? '') ?>"
                                            title="Hapus Data">
                                            <i class="fas fa-trash"></i>
                                        </button>
                                    <?php endif; ?>
                                </div>
                            </td>

                        </tr>
                    <?php endforeach; ?>
                <?php else: ?>
                    <!-- ✅ Jika Tidak Ada Data -->
                    <tr class="no-data text-center">
                        <td>—</td> <!-- No -->
                        <?php foreach ($fields as $field): ?>
                            <td>—</td>
                        <?php endforeach; ?>
                        <td class="text-muted">Tidak ada data</td>
                    </tr>
                <?php endif; ?>
            </tbody>
        </table>
    </div>



</div>

<!-- Modal Tambah/Edit -->
<div class="modal fade" id="formModal" tabindex="-1">
    <div class="modal-dialog modal-lg modal-dialog-scrollable">
        <div class="modal-content">
            <form id="crudForm">
                <div class="modal-header bg-primary text-white">
                    <h5 class="modal-title">Form <?= esc($table) ?></h5>
                    <button type="button" class="close text-white" data-dismiss="modal">&times;</button>
                </div>

                <!-- Body scrollable dan smooth -->
                <div class="modal-body p-3 scrollable">
                    <div class="table-responsive">
                        <table class="table table-borderless table-sm mb-0" id="crudFormTable">
                            <tbody>
                                <!-- JS akan mengisi field otomatis di sini -->
                            </tbody>
                        </table>
                    </div>
                </div>

                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-dismiss="modal">Batal</button>
                    <button type="submit" class="btn btn-primary">Simpan</button>
                </div>
            </form>
        </div>
    </div>
</div>


<!-- Modal Import -->
<div class="modal fade" id="importModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <form id="importForm" enctype="multipart/form-data">
                <div class="modal-header">
                    <h5 class="modal-title">Import Data <?= esc($table) ?></h5>
                    <button type="button" class="close" data-dismiss="modal">&times;</button>
                </div>
                <div class="modal-body">
                    <div class="form-group">
                        <label>Pilih file Excel (.xls / .xlsx)</label>
                        <input type="file" name="file" class="form-control" required>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-dismiss="modal">Batal</button>
                    <button type="submit" class="btn btn-primary">Upload</button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- Modal View (Detail) -->
<div class="modal fade" id="viewModal" tabindex="-1">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header bg-secondary text-white">
                <h5 class="modal-title">Detail Data <?= esc($table) ?></h5>
                <button type="button" class="close text-white" data-dismiss="modal">&times;</button>
            </div>
            <div class="modal-body">
                <div id="viewContent" class="p-3">
                    <!-- Konten detail diisi oleh JS -->
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-dismiss="modal">Tutup</button>
            </div>
        </div>
    </div>
</div>