<?php

namespace App\Http\Controllers\user;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\DB;
use App\Models\User;
use App\Models\Deposit;
use App\Models\UserLedger; 

class NagorikpayController extends Controller
{
   
    public function pay(Request $request)
    {
        $request->validate(['amount' => 'required|numeric|min:300']);

        $user = Auth::user();
        $amount = $request->amount;
        $sessionKey = uniqid('np_', true); 

        $payload = [
            'success_url' => route('nagorikpay.success') . '?sessionKey=' . $sessionKey,
            'cancel_url' => route('nagorikpay.cancel'),
            'webhook_url' => route('nagorikpay.webhook'),
            'meta_data' => [
                'user_id' => $user->id,
                'username' => $user->name,
            ],
            'amount' => $amount,
            'cus_name' => $user->name,
            'cus_email' => $user->email,
        ];

        Log::info('Nagorikpay Payment Request Payload:', $payload);

        try {
            $response = Http::withHeaders([
                'API-KEY' => env('NAGORIKPAY_API_KEY'),
                'Content-Type' => 'application/json'
            ])->post('https://pay.zavirahost.com/api/payment/create', $payload);

            $result = $response->json();
            Log::info('Nagorikpay Payment Response:', ['status_code' => $response->status(), 'response_body' => $result]);

            if ($response->successful() && isset($result['status']) && $result['status'] == 1 && !empty($result['payment_url'])) {
                Deposit::create([
                    'user_id' => $user->id,
                    'amount' => $amount,
                    'trx' => $sessionKey, 
                    'status' => 'pending',
                    'method_name' => 'Nagorikpay',
                    'date' => now(),
                ]);

                return redirect()->away($result['payment_url']);
            }

            $errorMessage = $result['message'] ?? 'Payment initialization failed. Check API Key.';
            Log::error('Nagorikpay Initialization Failed:', ['error_message' => $errorMessage, 'full_response' => $result]);
            return redirect()->route('user.recharge')->with('error', $errorMessage);

        } catch (\Exception $e) {
            Log::emergency('Nagorikpay Connection Exception:', ['exception_message' => $e->getMessage()]);
            return redirect()->route('user.recharge')->with('error', 'Could not connect to payment gateway.');
        }
    }

 
    public function success(Request $request)
    {
        $transactionId = $request->query('transactionId');
        $sessionKey = $request->query('sessionKey');

        if (!$transactionId || !$sessionKey) {
            return redirect()->route('user.recharge')->with('error', 'Invalid transaction. Required parameters are missing.');
        }

        try {
            $deposit = Deposit::where('trx', $sessionKey)->where('status', 'pending')->first();

            if (!$deposit) {
                if (Deposit::where('trx', $transactionId)->where('status', 'approved')->exists()) {
                    return redirect()->route('dashboard')->with('success', 'Payment was already verified and credited.');
                }
                Log::warning('No matching pending deposit found for sessionKey:', ['sessionKey' => $sessionKey]);
                return redirect()->route('user.recharge')->with('error', 'Your payment session was not found or has expired.');
            }

            $response = Http::withHeaders([
                'API-KEY' => env('NAGORIKPAY_API_KEY'),
                'Content-Type' => 'application/json'
            ])->post('https://pay.zavirahost.com/api/payment/verify', [
                'transaction_id' => $transactionId
            ]);

            $result = $response->json();
            Log::info('Nagorikpay Verification Response:', $result);

            if ($response->successful() && isset($result['status']) && $result['status'] === 'COMPLETED') {
                $user = User::find($deposit->user_id);
                $amount = (float) $result['amount'];

                if ($user) {
                    DB::beginTransaction();
                    try {
                        $user->balance += $amount;
                        $user->save();

                        $deposit->update([
                            'trx' => $transactionId,
                            'status' => 'approved',
                        ]);

                       
                        UserLedger::create([
                            'user_id'       => $user->id,
                            'reason'        => 'Deposit via Onepays News',
                            'perticulation' => 'TRX: ' . $transactionId,
                            'amount'        => $amount,
                            'credit'        => $amount, 
                            'debit'         => 0,      
                            'status'        => 'approved',
                            'date'          => now(),
                        ]);

                        DB::commit(); 
                        return redirect()->route('dashboard')->with('success', "Payment of ৳{$amount} was successful!");

                    } catch (\Exception $dbException) {
                        DB::rollBack(); 
                        Log::emergency('Database update failed after Nagorikpay verification:', ['exception_message' => $dbException->getMessage()]);
                        return redirect()->route('user.recharge')->with('error', 'Payment successful, but failed to update balance. Contact support.');
                    }
                }
            }

            $errorMessage = $result['message'] ?? 'Payment verification failed.';
            return redirect()->route('user.recharge')->with('error', $errorMessage);

        } catch (\Exception $e) {
            Log::emergency('Nagorikpay Verification Exception:', ['exception_message' => $e->getMessage()]);
            return redirect()->route('user.recharge')->with('error', 'An error occurred during payment verification.');
        }
    }

    public function cancel(Request $request)
    {
        return redirect()->route('user.recharge')->with('error', 'You have cancelled the payment.');
    }
    
    public function webhook(Request $request)
    {
        Log::info('Nagorikpay Webhook Received:', $request->all());
        return response()->json(['status' => 'success']);
    }
}