<?php

namespace App\Http\Controllers;

use App\Models\ContactRequest;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;
use Illuminate\Validation\ValidationException;

class ContactRequestController extends Controller
{
    /**
     * Public form endpoint (no auth) — accepts contact form submissions from the marketing site.
     */
    public function store(Request $request): JsonResponse|RedirectResponse
    {
        try {
            $data = $request->validate([
                'name' => ['required', 'string', 'max:150'],
                'email' => ['required', 'email', 'max:191'],
                'organization' => ['nullable', 'string', 'max:191'],
                'phone' => ['nullable', 'string', 'max:60'],
                'message' => ['nullable', 'string', 'max:5000'],
            ]);
        } catch (ValidationException $e) {
            if ($request->expectsJson() || $request->wantsJson()) {
                return response()->json([
                    'success' => false,
                    'message' => 'Please correct the highlighted fields and try again.',
                    'errors' => $e->errors(),
                ], 422);
            }

            throw $e;
        }

        $contact = ContactRequest::create([
            'name' => trim($data['name']),
            'email' => strtolower(trim($data['email'])),
            'organization' => isset($data['organization']) ? trim($data['organization']) : null,
            'phone' => isset($data['phone']) ? trim($data['phone']) : null,
            'message' => isset($data['message']) ? trim($data['message']) : null,
            'source' => 'website_contact_form',
            'status' => ContactRequest::STATUS_NEW,
            'ip_address' => $request->ip(),
            'user_agent' => substr((string) $request->userAgent(), 0, 255),
        ]);

        Log::info('New contact request received', [
            'id' => $contact->id,
            'email' => $contact->email,
            'organization' => $contact->organization,
        ]);

        $payload = [
            'success' => true,
            'message' => 'Thanks ' . $contact->name . '! Your message has been received. Our team will reply at ' . $contact->email . ' shortly.',
            'id' => $contact->id,
        ];

        if ($request->expectsJson() || $request->wantsJson()) {
            return response()->json($payload);
        }

        return redirect()
            ->back()
            ->with('success', $payload['message']);
    }
}
