<?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\CertificatePayment;
use App\Services\PaystackService;
use App\Services\PaymentProofService;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Http\RedirectResponse;

/**
 * CertificatePaymentController
 *
 * Handles certificate fee payments (Paystack or cash).
 *
 * Requirements: 8.3, 8.4, 8.5, 17.18
 */
class CertificatePaymentController extends Controller
{
    public function __construct(
        protected PaystackService $paystackService,
        protected PaymentProofService $proofService
    ) {
        $this->middleware('auth');
    }

    /**
     * Initialize certificate 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->canAccess()) {
            return response()->json(['error' => 'Not enrolled in this course'], 403);
        }

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

        // For Paystack
        $reference = $this->paystackService->generateReference('SP-CERT-');
        $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->certificate_fee,
            reference: $reference,
            currency: $enrollment->currency ?? 'KES',
            metadata: [
                'enrollment_id' => $enrollment->id,
                'fee_type' => 'certificate',
            ]
        );

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

    /**
     * Verify certificate 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) {
            return response()->json(['error' => 'Not enrolled'], 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
        CertificatePayment::create([
            'enrollment_id' => $enrollment->id,
            'user_id' => auth()->id(),
            'course_id' => $course->id,
            'payment_reference' => $reference,
            'payment_method' => 'paystack',
            'amount_paid' => $course->certificate_fee,
            'currency' => $enrollment->currency ?? 'KES',
            'payment_date' => now(),
        ]);

        // Mark certificate fee as paid
        $enrollment->update(['certificate_fee_paid' => true]);

        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) {
            return redirect()->back()->with('error', 'Not enrolled in this course');
        }

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

            $enrollment->update(['status' => 'pending_verification']);

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