<?php

namespace App\Http\Controllers\Api\Admin;

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

class EmailCampaignRecipientApiController extends Controller
{
    public function records(Request $request, EmailCampaign $emailCampaign): JsonResponse
    {
        $draw = (int) $request->input('draw', 1);
        $start = (int) $request->input('start', 0);
        $length = (int) $request->input('length', 25);
        $search = $request->input('search.value', '');

        $base = $emailCampaign->recipients();

        $total = $base->count();

        if ($search !== '') {
            $base->where(function ($q) use ($search) {
                $q->where('email_snapshot', 'like', "%$search%")
                  ->orWhere('name_snapshot', 'like', "%$search%");
            });
        }

        $filtered = $base->count();

        $rows = $base->orderByDesc('id')
            ->skip($start)->take($length)
            ->get();

        return response()->json([
            'draw' => $draw,
            'recordsTotal' => $total,
            'recordsFiltered' => $filtered,
            'data' => $rows->map(fn ($r) => [
                'id' => $r->id,
                'email' => $r->email_snapshot,
                'name' => $r->name_snapshot,
                'status' => $r->status,
                'sent_at' => $r->sent_at?->format('Y-m-d H:i'),
                'opened_at' => $r->opened_at?->format('Y-m-d H:i'),
                'opened_count' => $r->opened_count,
                'clicked_at' => $r->clicked_at?->format('Y-m-d H:i'),
                'click_count' => $r->click_count,
                'last_error' => $r->last_error,
            ]),
        ]);
    }
}
