@extends('layouts.admin')

@section('title', 'Customer Management')

@section('page-title', 'Customer Management')

@section('content')
<div class="mx-auto max-w-[1200px] flex flex-col gap-6">
    <!-- Actions Panel -->
    <div class="flex flex-col gap-4 rounded-xl border border-gray-200 bg-white p-5 shadow-sm md:flex-row md:items-center md:justify-between">
        <div>
            <h3 class="text-lg font-bold text-gray-900">All Customers</h3>
            <p class="text-sm text-gray-500">Manage and view your client database</p>
        </div>
        <div class="flex gap-3">
            <div class="relative" id="export-dropdown">
                <button type="button" onclick="toggleExportDropdown()" class="inline-flex items-center justify-center gap-2 rounded-lg border border-gray-200 bg-white px-4 py-2.5 text-sm font-medium text-gray-700 hover:bg-gray-50">
                    <span class="material-symbols-outlined text-[20px]">file_download</span>
                    Export
                    <span class="material-symbols-outlined text-[16px] transition-transform" id="export-arrow">expand_more</span>
                </button>
                <div id="export-menu" class="absolute right-0 top-full mt-1 w-48 bg-white rounded-lg shadow-lg border border-gray-200 hidden z-10">
                    @php
                        $exportParams = request()->query();
                        unset($exportParams['ajax']); // Remove ajax parameter for export
                    @endphp
                    <a href="{{ route('admin.customers.export', array_merge($exportParams, ['format' => 'csv'])) }}" class="flex items-center gap-2 px-4 py-2.5 text-sm text-gray-700 hover:bg-gray-50 first:rounded-t-lg">
                        <span class="material-symbols-outlined text-[18px]">description</span>
                        Export as CSV
                    </a>
                    <a href="{{ route('admin.customers.export', array_merge($exportParams, ['format' => 'pdf'])) }}" class="flex items-center gap-2 px-4 py-2.5 text-sm text-gray-700 hover:bg-gray-50 last:rounded-b-lg">
                        <span class="material-symbols-outlined text-[18px]">picture_as_pdf</span>
                        Export as PDF
                    </a>
                </div>
            </div>
            <a href="{{ route('admin.customers.create') }}" class="inline-flex items-center justify-center gap-2 rounded-lg bg-primary px-4 py-2.5 text-sm font-medium text-white shadow-sm hover:bg-blue-600 focus:outline-none focus:ring-2 focus:ring-primary focus:ring-offset-2">
                <span class="material-symbols-outlined text-[20px]">add</span>
                Add New Customer
            </a>
        </div>
    </div>
    
    <!-- Filter & Search Toolbar -->
    <div class="grid gap-4 md:grid-cols-12">
        <div class="md:col-span-5 relative">
            <form id="search-form" method="GET" action="{{ route('admin.customers.index') }}">
                <span class="material-symbols-outlined absolute left-3 top-1/2 -translate-y-1/2 text-[20px] text-gray-400">search</span>
                <input id="search-input" name="search" value="{{ request('search') }}" class="h-11 w-full rounded-lg border border-gray-200 bg-white pl-10 text-sm text-gray-900 placeholder-gray-500 focus:border-primary focus:ring-1 focus:ring-primary" placeholder="Search by name, email, or phone..." type="text"/>
                @if(request('is_active'))
                    <input type="hidden" name="is_active" value="{{ request('is_active') }}">
                @endif
            </form>
        </div>
        <div class="md:col-span-3">
            <div class="relative">
                <form id="filter-form" method="GET" action="{{ route('admin.customers.index') }}">
                    @if(request('search'))
                        <input type="hidden" name="search" value="{{ request('search') }}">
                    @endif
                    <span class="material-symbols-outlined absolute left-3 top-1/2 -translate-y-1/2 text-[20px] text-gray-400">filter_list</span>
                    <select id="status-filter" name="is_active" class="h-11 w-full appearance-none rounded-lg border border-gray-200 bg-white pl-10 pr-8 text-sm text-gray-900 focus:border-primary focus:ring-1 focus:ring-primary">
                        <option value="">Filter by Status</option>
                        <option value="1" {{ request('is_active') == '1' ? 'selected' : '' }}>Active</option>
                        <option value="0" {{ request('is_active') == '0' ? 'selected' : '' }}>Inactive</option>
                    </select>
                    <span class="material-symbols-outlined absolute right-3 top-1/2 -translate-y-1/2 pointer-events-none text-[20px] text-gray-400">expand_more</span>
                </form>
            </div>
        </div>
        <!-- Spacer on large screens -->
        <div class="hidden md:block md:col-span-4"></div>
    </div>
    
    <!-- Data Table Card -->
    <div class="overflow-hidden rounded-xl border border-gray-200 bg-white shadow-sm">
        <div class="overflow-x-auto custom-scrollbar">
            <table class="w-full min-w-[1000px] text-left text-sm">
                <thead class="bg-gray-50 text-xs uppercase text-gray-500">
                    <tr>
                        <th class="px-6 py-4 font-semibold" scope="col">Customer Name</th>
                        <th class="px-6 py-4 font-semibold" scope="col">Email & Phone</th>
                        <th class="px-6 py-4 font-semibold text-center" scope="col">Total Invoices</th>
                        <th class="px-6 py-4 font-semibold text-right" scope="col">Outstanding Balance</th>
                        <th class="px-6 py-4 font-semibold text-center" scope="col">Status</th>
                        <th class="px-6 py-4 font-semibold text-right" scope="col">Actions</th>
                    </tr>
                </thead>
                <tbody id="customers-table-body" class="divide-y divide-gray-100">
                    @include('admin.customers.partials.table-rows', ['customers' => $customers])
                </tbody>
            </table>
        </div>
        <!-- Pagination -->
        <div id="customers-pagination">
            @include('admin.customers.partials.pagination', ['customers' => $customers])
        </div>
    </div>
</div>

<style>
.custom-scrollbar::-webkit-scrollbar {
    height: 8px;
    width: 8px;
}
.custom-scrollbar::-webkit-scrollbar-track {
    background: transparent;
}
.custom-scrollbar::-webkit-scrollbar-thumb {
    background-color: #cbd5e1;
    border-radius: 20px;
}

@media (prefers-color-scheme: dark) {
    .dark\:text-green-400 {
        color: rgb(255 255 255);
    }
}
</style>

<script>
// Export dropdown toggle
function toggleExportDropdown() {
    const menu = document.getElementById('export-menu');
    const arrow = document.getElementById('export-arrow');
    const isHidden = menu.classList.contains('hidden');
    
    // Close all other dropdowns
    document.querySelectorAll('#export-menu').forEach(m => {
        if (m !== menu) {
            m.classList.add('hidden');
        }
    });
    
    if (isHidden) {
        menu.classList.remove('hidden');
        arrow.style.transform = 'rotate(180deg)';
    } else {
        menu.classList.add('hidden');
        arrow.style.transform = 'rotate(0deg)';
    }
}

// Close dropdown when clicking outside
document.addEventListener('click', function(event) {
    const dropdown = document.getElementById('export-dropdown');
    if (dropdown && !dropdown.contains(event.target)) {
        const menu = document.getElementById('export-menu');
        const arrow = document.getElementById('export-arrow');
        menu.classList.add('hidden');
        arrow.style.transform = 'rotate(0deg)';
    }
});

document.addEventListener('DOMContentLoaded', function() {
    const searchInput = document.getElementById('search-input');
    const statusFilter = document.getElementById('status-filter');
    let searchTimeout;

    // AJAX search function
    function performSearch() {
        const searchValue = searchInput.value;
        const statusValue = statusFilter.value;
        const url = new URL('{{ route("admin.customers.index") }}', window.location.origin);
        
        if (searchValue) {
            url.searchParams.append('search', searchValue);
        }
        if (statusValue) {
            url.searchParams.append('is_active', statusValue);
        }
        url.searchParams.append('ajax', '1');

        // Show loading state
        const tableBody = document.getElementById('customers-table-body');
        const pagination = document.getElementById('customers-pagination');
        tableBody.innerHTML = '<tr><td colspan="6" class="px-6 py-8 text-center text-gray-500">Loading...</td></tr>';
        pagination.innerHTML = '';

        fetch(url, {
            method: 'GET',
            headers: {
                'X-Requested-With': 'XMLHttpRequest',
                'Accept': 'application/json',
            }
        })
        .then(response => response.json())
        .then(data => {
            tableBody.innerHTML = data.html;
            pagination.innerHTML = data.pagination;
            
            // Update URL without reload
            window.history.pushState({}, '', url.pathname + url.search);
        })
        .catch(error => {
            console.error('Error:', error);
            tableBody.innerHTML = '<tr><td colspan="6" class="px-6 py-8 text-center text-red-500">Error loading data. Please refresh the page.</td></tr>';
        });
    }

    // Search input with debounce
    searchInput.addEventListener('input', function() {
        clearTimeout(searchTimeout);
        searchTimeout = setTimeout(performSearch, 500);
    });

    // Status filter change
    statusFilter.addEventListener('change', function() {
        performSearch();
    });

    // Handle pagination links (delegate event)
    document.addEventListener('click', function(e) {
        if (e.target.closest('.pagination a')) {
            e.preventDefault();
            const url = e.target.closest('a').href;
            
            const tableBody = document.getElementById('customers-table-body');
            const pagination = document.getElementById('customers-pagination');
            tableBody.innerHTML = '<tr><td colspan="6" class="px-6 py-8 text-center text-gray-500">Loading...</td></tr>';
            pagination.innerHTML = '';

            fetch(url + '&ajax=1', {
                method: 'GET',
                headers: {
                    'X-Requested-With': 'XMLHttpRequest',
                    'Accept': 'application/json',
                }
            })
            .then(response => response.json())
            .then(data => {
                tableBody.innerHTML = data.html;
                pagination.innerHTML = data.pagination;
                window.history.pushState({}, '', url);
            })
            .catch(error => {
                console.error('Error:', error);
                tableBody.innerHTML = '<tr><td colspan="6" class="px-6 py-8 text-center text-red-500">Error loading data. Please refresh the page.</td></tr>';
            });
        }
    });
});

// Delete modal functions
let deleteFormAction = '';

function openDeleteModal(customerId, customerName) {
    deleteFormAction = '{{ route("admin.customers.destroy", ":id") }}'.replace(':id', customerId);
    document.getElementById('delete-form').action = deleteFormAction;
    document.getElementById('delete-customer-name').textContent = customerName;
    document.getElementById('delete-modal').classList.remove('hidden');
    document.body.style.overflow = 'hidden';
}

function closeDeleteModal() {
    document.getElementById('delete-modal').classList.add('hidden');
    document.body.style.overflow = '';
}

// Close modal when clicking outside
document.addEventListener('DOMContentLoaded', function() {
    const deleteModal = document.getElementById('delete-modal');
    if (deleteModal) {
        deleteModal.addEventListener('click', function(e) {
            if (e.target === this) {
                closeDeleteModal();
            }
        });
    }
});
</script>

<!-- Delete Confirmation Modal -->
<div id="delete-modal" data-admin-modal class="hidden fixed inset-0 bg-black/50 z-50 flex items-center justify-center p-4">
    <div class="bg-white rounded-xl shadow-xl max-w-md w-full">
        <div class="p-6">
            <div class="flex items-center gap-4 mb-4">
                <div class="h-12 w-12 rounded-full bg-red-100 flex items-center justify-center">
                    <span class="material-symbols-outlined text-red-600 text-2xl">warning</span>
                </div>
                <div>
                    <h3 class="text-lg font-bold text-gray-900">Delete Customer</h3>
                    <p class="text-sm text-gray-600">This action cannot be undone</p>
                </div>
            </div>
            <p class="text-gray-700 mb-6">
                Are you sure you want to delete <strong id="delete-customer-name"></strong>? This will permanently remove the customer and all associated data.
            </p>
            <form id="delete-form" method="POST" class="flex justify-end gap-3">
                @csrf
                @method('DELETE')
                <button type="button" onclick="closeDeleteModal()" class="px-4 py-2 border border-gray-200 text-gray-700 rounded-lg hover:bg-gray-50 transition-colors">
                    Cancel
                </button>
                <button type="submit" class="px-4 py-2 bg-red-600 text-white rounded-lg hover:bg-red-700 transition-colors">
                    Delete Customer
                </button>
            </form>
        </div>
    </div>
</div>
@endsection
