/**
 * Manual Payment JavaScript
 *
 * Handles manual payment form interactions
 *
 * @package EasyInvoice
 * @since 1.0.0
 */

// Add CSS styles for manual payment
jQuery('<style>')
    .prop('type', 'text/css')
    .html(`
        .manual-payment-form {
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
        }
        
        .payment-methods {
            display: flex;
            gap: 12px;
            margin-bottom: 20px;
            flex-wrap: wrap;
        }
        
        .payment-method-option {
            flex: 1;
            min-width: 120px;
        }
        
        .payment-method-option input[type="radio"] {
            display: none;
        }
        
        .payment-method-option label {
            display: flex;
            flex-direction: column;
            align-items: center;
            padding: 16px;
            border: 2px solid #e5e7eb;
            border-radius: 8px;
            cursor: pointer;
            transition: all 0.2s ease;
            background: #ffffff;
        }
        
        .payment-method-option label:hover {
            border-color: #10b981;
            background: #f0fdf4;
        }
        
        .payment-method-option input[type="radio"]:checked + label {
            border-color: #10b981;
            background: #f0fdf4;
            color: #059669;
        }
        
        .payment-method-option label i {
            font-size: 24px;
            margin-bottom: 8px;
        }
        
        .payment-method-option label span {
            font-size: 14px;
            font-weight: 500;
        }
        
        .payment-details {
            margin-bottom: 20px;
            padding: 16px;
            background: #f8fafc;
            border-radius: 8px;
            border: 1px solid #e5e7eb;
        }
        
        .bank-details-table {
            width: 100%;
            border-collapse: collapse;
            margin-bottom: 16px;
        }
        
        .bank-details-table th,
        .bank-details-table td {
            padding: 8px 12px;
            border-bottom: 1px solid #e5e7eb;
            text-align: left;
        }
        
        .bank-details-table th {
            font-weight: 600;
            color: #374151;
            width: 40%;
        }
        
        .payment-proof-section {
            padding: 20px;
            background: #ffffff;
            border: 1px solid #e5e7eb;
            border-radius: 8px;
        }
        
        .payment-proof-section h4 {
            margin: 0 0 16px 0;
            font-size: 16px;
            font-weight: 600;
            color: #374151;
        }
        
        .form-group {
            margin-bottom: 16px;
        }
        
        .form-group label {
            display: block;
            margin-bottom: 6px;
            font-weight: 500;
            color: #374151;
        }
        
        .form-group input[type="file"],
        .form-group textarea {
            width: 100%;
            padding: 10px;
            border: 1px solid #d1d5db;
            border-radius: 6px;
            font-size: 14px;
            transition: border-color 0.2s ease;
        }
        
        .form-group input[type="file"]:focus,
        .form-group textarea:focus {
            outline: none;
            border-color: #10b981;
            box-shadow: 0 0 0 3px rgba(16, 185, 129, 0.1);
        }
        
        .form-actions {
            margin-top: 20px;
            text-align: right;
        }
        
        .manual-payment-submit {
            background: #10b981;
            color: white;
            padding: 12px 24px;
            border: none;
            border-radius: 6px;
            font-size: 14px;
            font-weight: 500;
            cursor: pointer;
            transition: background-color 0.2s ease;
        }
        
        .manual-payment-submit:hover {
            background: #059669;
        }
        
        .manual-payment-submit:disabled {
            background: #9ca3af;
            cursor: not-allowed;
        }
        
        #payment-proof-preview {
            margin-top: 12px;
            padding: 12px;
            background: #f8fafc;
            border: 1px solid #e5e7eb;
            border-radius: 6px;
        }
        
        #payment-proof-preview img {
            max-width: 200px;
            max-height: 200px;
            border-radius: 4px;
        }
    `)
    .appendTo('head');

jQuery(document).ready(function($) {
    // Handle payment method selection
    $(document).on('change', 'input[name="payment_type"]', function() {
        const selectedMethod = $(this).val();
        
        // Hide all payment details
        $('.cash-details, .bank-details, .cheque-details').hide();
        
        // Show selected payment details
        $('#' + selectedMethod + '-details').show();
    });

    // Handle manual payment submission
    $(document).on('click', '.manual-payment-submit', function(e) {
        e.preventDefault();
        
        const form = $(this).closest('form');
        const invoiceId = form.find('input[name="invoice_id"]').val();
        const paymentType = form.find('input[name="payment_type"]:checked').val();
        const paymentNotes = form.find('textarea[name="payment_notes"]').val();
        const paymentProof = form.find('input[name="payment_proof"]')[0].files[0];
        
        // Validate form
        if (!paymentType) {
            alert('Please select a payment method');
            return;
        }
        
        // Create form data
        const formData = new FormData();
        formData.append('action', 'easy_invoice_submit_manual_payment');
        formData.append('invoice_id', invoiceId);
        formData.append('payment_type', paymentType);
        formData.append('payment_notes', paymentNotes);
        formData.append('payment_proof', paymentProof);
        formData.append('nonce', easy_invoice_ajax.nonce);
        
        // Show loading
        $(this).prop('disabled', true).text('Processing...');
        
        // Submit payment
        $.ajax({
            url: easy_invoice_ajax.ajax_url,
            type: 'POST',
            data: formData,
            processData: false,
            contentType: false,
            success: function(response) {
                if (response.success) {
                    alert('Payment submitted successfully! Your payment will be verified by the administrator.');
                    // Reload page or redirect
                    window.location.reload();
                } else {
                    alert('Error: ' + response.data.message);
                }
            },
            error: function() {
                alert('An error occurred while processing your payment. Please try again.');
            },
            complete: function() {
                // Restore button
                $(this).prop('disabled', false).text('Submit Payment');
            }
        });
    });

    // Handle payment proof file upload
    $(document).on('change', '#payment_proof', function() {
        const file = this.files[0];
        const fileSize = file.size / 1024 / 1024; // Convert to MB
        
        if (fileSize > 5) {
            alert('File size must be less than 5MB');
            $(this).val('');
            return;
        }
        
        const allowedTypes = ['image/jpeg', 'image/png', 'image/gif', 'application/pdf'];
        if (!allowedTypes.includes(file.type)) {
            alert('Only JPG, PNG, GIF, and PDF files are allowed');
            $(this).val('');
            return;
        }
        
        // Show file preview
        const preview = $('#payment-proof-preview');
        if (file.type.startsWith('image/')) {
            const reader = new FileReader();
            reader.onload = function(e) {
                preview.html('<img src="' + e.target.result + '" style="max-width: 200px; max-height: 200px;" />');
            };
            reader.readAsDataURL(file);
        } else {
            preview.html('<p>' + file.name + ' (' + fileSize.toFixed(2) + ' MB)</p>');
        }
    });
});
