<?php
// modals/user_modals.php
// This file contains modals for user management operations
?>

<!-- Modal for Changing User Status -->
<div class="modal fade" id="statusModal" tabindex="-1" aria-labelledby="statusModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <form method="POST">
                <div class="modal-header">
                    <h5 class="modal-title" id="statusModalLabel">Change User Status</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <input type="hidden" name="action_type" value="update_status">
                    <input type="hidden" name="user_id" id="statusUserId">
                    
                    <div class="mb-3">
                        <label class="form-label">New Status <span class="text-danger">*</span></label>
                        <select class="form-control" name="status" required>
                            <option value="verified">✅ Verified</option>
                            <option value="pending">⏳ Pending</option>
                            <option value="rejected">❌ Rejected</option>
                        </select>
                        <small class="text-mute">Changing status will trigger email notification</small>
                    </div>
                    
                    <div class="mb-3">
                        <label class="form-label">Reason for Status Change</label>
                        <textarea class="form-control" name="reason" rows="3" placeholder="Enter reason for status change (optional but recommended)..." maxlength="500"></textarea>
                        <small class="text-mute">Maximum 500 characters</small>
                    </div>
                    
                    <div class="mb-3">
                        <label class="form-label">Send Notification Email</label>
                        <div class="form-check">
                            <input class="form-check-input" type="checkbox" name="send_email" id="sendEmail" checked>
                            <label class="form-check-label" for="sendEmail">
                                Send email notification to user
                            </label>
                        </div>
                    </div>
                    
                    <div class="mb-3">
                        <label class="form-label">Admin PIN <span class="text-danger">*</span></label>
                        <div class="input-group">
                            <input type="password" class="form-control" name="admin_pin" required placeholder="Enter your 4-digit PIN" maxlength="4" pattern="\d{4}">
                            <button type="button" class="btn btn-outline-secondary" onclick="togglePinVisibility(this)">
                                <i class="fas fa-eye"></i>
                            </button>
                        </div>
                        <small class="text-mute">Required for security confirmation (4 digits)</small>
                    </div>
                    
                    <div class="alert alert-warning">
                        <i class="fas fa-exclamation-triangle me-2"></i>
                        <strong>Warning:</strong> Changing user status may affect their ability to deposit, withdraw, or use trading bots.
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">
                        <i class="fas fa-times me-1"></i> Cancel
                    </button>
                    <button type="submit" class="btn btn-primary">
                        <i class="fas fa-save me-1"></i> Update Status
                    </button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- Modal for Adjusting User Balance -->
<div class="modal fade" id="balanceModal" tabindex="-1" aria-labelledby="balanceModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <form method="POST">
                <div class="modal-header">
                    <h5 class="modal-title" id="balanceModalLabel">Adjust User Balance</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <input type="hidden" name="action_type" value="update_balance">
                    <input type="hidden" name="user_id" id="balanceUserId">
                    
                    <div class="row mb-3">
                        <div class="col-md-6">
                            <div class="form-group">
                                <label class="form-label">Current Balance</label>
                                <div class="input-group">
                                    <span class="input-group-text">$</span>
                                    <input type="text" class="form-control" id="currentBalance" readonly style="background-color: #f8f9fa;">
                                </div>
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="form-group">
                                <label class="form-label">Available Balance</label>
                                <div class="input-group">
                                    <span class="input-group-text">$</span>
                                    <input type="text" class="form-control" id="availableBalance" readonly style="background-color: #f8f9fa;">
                                </div>
                            </div>
                        </div>
                    </div>
                    
                    <div class="mb-3">
                        <label class="form-label">Action <span class="text-danger">*</span></label>
                        <div class="btn-group w-100" role="group">
                            <input type="radio" class="btn-check" name="balance_type" id="addFunds" value="add" checked>
                            <label class="btn btn-outline-success" for="addFunds">
                                <i class="fas fa-plus-circle me-1"></i> Add Funds
                            </label>
                            
                            <input type="radio" class="btn-check" name="balance_type" id="deductFunds" value="deduct">
                            <label class="btn btn-outline-danger" for="deductFunds">
                                <i class="fas fa-minus-circle me-1"></i> Deduct Funds
                            </label>
                        </div>
                    </div>
                    
                    <div class="mb-3">
                        <label class="form-label">Amount ($) <span class="text-danger">*</span></label>
                        <div class="input-group">
                            <span class="input-group-text">$</span>
                            <input type="number" class="form-control" name="amount" step="0.01" min="0.01" required placeholder="0.00">
                            <span class="input-group-text">.00</span>
                        </div>
                        <small class="text-mute">Minimum amount: $0.01</small>
                    </div>
                    
                    <div class="mb-3">
                        <label class="form-label">Transaction Type</label>
                        <select class="form-control" name="transaction_type">
                            <option value="manual_adjustment">Manual Adjustment</option>
                            <option value="bonus">Bonus Payment</option>
                            <option value="refund">Refund</option>
                            <option value="correction">Balance Correction</option>
                            <option value="other">Other</option>
                        </select>
                    </div>
                    
                    <div class="mb-3">
                        <label class="form-label">Description / Note <span class="text-danger">*</span></label>
                        <textarea class="form-control" name="note" rows="3" required placeholder="Enter detailed reason for this balance adjustment..."></textarea>
                        <small class="text-mute">This note will appear in the transaction history</small>
                    </div>
                    
                    <div class="mb-3">
                        <label class="form-label">Admin PIN <span class="text-danger">*</span></label>
                        <div class="input-group">
                            <input type="password" class="form-control" name="admin_pin" required placeholder="Enter your 4-digit PIN" maxlength="4" pattern="\d{4}">
                            <button type="button" class="btn btn-outline-secondary" onclick="togglePinVisibility(this)">
                                <i class="fas fa-eye"></i>
                            </button>
                        </div>
                        <small class="text-mute">Required for security confirmation (4 digits)</small>
                    </div>
                    
                    <div class="alert alert-info">
                        <i class="fas fa-info-circle me-2"></i>
                        <strong>Note:</strong> This adjustment will be recorded in the transaction history and will affect both total and available balance.
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">
                        <i class="fas fa-times me-1"></i> Cancel
                    </button>
                    <button type="submit" class="btn btn-primary">
                        <i class="fas fa-check-circle me-1"></i> Confirm Adjustment
                    </button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- Modal for Bulk User Actions -->
<div class="modal fade" id="bulkActionModal" tabindex="-1" aria-labelledby="bulkActionModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <form method="POST" id="bulkActionForm">
                <div class="modal-header">
                    <h5 class="modal-title" id="bulkActionModalLabel">Bulk User Action</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <input type="hidden" name="action_type" id="bulkActionType">
                    <input type="hidden" name="user_ids" id="bulkUserIds">
                    
                    <div class="mb-3">
                        <label class="form-label">Selected Users</label>
                        <div class="alert alert-light">
                            <i class="fas fa-users me-2"></i>
                            <span id="selectedUsersCount">0</span> user(s) selected
                        </div>
                    </div>
                    
                    <div class="mb-3">
                        <label class="form-label">Action <span class="text-danger">*</span></label>
                        <select class="form-control" name="bulk_action" id="bulkActionSelect" required>
                            <option value="">-- Select Action --</option>
                            <option value="verify">Verify Selected Users</option>
                            <option value="reject">Reject Selected Users</option>
                            <option value="pending">Mark as Pending</option>
                            <option value="export">Export Selected Users</option>
                            <option value="send_email">Send Email to Selected</option>
                        </select>
                    </div>
                    
                    <div id="bulkActionExtraFields" style="display: none;">
                        <!-- Additional fields will be shown here based on selected action -->
                    </div>
                    
                    <div class="mb-3">
                        <label class="form-label">Admin PIN <span class="text-danger">*</span></label>
                        <div class="input-group">
                            <input type="password" class="form-control" name="admin_pin" required placeholder="Enter your 4-digit PIN" maxlength="4" pattern="\d{4}">
                            <button type="button" class="btn btn-outline-secondary" onclick="togglePinVisibility(this)">
                                <i class="fas fa-eye"></i>
                            </button>
                        </div>
                        <small class="text-mute">Required for security confirmation</small>
                    </div>
                    
                    <div class="alert alert-warning">
                        <i class="fas fa-exclamation-triangle me-2"></i>
                        This action will affect all selected users. Please review carefully before proceeding.
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">
                        <i class="fas fa-times me-1"></i> Cancel
                    </button>
                    <button type="submit" class="btn btn-primary" id="bulkActionSubmit">
                        <i class="fas fa-play me-1"></i> Execute Action
                    </button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- Modal for Viewing User Activity Logs -->
<div class="modal fade" id="activityLogModal" tabindex="-1" aria-labelledby="activityLogModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="activityLogModalLabel">User Activity Logs</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <div class="text-center" id="activityLogLoader">
                    <div class="spinner-border text-primary" role="status">
                        <span class="visually-hidden">Loading...</span>
                    </div>
                    <p class="mt-2">Loading activity logs...</p>
                </div>
                <div id="activityLogContent" style="display: none;">
                    <!-- Activity logs will be loaded here -->
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">
                    <i class="fas fa-times me-1"></i> Close
                </button>
            </div>
        </div>
    </div>
</div>

<!-- Modal for KYC Document Preview -->
<div class="modal fade" id="kycPreviewModal" tabindex="-1" aria-labelledby="kycPreviewModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-xl">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="kycPreviewModalLabel">KYC Document Preview</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body text-center">
                <div id="kycDocumentContainer">
                    <!-- Document will be loaded here -->
                </div>
            </div>
            <div class="modal-footer">
                <div class="me-auto">
                    <span class="badge bg-secondary" id="kycDocumentType"></span>
                    <span class="badge bg-info ms-2" id="kycDocumentStatus"></span>
                </div>
                <a href="#" class="btn btn-success" id="verifyKycBtn" onclick="verifyKycDocument()">
                    <i class="fas fa-check me-1"></i> Verify Document
                </a>
                <a href="#" class="btn btn-danger" id="rejectKycBtn" onclick="rejectKycDocument()">
                    <i class="fas fa-times me-1"></i> Reject Document
                </a>
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">
                    <i class="fas fa-times me-1"></i> Close
                </button>
            </div>
        </div>
    </div>
</div>

<!-- Modal for Quick User Notes -->
<div class="modal fade" id="userNotesModal" tabindex="-1" aria-labelledby="userNotesModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <form method="POST" id="userNotesForm">
                <div class="modal-header">
                    <h5 class="modal-title" id="userNotesModalLabel">Add User Note</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <input type="hidden" name="action_type" value="add_note">
                    <input type="hidden" name="user_id" id="noteUserId">
                    
                    <div class="mb-3">
                        <label class="form-label">Note Type</label>
                        <select class="form-control" name="note_type">
                            <option value="general">General Note</option>
                            <option value="warning">Warning</option>
                            <option value="support">Support Note</option>
                            <option value="verification">Verification Note</option>
                            <option value="internal">Internal Note</option>
                        </select>
                    </div>
                    
                    <div class="mb-3">
                        <label class="form-label">Note <span class="text-danger">*</span></label>
                        <textarea class="form-control" name="note" rows="5" required placeholder="Enter your note here..."></textarea>
                        <small class="text-mute">This note will be visible to all admins</small>
                    </div>
                    
                    <div class="mb-3">
                        <label class="form-label">Priority</label>
                        <div class="form-check">
                            <input class="form-check-input" type="checkbox" name="high_priority" id="highPriority">
                            <label class="form-check-label text-danger" for="highPriority">
                                <i class="fas fa-exclamation-circle me-1"></i> High Priority
                            </label>
                        </div>
                    </div>
                    
                    <div class="mb-3">
                        <label class="form-label">Admin PIN (Optional)</label>
                        <input type="password" class="form-control" name="admin_pin" placeholder="Enter PIN if adding sensitive info">
                        <small class="text-mute">PIN only required for sensitive information</small>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">
                        <i class="fas fa-times me-1"></i> Cancel
                    </button>
                    <button type="submit" class="btn btn-primary">
                        <i class="fas fa-save me-1"></i> Save Note
                    </button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- Modal for Send Email to User -->
<div class="modal fade" id="sendEmailModal" tabindex="-1" aria-labelledby="sendEmailModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <form method="POST" id="sendEmailForm">
                <div class="modal-header">
                    <h5 class="modal-title" id="sendEmailModalLabel">Send Email to User</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <input type="hidden" name="action_type" value="send_email">
                    <input type="hidden" name="user_id" id="emailUserId">
                    <input type="hidden" name="user_email" id="userEmail">
                    
                    <div class="mb-3">
                        <label class="form-label">Recipient</label>
                        <input type="text" class="form-control" id="recipientEmail" readonly style="background-color: #f8f9fa;">
                    </div>
                    
                    <div class="mb-3">
                        <label class="form-label">Subject <span class="text-danger">*</span></label>
                        <input type="text" class="form-control" name="subject" required placeholder="Email subject...">
                    </div>
                    
                    <div class="mb-3">
                        <label class="form-label">Email Template</label>
                        <select class="form-control" name="email_template" onchange="loadEmailTemplate(this.value)">
                            <option value="">-- Custom Message --</option>
                            <option value="welcome">Welcome Email</option>
                            <option value="verification">Verification Approved</option>
                            <option value="rejection">Verification Rejected</option>
                            <option value="deposit">Deposit Received</option>
                            <option value="withdrawal">Withdrawal Processed</option>
                            <option value="warning">Account Warning</option>
                        </select>
                    </div>
                    
                    <div class="mb-3">
                        <label class="form-label">Message <span class="text-danger">*</span></label>
                        <textarea class="form-control" name="message" rows="8" required placeholder="Type your message here..."></textarea>
                        <small class="text-mute">You can use variables like {username}, {first_name}, {last_name}</small>
                    </div>
                    
                    <div class="mb-3">
                        <label class="form-label">Admin PIN <span class="text-danger">*</span></label>
                        <input type="password" class="form-control" name="admin_pin" required placeholder="Enter your 4-digit PIN">
                        <small class="text-mute">Required for sending emails</small>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">
                        <i class="fas fa-times me-1"></i> Cancel
                    </button>
                    <button type="submit" class="btn btn-primary">
                        <i class="fas fa-paper-plane me-1"></i> Send Email
                    </button>
                </div>
            </form>
        </div>
    </div>
</div>


<!-- Modal for Changing User Status -->
<div class="modal fade" id="statusModal" tabindex="-1" aria-labelledby="statusModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <form method="POST" action="view_user.php?id=<?php echo $user_id; ?>">
                <div class="modal-header">
                    <h5 class="modal-title" id="statusModalLabel">Change User Status</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <input type="hidden" name="action_type" value="update_status">
                    <input type="hidden" name="user_id" value="<?php echo $user_id; ?>">
                    
                    <div class="mb-3">
                        <label class="form-label">New Status</label>
                        <select class="form-control" name="status" required>
                            <option value="verified" <?php echo $user['status'] == 'verified' ? 'selected' : ''; ?>>Verified</option>
                            <option value="pending" <?php echo $user['status'] == 'pending' ? 'selected' : ''; ?>>Pending</option>
                            <option value="rejected" <?php echo $user['status'] == 'rejected' ? 'selected' : ''; ?>>Rejected</option>
                        </select>
                    </div>
                    
                    <div class="mb-3">
                        <label class="form-label">Reason (Optional)</label>
                        <textarea class="form-control" name="reason" rows="3" placeholder="Enter reason for status change..."></textarea>
                    </div>
                    
                    <div class="mb-3">
                        <label class="form-label">Admin PIN <span class="text-danger">*</span></label>
                        <input type="password" class="form-control" name="admin_pin" required placeholder="Enter your 4-digit PIN">
                        <small class="text-mute">Required for security confirmation</small>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                    <button type="submit" class="btn btn-primary">Update Status</button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- Modal for Adjusting Balance -->
<div class="modal fade" id="balanceModal" tabindex="-1" aria-labelledby="balanceModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <form method="POST" action="view_user.php?id=<?php echo $user_id; ?>">
                <div class="modal-header">
                    <h5 class="modal-title" id="balanceModalLabel">Adjust User Balance</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <input type="hidden" name="action_type" value="update_balance">
                    <input type="hidden" name="user_id" value="<?php echo $user_id; ?>">
                    
                    <div class="mb-3">
                        <label class="form-label">Action</label>
                        <select class="form-control" name="balance_type" required>
                            <option value="add">Add Funds</option>
                            <option value="deduct">Deduct Funds</option>
                        </select>
                    </div>
                    
                    <div class="mb-3">
                        <label class="form-label">Amount ($)</label>
                        <input type="number" class="form-control" name="amount" step="0.01" min="0.01" required placeholder="0.00">
                    </div>
                    
                    <div class="mb-3">
                        <label class="form-label">Note (Optional)</label>
                        <textarea class="form-control" name="note" rows="3" placeholder="Enter reason for balance adjustment..."></textarea>
                    </div>
                    
                    <div class="mb-3">
                        <label class="form-label">Admin PIN <span class="text-danger">*</span></label>
                        <input type="password" class="form-control" name="admin_pin" required placeholder="Enter your 4-digit PIN">
                        <small class="text-mute">Required for security confirmation</small>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                    <button type="submit" class="btn btn-primary">Update Balance</button>
                </div>
            </form>
        </div>
    </div>
</div>


<!-- JavaScript for Modal Functions -->
<script>
// Toggle PIN visibility
function togglePinVisibility(button) {
    const input = button.parentElement.querySelector('input');
    const icon = button.querySelector('i');
    
    if (input.type === 'password') {
        input.type = 'text';
        icon.classList.remove('fa-eye');
        icon.classList.add('fa-eye-slash');
    } else {
        input.type = 'password';
        icon.classList.remove('fa-eye-slash');
        icon.classList.add('fa-eye');
    }
}

// Status Modal Event
$('#statusModal').on('show.bs.modal', function (event) {
    var button = $(event.relatedTarget);
    var userId = button.data('user-id');
    var currentStatus = button.data('current-status') || 'pending';
    var modal = $(this);
    
    modal.find('#statusUserId').val(userId);
    modal.find('select[name="status"]').val(currentStatus);
    modal.find('.modal-title').text('Change Status for User #' + userId);
});

// Balance Modal Event
$('#balanceModal').on('show.bs.modal', function (event) {
    var button = $(event.relatedTarget);
    var userId = button.data('user-id');
    var currentBalance = button.data('current-balance') || '0.00';
    var availableBalance = button.data('available-balance') || '0.00';
    var modal = $(this);
    
    modal.find('#balanceUserId').val(userId);
    modal.find('#currentBalance').val('$' + parseFloat(currentBalance).toFixed(2));
    modal.find('#availableBalance').val('$' + parseFloat(availableBalance).toFixed(2));
    modal.find('.modal-title').text('Adjust Balance for User #' + userId);
    
    // Clear form
    modal.find('input[name="amount"]').val('');
    modal.find('textarea[name="note"]').val('');
    modal.find('input[name="admin_pin"]').val('');
});

// Bulk Action Modal Event
$('#bulkActionModal').on('show.bs.modal', function (event) {
    var selectedUsers = [];
    $('.user-checkbox:checked').each(function() {
        selectedUsers.push($(this).val());
    });
    
    if (selectedUsers.length === 0) {
        Swal.fire({
            icon: 'warning',
            title: 'No Users Selected',
            text: 'Please select at least one user to perform bulk action.',
            confirmButtonColor: '#3085d6'
        });
        return false;
    }
    
    var modal = $(this);
    modal.find('#selectedUsersCount').text(selectedUsers.length);
    modal.find('#bulkUserIds').val(selectedUsers.join(','));
    
    // Reset form
    modal.find('#bulkActionSelect').val('');
    modal.find('#bulkActionExtraFields').hide().html('');
});

// Bulk action selection change
$('#bulkActionSelect').on('change', function() {
    var action = $(this).val();
    var extraFields = $('#bulkActionExtraFields');
    
    if (action === '') {
        extraFields.hide().html('');
        return;
    }
    
    var fieldsHtml = '';
    
    switch(action) {
        case 'verify':
        case 'reject':
        case 'pending':
            fieldsHtml = `
                <div class="mb-3">
                    <label class="form-label">Reason (Optional)</label>
                    <textarea class="form-control" name="reason" rows="3" placeholder="Enter reason for status change..."></textarea>
                </div>
                <div class="form-check mb-3">
                    <input class="form-check-input" type="checkbox" name="send_email" id="bulkSendEmail" checked>
                    <label class="form-check-label" for="bulkSendEmail">
                        Send email notification to users
                    </label>
                </div>
            `;
            break;
            
        case 'send_email':
            fieldsHtml = `
                <div class="mb-3">
                    <label class="form-label">Email Subject <span class="text-danger">*</span></label>
                    <input type="text" class="form-control" name="email_subject" required>
                </div>
                <div class="mb-3">
                    <label class="form-label">Email Message <span class="text-danger">*</span></label>
                    <textarea class="form-control" name="email_message" rows="5" required></textarea>
                    <small class="text-mute">Use {username} to insert username dynamically</small>
                </div>
            `;
            break;
    }
    
    extraFields.html(fieldsHtml).show();
});

// View Activity Logs
function viewUserActivity(userId) {
    $('#activityLogModal').modal('show');
    
    $.ajax({
        url: 'ajax/get_user_activities.php',
        type: 'GET',
        data: { user_id: userId },
        beforeSend: function() {
            $('#activityLogLoader').show();
            $('#activityLogContent').hide();
        },
        success: function(response) {
            $('#activityLogLoader').hide();
            $('#activityLogContent').html(response).show();
        },
        error: function() {
            $('#activityLogLoader').html('<div class="alert alert-danger">Failed to load activity logs</div>');
        }
    });
}

// View KYC Document
function viewKycDocument(docId, docType, docPath, docStatus) {
    $('#kycPreviewModal').modal('show');
    
    var container = $('#kycDocumentContainer');
    var typeBadge = $('#kycDocumentType');
    var statusBadge = $('#kycDocumentStatus');
    
    // Update badges
    typeBadge.text(docType.replace('_', ' ').toUpperCase());
    statusBadge.text(docStatus.toUpperCase());
    
    // Clear container and show loading
    container.html(`
        <div class="text-center py-5">
            <div class="spinner-border text-primary" role="status">
                <span class="visually-hidden">Loading...</span>
            </div>
            <p class="mt-2">Loading document...</p>
        </div>
    `);
    
    // Load document based on file extension
    var extension = docPath.split('.').pop().toLowerCase();
    
    setTimeout(function() {
        if (extension.match(/(jpg|jpeg|png|gif|bmp|webp)$/)) {
            // Image file
            container.html(`
                <div class="text-center">
                    <img src="${docPath}" class="img-fluid rounded shadow" style="max-height: 500px;" alt="KYC Document">
                    <p class="mt-3 text-mute">Click image to zoom</p>
                </div>
            `);
        } else if (extension.match(/(pdf)$/)) {
            // PDF file
            container.html(`
                <div class="text-center">
                    <iframe src="${docPath}" width="100%" height="500px" class="border rounded"></iframe>
                    <p class="mt-3 text-mute">PDF Document</p>
                </div>
            `);
        } else {
            // Other file types
            container.html(`
                <div class="alert alert-info">
                    <i class="fas fa-info-circle me-2"></i>
                    Document preview not available for this file type.
                    <div class="mt-2">
                        <a href="${docPath}" class="btn btn-primary" target="_blank">
                            <i class="fas fa-download me-1"></i> Download Document
                        </a>
                    </div>
                </div>
            `);
        }
    }, 1000);
}

// Verify KYC Document
function verifyKycDocument() {
    // This function would be implemented based on your specific KYC verification logic
    Swal.fire({
        title: 'Verify Document?',
        text: 'Are you sure you want to mark this document as verified?',
        icon: 'question',
        showCancelButton: true,
        confirmButtonText: 'Yes, Verify',
        cancelButtonText: 'Cancel'
    }).then((result) => {
        if (result.isConfirmed) {
            // Submit verification form
            // You would need to implement this based on your form structure
        }
    });
}

// Reject KYC Document
function rejectKycDocument() {
    Swal.fire({
        title: 'Reject Document?',
        text: 'Are you sure you want to reject this document?',
        icon: 'warning',
        showCancelButton: true,
        confirmButtonColor: '#d33',
        confirmButtonText: 'Yes, Reject',
        cancelButtonText: 'Cancel',
        input: 'textarea',
        inputLabel: 'Reason for rejection:',
        inputPlaceholder: 'Enter reason for rejecting this document...',
        inputValidator: (value) => {
            if (!value) {
                return 'Please provide a reason for rejection';
            }
        }
    }).then((result) => {
        if (result.isConfirmed) {
            // Submit rejection form with reason
            // You would need to implement this based on your form structure
        }
    });
}

// Load Email Template
function loadEmailTemplate(template) {
    if (!template) return;
    
    var messageField = $('textarea[name="message"]');
    var subjectField = $('input[name="subject"]');
    
    var templates = {
        welcome: {
            subject: 'Welcome to AI Trading Platform',
            message: 'Dear {username},\n\nWelcome to our AI Trading Platform! Your account has been successfully created.\n\nYou can now log in and start exploring our trading bot features.\n\nBest regards,\nAI Trading Team'
        },
        verification: {
            subject: 'Account Verification Approved',
            message: 'Dear {username},\n\nWe are pleased to inform you that your account verification has been approved!\n\nYou now have full access to all platform features.\n\nThank you for choosing our platform.\n\nBest regards,\nAI Trading Team'
        },
        rejection: {
            subject: 'Account Verification Update',
            message: 'Dear {username},\n\nWe regret to inform you that your account verification could not be completed at this time.\n\nPlease review the KYC requirements and resubmit your documents.\n\nIf you have any questions, please contact our support team.\n\nBest regards,\nAI Trading Team'
        },
        deposit: {
            subject: 'Deposit Received',
            message: 'Dear {username},\n\nYour deposit has been successfully received and credited to your account.\n\nYou can now start trading with our AI bots.\n\nThank you for your trust in our platform.\n\nBest regards,\nAI Trading Team'
        },
        withdrawal: {
            subject: 'Withdrawal Processed',
            message: 'Dear {username},\n\nYour withdrawal request has been processed successfully.\n\nThe funds should reflect in your account shortly.\n\nThank you for trading with us.\n\nBest regards,\nAI Trading Team'
        },
        warning: {
            subject: 'Important Account Notice',
            message: 'Dear {username},\n\nThis is an important notice regarding your account.\n\nPlease review your account activity and ensure all information is up to date.\n\nIf you have any questions, contact our support team immediately.\n\nBest regards,\nAI Trading Team'
        }
    };
    
    if (templates[template]) {
        subjectField.val(templates[template].subject);
        messageField.val(templates[template].message);
    }
}

// Send Email Modal Event
$('#sendEmailModal').on('show.bs.modal', function (event) {
    var button = $(event.relatedTarget);
    var userId = button.data('user-id');
    var userEmail = button.data('user-email') || '';
    var username = button.data('username') || 'User';
    var modal = $(this);
    
    modal.find('#emailUserId').val(userId);
    modal.find('#userEmail').val(userEmail);
    modal.find('#recipientEmail').val(userEmail + ' (' + username + ')');
    modal.find('.modal-title').text('Send Email to ' + username);
    
    // Clear form
    modal.find('input[name="subject"]').val('');
    modal.find('textarea[name="message"]').val('');
    modal.find('input[name="admin_pin"]').val('');
});

// User Notes Modal Event
$('#userNotesModal').on('show.bs.modal', function (event) {
    var button = $(event.relatedTarget);
    var userId = button.data('user-id');
    var username = button.data('username') || 'User';
    var modal = $(this);
    
    modal.find('#noteUserId').val(userId);
    modal.find('.modal-title').text('Add Note for ' + username);
    
    // Clear form
    modal.find('textarea[name="note"]').val('');
    modal.find('input[name="admin_pin"]').val('');
});

// Form validation for PIN
$('form').on('submit', function(e) {
    var pinInput = $(this).find('input[name="admin_pin"]');
    if (pinInput.length && pinInput.attr('required')) {
        var pin = pinInput.val();
        if (pin.length !== 4 || !/^\d+$/.test(pin)) {
            e.preventDefault();
            Swal.fire({
                icon: 'error',
                title: 'Invalid PIN',
                text: 'PIN must be exactly 4 digits.',
                confirmButtonColor: '#3085d6'
            });
        }
    }
});

// Initialize tooltips on modal show
$('.modal').on('shown.bs.modal', function () {
    $('[data-bs-toggle="tooltip"]').tooltip();
});

// Prevent modal background scrolling
$('.modal').on('show.bs.modal', function () {
    $('body').addClass('modal-open');
}).on('hidden.bs.modal', function () {
    $('body').removeClass('modal-open');
});
</script>

<style>
/* Modal Custom Styles */
.modal-content {
    border-radius: 15px;
    border: none;
    box-shadow: 0 10px 40px rgba(0,0,0,0.1);
}

.modal-header {
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    color: white;
    border-radius: 15px 15px 0 0;
    padding: 20px 30px;
    border-bottom: none;
}

.modal-header .btn-close {
    filter: invert(1) brightness(100%);
    opacity: 0.8;
}

.modal-header .btn-close:hover {
    opacity: 1;
}

.modal-body {
    padding: 30px;
}

.modal-footer {
    border-top: 1px solid #eee;
    border-radius: 0 0 15px 15px;
    padding: 20px 30px;
}

/* Form Styles in Modals */
.modal .form-control:focus {
    border-color: #667eea;
    box-shadow: 0 0 0 0.2rem rgba(102, 126, 234, 0.25);
}

.modal .input-group-text {
    background-color: #f8f9fa;
    border-color: #dee2e6;
}

.modal .btn-group .btn-outline-success.active,
.modal .btn-group .btn-outline-success:active,
.modal .btn-group .btn-outline-success:focus {
    background-color: #198754;
    color: white;
    border-color: #198754;
}

.modal .btn-group .btn-outline-danger.active,
.modal .btn-group .btn-outline-danger:active,
.modal .btn-group .btn-outline-danger:focus {
    background-color: #dc3545;
    color: white;
    border-color: #dc3545;
}

/* Alert Styles in Modals */
.modal .alert {
    border-radius: 10px;
    border: none;
}

.modal .alert-warning {
    background-color: #fff3cd;
    border-left: 4px solid #ffc107;
}

.modal .alert-info {
    background-color: #d1ecf1;
    border-left: 4px solid #0dcaf0;
}

/* KYC Document Preview */
#kycDocumentContainer img {
    max-width: 100%;
    height: auto;
    cursor: pointer;
    transition: transform 0.3s ease;
}

#kycDocumentContainer img:hover {
    transform: scale(1.02);
}

/* Loading Spinner */
.spinner-border {
    width: 3rem;
    height: 3rem;
}

/* Responsive Modals */
@media (max-width: 768px) {
    .modal-dialog {
        margin: 10px;
    }
    
    .modal-header,
    .modal-body,
    .modal-footer {
        padding: 15px 20px;
    }
}

/* Pin Input Security */
input[type="password"] {
    font-family: 'Courier New', monospace;
    letter-spacing: 2px;
    font-weight: bold;
}

/* Custom Scrollbar for Modal Body */
.modal-body::-webkit-scrollbar {
    width: 8px;
}

.modal-body::-webkit-scrollbar-track {
    background: #f1f1f1;
    border-radius: 4px;
}

.modal-body::-webkit-scrollbar-thumb {
    background: #c1c1c1;
    border-radius: 4px;
}

.modal-body::-webkit-scrollbar-thumb:hover {
    background: #a1a1a1;
}
</style>