<?php
/**
 * New Payment Template
 *
 * @package Easy_Invoice
 */

namespace EasyInvoice\Templates\Payments;

use EasyInvoice\Models\Invoice;
?>

<div class="p-8">
    <div class="flex justify-between items-center mb-6">
        <h1 class="text-2xl font-bold text-gray-900">
            <?php _e('Add New Payment', 'easy-invoice'); ?>
        </h1>
        <a href="<?php echo admin_url('admin.php?page=easy-invoice-payments'); ?>" 
           class="inline-flex items-center px-4 py-2 border border-transparent text-sm font-medium rounded-md shadow-sm text-white bg-indigo-600 hover:bg-indigo-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500">
            <?php _e('Back to Payments', 'easy-invoice'); ?>
        </a>
    </div>

    <div class="bg-white shadow overflow-hidden sm:rounded-lg">
        <form method="post" action="<?php echo admin_url('admin-ajax.php'); ?>" id="new-payment-form" class="space-y-6 p-6">
            <?php wp_nonce_field('easy_invoice_payment', 'payment_nonce'); ?>
            <input type="hidden" name="action" value="easy_invoice_process_payment">

            <div class="grid grid-cols-1 gap-6 sm:grid-cols-2">
                <!-- Invoice Selection -->
                <div>
                    <label for="invoice_id" class="block text-sm font-medium text-gray-700">
                        <?php _e('Invoice', 'easy-invoice'); ?> <span class="text-red-500">*</span>
                    </label>
                    <select name="invoice_id" id="invoice_id" required
                            class="mt-1 block w-full pl-3 pr-10 py-2 text-base border border-gray-300 focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm rounded-md">
                        <option value=""><?php _e('Select Invoice', 'easy-invoice'); ?></option>
                        <?php
                        $invoices = get_posts(array(
                            'post_type' => 'easy_invoice',
                            'posts_per_page' => -1,
                            'post_status' => 'publish',
                            'orderby' => 'date',
                            'order' => 'DESC',
                            'meta_query' => array(
                                'relation' => 'OR',
                                array(
                                    'key' => '_payment_status',
                                    'value' => 'unpaid',
                                    'compare' => '='
                                ),
                                array(
                                    'key' => '_payment_status',
                                    'compare' => 'NOT EXISTS'
                                ),
                                array(
                                    'key' => '_payment_status',
                                    'value' => '',
                                    'compare' => '='
                                )
                            )
                        ));

                        foreach ($invoices as $post) {
                            $invoice = new Invoice($post);
                            
                            // Get invoice number - try different methods
                            $invoice_number = $invoice->getNumber();
                            if (empty($invoice_number)) {
                                $invoice_number = get_post_meta($invoice->getId(), '_easy_invoice_number', true);
                            }
                            if (empty($invoice_number)) {
                                $invoice_number = 'INV-' . $invoice->getId();
                            }
                            
                            // Get total amount
                            $total = $invoice->getTotal();
                            if (empty($total)) {
                                $total = get_post_meta($invoice->getId(), '_easy_invoice_total', true);
                            }
                            if (empty($total)) {
                                $total = 0;
                            }
                            
                            // Get currency symbol
                            $currency_symbol = $invoice->getCurrencySymbol();
                            if (empty($currency_symbol)) {
                                $currency_symbol = get_option('easy_invoice_currency_symbol', '$');
                            }
                            
                            printf(
                                '<option value="%d">%s - %s</option>',
                                $invoice->getId(),
                                esc_html($invoice_number),
                                esc_html($currency_symbol . number_format($total, 2))
                            );
                        }
                        ?>
                    </select>
                </div>

                <!-- Payment Method -->
                <div>
                    <label for="payment_method" class="block text-sm font-medium text-gray-700">
                        <?php _e('Payment Method', 'easy-invoice'); ?> <span class="text-red-500">*</span>
                    </label>
                    <select name="payment_method" id="payment_method" required
                    class="mt-1 block w-full pl-3 pr-10 py-2 text-base border border-gray-300 focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm rounded-md">
                        <option value=""><?php _e('Select Payment Method', 'easy-invoice'); ?></option>
                        <?php
                        // Get available payment gateways (sorted)
                        $gateway_manager = \EasyInvoice\EasyInvoice::getInstance()->getGatewayManager();
                        $enabled_gateways = $gateway_manager->getEnabledGateways();
                        
                        // Show only enabled gateways and manual options
                        $available_methods = [
                            'manual' => __('Manual', 'easy-invoice'),
                        ];
                        
                        // Add enabled gateways only (already sorted)
                        foreach ($enabled_gateways as $gateway_id => $gateway) {
                            $available_methods[$gateway_id] = $gateway_manager->getGatewayDisplayName($gateway_id);
                        }
                        
                        foreach ($available_methods as $method_id => $method_name) {
                            printf(
                                '<option value="%s">%s</option>',
                                esc_attr($method_id),
                                esc_html($method_name)
                            );
                        }
                        ?>
                    </select>
                </div>

                <!-- Amount -->
                <div>
                    <label for="amount" class="block text-sm font-medium text-gray-700">
                        <?php _e('Amount', 'easy-invoice'); ?> <span class="text-red-500">*</span>
                    </label>
                    <div class="mt-1 relative rounded-md shadow-sm">
                        <div class="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
                            <span class="text-gray-500 sm:text-sm"><?php echo get_option('easy_invoice_currency_symbol', '$'); ?></span>
                        </div>
                        <input type="number" name="amount" id="amount" step="0.01" required
                               class="mt-1 block w-full border border-gray-300 rounded-md shadow-sm py-2 pl-7 pr-3 focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm"
                               placeholder="0.00">
                    </div>
                </div>

                <!-- Payment Date -->
                <div>
                    <label for="payment_date" class="block text-sm font-medium text-gray-700">
                        <?php _e('Payment Date', 'easy-invoice'); ?> <span class="text-red-500">*</span>
                    </label>
                    <input type="date" name="payment_date" id="payment_date" 
                           value="<?php echo date('Y-m-d'); ?>" required
                           class="mt-1 block w-full border border-gray-300 rounded-md shadow-sm py-2 px-3 focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm">
                </div>

                <!-- Notes -->
                <div class="sm:col-span-2">
                    <label for="notes" class="block text-sm font-medium text-gray-700">
                        <?php _e('Notes', 'easy-invoice'); ?>
                    </label>
                    <div class="mt-1">
                        <textarea name="notes" id="notes" rows="3"
                                  class="mt-1 block w-full border border-gray-300 rounded-md shadow-sm py-2 px-3 focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm"
                                  placeholder="<?php _e('Add any additional notes about this payment...', 'easy-invoice'); ?>"></textarea>
                    </div>
                </div>
            </div>

            <div class="pt-5">
                <div class="flex justify-end">
                    <button type="submit"
                            class="ml-3 inline-flex justify-center py-2 px-4 border border-transparent shadow-sm text-sm font-medium rounded-md text-white bg-indigo-600 hover:bg-indigo-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500">
                        <?php _e('Add Payment', 'easy-invoice'); ?>
                    </button>
                </div>
            </div>
        </form>
    </div>
</div>

<script>
jQuery(document).ready(function($) {
    // Update amount when invoice is selected
    $('#invoice_id').on('change', function() {
        var selectedOption = $(this).find('option:selected');
        var amount = selectedOption.text().split(' - ')[1];
        if (amount) {
            $('#amount').val(amount.replace(/[^0-9.-]+/g, ''));
        }
    });

    // Form submission
    $('#new-payment-form').on('submit', function(e) {
        e.preventDefault();
        
        var formData = new FormData(this);
        
        $.ajax({
            url: $(this).attr('action'),
            type: 'POST',
            data: formData,
            processData: false,
            contentType: false,
            success: function(response) {
                if (response.success) {
                    window.location.href = '<?php echo admin_url('admin.php?page=easy-invoice-payments'); ?>';
                } else {
                    EasyInvoiceToast.error(response.data.message || '<?php _e('An error occurred', 'easy-invoice'); ?>');
                }
            },
            error: function() {
                EasyInvoiceToast.error('<?php _e('An error occurred', 'easy-invoice'); ?>');
            }
        });
    });
});
</script> 