<?php

namespace App\Http\Controllers\SelfPaced\Learner;

use App\Http\Requests\SelfPaced\StorePaymentProofRequest;
use App\Http\Controllers\Controller;
use App\Models\SelfPaced\Course;
use App\Models\SelfPaced\ResitPayment;
use App\Services\PaystackService;
use App\Services\PaymentProofService;
use App\Services\SelfPacedService;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Http\RedirectResponse;

/**
 * ResitPaymentController
 *
 * Handles exam re-sit fee payments (Paystack or cash).
 *
 * Requirements: 18.8, 18.10, 18.11
 */
class ResitPaymentController extends Controller
{
    public function __construct(
        protected PaystackService $paystackService,
        protected PaymentProofService $proofService,
        protected SelfPacedService $selfPacedService
    ) {
        $this->middleware('auth');
    }

    /**
     * Initialize re-sit fee payment
     *
     * @param Request $request
     * @param Course $course
     * @return JsonResponse
     */
    public function init(Request $request, Course $course): JsonResponse
    {
        $enrollment = auth()->user()->enrollments()
            ->where('course_id', $course->id)
            ->first();

        if (!$enrollment || !$enrollment->isExamExhausted()) {
            return response()->json(['error' => 'Not eligible for re-sit'], 403);
        }

        // For cash payment
        if ($request->input('method') === 'cash') {
            return response()->json(['method' => 'cash']);
        }

        // For Paystack
        $reference = $this->paystackService->generateReference('SP-RESIT-');
        $config = \App\Models\SelfPaced\PaystackConfig::getActive();

        if (!$config) {
            return response()->json(['error' => 'Paystack not configured'], 500);
        }

        $inlineConfig = $this->paystackService->buildInlineConfig(
            publicKey: $config->public_key,
            email: auth()->user()->email,
            amount: (float)$course->exam_failure_fee,
            reference: $reference,
            currency: $enrollment->currency ?? 'KES',
            metadata: [
                'enrollment_id' => $enrollment->id,
                'fee_type' => 'resit',
                'resit_number' => $enrollment->resit_attempt_count + 1,
            ]
        );

        return response()->json($inlineConfig);
    }

    /**
     * Verify re-sit payment
     *
     * @param Request $request
     * @param Course $course
     * @return JsonResponse
     */
    public function verify(Request $request, Course $course): JsonResponse
    {
        $enrollment = auth()->user()->enrollments()
            ->where('course_id', $course->id)
            ->first();

        if (!$enrollment || !$enrollment->isExamExhausted()) {
            return response()->json(['error' => 'Not eligible'], 403);
        }

        $reference = $request->input('reference');
        $config = \App\Models\SelfPaced\PaystackConfig::getActive();

        if (!$config) {
            return response()->json(['error' => 'Payment system error'], 500);
        }

        // Verify with Paystack
        $result = $this->paystackService->verifyTransaction(
            $reference,
            $config->secret_key
        );

        if ($result['status'] !== 'success') {
            return response()->json(['error' => 'Payment verification failed'], 400);
        }

        // Create payment record
        ResitPayment::create([
            'enrollment_id' => $enrollment->id,
            'user_id' => auth()->id(),
            'course_id' => $course->id,
            'payment_reference' => $reference,
            'payment_method' => 'paystack',
            'amount_paid' => $course->exam_failure_fee,
            'currency' => $enrollment->currency ?? 'KES',
            'resit_number' => $enrollment->resit_attempt_count + 1,
            'payment_date' => now(),
        ]);

        // Perform reset
        $this->selfPacedService->performResitReset($enrollment);

        return response()->json(['success' => true]);
    }

    /**
     * Submit cash payment proof
     *
     * @param StorePaymentProofRequest $request
     * @param Course $course
     * @return RedirectResponse
     */
    public function submitProof(StorePaymentProofRequest $request, Course $course): RedirectResponse
    {
        $enrollment = auth()->user()->enrollments()
            ->where('course_id', $course->id)
            ->first();

        if (!$enrollment || !$enrollment->isExamExhausted()) {
            return redirect()->back()->with('error', 'Not eligible for re-sit');
        }

        try {
            $proof = $this->proofService->storeProof(
                $enrollment,
                $request->file('file'),
                $request->input('proof_type'),
                'resit',
                $course->exam_failure_fee,
                $enrollment->currency ?? 'KES'
            );

            return redirect()->back()->with('success', 'Re-sit payment proof submitted for verification');
        } catch (\Exception $e) {
            return redirect()->back()->with('error', $e->getMessage());
        }
    }
}
