<?php

namespace App\Http\Controllers;

use App\Models\Order;
use App\Models\OrderItem;
use App\Models\Product;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Str;

class CheckoutController extends Controller
{
    public function index()
    {
        $cart = session()->get('cart', []);

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

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

        $discount = 0;
        $appliedCoupon = session()->get('coupon');
        if ($appliedCoupon) {
            if ($appliedCoupon['type'] === 'percent') {
                $discount = ($subtotal * $appliedCoupon['value']) / 100;
            } elseif ($appliedCoupon['type'] === 'fixed') {
                $discount = min($subtotal, $appliedCoupon['value']);
            }
        }

        $shipping = ($subtotal > 499 || $subtotal == 0) ? 0 : 49;
        $total = max(0, $subtotal - $discount) + $shipping;

        $user = Auth::user();

        return view('pages.checkout', [
            'cart' => $cart,
            'subtotal' => $subtotal,
            'discount' => $discount,
            'shipping' => $shipping,
            'total' => $total,
            'appliedCoupon' => $appliedCoupon,
            'user' => $user,
        ]);
    }

    public function store(Request $request)
    {
        $cart = session()->get('cart', []);

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

        $request->validate([
            'customer_name' => 'required|string|max:255',
            'customer_email' => 'required|email|max:255',
            'customer_phone' => 'required|string|max:20',
            'shipping_address' => 'required|string|max:500',
            'city' => 'required|string|max:100',
            'state' => 'required|string|max:100',
            'pincode' => 'required|string|max:10',
            'payment_method' => 'required|string|in:cod,online',
            'notes' => 'nullable|string|max:500',
        ]);

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

        $discount = 0;
        $appliedCoupon = session()->get('coupon');
        if ($appliedCoupon) {
            if ($appliedCoupon['type'] === 'percent') {
                $discount = ($subtotal * $appliedCoupon['value']) / 100;
            } elseif ($appliedCoupon['type'] === 'fixed') {
                $discount = min($subtotal, $appliedCoupon['value']);
            }
        }

        $shipping = ($subtotal > 499 || $subtotal == 0) ? 0 : 49;
        $total = max(0, $subtotal - $discount) + $shipping;

        $orderNumber = 'DIV-' . strtoupper(Str::random(6));

        $order = Order::create([
            'order_number' => $orderNumber,
            'user_id' => Auth::id(),
            'customer_name' => $request->customer_name,
            'customer_email' => $request->customer_email,
            'customer_phone' => $request->customer_phone,
            'shipping_address' => $request->shipping_address,
            'city' => $request->city,
            'state' => $request->state,
            'pincode' => $request->pincode,
            'total_amount' => $total,
            'discount_amount' => $discount,
            'coupon_code' => $appliedCoupon['code'] ?? null,
            'payment_method' => $request->payment_method,
            'payment_status' => $request->payment_method === 'online' ? 'paid' : 'pending',
            'order_status' => 'pending',
            'notes' => $request->notes,
        ]);

        foreach ($cart as $item) {
            OrderItem::create([
                'order_id' => $order->id,
                'product_id' => $item['product_id'],
                'product_name' => $item['name'],
                'price' => $item['price'],
                'quantity' => $item['quantity'],
                'size' => $item['size'],
                'subtotal' => $item['price'] * $item['quantity'],
            ]);

            // Decrement product stock if available
            $product = Product::find($item['product_id']);
            if ($product && $product->stock >= $item['quantity']) {
                $product->decrement('stock', $item['quantity']);
            }
        }

        // Clear cart & coupon
        session()->forget(['cart', 'coupon']);

        return redirect()->route('checkout.success', ['order_number' => $order->order_number])
            ->with('success', 'Order placed successfully!');
    }

    public function success(string $order_number)
    {
        $order = Order::with('items')->where('order_number', $order_number)->firstOrFail();

        return view('pages.order-confirmation', [
            'order' => $order,
        ]);
    }
}
