<?php

namespace App\Http\Controllers\Seller;

use App\Http\Controllers\Controller;
use App\Models\Plan;
use App\Models\Subscription;
use App\Services\PaymentService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;

class SubscriptionController extends Controller
{
    protected $paymentService;

    public function __construct(PaymentService $paymentService)
    {
        $this->paymentService = $paymentService;
    }

    public function index()
    {
        $plans = Plan::active()->orderBy('price_inr')->get();
        $currentSubscription = Auth::user()->seller->subscription()->active()->first();
        return view('seller.subscription.index', compact('plans', 'currentSubscription'));
    }

    public function checkout(Plan $plan)
    {
        $seller = Auth::user()->seller;
        $requestedCurrency = request()->query('currency');
        // Allow override if valid, otherwise fallback to country-based default
        if (in_array($requestedCurrency, ['INR', 'USD'])) {
            $currency = $requestedCurrency;
        } else {
            $currency = $seller->country == 'India' ? 'INR' : 'USD';
        }
        $amount = $currency == 'INR' ? $plan->price_inr : $plan->price_usd;

        // Use dynamic GST from settings
        $gstPercentage = \App\Models\Setting::getValue('gst_percentage', 18);
        $gstAmount = ($currency == 'INR') ? ($amount * $gstPercentage / 100) : 0;
        $totalAmount = $amount + $gstAmount;

        // Create Pending Transaction
        $transaction = \App\Models\Transaction::create([
            'user_id' => Auth::id(),
            'seller_id' => $seller->id,
            'transaction_type' => 'subscription',
            'reference_id' => 0,
            'amount' => $amount,
            'platform_commission' => 0,
            'gst_amount' => $gstAmount,
            'total_amount' => $totalAmount,
            'currency' => $currency,
            'status' => 'pending',
            'metadata' => [
                'plan_id' => $plan->id,
                'plan_name' => $plan->name,
                'duration_days' => $plan->duration_days,
            ],
        ]);

        // Fetch Enabled Gateways
        $gateways = [
            'razorpay' => \App\Models\Setting::getValue('razorpay_enabled', false),
            'paypal' => \App\Models\Setting::getValue('paypal_enabled', false),
            'manual' => \App\Models\Setting::getValue('manual_payment_enabled', false),
        ];

        $razorpayOrder = null;
        if ($gateways['razorpay'] && $currency == 'INR') {
            $razorpayOrder = $this->paymentService->createRazorpayOrder($totalAmount, 'INR', 'sub_' . $transaction->id);
            if ($razorpayOrder && isset($razorpayOrder['id'])) {
                $transaction->update(['order_id' => $razorpayOrder['id'], 'payment_gateway' => 'razorpay']);
            }
        }

        return view('seller.subscription.checkout', compact('plan', 'currency', 'amount', 'transaction', 'gateways', 'razorpayOrder', 'gstAmount', 'totalAmount'));
    }

    public function paymentSuccess(Request $request)
    {
        $transactionId = $request->transaction_id;
        $paymentMethod = $request->payment_method;
        $paymentId = $request->payment_id;

        $transaction = \App\Models\Transaction::findOrFail($transactionId);

        // Security: Verify transaction belongs to current user
        if ($transaction->user_id !== Auth::id()) {
            return redirect()->route('seller.subscription.index')->with('error', 'Unauthorized access.');
        }

        if ($paymentMethod === 'manual') {
            $transaction->update([
                'status' => 'pending_approval',
                'payment_gateway' => 'manual',
                'payment_method' => 'bank_transfer',
                'payment_id' => $paymentId ?? 'MANUAL_' . time(),
            ]);

            return redirect()->route('seller.subscription.index')->with('success', 'Subscription request submitted. Waiting for admin approval.');
        }

        // Security: Verify Razorpay payment signature
        if ($paymentMethod === 'razorpay' && $request->has('razorpay_signature')) {
            $verified = $this->paymentService->verifyRazorpayPayment(
                $request->razorpay_signature,
                $paymentId,
                $transaction->order_id
            );

            if (!$verified) {
                $transaction->update(['status' => 'failed']);
                return redirect()->route('seller.subscription.index')->with('error', 'Payment verification failed. Please try again.');
            }
        }

        $transaction->update([
            'payment_id' => $paymentId,
            'payment_method' => $paymentMethod,
        ]);

        // Activate using Service
        $transactionService = app(\App\Services\TransactionService::class);
        $transactionService->activateTransaction($transaction);

        return redirect()->route('seller.subscription.index')->with('success', 'Subscription activated successfully!');
    }

    public function initiatePaypal(Request $request)
    {
        $plan = Plan::findOrFail($request->plan_id);
        $seller = Auth::user()->seller;
        $amount = $plan->price_usd;

        // Create Pending Transaction
        $transaction = \App\Models\Transaction::create([
            'user_id' => Auth::id(),
            'seller_id' => $seller->id,
            'transaction_type' => 'subscription',
            'reference_id' => 0,
            'amount' => $amount,
            'platform_commission' => 0,
            'gst_amount' => 0,
            'total_amount' => $amount,
            'currency' => 'USD',
            'status' => 'pending',
            'payment_gateway' => 'paypal',
            'metadata' => [
                'plan_id' => $plan->id,
                'plan_name' => $plan->name,
                'duration_days' => $plan->duration_days,
            ],
        ]);

        // Create PayPal Order
        $paypalOrder = $this->paymentService->createPaypalOrder(
            $amount, 
            'USD', 
            $plan->name . ' Subscription'
        );

        if ($paypalOrder['success'] && isset($paypalOrder['approval_url'])) {
            $transaction->update(['order_id' => $paypalOrder['order_id']]);
            
            // Store transaction ID in session for callback
            session(['paypal_transaction_id' => $transaction->id]);
            
            return redirect()->away($paypalOrder['approval_url']);
        }

        return redirect()->route('seller.subscription.index')
            ->with('error', 'Failed to create PayPal order. Please try again.');
    }

    public function paypalSuccess(Request $request)
    {
        $token = $request->query('token'); // PayPal order ID
        $transactionId = session('paypal_transaction_id');

        if (!$token || !$transactionId) {
            return redirect()->route('seller.subscription.index')
                ->with('error', 'Invalid PayPal callback.');
        }

        $transaction = \App\Models\Transaction::find($transactionId);
        
        if (!$transaction) {
            return redirect()->route('seller.subscription.index')
                ->with('error', 'Transaction not found.');
        }

        // Security: Verify transaction belongs to current user
        if ($transaction->user_id !== Auth::id()) {
            session()->forget('paypal_transaction_id');
            return redirect()->route('seller.subscription.index')
                ->with('error', 'Unauthorized access.');
        }

        // Capture the payment
        $captureResult = $this->paymentService->capturePaypalOrder($token);

        if ($captureResult['success']) {
            // Update payment details (don't change status - let activateTransaction handle it)
            $transaction->update([
                'payment_id' => $captureResult['payment_id'],
                'payment_method' => 'paypal',
            ]);

            // Activate subscription (this will set status to 'success')
            $transactionService = app(\App\Services\TransactionService::class);
            $transactionService->activateTransaction($transaction);

            // Clear session
            session()->forget('paypal_transaction_id');

            return redirect()->route('seller.subscription.index')
                ->with('success', 'PayPal payment successful! Subscription activated.');
        }

        return redirect()->route('seller.subscription.index')
            ->with('error', 'Failed to capture PayPal payment. Please contact support.');
    }


    // MOCK PAYMENT FOR TESTING - DISABLED IN PRODUCTION
    public function mockPayment(Request $request)
    {
        // Security: Block in production environment
        if (app()->environment('production')) {
            abort(404, 'Not Found');
        }
        
        $plan = Plan::findOrFail($request->plan_id);
        $amount = $request->currency == 'INR' ? $plan->price_inr : $plan->price_usd;
        
        $gstAmount = ($request->currency == 'INR') ? ($amount * 0.18) : 0;
        $totalAmount = $amount + $gstAmount;
        
        // Create Transaction
        $transaction = \App\Models\Transaction::create([
            'user_id' => Auth::id(),
            'seller_id' => Auth::user()->seller->id,
            'transaction_type' => 'subscription',
            'reference_id' => 0, // Will be updated after subscription activation
            'amount' => $amount,
            'platform_commission' => 0,
            'gst_amount' => $gstAmount,
            'total_amount' => $totalAmount,
            'currency' => $request->currency,
            'status' => 'pending', // activateTransaction will change to 'success'
            'payment_gateway' => 'mock_gateway',
            'payment_method' => 'test_card',
            'payment_id' => 'MOCK_' . strtoupper(uniqid()),
            'metadata' => [
                'plan_id' => $plan->id, 
                'plan_name' => $plan->name
            ],
        ]);

        // Activate Subscription
        $transactionService = app(\App\Services\TransactionService::class);
        $transactionService->activateTransaction($transaction);

        return redirect()->route('seller.subscription.index')
            ->with('success', 'Test Payment Successful! Subscription Activated.');
    }
}
