<?php

namespace App\Http\Controllers;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Auth;
use Illuminate\Http\Request;

class CheckoutController extends Controller
{
   public function showCheckout(Request $request) {
    if (!Auth::check()) {
        session(['url.intended' => url()->current()]);
        return redirect()->route('login')->with('error', 'You must be logged in to access the checkout page.');
    }

    \Log::info('Checkout data received:', $request->all());

    $courseId = $request->query('courseId');

    // Fetch course details from the database using the course ID
    $course = DB::table('COURSES')->where('CourseID', $courseId)->first();

    // If no course is found, return an error message
    if (!$course) {
        return redirect()->back()->with('error', 'Invalid course ID provided.');
    }

    // You now have $course->CourseName and $course->CoursePrice available, fetched securely from the database
    return view('Checkout', ['course' => $course]);
}




   public function handleCheckout(Request $request) {
    if ($request->has('couponCode') && $request->input('paymentMethod') === 'coupon') {
        if (!Auth::check()) {
            return redirect()->back()->with('error', 'You must be logged in to redeem a coupon.');
        }

     $courseId = $request->query('courseId');
   $course = DB::table('COURSES')->where('CourseID', $courseId)->first(['CourseName']);

    
    
        $userId = Auth::id();
        $couponCode = $request->input('couponCode');
        $courseName = $course->CourseName;
    


        if ($courseId === null) {
            return redirect()->back()->with('error', 'Invalid course name provided.');
        }


        try {
      
            $redeemResult = DB::select("CALL RedeemCoupon(?, ?, ?)", [$userId, $couponCode, $courseId]);

            $redeemMessage = $redeemResult[0]->{'Success: The Course has been Successfully Redeemed with the Coupon.'} ?? 
                             $redeemResult[0]->{'Error: The User is Already Enrolled in this Course.'} ?? 
                             $redeemResult[0]->{'Error: Invalid Coupon Code or Coupon Code Already Used.'} ?? 
                             'An unexpected error occurred during coupon redemption.';

            if (strpos($redeemMessage, 'Success') !== false) {
          
                return redirect()->back()->with('success', $redeemMessage);
            } else {
     
                return redirect()->back()->with('error', $redeemMessage);
            }
        } catch (\Exception $e) {
    
            return redirect()->back()->with('error', 'Error during transaction: ' . $e->getMessage());
        }
    } else {
      
    }
}
}