<?php

namespace App\Http\Controllers\SuperAdmin;

use App\Http\Controllers\Controller;
use App\Models\ContactSubmission;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

class ContactSubmissionController extends Controller
{
    public function index(Request $request): JsonResponse
    {
        $query = ContactSubmission::latest();

        if ($request->filled('status')) {
            $query->where('status', $request->input('status'));
        }

        if ($request->filled('search')) {
            $s = $request->input('search');
            $query->where(function ($q) use ($s) {
                $q->where('name',    'like', "%{$s}%")
                  ->orWhere('email',   'like', "%{$s}%")
                  ->orWhere('subject', 'like', "%{$s}%")
                  ->orWhere('message', 'like', "%{$s}%")
                  ->orWhere('business','like', "%{$s}%");
            });
        }

        $submissions = $query->paginate(25);

        return response()->json([
            'data'       => $submissions->items(),
            'meta'       => [
                'current_page' => $submissions->currentPage(),
                'last_page'    => $submissions->lastPage(),
                'total'        => $submissions->total(),
                'from'         => $submissions->firstItem(),
                'to'           => $submissions->lastItem(),
            ],
            'unread_count' => ContactSubmission::unread()->count(),
        ]);
    }

    public function show(ContactSubmission $contactSubmission): JsonResponse
    {
        $contactSubmission->markRead();

        return response()->json($contactSubmission);
    }

    public function updateStatus(Request $request, ContactSubmission $contactSubmission): JsonResponse
    {
        $request->validate([
            'status' => 'required|in:new,read,replied,archived',
            'notes'  => 'nullable|string|max:2000',
        ]);

        $contactSubmission->update($request->only('status', 'notes'));

        return response()->json($contactSubmission);
    }

    public function destroy(ContactSubmission $contactSubmission): JsonResponse
    {
        $contactSubmission->delete();

        return response()->json(['message' => 'Submission deleted.']);
    }

    public function stats(): JsonResponse
    {
        return response()->json([
            'total'    => ContactSubmission::count(),
            'new'      => ContactSubmission::where('status', 'new')->count(),
            'replied'  => ContactSubmission::where('status', 'replied')->count(),
            'archived' => ContactSubmission::where('status', 'archived')->count(),
        ]);
    }
}
