<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Services\StripeService;
use App\Services\RazorpayService;
use App\Services\PhonePeService;
use Illuminate\Support\Facades\Log;
use App\Models\Transaction;
use App\Models\User;

class PaymentWebhookController extends Controller
{
    /**
     * Handle Stripe webhook
     */
    public function stripeWebhook(Request $request)
    {
        $payload = $request->getContent();
        $sigHeader = $request->header('Stripe-Signature');
        $webhookSecret = config('services.stripe.webhook_secret');

        try {
            $event = \Stripe\Webhook::constructEvent($payload, $sigHeader, $webhookSecret);
            
            Log::info('Stripe webhook received', ['type' => $event->type]);

            switch ($event->type) {
                case 'payment_intent.succeeded':
                    $this->handleStripePaymentSuccess($event->data->object);
                    break;
                    
                case 'payment_intent.payment_failed':
                    $this->handleStripePaymentFailed($event->data->object);
                    break;
                    
                case 'customer.subscription.created':
                case 'customer.subscription.updated':
                    $this->handleStripeSubscriptionUpdate($event->data->object);
                    break;
                    
                case 'customer.subscription.deleted':
                    $this->handleStripeSubscriptionCancelled($event->data->object);
                    break;
            }

            return response()->json(['status' => 'success']);
        } catch (\Exception $e) {
            Log::error('Stripe webhook error: ' . $e->getMessage());
            return response()->json(['error' => $e->getMessage()], 400);
        }
    }

    /**
     * Handle Razorpay webhook
     */
    public function razorpayWebhook(Request $request)
    {
        $webhookSecret = config('services.razorpay.webhook_secret');
        $webhookSignature = $request->header('X-Razorpay-Signature');
        
        try {
            // Verify webhook signature
            $expectedSignature = hash_hmac('sha256', $request->getContent(), $webhookSecret);
            
            if ($webhookSignature !== $expectedSignature) {
                return response()->json(['error' => 'Invalid signature'], 400);
            }

            $payload = $request->all();
            $event = $payload['event'];

            Log::info('Razorpay webhook received', ['event' => $event]);

            switch ($event) {
                case 'payment.authorized':
                case 'payment.captured':
                    $this->handleRazorpayPaymentSuccess($payload['payload']['payment']['entity']);
                    break;
                    
                case 'payment.failed':
                    $this->handleRazorpayPaymentFailed($payload['payload']['payment']['entity']);
                    break;
                    
                case 'subscription.charged':
                    $this->handleRazorpaySubscriptionCharged($payload['payload']['subscription']['entity']);
                    break;
                    
                case 'subscription.cancelled':
                    $this->handleRazorpaySubscriptionCancelled($payload['payload']['subscription']['entity']);
                    break;
            }

            return response()->json(['status' => 'success']);
        } catch (\Exception $e) {
            Log::error('Razorpay webhook error: ' . $e->getMessage());
            return response()->json(['error' => $e->getMessage()], 400);
        }
    }

    /**
     * Handle PhonePe webhook
     */
    public function phonepeWebhook(Request $request)
    {
        try {
            $base64Response = $request->input('response');
            $xVerify = $request->header('X-VERIFY');
            
            // Verify signature
            $saltKey = config('services.phonepe.salt_key');
            $saltIndex = config('services.phonepe.salt_index', 1);
            $expectedXVerify = hash('sha256', $base64Response . $saltKey) . '###' . $saltIndex;
            
            if ($xVerify !== $expectedXVerify) {
                return response()->json(['error' => 'Invalid signature'], 400);
            }

            $response = json_decode(base64_decode($base64Response), true);
            
            Log::info('PhonePe webhook received', ['response' => $response]);

            if ($response['success'] && $response['code'] === 'PAYMENT_SUCCESS') {
                $this->handlePhonePePaymentSuccess($response['data']);
            } else {
                $this->handlePhonePePaymentFailed($response['data']);
            }

            return response()->json(['status' => 'success']);
        } catch (\Exception $e) {
            Log::error('PhonePe webhook error: ' . $e->getMessage());
            return response()->json(['error' => $e->getMessage()], 400);
        }
    }

    /**
     * Handle PayPal webhook
     */
    public function paypalWebhook(Request $request)
    {
        try {
            $payload = $request->all();
            $event = $payload['event_type'];

            Log::info('PayPal webhook received', ['event' => $event]);

            switch ($event) {
                case 'PAYMENT.CAPTURE.COMPLETED':
                    $this->handlePayPalPaymentSuccess($payload['resource']);
                    break;
                    
                case 'PAYMENT.CAPTURE.DENIED':
                case 'PAYMENT.CAPTURE.DECLINED':
                    $this->handlePayPalPaymentFailed($payload['resource']);
                    break;
            }

            return response()->json(['status' => 'success']);
        } catch (\Exception $e) {
            Log::error('PayPal webhook error: ' . $e->getMessage());
            return response()->json(['error' => $e->getMessage()], 400);
        }
    }

    // Stripe handlers
    private function handleStripePaymentSuccess($paymentIntent)
    {
        $transaction = Transaction::where('gateway_transaction_id', $paymentIntent->id)->first();
        
        if ($transaction) {
            $transaction->update([
                'status' => 'completed',
                'paid_at' => now(),
            ]);

            // Activate subscription if applicable
            if ($transaction->plan_id) {
                $this->activateUserSubscription($transaction->user_id, $transaction->plan_id);
            }
        }
    }

    private function handleStripePaymentFailed($paymentIntent)
    {
        $transaction = Transaction::where('gateway_transaction_id', $paymentIntent->id)->first();
        
        if ($transaction) {
            $transaction->update(['status' => 'failed']);
        }
    }

    private function handleStripeSubscriptionUpdate($subscription)
    {
        // Update user subscription
        $user = User::where('stripe_customer_id', $subscription->customer)->first();
        
        if ($user) {
            $user->update([
                'subscription_status' => $subscription->status,
                'subscription_ends_at' => \Carbon\Carbon::createFromTimestamp($subscription->current_period_end),
            ]);
        }
    }

    private function handleStripeSubscriptionCancelled($subscription)
    {
        $user = User::where('stripe_customer_id', $subscription->customer)->first();
        
        if ($user) {
            $user->update([
                'subscription_status' => 'cancelled',
                'subscription_ends_at' => \Carbon\Carbon::createFromTimestamp($subscription->ended_at),
            ]);
        }
    }

    // Razorpay handlers
    private function handleRazorpayPaymentSuccess($payment)
    {
        $transaction = Transaction::where('gateway_transaction_id', $payment['id'])->first();
        
        if ($transaction) {
            $transaction->update([
                'status' => 'completed',
                'paid_at' => now(),
            ]);

            if ($transaction->plan_id) {
                $this->activateUserSubscription($transaction->user_id, $transaction->plan_id);
            }
        }
    }

    private function handleRazorpayPaymentFailed($payment)
    {
        $transaction = Transaction::where('gateway_transaction_id', $payment['id'])->first();
        
        if ($transaction) {
            $transaction->update(['status' => 'failed']);
        }
    }

    private function handleRazorpaySubscriptionCharged($subscription)
    {
        // Handle subscription charge
        Log::info('Razorpay subscription charged', ['subscription_id' => $subscription['id']]);
    }

    private function handleRazorpaySubscriptionCancelled($subscription)
    {
        // Handle subscription cancellation
        Log::info('Razorpay subscription cancelled', ['subscription_id' => $subscription['id']]);
    }

    // PhonePe handlers
    private function handlePhonePePaymentSuccess($data)
    {
        $transaction = Transaction::where('gateway_transaction_id', $data['merchantTransactionId'])->first();
        
        if ($transaction) {
            $transaction->update([
                'status' => 'completed',
                'paid_at' => now(),
            ]);

            if ($transaction->plan_id) {
                $this->activateUserSubscription($transaction->user_id, $transaction->plan_id);
            }
        }
    }

    private function handlePhonePePaymentFailed($data)
    {
        $transaction = Transaction::where('gateway_transaction_id', $data['merchantTransactionId'])->first();
        
        if ($transaction) {
            $transaction->update(['status' => 'failed']);
        }
    }

    // PayPal handlers
    private function handlePayPalPaymentSuccess($resource)
    {
        $transaction = Transaction::where('gateway_transaction_id', $resource['id'])->first();
        
        if ($transaction) {
            $transaction->update([
                'status' => 'completed',
                'paid_at' => now(),
            ]);

            if ($transaction->plan_id) {
                $this->activateUserSubscription($transaction->user_id, $transaction->plan_id);
            }
        }
    }

    private function handlePayPalPaymentFailed($resource)
    {
        $transaction = Transaction::where('gateway_transaction_id', $resource['id'])->first();
        
        if ($transaction) {
            $transaction->update(['status' => 'failed']);
        }
    }

    // Helper method to activate subscription
    private function activateUserSubscription($userId, $planId)
    {
        $user = User::find($userId);
        $plan = \App\Models\UserPlan::find($planId);
        
        if ($user && $plan) {
            $user->update([
                'current_plan_id' => $planId,
                'plan_expires_at' => now()->addDays($plan->duration ?? 30),
            ]);

            Log::info('User subscription activated', [
                'user_id' => $userId,
                'plan_id' => $planId,
            ]);
        }
    }
}
