<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta name="csrf-token" content="{{ csrf_token() }}">
    <title>Agent CRM + Ops Dashboard</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <script src="https://unpkg.com/lucide@latest/dist/umd/lucide.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
    <script defer src="https://unpkg.com/alpinejs@3.x.x/dist/cdn.min.js"></script>
    <style>
        .search-highlight {
            background-color: #fef3c7 !important;
            border-left: 4px solid #f59e0b;
        }
        .search-highlight td {
            font-weight: 500;
        }
    </style>
</head>
<body class="bg-gray-50 min-h-screen">
    <!-- Top Bar -->
    <div class="sticky top-0 z-40 bg-white/80 backdrop-blur border-b">
        <div class="max-w-7xl mx-auto px-4 py-3 flex items-center gap-3">
            <div class="flex items-center gap-2">
                <span class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-gray-100 text-gray-800">MVP</span>
                <h1 class="text-xl font-semibold">Agent CRM + Ops (Laravel)</h1>
                <span class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-blue-100 text-blue-800">Asia/Dhaka</span>
            </div>
            <div class="ml-auto flex items-center gap-2">
                <button class="inline-flex items-center px-3 py-1.5 border border-gray-300 text-sm leading-4 font-medium rounded-md text-gray-700 bg-white hover:bg-gray-50">
                    <i data-lucide="refresh-cw" class="h-4 w-4 mr-1"></i>রিফ্রেশ
                </button>
                <div class="flex gap-2">
                    <button onclick="exportAllClients()" class="inline-flex items-center px-3 py-1.5 border border-gray-300 text-sm leading-4 font-medium rounded-md text-gray-700 bg-white hover:bg-gray-50">
                        <i data-lucide="download" class="h-4 w-4 mr-1"></i>CSV এক্সপোর্ট
                    </button>
                    <button onclick="exportToGoogleSheets()" class="inline-flex items-center px-3 py-1.5 border border-transparent text-sm leading-4 font-medium rounded-md text-white bg-green-600 hover:bg-green-700">
                        <i data-lucide="table" class="h-4 w-4 mr-1"></i>Google Sheets
                    </button>
                </div>
            </div>
        </div>
    </div>

    <!-- Main Content -->
    <div class="max-w-7xl mx-auto px-4 py-6">
        <!-- Success/Error Messages -->
        @if(session('success'))
            <div class="mb-4 bg-green-100 border border-green-400 text-green-700 px-4 py-3 rounded">
                {{ session('success') }}
            </div>
        @endif

        <!-- Advanced Search Bar -->
        <div class="mb-6 bg-white rounded-lg shadow p-4">
            <div class="flex items-center space-x-3">
                <i data-lucide="search" class="h-5 w-5 text-gray-400"></i>
                <input 
                    type="text" 
                    id="advancedSearch" 
                    placeholder="খুঁজুন... নাম, ফোন, স্কোপ, ব্যালেন্স (Real-time Search)" 
                    class="flex-1 px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
                    onkeyup="performAdvancedSearch(this.value)"
                >
                <div class="flex items-center space-x-2 text-sm text-gray-500">
                    <span id="searchResults">{{ $clients->count() }} clients</span>
                    <button onclick="clearAdvancedSearch()" class="text-blue-600 hover:text-blue-800" id="clearSearchBtn" style="display: none;">
                        <i data-lucide="x" class="h-4 w-4"></i> Clear
                    </button>
                </div>
            </div>
            
            <!-- Search Filter Options -->
            <div class="mt-3 flex flex-wrap gap-2 text-sm">
                <span class="text-gray-600">Quick filters:</span>
                <button onclick="searchFilter('low balance')" class="px-2 py-1 bg-red-100 text-red-800 rounded-full hover:bg-red-200">Low Balance</button>
                <button onclick="searchFilter('facebook')" class="px-2 py-1 bg-blue-100 text-blue-800 rounded-full hover:bg-blue-200">Facebook</button>
                <button onclick="searchFilter('consultancy')" class="px-2 py-1 bg-green-100 text-green-800 rounded-full hover:bg-green-200">Consultancy</button>
                <button onclick="searchFilter('active')" class="px-2 py-1 bg-gray-100 text-gray-800 rounded-full hover:bg-gray-200">Active</button>
            </div>
        </div>

        <!-- Advanced Agent Query Section -->
        <div class="mb-6 bg-white rounded-lg shadow p-6">
            <div class="flex items-center space-x-2 mb-4">
                <i data-lucide="bot" class="h-5 w-5 text-blue-600"></i>
                <h3 class="text-lg font-semibold">Agent Query (খুঁজুন)</h3>
                <span class="text-xs bg-blue-100 text-blue-800 px-2 py-1 rounded-full">Advanced</span>
            </div>
            <div class="space-y-4">
                <input 
                    type="text" 
                    id="agentQuery"
                    placeholder="উদাহরণ: 'ফেসবুক ক্লায়েন্টদের ব্যালেন্স দাও' বা 'সবার হোয়াটসঅ্যাপ নাম্বার'" 
                    class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
                >
                <div class="flex gap-2">
                    <button onclick="executeAgentQuery()" class="bg-blue-600 text-white px-4 py-2 rounded hover:bg-blue-700">
                        খুঁজুন (Search)
                    </button>
                    <button onclick="clearAgentResults()" class="bg-gray-500 text-white px-4 py-2 rounded hover:bg-gray-600">
                        Clear
                    </button>
                </div>
            </div>
            
            <div id="agentResults" class="mt-4 hidden">
                <div class="p-4 bg-gray-50 rounded-md">
                    <div class="flex justify-between items-center mb-2">
                        <h4 class="font-medium">Results:</h4>
                        <span id="resultSummary" class="text-sm text-gray-600"></span>
                    </div>
                    <div class="overflow-x-auto">
                        <table id="resultsTable" class="min-w-full">
                            <thead id="resultsHeader">
                                <!-- Dynamic headers -->
                            </thead>
                            <tbody id="resultsBody" class="bg-white divide-y divide-gray-200">
                                <!-- Dynamic results -->
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
            
            <div class="mt-4 text-xs text-gray-500 space-y-1">
                <p><strong>সাপোর্টেড কীওয়ার্ডস:</strong></p>
                <p>• <strong>ফোন/হোয়াটসঅ্যাপ:</strong> ফোন, হোয়াটসঅ্যাপ, phone, whatsapp</p>
                <p>• <strong>ব্যালেন্স:</strong> ব্যালেন্স, balance, কত টাকা বাকি</p>
                <p>• <strong>স্কোপ ফিল্টার:</strong> ফেসবুক, facebook, consultancy, ল্যান্ডিং, website</p>
                <p>• <strong>অর্থ তথ্য:</strong> জমা, deposited, খরচ, spent</p>
            </div>
        </div>

        <!-- Overview Cards & Charts -->
        <div class="grid grid-cols-1 lg:grid-cols-3 gap-6 mb-6">
            <!-- Spending Chart -->
            <div class="lg:col-span-2">
                <div class="bg-white p-6 rounded-lg shadow-lg">
                    <div class="flex items-center justify-between mb-4">
                        <div class="flex items-center space-x-2">
                            <i data-lucide="trending-up" class="h-5 w-5 text-green-600"></i>
                            <h3 class="text-lg font-semibold">৭ দিনের Spend (USD)</h3>
                        </div>
                        <span class="text-xs bg-blue-100 text-blue-800 px-2 py-1 rounded-full">All Clients</span>
                    </div>
                    <div class="h-64">
                        <canvas id="spendingChart"></canvas>
                    </div>
                </div>
            </div>
            
            <!-- Alerts & Digest -->
            <div class="bg-white p-6 rounded-lg shadow-lg">
                <div class="flex items-center space-x-2 mb-4">
                    <i data-lucide="bell" class="h-5 w-5 text-yellow-600"></i>
                    <h3 class="text-lg font-semibold">অ্যালার্ট ও ডাইজেস্ট</h3>
                </div>
                
                <!-- Low Balance Alert Settings -->
                @php
                    $lowBalanceThreshold = session('low_balance_threshold', 50);
                    $lowBalanceClients = $clients->filter(function($client) use ($lowBalanceThreshold) {
                        return ($client->deposited - $client->spent) <= $lowBalanceThreshold;
                    });
                @endphp
                
                <div class="space-y-3 text-sm">
                    <form method="POST" action="{{ route('settings.update') }}" class="space-y-3">
                        @csrf
                        <div class="p-3 rounded-xl border {{ $lowBalanceClients->count() > 0 ? 'bg-red-50 border-red-200' : 'bg-gray-50' }}">
                            <div class="flex items-center justify-between mb-2">
                                <label class="font-medium">Low Balance Threshold:</label>
                                <div class="flex items-center gap-2">
                                    <span>$</span>
                                    <input type="number" name="threshold" value="{{ $lowBalanceThreshold }}" 
                                           class="w-16 px-2 py-1 text-xs border rounded" step="0.01" min="0">
                                    <button type="submit" class="text-xs bg-blue-600 text-white px-2 py-1 rounded hover:bg-blue-700">Save</button>
                                </div>
                            </div>
                            
                            @if($lowBalanceClients->count() > 0)
                                <div class="text-red-700">
                                    <div class="flex items-center gap-1 mb-1">
                                        <i data-lucide="alert-triangle" class="h-3 w-3"></i>
                                        <span class="font-medium">{{ $lowBalanceClients->count() }} Low Balance Alert(s)</span>
                                    </div>
                                    <div class="text-xs space-y-1">
                                        @foreach($lowBalanceClients->take(3) as $client)
                                            <div>• {{ $client->name }}: ${{ number_format($client->deposited - $client->spent, 2) }}</div>
                                        @endforeach
                                        @if($lowBalanceClients->count() > 3)
                                            <div class="text-red-500">... and {{ $lowBalanceClients->count() - 3 }} more</div>
                                        @endif
                                    </div>
                                </div>
                            @else
                                <div class="text-green-700 text-xs">✓ All clients above threshold</div>
                            @endif
                        </div>
                    </form>
                    
                    <!-- Auto Digest Settings -->
                    <form method="POST" action="{{ route('digest.toggle') }}" class="space-y-2">
                        @csrf
                        <div class="flex items-center gap-2">
                            <input type="checkbox" name="auto_digest" id="autoDigest" 
                                   {{ session('auto_digest_enabled', false) ? 'checked' : '' }}
                                   onchange="this.form.submit()"
                                   class="rounded border-gray-300 text-indigo-600">
                            <label for="autoDigest" class="text-sm">সকাল ৯টায় ডেইলি ডাইজেস্ট পাঠাও</label>
                        </div>
                        
                        <div class="text-xs text-gray-500 ml-5">
                            <div>✉ Client balance summary</div>
                            <div>📊 Daily spending overview</div>
                            <div>⚠ Low balance warnings</div>
                        </div>
                    </form>
                    <div class="text-xs text-gray-500">
                        নোট: রিমাইন্ডার/ডাইজেস্ট লাইভ করতে ব্যাকএন্ড/অটোমেশন দরকার হবে।
                    </div>
                </div>
            </div>
        </div>

        <!-- Quick Actions -->
        <div class="grid grid-cols-1 md:grid-cols-3 gap-6 mb-8">
            <!-- Add New Client -->
            <div class="bg-white rounded-lg shadow p-6">
                <h4 class="text-md font-medium text-gray-900 mb-3">Add New Client / নতুন ক্লায়েন্ট</h4>
                <form method="POST" action="{{ route('clients.store') }}" class="space-y-3">
                    @csrf
                    <input type="text" name="name" placeholder="Client Name" required 
                           class="w-full border-gray-300 rounded-md shadow-sm text-sm">
                    <input type="text" name="phone" placeholder="+8801XXXXXXXXX" required
                           class="w-full border-gray-300 rounded-md shadow-sm text-sm">
                    <input type="url" name="fb_page" placeholder="Facebook Page URL"
                           class="w-full border-gray-300 rounded-md shadow-sm text-sm">
                    <button type="submit" class="w-full bg-green-600 text-white py-2 rounded-md hover:bg-green-700 text-sm">
                        <i data-lucide="plus" class="h-4 w-4 inline mr-1"></i>Create Client
                    </button>
                </form>
            </div>

            <!-- Add Funds -->
            <div class="bg-white rounded-lg shadow p-6">
                <h4 class="text-md font-medium text-gray-900 mb-3">Add Funds / টাকা জমা</h4>
                <form method="POST" action="{{ route('wallet.add-funds') }}" class="space-y-3">
                    @csrf
                    <select name="client_id" required class="w-full border-gray-300 rounded-md shadow-sm text-sm">
                        <option value="">Select Client</option>
                        @foreach($clients as $client)
                            <option value="{{ $client->client_id }}">{{ $client->name }}</option>
                        @endforeach
                    </select>
                    <input type="number" name="amount" step="0.01" min="0.01" placeholder="Amount ($)" required
                           class="w-full border-gray-300 rounded-md shadow-sm text-sm">
                    <button type="submit" class="w-full bg-blue-600 text-white py-2 rounded-md hover:bg-blue-700 text-sm">
                        <i data-lucide="wallet" class="h-4 w-4 inline mr-1"></i>Add Funds
                    </button>
                </form>
            </div>

            <!-- Record Spending -->
            <div class="bg-white rounded-lg shadow p-6">
                <h4 class="text-md font-medium text-gray-900 mb-3">Record Spend / খরচ রেকর্ড</h4>
                <form method="POST" action="{{ route('wallet.record-spend') }}" class="space-y-3">
                    @csrf
                    <select name="client_id" required class="w-full border-gray-300 rounded-md shadow-sm text-sm">
                        <option value="">Select Client</option>
                        @foreach($clients as $client)
                            <option value="{{ $client->client_id }}">{{ $client->name }}</option>
                        @endforeach
                    </select>
                    <input type="number" name="amount" step="0.01" min="0.01" placeholder="Amount ($)" required
                           class="w-full border-gray-300 rounded-md shadow-sm text-sm">
                    <input type="date" name="spend_date" value="{{ date('Y-m-d') }}" required
                           class="w-full border-gray-300 rounded-md shadow-sm text-sm">
                    <input type="text" name="note" placeholder="Note (optional)"
                           class="w-full border-gray-300 rounded-md shadow-sm text-sm">
                    <button type="submit" class="w-full bg-red-600 text-white py-2 rounded-md hover:bg-red-700 text-sm">
                        <i data-lucide="minus-circle" class="h-4 w-4 inline mr-1"></i>Record Spend
                    </button>
                </form>
            </div>
        </div>

        <!-- Advanced Schedule Meeting -->
        <div class="mb-8 bg-white rounded-lg shadow p-6">
            <div class="flex items-center space-x-2 mb-4">
                <i data-lucide="calendar" class="h-5 w-5 text-purple-600"></i>
                <h4 class="text-lg font-semibold">Schedule Meeting / মিটিং শিডিউল</h4>
                <span class="text-xs bg-purple-100 text-purple-800 px-2 py-1 rounded-full">Advanced</span>
            </div>
            <form method="POST" action="{{ route('meetings.store') }}" class="space-y-4">
                @csrf
                <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4">
                    <select name="client_id" required class="border-gray-300 rounded-md shadow-sm">
                        <option value="">Select Client</option>
                        @foreach($clients as $client)
                            <option value="{{ $client->client_id }}">{{ $client->name }}</option>
                        @endforeach
                    </select>
                    <input type="text" name="title" placeholder="Meeting Title" required
                           class="border-gray-300 rounded-md shadow-sm">
                    <input type="date" name="meeting_date" value="{{ date('Y-m-d') }}" required
                           class="border-gray-300 rounded-md shadow-sm">
                    <input type="time" name="meeting_time" value="{{ date('H:i') }}" required
                           class="border-gray-300 rounded-md shadow-sm">
                </div>
                
                <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                    <select name="location" class="border-gray-300 rounded-md shadow-sm">
                        <option value="Google Meet">Google Meet</option>
                        <option value="Zoom">Zoom</option>
                        <option value="Microsoft Teams">Microsoft Teams</option>
                        <option value="Phone Call">Phone Call</option>
                        <option value="In-Person">In-Person</option>
                        <option value="WhatsApp">WhatsApp Video</option>
                    </select>
                    
                    <div class="flex items-center space-x-4">
                        <span class="text-sm font-medium text-gray-700">Reminders:</span>
                        <label class="flex items-center space-x-1">
                            <input type="checkbox" name="r1" value="1" checked class="rounded border-gray-300 text-indigo-600">
                            <span class="text-sm">১ দিন আগে</span>
                        </label>
                        <label class="flex items-center space-x-1">
                            <input type="checkbox" name="r2" value="1" checked class="rounded border-gray-300 text-indigo-600">
                            <span class="text-sm">৩ ঘন্টা আগে</span>
                        </label>
                        <label class="flex items-center space-x-1">
                            <input type="checkbox" name="r3" value="1" checked class="rounded border-gray-300 text-indigo-600">
                            <span class="text-sm">৩০ মিনিট আগে</span>
                        </label>
                        <label class="flex items-center space-x-1">
                            <input type="checkbox" name="r4" value="1" class="rounded border-gray-300 text-indigo-600">
                            <span class="text-sm">১০ মিনিট আগে</span>
                        </label>
                    </div>
                </div>
                
                <button type="submit" class="bg-purple-600 text-white px-6 py-2 rounded-md hover:bg-purple-700 flex items-center space-x-2">
                    <i data-lucide="calendar-plus" class="h-4 w-4"></i>
                    <span>Schedule Meeting</span>
                </button>
            </form>
        </div>

        <!-- Metrics Overview -->
        <div class="grid grid-cols-1 md:grid-cols-4 gap-6 mb-8">
            <div class="bg-white rounded-lg shadow p-6">
                <div class="flex items-center">
                    <div class="flex-1">
                        <p class="text-sm font-medium text-gray-500">Total Deposited</p>
                        <p class="text-2xl font-semibold text-gray-900">${{ number_format($totalDeposited, 2) }}</p>
                    </div>
                    <div class="flex-shrink-0">
                        <i data-lucide="wallet" class="h-8 w-8 text-green-500"></i>
                    </div>
                </div>
            </div>

            <div class="bg-white rounded-lg shadow p-6">
                <div class="flex items-center">
                    <div class="flex-1">
                        <p class="text-sm font-medium text-gray-500">Total Spent</p>
                        <p class="text-2xl font-semibold text-gray-900">${{ number_format($totalSpent, 2) }}</p>
                    </div>
                    <div class="flex-shrink-0">
                        <i data-lucide="dollar-sign" class="h-8 w-8 text-red-500"></i>
                    </div>
                </div>
            </div>

            <div class="bg-white rounded-lg shadow p-6">
                <div class="flex items-center">
                    <div class="flex-1">
                        <p class="text-sm font-medium text-gray-500">Current Balance</p>
                        <p class="text-2xl font-semibold text-gray-900">${{ number_format($totalBalance, 2) }}</p>
                    </div>
                    <div class="flex-shrink-0">
                        <i data-lucide="check-circle-2" class="h-8 w-8 text-blue-500"></i>
                    </div>
                </div>
            </div>

            <div class="bg-white rounded-lg shadow p-6">
                <div class="flex items-center">
                    <div class="flex-1">
                        <p class="text-sm font-medium text-gray-500">Active Clients</p>
                        <p class="text-2xl font-semibold text-gray-900">{{ $activeClients }}</p>
                    </div>
                    <div class="flex-shrink-0">
                        <i data-lucide="users" class="h-8 w-8 text-purple-500"></i>
                    </div>
                </div>
            </div>
        </div>

        <!-- Clients Table -->
        <div class="bg-white rounded-lg shadow">
            <div class="px-6 py-4 border-b border-gray-200">
                <h3 class="text-lg font-medium text-gray-900">Client Management / ক্লায়েন্ট ম্যানেজমেন্ট</h3>
                <p class="text-sm text-gray-500">Manage all your clients and their wallet information</p>
            </div>
            <div class="overflow-x-auto">
                <table class="min-w-full divide-y divide-gray-200">
                    <thead class="bg-gray-50">
                        <tr>
                            <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Client ID</th>
                            <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Name / নাম</th>
                            <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Phone</th>
                            <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Status</th>
                            <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Deposited</th>
                            <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Spent</th>
                            <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Balance</th>
                            <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Scopes</th>
                            <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Actions</th>
                        </tr>
                    </thead>
                    <tbody class="bg-white divide-y divide-gray-200" id="clientTableBody">
                        @foreach($clients as $client)
                        <tr data-client-id="{{ $client->client_id }}">
                            <td class="px-6 py-4 whitespace-nowrap text-sm font-medium text-gray-900">{{ $client->client_id }}</td>
                            <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-900">{{ $client->name }}</td>
                            <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-900">{{ $client->phone }}</td>
                            <td class="px-6 py-4 whitespace-nowrap">
                                <span class="inline-flex px-2 py-1 text-xs font-semibold rounded-full 
                                    {{ $client->status === 'Active' ? 'bg-green-100 text-green-800' : 'bg-gray-100 text-gray-800' }}">
                                    {{ $client->status }}
                                </span>
                            </td>
                            <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-900">${{ number_format($client->deposited, 2) }}</td>
                            <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-900">${{ number_format($client->spent, 2) }}</td>
                            <td class="px-6 py-4 whitespace-nowrap text-sm font-medium 
                                {{ $client->balance >= 0 ? 'text-green-600' : 'text-red-600' }}">
                                ${{ number_format($client->balance, 2) }}
                            </td>
                            <td class="px-6 py-4 text-sm text-gray-900">
                                <div class="flex flex-wrap gap-1">
                                    @if($client->scopes)
                                        @foreach($client->scopes as $scope)
                                            <span class="inline-flex items-center gap-1 bg-gradient-to-r from-blue-100 to-blue-50 text-blue-800 text-xs px-2.5 py-1 rounded-full border border-blue-200 hover:bg-blue-200 transition-colors">
                                                <i data-lucide="tag" class="h-3 w-3"></i>
                                                {{ $scope }}
                                                <button onclick="removeScope('{{ $client->client_id }}', '{{ $scope }}')" class="ml-1 text-blue-600 hover:text-red-600 transition-colors">
                                                    <i data-lucide="x" class="h-3 w-3"></i>
                                                </button>
                                            </span>
                                        @endforeach
                                    @endif
                                    <button onclick="addScopeModal('{{ $client->client_id }}')" class="inline-flex items-center gap-1 bg-green-100 text-green-700 text-xs px-2.5 py-1 rounded-full border border-green-200 hover:bg-green-200 transition-colors">
                                        <i data-lucide="plus" class="h-3 w-3"></i>
                                        Add Scope
                                    </button>
                                </div>
                            </td>
                            <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
                                <a href="{{ route('wallet.export-csv', $client->client_id) }}" 
                                   class="text-indigo-600 hover:text-indigo-900 mr-3">
                                    <i data-lucide="download" class="h-4 w-4 inline"></i> CSV
                                </a>
                                <button onclick="copyPortalUrl('{{ $client->client_id }}')" 
                                        class="text-green-600 hover:text-green-900">
                                    <i data-lucide="external-link" class="h-4 w-4 inline"></i> Portal
                                </button>
                            </td>
                        </tr>
                        @endforeach
                    </tbody>
                </table>
            </div>
        </div>
    </div>

    <script>
        // Initialize Lucide icons
        document.addEventListener('DOMContentLoaded', function() {
            lucide.createIcons();
        });
        
        // Reinitialize after dynamic content
        lucide.createIcons();
        
        // Advanced Agent Query Functions
        async function executeAgentQuery() {
            const query = document.getElementById('agentQuery').value.trim();
            if (!query) return;
            
            try {
                const response = await fetch(`/agent-query?q=${encodeURIComponent(query)}`, {
                    headers: {
                        'X-Requested-With': 'XMLHttpRequest'
                    }
                });
                const data = await response.json();
                
                if (data.error) {
                    alert(data.error);
                    return;
                }
                
                displayAgentResults(data);
            } catch (error) {
                console.error('Agent query error:', error);
                alert('Query failed. Please try again.');
            }
        }
        
        function displayAgentResults(data) {
            const resultsDiv = document.getElementById('agentResults');
            const summarySpan = document.getElementById('resultSummary');
            const headerDiv = document.getElementById('resultsHeader');
            const bodyDiv = document.getElementById('resultsBody');
            
            // Show summary
            summarySpan.textContent = data.summary;
            
            // Build dynamic headers
            let headerHtml = '<tr class="bg-gray-200">';
            data.columns.forEach(col => {
                headerHtml += `<th class="px-3 py-2 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">${col.label}</th>`;
            });
            headerHtml += '</tr>';
            headerDiv.innerHTML = headerHtml;
            
            // Build results rows
            let bodyHtml = '';
            data.results.forEach(result => {
                bodyHtml += '<tr>';
                data.columns.forEach(col => {
                    const value = result[col.key] || '';
                    bodyHtml += `<td class="px-3 py-2 whitespace-nowrap text-sm text-gray-900">${value}</td>`;
                });
                bodyHtml += '</tr>';
            });
            bodyDiv.innerHTML = bodyHtml;
            
            resultsDiv.classList.remove('hidden');
        }
        
        function clearAgentResults() {
            document.getElementById('agentQuery').value = '';
            document.getElementById('agentResults').classList.add('hidden');
        }
        
        // Handle Enter key in agent query input
        document.getElementById('agentQuery').addEventListener('keypress', function(e) {
            if (e.key === 'Enter') {
                e.preventDefault();
                executeAgentQuery();
            }
        });
        
        // Initialize 7-day spending chart
        async function initSpendingChart() {
            try {
                const response = await fetch('/spending-chart');
                const data = await response.json();
                
                const ctx = document.getElementById('spendingChart').getContext('2d');
                new Chart(ctx, {
                    type: 'line',
                    data: {
                        labels: data.map(d => d.day),
                        datasets: [{
                            label: 'Spend (USD)',
                            data: data.map(d => d.spend),
                            borderColor: '#0ea5e9',
                            backgroundColor: 'rgba(14, 165, 233, 0.1)',
                            fill: true,
                            tension: 0.4,
                            pointBackgroundColor: '#0ea5e9',
                            pointBorderColor: '#fff',
                            pointBorderWidth: 2,
                            pointRadius: 5
                        }]
                    },
                    options: {
                        responsive: true,
                        maintainAspectRatio: false,
                        plugins: {
                            legend: {
                                display: false
                            }
                        },
                        scales: {
                            y: {
                                beginAtZero: true,
                                grid: {
                                    color: '#f1f5f9'
                                },
                                ticks: {
                                    callback: function(value) {
                                        return '$' + value;
                                    }
                                }
                            },
                            x: {
                                grid: {
                                    display: false
                                }
                            }
                        },
                        elements: {
                            point: {
                                hoverRadius: 8
                            }
                        }
                    }
                });
            } catch (error) {
                console.error('Failed to load spending chart:', error);
            }
        }
        
        // Initialize chart when page loads (removed duplicate)
        // All initialization is now in advanced search section
        
        // Agent Query Functions (Fixed Implementation)
        async function executeAgentQuery() {
            const query = document.getElementById('agentQuery').value.trim();
            if (!query) return;
            
            try {
                const response = await fetch(`/agent-query?q=${encodeURIComponent(query)}`, {
                    headers: {
                        'X-Requested-With': 'XMLHttpRequest',
                        'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').getAttribute('content')
                    }
                });
                const data = await response.json();
                
                if (data.error) {
                    alert(data.error);
                    return;
                }
                
                displayAgentResults(data);
            } catch (error) {
                console.error('Agent query error:', error);
                alert('Query failed. Please try again.');
            }
        }
        
        function displayAgentResults(data) {
            const resultsDiv = document.getElementById('agentResults');
            const summarySpan = document.getElementById('resultSummary');
            const headerDiv = document.getElementById('resultsHeader');
            const bodyDiv = document.getElementById('resultsBody');
            
            // Show summary
            summarySpan.textContent = data.summary;
            
            // Build dynamic headers
            let headerHtml = '<tr class="bg-gray-200">';
            data.columns.forEach(col => {
                headerHtml += `<th class="px-3 py-2 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">${col.label}</th>`;
            });
            headerHtml += '</tr>';
            headerDiv.innerHTML = headerHtml;
            
            // Build results rows
            let bodyHtml = '';
            data.results.forEach(result => {
                bodyHtml += '<tr>';
                data.columns.forEach(col => {
                    const value = result[col.key] || '';
                    bodyHtml += `<td class="px-3 py-2 whitespace-nowrap text-sm text-gray-900">${value}</td>`;
                });
                bodyHtml += '</tr>';
            });
            bodyDiv.innerHTML = bodyHtml;
            
            resultsDiv.classList.remove('hidden');
        }
        
        function clearAgentResults() {
            document.getElementById('agentQuery').value = '';
            document.getElementById('agentResults').classList.add('hidden');
        }
        
        // Export Functions (Google Sheets Integration)
        async function exportAllClients() {
            try {
                const response = await fetch('/export/all-clients-csv', {
                    method: 'GET',
                    headers: {
                        'X-Requested-With': 'XMLHttpRequest'
                    }
                });
                
                if (response.ok) {
                    const blob = await response.blob();
                    const url = window.URL.createObjectURL(blob);
                    const a = document.createElement('a');
                    a.style.display = 'none';
                    a.href = url;
                    a.download = `all_clients_${new Date().toISOString().split('T')[0]}.csv`;
                    document.body.appendChild(a);
                    a.click();
                    window.URL.revokeObjectURL(url);
                    alert('CSV এক্সপোর্ট সম্পূর্ণ হয়েছে!');
                } else {
                    alert('Export failed. Please try again.');
                }
            } catch (error) {
                console.error('Export error:', error);
                alert('Export failed. Please try again.');
            }
        }
        
        async function exportToGoogleSheets() {
            try {
                const response = await fetch('/export/google-sheets', {
                    method: 'POST',
                    headers: {
                        'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').getAttribute('content'),
                        'Content-Type': 'application/json',
                        'X-Requested-With': 'XMLHttpRequest'
                    }
                });
                
                const data = await response.json();
                
                if (data.success) {
                    if (data.sheets_url) {
                        // Open Google Sheets in new tab
                        window.open(data.sheets_url, '_blank');
                        alert('Google Sheets এ export সফল! নতুন ট্যাবে খোলা হচ্ছে।');
                    } else {
                        // Show instructions modal with CSV data
                        showGoogleSheetsModal(data);
                    }
                } else {
                    alert(data.message || 'Google Sheets export failed. Please try again.');
                }
            } catch (error) {
                console.error('Google Sheets export error:', error);
                alert('Google Sheets export failed. Please try again.');
            }
        }
        
        function showGoogleSheetsModal(data) {
            // Create modal
            const modal = document.createElement('div');
            modal.className = 'fixed inset-0 bg-gray-600 bg-opacity-50 overflow-y-auto h-full w-full z-50';
            modal.innerHTML = `
                <div class="relative top-20 mx-auto p-5 border w-11/12 md:w-3/4 lg:w-1/2 shadow-lg rounded-md bg-white">
                    <div class="mt-3">
                        <h3 class="text-lg font-bold text-gray-900 mb-4">Google Sheets Import Instructions</h3>
                        <div class="space-y-3 text-sm text-gray-700">
                            <p><strong>Total Clients:</strong> ${data.total_clients} | <strong>Generated:</strong> ${data.timestamp}</p>
                            <div class="bg-blue-50 p-3 rounded">
                                <h4 class="font-medium text-blue-800 mb-2">Import Steps:</h4>
                                <ol class="list-decimal list-inside space-y-1">
                                    ${data.instructions.map(instruction => `<li>${instruction}</li>`).join('')}
                                </ol>
                            </div>
                            <div>
                                <label class="block font-medium mb-2">CSV Data (Ready to copy):</label>
                                <textarea readonly class="w-full h-32 p-2 border rounded text-xs font-mono" 
                                          id="csvDataTextarea">${data.csv_data}</textarea>
                            </div>
                            <div class="flex gap-2">
                                <button onclick="copyCsvData()" class="bg-green-600 text-white px-4 py-2 rounded hover:bg-green-700 text-sm">
                                    Copy CSV Data
                                </button>
                                <button onclick="closeGoogleSheetsModal()" class="bg-gray-600 text-white px-4 py-2 rounded hover:bg-gray-700 text-sm">
                                    Close
                                </button>
                            </div>
                        </div>
                    </div>
                </div>
            `;
            
            document.body.appendChild(modal);
        }
        
        function copyCsvData() {
            const textarea = document.getElementById('csvDataTextarea');
            textarea.select();
            document.execCommand('copy');
            alert('CSV data copied to clipboard! এখন Google Sheets এ paste করুন।');
        }
        
        function closeGoogleSheetsModal() {
            const modal = document.querySelector('.fixed.inset-0.bg-gray-600');
            if (modal) {
                document.body.removeChild(modal);
            }
        }
        
        // Advanced Search Functions (Real-time)
        let searchTimeout;
        let allClients = []; // Store all client data for filtering
        
        // Initialize search data
        document.addEventListener('DOMContentLoaded', function() {
            initSpendingChart();
            loadClientData();
            
            // Initialize Enter key handler for agent query
            document.getElementById('agentQuery').addEventListener('keypress', function(e) {
                if (e.key === 'Enter') {
                    e.preventDefault();
                    executeAgentQuery();
                }
            });
        });
        
        function loadClientData() {
            // Extract client data from the table for searching
            const clientRows = document.querySelectorAll('#clientTableBody tr[data-client-id]');
            allClients = Array.from(clientRows).map(row => {
                const cells = row.querySelectorAll('td');
                return {
                    element: row,
                    clientId: row.getAttribute('data-client-id'),
                    name: cells[1]?.textContent?.toLowerCase() || '',
                    phone: cells[2]?.textContent?.toLowerCase() || '',
                    fbPage: cells[3]?.textContent?.toLowerCase() || '',
                    status: cells[4]?.textContent?.toLowerCase() || '',
                    deposited: parseFloat(cells[5]?.textContent?.replace(/[^0-9.-]/g, '') || 0),
                    spent: parseFloat(cells[6]?.textContent?.replace(/[^0-9.-]/g, '') || 0),
                    balance: parseFloat(cells[7]?.textContent?.replace(/[^0-9.-]/g, '') || 0),
                    scopes: cells[8]?.textContent?.toLowerCase() || ''
                };
            });
        }
        
        function performAdvancedSearch(query) {
            clearTimeout(searchTimeout);
            searchTimeout = setTimeout(() => {
                executeAdvancedSearch(query);
            }, 300); // Debounce for 300ms
        }
        
        function executeAdvancedSearch(query) {
            const searchTerm = query.toLowerCase().trim();
            const clearBtn = document.getElementById('clearSearchBtn');
            const resultsSpan = document.getElementById('searchResults');
            
            if (!searchTerm) {
                // Show all clients
                allClients.forEach(client => {
                    client.element.style.display = '';
                    client.element.classList.remove('search-highlight');
                });
                resultsSpan.textContent = `${allClients.length} clients`;
                clearBtn.style.display = 'none';
                return;
            }
            
            clearBtn.style.display = 'inline-block';
            
            // Advanced search logic
            let visibleCount = 0;
            allClients.forEach(client => {
                let matches = false;
                
                // Multi-field search
                if (client.name.includes(searchTerm) ||
                    client.phone.includes(searchTerm) ||
                    client.fbPage.includes(searchTerm) ||
                    client.status.includes(searchTerm) ||
                    client.scopes.includes(searchTerm)) {
                    matches = true;
                }
                
                // Special search terms
                if (searchTerm.includes('low') || searchTerm.includes('কম')) {
                    if (client.balance <= 50) matches = true;
                }
                if (searchTerm.includes('high') || searchTerm.includes('বেশি')) {
                    if (client.balance >= 200) matches = true;
                }
                if (searchTerm.includes('balance') || searchTerm.includes('ব্যালেন্স')) {
                    matches = true; // Show all for balance queries
                }
                
                // Numeric search (for balance ranges)
                const numericSearch = parseFloat(searchTerm);
                if (!isNaN(numericSearch)) {
                    if (Math.abs(client.balance - numericSearch) < 10) {
                        matches = true;
                    }
                }
                
                // Show/hide based on match
                if (matches) {
                    client.element.style.display = '';
                    client.element.classList.add('search-highlight');
                    visibleCount++;
                } else {
                    client.element.style.display = 'none';
                    client.element.classList.remove('search-highlight');
                }
            });
            
            resultsSpan.textContent = `${visibleCount} of ${allClientData.length} clients`;
        }
        
        function searchFilter(filterType) {
            document.getElementById('advancedSearch').value = filterType;
            executeAdvancedSearchLogic(filterType);
        }
        
        function clearAdvancedSearch() {
            document.getElementById('advancedSearch').value = '';
            executeAdvancedSearchLogic('');
        }
        
        function copyPortalUrl(clientId) {
            fetch(`/clients/${clientId}/portal-url`)
                .then(response => response.json())
                .then(data => {
                    if (data.portal_url) {
                        navigator.clipboard.writeText(data.portal_url).then(() => {
                            alert('Portal URL copied to clipboard!');
                        });
                    }
                })
                .catch(error => console.error('Error:', error));
        }
        
        // Add Scope Modal Management
        function addScopeModal(clientId) {
            document.getElementById('scopeClientId').value = clientId;
            document.getElementById('addScopeModal').classList.remove('hidden');
        }
        
        function closeScopeModal() {
            document.getElementById('addScopeModal').classList.add('hidden');
            document.getElementById('addScopeForm').reset();
        }
        
        function submitAddScope(event) {
            event.preventDefault();
            const formData = new FormData(event.target);
            
            fetch('/clients/add-scope', {
                method: 'POST',
                headers: {
                    'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').getAttribute('content'),
                    'Accept': 'application/json'
                },
                body: formData
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    closeScopeModal();
                    location.reload(); // Refresh to show new scope with updated icons
                } else {
                    alert('Error adding scope');
                }
            })
            .catch(error => {
                console.error('Error:', error);
                alert('Error adding scope');
            });
        }
        
        function removeScope(clientId, scope) {
            if (!confirm(`Remove "${scope}" scope from this client?`)) return;
            
            fetch('/clients/remove-scope', {
                method: 'POST',
                headers: {
                    'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').getAttribute('content'),
                    'Content-Type': 'application/json',
                    'Accept': 'application/json'
                },
                body: JSON.stringify({
                    client_id: clientId,
                    scope: scope
                })
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    location.reload(); // Refresh to update UI and icons
                } else {
                    alert('Error removing scope');
                }
            })
            .catch(error => {
                console.error('Error:', error);
                alert('Error removing scope');
            });
        }
    </script>

    <!-- Add Scope Modal -->
    <div id="addScopeModal" class="fixed inset-0 bg-gray-600 bg-opacity-50 hidden z-50 flex items-center justify-center">
        <div class="bg-white p-6 rounded-lg shadow-lg max-w-md w-full mx-4">
            <div class="flex justify-between items-center mb-4">
                <h3 class="text-lg font-semibold text-gray-800">Add New Scope</h3>
                <button onclick="closeScopeModal()" class="text-gray-500 hover:text-gray-700">
                    <i data-lucide="x" class="h-5 w-5"></i>
                </button>
            </div>
            <form id="addScopeForm" onsubmit="submitAddScope(event)">
                <input type="hidden" id="scopeClientId" name="client_id">
                <div class="mb-4">
                    <label class="block text-sm font-medium text-gray-700 mb-2">Select Scope:</label>
                    <select name="scope" class="w-full border border-gray-300 rounded-md shadow-sm px-3 py-2" required>
                        <option value="">Choose a scope...</option>
                        <option value="Facebook Marketing">Facebook Marketing</option>
                        <option value="Google Ads">Google Ads</option>
                        <option value="Landing Page">Landing Page</option>
                        <option value="SEO">SEO</option>
                        <option value="Consultancy">Consultancy</option>
                        <option value="Website Development">Website Development</option>
                        <option value="Content Creation">Content Creation</option>
                        <option value="Social Media Management">Social Media Management</option>
                    </select>
                </div>
                <div class="flex justify-end gap-3">
                    <button type="button" onclick="closeScopeModal()" class="px-4 py-2 text-gray-600 border border-gray-300 rounded-md hover:bg-gray-50">
                        Cancel
                    </button>
                    <button type="submit" class="px-4 py-2 bg-blue-600 text-white rounded-md hover:bg-blue-700">
                        Add Scope
                    </button>
                </div>
            </form>
        </div>
    </div>
</body>
</html>