<?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') ?> mr-2"></i>
            Data <?= ucwords(str_replace('_', ' ', esc($table))) ?>
        </h4>

        <!-- Notifikasi Active View -->
        <?php if ($isActiveView): ?>
            <div class="alert alert-info text-center shadow-sm mb-3 py-2">
                <i class="fa fa-eye mr-1"></i>
                Menggunakan <strong>Active View</strong> dari tabel konfigurasi:
                <code><?= esc($sessionTable) ?></code> untuk <strong><?= esc($table) ?></strong>
            </div>
        <?php endif; ?>

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

    <!-- Informasi Tabel & Panduan Pengguna -->
    <div class="row mb-2">
        <div class="col-md-6 mb-2">
            <div class="card shadow-sm border-0 bg-light h-100">
                <div class="card-body p-3">
                    <h6 class="card-title mb-2 text-primary" style="font-size: 0.9rem;">
                        <i class="fas fa-info-circle mr-1"></i> Informasi Tabel
                    </h6>
                    <p class="card-text text-muted mb-0" style="font-size: 0.8rem; line-height: 1.4;">
                        <?= !empty($infoTabel)
                            ? strip_tags($infoTabel, '<p><b><i><u><strong><em><br><ul><ol><li><a>')
                            : 'Tabel <strong>' . ucwords(str_replace('_', ' ', esc($table))) . '</strong> berisi data penting untuk pengelolaan sistem.'
                        ?>
                    </p>
                </div>
            </div>
        </div>

        <div class="col-md-6 mb-2">
            <div class="card shadow-sm border-0 bg-light h-100">
                <div class="card-body p-3">
                    <h6 class="card-title mb-2 text-warning" style="font-size: 0.9rem;">
                        <i class="fas fa-lightbulb mr-1"></i> Panduan Pengguna
                    </h6>
                    <p class="card-text text-muted mb-0" style="font-size: 0.8rem; line-height: 1.4;">
                        <?= !empty($infoUser)
                            ? strip_tags($infoUser, '<p><b><i><u><strong><em><br><ul><ol><li><a>')
                            : 'Gunakan tombol <strong>Tambah</strong> untuk menambah data, atau klik <strong>Edit</strong> untuk mengubah data.'
                        ?>
                    </p>
                </div>
            </div>
        </div>
    </div>

    <!-- Tombol Aksi Utama -->
    <div class="d-flex justify-content-between align-items-center mb-1">
        <div class="btn-group" role="group" aria-label="Aksi CRUD">

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

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

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

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

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

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

                <!-- ActiveView Toggle -->
                <?php if ($buttons['activeView'] === 'aktif'): ?>
                    <button type="button"
                        class="btn btn-sm <?= $isActiveButton ? 'btn-success' : 'btn-outline-secondary' ?> activeView"
                        data-table="<?= esc($targetTable) ?>"
                        title="<?= $isActiveButton ? 'Nonaktifkan Active View' : 'Aktifkan Active View' ?>">
                        <i class="fas <?= $isActiveButton ? 'fa-eye-slash' : 'fa-eye' ?> mr-1"></i>
                        ActiveView
                    </button>
                <?php endif; ?>
            <?php endif; ?>

        </div>
    </div>

    <div class="table-responsive">
        <table id="datatable" class="table table-bordered table-striped table-hover dataTable-custom-style">
            <thead class="table-secondary">
                <tr>
                    <th class="text-center column-fit" data-dt-idx="0">No</th>
                    <?php $i = 1; // Mulai indeks dari 1 untuk kolom data 
                    ?>
                    <?php foreach ($fields as $field): ?>
                        <th class="text-start" data-dt-idx="<?= $i++ ?>"><?= ucfirst(esc($field)) ?></th>
                    <?php endforeach; ?>
                    <th class="text-center column-fit" data-dt-idx="<?= $i ?>">Aksi</th>
                </tr>
            </thead>
            <tbody>
                <?php if (!empty($rows)): ?>
                    <?php $no = 1; ?>
                    <?php foreach ($rows as $row):
                        $primaryValue = $row[$meta[0]['name']] ?? '';
                        $rowId = esc($primaryValue);
                    ?>
                        <tr data-id="<?= $rowId ?>">
                            <td class="text-center column-fit"><?= $no++ ?></td>

                            <?php foreach ($fields as $field):
                                $value = $row[$field] ?? '';
                                $cleanedValue = nl2br(esc($value));
                            ?>
                                <td>
                                    <?php if (in_array($field, $toggleFields ?? []) && in_array($value, ['aktif', 'nonaktif'])): ?>
                                        <div class="d-flex justify-content-center align-items-center" style="min-height:50px;">
                                            <div class="custom-control custom-switch">
                                                <input type="checkbox"
                                                    class="custom-control-input toggle-status"
                                                    id="switch_<?= esc($targetTable) ?>_<?= esc($field) ?>_<?= $rowId ?>"
                                                    data-table="<?= esc($targetTable) ?>"
                                                    data-id="<?= $rowId ?>"
                                                    data-column="<?= esc($field) ?>"
                                                    <?= $value === 'aktif' ? 'checked' : '' ?>>
                                                <label class="custom-control-label"
                                                    for="switch_<?= esc($targetTable) ?>_<?= esc($field) ?>_<?= $rowId ?>">
                                                    <?= $value === 'aktif' ? 'ON' : 'OFF' ?>
                                                </label>
                                            </div>
                                        </div>
                                    <?php elseif (is_numeric($value) && $field !== $meta[0]['name']): ?>
                                        <div class="d-flex justify-content-end align-items-center pe-2" style="min-height:50px;">
                                            <?= $cleanedValue ?>
                                        </div>
                                    <?php else: ?>
                                        <div class="d-flex justify-content-start align-items-center ps-2" style="min-height:50px;">
                                            <?= $cleanedValue ?>
                                        </div>
                                    <?php endif; ?>
                                </td>
                            <?php endforeach; ?>

                            <td class="column-fit">
                                <div class="d-flex justify-content-center align-items-center gap-1" style="min-height:50px;">
                                    <?php if ($buttons['view'] === 'aktif'): ?>
                                        <button type="button"
                                            class="btn btn-sm btn-info view-btn"
                                            data-table="<?= esc($targetTable) ?>"
                                            data-id="<?= $rowId ?>"
                                            title="Lihat Detail">
                                            <i class="fas fa-eye"></i>
                                        </button>
                                    <?php endif; ?>

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

                                    <?php if ($buttons['delete'] === 'aktif'): ?>
                                        <button type="button"
                                            class="btn btn-sm btn-danger delete-btn"
                                            data-table="<?= esc($targetTable) ?>"
                                            data-id="<?= $rowId ?>"
                                            title="Hapus Data">
                                            <i class="fas fa-trash"></i>
                                        </button>
                                    <?php endif; ?>
                                </div>
                            </td>
                        </tr>
                    <?php endforeach; ?>
                <?php else: ?>
                    <tr>
                        <td colspan="<?= count($fields) + 2 ?>" class="text-center text-muted py-4">
                            <i class="fas fa-inbox fa-2x mb-2 d-block"></i>
                            Tidak ada data
                        </td>
                    </tr>
                <?php endif; ?>
            </tbody>
        </table>
    </div>
    <!-- Modal Form (Tambah/Edit) -->
    <div class="modal fade" id="formModal" tabindex="-1" role="dialog" aria-labelledby="formModalLabel" aria-hidden="true">
        <div class="modal-dialog modal-lg modal-dialog-scrollable" role="document">
            <div class="modal-content">
                <form id="crudForm">
                    <div class="modal-header bg-primary text-white">
                        <h5 class="modal-title" id="formModalLabel">Form <?= esc($targetTable) ?></h5>
                        <button type="button" class="close text-white" data-dismiss="modal" aria-label="Close">
                            <span aria-hidden="true">&times;</span>
                        </button>
                    </div>
                    <div class="modal-body p-3">
                        <div class="table-responsive">
                            <table class="table table-borderless table-sm mb-0" id="crudFormTable">
                                <tbody>
                                    <!-- Diisi oleh JavaScript -->
                                </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" role="dialog" aria-labelledby="importModalLabel" aria-hidden="true">
        <div class="modal-dialog" role="document">
            <div class="modal-content">
                <form id="importForm" enctype="multipart/form-data">
                    <div class="modal-header">
                        <h5 class="modal-title" id="importModalLabel">Import Data <?= esc($targetTable) ?></h5>
                        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                            <span aria-hidden="true">&times;</span>
                        </button>
                    </div>
                    <div class="modal-body">
                        <div class="form-group">
                            <label for="importFile">Pilih file Excel</label>
                            <input type="file" name="file" id="importFile" class="form-control" accept=".xls,.xlsx" required>
                            <small class="form-text text-muted">Format: .xls atau .xlsx</small>
                        </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" role="dialog" aria-labelledby="viewModalLabel" aria-hidden="true">
        <div class="modal-dialog modal-lg" role="document">
            <div class="modal-content">
                <div class="modal-header bg-secondary text-white">
                    <h5 class="modal-title" id="viewModalLabel">Detail Data <?= esc($targetTable) ?></h5>
                    <button type="button" class="close text-white" data-dismiss="modal" aria-label="Close">
                        <span aria-hidden="true">&times;</span>
                    </button>
                </div>
                <div class="modal-body">
                    <div id="viewContent" class="p-3">
                        <!-- 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>

</div> <!-- #crud-content -->

<?php if ($isActiveView): ?>
    <script>
        document.addEventListener('DOMContentLoaded', function() {
            Swal.fire({
                icon: 'info',
                title: 'Active View Aktif',
                html: `
                Tampilan ini menggunakan konfigurasi dari tabel:<br>
                <code class="text-primary"><?= esc($sessionTable) ?></code><br>
                untuk data <strong><?= esc($table) ?></strong>
            `,
                timer: 4000,
                timerProgressBar: true,
                showConfirmButton: false
            });
        });
    </script>
<?php endif; ?>