@extends('admin.layouts.app')

@section('content')
    <div class="container-fluid">
        <div class="row">
            <div class="col-12">
                <div class="card">
                    <div class="card-header d-flex align-items-center justify-content-between">
                        <h2 class="mb-0">{{ trans('admin/main.all_users') }}</h2>
                        <div class="d-flex align-items-center">
                            <form method="GET" action="{{ url('/admin/webinars/show-all-users') }}" class="d-flex align-items-center mr-3">
                                <input type="text" name="q" value="{{ $search }}" class="form-control" placeholder="{{ trans('admin/main.search') }}" style="width: 250px;">
                                <input type="hidden" name="selected_ids" value="{{ implode(',', $selectedIds) }}" id="selectedIdsInput">
                                @if(!empty($selectIdentifier))
                                    <input type="hidden" name="select_identifier" value="{{ $selectIdentifier }}">
                                @endif
                                <button type="submit" class="btn btn-primary ml-2">{{ trans('admin/main.search') }}</button>
                            </form>
                            <button type="button" class="btn btn-success" id="applySelectionBtn">
                                <i data-feather="check" width="16" height="16"></i> Apply
                            </button>
                        </div>
                    </div>
                    <div class="card-body">
                        <div class="mb-3">
                            <div class="custom-control custom-checkbox">
                                <input type="checkbox" class="custom-control-input" id="selectAllUsers">
                                <label class="custom-control-label" for="selectAllUsers">
                                    <strong>Select All</strong>
                                </label>
                            </div>
                        </div>
                        <div class="table-responsive" style="max-height: 600px; overflow-y: auto;">
                            <table class="table table-striped">
                                <thead class="thead-light" style="position: sticky; top: 0; z-index: 10; background: white;">
                                    <tr>
                                        <th width="50">{{ trans('admin/main.select') }}</th>
                                        <th>{{ trans('admin/main.name') }}</th>
                                        <th>{{ trans('admin/main.email') }}</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    @if($users->count() > 0)
                                        @foreach($users as $user)
                                            <tr>
                                                <td>
                                                    <div class="custom-control custom-checkbox">
                                                        <input type="checkbox" 
                                                               class="custom-control-input user-checkbox" 
                                                               id="user_{{ $user->id }}" 
                                                               value="{{ $user->id }}"
                                                               @if(in_array($user->id, $selectedIds)) checked @endif>
                                                        <label class="custom-control-label" for="user_{{ $user->id }}"></label>
                                                    </div>
                                                </td>
                                                <td>{{ $user->full_name }}</td>
                                                <td>{{ $user->email }}</td>
                                            </tr>
                                        @endforeach
                                    @else
                                        <tr>
                                            <td colspan="3" class="text-center">{{ trans('admin/main.no_result') }}</td>
                                        </tr>
                                    @endif
                                </tbody>
                            </table>
                        </div>
                        <div class="mt-3">
                            <p class="text-muted">
                                <strong>{{ $users->count() }}</strong> users found
                            </p>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <script>
        (function() {
            // Initialize feather icons
            if (typeof feather !== 'undefined') {
                feather.replace();
            }

            // Get select identifier from URL
            const urlParams = new URLSearchParams(window.location.search);
            const selectIdentifier = urlParams.get('select_identifier') || '';

            // Select all functionality
            const selectAllCheckbox = document.getElementById('selectAllUsers');
            const userCheckboxes = document.querySelectorAll('.user-checkbox');
            const applyBtn = document.getElementById('applySelectionBtn');
            const selectedIdsInput = document.getElementById('selectedIdsInput');

            // Select/Deselect all
            if (selectAllCheckbox) {
                selectAllCheckbox.addEventListener('change', function() {
                    userCheckboxes.forEach(function(checkbox) {
                        checkbox.checked = selectAllCheckbox.checked;
                    });
                    updateSelectedIdsInput();
                });
            }

            // Update individual checkbox
            userCheckboxes.forEach(function(checkbox) {
                checkbox.addEventListener('change', function() {
                    updateSelectAllState();
                    updateSelectedIdsInput();
                });
            });

            // Update select all checkbox state
            function updateSelectAllState() {
                if (selectAllCheckbox && userCheckboxes.length > 0) {
                    const allChecked = Array.from(userCheckboxes).every(function(cb) {
                        return cb.checked;
                    });
                    selectAllCheckbox.checked = allChecked;
                }
            }

            // Update selected IDs input
            function updateSelectedIdsInput() {
                const selectedIds = [];
                userCheckboxes.forEach(function(checkbox) {
                    if (checkbox.checked) {
                        selectedIds.push(checkbox.value);
                    }
                });
                if (selectedIdsInput) {
                    selectedIdsInput.value = selectedIds.join(',');
                }
            }

            // Initialize select all state
            updateSelectAllState();

            // Apply selection button
            if (applyBtn) {
                applyBtn.addEventListener('click', function() {
                    const selectedIds = [];
                    userCheckboxes.forEach(function(checkbox) {
                        if (checkbox.checked) {
                            selectedIds.push(parseInt(checkbox.value));
                        }
                    });

                    console.log('Selected user IDs:', selectedIds);
                    console.log('Select identifier:', selectIdentifier);

                    // Store in localStorage to communicate with parent window
                    const storageKey = 'webinar_selected_users_' + new Date().getTime();
                    localStorage.setItem(storageKey, JSON.stringify({
                        selectedIds: selectedIds,
                        selectIdentifier: selectIdentifier,
                        timestamp: new Date().getTime()
                    }));

                    // Also store in sessionStorage for the parent window
                    if (selectIdentifier) {
                        sessionStorage.setItem('lastSelectIdentifier', selectIdentifier);
                    }

                    // Send message to parent window if it exists
                    if (window.opener && !window.opener.closed) {
                        window.opener.postMessage({
                            type: 'users_selected',
                            selectedIds: selectedIds,
                            selectIdentifier: selectIdentifier,
                            storageKey: storageKey
                        }, '*');
                    }

                    // Show success message
                    alert('Users selected successfully: ' + selectedIds.length);
                    
                    // Close the window after a short delay
                    setTimeout(function() {
                        window.close();
                    }, 1000);
                });
            }
        })();
    </script>
@endsection

