<?php

namespace App\Services\Payment;

use App\Models\PaymentGateway;
use App\Models\PaymentLog;
use App\Models\Transaction;
use Illuminate\Support\Str;

class OfflinePaymentService
{
    protected $gateway;

    public function __construct()
    {
        $this->gateway = PaymentGateway::getByName('offline');
    }

    /**
     * Create offline payment request
     */
    public function createPaymentRequest($amount, $userId, $metadata = [])
    {
        if (!$this->gateway || !$this->gateway->is_active) {
            throw new \Exception('Offline payment is not enabled');
        }

        $reference = 'OFF_' . Str::upper(Str::random(16));

        $instructions = $this->gateway->settings['instructions'] ?? 'Please contact admin for payment instructions';
        $bankDetails = $this->gateway->settings['bank_details'] ?? '';
        $requiresApproval = $this->gateway->settings['requires_approval'] ?? true;

        PaymentLog::logEvent(
            'offline',
            'create_payment_request',
            [
                'amount' => $amount,
                'user_id' => $userId,
                'metadata' => $metadata
            ],
            ['reference' => $reference],
            'success'
        );

        return [
            'success' => true,
            'reference' => $reference,
            'instructions' => $instructions,
            'bank_details' => $bankDetails,
            'requires_approval' => $requiresApproval,
            'message' => 'Please make payment and wait for admin approval'
        ];
    }

    /**
     * Admin approve payment
     */
    public function approvePayment(Transaction $transaction, $adminId, $notes = null)
    {
        if ($transaction->payment_gateway !== 'offline') {
            return [
                'success' => false,
                'message' => 'This is not an offline payment transaction'
            ];
        }

        $transaction->markAsSuccessful([
            'approved_by' => $adminId,
            'approved_at' => now()->toISOString(),
            'admin_notes' => $notes
        ]);

        PaymentLog::logEvent(
            'offline',
            'payment_approved',
            [
                'transaction_id' => $transaction->id,
                'approved_by' => $adminId,
                'notes' => $notes
            ],
            ['status' => 'approved'],
            'success',
            $transaction->id
        );

        return [
            'success' => true,
            'message' => 'Payment approved successfully'
        ];
    }

    /**
     * Admin reject payment
     */
    public function rejectPayment(Transaction $transaction, $adminId, $reason = null)
    {
        if ($transaction->payment_gateway !== 'offline') {
            return [
                'success' => false,
                'message' => 'This is not an offline payment transaction'
            ];
        }

        $transaction->markAsFailed([
            'rejected_by' => $adminId,
            'rejected_at' => now()->toISOString(),
            'rejection_reason' => $reason
        ]);

        PaymentLog::logEvent(
            'offline',
            'payment_rejected',
            [
                'transaction_id' => $transaction->id,
                'rejected_by' => $adminId,
                'reason' => $reason
            ],
            ['status' => 'rejected'],
            'success',
            $transaction->id
        );

        return [
            'success' => true,
            'message' => 'Payment rejected'
        ];
    }

    /**
     * Get pending offline payments (for admin review)
     */
    public static function getPendingPayments()
    {
        return Transaction::where('payment_gateway', 'offline')
            ->where('gateway_status', 'pending')
            ->with('user')
            ->orderBy('created_at', 'desc')
            ->get();
    }
}
