<?php

namespace App\Http\Controllers;

use App\Models\Address;
use App\Models\Order;
use App\Models\Product;
use Illuminate\Http\Request;

class CheckoutController extends Controller
{
    public function __construct()
    {
        $this->middleware('auth');
    }

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

        $items = collect($cart)
            ->map(function ($quantity, $id) {
                return [
                    'product' => Product::find($id),
                    'quantity' => $quantity,
                ];
            })
            ->filter(fn ($item) => $item['product'] !== null);

        if ($items->isEmpty()) {
            return redirect()->route('cart.index')->with('error', 'Your cart contains invalid items.');
        }

        $total = $items->sum(fn ($item) => $item['product']->display_price * $item['quantity']);
        $addresses = auth()->user()->addresses()->get();
        $defaultAddress = auth()->user()->addresses()->where('is_default', true)->first();

        return view('checkout.index', compact('addresses', 'defaultAddress', 'items', 'total'));
    }

    public function payment(Order $order)
    {
        $this->authorize('view', $order);

        return view('checkout.payment', compact('order'));
    }

    public function processPayment(Request $request, Order $order)
    {
        $this->authorize('view', $order);

        $validated = $request->validate([
            'razorpay_payment_id' => 'required_if:method,razorpay',
            'status' => 'required|in:success,failed',
        ]);

        if ($validated['status'] === 'success') {
            $order->update([
                'payment_status' => 'completed',
                'status' => 'Processing',
            ]);
            return redirect()->route('orders.show', $order)->with('success', 'Payment successful! Your order is being processed.');
        } else {
            $order->update(['payment_status' => 'failed']);
            return redirect()->route('checkout.index')->with('error', 'Payment failed. Please try again.');
        }
    }

    public function saveAddress(Request $request)
    {
        $validated = $request->validate([
            'type' => 'required|in:billing,shipping',
            'full_name' => 'required|string',
            'phone' => 'required|string',
            'email' => 'required|email',
            'address' => 'required|string',
            'city' => 'required|string',
            'state' => 'required|string',
            'postal_code' => 'required|string',
            'is_default' => 'boolean',
        ]);

        $address = auth()->user()->addresses()->create($validated);

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