<?php

namespace App\Http\Controllers;

use App\Models\Order;
use App\Models\OrderItem;
use App\Models\Product;
use App\Services\Payment\PaymentServiceInterface;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Session;

class CheckoutController extends Controller
{
    protected $paymentService;

    public function __construct(PaymentServiceInterface $paymentService)
    {
        $this->middleware('auth');
        $this->paymentService = $paymentService;
    }

    public function index()
    {
        $currency = session('currency', 'USD');
        $cart = Session::get('cart', []);
        if (empty($cart)) {
            return redirect()->route('cart.index')->with('error', 'Your cart is empty!');
        }

        $cartItems = [];
        $total = 0;

        foreach ($cart as $id => $details) {
            $product = Product::find($id);
            if ($product) {
                $cartItems[] = [
                    'product' => $product,
                    'quantity' => $details['quantity'],
                    'subtotal' => $product->getCurrentPrice($currency) * $details['quantity']
                ];
                $total += $product->getCurrentPrice($currency) * $details['quantity'];
            }
        }

        return view('checkout.index', compact('cartItems', 'total', 'currency'));
    }

    public function process(Request $request)
    {
        $currency = session('currency', 'USD');
        $request->validate([
            'shipping_address' => 'required|array',
            'billing_address' => 'required|array',
            'payment_method' => 'required|string',
        ]);

        $cart = Session::get('cart', []);
        $total = 0;

        foreach ($cart as $id => $details) {
            $product = Product::find($id);
            if ($product) {
                $total += $product->getCurrentPrice($currency) * $details['quantity'];
            }
        }

        // Create order
        $order = Order::create([
            'user_id' => Auth::id(),
            'order_number' => Order::generateOrderNumber(),
            'total_amount' => $total,
            'currency' => $currency,
            'status' => 'pending',
            'payment_status' => 'pending',
            'payment_method' => $request->payment_method,
            'shipping_address' => $request->shipping_address,
            'billing_address' => $request->billing_address,
            'notes' => $request->notes,
        ]);

        // Create order items
        foreach ($cart as $id => $details) {
            $product = Product::find($id);
            if ($product) {
                OrderItem::create([
                    'order_id' => $order->id,
                    'product_id' => $product->id,
                    'quantity' => $details['quantity'],
                    'price' => $product->getCurrentPrice($currency),
                ]);
            }
        }

        // Initialize payment
        $paymentDetails = $this->paymentService->initializePayment($order);

        if ($request->payment_method === 'stripe') {
            return view('checkout.payment', compact('order', 'paymentDetails', 'currency'));
        }

        // For other payment methods
        if ($this->paymentService->processPayment($order, $paymentDetails)) {
            Session::forget('cart');
            return redirect()->route('checkout.success', $order);
        }

        return redirect()->back()->with('error', 'Payment processing failed. Please try again.');
    }

    public function confirmPayment(Request $request, Order $order)
    {
        if ($this->paymentService->verifyPayment($order, $request->all())) {
            $order->update([
                'status' => 'confirmed',
                'payment_status' => 'paid',
            ]);

            Session::forget('cart');
            return redirect()->route('checkout.success', $order);
        }

        return redirect()->back()->with('error', 'Payment verification failed. Please contact support.');
    }

    public function success(Order $order)
    {
        $currency = session('currency', 'USD');
        return view('checkout.success', compact('order', 'currency'));
    }
}
