<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\EmailLog;
use App\Models\EmailTemplate;
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Inertia\Inertia;
use Inertia\Response;

class EmailLogController extends Controller
{
    use AuthorizesRequests;

    public function index(Request $request): Response
    {
        $this->authorize('viewAny', EmailTemplate::class); // reuse same permission gate for admin area

        $query = EmailLog::query()
            ->with(['template:id,name'])
            ->orderByDesc('created_at');

        $status = trim((string) $request->input('status', ''));
        if ($status !== '') {
            $query->where('status', $status);
        }
        if ($email = trim((string) $request->input('to'))) {
            $query->where('to_email', 'like', '%'.str_replace(['%', '_'], ['\%', '\_'], $email).'%');
        }
        if ($subject = trim((string) $request->input('subject'))) {
            $query->where('subject', 'like', '%'.str_replace(['%', '_'], ['\%', '\_'], $subject).'%');
        }
        if ($templateId = (int) $request->input('template_id')) {
            $query->where('template_id', $templateId);
        }
        if ($from = $request->date('date_from')) {
            $query->whereDate('created_at', '>=', $from);
        }
        if ($to = $request->date('date_to')) {
            $query->whereDate('created_at', '<=', $to);
        }

        $logs = $query->paginate(20)->withQueryString();
        $templates = EmailTemplate::query()->orderBy('name')->get(['id', 'name']);

        return Inertia::render('Admin/EmailLogs/Index', [
            'logs' => $logs,
            'filters' => [
                'status' => $status,
                'to' => $email ?? '',
                'subject' => $subject ?? '',
                'template_id' => $templateId ?: null,
                'date_from' => $request->input('date_from'),
                'date_to' => $request->input('date_to'),
            ],
            'templates' => $templates,
        ]);
    }

    public function show(EmailLog $emailLog): Response
    {
        $this->authorize('viewAny', EmailTemplate::class);

        $emailLog->load(['template:id,name', 'body']);

        return Inertia::render('Admin/EmailLogs/Show', [
            'log' => $emailLog,
        ]);
    }

    public function body(EmailLog $emailLog): JsonResponse
    {
        $this->authorize('viewAny', EmailTemplate::class);

        $emailLog->load('body');

        return response()->json([
            'html' => $emailLog->body?->body_html ?? '',
        ]);
    }
}
