<?php

namespace App\Http\Controllers\Meet;

use App\Http\Controllers\Controller;
use App\Http\Controllers\Meet\Concerns\ScopesToAccount;
use App\Models\ContactGroup;
use App\Services\Meet\ContactService;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\View\View;

class ContactGroupController extends Controller
{
    use ScopesToAccount;

    public function index(Request $request): View
    {
        $this->authorizeAbility($request, 'meetings.manage');
        $organization = $this->organization($request);

        $groups = ContactGroup::owned($this->ownerRef($request))
            ->where('organization_id', $organization->id)
            ->withCount('members')
            ->orderBy('name')
            ->get();

        return view('meet.contacts.groups', compact('groups', 'organization'));
    }

    public function store(Request $request): RedirectResponse
    {
        $this->authorizeAbility($request, 'meetings.manage');
        $organization = $this->organization($request);

        $validated = $request->validate([
            'name' => ['required', 'string', 'max:255'],
            'description' => ['nullable', 'string'],
            'emails' => ['nullable', 'string'],
        ]);

        $group = ContactGroup::create([
            'owner_ref' => $this->ownerRef($request),
            'organization_id' => $organization->id,
            'name' => $validated['name'],
            'description' => $validated['description'] ?? null,
        ]);

        if ($emails = trim((string) ($validated['emails'] ?? ''))) {
            foreach (preg_split('/[\s,;]+/', $emails) as $email) {
                if ($email = trim($email)) {
                    $group->members()->create(['email' => $email]);
                }
            }
        }

        return redirect()->route('meet.contacts.groups')->with('success', 'Contact group created.');
    }
}
