@extends('FrontUser.layouts.app')

@section('title', 'Search')

@section('content')
<div class="search-page">
    <!-- Page Header -->
    <div class="page-header mb-4">
        <div class="d-flex justify-content-between align-items-center">
            <div>
                <h2 class="page-title">Search</h2>
                <p class="page-subtitle">Find your calls and transactions</p>
            </div>
        </div>
    </div>

    <!-- Search Form -->
    <div class="card mb-4">
        <div class="card-body">
            <form id="searchForm" class="search-form">
                <div class="row">
                    <div class="col-md-8">
                        <div class="search-input-wrapper">
                            <input type="text" 
                                   class="form-control search-input" 
                                   id="searchQuery" 
                                   name="q" 
                                   value="{{ $query }}"
                                   placeholder="Search calls, transactions, phone numbers..."
                                   autocomplete="off">
                            <button type="submit" class="search-btn">
                                <i class="fas fa-search"></i>
                            </button>
                        </div>
                    </div>
                    <div class="col-md-4">
                        <select class="form-control" id="searchType" name="type">
                            <option value="all" {{ $type === 'all' ? 'selected' : '' }}>All Results</option>
                            <option value="calls" {{ $type === 'calls' ? 'selected' : '' }}>Calls Only</option>
                            <option value="transactions" {{ $type === 'transactions' ? 'selected' : '' }}>Transactions Only</option>
                        </select>
                    </div>
                </div>
            </form>
        </div>
    </div>

    <!-- Search Results -->
    <div id="searchResults">
        @if(!empty($query))
            <div class="search-results-header mb-3">
                <h5>Search Results for "{{ $query }}"</h5>
                <span class="badge bg-primary">{{ $results['total'] }} results found</span>
            </div>

            @if($results['total'] > 0)
                <!-- Calls Results -->
                @if($results['calls']->count() > 0)
                    <div class="card mb-4">
                        <div class="card-header">
                            <h6 class="mb-0">
                                <i class="fas fa-phone text-primary"></i> 
                                Calls ({{ $results['calls']->count() }})
                            </h6>
                        </div>
                        <div class="card-body">
                            <div class="search-results-list">
                                @foreach($results['calls'] as $call)
                                    <div class="search-result-item">
                                        <div class="result-content">
                                            <h6 class="result-title">
                                                <a href="{{ route('user.calls.show', $call->id) }}">
                                                    Call to {{ $call->phone_number }}
                                                </a>
                                            </h6>
                                            <p class="result-description">
                                                <span class="badge bg-{{ $call->status === 'completed' ? 'success' : ($call->status === 'in_progress' ? 'warning' : 'secondary') }}">
                                                    {{ ucfirst($call->status) }}
                                                </span>
                                                Package: {{ $call->package_name }} | 
                                                Cost: ₹{{ number_format($call->cost, 2) }}
                                            </p>
                                            <small class="result-date text-muted">
                                                <i class="fas fa-clock"></i> {{ $call->created_at->format('M d, Y H:i') }}
                                            </small>
                                        </div>
                                        <div class="result-actions">
                                            <a href="{{ route('user.calls.show', $call->id) }}" class="btn btn-sm btn-outline-primary">
                                                <i class="fas fa-eye"></i> View
                                            </a>
                                        </div>
                                    </div>
                                @endforeach
                            </div>
                        </div>
                    </div>
                @endif

                <!-- Transactions Results -->
                @if($results['transactions']->count() > 0)
                    <div class="card mb-4">
                        <div class="card-header">
                            <h6 class="mb-0">
                                <i class="fas fa-wallet text-success"></i> 
                                Transactions ({{ $results['transactions']->count() }})
                            </h6>
                        </div>
                        <div class="card-body">
                            <div class="search-results-list">
                                @foreach($results['transactions'] as $transaction)
                                    <div class="search-result-item">
                                        <div class="result-content">
                                            <h6 class="result-title">
                                                <a href="{{ route('user.wallet.transactions') }}">
                                                    {{ $transaction->description }}
                                                </a>
                                            </h6>
                                            <p class="result-description">
                                                <span class="badge bg-{{ $transaction->type === 'credit' ? 'success' : 'danger' }}">
                                                    {{ ucfirst($transaction->type) }}
                                                </span>
                                                Amount: ₹{{ number_format($transaction->amount, 2) }} | 
                                                Status: {{ ucfirst($transaction->status) }}
                                            </p>
                                            <small class="result-date text-muted">
                                                <i class="fas fa-clock"></i> {{ $transaction->created_at->format('M d, Y H:i') }}
                                            </small>
                                        </div>
                                        <div class="result-actions">
                                            <a href="{{ route('user.wallet.transactions') }}" class="btn btn-sm btn-outline-primary">
                                                <i class="fas fa-eye"></i> View
                                            </a>
                                        </div>
                                    </div>
                                @endforeach
                            </div>
                        </div>
                    </div>
                @endif
            @else
                <div class="card">
                    <div class="card-body text-center py-5">
                        <i class="fas fa-search text-muted" style="font-size: 48px;"></i>
                        <h5 class="mt-3 text-muted">No results found</h5>
                        <p class="text-muted">Try adjusting your search terms or filters</p>
                    </div>
                </div>
            @endif
        @else
            <div class="card">
                <div class="card-body text-center py-5">
                    <i class="fas fa-search text-muted" style="font-size: 48px;"></i>
                    <h5 class="mt-3 text-muted">Start searching</h5>
                    <p class="text-muted">Enter a search term to find your calls and transactions</p>
                </div>
            </div>
        @endif
    </div>
</div>
@endsection

@section('scripts')
<script>
document.addEventListener('DOMContentLoaded', function() {
    const searchForm = document.getElementById('searchForm');
    const searchInput = document.getElementById('searchQuery');
    const searchType = document.getElementById('searchType');
    const searchResults = document.getElementById('searchResults');

    // Auto-search on input change (debounced)
    let searchTimeout;
    searchInput.addEventListener('input', function() {
        clearTimeout(searchTimeout);
        searchTimeout = setTimeout(() => {
            if (this.value.length >= 2) {
                performSearch();
            } else if (this.value.length === 0) {
                clearResults();
            }
        }, 500);
    });

    // Search on type change
    searchType.addEventListener('change', function() {
        if (searchInput.value.length >= 2) {
            performSearch();
        }
    });

    // Form submission
    searchForm.addEventListener('submit', function(e) {
        e.preventDefault();
        performSearch();
    });

    function performSearch() {
        const query = searchInput.value.trim();
        const type = searchType.value;

        if (query.length < 2) {
            return;
        }

        // Show loading state
        searchResults.innerHTML = `
            <div class="card">
                <div class="card-body text-center py-5">
                    <div class="spinner-border text-primary" role="status">
                        <span class="visually-hidden">Searching...</span>
                    </div>
                    <p class="mt-3 text-muted">Searching...</p>
                </div>
            </div>
        `;

        // Update URL without page reload
        const url = new URL(window.location);
        url.searchParams.set('q', query);
        url.searchParams.set('type', type);
        window.history.pushState({}, '', url);

        // Perform AJAX search
        fetch(`{{ route('user.search') }}?q=${encodeURIComponent(query)}&type=${type}`)
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    displayResults(data.results, query, type);
                } else {
                    showError('Search failed. Please try again.');
                }
            })
            .catch(error => {
                console.error('Search error:', error);
                showError('An error occurred while searching.');
            });
    }

    function displayResults(results, query, type) {
        if (results.length === 0) {
            searchResults.innerHTML = `
                <div class="search-results-header mb-3">
                    <h5>Search Results for "${query}"</h5>
                    <span class="badge bg-secondary">0 results found</span>
                </div>
                <div class="card">
                    <div class="card-body text-center py-5">
                        <i class="fas fa-search text-muted" style="font-size: 48px;"></i>
                        <h5 class="mt-3 text-muted">No results found</h5>
                        <p class="text-muted">Try adjusting your search terms or filters</p>
                    </div>
                </div>
            `;
            return;
        }

        let html = `
            <div class="search-results-header mb-3">
                <h5>Search Results for "${query}"</h5>
                <span class="badge bg-primary">${results.length} results found</span>
            </div>
            <div class="card">
                <div class="card-body">
                    <div class="search-results-list">
        `;

        results.forEach(result => {
            const typeIcon = result.type === 'call' ? 'fas fa-phone text-primary' : 'fas fa-wallet text-success';
            const typeBadge = result.type === 'call' ? 'Call' : 'Transaction';
            
            html += `
                <div class="search-result-item">
                    <div class="result-content">
                        <h6 class="result-title">
                            <a href="${result.url}">${result.title}</a>
                        </h6>
                        <p class="result-description">${result.description}</p>
                        <small class="result-date text-muted">
                            <i class="fas fa-clock"></i> ${result.date}
                        </small>
                    </div>
                    <div class="result-actions">
                        <a href="${result.url}" class="btn btn-sm btn-outline-primary">
                            <i class="fas fa-eye"></i> View
                        </a>
                    </div>
                </div>
            `;
        });

        html += `
                    </div>
                </div>
            </div>
        `;

        searchResults.innerHTML = html;
    }

    function clearResults() {
        searchResults.innerHTML = `
            <div class="card">
                <div class="card-body text-center py-5">
                    <i class="fas fa-search text-muted" style="font-size: 48px;"></i>
                    <h5 class="mt-3 text-muted">Start searching</h5>
                    <p class="text-muted">Enter a search term to find your calls and transactions</p>
                </div>
            </div>
        `;
    }

    function showError(message) {
        searchResults.innerHTML = `
            <div class="card">
                <div class="card-body text-center py-5">
                    <i class="fas fa-exclamation-triangle text-warning" style="font-size: 48px;"></i>
                    <h5 class="mt-3 text-muted">Search Error</h5>
                    <p class="text-muted">${message}</p>
                </div>
            </div>
        `;
    }
});
</script>
@endsection
