<?php

namespace App\Http\Controllers\Front;

use App\Http\Controllers\Controller;
use App\Models\Cart;
use App\Models\Order;
use App\Models\PaymentGateway;
use App\Models\PaymentMethod;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Str;

class CheckoutController extends Controller
{
    public function index()
    {
        $sessionId = session()->getId();
        $cartItems = Cart::where(function ($q) use ($sessionId) {
            $q->where('session_id', $sessionId);
            if (Auth::check()) {
                $q->orWhere('user_id', Auth::id());
            }
        })->with('product')->get();

        if ($cartItems->isEmpty()) {
            return redirect()->route('cart')->with('error', 'Your cart is empty.');
        }

        $subtotal = $cartItems->sum(fn($item) => $item->quantity * $item->price);
        $paymentMethods = PaymentMethod::active()->ordered()->get();
        $paymentGateways = PaymentGateway::active()->ordered()->get();
        return view('front.checkout', compact('cartItems', 'subtotal', 'paymentMethods', 'paymentGateways'));
    }

    public function store(Request $request)
    {
        $data = $request->validate([
            'name' => 'required|string|max:255',
            'email' => 'required|email|max:255',
            'phone' => 'required|string|max:50',
            'address' => 'required|string',
            'city' => 'required|string|max:100',
            'state' => 'required|string|max:100',
            'zip' => 'required|string|max:20',
            'country' => 'required|string|max:100',
            'payment_method' => 'required|string|max:50',
            'notes' => 'nullable|string',
        ]);

        $sessionId = session()->getId();
        $cartItems = Cart::where(function ($q) use ($sessionId) {
            $q->where('session_id', $sessionId);
            if (Auth::check()) {
                $q->orWhere('user_id', Auth::id());
            }
        })->with('product')->get();

        if ($cartItems->isEmpty()) {
            return back()->with('error', 'Your cart is empty.');
        }

        $subtotal = $cartItems->sum(fn($item) => $item->quantity * $item->price);

        $address = "{$data['address']}, {$data['city']}, {$data['state']} {$data['zip']}, {$data['country']}";

        $paymentGateway = PaymentGateway::active()->where('code', $data['payment_method'])->first();
        $gatewayTransactionId = null;
        $gatewayResponse = null;

        if ($paymentGateway) {
            $resolved = $paymentGateway->resolveGateway();
            if ($resolved) {
                $gatewayResponse = $resolved->process([
                    'amount' => $subtotal,
                    'currency' => 'USD',
                    'return_url' => route('checkout.success', ['order' => 'ORDER_ID']),
                    'cancel_url' => route('checkout'),
                ], $paymentGateway);

                $gatewayTransactionId = $gatewayResponse['transaction_id'] ?? null;

                if (!($gatewayResponse['success'] ?? false)) {
                    return back()->with('error', $gatewayResponse['message'] ?? 'Payment processing failed.');
                }
            }
        }

        $order = Order::create([
            'user_id' => Auth::id(),
            'order_number' => 'ORD-' . strtoupper(Str::random(10)),
            'status' => 'pending',
            'subtotal' => $subtotal,
            'tax' => 0,
            'shipping' => 0,
            'total' => $subtotal,
            'shipping_address' => $address,
            'billing_address' => $address,
            'payment_method' => $data['payment_method'],
            'payment_status' => 'pending',
            'gateway_transaction_id' => $gatewayTransactionId,
            'gateway_response' => $gatewayResponse ? json_encode($gatewayResponse) : null,
            'notes' => $data['notes'],
        ]);

        foreach ($cartItems as $item) {
            $order->items()->create([
                'product_id' => $item->product_id,
                'product_name' => $item->product->name,
                'product_sku' => $item->product->sku,
                'price' => $item->price,
                'quantity' => $item->quantity,
                'subtotal' => $item->quantity * $item->price,
            ]);
        }

        Cart::whereIn('id', $cartItems->pluck('id'))->delete();

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

    public function success(Order $order)
    {
        return view('front.checkout-success', compact('order'));
    }
}
