<!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>Elite Crypto - Admin Panel</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>

<body class="bg-gray-100">
    <div class="min-h-screen">
        <!-- Header -->
        <header class="bg-gradient-to-r from-blue-600 to-purple-600 text-white shadow-lg">
            <div class="container mx-auto px-4 py-6">
                <h1 class="text-3xl font-bold">🚀 Elite Crypto Investment Bot - Admin Panel</h1>
            </div>
        </header>

        <!-- Stats Cards -->
        <div class="container mx-auto px-4 py-8">
            <div class="grid grid-cols-1 md:grid-cols-3 gap-6 mb-8">
                <div class="bg-white rounded-lg shadow-md p-6">
                    <div class="flex items-center justify-between">
                        <div>
                            <p class="text-gray-500 text-sm">Total Users</p>
                            <h3 class="text-3xl font-bold text-blue-600">{{ $stats['total_users'] }}</h3>
                        </div>
                        <div class="text-4xl">👥</div>
                    </div>
                </div>

                <div class="bg-white rounded-lg shadow-md p-6">
                    <div class="flex items-center justify-between">
                        <div>
                            <p class="text-gray-500 text-sm">Total Investments</p>
                            <h3 class="text-3xl font-bold text-green-600">${{ number_format($stats['total_investments'],
                                2) }}</h3>
                        </div>
                        <div class="text-4xl">💰</div>
                    </div>
                </div>

                <div class="bg-white rounded-lg shadow-md p-6">
                    <div class="flex items-center justify-between">
                        <div>
                            <p class="text-gray-500 text-sm">Pending Investments</p>
                            <h3 class="text-3xl font-bold text-orange-600">{{ $stats['pending_investments'] }}</h3>
                        </div>
                        <div class="text-4xl">⏳</div>
                    </div>
                </div>
            </div>

            <!-- Pending Investments Section -->
            @php
            $pendingInvestments = App\Models\UserInvestment::with('user')
            ->where('status', 'pending')
            ->latest()
            ->get();
            @endphp

            @if($pendingInvestments->count() > 0)
            <div class="bg-white rounded-lg shadow-md p-6 mb-8">
                <h2 class="text-2xl font-bold mb-4 text-gray-800">⏳ Pending Investments ({{ $pendingInvestments->count()
                    }})</h2>

                <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
                    @foreach($pendingInvestments as $investment)
                    <div class="border rounded-lg p-4 bg-gray-50 hover:shadow-lg transition">
                        <div class="mb-3">
                            <h3 class="font-bold text-lg text-gray-800">Investment #{{ $investment->id }}</h3>
                            <p class="text-sm text-gray-600">{{ $investment->created_at->format('d M Y, h:i A') }}</p>
                        </div>

                        <div class="mb-3">
                            <p class="text-sm text-gray-600">User:</p>
                            <p class="font-semibold">{{ $investment->user->first_name }} {{ $investment->user->last_name
                                }}</p>
                            <p class="text-xs text-gray-500">Chat ID: {{ $investment->user->chat_id }}</p>
                        </div>

                        <div class="mb-3">
                            <p class="text-sm text-gray-600">Amount:</p>
                            <p class="text-2xl font-bold text-green-600">${{ number_format($investment->amount, 2) }}
                            </p>
                        </div>

                        @if($investment->transaction_proof)
                        <div class="mb-3">
                            <p class="text-sm text-gray-600 mb-2">Transaction Proof:</p>
                            <button onclick="viewImage('{{ $investment->id }}')"
                                class="w-full bg-blue-100 text-blue-700 px-3 py-2 rounded hover:bg-blue-200 transition text-sm">
                                📷 View Screenshot
                            </button>
                            <input type="hidden" id="proof_{{ $investment->id }}"
                                value="{{ $investment->transaction_proof }}">
                        </div>
                        @endif

                        <div class="flex gap-2 mt-4">
                            <button onclick="approveInvestment({{ $investment->id }})"
                                class="flex-1 bg-green-500 text-white px-4 py-2 rounded hover:bg-green-600 transition font-semibold">
                                ✅ Approve
                            </button>
                            <button onclick="rejectInvestment({{ $investment->id }})"
                                class="flex-1 bg-red-500 text-white px-4 py-2 rounded hover:bg-red-600 transition font-semibold">
                                ❌ Reject
                            </button>
                        </div>
                    </div>
                    @endforeach
                </div>
            </div>
            @endif

            <!-- Send Message Section -->
            <div class="bg-white rounded-lg shadow-md p-6 mb-8">
                <h2 class="text-2xl font-bold mb-4 text-gray-800">📤 Send Message to User</h2>

                <form id="sendMessageForm" enctype="multipart/form-data">
                    <div class="grid grid-cols-1 md:grid-cols-2 gap-4 mb-4">
                        <div>
                            <label class="block text-gray-700 font-semibold mb-2">Chat ID</label>
                            <input type="text" name="chat_id" id="chat_id"
                                class="w-full px-4 py-2 border rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
                                placeholder="Enter user's chat ID" required>
                        </div>

                        <div>
                            <label class="block text-gray-700 font-semibold mb-2">Message Type</label>
                            <select id="messageType"
                                class="w-full px-4 py-2 border rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500">
                                <option value="text">Text Only</option>
                                <option value="photo">Text + Photo</option>
                                <option value="video">Text + Video</option>
                            </select>
                        </div>
                    </div>

                    <div class="mb-4">
                        <label class="block text-gray-700 font-semibold mb-2">Message</label>
                        <textarea name="message" id="message" rows="4"
                            class="w-full px-4 py-2 border rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
                            placeholder="Type your message here..." required></textarea>
                    </div>

                    <div id="photoUpload" class="mb-4 hidden">
                        <label class="block text-gray-700 font-semibold mb-2">Upload Photo</label>
                        <input type="file" name="photo" accept="image/*"
                            class="w-full px-4 py-2 border rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500">
                    </div>

                    <div id="videoUpload" class="mb-4 hidden">
                        <label class="block text-gray-700 font-semibold mb-2">Upload Video</label>
                        <input type="file" name="video" accept="video/*"
                            class="w-full px-4 py-2 border rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500">
                    </div>

                    <button type="submit"
                        class="bg-blue-600 text-white px-6 py-3 rounded-lg hover:bg-blue-700 transition duration-200 font-semibold">
                        📤 Send Message
                    </button>
                </form>

                <div id="messageStatus" class="mt-4"></div>
            </div>

            <!-- Users List -->
            <div class="bg-white rounded-lg shadow-md p-6">
                <h2 class="text-2xl font-bold mb-4 text-gray-800">👥 Users List</h2>

                <div class="overflow-x-auto">
                    <table class="w-full">
                        <thead>
                            <tr class="bg-gray-200">
                                <th class="px-4 py-3 text-left">ID</th>
                                <th class="px-4 py-3 text-left">Name</th>
                                <th class="px-4 py-3 text-left">Chat ID</th>
                                <th class="px-4 py-3 text-left">Username</th>
                                <th class="px-4 py-3 text-left">Investments</th>
                                <th class="px-4 py-3 text-left">Total Amount</th>
                                <th class="px-4 py-3 text-left">Status</th>
                                <th class="px-4 py-3 text-left">Actions</th>
                            </tr>
                        </thead>
                        <tbody>
                            @foreach($users as $user)
                            <tr class="border-b hover:bg-gray-50">
                                <td class="px-4 py-3">{{ $user->id }}</td>
                                <td class="px-4 py-3 font-semibold">{{ $user->first_name }} {{ $user->last_name }}</td>
                                <td class="px-4 py-3">
                                    <code class="bg-gray-100 px-2 py-1 rounded cursor-pointer"
                                        onclick="copyToClipboard('{{ $user->chat_id }}')">
                                        {{ $user->chat_id }}
                                    </code>
                                </td>
                                <td class="px-4 py-3">{{ $user->username ?? 'N/A' }}</td>
                                <td class="px-4 py-3">
                                    <span class="bg-blue-100 text-blue-800 px-2 py-1 rounded">
                                        {{ $user->investments->count() }}
                                    </span>
                                </td>
                                <td class="px-4 py-3 font-semibold text-green-600">
                                    ${{ number_format($user->investments->sum('amount'), 2) }}
                                </td>
                                <td class="px-4 py-3">
                                    @if($user->is_admin)
                                    <span class="bg-purple-100 text-purple-800 px-2 py-1 rounded text-xs font-semibold">
                                        👑 ADMIN
                                    </span>
                                    @elseif($user->is_blocked)
                                    <span class="bg-red-100 text-red-800 px-2 py-1 rounded text-xs font-semibold">
                                        🚫 BLOCKED
                                    </span>
                                    @else
                                    <span class="bg-green-100 text-green-800 px-2 py-1 rounded text-xs font-semibold">
                                        ✅ Active
                                    </span>
                                    @endif
                                </td>
                                <td class="px-4 py-3">
                                    <button onclick="fillChatId('{{ $user->chat_id }}')"
                                        class="bg-blue-500 text-white px-3 py-1 rounded text-sm hover:bg-blue-600 transition">
                                        📤 Message
                                    </button>
                                    @if(!$user->is_admin)
                                    <button onclick="makeAdmin('{{ $user->chat_id }}')"
                                        class="bg-purple-500 text-white px-3 py-1 rounded text-sm hover:bg-purple-600 transition ml-2">
                                        👑 Admin
                                    </button>
                                    @endif
                                </td>
                            </tr>
                            @endforeach
                        </tbody>
                    </table>
                </div>

                <div class="mt-4">
                    {{ $users->links() }}
                </div>
            </div>
        </div>
    </div>

    <!-- Image Modal -->
    <div id="imageModal" class="hidden fixed inset-0 bg-black bg-opacity-75 z-50 flex items-center justify-center p-4">
        <div class="bg-white rounded-lg max-w-4xl w-full p-6 relative">
            <button onclick="closeImageModal()"
                class="absolute top-4 right-4 bg-red-500 text-white px-4 py-2 rounded hover:bg-red-600">
                ✕ Close
            </button>
            <h3 class="text-xl font-bold mb-4">Transaction Proof</h3>
            <div id="imageContainer" class="text-center">
                <p class="text-gray-600">Loading image...</p>
            </div>
        </div>
    </div>

    <script>
        $.ajaxSetup({
            headers: {
                'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
            }
        });

        // Message type toggle
        $('#messageType').change(function() {
            const type = $(this).val();
            $('#photoUpload, #videoUpload').addClass('hidden');
            
            if (type === 'photo') {
                $('#photoUpload').removeClass('hidden');
            } else if (type === 'video') {
                $('#videoUpload').removeClass('hidden');
            }
        });

        // Send message form
        $('#sendMessageForm').submit(function(e) {
            e.preventDefault();
            
            const formData = new FormData(this);
            
            $('#messageStatus').html('<div class="bg-blue-100 text-blue-800 px-4 py-3 rounded">📤 Sending message...</div>');
            
            $.ajax({
                url: '/admin/send-message',
                type: 'POST',
                data: formData,
                processData: false,
                contentType: false,
                success: function(response) {
                    if (response.success) {
                        $('#messageStatus').html('<div class="bg-green-100 text-green-800 px-4 py-3 rounded">✅ ' + response.message + '</div>');
                        $('#sendMessageForm')[0].reset();
                        setTimeout(() => $('#messageStatus').html(''), 3000);
                    } else {
                        $('#messageStatus').html('<div class="bg-red-100 text-red-800 px-4 py-3 rounded">❌ ' + response.message + '</div>');
                    }
                },
                error: function() {
                    $('#messageStatus').html('<div class="bg-red-100 text-red-800 px-4 py-3 rounded">❌ Error sending message!</div>');
                }
            });
        });

        // Approve investment
        function approveInvestment(id) {
            if (!confirm('Are you sure you want to approve this investment?')) {
                return;
            }

            $.post('/admin/approve-investment/' + id, function(response) {
                if (response.success) {
                    alert('✅ ' + response.message);
                    location.reload();
                } else {
                    alert('❌ ' + response.message);
                }
            }).fail(function() {
                alert('❌ Error approving investment!');
            });
        }

        // Reject investment
        function rejectInvestment(id) {
            if (!confirm('Are you sure you want to reject this investment?')) {
                return;
            }

            $.post('/admin/reject-investment/' + id, function(response) {
                if (response.success) {
                    alert('✅ ' + response.message);
                    location.reload();
                } else {
                    alert('❌ ' + response.message);
                }
            }).fail(function() {
                alert('❌ Error rejecting investment!');
            });
        }

        // View transaction proof image
        function viewImage(investmentId) {
            const fileId = $('#proof_' + investmentId).val();
            
            $('#imageModal').removeClass('hidden');
            $('#imageContainer').html('<p class="text-gray-600">Loading image from Telegram...</p>');
            
            // Get file from Telegram
            $.get('/admin/get-telegram-file/' + fileId, function(response) {
                if (response.success) {
                    $('#imageContainer').html(
                        '<img src="' + response.file_url + '" alt="Transaction Proof" class="max-w-full h-auto rounded">'
                    );
                } else {
                    $('#imageContainer').html(
                        '<p class="text-red-600">❌ Error loading image: ' + response.message + '</p>' +
                        '<p class="text-sm text-gray-600 mt-2">File ID: ' + fileId + '</p>'
                    );
                }
            }).fail(function() {
                $('#imageContainer').html(
                    '<p class="text-red-600">❌ Failed to load image from Telegram</p>' +
                    '<p class="text-sm text-gray-600 mt-2">File ID: ' + fileId + '</p>'
                );
            });
        }

        function closeImageModal() {
            $('#imageModal').addClass('hidden');
        }

        function fillChatId(chatId) {
            $('#chat_id').val(chatId);
            $('html, body').animate({
                scrollTop: $("#sendMessageForm").offset().top - 100
            }, 500);
            $('#chat_id').focus();
        }

        function copyToClipboard(text) {
            navigator.clipboard.writeText(text);
            alert('Chat ID copied: ' + text);
        }

        function makeAdmin(chatId) {
            if (!confirm('Are you sure you want to make this user an admin?')) {
                return;
            }

            $.post('/admin/make-admin/' + chatId, function(response) {
                if (response.success) {
                    alert('✅ ' + response.message);
                    location.reload();
                } else {
                    alert('❌ ' + response.message);
                }
            });
        }
    </script>
</body>

</html>