<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Http\Requests\Admin\SmsReportIndexRequest;
use App\Http\Requests\Admin\SmsReportRecordsRequest;
use App\Models\SmsMessage;
use Illuminate\Http\JsonResponse;
use Illuminate\View\View;

class SmsReportController extends Controller
{
    public function index(SmsReportIndexRequest $request): View
    {
        return view('admin.sms-reports.index');
    }

    public function records(SmsReportRecordsRequest $request): JsonResponse
    {
        $query = SmsMessage::query();
        if ($request->filled('status') && $request->status !== 'all') {
            $query->where('status', $request->status);
        }
        $messages = $query->orderBy('created_at', 'desc')->get();

        $data = $messages->map(fn ($m) => [
            'id' => $m->id,
            'to_number' => $m->to_number,
            'from_number' => $m->from_number,
            'content' => str($m->content)->limit(80),
            'provider' => $m->provider,
            'status' => $m->status,
            'sent_at' => optional($m->sent_at)->format('Y-m-d H:i:s'),
            'delivered_at' => optional($m->delivered_at)->format('Y-m-d H:i:s'),
        ]);

        return response()->json([
            'draw' => (int) $request->input('draw'),
            'recordsTotal' => $data->count(),
            'recordsFiltered' => $data->count(),
            'data' => $data,
        ]);
    }
}
