@extends('frontend.layouts.app_minimal')

@section('title', app_name() . ' | ' . __('labels.frontend.auth.register_box_title'))

@section('content')
    {{ html()->form('POST', route('frontend.user.newplan'))->id('payment-form')->open() }}
    {{ html()->hidden('stripe_plan_id')}}
    <div class="row justify-content-center align-items-center">
        <div class="col col-sm-8 align-self-center">
            <div class="card card-body">
                <div class="g_et_al_header2 text-center mb-2">
                    Sign up to Graphics Et Al
                </div>
                <div class="row">
                    <div class="col">
                        <div class="form-group">

                            {{ html()->label('Subscription level')->for('subscription_level') }}
                            <div class="custom-control custom-radio">
                                {{html()->radio('subscription_level',$plan&&$plan->selector=='student')
->class('custom-control-input')->id('radio2')
->value('student')
->attribute('onchange', "$('#payment_freq_group').show();$('#radio5').attr('required', 'required'); $('#update_plan_but').prop('disabled',false)")}}
                                <label class="custom-control-label" for="radio2">Student</label>
                            </div>
                            <div class="custom-control custom-radio">
                                {{html()->radio('subscription_level',$plan&&$plan->selector=='researcher')->class('custom-control-input')->id('radio3')->value('researcher')
->attribute('onchange', "$('#payment_freq_group').show();$('#radio5').attr('required', 'required'); $('#update_plan_but').prop('disabled',false)")}}
                                <label class="custom-control-label" for="radio3">Researcher</label>
                            </div>
                            <div class="custom-control custom-radio">
                                {{html()->radio('subscription_level',$plan&&$plan->selector=='lab')->class('custom-control-input')->id('radio4')->value('lab')
->attribute('onchange', "$('#payment_freq_group').show();$('#radio5').attr('required', 'required'); $('#update_plan_but').prop('disabled',true)")}}
                                <label class="custom-control-label" for="radio4">Lab</label>
                            </div>

                            {{--                                               onchange="$('#payment_freq_group').show();$('#payment_freq_group').attr('required', '')"/>--}}
                        </div><!--form-group-->
                    </div><!--col-->
                    <div class="col">
                        <div class="form-group" id="payment_freq_group">
                            {{ html()->label('Payment frequency')->for('payment_frequency') }}
                            <div class="custom-control custom-radio">
                                {{html()->radio('payment_frequency',$plan&&$plan->period=='yearly')->class('custom-control-input')->id('radio5')->required()->value('yearly')}}
                                <label class="custom-control-label" for="radio5"><span id="yearlycost"></span>
                                    Yearly
                                </label>
                            </div>
                            <div class="custom-control custom-radio">
                                {{html()->radio('payment_frequency',$plan&&$plan->period=='monthly')->class('custom-control-input')->id('radio6')->value('monthly')}}
                                <label class="custom-control-label" for="radio6"><span id="monthlycost"></span>
                                    Monthly</label>
                            </div>
                        </div><!--form-group-->
                    </div><!--row-->
                    <div class="col ">
                        <div class="row mb-2">{{ html()->label('Plan details') }}</div>
                        <div class="row g_et_al_paragraph2" id="selected_plan_details">
                            {{--                            @if (!$logged_in_user->subscriptions->count() > 0)--}}
                            {{--                                Free plan: no time limit, just free.--}}
                            {{--                                Perfect for small projects. You get 3 boards and access to the free graphics.--}}
                            {{--                            @endif--}}
                        </div>
                    </div>

                </div><!--row-->

                {{--                <div class="row" id="lab_name_group" style="{{$plan&&$plan->selector=='lab'?'':'display: none'}}">--}}
                {{--                    <div class="col">--}}
                {{--                        <div class="form-group">--}}
                {{--                            {{ html()->label('Lab name')->for('lab_name') }}--}}
                {{--                            {{ html()->text('lab_name')--}}
                {{--                                ->class('form-control')--}}
                {{--                                ->placeholder('My awesome lab')--}}
                {{--->value(($plan&&$plan->selector=='lab')?$logged_in_user->my_lab['name']:'')--}}
                {{--                                ->attribute('maxlength', 191)--}}
                {{--                               }}--}}
                {{--                        </div><!--form-group-->--}}
                {{--                    </div><!--col-->--}}
                {{--                </div><!--row-->--}}
                <div class="row" style="padding-bottom: 10px">
                    <div class="col">
                        Selected plan price: <span style="font-weight: bold">AUD <span
                                id="selected_plan_cost"></span> </span>
                    </div>
                </div>

            </div>

            <button class="btn btn-success btn-block" id="card-button">Let's go!<i class="fas fa-arrow-right"></i>
            </button>
            <div class="row">
                <div class="col pt-2">
                    <p>If you have any promotional codes, you can apply them in the next step
                    </p>
                    <p>By subscribing to Graphics et al, you agree to the <a href="#" data-toggle="modal"
                                                                             data-target="#disclaimer">Terms and
                            conditions</a>.
                    </p>
                </div>
            </div>
            <a href="{{route('frontend.user.account')}}"
               class="btn btn-outline-warning btn-block"><i class="fas fa-arrow-left">
                </i>Return</a>

        </div><!-- row -->

    </div>

    {{ html()->form()->close() }}

@endsection

@section('dialogs')
    <div id="disclaimer" class="modal fade" role="dialog">
        <div class="modal-dialog modal-lg">
            <div class="modal-content">
                <div class="modal-header">
                    <h4 class="modal-title">Terms and conditions</h4>
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                        <span aria-hidden="true">&times;</span>
                    </button>
                </div>

                <div class="modal-body">

                    @lang('strings.frontend.terms_and_conditions.text')

                </div>
            </div>
        </div>
    </div>
    <div class="modal fade load-spinner" data-backdrop="static" data-keyboard="false" tabindex="-1">
        <div class="modal-dialog modal-lg">
            <div class="modal-content">
                <i class="fas fa-circle-notch fa-spin fa-3x mx-auto"></i>
            </div>
        </div>
    </div>
@endsection

@push('after-scripts')

    <script src="https://js.stripe.com/v3/"></script>
    <script type="text/javascript">
        $.ajaxSetup({
            headers: {
                'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
            }
        });
    </script>

    <script>

        var selected_plan = '';
        var success_status = false;
        var promo_id = '';
        var promo_percent = 100;

        $(document).ready(function () {
            //$("#card-button").prop('disabled', true);
            // toggle lab name
            $('input[type=radio]').on('change', function () {
                console.log($('#radio4').is(':checked'))
                // if ($('#radio4').is(':checked')) {
                //     $('#lab_name_group').show();
                //     $('#lab_name').attr('required', 'required');
                //     if ($('#lab_name').val() != null && $('#lab_name').val() != '') {
                //          $("#card-button").prop('disabled', false);
                //     } else {
                //          $("#card-button").prop('disabled', true);
                //     }
                // } else {
                //     $('#lab_name_group').hide();
                //     $('#lab_name').removeAttr('required');
                //     $("#card-button").prop('disabled', false);
                // }
                // get plan details
                getPlanDetails();
                // Catch the submit function on the form, trigger the checkout process at Stripe
                $('#payment-form').on('submit', (e) => {
                    e.preventDefault();
                    triggerCheckout()
                });
            });

            // listen for lab name update

            // $("#lab_name").on('change keyup', function () {
            //     if ($('#radio4').is(':checked')) {
            //         if ($('#lab_name').val() != null && $('#lab_name').val() != '') {
            //             $("#update_plan_but").prop('disabled', false);
            //         } else {
            //             $("#update_plan_but").prop('disabled', true);
            //         }
            //     } else {
            //         $("#update_plan_but").prop('disabled', false);
            //         $("#card-button").prop('disabled', true);
            //
            //     }
            // });
            getPlanDetails();
        });

        // retrieve the plan details
        const getPlanDetails = () => {

            //@TODO append a loading indicator
            // wait(true);
            var vars = [];
            vars.push({name: 'subscription_level', value: $("input[name='subscription_level']:checked").val()});
            vars.push({name: 'payment_frequency', value: $("input[name='payment_frequency']:checked").val()});
            loading = true;
            $.ajax(
                {
                    url: '{{URL::to('getplandetails')}}',
                    data: vars,
                    type: "post",
                    datatype: "json"
                }).done(function (data) {
                //@TODO remove the loading indicator
                // wait(false);
                data.level_plans.forEach(function (item, index) {
                    $("#selected_plan_details").html(item.description)
                    if (item.period == 'monthly') {
                        $("#monthlycost").html('<strong>$' + ((item.cost / 100) * (promo_percent / 100)).toFixed(2) + '</strong>')
                    }
                    if (item.period == 'yearly') {
                        $("#yearlycost").html('<strong>$' + ((item.cost / 100) * (promo_percent / 100)).toFixed(2) + '</strong>')
                    }
                })
                // if there's a selected plan, there should be enough data to go on
                if (data.selected_plan) {
                    $("#selected_plan_cost").html('<strong>$' + ((data.selected_plan.cost / 100) * (promo_percent / 100)).toFixed(2) + '</strong>')
                    $("#selected_plan_details").html(data.selected_plan.description);
                    @if(!$plan)
                    // set the hidden plan ID value in the payment form
                    $('input[name="stripe_plan_id"]').val(data.selected_plan.id);
                    // if there's no payment detail, then show the payment portal
                    @endif
                }
                loading = false;
            }).fail(function (jqXHR, ajaxOptions, thrownError) {
                wait(false);

                Swal.fire({
                    icon: 'error',
                    title: 'Oops...',
                    text: 'Something went wrong!',
                })

                console.log('no data');
                loading = false;
                //@TODO indicate somewhere the load failed

            });
        }

        const triggerCheckout = () => {
            let formData = $("#payment-form").serialize();
            console.log(formData)
            wait(true);
            axios.post('{{route('frontend.user.newplan')}}',
                formData
            ).then(function (response) {
                console.log(response)
                Stripe('{{Config::get('cashier.key')}}').redirectToCheckout({
                    sessionId: response.data.id
                }).then(function (result) {
                    if (result.error) {
                        Swal.fire({
                            icon: 'error',
                            title: 'Oops...',
                            text: 'Something went wrong!',
                            footer: result.error.message
                        })
                    }
                })
            }).catch(function (error) {
                //   console.log(error);
                Swal.fire({
                    icon: 'error',
                    title: 'Oops...',
                    text: 'Something went wrong!',
                    footer: error.message
                })

            })
                .finally(function () {
                    // always executed
                    wait(false)
                });
        }

        const checkoutResultHandler = (session) => {

        }


        // if there's not already a plan
        {{--        @if(!$plan)--}}
        {{--        // Submit the payment form, along with the parameters with the token ID.--}}
        {{--        const stripePaymentHandler = (setupIntent) => {--}}
        {{--            // get the form and variables--}}
        {{--            let form = document.getElementById('payment-form');--}}
        {{--            let hiddenInput = document.createElement('input');--}}
        {{--            hiddenInput.setAttribute('type', 'hidden');--}}
        {{--            hiddenInput.setAttribute('name', 'stripePaymentMethod');--}}
        {{--            hiddenInput.setAttribute('value', setupIntent.payment_method);--}}
        {{--            form.appendChild(hiddenInput);--}}
        {{--            console.log('stripePaymentHandler says:'+promo_id);--}}
        {{--            if (promo_id.length > 0) {--}}
        {{--                console.log('stripePaymentHandler says promo_id.length>0');--}}
        {{--                let promo_input = document.createElement('input');--}}
        {{--                promo_input.setAttribute('type', 'hidden');--}}
        {{--                promo_input.setAttribute('name', 'promo_id');--}}
        {{--                promo_input.setAttribute('value', promo_id);--}}
        {{--                form.appendChild(promo_input);--}}
        {{--            }--}}
        {{--           // wait(true);--}}
        {{--            form.submit();--}}
        {{--        }--}}

        {{--        @else--}}

        // just update the plan
        //@TODO maybe put some confirmation in here?
        function updatePlan() {
            console.log('updatePlan says promo_id is:' + promo_id);
            var form = document.getElementById('payment-form');
            if (promo_id.length > 0) {
                console.log('updatePlan says promo_id.length>0');
                let promo_input = document.createElement('input');
                promo_input.setAttribute('type', 'hidden');
                promo_input.setAttribute('name', 'promo_id');
                promo_input.setAttribute('value', promo_id);
                form.appendChild(promo_input);
            }
            //wait(true);
            form.submit();
        }

        {{--// @endif--}}

        {{--        function handleConfirmationClose() {--}}
        {{--            if (success_status) {--}}
        {{--                window.location.replace('{{route('frontend.user.account')}}');--}}
        {{--            } else {--}}
        {{--                window.location.reload();--}}
        {{--            }--}}
        {{--        }--}}

        function wait(on) {
            console.log(on)
            if (on) {
                $('.load-spinner').modal('show');
            } else {
                setTimeout(function () {
                    $('.load-spinner').modal('hide');
                }, 500)

            }
        }

        {{--const checkPromoCode = () => {--}}
        {{--    axios.get('{{URL::to('checkpromocode')}}', {params: {code: $("#promo_code").val()}})--}}
        {{--        .then((response) => {--}}
        {{--            console.log(response)--}}
        {{--            if (response.data.error) {--}}
        {{--                console.log('error!')--}}
        {{--                $("#promo_success").hide().html('')--}}
        {{--                $("#promo_error").show().html(response.data.message)--}}
        {{--                promo_id = '';--}}
        {{--                promo_percent = 100;--}}
        {{--            } else {--}}
        {{--                $("#promo_success").show().html(response.data.name + ': ' + response.data.percent_off + '% off!')--}}
        {{--                $("#promo_error").hide().html('');--}}
        {{--                promo_id = response.data.id;--}}
        {{--                promo_percent = response.data.percent_off;--}}
        {{--            }--}}
        {{--        }).finally(getPlanDetails);--}}
        {{--}--}}

    </script>

@endpush

@push('after-styles')
    <style>


        /*#payment-form {*/
        /*    font-family: Inter UI, Open Sans, Segoe UI, sans-serif;*/
        /*    font-size: 16px;*/
        /*    font-weight: 500;*/
        /*}*/

        /*!*form {*!*/

        /*!*    padding: 15px;*!*/
        /*!*}*!*/


        fieldset {
            border: 1px solid black;
            padding: 5px;

            background: rgba(18, 91, 152, 0.05);
            border-radius: 3px;
        }

        fieldset legend {
            float: left;
            width: 100%;
            text-align: center;
            font-size: 13px;
            color: #8898aa;
            padding: 3px 10px 7px;
        }

        /*.card-only {*/
        /*    display: block;*/
        /*}*/

        /*.payment-request-available {*/
        /*    display: none;*/
        /*}*/

        /*fieldset legend + * {*/
        /*    clear: both;*/
        /*}*/

        /*input, button {*/
        /*    -webkit-appearance: none;*/
        /*    -moz-appearance: none;*/
        /*    appearance: none;*/
        /*    outline: none;*/
        /*    border-style: none;*/
        /*    color: #fff;*/
        /*}*/

        /*input:-webkit-autofill {*/
        /*    transition: background-color 100000000s;*/
        /*    -webkit-animation: 1ms void-animation-out;*/
        /*}*/


        /*input {*/
        /*    -webkit-animation: 1ms void-animation-out;*/
        /*}*/

        /*input::-webkit-input-placeholder {*/
        /*    color: #9bacc8;*/
        /*}*/

        /*input::-moz-placeholder {*/
        /*    color: #9bacc8;*/
        /*}*/

        /*input:-ms-input-placeholder {*/
        /*    color: #9bacc8;*/
        /*}*/

        /*button {*/
        /*    display: block;*/
        /*    width: 100%;*/
        /*    height: 37px;*/
        /*    background-color: #d782d9;*/
        /*    border-radius: 2px;*/
        /*    color: #fff;*/
        /*    cursor: pointer;*/
        /*}*/

        /*button:active {*/
        /*    background-color: #b76ac4;*/
        /*}*/

        /*.error svg .base {*/
        /*    fill: #e25950;*/
        /*}*/

        /*.error svg .glyph {*/
        /*    fill: #f6f9fc;*/
        /*}*/

        /*.error .message {*/
        /*    color: #e25950;*/
        /*}*/

        /*.success .icon .border {*/
        /*    stroke: #ffc7ee;*/
        /*}*/

        /*.success .icon .checkmark {*/
        /*    stroke: #d782d9;*/
        /*}*/

        /*.success .title {*/
        /*    color: #32325d;*/
        /*}*/

        /*.success .message {*/
        /*    color: #8898aa;*/
        /*}*/

        /*.success .reset path {*/
        /*    fill: #d782d9;*/
        /*}*/


    </style>
@endpush
