<?php

namespace App\Http\Controllers;

use App\Models\CallLater;
use Illuminate\Http\Request;
use Inertia\Inertia;

class CallLaterController extends Controller
{
    public function index(Request $request): \Inertia\Response
    {
        $query = CallLater::query()
            ->with([
                'clientCase.person',
                'contract',
                'user',
                'activity',
            ])
            ->whereNull('completed_at')
            ->orderBy('call_back_at', 'asc');

        if ($request->filled('date_from')) {
            $query->whereDate('call_back_at', '>=', $request->date_from);
        }
        if ($request->filled('date_to')) {
            $query->whereDate('call_back_at', '<=', $request->date_to);
        }
        if ($request->filled('search')) {
            $term = '%'.$request->search.'%';
            $query->whereHas('clientCase.person', function ($q) use ($term) {
                $q->where('first_name', 'ilike', $term)
                    ->orWhere('last_name', 'ilike', $term)
                    ->orWhere('full_name', 'ilike', $term)
                    ->orWhereRaw("CONCAT(first_name, ' ', last_name) ILIKE ?", [$term]);
            });
        }

        $callLaters = $query->paginate(50)->withQueryString();

        return Inertia::render('CallLaters/Index', [
            'callLaters' => $callLaters,
            'filters' => $request->only(['date_from', 'date_to', 'search']),
        ]);
    }

    public function complete(CallLater $callLater): \Illuminate\Http\RedirectResponse
    {
        $callLater->update(['completed_at' => now()]);

        return back()->with('success', 'Klic označen kot opravljen.');
    }
}
