<?php

namespace App\Http\Controllers\Api\V1\Website;

use App\Domain\Website\Models\ContactEnquiry;
use App\Http\Controllers\Controller;
use App\Support\ApiResponse;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Validation\Rule;

/** Inbox for messages sent through the public contact form. */
class ContactEnquiryController extends Controller
{
    public function index(Request $request): JsonResponse
    {
        abort_unless($request->user()->can('support.view'), 403);

        $enquiries = ContactEnquiry::query()
            ->where('company_id', $request->user()->company_id)
            ->with('handledBy:id,name')
            ->when($request->filled('status'), fn ($q) => $q->where('status', $request->string('status')))
            ->when($request->filled('audience'), fn ($q) => $q->where('audience', $request->string('audience')))
            ->latest('created_at')
            ->paginate($request->integer('per_page', 25));

        return ApiResponse::success(
            $enquiries->through(fn (ContactEnquiry $enquiry) => [
                'id' => $enquiry->uuid,
                'name' => $enquiry->name,
                'email' => $enquiry->email,
                'phone' => $enquiry->phone,
                'subject' => $enquiry->subject,
                'message' => $enquiry->message,
                'audience' => $enquiry->audience,
                'status' => $enquiry->status,
                'internal_notes' => $enquiry->internal_notes,
                'handled_by' => $enquiry->handledBy?->name,
                'handled_at' => $enquiry->handled_at?->toIso8601String(),
                'created_at' => $enquiry->created_at?->toIso8601String(),
            ])
        );
    }

    public function update(Request $request, string $uuid): JsonResponse
    {
        abort_unless($request->user()->can('support.respond'), 403);

        $validated = $request->validate([
            'status' => ['required', Rule::in(['new', 'in_progress', 'answered', 'closed', 'spam'])],
            'internal_notes' => ['nullable', 'string', 'max:2000'],
        ]);

        $enquiry = ContactEnquiry::where('uuid', $uuid)
            ->where('company_id', $request->user()->company_id)
            ->first();

        abort_if($enquiry === null, 404);

        $enquiry->update([
            'status' => $validated['status'],
            'internal_notes' => $validated['internal_notes'] ?? $enquiry->internal_notes,
            'handled_by' => $request->user()->getKey(),
            'handled_at' => now(),
        ]);

        return ApiResponse::success(null, 'Enquiry updated.');
    }
}
