<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Services\AuditLogService;
use App\Services\ContactSettingService;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Inertia\Inertia;
use Inertia\Response;

class ContactSettingController extends Controller
{
    public function edit(ContactSettingService $contactSettingService): Response
    {
        return Inertia::render('Admin/Settings/Contact', [
            'contact' => $contactSettingService->get(),
        ]);
    }

    public function update(
        Request $request,
        ContactSettingService $contactSettingService,
        AuditLogService $auditLogService
    ): RedirectResponse {
        $data = $request->validate([
            'support_phone' => ['nullable', 'string', 'max:40', 'regex:/^[0-9+\s().-]+$/'],
            'support_email' => ['nullable', 'email:rfc', 'max:191'],
            'whatsapp_number' => ['nullable', 'string', 'max:40', 'regex:/^[0-9+\s().-]+$/'],
            'whatsapp_group_url' => ['nullable', 'url', 'max:255', 'starts_with:https://'],
            'telegram_url' => ['nullable', 'url', 'max:255', 'starts_with:https://'],
            'website_url' => ['nullable', 'url', 'max:255', 'starts_with:https://'],
            'office_address' => ['nullable', 'string', 'max:1000'],
            'business_hours' => ['nullable', 'string', 'max:255'],
            'support_note' => ['nullable', 'string', 'max:3000'],
        ], [
            'support_phone.regex' => 'Support phone contains invalid characters.',
            'whatsapp_number.regex' => 'WhatsApp number contains invalid characters.',
            'whatsapp_group_url.starts_with' => 'WhatsApp group URL must start with https://',
            'telegram_url.starts_with' => 'Telegram URL must start with https://',
            'website_url.starts_with' => 'Website URL must start with https://',
        ]);

        $old = $contactSettingService->get();
        $new = $contactSettingService->update($data);

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

        return back()->with('success', 'Contact settings updated successfully.');
    }
}
