<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\UserNotification;
use App\Services\AuditLogService;
use App\Services\LegalService;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Inertia\Inertia;
use Inertia\Response;

class LegalSettingController extends Controller
{
    public function edit(LegalService $legalService): Response
    {
        return Inertia::render('Admin/Settings/Legal', [
            'legal' => $legalService->get(),
        ]);
    }

    public function update(Request $request, LegalService $legalService, AuditLogService $auditLogService): RedirectResponse
    {
        $data = $request->validate([
            'terms_title' => ['required', 'string', 'max:191'],
            'terms_content' => ['required', 'string', 'min:40', 'max:50000'],
            'publish_new_version' => ['nullable', 'boolean'],
        ]);

        $old = $legalService->get();
        $new = $legalService->update(
            title: (string) $data['terms_title'],
            content: (string) $data['terms_content'],
            publishNewVersion: (bool) ($data['publish_new_version'] ?? true)
        );

        if ((int) ($new['terms_version'] ?? 1) > (int) ($old['terms_version'] ?? 1)) {
            UserNotification::query()->create([
                'created_by_admin_id' => $request->user()?->id,
                'title' => 'Terms & Conditions Updated',
                'message' => 'Our Terms & Conditions were updated. Please open About page and acknowledge to continue using the app.',
                'audience' => 'all',
                'recipient_ids_json' => null,
                'show_popup' => false,
                'show_in_inbox' => true,
                'is_active' => true,
            ]);
        }

        $auditLogService->log(
            admin: $request->user(),
            action: 'legal.terms.updated',
            entity: 'system_settings',
            entityId: 'legal',
            oldValues: $old,
            newValues: $new,
            ipAddress: $request->ip(),
            userAgent: $request->userAgent()
        );

        return back()->with('success', 'Terms & conditions updated successfully.');
    }
}
