<?php

namespace App\Http\Controllers\Admin;

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

class CustomerGroupController extends Controller
{
    public function index()
    {
        $customerGroups = CustomerGroup::latest()->paginate(10);
        return view('admin.customer-groups.index', compact('customerGroups'));
    }

    public function create()
    {
        return view('admin.customer-groups.create');
    }

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

        $validated['permissions'] = $validated['permissions'] 
            ? json_decode($validated['permissions'], true) 
            : null;

        CustomerGroup::create($validated);

        return redirect()->route('admin.customer-groups.index')
            ->with('success', 'Customer group created successfully');
    }

    public function edit(CustomerGroup $customerGroup)
    {
        return view('admin.customer-groups.edit', compact('customerGroup'));
    }

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

        $validated['permissions'] = $validated['permissions'] 
            ? json_decode($validated['permissions'], true) 
            : null;

        $customerGroup->update($validated);

        return redirect()->route('admin.customer-groups.index')
            ->with('success', 'Customer group updated successfully');
    }

    public function destroy(CustomerGroup $customerGroup)
    {
        $customerGroup->delete();

        return redirect()->route('admin.customer-groups.index')
            ->with('success', 'Customer group deleted successfully');
    }
}
