<?php

namespace App\Http\Controllers\Admin;

use App\Enums\ReminderType;
use App\Http\Controllers\Controller;
use App\Models\Customer;
use App\Models\ReminderLog;
use Illuminate\Http\Request;
use Illuminate\View\View;

class ReminderLogController extends Controller
{
    public function __construct()
    {
        $this->middleware('permission:view_reminder_logs');
    }

    public function index(Request $request): View
    {
        $q = ReminderLog::query()
            ->with(['customer', 'invoice', 'quotation', 'payment'])
            ->orderByDesc('id');

        if ($request->filled('status')) {
            $q->where('status', $request->get('status'));
        }
        if ($request->filled('reminder_type')) {
            $q->where('reminder_type', $request->get('reminder_type'));
        }
        if ($request->filled('customer_id')) {
            $q->where('customer_id', $request->get('customer_id'));
        }
        if ($request->filled('date_from')) {
            $q->whereDate('created_at', '>=', $request->get('date_from'));
        }
        if ($request->filled('date_to')) {
            $q->whereDate('created_at', '<=', $request->get('date_to'));
        }

        $logs = $q->paginate(25)->withQueryString();
        $customers = Customer::query()->orderBy('name')->limit(500)->get(['id', 'name']);

        $reminderTypes = ReminderType::cases();

        return view('admin.reminders.logs.index', compact('logs', 'customers', 'reminderTypes'));
    }
}
