<?php

namespace App\Http\Controllers\Settings;

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

class CustomerGroupController extends Controller
{
    public function index()
    {
        $groups = CustomerGroup::withCount('customers')->get();
        return view('settings.customer_groups.index', compact('groups'));
    }

    public function store(Request $request)
    {
        $validated = $request->validate([
            'name' => 'required|string|max:255',
            'discount_percentage' => 'required|numeric|min:0|max:100',
            'description' => 'nullable|string',
            'points_unit' => 'required|integer|min:1',
            'currency_unit' => 'required|numeric|min:0',
        ]);

        CustomerGroup::create($validated);

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

    public function update(Request $request, CustomerGroup $customerGroup)
    {
        $validated = $request->validate([
            'name' => 'required|string|max:255',
            'discount_percentage' => 'required|numeric|min:0|max:100',
            'description' => 'nullable|string',
            'points_unit' => 'required|integer|min:1',
            'currency_unit' => 'required|numeric|min:0',
        ]);

        $customerGroup->update($validated);

        return back()->with('success', 'Customer Group updated successfully.');
    }

    public function destroy(CustomerGroup $customerGroup)
    {
        if ($customerGroup->customers()->count() > 0) {
            return back()->with('error', 'Cannot delete group with associated customers.');
        }

        $customerGroup->delete();

        return back()->with('success', 'Customer Group deleted successfully.');
    }
}
