<?php

namespace EasyInvoice\Admin;

class InvoiceAdmin {
    public function init(): void {
        add_action('admin_menu', [$this, 'registerMenus']);
        add_action('admin_enqueue_scripts', [$this, 'enqueueAssets']);
        
        // Add custom columns to invoice list
        add_filter('manage_easy-invoice_posts_columns', [$this, 'addCustomColumns']);
        add_action('manage_easy-invoice_posts_custom_column', [$this, 'renderCustomColumns'], 10, 2);
        
        // Add payment status filter
        add_action('restrict_manage_posts', [$this, 'addPaymentStatusFilter']);
        add_filter('parse_query', [$this, 'filterByPaymentStatus']);
        
        // Add row actions for manual payments
        add_filter('post_row_actions', [$this, 'addManualPaymentRowActions'], 10, 2);
    }

    /**
     * Add custom columns to invoice list
     * 
     * @param array $columns
     * @return array
     */
    public function addCustomColumns($columns): array {
        $new_columns = [];
        
        foreach ($columns as $key => $value) {
            $new_columns[$key] = $value;
            
            if ($key === 'title') {
                $new_columns['invoice_number'] = __('Invoice Number', 'easy-invoice');
                $new_columns['customer'] = __('Customer', 'easy-invoice');
                $new_columns['amount'] = __('Amount', 'easy-invoice');
                $new_columns['due_date'] = __('Due Date', 'easy-invoice');
                $new_columns['payment_status'] = __('Payment Status', 'easy-invoice');
            }
        }
        
        return $new_columns;
    }
    
    /**
     * Render custom columns
     * 
     * @param string $column
     * @param int $post_id
     */
    public function renderCustomColumns($column, $post_id): void {
        $invoice = new \EasyInvoice\Models\Invoice(get_post($post_id));
        
        switch ($column) {
            case 'invoice_number':
                echo esc_html($invoice->getNumber());
                break;
                
            case 'customer':
                echo esc_html($invoice->getCustomerName());
                break;
                
            case 'amount':
                $formatter = new \EasyInvoice\Helpers\InvoiceFormatter($invoice);
                echo esc_html($formatter->format($invoice->getTotal()));
                break;
                
            case 'due_date':
                echo esc_html($invoice->getDueDate());
                break;
                
            case 'payment_status':
                $status = $invoice->getStatus();
                $payment_status = get_post_meta($post_id, '_payment_status', true);
                $payment_method = get_post_meta($post_id, '_payment_method', true);
                
                if ($status === 'paid') {
                    echo '<span class="status-paid">' . __('Paid', 'easy-invoice') . '</span>';
                } elseif ($payment_status === 'pending' && in_array($payment_method, ['bank', 'cheque'])) {
                    $method_label = $payment_method === 'bank' ? __('Bank Transfer', 'easy-invoice') : __('Cheque', 'easy-invoice');
                    echo '<span class="status-pending">' . sprintf(__('Pending %s', 'easy-invoice'), $method_label) . '</span>';
                    
                    // Add verification link
                    echo '<br><a href="' . admin_url('admin.php?page=easy-invoice-invoices&action=verify-payment&invoice_id=' . $post_id) . '" class="verify-payment-link">' . __('Verify Payment', 'easy-invoice') . '</a>';
                } elseif ($payment_status === 'rejected') {
                    echo '<span class="status-rejected">' . __('Payment Rejected', 'easy-invoice') . '</span>';
                } else {
                    echo '<span class="status-unpaid">' . __('Unpaid', 'easy-invoice') . '</span>';
                }
                break;
        }
    }
    
    /**
     * Add payment status filter to invoices list
     */
    public function addPaymentStatusFilter(): void {
        global $typenow;
        
        if ($typenow !== 'easy-invoice') {
            return;
        }
        
        $current_status = isset($_GET['payment_status']) ? sanitize_text_field($_GET['payment_status']) : '';
        
        $statuses = [
            '' => __('All Payment Statuses', 'easy-invoice'),
            'paid' => __('Paid', 'easy-invoice'),
            'unpaid' => __('Unpaid', 'easy-invoice'),
            'pending_bank' => __('Pending Bank Transfer', 'easy-invoice'),
            'pending_cheque' => __('Pending Cheque', 'easy-invoice'),
            'rejected' => __('Payment Rejected', 'easy-invoice')
        ];
        
        echo '<select name="payment_status">';
        foreach ($statuses as $value => $label) {
            echo '<option value="' . esc_attr($value) . '" ' . selected($current_status, $value, false) . '>' . esc_html($label) . '</option>';
        }
        echo '</select>';
    }
    
    /**
     * Filter invoices by payment status
     * 
     * @param \WP_Query $query
     */
    public function filterByPaymentStatus($query): void {
        global $pagenow, $typenow;
        
        if ($pagenow !== 'edit.php' || $typenow !== 'easy-invoice' || !isset($_GET['payment_status']) || empty($_GET['payment_status'])) {
            return;
        }
        
        $status = sanitize_text_field($_GET['payment_status']);
        
        switch ($status) {
            case 'paid':
                $query->query_vars['meta_query'][] = [
                    'key' => '_status',
                    'value' => 'paid',
                    'compare' => '='
                ];
                break;
                
            case 'unpaid':
                $query->query_vars['meta_query'][] = [
                    [
                        'key' => '_status',
                        'value' => 'paid',
                        'compare' => '!='
                    ],
                    [
                        'relation' => 'OR',
                        [
                            'key' => '_payment_status',
                            'compare' => 'NOT EXISTS'
                        ],
                        [
                            'key' => '_payment_status',
                            'value' => ['pending', 'rejected'],
                            'compare' => 'NOT IN'
                        ]
                    ]
                ];
                break;
                
            case 'pending_bank':
                $query->query_vars['meta_query'][] = [
                    [
                        'key' => '_payment_status',
                        'value' => 'pending',
                        'compare' => '='
                    ],
                    [
                        'key' => '_payment_method',
                        'value' => 'bank',
                        'compare' => '='
                    ]
                ];
                break;
                
            case 'pending_cheque':
                $query->query_vars['meta_query'][] = [
                    [
                        'key' => '_payment_status',
                        'value' => 'pending',
                        'compare' => '='
                    ],
                    [
                        'key' => '_payment_method',
                        'value' => 'cheque',
                        'compare' => '='
                    ]
                ];
                break;
                
            case 'rejected':
                $query->query_vars['meta_query'][] = [
                    'key' => '_payment_status',
                    'value' => 'rejected',
                    'compare' => '='
                ];
                break;
        }
    }
    
    /**
     * Add row actions for manual payments
     * 
     * @param array $actions
     * @param \WP_Post $post
     * @return array
     */
    public function addManualPaymentRowActions($actions, $post): array {
        if ($post->post_type !== 'easy_invoice') {
            return $actions;
        }
        
        $payment_status = get_post_meta($post->ID, '_payment_status', true);
        $payment_method = get_post_meta($post->ID, '_payment_method', true);
        
        if ($payment_status === 'pending' && in_array($payment_method, ['bank', 'cheque'])) {
            $actions['verify_payment'] = sprintf(
                '<a href="%s">%s</a>',
                admin_url('admin.php?page=easy-invoice-invoices&action=verify-payment&invoice_id=' . $post->ID),
                __('Verify Payment', 'easy-invoice')
            );
        }
        
        return $actions;
    }
} 