<?php

namespace App\Http\Controllers\Coach;

use App\Http\Controllers\Controller;
use App\Http\Requests\Coach\RejectPaymentRequest;
use App\Models\Payment;
use App\Services\PaymentService;
use Illuminate\Http\RedirectResponse;
use Illuminate\View\View;

class PaymentController extends Controller
{
    public function __construct(private readonly PaymentService $paymentService)
    {
    }

    public function index(): View
    {
        $coach = auth()->user()->coach;

        $payments = Payment::query()
            ->whereHas('coachRequest', fn ($q) => $q->where('coach_id', $coach->id))
            ->with('coachRequest.athlete.user')
            ->latest('submitted_at')
            ->get();

        return view('coach.payments.index', compact('payments'));
    }

    public function approve(Payment $payment): RedirectResponse
    {
        $this->authorize('review', $payment);

        $this->paymentService->approve($payment, auth()->user());

        return back()->with('status', 'پرداخت تأیید شد.');
    }

    public function reject(RejectPaymentRequest $request, Payment $payment): RedirectResponse
    {
        $this->authorize('review', $payment);

        $this->paymentService->reject($payment, $request->user(), $request->string('reason')->toString());

        return back()->with('status', 'رسید رد شد. ورزشکار می‌تواند رسید جدید ارسال کند.');
    }
}
