<?php

namespace App\Http\Controllers;

use App\Models\Applicant;
use App\Models\Invoice;
use App\Models\CentralPaymentRecord;
use App\Services\FlutterwaveService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;

class FlutterwaveController extends Controller
{
    protected $flutterwave;

    public function __construct(FlutterwaveService $flutterwave)
    {
        $this->flutterwave = $flutterwave;
    }

    /**
     * Initialize payment for an applicant's registration fee
     */
    public function payRegistrationFee(Request $request)
    {
        $applicant = Applicant::findOrFail(session('applicant_id'));
        $amount = 50.00; // Fixed registration fee for now

        if ($request->has('save_card')) {
            session(['save_payment_method' => true]);
        }

        $data = [
            'tx_ref' => 'REG-' . $applicant->id . '-' . time(),
            'amount' => $amount,
            'currency' => 'RWF', 
            'email' => $applicant->email,
            'name' => $applicant->username,
            'title' => 'School Registration Fee',
            'description' => 'Provisioning fee for ' . ($applicant->school_name ?? 'New School'),
            'redirect_url' => route('flutterwave.callback'),
        ];

        $payment = $this->flutterwave->initializePayment($data);

        if ($payment && $payment['status'] === 'success') {
            return redirect($payment['data']['link']);
        }

        return back()->with('error', 'Unable to initialize payment. Please try again or use manual upload.');
    }

    /**
     * Initialize payment for an invoice
     */
    public function payInvoice(Invoice $invoice)
    {
        if (request()->has('save_card')) {
            session(['save_payment_method' => true]);
        }

        $data = [
            'tx_ref' => 'INV-' . $invoice->id . '-' . time(),
            'amount' => $invoice->amount,
            'currency' => 'RWF',
            'email' => $invoice->tenant->email ?? 'admin@school.com',
            'name' => $invoice->tenant->school_name ?? $invoice->tenant->tenant_id,
            'title' => 'Invoice Payment #' . $invoice->id,
            'description' => $invoice->description ?? 'Subscription payment',
            'redirect_url' => route('flutterwave.callback'),
        ];

        $payment = $this->flutterwave->initializePayment($data);

        if ($payment && $payment['status'] === 'success') {
            return redirect($payment['data']['link']);
        }

        return back()->with('error', 'Unable to initialize online payment.');
    }

    /**
     * Handle payment callback
     */
    public function handleCallback(Request $request)
    {
        $status = $request->get('status');
        $transactionId = $request->get('transaction_id');
        $txRef = $request->get('tx_ref');

        if ($status === 'successful' || $status === 'completed') {
            $verification = $this->flutterwave->verifyTransaction($transactionId);

            if ($verification && $verification['status'] === 'success') {
                $data = $verification['data'];
                
                // Save payment method if requested
                if (session('save_payment_method') && isset($data['card']['token'])) {
                    $this->savePaymentMethod($data, $txRef);
                    session()->forget('save_payment_method');
                }

                // Check if it's a registration payment
                if (str_starts_with($txRef, 'REG-')) {
                    return $this->processRegistrationPayment($data);
                }
                
                // Check if it's an invoice payment
                if (str_starts_with($txRef, 'INV-')) {
                    return $this->processInvoicePayment($data);
                }
            }
        }

        return redirect()->route('applicants.dashboard')->with('error', 'Payment failed or was cancelled.');
    }

    protected function savePaymentMethod($data, $txRef)
    {
        $applicantId = null;
        $tenantId = null;

        if (str_starts_with($txRef, 'REG-')) {
            $parts = explode('-', $txRef);
            $applicantId = $parts[1];
        } elseif (str_starts_with($txRef, 'INV-')) {
            $parts = explode('-', $txRef);
            $invoice = Invoice::find($parts[1]);
            $tenantId = $invoice ? $invoice->tenant_id : null;
        }

        \App\Models\TenantPaymentMethod::updateOrCreate(
            ['email' => $data['customer']['email']],
            [
                'tenant_id' => $tenantId,
                'applicant_id' => $applicantId,
                'token' => $data['card']['token'],
                'card_last4' => $data['card']['last_4digits'],
                'card_brand' => $data['card']['type'],
                'card_exp' => $data['card']['expiry'],
                'is_active' => true,
            ]
        );
    }

    protected function processRegistrationPayment($data)
    {
        // tx_ref format: REG-{id}-{time}
        $parts = explode('-', $data['tx_ref']);
        $applicantId = $parts[1];
        
        $applicant = Applicant::find($applicantId);
        if ($applicant) {
            $applicant->update([
                'amount_paid' => $data['amount'],
                // Payment is automatically verified by gateway
            ]);
            
            return redirect()->route('applicants.dashboard')->with('success', 'Payment successful! Your application is now under review.');
        }
        
        return redirect()->route('/')->with('error', 'Applicant not found.');
    }

    private function processInvoicePayment($data)
    {
        // tx_ref format: INV-{id}-{time}
        $parts = explode('-', $data['tx_ref']);
        $invoiceId = $parts[1];
        
        $invoice = Invoice::find($invoiceId);
        if ($invoice) {
            // Record the payment
            $paymentRecord = CentralPaymentRecord::create([
                'invoiceid' => $invoice->id,
                'tenant_id' => $invoice->tenant_id,
                'amt_paid' => $data['amount'],
                'paid' => true,
                'payment_date' => now(),
                'payment_method' => 'Flutterwave',
                'comments' => 'Transaction ID: ' . $data['id'],
            ]);

            // Credit the account using CentralBillingService
            app(\App\Services\CentralBillingService::class)->creditAccount($paymentRecord);

            return redirect()->route('admin.billing.index')->with('success', 'Mobile Money payment successful for invoice #' . $invoice->id);
        }

        return redirect()->route('admin.billing.index')->with('error', 'Invoice not found.');
    }

    /**
     * Webhook for asynchronous notifications
     */
    public function handleWebhook(Request $request)
    {
        // Verify signature (optional but recommended)
        $signature = $request->header('verif-hash');
        if (!$signature || $signature !== config('services.flutterwave.secret_key')) {
            // Handle error or just ignore
            // return response()->json(['status' => 'unauthorized'], 401);
        }

        $payload = $request->all();
        Log::info('Flutterwave Webhook: ', $payload);

        if ($payload['event'] === 'charge.completed' && $payload['data']['status'] === 'successful') {
            $data = $payload['data'];
            $txRef = $data['tx_ref'];

            if (str_starts_with($txRef, 'REG-')) {
                $parts = explode('-', $txRef);
                $applicantId = $parts[1];
                $applicant = Applicant::find($applicantId);
                if ($applicant) {
                    $applicant->update(['amount_paid' => $data['amount']]);
                }
            } elseif (str_starts_with($txRef, 'INV-')) {
                $parts = explode('-', $txRef);
                $invoiceId = $parts[1];
                $invoice = Invoice::find($invoiceId);
                if ($invoice) {
                    // Similar logic to processInvoicePayment but check if already processed
                    $exists = CentralPaymentRecord::where('comments', 'like', '%' . $data['id'] . '%')->exists();
                    if (!$exists) {
                        $paymentRecord = CentralPaymentRecord::create([
                            'invoiceid' => $invoice->id,
                            'tenant_id' => $invoice->tenant_id,
                            'amt_paid' => $data['amount'],
                            'paid' => true,
                            'payment_date' => now(),
                            'payment_method' => 'Flutterwave Webhook',
                            'comments' => 'Transaction ID: ' . $data['id'],
                        ]);
                        app(\App\Services\CentralBillingService::class)->creditAccount($paymentRecord);
                    }
                }
            }
        }

        return response()->json(['status' => 'success']);
    }
}
