@extends('admin.layouts.app')

@section('title', __('dashboard.manage_members') . ' - ' . $academy->name)

@section('content')
<x-admin.page-header title="{{ __('dashboard.manage_members') ?? 'Manage Members' }} - {{ $academy->name }}" :breadcrumbs="[__('dashboard.academies') => route('admin.academies.index'), __('dashboard.manage_members') ?? 'Manage Members' => '']" />

<div class="row mt-3">
    <!-- Left: Available Members DataTable -->
    <div class="col-lg-5">
        <div class="card h-100">
            <div class="card-header pb-0 card-no-border">
                <h5 class="card-title mb-0">{{ __('dashboard.available_members') ?? 'Available Members' }}</h5>
                <div class="d-flex flex-wrap gap-2 mt-2">
                    <a href="{{ route('admin.academies.members.export.members', $academy->id) }}" class="btn btn-soft-primary btn-sm">
                        <i class="ri-download-2-line me-1"></i> {{ __('Export Members') }}
                    </a>
                    <a href="{{ route('admin.academies.members.export.dependents', $academy->id) }}" class="btn btn-soft-primary btn-sm">
                        <i class="ri-download-2-line me-1"></i> {{ __('Export Dependents') }}
                    </a>
                    <a href="{{ route('admin.academies.members.export.all', $academy->id) }}" class="btn btn-soft-info btn-sm">
                        <i class="ri-download-2-line me-1"></i> {{ __('Export All (Members + Dependents)') }}
                    </a>
                   
                </div>
                <div class="filter-section mt-2">
                    <div class="row g-3 align-items-end">
                        {{-- <x-select col="12"
                                  name="am-type-filter"
                                  label="{{ __('Type') }}"
                                  :options="$recordTypes" /> --}}
                    </div>
                </div>
            </div>
            <div class="card-body">
                {{-- Two hidden inputs, one per type, so the DataTable can exclude each set independently --}}
                <input type="hidden" id="am-hidden-member-ids"    value="">
                <input type="hidden" id="am-hidden-dependent-ids" value="">
                <div class="table-responsive custom-scrollbar server-side-table">
                    {!! $dataTable->table(['class' => 'table table-bordered', 'id' => 'academy-member-all-table']) !!}
                </div>
            </div>
        </div>
    </div>

    <!-- Middle: Transfer Buttons -->
    <div class="col-lg-2 d-flex flex-column align-items-center justify-content-center gap-3 py-4">
        <button id="add-members-btn" class="btn btn-primary btn-icon rounded-circle shadow-sm" style="width: 50px; height: 50px;" title="Add Selected">
            <i class="ri-arrow-right-line fs-3"></i>
        </button>
        <button id="remove-members-btn" class="btn btn-danger btn-icon rounded-circle shadow-sm" style="width: 50px; height: 50px;" title="Remove Selected">
            <i class="ri-arrow-left-line fs-3"></i>
        </button>
    </div>

    <!-- Right: Selected Members Table (client-side) -->
    <div class="col-lg-5">
        <div class="card h-100">
            <div class="card-header pb-0 card-no-border d-flex justify-content-between align-items-center">
                <div>
                    <h5 class="card-title mb-0">{{ __('dashboard.selected_members') ?? 'Selected Members' }}</h5>
                    <div class="d-flex flex-wrap gap-2 mt-2">
                        <a href="{{ route('admin.academies.members.export-selected.members', $academy->id) }}" class="btn btn-soft-primary btn-sm">
                            <i class="ri-download-2-line me-1"></i> {{ __('Export Selected Members') }}
                        </a>
                        <a href="{{ route('admin.academies.members.export-selected.dependents', $academy->id) }}" class="btn btn-soft-primary btn-sm">
                            <i class="ri-download-2-line me-1"></i> {{ __('Export Selected Dependents') }}
                        </a>
                        <a href="{{ route('admin.academies.members.export-selected.all', $academy->id) }}" class="btn btn-soft-info btn-sm">
                            <i class="ri-download-2-line me-1"></i> {{ __('Export Selected All') }}
                        </a>
                        <a href="{{ route('admin.academies.members.import.page', $academy->id) }}" class="btn btn-soft-success btn-sm">
                            <i class="ri-upload-2-line me-1"></i> {{ __('Import members & dependents') }}
                        </a>
                    </div>
                </div>
                <span class="badge bg-primary" id="selected-count">0</span>
            </div>
            <div class="card-body">
                <div class="table-responsive custom-scrollbar">
                    <table class="table table-bordered" id="academy-assigned-members-table">
                        <thead>
                        <tr>
                            <th class="text-center" style="width: 8%">
                                <input type="checkbox" id="am-selected-check-all">
                            </th>
                            <th>{{ __('dashboard.name') }}</th>
                            <th>{{ __('dashboard.phone') }}</th>
                            <th>{{ __('dashboard.type') }}</th>
                            <th>{{ __('dashboard.status') }}</th>
                        </tr>
                        </thead>
                        <tbody></tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>
</div>

<div class="position-sticky bottom-0 mt-3" style="z-index: 1020;">
    <div class="card border-0 shadow-sm">
        <div class="card-body d-flex justify-content-end gap-2">
            <form id="export-selected-form" action="{{ route('admin.academies.members.export-selected', $academy->id) }}" method="POST" class="d-inline">
                @csrf
                <input type="hidden" name="member_ids" id="export-member-ids" value="">
                <input type="hidden" name="dependent_ids" id="export-dependent-ids" value="">
                <button type="submit" id="export-selected-btn" class="btn btn-outline-primary">
                    <i class="ri-download-2-line me-1"></i> {{ __('Export Selected') }}
                </button>
            </form>
            <button type="button" id="save-members-btn" class="btn btn-success">
                <i class="ri-save-line me-1"></i> {{ __('dashboard.save') }}
            </button>
        </div>
    </div>
</div>
@endsection

@push('scripts')
    {!! $dataTable->scripts() !!}
    <script>
        document.addEventListener('DOMContentLoaded', function () {
            const MEMBER_STATUS_LABELS = @json($memberStatusEnumLabels);
            const MEMBER_STATUS_COLORS = @json($memberStatusEnumColors);

            function memberStatusBadge(status) {
                const v = parseInt(String(status ?? '1'), 10);
                if (!Number.isFinite(v)) {
                    return '<span class="text-muted">—</span>';
                }
                const label = MEMBER_STATUS_LABELS[v] ?? MEMBER_STATUS_LABELS[String(v)] ?? '—';
                const color = MEMBER_STATUS_COLORS[v] ?? MEMBER_STATUS_COLORS[String(v)] ?? 'secondary';
                return '<span class="badge bg-' + color + '-subtle text-' + color + '">' + label + '</span>';
            }

            const availableTable = $('#academy-member-all-table').DataTable();

            const assignedTable = $('#academy-assigned-members-table').DataTable({
                processing: false,
                serverSide: false,
                paging: true,
                searching: true,
                info: true,
                pageLength: 10,
                order: [[1, 'asc']],
                columns: [
                    { data: 'checkbox',  orderable: false, searchable: false, className: 'text-center' },
                    { data: 'name' },
                    { data: 'phone' },
                    { data: 'type',      orderable: false, searchable: false },
                    { data: 'status',    orderable: false, searchable: false, render: function (data) { return memberStatusBadge(data); } },
                ],
            });

            const selectedCount = $('#selected-count');

            // ─── State ────────────────────────────────────────────────────────
            // Separate sets so all dependents (even from the same parent) are tracked individually.
            const selectedMemberIds    = new Set();   // actual member IDs (m.id)
            const selectedDependentIds = new Set();   // actual dependent IDs (d.id)

            // ─── Helpers ──────────────────────────────────────────────────────
            function refreshSelectedCount() {
                selectedCount.text(selectedMemberIds.size + selectedDependentIds.size);
            }

            function syncHiddenInputs() {
                const membersCsv = Array.from(selectedMemberIds).join(',');
                const dependentsCsv = Array.from(selectedDependentIds).join(',');
                document.getElementById('am-hidden-member-ids').value    = membersCsv;
                document.getElementById('am-hidden-dependent-ids').value = dependentsCsv;

                const exportMembers = document.getElementById('export-member-ids');
                const exportDependents = document.getElementById('export-dependent-ids');
                if (exportMembers) exportMembers.value = membersCsv;
                if (exportDependents) exportDependents.value = dependentsCsv;
            }

            const TYPE_LABEL_MEMBER = @json(__('dashboard.member'));
            const TYPE_LABEL_DEPENDENT = @json(__('dashboard.dependent'));

            function typeLabel(recordType) {
                return String(recordType || '').toLowerCase() === 'dependent' ? TYPE_LABEL_DEPENDENT : TYPE_LABEL_MEMBER;
            }

            // ─── Assigned-table duplicate checks ─────────────────────────────
            function assignedTableHasRowKey(rowKey) {
                return assignedTable.rows().data().toArray()
                    .some(r => (r.row_key || '') === rowKey);
            }

            // ─── Load saved selections from DB ───────────────────────────────
            function loadSelectedIds() {
                return fetch("{{ route('admin.academies.members.ids', $academy->id) }}")
                    .then(r => r.json())
                    .then(data => {
                        selectedMemberIds.clear();
                        selectedDependentIds.clear();
                        (data.member_ids    || []).forEach(id => selectedMemberIds.add(Number(id)));
                        (data.dependent_ids || []).forEach(id => selectedDependentIds.add(Number(id)));
                        syncHiddenInputs();
                        refreshSelectedCount();
                    });
            }

            function loadSelectedMembersTable() {
                return fetch("{{ route('admin.academies.members.selected', $academy->id) }}")
                    .then(r => r.json())
                    .then(data => {
                        const rows = (data.members || []).map(m => ({
                            checkbox:     `<input type="checkbox" class="row-checkbox" value="${m.row_key}" data-record-type="${m.type_value === 2 ? 'dependent' : 'member'}" data-id="${m.dependent_id ?? m.id}">`,
                            row_key:      m.row_key,
                            member_id:    Number(m.member_id ?? m.id),
                            dependent_id: m.dependent_id ? Number(m.dependent_id) : null,
                            name:         m.name  ?? '-',
                            phone:        m.phone ?? '-',
                            type:         m.type  ?? typeLabel(m.type_value === 2 ? 'dependent' : 'member'),
                            status:       m.status != null ? Number(m.status) : 1,
                        }));
                        assignedTable.clear().rows.add(rows).draw(false);
                        $('#am-selected-check-all').prop('checked', false);
                    });
            }

            // ─── Add to assigned table ────────────────────────────────────────
            function addToAssignedTableFromRowData(rowData) {
                const rowKey      = String(rowData?.row_key ?? '');
                const recordType  = String(rowData?.record_type ?? 'member').toLowerCase();
                const memberId    = Number(rowData?.member_id ?? 0);
                const dependentId = rowData?.dependent_id ? Number(rowData.dependent_id) : null;

                if (!rowKey || assignedTableHasRowKey(rowKey)) return;

                assignedTable.row.add({
                    checkbox:     `<input type="checkbox" class="row-checkbox" value="${rowKey}" data-record-type="${recordType}" data-id="${dependentId ?? memberId}">`,
                    row_key:      rowKey,
                    member_id:    memberId,
                    dependent_id: dependentId,
                    name:         rowData?.name  ?? '-',
                    phone:        rowData?.phone ?? '-',
                    type:         typeLabel(recordType),
                    status:       rowData?.status != null ? Number(rowData.status) : 1,
                }).draw(false);
            }

            // ─── Type filter ──────────────────────────────────────────────────
            $('#am-type-filter').on('change', function () {
                availableTable.draw();
            });

            initDataTableFilters({
                tableId:  'academy-member-all-table',
                csrf:     '{{ csrf_token() }}',
                filters:  ['#am-type-filter'],
                selectAll: '#am-check-all',
            });

            // Fix search-box alignment
            const dtSearchAvailable = document.querySelector('#academy-member-all-table_filter');
            if (dtSearchAvailable) dtSearchAvailable.classList.remove('text-end');
            const dtSearchAssigned  = document.querySelector('#academy-assigned-members-table_filter');
            if (dtSearchAssigned) dtSearchAssigned.classList.remove('text-end');

            // ─── Select-all on assigned table ────────────────────────────────
            $('#am-selected-check-all').on('change', function () {
                const checked = $(this).is(':checked');
                $('#academy-assigned-members-table tbody .row-checkbox').prop('checked', checked);
            });

            // ─── Add button ───────────────────────────────────────────────────
            $('#add-members-btn').on('click', function () {
                $('#academy-member-all-table tbody .row-checkbox:checked').each(function () {
                    const tr      = $(this).closest('tr');
                    const row     = availableTable.row(tr);
                    const rowData = row.data();
                    if (!rowData) return;

                    const recordType  = String(rowData.record_type ?? 'member').toLowerCase();
                    const memberId    = Number(rowData.member_id ?? 0);
                    const dependentId = rowData.dependent_id ? Number(rowData.dependent_id) : null;

                    if (recordType === 'dependent' && dependentId) {
                        selectedDependentIds.add(dependentId);
                    } else if (memberId) {
                        selectedMemberIds.add(memberId);
                    }

                    addToAssignedTableFromRowData(rowData);
                    row.remove();
                });

                $('#am-check-all').prop('checked', false);
                syncHiddenInputs();
                refreshSelectedCount();
                availableTable.ajax.reload(null, false);
            });

            // ─── Remove button ────────────────────────────────────────────────
            $('#remove-members-btn').on('click', function () {
                $('#academy-assigned-members-table tbody .row-checkbox:checked').each(function () {
                    const tr      = $(this).closest('tr');
                    const row     = assignedTable.row(tr);
                    const rowData = row.data();
                    if (!rowData) return;

                    const recordType  = String($(this).data('record-type') ?? rowData.dependent_id ? 'dependent' : 'member');
                    const dependentId = rowData.dependent_id ? Number(rowData.dependent_id) : null;
                    const memberId    = Number(rowData.member_id ?? 0);

                    row.remove();

                    if (recordType === 'dependent' && dependentId) {
                        selectedDependentIds.delete(dependentId);
                    } else if (memberId) {
                        selectedMemberIds.delete(memberId);
                    }
                });

                $('#am-selected-check-all').prop('checked', false);
                syncHiddenInputs();
                refreshSelectedCount();
                assignedTable.draw(false);
                availableTable.ajax.reload(null, false);
            });

            // ─── Save ─────────────────────────────────────────────────────────
            $(document)
                .off('click', '#save-members-btn')
                .on('click', '#save-members-btn', function (e) {
                    e.preventDefault();
                    e.stopPropagation();

                    const $btn = $(this);
                    $btn.prop('disabled', true);

                    $.ajax({
                        url:         "{{ route('admin.academies.members.sync', $academy->id) }}",
                        method:      'POST',
                        contentType: 'application/json; charset=utf-8',
                        dataType:    'json',
                        headers:     { 'X-CSRF-TOKEN': '{{ csrf_token() }}' },
                        data: JSON.stringify({
                            member_ids:    Array.from(selectedMemberIds),
                            dependent_ids: Array.from(selectedDependentIds),
                        }),
                        success: function (res) {
                            if (res && res.success) {
                                if (typeof showToast === 'function') showToast('success', res.message);
                                setTimeout(() => { window.location.href = "{{ route('admin.academies.index') }}"; }, 300);
                                return;
                            }
                            if (typeof showToast === 'function') showToast('error', res?.message || 'Error occurred');
                            $btn.prop('disabled', false);
                        },
                        error: function (xhr) {
                            const msg = xhr.responseJSON?.message || 'Error occurred';
                            if (typeof showToast === 'function') showToast('error', msg);
                            $btn.prop('disabled', false);
                        },
                    });

                    return false;
                });

            // ─── Init ─────────────────────────────────────────────────────────
            loadSelectedIds()
                .then(loadSelectedMembersTable)
                .then(() => availableTable.draw());

            $('#export-selected-form').on('submit', function (e) {
                if (selectedMemberIds.size === 0 && selectedDependentIds.size === 0) {
                    e.preventDefault();
                    if (typeof showToast === 'function') {
                        showToast('error', 'No selected members/dependents to export.');
                    }
                }
            });
        });
    </script>
@endpush
