<?php

namespace EasyInvoice\Traits;

/**
 * Trait for calculating payment totals
 * 
 * This trait provides shared functionality for calculating total payments
 * for invoices across different payment gateways.
 */
trait PaymentCalculationTrait
{
    /**
     * Calculate total payments for a specific invoice
     *
     * @param int $invoice_id
     * @return float
     */
    private function calculateTotalPaymentsForInvoice($invoice_id): float
    {
        // Get all payment records for this invoice
        $payments = get_posts([
            'post_type' => 'easy_invoice_payment',
            'post_status' => 'publish',
            'meta_query' => [
                [
                    'key' => '_invoice_id',
                    'value' => $invoice_id,
                    'compare' => '='
                ],
                [
                    'key' => '_status',
                    'value' => 'completed',
                    'compare' => '='
                ]
            ],
            'numberposts' => -1
        ]);
        
        $total_payments = 0.0;
        
        foreach ($payments as $payment) {
            $amount = get_post_meta($payment->ID, '_amount', true);
            if ($amount && is_numeric($amount)) {
                $total_payments += floatval($amount);
            }
        }
        
        return $total_payments;
    }
    
    /**
     * Check if invoice should be marked as paid based on total payments
     *
     * @param int $invoice_id
     * @param \EasyInvoice\Models\Invoice $invoice
     * @return bool
     */
    private function shouldMarkInvoiceAsPaid($invoice_id, $invoice): bool
    {
        $total_payments = $this->calculateTotalPaymentsForInvoice($invoice_id);
        $invoice_total = $invoice->getTotal();
        
        return $total_payments >= $invoice_total;
    }
    
    /**
     * Update invoice status to paid only if total payments are sufficient
     *
     * @param int $invoice_id
     * @param \EasyInvoice\Models\Invoice $invoice
     * @param string $gateway_name
     * @return bool True if status was updated, false otherwise
     */
    private function updateInvoiceStatusIfPaid($invoice_id, $invoice, $gateway_name = ''): bool
    {
        if ($this->shouldMarkInvoiceAsPaid($invoice_id, $invoice)) {
            $invoice->setStatus('paid');
            $invoice->save();
            
            // Log the status update
            if (method_exists($this, 'log')) {
                $this->log("Invoice #$invoice_id status updated to 'paid' - payments complete", 'info');
            } else {
                error_log("Easy Invoice: Invoice #$invoice_id status updated to 'paid' - payments complete");
            }
            
            // Trigger hook when invoice is marked as paid (for email notifications, etc.)
            // Get payment method and transaction ID from the most recent payment
            $payment_method = get_post_meta($invoice_id, '_payment_method', true) ?: $gateway_name ?: 'online';
            $transaction_id = get_post_meta($invoice_id, '_transaction_id', true) ?: '';
            $payment_amount = $invoice->getTotal();
            
            do_action('easy_invoice_payment_completed', $invoice_id, $invoice, [
                'payment_method' => $payment_method,
                'gateway_name' => $gateway_name,
                'transaction_id' => $transaction_id,
                'amount' => $payment_amount
            ]);
            
            return true;
        } else {
            // Log that status remains unchanged
            if (method_exists($this, 'log')) {
                $this->log("Invoice #$invoice_id status remains unchanged - partial payment received", 'info');
            } else {
                error_log("Easy Invoice: Invoice #$invoice_id status remains unchanged - partial payment received");
            }
            
            return false;
        }
    }
}
