<?php

namespace App\Http\Controllers\Store;

use App\Http\Controllers\Controller;
use App\Models\Coupon;
use App\Models\Package;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Session;

class CouponController extends Controller
{
    /**
     * Apply a coupon to the session
     */
    public function apply(Request $request)
    {
        $request->validate([
            'coupon_code' => 'required|string|max:50',
            'package_slug' => 'required|string|exists:packages,slug',
        ]);

        $package = Package::where('slug', $request->package_slug)
            ->where('is_active', true)
            ->firstOrFail();

        $coupon = Coupon::where('code', $request->coupon_code)->first();

        // Check if coupon exists
        if (!$coupon) {
            return response()->json([
                'success' => false,
                'message' => 'Invalid coupon code.'
            ]);
        }

        // Check if coupon is valid
        if (!$coupon->isValid()) {
            return response()->json([
                'success' => false,
                'message' => 'This coupon is no longer valid.'
            ]);
        }

        // Calculate discount
        $originalPrice = $package->price;
        $discountAmount = $coupon->calculateDiscount($originalPrice);
        $finalPrice = $originalPrice - $discountAmount;

        // Store in session
        Session::put('coupon', [
            'id' => $coupon->id,
            'code' => $coupon->code,
            'discount_amount' => $discountAmount,
            'original_price' => $originalPrice,
            'final_price' => $finalPrice,
        ]);

        return response()->json([
            'success' => true,
            'message' => 'Coupon applied successfully!',
            'original_price' => number_format($originalPrice, 2),
            'discount_amount' => number_format($discountAmount, 2),
            'final_price' => number_format($finalPrice, 2),
            'coupon_code' => $coupon->code,
        ]);
    }

    /**
     * Remove a coupon from the session
     */
    public function remove()
    {
        Session::forget('coupon');
        
        return response()->json([
            'success' => true,
            'message' => 'Coupon removed successfully!'
        ]);
    }
}