<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Coupon;
use Illuminate\Http\Request;

class AdminCouponController extends Controller
{
    public function index()
    {
        $coupons = Coupon::withCount('usages')->latest()->get();
        return view('admin.coupons.index', compact('coupons'));
    }

    public function store(Request $request)
    {
        $request->validate([
            'code'        => 'required|string|unique:coupons,code',
            'amount'      => 'required|numeric|min:1',
            'max_uses'    => 'required|integer|min:1',
            'expires_at'  => 'nullable|date|after:today',
            'description' => 'nullable|string|max:255',
        ]);

        Coupon::create([
            'code'        => strtoupper(trim($request->code)),
            'amount'      => $request->amount,
            'max_uses'    => $request->max_uses,
            'expires_at'  => $request->expires_at,
            'description' => $request->description,
            'is_active'   => true,
        ]);

        return back()->with('success', 'Coupon created successfully.');
    }

    public function toggle($id)
    {
        $coupon = Coupon::findOrFail($id);
        $coupon->update(['is_active' => !$coupon->is_active]);
        return back()->with('success', 'Coupon status updated.');
    }

    public function destroy($id)
    {
        Coupon::findOrFail($id)->delete();
        return back()->with('success', 'Coupon deleted.');
    }
}
