<?php

namespace App\Http\Controllers\Tenant;

use App\Domain\Billing\InstallmentService;
use App\Enums\PaymentMethod;
use App\Http\Controllers\Controller;
use App\Http\Requests\InstallmentScheduleRequest;
use App\Models\Installment;
use App\Models\Invoice;

class InstallmentController extends Controller
{
    public function __construct(protected InstallmentService $service)
    {
    }

    /** The collections screen: overdue + upcoming, with one-click collect. */
    public function index()
    {
        abort_unless(auth()->user()->can('installments.view'), 403);

        return view('invoices.installments', [
            'overdue' => Installment::overdue()
                ->with(['invoice.patient:id,full_name,phone'])
                ->orderBy('due_date')->get(),
            'upcoming' => Installment::dueBetween(today(), today()->addDays(30))
                ->with(['invoice.patient:id,full_name,phone'])
                ->orderBy('due_date')->paginate(30),
            'widgets' => $this->service->dashboardWidgets(),
            'methods' => PaymentMethod::cases(),
        ]);
    }

    public function store(InstallmentScheduleRequest $request, Invoice $invoice)
    {
        $this->authorize('update', $invoice);

        $this->service->createSchedule(
            invoice: $invoice,
            months: $request->integer('months'),
            downPayment: $request->integer('down_payment', 0),
            firstDueDate: $request->first_due_date,
        );

        return back()->with('status', __('Installment schedule created.'));
    }
}
