<?php

namespace App\Http\Controllers\SuperAdmin;

use App\Http\Controllers\Controller;
use App\Models\{AuditLog, CompanyGroup};
use Illuminate\Http\Request;

class CompanyGroupController extends Controller
{
    public function store(Request $request)
    {
        $validated = $request->validate([
            'name' => 'required|string|max:150',
        ]);

        $group = CompanyGroup::create([
            'group_code' => CompanyGroup::nextGroupCode(),
            'name'       => $validated['name'],
        ]);

        AuditLog::record('create', 'company_group', (string) $group->id,
            null, ['name' => $group->name, 'code' => $group->group_code],
            "Company group created: {$group->name}");

        if ($request->expectsJson()) {
            return response()->json([
                'success' => true,
                'group'   => $group->loadCount('companies'),
            ]);
        }

        return back()->with('success', "Group {$group->group_code} created successfully.");
    }

    public function destroy(CompanyGroup $group)
    {
        $name = $group->name;
        $code = $group->group_code;

        $group->companies()->update(['company_group_id' => null]);
        $group->delete();

        AuditLog::record('delete', 'company_group', (string) $group->id,
            ['name' => $name, 'code' => $code], null,
            "Company group deleted: {$name}");

        if (request()->expectsJson()) {
            return response()->json(['success' => true]);
        }

        return back()->with('success', "Group {$code} deleted successfully.");
    }
}
