<?php
/**
 * Admin template for verifying manual payments
 *
 * @package Easy_Invoice
 */

// Prevent direct access
if (!defined('ABSPATH')) {
    exit;
}

// Get invoice ID
$invoice_id = isset($_GET['invoice_id']) ? intval($_GET['invoice_id']) : 0;
if (!$invoice_id) {
    wp_die(__('Invoice ID is required', 'easy-invoice'));
}

// Get invoice
$invoice = new \EasyInvoice\Models\Invoice(get_post($invoice_id));
if (!$invoice->getPost()) {
    wp_die(__('Invalid invoice', 'easy-invoice'));
}

// Get payment details
$payment_method = get_post_meta($invoice_id, '_payment_method', true);
$payment_status = get_post_meta($invoice_id, '_payment_status', true);

// If not a manual payment or not pending, redirect to invoice view
if (!in_array($payment_method, ['bank', 'cheque']) || $payment_status !== 'pending') {
    wp_redirect(admin_url('admin.php?page=easy-invoice-invoices&action=view&id=' . $invoice_id));
    exit;
}

// Get payment proof details
$transaction_id = '';
$payment_date = '';
$notes = '';
$proof_url = '';
$submission_date = '';

if ($payment_method === 'bank') {
    $transaction_id = get_post_meta($invoice_id, '_bank_transaction_id', true);
    $notes = get_post_meta($invoice_id, '_bank_payment_notes', true);
    $proof_url = get_post_meta($invoice_id, '_bank_payment_proof', true);
    $submission_date = get_post_meta($invoice_id, '_bank_payment_date', true);
} elseif ($payment_method === 'cheque') {
    $transaction_id = get_post_meta($invoice_id, '_cheque_number', true);
    $bank_name = get_post_meta($invoice_id, '_cheque_bank_name', true);
    $payment_date = get_post_meta($invoice_id, '_cheque_date', true);
    $notes = get_post_meta($invoice_id, '_cheque_notes', true);
    $proof_url = get_post_meta($invoice_id, '_cheque_image', true);
    $submission_date = get_post_meta($invoice_id, '_cheque_submission_date', true);
}

// Format payment method label
$payment_method_label = $payment_method === 'bank' ? __('Bank Transfer', 'easy-invoice') : __('Cheque', 'easy-invoice');

// Format dates
$formatted_submission_date = $submission_date ? date_i18n(get_option('date_format') . ' ' . get_option('time_format'), strtotime($submission_date)) : '';
$formatted_payment_date = $payment_date ? date_i18n(get_option('date_format'), strtotime($payment_date)) : '';
?>

<div class="wrap">
    <h1><?php printf(__('Verify %s Payment', 'easy-invoice'), $payment_method_label); ?></h1>
    
    <div class="notice notice-info">
        <p><?php _e('Please review the payment details submitted by the customer and verify the payment.', 'easy-invoice'); ?></p>
    </div>
    
    <div class="metabox-holder">
        <div class="postbox">
            <h2 class="hndle"><span><?php _e('Invoice Details', 'easy-invoice'); ?></span></h2>
            <div class="inside">
                <table class="form-table">
                    <tr>
                        <th><?php _e('Invoice Number', 'easy-invoice'); ?></th>
                        <td><?php echo esc_html($invoice->getNumber()); ?></td>
                    </tr>
                    <tr>
                        <th><?php _e('Customer', 'easy-invoice'); ?></th>
                        <td><?php echo esc_html($invoice->getCustomerName()); ?></td>
                    </tr>
                    <tr>
                        <th><?php _e('Amount', 'easy-invoice'); ?></th>
                        <td><?php 
                            $formatter = new \EasyInvoice\Helpers\InvoiceFormatter($invoice);
                            echo esc_html($formatter->format($invoice->getTotal())); 
                        ?></td>
                    </tr>
                    <tr>
                        <th><?php _e('Due Date', 'easy-invoice'); ?></th>
                        <td><?php echo esc_html($invoice->getDueDate()); ?></td>
                    </tr>
                </table>
            </div>
        </div>
        
        <div class="postbox">
            <h2 class="hndle"><span><?php printf(__('%s Payment Details', 'easy-invoice'), $payment_method_label); ?></span></h2>
            <div class="inside">
                <table class="form-table">
                    <?php if ($payment_method === 'bank'): ?>
                    <tr>
                        <th><?php _e('Transaction ID', 'easy-invoice'); ?></th>
                        <td><?php echo esc_html($transaction_id); ?></td>
                    </tr>
                    <?php elseif ($payment_method === 'cheque'): ?>
                    <tr>
                        <th><?php _e('Cheque Number', 'easy-invoice'); ?></th>
                        <td><?php echo esc_html($transaction_id); ?></td>
                    </tr>
                    <?php if ($bank_name): ?>
                    <tr>
                        <th><?php _e('Bank Name', 'easy-invoice'); ?></th>
                        <td><?php echo esc_html($bank_name); ?></td>
                    </tr>
                    <?php endif; ?>
                    <?php if ($payment_date): ?>
                    <tr>
                        <th><?php _e('Cheque Date', 'easy-invoice'); ?></th>
                        <td><?php echo esc_html($formatted_payment_date); ?></td>
                    </tr>
                    <?php endif; ?>
                    <?php endif; ?>
                    
                    <?php if ($submission_date): ?>
                    <tr>
                        <th><?php _e('Submission Date', 'easy-invoice'); ?></th>
                        <td><?php echo esc_html($formatted_submission_date); ?></td>
                    </tr>
                    <?php endif; ?>
                    
                    <?php if ($notes): ?>
                    <tr>
                        <th><?php _e('Customer Notes', 'easy-invoice'); ?></th>
                        <td><?php echo wpautop(esc_html($notes)); ?></td>
                    </tr>
                    <?php endif; ?>
                    
                    <?php if ($proof_url): ?>
                    <tr>
                        <th><?php _e('Payment Proof', 'easy-invoice'); ?></th>
                        <td>
                            <?php if (wp_check_filetype(basename($proof_url), null)['ext'] === 'pdf'): ?>
                                <a href="<?php echo esc_url($proof_url); ?>" target="_blank" class="button"><?php _e('View PDF', 'easy-invoice'); ?></a>
                            <?php else: ?>
                                <a href="<?php echo esc_url($proof_url); ?>" target="_blank">
                                    <img src="<?php echo esc_url($proof_url); ?>" alt="<?php _e('Payment Proof', 'easy-invoice'); ?>" style="max-width: 300px; max-height: 200px;">
                                </a>
                            <?php endif; ?>
                        </td>
                    </tr>
                    <?php endif; ?>
                </table>
            </div>
        </div>
        
        <div class="postbox">
            <h2 class="hndle"><span><?php _e('Payment Verification', 'easy-invoice'); ?></span></h2>
            <div class="inside">
                <form id="payment-verification-form" method="post">
                    <input type="hidden" name="action" value="easy_invoice_verify_manual_payment">
                    <input type="hidden" name="invoice_id" value="<?php echo esc_attr($invoice_id); ?>">
                    <input type="hidden" name="payment_method" value="<?php echo esc_attr($payment_method); ?>">
                    <?php wp_nonce_field('easy_invoice_admin', 'nonce'); ?>
                    
                    <table class="form-table">
                        <tr>
                            <th><?php _e('Transaction ID', 'easy-invoice'); ?></th>
                            <td>
                                <input type="text" name="transaction_id" value="<?php echo esc_attr($transaction_id); ?>" class="regular-text">
                                <p class="description"><?php _e('Enter the transaction ID for this payment.', 'easy-invoice'); ?></p>
                            </td>
                        </tr>
                        <tr>
                            <th><?php _e('Admin Notes', 'easy-invoice'); ?></th>
                            <td>
                                <textarea name="notes" rows="3" class="large-text"></textarea>
                                <p class="description"><?php _e('Add any notes about this payment (optional).', 'easy-invoice'); ?></p>
                            </td>
                        </tr>
                    </table>
                    
                    <div class="verification-actions">
                        <button type="submit" class="button button-primary verify-payment-btn"><?php _e('Verify Payment', 'easy-invoice'); ?></button>
                        <button type="button" class="button reject-payment-btn"><?php _e('Reject Payment', 'easy-invoice'); ?></button>
                    </div>
                </form>
                
                <div id="reject-payment-form" style="display: none; margin-top: 20px; padding-top: 20px; border-top: 1px solid #ddd;">
                    <h3><?php _e('Reject Payment', 'easy-invoice'); ?></h3>
                    <p><?php _e('Please provide a reason for rejecting this payment:', 'easy-invoice'); ?></p>
                    
                    <form method="post">
                        <input type="hidden" name="action" value="easy_invoice_reject_manual_payment">
                        <input type="hidden" name="invoice_id" value="<?php echo esc_attr($invoice_id); ?>">
                        <?php wp_nonce_field('easy_invoice_admin', 'nonce'); ?>
                        
                        <textarea name="reason" rows="3" class="large-text" required></textarea>
                        <p class="description"><?php _e('This reason will be included in the email sent to the customer.', 'easy-invoice'); ?></p>
                        
                        <div class="verification-actions" style="margin-top: 10px;">
                            <button type="submit" class="button button-secondary"><?php _e('Confirm Rejection', 'easy-invoice'); ?></button>
                            <button type="button" class="button cancel-rejection-btn"><?php _e('Cancel', 'easy-invoice'); ?></button>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>
</div>

<style>
.verification-actions {
    margin-top: 20px;
    padding-top: 15px;
    border-top: 1px solid #eee;
}
.reject-payment-btn {
    margin-left: 10px;
}
</style>

<script>
jQuery(document).ready(function($) {
    // Show/hide rejection form
    $('.reject-payment-btn').on('click', function() {
        $('#reject-payment-form').show();
    });
    
    $('.cancel-rejection-btn').on('click', function() {
        $('#reject-payment-form').hide();
    });
    
    // Handle verify payment form submission
    $('#payment-verification-form').on('submit', function(e) {
        e.preventDefault();
        
        var formData = $(this).serialize();
        
        // Show loading
        $('.verify-payment-btn').prop('disabled', true).text('<?php _e('Processing...', 'easy-invoice'); ?>');
        
        $.ajax({
            url: ajaxurl,
            type: 'POST',
            data: formData,
            success: function(response) {
                if (response.success) {
                    // Use toast system if available, otherwise fallback to alert
                    if (typeof EasyInvoiceToast !== 'undefined') {
                        EasyInvoiceToast.success(response.data.message);
                    } else {
                        alert(response.data.message);
                    }
                    window.location.href = '<?php echo esc_js(admin_url('admin.php?page=easy-invoice-invoices&action=view&id=' . $invoice_id)); ?>';
                } else {
                    // Use toast system if available, otherwise fallback to alert
                    if (typeof EasyInvoiceToast !== 'undefined') {
                        EasyInvoiceToast.error(response.data.message);
                    } else {
                        alert(response.data.message);
                    }
                    $('.verify-payment-btn').prop('disabled', false).text('<?php _e('Verify Payment', 'easy-invoice'); ?>');
                }
            },
            error: function() {
                // Use toast system if available, otherwise fallback to alert
                if (typeof EasyInvoiceToast !== 'undefined') {
                    EasyInvoiceToast.error('<?php _e('An error occurred. Please try again.', 'easy-invoice'); ?>');
                } else {
                    alert('<?php _e('An error occurred. Please try again.', 'easy-invoice'); ?>');
                }
                $('.verify-payment-btn').prop('disabled', false).text('<?php _e('Verify Payment', 'easy-invoice'); ?>');
            }
        });
    });
});
</script> 