<?php

namespace App\Http\Controllers\Admin;

use App\Models\CallbackRequest;
use Illuminate\Http\Request;
use Illuminate\View\View;

class CallbackRequestController extends Controller
{
    public function index(Request $request): View
    {
        $title = 'Callback Requests';

        $callbackRequests = CallbackRequest::query()
            ->when($request->filled('search'), function ($query) use ($request) {
                $search = trim((string) $request->input('search'));

                $query->where(function ($q) use ($search) {
                    $q->where('name', 'like', '%' . $search . '%')
                        ->orWhere('mobile', 'like', '%' . $search . '%')
                        ->orWhere('source_page', 'like', '%' . $search . '%')
                        ->orWhere('ip_address', 'like', '%' . $search . '%');
                });
            })
            ->when($request->filled('locale'), function ($query) use ($request) {
                $query->where('locale', $request->input('locale'));
            })
            ->when($request->filled('source_page'), function ($query) use ($request) {
                $query->where('source_page', 'like', '%' . trim((string) $request->input('source_page')) . '%');
            })
            ->when($request->filled('date_from'), function ($query) use ($request) {
                $query->whereDate('created_at', '>=', $request->input('date_from'));
            })
            ->when($request->filled('date_to'), function ($query) use ($request) {
                $query->whereDate('created_at', '<=', $request->input('date_to'));
            })
            ->latest()
            ->paginate(20)
            ->withQueryString();

        return view('admin.callback-requests.index', compact('title', 'callbackRequests'));
    }
}
