@extends('admin.layouts.app')

@section('title', $title)

@section('content')
    <div class="col-md-12">

        @include('admin.layouts.notifications')

        <!-- Page Heading & Search Area -->
        <div class="row mb-3">
            <div class="col-md-9">
                <h4 class="c-grey-900">{{ $title }} <a class="btn btn-primary" href="{{ route('ch-admin.ticket.create') }}"><i class="ti-plus"></i></a></h4>
            </div>

            <div class="col-md-3">
                <form method="GET" action="{{ route('ch-admin.ticket.index') }}">
                    <div class="input-group">
                        <input type="text" name="search" class="form-control" placeholder="Search…" aria-label="Search" value="{{ request('search') }}">
                        <button class="btn btn-info" type="submit"><i class="ti ti-search"></i></button>
                    </div>
                    <!-- Include current filter values as hidden inputs -->
                    <input type="hidden" name="category_id" value="{{ request('category_id') }}">
                    <input type="hidden" name="user_id" value="{{ request('user_id') }}">
                    <input type="hidden" name="status" value="{{ request('status') }}">
                    <input type="hidden" name="priority" value="{{ request('priority') }}">
                </form>
            </div>
        </div>

        <!-- Main Content -->
        <div class="row">
            <div class="bgc-white bd bdrs-3 p-20 mB-20">

                <!-- Filters Section -->
                <div class="row mb-3">
                    <form method="GET" action="{{ route('ch-admin.ticket.index') }}" class="d-flex align-items-center gap-3 w-100">
                        <!-- Filter by Categories -->
                        <div class="flex-shrink-0">
                            <select name="category_id" class="form-control">
                                <option value="">All Categories</option>
                                @foreach($ticketCategories as $ticketCategory)
                                    <option value="{{ $ticketCategory->id }}" {{ request('category_id') == $ticketCategory->id ? 'selected' : '' }}>{{ $ticketCategory->name }}</option>
                                @endforeach
                            </select>
                        </div>

                        <!-- Filter by Author -->
                        <div class="flex-shrink-0">
                            <select name="user_id" class="form-control">
                                <option value="">All Users</option>
                                @foreach($users as $user)
                                    <option value="{{ $user->id }}" {{ request('user_id') == $user->id ? 'selected' : '' }}>
                                        {{ $user->first_name }} {{ $user->last_name }}
                                    </option>
                                @endforeach
                            </select>
                        </div>

                        <!-- Filter by Status -->
                        <div class="flex-shrink-0">
                            <select name="status" class="form-control">
                                <option value="">All Status</option>
                                <option value="Open" {{ request('status') == 'Open' ? 'selected' : '' }}>Open</option>
                                <option value="In Progress" {{ request('status') == 'In Progress' ? 'selected' : '' }}>In Progress</option>
                                <option value="Resolved" {{ request('status') == 'Resolved' ? 'selected' : '' }}>Resolved</option>
                                <option value="Closed" {{ request('status') == 'Closed' ? 'selected' : '' }}>Closed</option>
                            </select>
                        </div>

                        <!-- Filter by Priority -->
                        <div class="flex-shrink-0">
                            <select name="priority" class="form-control">
                                <option value="">All Priorities</option>
                                <option value="Low" {{ request('priority') == 'Low' ? 'selected' : '' }}>Low</option>
                                <option value="Medium" {{ request('priority') == 'Medium' ? 'selected' : '' }}>Medium</option>
                                <option value="High" {{ request('priority') == 'High' ? 'selected' : '' }}>High</option>
                                <option value="Critical" {{ request('priority') == 'Critical' ? 'selected' : '' }}>Critical</option>
                            </select>
                        </div>

                        <!-- Filter / Delete Buttons -->
                        <div class="flex-shrink-0">
                            <button type="submit" class="btn btn-info">Apply Filters</button>
                            @if(request('category_id') || request('user_id') || request('priority') || request('status'))
                                <a href="{{ route('ch-admin.ticket.index') }}" class="btn btn-secondary">Reset</a>
                            @endif
                            <button class="btn btn-danger" id="delete-bulk-btn" type="button" style="display: none"><i class="ti-trash"></i> Delete</button>
                        </div>
                        <input type="hidden" name="search" value="{{ request('search') }}">
                    </form>
                </div>

                <!-- Tickets Table -->
                <div class="row">
                    <table class="table table-striped">
                    <thead>
                    <tr>
                        <th><input type="checkbox" id="select-all" class="form-check-input"></th>
                        <th>ID</th>
                        <th>Subject</th>
                        <th>User</th>
                        <th>Category</th>
                        <th>Status</th>
                        <th>Priority</th>
                        <th>Last Updated</th>
                        <th>Created On</th>
                        <th>Actions</th>
                    </tr>
                    </thead>
                    <tbody>
                    @if($tickets->isEmpty())
                        <tr><td colspan="10" class="text-center">No records found</td></tr>
                    @else
                        @foreach($tickets as $ticket)
                            <tr>
                                <td><input type="checkbox" class="form-check-input select-ticket" value="{{ $ticket->id }}"></td>
                                <td>
                                    <a href="{{ route('ch-admin.ticket.show', $ticket->id) }}" title="View Ticket Details">
                                    {{ $ticket->reference_id }}
                                    </a>
                                </td>
                                <td>{{ $ticket->subject }}</td>
                                <td>{{ $ticket->user->first_name }} {{ $ticket->user->last_name }}</td>
                                <td>{{ $ticket->category ? $ticket->category->name : '' }}</td>
                                <td>
                                    @php
                                        $statusClasses = [
                                            'Open' => 'bg-secondary text-white',
                                            'In Progress' => 'bg-primary text-white',
                                            'Resolved' => 'bg-success text-white',
                                            'Closed' => 'bg-dark text-white'
                                        ];
                                    @endphp
                                    <span class="badge {{ $statusClasses[$ticket->status] ?? 'bg-dark text-white' }}">
                                        {{ $ticket->status }}
                                    </span>
                                </td>
                                <td>
                                    @php
                                        $priorityClasses = [
                                            'Low' => 'bg-secondary text-light',
                                            'Medium' => 'bg-primary text-white',
                                            'High' => 'bg-warning text-dark',
                                            'Critical' => 'bg-danger text-light'
                                        ];
                                    @endphp
                                    <span class="badge {{ $priorityClasses[$ticket->priority] ?? 'bg-danger text-light' }}">
                                        {{ $ticket->priority }}
                                    </span>
                                </td>
                                <td title="{{ $ticket->updated_at->format('h:i A, d-m-Y') }}">{{ $ticket->updated_at->diffForHumans() }}</td>
                                <td title="{{ $ticket->created_at->format('h:i A, d-m-Y') }}">{{ $ticket->created_at->diffForHumans() }}</td>
                                <td>
                                    <div class="d-flex justify-content-start">
                                        <a href="{{ route('ch-admin.ticket.show', $ticket->id) }}" class="btn btn-sm btn-primary me-1" title="View Ticket Details"><i class="ti-eye"></i></a>
                                        <form action="{{ route('ch-admin.ticket.destroy') }}" method="POST" style="display: inline;">
                                            @csrf
                                            @method('DELETE')
                                            <input type="hidden" name="ticket_id" value="{{ $ticket->id }}">
                                            <button type="submit" class="btn btn-sm btn-danger" onclick="return confirm('Are you sure you want to delete this ticket?')"><i class="ti-trash"></i></button>
                                        </form>
                                    </div>
                                </td>
                            </tr>
                        @endforeach
                    @endif
                    </tbody>
                </table>
                </div>

                <!-- Pagination Link -->
                @if($tickets->hasPages())
                    <div class="mt-4">
                        {{ $tickets->links() }}
                    </div>
                @endif
            </div>
        </div>

    </div>
@endsection

@push('scripts')
    <script src="{{url('assets/custom/js/axios.min.js')}}"></script>
    <script>
        const selectAllCheckbox = document.getElementById('select-all');
        const ticketCheckboxes = document.querySelectorAll('.select-ticket');
        const deleteBulkBtn = document.getElementById('delete-bulk-btn');

        selectAllCheckbox.addEventListener('click', function() {
            const isChecked = this.checked;
            ticketCheckboxes.forEach(checkbox => {
                checkbox.checked = isChecked;
            });
            toggleDeleteButton();
        });

        ticketCheckboxes.forEach(checkbox => {
            checkbox.addEventListener('click', function() {
                const allChecked = [...ticketCheckboxes].every(checkbox => checkbox.checked);
                selectAllCheckbox.checked = allChecked;

                if (!this.checked) {
                    selectAllCheckbox.checked = false;
                }

                toggleDeleteButton();
            });
        });

        function toggleDeleteButton() {
            const isChecked = [...ticketCheckboxes].some(checkbox => checkbox.checked);
            deleteBulkBtn.style.display = isChecked ? 'inline-block' : 'none';
        }

        function updateSelectAllCheckbox() {
            const allChecked = [...ticketCheckboxes].every(checkbox => checkbox.checked);
            selectAllCheckbox.checked = allChecked;
        }

        function getSelectedTickets() {
            const selectedTickets = [];
            document.querySelectorAll('.select-ticket:checked').forEach(function (checkbox) {
                selectedTickets.push(checkbox.value);
            });
            return selectedTickets;
        }

        deleteBulkBtn.addEventListener('click', function () {
            const selectedTickets = getSelectedTickets();

            if (selectedTickets.length === 0) {
                alert('Please select at least one ticket.');
                return;
            }

            if (!confirm('Are you sure you want to delete the selected tickets?')) {
                return;
            }

            httpClient.delete('{{ route("ch-admin.ticket.bulk.destroy") }}', {
                data: {
                    tickets: selectedTickets
                }
            })
            .then((response) => {
                if (response.data.success) {
                    window.location.href = '{{ route("ch-admin.ticket.index") }}';
                } else {
                    alert('Failed to delete tickets.');
                }
            })
            .catch((error) => {
                console.error(error);
                alert('An error occurred. Please try again.');
            });
        });

        toggleDeleteButton();
    </script>
@endpush
