<?php

namespace App\Models;

use CodeIgniter\Model;

class PaymentTransactionModel extends Model
{
    protected $table      = 'payment_transactions';
    protected $primaryKey = 'id';
    protected $allowedFields = [
        'transaction_id', 'reference', 'msisdn', 'amount', 'status', 'created_at',
        'currency', 'description', 'payment_method', 'gateway_reference', 'gateway_response',
        'client_ip', 'user_agent', 'failure_reason', 'processed_at', 'updated_at',
        'chargeback_status', 'chargeback_reason', 'chargeback_date', 'refund_status',
        'refund_amount', 'refund_reference', 'webhook_attempts', 'last_webhook_attempt', 'metadata'
    ];
    protected $useTimestamps = false;

    // Fetch all payment transactions
    public function getAllPaymentTransactions()
    {
        return $this->findAll();
    }

    // Fetch payment transactions filtered by status
    public function getPaymentTransactionsByStatus($status)
    {
        return $this->where('status', $status)->findAll();
    }

    // Fetch payment transactions by payment method
    public function getPaymentTransactionsByMethod($method)
    {
        return $this->where('payment_method', $method)->findAll();
    }

    // Fetch transactions with chargebacks
    public function getTransactionsWithChargebacks()
    {
        return $this->where('chargeback_status !=', 'none')->findAll();
    }

    // Fetch transactions with refunds
    public function getTransactionsWithRefunds()
    {
        return $this->where('refund_status !=', 'none')->findAll();
    }

    // Get transaction statistics for a date range
    public function getTransactionStats($startDate, $endDate)
    {
        $builder = $this->where('created_at >=', $startDate . ' 00:00:00')
                       ->where('created_at <=', $endDate . ' 23:59:59');

        $transactions = $builder->findAll();

        $stats = [
            'total_transactions' => count($transactions),
            'total_amount' => 0,
            'successful_transactions' => 0,
            'failed_transactions' => 0,
            'pending_transactions' => 0,
            'successful_amount' => 0,
            'failed_amount' => 0,
            'pending_amount' => 0,
            'chargebacks' => 0,
            'refunds' => 0,
            'refund_amount' => 0
        ];

        foreach ($transactions as $transaction) {
            $stats['total_amount'] += $transaction['amount'];
            
            switch ($transaction['status']) {
                case 'SUCCESS':
                    $stats['successful_transactions']++;
                    $stats['successful_amount'] += $transaction['amount'];
                    break;
                case 'FAILED':
                    $stats['failed_transactions']++;
                    $stats['failed_amount'] += $transaction['amount'];
                    break;
                case 'PENDING':
                    $stats['pending_transactions']++;
                    $stats['pending_amount'] += $transaction['amount'];
                    break;
            }

            if ($transaction['chargeback_status'] !== 'none') {
                $stats['chargebacks']++;
            }

            if ($transaction['refund_status'] !== 'none') {
                $stats['refunds']++;
                $stats['refund_amount'] += $transaction['refund_amount'];
            }
        }

        return $stats;
    }
}
