<?php $attributes ??= new \Illuminate\View\ComponentAttributeBag;

$__newAttributes = [];
$__propNames = \Illuminate\View\ComponentAttributeBag::extractPropNames(([
    'columns',           // Array of column definitions
    'dataUrl',           // URL for fetching data
    'baseUrl',           // Base URL for edit/delete (e.g. '_cp/companies')
    'exportUrl',         // URL for exporting XML
    'bulkUrl'      => null, // Optional URL for bulk delete
    'createUrl'    => null, // Optional URL for “create new” link
    'title'        => null, // Human-readable title (e.g. __('forms.Companies'))
    'enableExport'     => false, // Enable XML export (default: false)
    'enableBulkDelete' => false, // Enable bulk delete (default: false)
    'enableEdit'       => true,  // Enable edit action (default: true)
    'enableDelete'     => false, // Enable delete action (default: false)
    'instanceKey',          // Unique identifier for table instance
]));

foreach ($attributes->all() as $__key => $__value) {
    if (in_array($__key, $__propNames)) {
        $$__key = $$__key ?? $__value;
    } else {
        $__newAttributes[$__key] = $__value;
    }
}

$attributes = new \Illuminate\View\ComponentAttributeBag($__newAttributes);

unset($__propNames);
unset($__newAttributes);

foreach (array_filter(([
    'columns',           // Array of column definitions
    'dataUrl',           // URL for fetching data
    'baseUrl',           // Base URL for edit/delete (e.g. '_cp/companies')
    'exportUrl',         // URL for exporting XML
    'bulkUrl'      => null, // Optional URL for bulk delete
    'createUrl'    => null, // Optional URL for “create new” link
    'title'        => null, // Human-readable title (e.g. __('forms.Companies'))
    'enableExport'     => false, // Enable XML export (default: false)
    'enableBulkDelete' => false, // Enable bulk delete (default: false)
    'enableEdit'       => true,  // Enable edit action (default: true)
    'enableDelete'     => false, // Enable delete action (default: false)
    'instanceKey',          // Unique identifier for table instance
]), 'is_string', ARRAY_FILTER_USE_KEY) as $__key => $__value) {
    $$__key = $$__key ?? $__value;
}

$__defined_vars = get_defined_vars();

foreach ($attributes->all() as $__key => $__value) {
    if (array_key_exists($__key, $__defined_vars)) unset($$__key);
}

unset($__defined_vars, $__key, $__value); ?>

<?php
    // Fallbacks
    $bulkUrl   = $bulkUrl   ?? url($baseUrl . '/bulk-delete');
    $createUrl = $createUrl ?? url($baseUrl . '/create');
    $titleText = $title     ?? Str::headline(Str::plural(class_basename($baseUrl)));
?>

<div x-data="dataTable({
        instanceKey: '<?php echo e($instanceKey); ?>',
        dataUrl:      '<?php echo e($dataUrl); ?>',
        baseUrl:      '<?php echo e($baseUrl); ?>',
        exportUrl:    '<?php echo e($exportUrl); ?>',
        bulkUrl:      '<?php echo e($bulkUrl); ?>',
        columns:      <?php echo e(Illuminate\Support\Js::from($columns)); ?>,
        enableExport:     <?php echo e(json_encode($enableExport)); ?>,
        enableBulkDelete: <?php echo e(json_encode($enableBulkDelete)); ?>,
        enableEdit:       <?php echo e(json_encode($enableEdit)); ?>,
        enableDelete:     <?php echo e(json_encode($enableDelete)); ?>,
    })"
    x-init="init()"
    class="p-4 relative"
>

    <!-- Header -->
    <div class="box-header mb-4">
        <div class="flex justify-between items-center">
            <h5 class="box-title"><?php echo e($titleText); ?></h5>
            <div class="flex space-x-2">
                <button @click="showColumnManager = !showColumnManager"
                        class="ti-btn ti-btn-outline ti-btn-outline-secondary py-1 px-3">
                    <?php echo e(__('Manage Columns')); ?>

                </button>
                <a href="<?php echo e($createUrl); ?>"
                   class="ti-btn ti-btn-soft-success py-1 px-3">
                    <?php echo e(__('Create New')); ?>

                </a>
            </div>
        </div>
    </div>

    <!-- Export & Column Manager -->
    <div class="flex items-center justify-between mb-4 relative">
        <div class="flex space-x-2">
            <template x-if="enableExport && exportUrl">
                <a :href="exportUrl + '?' + new URLSearchParams({
                                search: search,
                                sort:   sortColumn,
                                direction: sortDirection
                            }).toString()"
                   class="px-4 py-1.5 bg-green-600 text-white rounded"
                   target="_blank"
                >
                    <?php echo e(__('Export XML')); ?>

                </a>
            </template>
        </div>

        <!-- Fluid, viewport-adaptive popup -->
        <div
            x-show="showColumnManager"
            x-cloak
            class="
              absolute top-full right-0 mt-2
              bg-white border rounded shadow-lg
              p-4

              /* cap height to viewport minus 4rem, scroll if too tall */
              max-h-[calc(100vh-4rem)]
              overflow-auto

              /* cap width to viewport minus 2rem, shrink to content */
              max-w-[calc(100vw-2rem)]
              w-auto

              z-50
            "
        >
            <div class="space-y-2">
                <template x-for="col in columns" :key="col.key">
                    <div class="flex items-center space-x-2">
                        <input type="checkbox"
                               :id="`${instanceKey}_col_${col.key}`"
                               :checked="col.visible"
                               @change="toggleColumnVisibility(col.key)"
                               class="form-checkbox"
                        />
                        <label x-text="col.label"></label>
                    </div>
                </template>
            </div>
        </div>
    </div>

    <!-- Search -->
    <div class="mb-4">
        <input type="text"
               x-model="search"
               @input.debounce="searchItems()"
               placeholder="<?php echo e(__('Search...')); ?>"
               class="py-2 px-3 ti-form-input w-full" />
    </div>

    <!-- Table -->
    <div class="box-body p-0 activity-table overflow-x-auto">
        <table class="ti-custom-table ti-custom-table-head w-full">
            <thead>
                <tr>
                    <th class="p-2" x-show="enableBulkDelete" x-cloak>
                        <input type="checkbox"
                               @change="selected = $event.target.checked ? items.map(i => i.id) : []">
                    </th>
                    <template x-for="col in columns.filter(c => c.visible)" :key="col.key">
                        <th class="p-2 cursor-pointer"
                            @click="sortBy(col.key)">
                            <span x-text="col.label"></span>
                            <span x-show="sortColumn === col.key"
                                  x-text="sortDirection === 'asc' ? '▲' : '▼'"></span>
                        </th>
                    </template>
                    <th class="!text-end p-2"><?php echo e(__('Actions')); ?></th>
                </tr>
            </thead>
            <tbody>
                <template x-for="item in items" :key="item.id">
                    <tr class="border-b hover:bg-gray-50">
                        <td class="p-2" x-show="enableBulkDelete" x-cloak>
                            <input type="checkbox" :value="item.id" x-model="selected">
                        </td>
                        <template x-for="col in columns.filter(c => c.visible)" :key="col.key + '_' + item.id">
                            <td class="p-2" x-text="item[col.key]"></td>
                        </template>
                        <td class="p-2 space-x-2 text-right">
                            <template x-if="enableEdit">
                                <a :href="baseUrl + '/' + item.id + '/edit'"
                                   class="text-blue-600 hover:underline">
                                    <?php echo e(__('Edit')); ?>

                                </a>
                            </template>
                            <template x-if="enableDelete">
                                <button @click.prevent="deleteItem(item.id)"
                                        class="text-red-600 hover:underline">
                                    <?php echo e(__('Delete')); ?>

                                </button>
                            </template>
                        </td>
                    </tr>
                </template>
            </tbody>
        </table>
    </div>

    <!-- Pagination & Bulk Delete -->
    <div class="flex items-center justify-between mt-4 text-sm text-gray-600">
        <div>
            <?php echo e(__('Page')); ?> <span x-text="currentPage"></span> <?php echo e(__('of')); ?>

            <span x-text="totalPages"></span>
        </div>
        <div class="space-x-1">
            <button @click="prevPage()"
                    :disabled="currentPage <= 1"
                    class="px-2 py-1 border rounded">
                <?php echo e(__('Prev')); ?>

            </button>
            <template x-for="pageNum in pagesList()" :key="pageNum">
                <button @click="goToPage(pageNum)"
                        x-text="pageNum"
                        class="px-2 py-1 border rounded"
                        :class="{ 'bg-gray-300': pageNum === currentPage }">
                </button>
            </template>
            <button @click="nextPage()"
                    :disabled="currentPage >= totalPages"
                    class="px-2 py-1 border rounded">
                <?php echo e(__('Next')); ?>

            </button>
        </div>

        <template x-if="enableBulkDelete">
            <button @click="deleteSelected()"
                    :disabled="selected.length === 0"
                    class="px-4 py-1 bg-red-600 text-white rounded disabled:opacity-50">
                <?php echo e(__('Delete Selected')); ?>

            </button>
        </template>
    </div>
</div><?php /**PATH C:\laragon\www\policypilot\resources\views/components/datatable.blade.php ENDPATH**/ ?>