// Admin panel JavaScript functionality
$(document).ready(function() {

    // Initialize admin dashboard
    if ($('#admin-dashboard').length) {
        loadDashboardStats();
        setInterval(loadDashboardStats, 60000); // Refresh every minute
    }

    // Load dashboard statistics
    function loadDashboardStats() {
        $.ajax({
            url: '../api/admin/get-dashboard-stats.php',
            method: 'GET',
            success: function(response) {
                if (response.success) {
                    updateDashboardStats(response.stats);
                }
            },
            error: function() {
                console.log('Failed to load dashboard stats');
            }
        });
    }

    function updateDashboardStats(stats) {
        $('#total-users').text(stats.total_users || 0);
        $('#active-investments').text(stats.active_investments || 0);
        $('#pending-deposits').text(stats.pending_deposits || 0);
        $('#pending-withdrawals').text(stats.pending_withdrawals || 0);
        $('#total-balance').text('$' + (stats.total_balance || 0).toLocaleString());
        $('#monthly-profit').text('$' + (stats.monthly_profit || 0).toLocaleString());
    }

    // User management
    $('.approve-deposit').on('click', function(e) {
        e.preventDefault();
        const depositId = $(this).data('id');

        if (confirm('Are you sure you want to approve this deposit?')) {
            $.ajax({
                url: '../api/admin/approve-deposit.php',
                method: 'POST',
                data: { id: depositId },
                success: function(response) {
                    if (response.success) {
                        location.reload();
                    } else {
                        alert('Failed to approve deposit: ' + response.message);
                    }
                }
            });
        }
    });

    $('.reject-deposit').on('click', function(e) {
        e.preventDefault();
        const depositId = $(this).data('id');
        const reason = prompt('Reason for rejection:');

        if (reason !== null) {
            $.ajax({
                url: '../api/admin/reject-deposit.php',
                method: 'POST',
                data: { id: depositId, reason: reason },
                success: function(response) {
                    if (response.success) {
                        location.reload();
                    } else {
                        alert('Failed to reject deposit: ' + response.message);
                    }
                }
            });
        }
    });

    $('.approve-withdrawal').on('click', function(e) {
        e.preventDefault();
        const withdrawalId = $(this).data('id');

        if (confirm('Are you sure you want to approve this withdrawal?')) {
            $.ajax({
                url: '../api/admin/approve-withdrawal.php',
                method: 'POST',
                data: { id: withdrawalId },
                success: function(response) {
                    if (response.success) {
                        location.reload();
                    } else {
                        alert('Failed to approve withdrawal: ' + response.message);
                    }
                }
            });
        }
    });

    $('.reject-withdrawal').on('click', function(e) {
        e.preventDefault();
        const withdrawalId = $(this).data('id');
        const reason = prompt('Reason for rejection:');

        if (reason !== null) {
            $.ajax({
                url: '../api/admin/reject-withdrawal.php',
                method: 'POST',
                data: { id: withdrawalId, reason: reason },
                success: function(response) {
                    if (response.success) {
                        location.reload();
                    } else {
                        alert('Failed to reject withdrawal: ' + response.message);
                    }
                }
            });
        }
    });

    // User status toggle
    $('.toggle-user-status').on('click', function(e) {
        e.preventDefault();
        const userId = $(this).data('id');
        const currentStatus = $(this).data('status');
        const newStatus = currentStatus === 'active' ? 'suspended' : 'active';

        if (confirm(`Are you sure you want to ${newStatus} this user?`)) {
            $.ajax({
                url: '../api/admin/toggle-user-status.php',
                method: 'POST',
                data: { id: userId, status: newStatus },
                success: function(response) {
                    if (response.success) {
                        location.reload();
                    } else {
                        alert('Failed to update user status: ' + response.message);
                    }
                }
            });
        }
    });

    // Investment plan management
    $('#add-plan-form').on('submit', function(e) {
        e.preventDefault();

        const formData = new FormData(this);

        $.ajax({
            url: '../api/admin/add-investment-plan.php',
            method: 'POST',
            data: formData,
            processData: false,
            contentType: false,
            success: function(response) {
                if (response.success) {
                    $('#add-plan-modal').hide();
                    location.reload();
                } else {
                    alert('Failed to add plan: ' + response.message);
                }
            }
        });
    });

    $('.edit-plan').on('click', function() {
        const planId = $(this).data('id');
        // Load plan data and show edit modal
        $.ajax({
            url: '../api/admin/get-plan.php',
            method: 'GET',
            data: { id: planId },
            success: function(response) {
                if (response.success) {
                    populateEditForm(response.plan);
                    $('#edit-plan-modal').show();
                }
            }
        });
    });

    $('.delete-plan').on('click', function(e) {
        e.preventDefault();
        const planId = $(this).data('id');

        if (confirm('Are you sure you want to delete this investment plan? This action cannot be undone.')) {
            $.ajax({
                url: '../api/admin/delete-plan.php',
                method: 'POST',
                data: { id: planId },
                success: function(response) {
                    if (response.success) {
                        location.reload();
                    } else {
                        alert('Failed to delete plan: ' + response.message);
                    }
                }
            });
        }
    });

    // Support ticket management
    $('.reply-ticket').on('click', function() {
        const ticketId = $(this).data('id');
        const replyText = $('#reply-text-' + ticketId).val();

        if (!replyText.trim()) {
            alert('Please enter a reply message');
            return;
        }

        $.ajax({
            url: '../api/admin/reply-ticket.php',
            method: 'POST',
            data: { ticket_id: ticketId, message: replyText },
            success: function(response) {
                if (response.success) {
                    location.reload();
                } else {
                    alert('Failed to send reply: ' + response.message);
                }
            }
        });
    });

    $('.close-ticket').on('click', function(e) {
        e.preventDefault();
        const ticketId = $(this).data('id');

        if (confirm('Are you sure you want to close this ticket?')) {
            $.ajax({
                url: '../api/admin/close-ticket.php',
                method: 'POST',
                data: { id: ticketId },
                success: function(response) {
                    if (response.success) {
                        location.reload();
                    } else {
                        alert('Failed to close ticket: ' + response.message);
                    }
                }
            });
        }
    });

    $('.delete-ticket').on('click', function(e) {
        e.preventDefault();
        const ticketId = $(this).data('id');

        if (confirm('Are you sure you want to delete this ticket? This action cannot be undone.')) {
            $.ajax({
                url: '../api/admin/delete-ticket.php',
                method: 'POST',
                data: { id: ticketId },
                success: function(response) {
                    if (response.success) {
                        location.reload();
                    } else {
                        alert('Failed to delete ticket: ' + response.message);
                    }
                }
            });
        }
    });

    // Bulk actions
    $('#select-all').on('change', function() {
        $('.bulk-select').prop('checked', $(this).prop('checked'));
        updateBulkActions();
    });

    $('.bulk-select').on('change', function() {
        updateBulkActions();
    });

    function updateBulkActions() {
        const checkedBoxes = $('.bulk-select:checked');
        if (checkedBoxes.length > 0) {
            $('#bulk-actions').show();
        } else {
            $('#bulk-actions').hide();
        }
    }

    $('#bulk-approve-deposits').on('click', function() {
        const selectedIds = $('.bulk-select:checked').map(function() {
            return $(this).val();
        }).get();

        if (selectedIds.length === 0) {
            alert('Please select deposits to approve');
            return;
        }

        if (confirm(`Are you sure you want to approve ${selectedIds.length} deposits?`)) {
            $.ajax({
                url: '../api/admin/bulk-approve-deposits.php',
                method: 'POST',
                data: { ids: selectedIds },
                success: function(response) {
                    if (response.success) {
                        location.reload();
                    } else {
                        alert('Failed to approve deposits: ' + response.message);
                    }
                }
            });
        }
    });

    // Settings management
    $('.setting-toggle').on('change', function() {
        const settingKey = $(this).data('key');
        const settingValue = $(this).prop('checked') ? '1' : '0';

        $.ajax({
            url: '../api/admin/update-setting.php',
            method: 'POST',
            data: { key: settingKey, value: settingValue },
            success: function(response) {
                if (!response.success) {
                    alert('Failed to update setting: ' + response.message);
                    $(this).prop('checked', !$(this).prop('checked')); // Revert
                }
            }.bind(this)
        });
    });

    // Export functionality
    $('.export-data').on('click', function(e) {
        e.preventDefault();
        const type = $(this).data('type');
        const format = $(this).data('format') || 'csv';

        window.location.href = `../api/admin/export.php?type=${type}&format=${format}`;
    });

    // Real-time notifications for admin
    function loadAdminNotifications() {
        $.ajax({
            url: '../api/admin/get-notifications.php',
            method: 'GET',
            success: function(response) {
                if (response.success) {
                    updateAdminNotificationBadge(response.notifications);
                }
            }
        });
    }

    function updateAdminNotificationBadge(notifications) {
        const unreadCount = notifications.filter(n => !n.is_read).length;
        if (unreadCount > 0) {
            $('.admin-notification-badge').text(unreadCount).show();
        } else {
            $('.admin-notification-badge').hide();
        }
    }

    // Load admin notifications every 30 seconds
    setInterval(loadAdminNotifications, 30000);
    loadAdminNotifications();

    // Modal management
    $('.modal-trigger').on('click', function() {
        const modalId = $(this).data('modal');
        $('#' + modalId).show();
    });

    $('.modal-close, .modal').on('click', function(e) {
        if (e.target === this || $(e.target).hasClass('modal-close')) {
            $(this).closest('.modal').hide();
        }
    });

    // Data table sorting and filtering
    $('.data-table th.sortable').on('click', function() {
        const table = $(this).closest('table');
        const index = $(this).index();
        const currentSort = $(this).data('sort') || 'asc';
        const newSort = currentSort === 'asc' ? 'desc' : 'asc';

        $(this).data('sort', newSort);
        $(this).siblings().removeClass('sort-asc sort-desc');
        $(this).addClass('sort-' + newSort);

        const rows = table.find('tbody tr').toArray().sort((a, b) => {
            const aVal = $(a).find('td').eq(index).text().toLowerCase();
            const bVal = $(b).find('td').eq(index).text().toLowerCase();

            if (newSort === 'asc') {
                return aVal.localeCompare(bVal);
            } else {
                return bVal.localeCompare(aVal);
            }
        });

        table.find('tbody').empty().append(rows);
    });

    // Search functionality
    $('.admin-search').on('input', function() {
        const query = $(this).val().toLowerCase();
        const table = $(this).data('table') || 'tbody';

        $(table + ' tr').each(function() {
            const text = $(this).text().toLowerCase();
            $(this).toggle(text.includes(query));
        });
    });

    console.log('Admin panel JavaScript loaded successfully');
});