<?php

namespace App\Http\Controllers\Seller;

use App\Http\Controllers\Controller;
use App\Models\PromotionPackage;
use App\Models\ProductPromotion;
use App\Models\Product;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class PromotionController extends Controller
{
    /**
     * Show seller's active promotions dashboard
     */
    public function index()
    {
        $seller = Auth::user()->seller;
        $activePromotions = ProductPromotion::where('seller_id', $seller->id)
            ->with(['product', 'package'])
            ->active()
            ->latest()
            ->get();

        $expiredPromotions = ProductPromotion::where('seller_id', $seller->id)
            ->with(['product', 'package'])
            ->expired()
            ->latest()
            ->limit(5)
            ->get();

        return view('seller.promotions.index', compact('activePromotions', 'expiredPromotions'));
    }

    /**
     * Show available promotion packages
     */
    public function packages()
    {
        $packages = PromotionPackage::active()->orderBy('price')->get();
        return view('seller.promotions.packages', compact('packages'));
    }

    /**
     * Show product selection for promotion
     */
    public function selectProduct(Request $request, PromotionPackage $package)
    {
        $seller = Auth::user()->seller;
        $products = Product::where('seller_id', $seller->id)->get();

        // Check if seller has reached promotion limit
        $currentPromotions = ProductPromotion::where('seller_id', $seller->id)
            ->active()
            ->count();

        $maxPromotions = \App\Models\PromotionSetting::get('max_promotions_per_seller', 5);

        if ($currentPromotions >= $maxPromotions) {
            return redirect()->route('seller.promotions.index')
                ->with('error', "You have reached the maximum limit of {$maxPromotions} active promotions.");
        }

        $currency = $request->query('currency', Auth::user()->seller->country == 'India' ? 'INR' : 'USD');
        return view('seller.promotions.select-product', compact('package', 'products', 'currency'));
    }

    /**
     * Show checkout page
     */
    public function checkout(Request $request, PromotionPackage $package)
    {
        $validated = $request->validate([
            'product_ids' => 'required|array',
            'product_ids.*' => 'exists:products,id',
        ]);

        $seller = Auth::user()->seller;
        $productIds = $validated['product_ids'];
        $products = Product::whereIn('id', $productIds)->get();
        $currency = $request->input('currency', 'INR');

        // Calculate amounts
        $baseAmount = ($currency === 'INR') ? $package->price : $package->price_usd;
        
        $commissionPercentage = \App\Models\PromotionSetting::get('platform_commission_percentage', 0);
        $platformCommission = ($baseAmount * $commissionPercentage) / 100;
        
        // GST only for INR
        $gstEnabled = ($currency === 'INR') ? \App\Models\PromotionSetting::get('gst_enabled', false) : false;
        $gstPercentage = $gstEnabled ? \App\Models\PromotionSetting::get('gst_percentage', 18) : 0;
        $taxableAmount = $baseAmount + $platformCommission;
        $gstAmount = ($taxableAmount * $gstPercentage) / 100;
        
        $totalAmount = $taxableAmount + $gstAmount;

        // Determine Gateway
        $paymentGateway = ($currency === 'INR') ? 'razorpay' : 'paypal';

        // Create pending transaction
        $transaction = \App\Models\Transaction::create([
            'user_id' => Auth::id(),
            'seller_id' => $seller->id,
            'transaction_type' => 'promotion',
            'reference_id' => 0, 
            'amount' => $baseAmount,
            'platform_commission' => $platformCommission,
            'gst_amount' => $gstAmount,
            'total_amount' => $totalAmount,
            'currency' => $currency,
            'status' => 'pending',
            'payment_gateway' => $paymentGateway,
            'metadata' => [
                'package_id' => $package->id,
                'package_name' => $package->name,
                'product_ids' => $productIds,
                'product_count' => count($productIds),
            ],
        ]);

        $razorpayOrder = null;
        if ($paymentGateway === 'razorpay') {
            // Create Razorpay order
            $paymentService = app(\App\Services\PaymentService::class);
            $razorpayOrder = $paymentService->createRazorpayOrder(
                $totalAmount,
                'INR',
                'promo_' . $transaction->id
            );

            if ($razorpayOrder && isset($razorpayOrder['order_id'])) {
                $transaction->update([
                    'order_id' => $razorpayOrder['order_id']
                ]);
            }
        }

        return view('seller.promotions.checkout', compact(
            'package',
            'products',
            'productIds',
            'baseAmount',
            'platformCommission',
            'commissionPercentage',
            'gstAmount',
            'gstPercentage',
            'totalAmount',
            'transaction',
            'currency',
            'razorpayOrder'
        ));
    }

    /**
     * Initiate payment
     */
    public function initiatePayment(Request $request)
    {
        $validated = $request->validate([
            'transaction_id' => 'required|exists:transactions,id',
            'payment_gateway' => 'required|in:razorpay,paypal,manual',
            'payment_id' => 'nullable|string',
        ]);

        $transaction = \App\Models\Transaction::findOrFail($validated['transaction_id']);

        // Handle Manual Payment
        if ($validated['payment_gateway'] === 'manual') {
            $transaction->update([
                'status' => 'pending_approval',
                'payment_gateway' => 'manual',
                'payment_method' => 'bank_transfer',
                'payment_id' => $request->payment_id ?? 'MANUAL_' . time(),
            ]);

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

        if ($validated['payment_gateway'] === 'paypal') {
            $paymentService = app(\App\Services\PaymentService::class);
            $paypalOrder = $paymentService->createPaypalOrder(
                $transaction->total_amount,
                'USD',
                'Promotion: ' . ($transaction->metadata['package_name'] ?? 'Package')
            );

            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()->back()->with('error', 'Failed to create PayPal order');
        }

        $transaction->markAsProcessing();

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

    /**
     * Handle payment callback
     */
    /**
     * Handle payment callback
     */
    public function paymentCallback(Request $request)
    {
        $transactionId = $request->input('transaction_id');
        $transaction = \App\Models\Transaction::findOrFail($transactionId);

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

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

        // Verify Razorpay payment
        if ($request->has('razorpay_payment_id')) {
            $paymentService = app(\App\Services\PaymentService::class);
            $verified = $paymentService->verifyRazorpayPayment(
                $request->razorpay_signature,
                $request->razorpay_payment_id,
                $transaction->order_id
            );

            if ($verified) {
                return $this->processSuccessfulPayment($transaction, $request->razorpay_payment_id, 'razorpay');
            } else {
                $transaction->markAsFailed('Payment verification failed');
                return redirect()->route('seller.promotions.payment.failed', $transaction)
                    ->with('error', 'Payment verification failed');
            }
        }

        // PayPal or other gateways
        return $this->processSuccessfulPayment($transaction, $request->payment_id ?? 'PAYPAL_' . time(), 'paypal');
    }

    /**
     * Process successful payment and create promotions
     */
    private function processSuccessfulPayment($transaction, $paymentId, $paymentMethod)
    {
        $transaction->update([
            'payment_id' => $paymentId,
            'payment_method' => $paymentMethod,
        ]);

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

        return redirect()->route('seller.promotions.payment.success', $transaction);
    }

    /**
     * Payment success page
     */
    public function paymentSuccess(\App\Models\Transaction $transaction)
    {
        if ($transaction->user_id !== Auth::id()) {
            abort(403);
        }

        return view('seller.promotions.payment-success', compact('transaction'));
    }

    /**
     * Payment failed page
     */
    public function paymentFailed(\App\Models\Transaction $transaction)
    {
        if ($transaction->user_id !== Auth::id()) {
            abort(403);
        }

        return view('seller.promotions.payment-failed', compact('transaction'));
    }

    /**
     * Cancel a promotion
     */
    public function destroy(ProductPromotion $promotion)
    {
        // Verify seller owns this promotion
        if ($promotion->seller_id !== Auth::user()->seller->id) {
            abort(403);
        }

        $promotion->update(['status' => 'cancelled']);

        return redirect()->route('seller.promotions.index')
            ->with('success', 'Promotion cancelled successfully.');
    }
}
