<?php

namespace App\Http\Controllers;

use App\Models\Order;
use App\Models\OrderItem;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class OrderController extends Controller
{
    public function index()
    {
        $orders = auth()->user()->orders()->with('items.product')->latest()->get();
        return view('orders.index', compact('orders'));
    }

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

        $total = 0;
        foreach($cart as $item) {
            $total += $item['price'] * $item['quantity'];
        }

        return view('checkout', compact('cart', 'total'));
    }

    public function store(Request $request)
    {
        $request->validate([
            'address' => 'required|string',
        ]);

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

        try {
            DB::transaction(function() use ($request, $cart) {
                $total = 0;
                foreach($cart as $id => $details) {
                    $product = \App\Models\Product::find($id);
                    if (!$product || $product->stock < $details['quantity']) {
                        throw new \Exception("Insufficient stock for " . ($product ? $product->name : "an item in your cart"));
                    }
                    $total += $details['price'] * $details['quantity'];
                }

                $order = Order::create([
                    'user_id' => auth()->id(),
                    'total_amount' => $total,
                    'address' => $request->address,
                    'status' => 'pending',
                ]);

                foreach($cart as $id => $details) {
                    OrderItem::create([
                        'order_id' => $order->id,
                        'product_id' => $id,
                        'quantity' => $details['quantity'],
                        'price' => $details['price'],
                    ]);

                    // Update stock and record movement
                    $product = \App\Models\Product::find($id);
                    if ($product) {
                        $product->decrement('stock', $details['quantity']);
                        
                        \App\Models\StockMovement::create([
                            'product_id' => $id,
                            'user_id' => auth()->id(),
                            'quantity' => -abs($details['quantity']),
                            'type' => 'sale',
                            'reference' => 'Order #' . $order->id,
                        ]);
                    }
                }

                session()->forget('cart');
            });
        } catch (\Exception $e) {
            return redirect()->back()->with('error', $e->getMessage());
        }

        return redirect()->route('order.index')->with('success', 'Order placed successfully!');
    }
}
