<?php

namespace App\Http\Controllers\Web;

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


use Illuminate\Support\Facades\Auth;


class CouponController extends Controller
{
    public function index()
    {
        $coupons = Coupon::all();
        return view('admin.coupons.index', compact('coupons'));
    }

    public function create()
    {
        return view('admin.coupons.create');
    }

    public function store(Request $request)
    {
        $request->validate([
            'code' => 'required|unique:coupons|max:255',
            'type' => 'required',
            'value' => 'required|numeric',
            'max_discount' => 'nullable|numeric',
            'min_order_value' => 'required|numeric',
            'usage_limit' => 'nullable|integer',
            'expire_date' => 'nullable',
        ]);


        $user = Auth::user();
        $dealerId = Auth::id();

        $request['dealer_id'] = $dealerId; 

        Coupon::create($request->all());
        return redirect()->route('coupons.index')
                         ->with('success', 'Coupon created successfully.');
    }

    public function show(Coupon $coupon)
    {
        return view('admin.coupons.show', compact('coupon'));
    }

    public function edit(Coupon $coupon)
    {
        return view('admin.coupons.edit', compact('coupon'));
    }

    public function update(Request $request, Coupon $coupon)
    {
        $request->validate([
            'code' => 'required|max:255|unique:coupons,code,' . $coupon->id,
            'type' => 'required',
            'value' => 'required|numeric',
            'max_discount' => 'nullable|numeric',
            'min_order_value' => 'required|numeric',
            'usage_limit' => 'nullable|integer',
            'expiration_date' => 'nullable',
        ]);

        $coupon->update($request->all());
        return redirect()->route('coupons.index')
                         ->with('success', 'Coupon updated successfully.');
    }

    public function destroy(Coupon $coupon)
    {
        $coupon->delete();
        return redirect()->route('coupons.index')
                         ->with('success', 'Coupon deleted successfully.');
    }
}
