<?php

namespace App\Http\Controllers\SelfPaced\Dashboard;

use App\Http\Controllers\Controller;
use App\Models\SelfPaced\PaymentProof;
use App\Services\PaymentProofService;
use Illuminate\Http\Request;
use Illuminate\View\View;
use Illuminate\Http\RedirectResponse;
use Symfony\Component\HttpFoundation\StreamedResponse;

/**
 * PaymentProofController
 *
 * Manages payment proof verification workflow.
 * Middleware: permission:verify self-paced payments
 *
 * Requirements: 17.11, 17.12, 17.13, 17.16
 */
class PaymentProofController extends Controller
{
    public function __construct(
        protected PaymentProofService $proofService
    ) {
        $this->middleware('auth');
        $this->middleware('permission:verify self-paced payments');
    }

    /**
     * List pending and recent proofs
     *
     * @param Request $request
     * @return View
     */
    public function index(Request $request): View
    {
        $perPage = $request->input('per_page', 20);
        $proofs = $this->proofService->getPendingProofs($perPage);

        return view('self-paced.dashboard.payment-proofs.index', [
            'proofs' => $proofs,
        ]);
    }

    /**
     * Show proof details
     *
     * @param PaymentProof $proof
     * @return View
     */
    public function show(PaymentProof $proof): View
    {
        return view('self-paced.dashboard.payment-proofs.show', [
            'proof' => $proof,
        ]);
    }

    /**
     * Approve a proof
     *
     * @param Request $request
     * @param PaymentProof $proof
     * @return RedirectResponse
     */
    public function approve(Request $request, PaymentProof $proof): RedirectResponse
    {
        try {
            $this->proofService->approveProof($proof, auth()->id());
            return redirect()->back()->with('success', 'Payment proof approved');
        } catch (\Exception $e) {
            return redirect()->back()->with('error', $e->getMessage());
        }
    }

    /**
     * Reject a proof
     *
     * @param Request $request
     * @param PaymentProof $proof
     * @return RedirectResponse
     */
    public function reject(Request $request, PaymentProof $proof): RedirectResponse
    {
        $request->validate(['rejection_reason' => ['required', 'string', 'min:10']]);

        try {
            $this->proofService->rejectProof(
                $proof,
                auth()->id(),
                $request->input('rejection_reason')
            );
            return redirect()->back()->with('success', 'Payment proof rejected');
        } catch (\Exception $e) {
            return redirect()->back()->with('error', $e->getMessage());
        }
    }

    /**
     * Stream proof file
     *
     * @param PaymentProof $proof
     * @return StreamedResponse
     */
    public function streamFile(PaymentProof $proof): StreamedResponse
    {
        return \Illuminate\Support\Facades\Storage::disk('public')
            ->download($proof->file_path, $proof->file_name);
    }
}
