<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\SmsLog;
use App\Models\SmsProfile;
use App\Models\SmsTemplate;
use Illuminate\Http\Request;
use Inertia\Inertia;

class SmsLogController extends Controller
{
    public function index(Request $request)
    {
        $query = SmsLog::query()->with(['profile:id,name', 'template:id,name,slug']);

        // Filters
        $status = $request->string('status')->toString();
        $profileId = $request->integer('profile_id');
        $templateId = $request->integer('template_id');
        $search = trim((string) $request->input('search', ''));
        $from = $request->date('from');
        $to = $request->date('to');

        if ($status !== '') {
            $query->where('status', $status);
        }
        if ($profileId) {
            $query->where('profile_id', $profileId);
        }
        if ($templateId) {
            $query->where('template_id', $templateId);
        }
        if ($search !== '') {
            $query->where(function ($q) use ($search): void {
                $q->where('to_number', 'ILIKE', "%$search%")
                    ->orWhere('sender', 'ILIKE', "%$search%")
                    ->orWhere('provider_message_id', 'ILIKE', "%$search%")
                    ->orWhere('message', 'ILIKE', "%$search%");
            });
        }
        if ($from) {
            $query->whereDate('created_at', '>=', $from);
        }
        if ($to) {
            $query->whereDate('created_at', '<=', $to);
        }

        $logs = $query->orderByDesc('id')->paginate(20)->withQueryString();

        if ($request->wantsJson() || $request->expectsJson()) {
            return response()->json($logs);
        }

        $profiles = SmsProfile::query()->orderBy('name')->get(['id', 'name']);
        $templates = SmsTemplate::query()->orderBy('name')->get(['id', 'name', 'slug']);

        return Inertia::render('Admin/SmsLogs/Index', [
            'logs' => $logs,
            'profiles' => $profiles,
            'templates' => $templates,
            'filters' => [
                'status' => $status ?: null,
                'profile_id' => $profileId ?: null,
                'template_id' => $templateId ?: null,
                'search' => $search ?: null,
                'from' => $from ? $from->format('Y-m-d') : null,
                'to' => $to ? $to->format('Y-m-d') : null,
            ],
        ]);
    }

    public function show(SmsLog $smsLog)
    {
        $smsLog->load(['profile:id,name', 'template:id,name,slug']);

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