<?php

namespace App\Http\Controllers;

use App\Models\Coupon;
use App\Models\Exam;
use App\Models\Payment;
use App\Models\StudentExam;
use App\Models\testcategory;
use App\Models\topic;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Stripe\Stripe;
use Stripe\Charge;
use Stripe\Checkout\Session;

class ExamController extends Controller
{
    public function index()
    {
        $exams = Exam::where('is_active', true)->get();
        return view('exams', compact('exams'));
    }

    public function topicindex()
    {
        $topics = topic::all();
        // dd($topic);
        return view('topic', compact('topics'));
    }

    public function showtopicexam($id)
    {
        $exams = Exam::with('testCategory')->where('topic_id', $id)->where('is_active', true)->get();

        $topics = topic::all();
        $testCategories = testcategory::all();
        // dd($exams);


        return view('exams', compact('exams','topics','testCategories'));
    }

    public function showPurchase($id)
    {
        // dd('hi');
        $exam = Exam::findOrFail($id);
        return view('exam.purchase', compact('exam'));
    }

    public function purchase(Request $request, $id)
    {
        $exam = Exam::findOrFail($id);

        $request->validate([
            'stripeToken' => 'required',
        ]);

        \Stripe\Stripe::setApiKey(config('services.stripe.secret'));

        try {
            $charge = \Stripe\Charge::create([
                'amount' => $exam->amount * 100, // convert dollars to cents
                'currency' => 'usd',
                'source' => $request->stripeToken,
                'description' => 'Payment for ' . $exam->name,
            ]);

            Payment::create([
                'user_id' => Auth::id(),
                'exam_id' => $exam->id,
                'amount' => $exam->amount,
                'status' => 'completed',
                'stripe_id' => $charge->id,
            ]);

            StudentExam::create([
                'user_id' => Auth::id(),
                'exam_id' => $exam->id,
                'attempts' => 0,
            ]);

            // ✅ Return JSON instead of redirect
            return response()->json([
                'success' => true,
                'message' => 'Payment successful',
                'redirect' => route('student.exams'),
            ]);

        } catch (\Exception $e) {
            // ✅ Return error in JSON format
            return response()->json([
                'success' => false,
                'message' => 'Payment failed: ' . $e->getMessage()
            ], 500);
        }
    }



    public function checkout(Request $request, $id)
    {
        $exam = Exam::findOrFail($id);
        $amount = $exam->amount;

        $couponCode = trim($request->input('coupon_code'));

        if ($couponCode) {
            $coupon = Coupon::where('code', $couponCode)->first();

            // Coupon does not exist
            if (!$coupon) {
                return back()->withErrors(['coupon_code' => 'Invalid coupon.']);
            }

            // Coupon expired (usage limit exceeded)
            if ($coupon->usage_limit <= $coupon->used_count) {
                return back()->withErrors(['coupon_code' => 'Coupon expired.']);
            }

            // Apply discount
            if ($coupon->type == 'percent') {
                $discount = ($amount * $coupon->value) / 100;
            } else {
                $discount = $coupon->value;
            }

            // Prevent discount more than total
            if ($discount >= $amount) {
                return back()->withErrors(['coupon_code' => 'You cannot use this coupon for this course.']);
            }

            // Reduce amount
            $amount -= $discount;
        }

        if ($request->filled('coupon_code')) {
            session(['applied_coupon' => $request->input('coupon_code')]);
        }

        Stripe::setApiKey(config('services.stripe.secret'));

        $session = Session::create([
            'payment_method_types' => ['card'],
            'line_items' => [[
                'price_data' => [
                    'currency' => 'usd',
                    'product_data' => [
                        'name' => $exam->name,
                    ],
                    'unit_amount' => round($amount * 100), // Stripe needs amount in cents
                ],
                'quantity' => 1,
            ]],
            'mode' => 'payment',
            'success_url' => route('exam.success', $exam->id),
            'cancel_url' => route('exam.purchase', $exam->id),
        ]);

        return redirect($session->url);
    }



    public function success($id)
    {
        $exam = Exam::findOrFail($id);

        $couponCode = session('applied_coupon'); // Retrieve coupon code from session if any
        //  dd($couponCode);
        $finalAmount = $exam->amount;
        $coupon = null;

        if ($couponCode) {

            // dd($couponCode);
            $coupon = Coupon::where('code', $couponCode)->first();

            if ($coupon) {
                // Apply discount
                if ($coupon->type === 'percent') {
                    $discount = ($finalAmount * $coupon->value) / 100;
                } else {
                    $discount = $coupon->value;
                }

                // Ensure discount doesn't exceed amount
                if ($discount > $finalAmount) {
                    $discount = $finalAmount;
                }

                $finalAmount = $finalAmount - $discount;

                // Update coupon usage
                $coupon->used_count += 1;
                $coupon->save();
            }
        }

        Payment::create([
            'user_id' => Auth::id(),
            'exam_id' => $id,
            'amount' => $finalAmount,
            'status' => 'completed',
            'stripe_id' => 'stripe-checkout', // Later you can store real Stripe ID
            'coupon_code' => $couponCode, // Optional: If you have this column in payments table
        ]);

        StudentExam::create([
            'user_id' => Auth::id(),
            'exam_id' => $id,
            'attempts' => 0,
        ]);

        // Clear the coupon from session after success
        session()->forget('applied_coupon');

        return redirect()->route('student.exams')->with('success', 'Exam purchased successfully!');
    }

}
