HEX
Server: Microsoft-IIS/8.5
System: Windows NT YDAWBH120 6.3 build 9600 (Windows Server 2012 R2 Standard Edition) AMD64
User: tentjecom_web (0)
PHP: 7.4.14
Disabled: NONE
Upload Files
File: D:/HostingSpaces/netwerkbrabant/netwerkbrabant.nl/app/KommaApp/Courses/CourseController.php
<?php

namespace App\KommaApp\Courses;

use App\Http\Controllers\Controller;
use App\Http\Requests\OrderChoosePaymentMethodRequest;
use App\Http\Requests\CourseSignUpRequest;
use App\KommaApp\Courses\Models\Course;
use App\KommaApp\CourseTypes\Models\CourseType;
use App\KommaApp\Orders\Models\Order;
use App\KommaApp\Orders\OrderService;
use App\KommaApp\Payments\PaymentService;
use App\Mail\Courses\SignedUpFreeMail;
use App\Mail\Courses\SignedUpFreePlusOneMail;
use App\Mail\Courses\SignedUpMail;
use App\Mail\Courses\SignedUpPlusOneMail;
use App\Mail\CourseSignUpMail;

class CourseController extends Controller
{
    private $modelPrefix = 'pages.courses.';
    private $courseService;

    public function __construct(CourseService $courseService)
    {
        parent::__construct();
        $this->courseService = $courseService;
    }

    /**
     * @param  CourseType|null  $courseType
     * @return \Illuminate\Contracts\View\View
     * @throws \Psr\Container\ContainerExceptionInterface
     * @throws \Psr\Container\NotFoundExceptionInterface
     */
    public function index(CourseType $courseType = null)
    {
        $page = $this->pageService->getPageById(request()->attributes->get('page_id'));
        $otherLanguageRoutes = $this->languageService->getOtherLanguagesRoutes($page);

        $isDigital = request()->get('digital');
        if($isDigital !== null) {
            if(!in_array($isDigital, ['true', 'false'])) return redirect($this->links->courses->route);
            $isDigital = $isDigital == 'true';

            $highlightedCourses = collect();

            $courses = isset($courseType) ? $this->courseService->getPaginatedCourses(null, ['course_type_id' => $courseType->id, 'digital' => $isDigital]) : $this->courseService->getPaginatedCourses(null, ['digital' => $isDigital]);

        }
        else {
            // Load the highlighted courses
            $highlightedCourses = isset($courseType) ? $this->courseService->getHighlightedCoursesByType($courseType) : $this->courseService->getHighlightedCourses();

            // Get the id's of the highlighted courses, because we need to exclude them from the paginated courses
            $courseIds = $highlightedCourses->pluck('id')->all();

            $courses = isset($courseType) ? $this->courseService->getPaginatedCourses($courseIds, ['course_type_id' => $courseType->id]) : $this->courseService->getPaginatedCourses($courseIds);
        }


        $pageCodeName = $page->code_name;
        $courses->withPath('/' . $this->links->$pageCodeName->route);

        $page->translation = $this->decodeDynamicContent( $page->translation );

        // Return view
        return \View::make($this->baseViewPath.$this->modelPrefix.'index',[
            'page' => $page,
            'otherLanguages' => $otherLanguageRoutes,
            'highlightedCourses' => $highlightedCourses,
            'courses' => $courses,
            'isDigital' => $isDigital,
            'courseType' => $courseType
        ]);

    }

    public function courseType(CourseType $courseType) {

        $courseType->load('translation');
        $courseType->translation = $this->decodeDynamicContent( $courseType->translation, 'main');

        return $this->index($courseType);
    }

    /**
     * @param Course $course
     * @return \Illuminate\Contracts\View\View
     */
    public function show(Course $course)
    {

        // Load translation by eager loading
        $course->load( 'translation', 'images', 'signUps');
        $course->setRelation('translation', $this->decodeDynamicContent($course->translation, 'content'));

        //$page = $this->pageService->getPageByCodeName('courses');
        $page = $this->pageService->getPageById(request()->attributes->get('page_id'));

        $otherCourses = $this->courseService->getNextCourses($course);

        // Clear the signed up persons from session
        session(['_old_input' => null]);

        // Return view
        return \View::make($this->baseViewPath.$this->modelPrefix. 'show',[
            'page' => $page,
            'course' => $course,
            'otherCourses' => $otherCourses,
        ]);
    }

    /**
     * Sync the given course with the billing system
     *
     * @param  Course  $course
     */
    public function sync(Course $course)
    {
        $this->courseService->syncCourse($course);
    }


    //================================================================================================================//
    //====                                                                                                       =====//
    //====                                 Functions for the sign up pages                                       =====//
    //====                                                                                                       =====//
    //================================================================================================================//


    /**
     * Sign up page of an course
     *
     * @param Course $course
     * @return mixed
     */
    public function signUp(Course $course)
    {
        // Load translation by eager loading
        $course->load( 'translation', 'images');

        $page = $this->pageService->getPageByCodeName('courses');

        // Clear the signed up persons from session
        session(['signedUpPersons' => null]);

        $this->populateFormWithUser();

        // Return view
        return \View::make($this->baseViewPath.$this->modelPrefix. 'signUp.show',[
            'page' => $page,
            'course' => $course,
        ]);
    }

    public function previewMail(){

        //$orderService = \App::make(OrderService::class);
        //$order = Order::where('id', '=', 2500)->first();

        /**
         * After signing up for a paid course...
         */
        // Sent to the person signing up for an course
        //return new SignedUpMail($order);

        // Sent to the plus one
        //return new SignedUpPlusOneMail($order, 'Kabouter Plop');

        /**
         * After signing up for a free course
         */
//        return new SignedUpFreeMail($order); //Course $course, CourseSignUp $courseSignUp
//        return new SignedUpFreePlusOneMail($order); //Course $course, CourseSignUp $courseSignUp, string $signedUpBy

        /**
         *  After successful payment (Mollie webhook)
         */
        //return new PaymentReceivedMail($order); //Order $order

        /**
         *  After any type of signup, sent to Erik
         */
        //return new CourseSignUpMail(); //CourseSignUp $courseSignUp, $signedUpBy, Course $course, $invoiceIdPrefixed


    }

    /**
     * Process the course sign up
     *
     * @param CourseSignUpRequest $request
     * @return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector
     */
    public function process(CourseSignUpRequest $request)
    {
        /** @var OrderService $orderService */
        $orderService = \App::make(OrderService::class);

        /** @var PaymentService $paymentService */
        $paymentService = \App::make(PaymentService::class);

        // Convert the request into signees and the producted course
        [$signees, $courseProduct, $course] = $this->courseService->convertRequest($request->except('_token', 'accept_legal'));

        $redirectRoute = null;
        $hasPaymentError = false;

        //Create array for signee names to put into the session
        $sessionSignees = [];

        // Loop through the signees
        foreach ($signees as $signeeType => $signee){

            // Create order for the signee
            $order = $course->with_invoicing ? $orderService->createOrderForSignee($signee, $courseProduct) : null;

            // Create Sign Up Models for the signee
            $signUped = $this->courseService->addSigneeToCourseSignUps($signee, $signees['main'], $course, isset($order) ? $order->invoice_id : null);

            $sessionSignees[] =  $signee->first_name;

            // If it is the main signee
            if($signeeType == 'main') {

                if(!$order) {
                    \Mail::send(new SignedUpFreeMail($course, $signUped));
                    continue;
                }

                // The signup confirmation is sent to the $order->mail
                \Mail::send(new SignedUpMail($order));

                // If the main signee chose iDeal as payment method
                if($signee->paymentMethod == PaymentService::PAYMENT_METHOD_IDEAL) {
                    $paymentDescription =  'Opleiding inschrijving: '. $course->translation->name . ' - '. $signee->first_name . ' '. $signee->last_name;
                    $redirectRoute = $paymentService->createPayment($order, $paymentDescription, url(route('validate.courseOrder', ['id' => $order->id])), $signee->paymentMethod);
                    if(empty($redirectRoute)) $hasPaymentError = true;
                }
                // The signee chose manual bank transfer --> WeFact
                else {
                    // Check if the signee chose to use a different email for the invoice
                    $orderService->sendInvoiceForOrderByWeFact($order, $course->wefact_code);
                }

            }
            // The plus one will receive a WeFact invoice
            else{

                if(!$order) {
                    \Mail::send(new SignedUpFreePlusOneMail($course, $signUped, $signees['main']->first_name.' '.$signees['main']->last_name));
                    continue;
                }

                $orderService->sendInvoiceForOrderByWeFact($order, $course->wefact_code);
                \Mail::send(new SignedUpPlusOneMail($order, $signees['main']->first_name.' '.$signees['main']->last_name));
            }
        }

        session(['signedUpPersons' => $sessionSignees]);

        if(!$course->with_invoicing) {
            return redirect($this->links->courses->route . '/' . $course->translation->slug . '/'. __('site/routes.events.signUp') . '/' . __('site/routes.courses.success'));
        }

        // If no redirect route is defined (when mollie is down) or when manual transaction
        if(empty($redirectRoute))
        {

            // If mollie is down
            if($hasPaymentError) {
                // redirect to page that indicates that there will be contacted about the payment
                return redirect($this->links->courses->route . '/' . $course->translation->slug. '/'. __('site/routes.courses.signUp') . '/' . __('site/routes.courses.paymentError'));
            }

            // Else redirect to page that indicates that the invoice will be send by WeFact
            return redirect($this->links->courses->route . '/' . $course->translation->slug. '/'. __('site/routes.courses.signUp') . '/' . __('site/routes.courses.paymentByPartner'));
        }

        // Redirect to payment route
        return redirect($redirectRoute, 303);
    }

    /**
     * Payment error page after sign up for an course
     *
     * @param Course $course
     * @return mixed
     */
    public function paymentError(Course $course)
    {
        // Load translation by eager loading
        $course->load( 'translation', 'images');
        $page = $this->pageService->getPageByCodeName('courses');

        return \View::make($this->baseViewPath.$this->modelPrefix. 'signUp.message',[
            'page' => $page,
            'messageCodeName' => 'paymentError',
            'course' => $course,
        ]);
    }

    /**
     * Validate the order and redirect it to the right order status
     * This is the controller that Mollie will call after finishing the sign up checkout
     *
     * @param $orderId
     * @return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector
     */
    public function validateCourseOrder($orderId)
    {

        // Get the (course) order and the course
        [$order, $course] = $this->courseService->getCourseOrderStatus($orderId);

        $mainCourseRoute = $this->links->courses->route . '/' . $course->translation->slug. '/' . __('site/routes.courses.signUp');

        switch ($order->status)
        {
            case Order::OPEN:
                return redirect($mainCourseRoute . '/' . __('site/routes.courses.choosePaymentMethod') . '/'.$order->id);

            case Order::AWAITING_PAYMENT:
                return redirect($mainCourseRoute . '/' . __('site/routes.courses.awaitingPayment'));

            case Order::PAID:
                return redirect($mainCourseRoute . '/' . __('site/routes.courses.success'));

            case Order::CANCELED:
                return redirect($mainCourseRoute . '/' . __('site/routes.courses.canceled'));
        }
    }

    /**
     * Awaiting page after sign up for an course
     *
     * @param Course $course
     * @return mixed
     */
    public function awaitingPayment(Course $course)
    {
        // Load translation by eager loading
        $course->load( 'translation', 'images');
        $page = $this->pageService->getPageByCodeName('courses');

        return \View::make($this->baseViewPath.$this->modelPrefix. 'signUp.message',[
            'page' => $page,
            'messageCodeName' => 'awaitingPayment',
            'course' => $course,
        ]);
    }

    /**
     * Choose a payment method for completing the sign up
     * Plus one will receive a link to this page
     * rr if you haven't completed the payment process you also receive a link to this page
     *
     * @param Course $course
     * @param $orderId
     * @return mixed
     */
    public function choosePaymentMethod(Course $course, $orderId)
    {
        // Load translation by eager loading
        $course->load( 'translation', 'images');
        $page = $this->pageService->getPageByCodeName('courses');

        // Clear the signed up persons from session
        session(['signedUpPersons' => null]);

        // Return view
        return \View::make($this->baseViewPath.$this->modelPrefix. 'signUp.choosePaymentMethod',[
            'page' => $page,
            'course' => $course,
            'orderId' => $orderId
        ]);
    }

    /**
     * Process the choose payment method form
     *
     * @param OrderChoosePaymentMethodRequest $request
     * @return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector
     */
    public function processPaymentMethod(OrderChoosePaymentMethodRequest $request)
    {
        $orderService = \App::make(OrderService::class);
        $paymentService = \App::make(PaymentService::class);

        $order = $orderService->getOrder($request->get('order'));
        $courseProduct = $order->products()->first();

        $redirectRoute = null;
        $paymentDescription =  'Opleiding inschrijving: '. $courseProduct->name . ' - '. $order->invoice_first_name . ' '. $order->invoice_last_name;
        $redirectRoute = $paymentService->createPayment($order, $paymentDescription, url(route('validate.courseOrder', ['id' => $order->id])), $request->get('paymentMethod'));

        // If no redirect route is defined (when mollie is down)
        if( empty($redirectRoute) )
        {
            $course = $this->courseService->getCourse($courseProduct->course_id);

            // redirect to page that indicates that there will be contacted about the payment
            return redirect($this->links->courses->route . '/' . $course->translation->slug. '/'. __('site/routes.courses.signUp') . '/' . __('site/routes.courses.paymentError'));
        }

        session(['signedUpPersons' => [$order->invoice_first_name]]);

        // Redirect to payment route
        return redirect($redirectRoute, 303);

    }

    /**
     * Success page after sign up for an course
     *
     * @param Course $course
     * @return mixed
     * @throws \Spatie\CalendarLinks\Exceptions\InvalidLink
     */
    public function success(Course $course)
    {

        // Load translation by eager loading
        $course->load( 'translation', 'images');

        // There should be signed up persons in the session, else redirect to the course show page
        $signedUpPersons = session('signedUpPersons', null);

        $page = $this->pageService->getPageByCodeName('courses');

        $nextCourse = $this->courseService->getNextCourses($course);

        return \View::make($this->baseViewPath.$this->modelPrefix. 'signUp.success',[
            'page' => $page,
            'course' => $course,
            'calenderEvent' => $this->courseService->createCalendarEvent($course),
            'nextCourse' => $nextCourse->first(),
            'signedUpPersons' => $signedUpPersons,
        ]);
    }

    /**
     * Payment by partner page after sign up for an course
     *
     * @param Course $course
     * @return mixed
     * @throws \Spatie\CalendarLinks\Exceptions\InvalidLink
     */
    public function paymentByPartner(Course $course)
    {
        // Load translation by eager loading
        $course->load( 'translation', 'images');

        // There should be signed up persons in the session, else redirect to the course show page
        $signedUpPersons = session('signedUpPersons', null);

        $page = $this->pageService->getPageByCodeName('courses');

        $nextCourse = $this->courseService->getNextCourses($course);

        return \View::make($this->baseViewPath.$this->modelPrefix. 'signUp.paymentByPartner',[
            'page' => $page,
            'course' => $course,
            'calenderEvent' => $this->courseService->createCalendarEvent($course),
            'nextCourse' => $nextCourse->first(),
            'signedUpPersons' => $signedUpPersons,
        ]);
    }

    /**
     * Canceled sign up for an course
     *
     * @param Course $course
     * @return mixed
     */
    public function canceled(Course $course)
    {
        // Load translation by eager loading
        $course->load( 'translation', 'images');
        $page = $this->pageService->getPageByCodeName('courses');

        return \View::make($this->baseViewPath.$this->modelPrefix. 'signUp.message',[
            'page' => $page,
            'messageCodeName' => 'canceled',
            'course' => $course,
        ]);
    }

}