<?php
namespace App\Http\Controllers;
use App\Models\Coupon;
use Illuminate\Http\Request;

class CouponController extends Controller {
    public function apply(Request $request) {
        $request->validate(['code' => 'required|string']);
        $code   = strtoupper(trim($request->code));
        $coupon = Coupon::where('code', $code)->first();

        $cartItems = \App\Models\CartItem::with('product')->where('session_id', session()->getId())->get();
        $subtotal  = $cartItems->sum(fn($i) => $i->product->price * $i->qty);

        if (!$coupon) return response()->json(['error' => 'Invalid coupon code.'], 422);
        if (!$coupon->isValid($subtotal)) return response()->json(['error' => 'Coupon not applicable (check min order, expiry, or usage limit).'], 422);

        $discount = $coupon->calculateDiscount($subtotal);
        session(['coupon' => ['id' => $coupon->id, 'code' => $coupon->code, 'discount' => $discount, 'type' => $coupon->type, 'value' => $coupon->value]]);

        return response()->json([
            'success'  => true,
            'code'     => $coupon->code,
            'discount' => $discount,
            'message'  => "Coupon applied! You save ₹" . number_format($discount),
        ]);
    }

    public function remove() {
        session()->forget('coupon');
        return response()->json(['success' => true]);
    }
}
