<?php

namespace App\Http\Controllers\Meet;

use App\Http\Controllers\Controller;
use App\Http\Controllers\Meet\Concerns\ScopesToAccount;
use App\Models\Branch;
use App\Services\Meet\AuditLogger;
use App\Services\Meet\MeetPermissions;
use App\Services\Meet\SecurityPolicyService;
use App\Support\OrganizationBranding;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\View\View;

class SettingsController extends Controller
{
    use ScopesToAccount;

    public function edit(Request $request): View
    {
        $this->authorizeAbility($request, 'settings.view');
        $organization = $this->organization($request);
        $canManage = app(MeetPermissions::class)->can($this->member($request), 'settings.manage');

        $branchCount = Branch::owned($this->ownerRef($request))
            ->where('organization_id', $organization->id)
            ->count();

        return view('meet.settings.edit', [
            'organization' => $organization,
            'canManage' => $canManage,
            'branchCount' => $branchCount,
            'isAdmin' => app(MeetPermissions::class)->isAdmin($this->member($request)),
            'orgTypes' => [
                'business' => 'Business',
                'healthcare' => 'Healthcare',
                'education' => 'Education',
                'nonprofit' => 'Nonprofit',
            ],
        ]);
    }

    public function update(Request $request): RedirectResponse
    {
        $this->authorizeAbility($request, 'settings.manage');
        $organization = $this->organization($request);
        $owner = $this->ownerRef($request);

        $validated = $request->validate([
            'name' => ['required', 'string', 'max:255'],
            'timezone' => ['required', 'timezone'],
            'org_type' => ['required', 'string', 'in:business,healthcare,education,nonprofit'],
            'logo' => ['nullable', 'image', 'mimes:jpeg,png,jpg,webp,svg', 'max:2048'],
            'remove_logo' => ['nullable', 'boolean'],
        ]);

        $settings = $organization->settings ?? [];
        $settings['onboarded'] = true;
        $settings['org_type'] = $validated['org_type'];

        $logoPath = $organization->logo_path;

        if ($request->boolean('remove_logo')) {
            OrganizationBranding::deleteStoredLogo($organization);
            $logoPath = null;
        }

        if ($request->hasFile('logo')) {
            $logoPath = OrganizationBranding::storeLogo($organization, $request->file('logo'));
        }

        $organization->update([
            'name' => $validated['name'],
            'timezone' => $validated['timezone'],
            'logo_path' => $logoPath,
            'settings' => $settings,
        ]);

        AuditLogger::record($owner, 'organization.updated', $organization->id, $owner, \App\Models\Organization::class, $organization->id);

        return back()->with('success', 'Settings saved.');
    }

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

        return view('meet.settings.security', [
            'organization' => $organization,
            'policy' => array_merge(config('meet.security_defaults'), $organization->security_policy ?? []),
        ]);
    }

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

        $validated = $request->validate([
            'org_only' => ['sometimes', 'boolean'],
            'authenticated_only' => ['sometimes', 'boolean'],
            'allowed_domains' => ['nullable', 'string'],
            'recording_host_only' => ['sometimes', 'boolean'],
            'watermark_enabled' => ['sometimes', 'boolean'],
            'session_idle_minutes' => ['nullable', 'integer', 'min:15', 'max:480'],
        ]);

        $domains = collect(explode(',', (string) ($validated['allowed_domains'] ?? '')))
            ->map(fn ($d) => trim($d))
            ->filter()
            ->values()
            ->all();

        $security->updateOrganizationPolicy($organization, [
            'org_only' => $request->boolean('org_only'),
            'authenticated_only' => $request->boolean('authenticated_only'),
            'allowed_domains' => $domains,
            'recording_host_only' => $request->boolean('recording_host_only', true),
            'watermark_enabled' => $request->boolean('watermark_enabled'),
            'session_idle_minutes' => $validated['session_idle_minutes'] ?? 120,
        ]);

        return redirect()->route('meet.settings.security')->with('success', 'Security policy updated.');
    }
}
