<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\Coupon;
use App\Models\Package;
use App\Models\Server;
use App\Models\Transaction;
use App\Services\PayPalService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Session;

class PayPalOrderController extends Controller
{
    protected $paypalService;

    public function __construct(PayPalService $paypalService)
    {
        $this->paypalService = $paypalService;
    }

    /**
     * Create PayPal order for JavaScript SDK
     */
    public function createOrder(Request $request)
    {
        try {
            $request->validate([
                'package_slug' => 'required|string|exists:packages,slug',
                'server_id' => 'nullable|integer|exists:servers,id'
            ]);

            if (!Auth::check()) {
                return response()->json(['error' => 'Authentication required'], 401);
            }

            $packageSlug = $request->input('package_slug');
            $serverId = $request->input('server_id') ?? session('current_server_id');
            
            // Get server if specified
            $server = null;
            if ($serverId) {
                $server = Server::where('is_active', true)->find($serverId);
            }
            
            // Get package
            $query = Package::where('slug', $packageSlug)
                ->where('is_active', true);
                
            if ($server) {
                $query->forServer($server->id);
            } else {
                $query->withServers();
            }
            
            $package = $query->firstOrFail();

            // Check if PayPal is enabled and configured
            if (!config_value('store_paypal_enabled', true) || !$this->paypalService->isConfigured()) {
                return response()->json(['error' => 'PayPal payments are not available'], 400);
            }

            // Get coupon from session and calculate final amount
            $couponData = Session::get('coupon');
            $couponId = null;
            $discountAmount = 0;
            $originalAmount = $package->price;
            $finalAmount = $package->price;
            
            if ($couponData) {
                $coupon = Coupon::find($couponData['id']);
                
                if ($coupon && $coupon->isValid()) {
                    $couponId = $coupon->id;
                    $discountAmount = $couponData['discount_amount'];
                    $finalAmount = $couponData['final_price'];
                }
            }

            // Create pending transaction
            $transaction = Transaction::create([
                'user_id' => Auth::id(),
                'package_id' => $package->id,
                'server_id' => $server ? $server->id : null,
                'amount' => $finalAmount,
                'original_amount' => $originalAmount,
                'discount_amount' => $discountAmount,
                'coupon_id' => $couponId,
                'payment_method' => 'paypal',
                'status' => 'pending',
                'ip_address' => $request->ip(),
            ]);

            // Create item name
            $itemName = $package->name . ' - ' . config_value('site_name', 'EdgeRP');
            if ($server) {
                $itemName .= ' (' . $server->name . ')';
            }

            // Create PayPal order
            $paypalOrder = $this->paypalService->createOrder($transaction, $itemName, $package->description);
            
            if ($paypalOrder && isset($paypalOrder['id'])) {
                // Store PayPal order ID in transaction
                $transaction->update(['paypal_order_id' => $paypalOrder['id']]);
                
                // Clear coupon from session after successful order creation
                if ($couponData && $couponId) {
                    // Increment coupon uses
                    $coupon = Coupon::find($couponId);
                    if ($coupon) {
                        $coupon->incrementUses();
                    }
                    Session::forget('coupon');
                }
                
                Log::info('PayPal order created for transaction', [
                    'transaction_id' => $transaction->id,
                    'paypal_order_id' => $paypalOrder['id'],
                    'amount' => $finalAmount,
                    'user_id' => Auth::id()
                ]);

                // Return order ID for PayPal SDK
                return response()->json([
                    'id' => $paypalOrder['id'],
                    'transaction_id' => $transaction->id
                ]);
            }
            
            // If order creation failed, mark transaction as failed
            $transaction->update(['status' => 'failed']);
            
            return response()->json(['error' => 'Failed to create PayPal order'], 500);
            
        } catch (\Illuminate\Validation\ValidationException $e) {
            return response()->json(['error' => 'Invalid request data', 'details' => $e->errors()], 422);
        } catch (\Illuminate\Database\Eloquent\ModelNotFoundException $e) {
            return response()->json(['error' => 'Package not found'], 404);
        } catch (\Exception $e) {
            Log::error('PayPal order creation failed', [
                'error' => $e->getMessage(),
                'trace' => $e->getTraceAsString(),
                'request' => $request->all()
            ]);
            
            return response()->json(['error' => 'Payment processing failed'], 500);
        }
    }

    /**
     * Get order details (for debugging/verification)
     */
    public function getOrderDetails(Request $request, $orderId)
    {
        try {
            if (!Auth::check()) {
                return response()->json(['error' => 'Authentication required'], 401);
            }

            $orderDetails = $this->paypalService->getOrderDetails($orderId);
            
            if ($orderDetails) {
                return response()->json($orderDetails);
            }
            
            return response()->json(['error' => 'Order not found'], 404);
            
        } catch (\Exception $e) {
            Log::error('Failed to get PayPal order details', [
                'error' => $e->getMessage(),
                'order_id' => $orderId
            ]);
            
            return response()->json(['error' => 'Failed to retrieve order details'], 500);
        }
    }
}