<!-- PIN Verification Modal -->
<div class="modal fade" id="pinVerificationModal" tabindex="-1" data-bs-backdrop="static" data-bs-keyboard="false">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content">
            <div class="modal-header bg-primary text-white">
                <h5 class="modal-title">
                    <i class="fa fa-lock"></i> PIN Verification Required
                </h5>
            </div>
            <div class="modal-body text-center">
                <div class="mb-3">
                    <i class="fa fa-shield-alt fa-3x text-primary mb-3"></i>
                    <h6>Enter your PIN to continue</h6>
                    <p class="text-muted">This action requires PIN verification for security</p>
                </div>
                
                <div class="mb-3">
                    <input type="password" 
                           id="pinInput" 
                           class="form-control form-control-lg text-center" 
                           placeholder="Enter PIN" 
                           maxlength="10" 
                           autocomplete="off"
                           style="font-size: 1.5rem; letter-spacing: 0.5rem;">
                    <small class="form-text text-muted">4-10 digit PIN (use keyboard or touch keypad)</small>
                    <div class="mt-2">
                        <small class="text-muted">
                            <span id="pinLength">0</span>/10 digits
                        </small>
                    </div>
                </div>
                
                <!-- Touch Keypad -->
                <div class="pin-keypad">
                    <div class="row g-2 mb-2">
                        <div class="col-4">
                            <button type="button" class="btn btn-outline-primary btn-lg w-100 pin-key" data-key="1">
                                <span class="pin-number">1</span>
                            </button>
                        </div>
                        <div class="col-4">
                            <button type="button" class="btn btn-outline-primary btn-lg w-100 pin-key" data-key="2">
                                <span class="pin-number">2</span>
                            </button>
                        </div>
                        <div class="col-4">
                            <button type="button" class="btn btn-outline-primary btn-lg w-100 pin-key" data-key="3">
                                <span class="pin-number">3</span>
                            </button>
                        </div>
                    </div>
                    <div class="row g-2 mb-2">
                        <div class="col-4">
                            <button type="button" class="btn btn-outline-primary btn-lg w-100 pin-key" data-key="4">
                                <span class="pin-number">4</span>
                            </button>
                        </div>
                        <div class="col-4">
                            <button type="button" class="btn btn-outline-primary btn-lg w-100 pin-key" data-key="5">
                                <span class="pin-number">5</span>
                            </button>
                        </div>
                        <div class="col-4">
                            <button type="button" class="btn btn-outline-primary btn-lg w-100 pin-key" data-key="6">
                                <span class="pin-number">6</span>
                            </button>
                        </div>
                    </div>
                    <div class="row g-2 mb-2">
                        <div class="col-4">
                            <button type="button" class="btn btn-outline-primary btn-lg w-100 pin-key" data-key="7">
                                <span class="pin-number">7</span>
                            </button>
                        </div>
                        <div class="col-4">
                            <button type="button" class="btn btn-outline-primary btn-lg w-100 pin-key" data-key="8">
                                <span class="pin-number">8</span>
                            </button>
                        </div>
                        <div class="col-4">
                            <button type="button" class="btn btn-outline-primary btn-lg w-100 pin-key" data-key="9">
                                <span class="pin-number">9</span>
                            </button>
                        </div>
                    </div>
                    <div class="row g-2">
                        <div class="col-4">
                            <button type="button" class="btn btn-outline-secondary btn-lg w-100" id="clearPinBtn">
                                <i class="fa fa-eraser"></i>
                            </button>
                        </div>
                        <div class="col-4">
                            <button type="button" class="btn btn-outline-primary btn-lg w-100 pin-key" data-key="0">
                                <span class="pin-number">0</span>
                            </button>
                        </div>
                        <div class="col-4">
                            <button type="button" class="btn btn-outline-danger btn-lg w-100" id="backspacePinBtn">
                                <i class="fa fa-backspace"></i>
                            </button>
                        </div>
                    </div>
                </div>
                
                <div id="pinError" class="alert alert-danger d-none" role="alert">
                    <i class="fa fa-exclamation-triangle"></i>
                    <span id="pinErrorMessage"></span>
                </div>
                
                <div id="pinLoading" class="d-none">
                    <div class="spinner-border text-primary" role="status">
                        <span class="visually-hidden">Verifying...</span>
                    </div>
                    <p class="mt-2">Verifying PIN...</p>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" id="cancelPinBtn">
                    <i class="fa fa-times"></i> Cancel
                </button>
                <button type="button" class="btn btn-primary" id="verifyPinBtn">
                    <i class="fa fa-check"></i> Verify PIN
                </button>
            </div>
        </div>
    </div>
</div>

<style>
/* PIN Keypad Styling */
.pin-keypad {
    max-width: 300px;
    margin: 0 auto;
    padding: 15px;
    border: 2px solid #e9ecef;
    border-radius: 10px;
    background-color: #f8f9fa;
}

.pin-key {
    height: 60px;
    font-size: 1.5rem;
    font-weight: bold;
    border-radius: 10px;
    transition: all 0.2s ease;
    touch-action: manipulation;
}

.pin-key:hover {
    transform: translateY(-2px);
    box-shadow: 0 4px 8px rgba(0,0,0,0.1);
}

.pin-key:active {
    transform: translateY(0);
    box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}

.pin-number {
    font-size: 1.8rem;
    font-weight: bold;
}

/* Touch-friendly button sizing */
@media (max-width: 768px) {
    .pin-key {
        height: 70px;
        font-size: 1.8rem;
    }
    
    .pin-number {
        font-size: 2rem;
    }
    
    .pin-keypad {
        max-width: 100%;
    }
    
    .modal-dialog {
        margin: 10px;
    }
}

/* Prevent zoom on input focus for mobile */
@media screen and (max-width: 768px) {
    #pinInput {
        font-size: 16px !important;
    }
}

/* PIN input styling */
#pinInput {
    background-color: #f8f9fa;
    border: 2px solid #dee2e6;
    border-radius: 10px;
}

#pinInput:focus {
    border-color: #0d6efd;
    box-shadow: 0 0 0 0.2rem rgba(13, 110, 253, 0.25);
}
</style>

<script>
// Global variables for PIN verification
let pinVerificationCallback = null;
let pinActionType = 'void';

// PIN input validation - only allow numbers (for keyboard input)
document.getElementById('pinInput').addEventListener('input', function(e) {
    this.value = this.value.replace(/[^0-9]/g, '');
    // Hide error message when user starts typing
    document.getElementById('pinError').classList.add('d-none');
    // Update PIN length counter
    updatePinLength();
});

// Update PIN length counter
function updatePinLength() {
    const pinInput = document.getElementById('pinInput');
    const pinLength = document.getElementById('pinLength');
    pinLength.textContent = pinInput.value.length;
}

// Keyboard support for PIN input
document.getElementById('pinInput').addEventListener('keypress', function(e) {
    if (e.key === 'Enter') {
        verifyPin();
    } else if (e.key >= '0' && e.key <= '9') {
        // Allow number keys
        return true;
    } else if (e.key === 'Backspace' || e.key === 'Delete') {
        // Allow backspace/delete
        return true;
    } else {
        // Block other keys
        e.preventDefault();
        return false;
    }
});

// Additional keyboard support for number keys
document.getElementById('pinInput').addEventListener('keydown', function(e) {
    // Allow: backspace, delete, tab, escape, enter, home, end, left, right, up, down
    if ([8, 9, 27, 13, 46, 35, 36, 37, 38, 39, 40].indexOf(e.keyCode) !== -1 ||
        // Allow: Ctrl+A, Ctrl+C, Ctrl+V, Ctrl+X
        (e.keyCode === 65 && e.ctrlKey === true) ||
        (e.keyCode === 67 && e.ctrlKey === true) ||
        (e.keyCode === 86 && e.ctrlKey === true) ||
        (e.keyCode === 88 && e.ctrlKey === true) ||
        // Allow: numbers on top row and numpad
        (e.keyCode >= 48 && e.keyCode <= 57) ||
        (e.keyCode >= 96 && e.keyCode <= 105)) {
        return;
    }
    // Block all other keys
    e.preventDefault();
});

// Touch keypad functionality
document.addEventListener('DOMContentLoaded', function() {
    // Number key buttons
    document.querySelectorAll('.pin-key').forEach(button => {
        button.addEventListener('click', function() {
            const key = this.getAttribute('data-key');
            addPinDigit(key);
        });
    });
    
    // Clear button
    document.getElementById('clearPinBtn').addEventListener('click', function() {
        clearPin();
    });
    
    // Backspace button
    document.getElementById('backspacePinBtn').addEventListener('click', function() {
        backspacePin();
    });
});

// Add digit to PIN
function addPinDigit(digit) {
    const pinInput = document.getElementById('pinInput');
    if (pinInput.value.length < 10) { // Max 10 digits
        pinInput.value += digit;
        // Hide error message when user starts typing
        document.getElementById('pinError').classList.add('d-none');
        // Update PIN length counter
        updatePinLength();
        
        // Visual feedback for touch
        const button = document.querySelector(`[data-key="${digit}"]`);
        if (button) {
            button.style.transform = 'scale(0.95)';
            setTimeout(() => {
                button.style.transform = '';
            }, 150);
        }
        
        // Auto-verify when PIN reaches 4 digits (optional - can be disabled)
        // Uncomment the following lines if you want auto-verification
        // if (pinInput.value.length >= 4) {
        //     setTimeout(() => {
        //         verifyPin();
        //     }, 500); // Small delay to show the digit was entered
        // }
    }
}

// Clear PIN
function clearPin() {
    document.getElementById('pinInput').value = '';
    document.getElementById('pinError').classList.add('d-none');
    updatePinLength();
    
    // Visual feedback
    const clearBtn = document.getElementById('clearPinBtn');
    clearBtn.style.transform = 'scale(0.95)';
    setTimeout(() => {
        clearBtn.style.transform = '';
    }, 150);
}

// Backspace PIN
function backspacePin() {
    const pinInput = document.getElementById('pinInput');
    if (pinInput.value.length > 0) {
        pinInput.value = pinInput.value.slice(0, -1);
        document.getElementById('pinError').classList.add('d-none');
        updatePinLength();
        
        // Visual feedback
        const backspaceBtn = document.getElementById('backspacePinBtn');
        backspaceBtn.style.transform = 'scale(0.95)';
        setTimeout(() => {
            backspaceBtn.style.transform = '';
        }, 150);
    }
}

// Verify PIN function
function verifyPin() {
    const pin = document.getElementById('pinInput').value;
    const errorDiv = document.getElementById('pinError');
    const loadingDiv = document.getElementById('pinLoading');
    const verifyBtn = document.getElementById('verifyPinBtn');
    
    // Hide error message
    errorDiv.classList.add('d-none');
    
    // Validate PIN format
    if (!pin || pin.length < 4) {
        showPinError('PIN must be at least 4 digits');
        return;
    }
    
    // Show loading
    loadingDiv.classList.remove('d-none');
    verifyBtn.disabled = true;
    
    // Prepare form data
    const formData = new FormData();
    formData.append('pin', pin);
    formData.append('action_type', pinActionType);
    
    // Send verification request
    fetch('ajax/verify_pin.php', {
        method: 'POST',
        body: formData
    })
    .then(response => response.json())
    .then(data => {
        loadingDiv.classList.add('d-none');
        verifyBtn.disabled = false;
        
        if (data.status === 'success') {
            // PIN verified successfully
            const modal = bootstrap.Modal.getInstance(document.getElementById('pinVerificationModal'));
            modal.hide();
            
            // Execute callback if provided
            if (pinVerificationCallback && typeof pinVerificationCallback === 'function') {
                pinVerificationCallback();
            }
        } else {
            showPinError(data.message || 'PIN verification failed');
        }
    })
    .catch(error => {
        loadingDiv.classList.add('d-none');
        verifyBtn.disabled = false;
        showPinError('Network error. Please try again.');
        console.error('PIN verification error:', error);
    });
}

// Show PIN error
function showPinError(message) {
    const errorDiv = document.getElementById('pinError');
    const errorMessage = document.getElementById('pinErrorMessage');
    
    errorMessage.textContent = message;
    errorDiv.classList.remove('d-none');
    
    // Clear PIN input
    document.getElementById('pinInput').value = '';
    document.getElementById('pinInput').focus();
}

// Show PIN verification modal
function showPinVerification(actionType, callback) {
    pinActionType = actionType || 'void';
    pinVerificationCallback = callback;
    
    // Reset modal state
    clearPin();
    document.getElementById('pinLoading').classList.add('d-none');
    document.getElementById('verifyPinBtn').disabled = false;
    
    // Show modal
    const modal = new bootstrap.Modal(document.getElementById('pinVerificationModal'));
    modal.show();
    
    // Focus on PIN input (for keyboard users)
    setTimeout(() => {
        document.getElementById('pinInput').focus();
    }, 500);
}

// Event listeners
document.getElementById('verifyPinBtn').addEventListener('click', verifyPin);

document.getElementById('cancelPinBtn').addEventListener('click', function() {
    const modal = bootstrap.Modal.getInstance(document.getElementById('pinVerificationModal'));
    modal.hide();
});

// Clear PIN input when modal is hidden
document.getElementById('pinVerificationModal').addEventListener('hidden.bs.modal', function() {
    clearPin();
    document.getElementById('pinLoading').classList.add('d-none');
    pinVerificationCallback = null;
});
</script>
