<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\ZakatTransaction;
use Illuminate\Http\JsonResponse;
use Illuminate\Support\Str;

class ZakatController extends Controller
{
    /**
     * Submit a Zakat donation calculation
     */
    public function donate(Request $request): JsonResponse
    {
        $request->validate([
            'name' => 'required|string|max:255',
            'email' => 'nullable|email|max:255',
            'phone' => 'required|string|max:50',
            'calculated_zakat_amount' => 'required|numeric|min:0',
            'donated_amount' => 'required|numeric|min:1',
        ]);

        $trackingId = 'ZAK-' . strtoupper(Str::random(8));

        $transaction = ZakatTransaction::create([
            'tracking_id' => $trackingId,
            'name' => $request->name,
            'email' => $request->email,
            'phone' => $request->phone,
            'calculated_zakat_amount' => $request->calculated_zakat_amount,
            'donated_amount' => $request->donated_amount,
            'status' => 'pending',
        ]);

        $sslService = new \App\Services\SslCommerzService();
        $gatewayUrl = $sslService->initiateZakatPayment($transaction);

        if (!$gatewayUrl) {
            return response()->json([
                'status' => 'error',
                'message' => 'Failed to connect to SSLCommerz gateway. Please try again.'
            ], 500);
        }

        return response()->json([
            'status' => 'success',
            'message' => 'Zakat pledge received.',
            'tracking_id' => $trackingId,
            'redirect_url' => $gatewayUrl
        ]);
    }

    /**
     * Handle successful payment redirect from SSLCommerz.
     */
    public function success(Request $request)
    {
        $tranId = $request->input('tran_id');
        $valId = $request->input('val_id');

        $transaction = ZakatTransaction::where('tracking_id', $tranId)->firstOrFail();
        $redirectUrl = config('services.sslcommerz.frontend_redirect');

        if ($transaction->status === 'completed') {
            return redirect($redirectUrl . '/?view=zakat&zakat_payment=success&trx_id=' . $tranId);
        }

        $sslService = new \App\Services\SslCommerzService();
        $isValid = $sslService->validatePayment($valId);

        if ($isValid) {
            $transaction->update(['status' => 'completed']);
            return redirect($redirectUrl . '/?view=zakat&zakat_payment=success&trx_id=' . $tranId);
        } else {
            $transaction->update(['status' => 'failed']);
            return redirect($redirectUrl . '/?view=zakat&zakat_payment=failed&trx_id=' . $tranId);
        }
    }

    /**
     * Handle failed payment redirect from SSLCommerz.
     */
    public function fail(Request $request)
    {
        $tranId = $request->input('tran_id');
        $transaction = ZakatTransaction::where('tracking_id', $tranId)->first();
        if ($transaction && $transaction->status === 'pending') {
            $transaction->update(['status' => 'failed']);
        }
        $redirectUrl = config('services.sslcommerz.frontend_redirect');
        return redirect($redirectUrl . '/?view=zakat&zakat_payment=failed&trx_id=' . $tranId);
    }

    /**
     * Handle canceled payment redirect from SSLCommerz.
     */
    public function cancel(Request $request)
    {
        $tranId = $request->input('tran_id');
        $transaction = ZakatTransaction::where('tracking_id', $tranId)->first();
        if ($transaction && $transaction->status === 'pending') {
            $transaction->update(['status' => 'failed']);
        }
        $redirectUrl = config('services.sslcommerz.frontend_redirect');
        return redirect($redirectUrl . '/?view=zakat&zakat_payment=cancelled&trx_id=' . $tranId);
    }

    /**
     * Handle IPN from SSLCommerz.
     */
    public function ipn(Request $request): JsonResponse
    {
        $tranId = $request->input('tran_id');
        $valId = $request->input('val_id');

        $transaction = ZakatTransaction::where('tracking_id', $tranId)->first();

        if ($transaction && $transaction->status === 'pending') {
            $sslService = new \App\Services\SslCommerzService();
            $isValid = $sslService->validatePayment($valId);

            if ($isValid) {
                $transaction->update(['status' => 'completed']);
                return response()->json(['status' => 'success', 'message' => 'IPN processed successfully.']);
            } else {
                $transaction->update(['status' => 'failed']);
                return response()->json(['status' => 'error', 'message' => 'Invalid credentials.'], 400);
            }
        }

        return response()->json(['status' => 'success', 'message' => 'Transaction already finalized.']);
    }
}
