<?php

namespace App\Http\Controllers;

use App\Http\Requests\StoreEventRegistrationRequest;
use App\Models\Event;
use App\Models\EventRegistration;
use App\Services\PayUService;
use Illuminate\Support\Str;

class EventRegistrationController extends Controller
{
    protected $payuService;

    public function __construct(PayUService $payuService)
    {
        $this->payuService = $payuService;
    }

    /**
     * Show event registration form
     */
    public function create()
    {
        // Get only active events for external registration
        $events = Event::active()->get();

        return view('registration.create', compact('events'));
    }

    /**
     * Store registration and initiate payment
     */
    public function store(StoreEventRegistrationRequest $request)
    {
        $event = Event::findOrFail($request->eventid);

        // Verify event registration is open
        if (!$event->isRegistrationOpen()) {
            return redirect()->back()
                           ->withErrors(['event' => 'Registration for this event is no longer open.']);
        }

        // Calculate the payable amount
        $amount = $event->getActualFees();

        // Generate unique registration ID
        $regId = $this->generateUniqueRegId();

        // Create registration record
        $registration = EventRegistration::create([
            'reg_id' => $regId,
            'name' => $request->student_name,
            'parent' => $request->parent_name,
            'email' => $request->email,
            'phone' => $request->phone,
            'eventid' => $request->eventid,
            'amount' => $amount,
            'datecreated' => now(),
            'status' => 'pending',
            'paymentmode' => 'PENDING',
        ]);

        // If amount is 0, mark as free registration
        if ($amount == 0) {
            return $this->processFreeRegistration($registration);
        }

        // Redirect to PayU payment gateway
        return $this->redirectToPayU($registration);
    }

    /**
     * Process free registration (no payment required)
     */
    protected function processFreeRegistration($registration)
    {
        $registration->markAsPaid(null, 'FREE');

        session()->put('registration_id', $registration->id);
        session()->put('reg_id', $registration->reg_id);

        return redirect()->route('registration.success')
                       ->with('message', 'Registration completed successfully!');
    }

    /**
     * Redirect to PayU payment gateway
     */
    protected function redirectToPayU($registration)
    {
        $paymentData = $this->payuService->generatePaymentData($registration);

        // Store transaction ID for verification later
        $registration->update(['txnid' => $paymentData['txnid']]);

        // Store payment data in session for display
        session()->put('payment_data', $paymentData);

        return redirect()->route('payment.redirect', ['regId' => $registration->reg_id]);
    }

    /**
     * Show payment redirect page
     */
    public function paymentRedirect($regId)
    {
        $registration = EventRegistration::where('reg_id', $regId)->firstOrFail();
        $paymentData = session('payment_data');

        if (!$paymentData) {
            return redirect()->route('registration.create')
                           ->withErrors(['error' => 'Payment data not found.']);
        }

        return view('payment.redirect', [
            'registration' => $registration,
            'paymentData' => $paymentData,
            'gatewayUrl' => $this->payuService->getGatewayUrl(),
        ]);
    }

    /**
     * Handle PayU success callback
     */
    public function paymentSuccess()
    {
        $result = $this->payuService->processCallback(request()->all());

        if ($result['success']) {
            session()->put('registration_id', $result['registration']->id);
            session()->put('reg_id', $result['registration']->reg_id);
        }

        return view('payment.result', [
            'success' => $result['success'],
            'message' => $result['message'],
            'registration' => $result['registration'] ?? null,
        ]);
    }

    /**
     * Handle PayU failure callback
     */
    public function paymentFailure()
    {
        $result = $this->payuService->processCallback(request()->all());

        return view('payment.result', [
            'success' => $result['success'],
            'message' => $result['message'],
            'registration' => $result['registration'] ?? null,
        ]);
    }

    /**
     * Show registration success page
     */
    public function success()
    {
        $registrationId = session('registration_id');
        
        if (!$registrationId) {
            return redirect()->route('registration.create')
                           ->withErrors(['error' => 'No active registration found.']);
        }

        $registration = EventRegistration::findOrFail($registrationId);

        return view('registration.success', compact('registration'));
    }

    /**
     * Show registration result (success/failure from PayU)
     */
    public function result()
    {
        $registration = EventRegistration::where('reg_id', request('regId'))
                                        ->firstOrFail();

        return view('registration.result', compact('registration'));
    }

    /**
     * Generate unique registration ID
     */
    protected function generateUniqueRegId()
    {
        do {
            // Format: REG-YYYYMMDD-XXXXX (e.g., REG-20240115-A7K9M)
            $regId = 'REG-' . now()->format('Ymd') . '-' . Str::random(5);
        } while (EventRegistration::where('reg_id', $regId)->exists());

        return $regId;
    }
}
