<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Http\Requests\Admin\ReviewPaymentSubmissionRequest;
use App\Models\PaymentSubmission;
use App\Services\Payments\PaymentReviewService;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;
use Illuminate\View\View;
use Symfony\Component\HttpFoundation\StreamedResponse;

/**
 * مراجعة طلبات الدفع الواردة من المستخدمين.
 */
final class PaymentReviewController extends Controller
{
    public function __construct(
        private readonly PaymentReviewService $reviewService,
    ) {}

    public function index(Request $request): View
    {
        $status = $request->query('status');
        $allowed = ['pending', 'approved', 'rejected'];
        $statusFilter = is_string($status) && in_array($status, $allowed, true) ? $status : null;

        $submissions = PaymentSubmission::query()
            ->with(['user:id,full_name,username,email', 'paymentMethod:id,name_ar,slug', 'subscriptionPlan:id,name,slug'])
            ->when($statusFilter, fn ($q) => $q->where('status', $statusFilter))
            ->when(! $statusFilter, fn ($q) => $q->where('status', PaymentSubmission::STATUS_PENDING))
            ->latest('id')
            ->paginate(20)
            ->withQueryString();

        $counts = [
            'pending' => PaymentSubmission::query()->where('status', PaymentSubmission::STATUS_PENDING)->count(),
            'approved' => PaymentSubmission::query()->where('status', PaymentSubmission::STATUS_APPROVED)->count(),
            'rejected' => PaymentSubmission::query()->where('status', PaymentSubmission::STATUS_REJECTED)->count(),
        ];

        return view('admin.payments.reviews', [
            'submissions' => $submissions,
            'statusFilter' => $statusFilter ?? 'pending',
            'counts' => $counts,
        ]);
    }

    public function show(PaymentSubmission $submission): View
    {
        $submission->load(['user', 'paymentMethod', 'subscriptionPlan', 'reviewer:id,full_name,username']);

        return view('admin.payments.show', [
            'submission' => $submission,
        ]);
    }

    public function approve(ReviewPaymentSubmissionRequest $request, PaymentSubmission $submission): RedirectResponse
    {
        $this->reviewService->approve($submission, $request->user(), $request->validated('admin_note'));

        return redirect()
            ->route('admin.payments.reviews.show', $submission)
            ->with('success', 'تمت الموافقة على الدفع وتطبيقه على حساب المستخدم.');
    }

    public function reject(ReviewPaymentSubmissionRequest $request, PaymentSubmission $submission): RedirectResponse
    {
        $this->reviewService->reject($submission, $request->user(), $request->validated('admin_note'));

        return redirect()
            ->route('admin.payments.reviews.show', $submission)
            ->with('success', 'تم رفض طلب الدفع.');
    }

    public function proof(PaymentSubmission $submission): StreamedResponse
    {
        if ($submission->proof_path === null || ! Storage::disk('local')->exists($submission->proof_path)) {
            abort(404);
        }

        return Storage::disk('local')->download($submission->proof_path, 'payment-proof-'.$submission->id);
    }
}
