@extends('layouts.app', ['title' => __tr('Subscription')])
@section('content')
    @include('users.partials.header', [
    'title' => __tr('Subscription'),
    'description' => '',
    'class' => 'col-lg-7'
    ])
   @if(isset($message))
    <div class="container">
        <div class="alert alert-danger">
            {{ $message }}
        </div>
    </div>
   @else
   @php
   $subscriptionPlans = getAppSettings('subscription_plans');
   $hasPlansForPurchase = false;
   foreach ($planStructure as $planKey => $plan) {
       $plan = $planDetails[$planKey];
       if (!$plan['enabled']) {
           continue;
       }
       $hasPlansForPurchase = true;
       break;
   }
   @endphp
   <div class="container-fluid">
       <div class="row">
           <div class="col-xl-12">
            @if(getAppSettings('enable_stripe') and !$isValidStripeKeys)
               <div class="alert alert-danger">
                    {{  __tr('Stripe is not correctly configured, Invalid Keys. Please contact administrator') }}
               </div>
               @endif
               <div class="card mb-4">
                   <div class="card-body">
                       @if (request('success') == true and request('message'))
                           <div class="alert alert-success">
                               {{ request('message') }}
                           </div>
                       @elseif(request('message'))
                           <div class="alert alert-warning">
                               {{ request('message') }}
                           </div>
                       @endif
                       @if ($currentPlan and $subscriber->subscribed($currentPlan['id']))
                           @if ($subscriber->subscription($currentPlan['id'])->onTrial())
                               <div class="alert alert-warning">
                                   {{  __tr('You are on trial until __trialEndsAt__', [
                                       '__trialEndsAt__' => formatDateTime($subscriber->trialEndsAt($currentPlan['id']))
                                   ]) }}
                               </div>
                           @endif
                           @if ($subscriber->subscription($currentPlan['id'])->onGracePeriod())
                               <div class="alert alert-warning">
                                   {{  __tr('Subscription has been cancelled and you are on the grace period till __endsAt__', [
                                       '__endsAt__' => formatDateTime($subscriber->subscription($currentPlan['id'])->ends_at)
                                   ]) }}
                               </div>
                           @endif
                           <fieldset class="mb-4">
                               <legend>{{ __tr('Current Plan') }}</legend>
                               <h2 class="text-primary">{{ $planDetails[$currentPlan['id']]['title'] }}</h2>
                               @foreach ($planStructure[$currentPlan['id']]['features'] as $featureKey => $featureValue)
                                   @php
                                       $featureValue = $planDetails[$currentPlan['id']]['features'][$featureKey];
                                   @endphp
                                   <div class="my-2">
                                       <i class="fa fa-check text-success mr-2"></i>
                                       @if (isset($featureValue['limit']) and $featureValue['limit'] < 0)
                                           {{ __tr('Unlimited') }}
                                       @elseif(isset($featureValue['limit']))
                                           {{ $featureValue['limit'] }}
                                       @endif
                                       {{ Str::title($featureValue['description']) }}
                                       @if(isset($featureValue['limit_duration_title']))
                                            {{ Str::title($featureValue['limit_duration_title']) }}
                                        @endif
                                   </div>
                               @endforeach
                               @foreach ($planDetails[$currentPlan['id']]['charges'] as $itemKey => $itemValue)
                                   @if ($planSelectorId === $currentPlan['id'] . '___' . $itemKey)
                                       <label class="my-3 text-primary">
                                           {{ formatAmount($itemValue['charge'], true) }} /
                                           {{ $itemKey }}
                                       </label>
                                   @endif
                               @endforeach
                           </fieldset>
                           @if (!$subscriber->subscription($currentPlan['id'])->canceled())
                               <a data-show-processing="true" class="lw-ajax-link-action btn btn-danger" href="{{ route('subscription.write.cancel') }}">
                                   {{ __tr('Cancel Subscription') }}
                               </a>
                           @endif
                       @else
                           @if ($freePlanDetails['enabled'])
                               <fieldset class="mb-4">
                                   <legend>{{ __tr('Current Plan') }}</legend>
                                   <h2 class="text-primary">{{ $freePlanDetails['title'] }}</h2>
                                   @foreach ($freePlanStructure['features'] as $featureKey => $featureValue)
                                       @php
                                           $featureValue = $freePlanDetails['features'][$featureKey];
                                       @endphp
                                       <div class="my-2">
                                           <i class="fa fa-check text-success mr-2"></i>
                                           @if (isset($featureValue['limit']) and $featureValue['limit'] < 0)
                                               {{ __tr('Unlimited') }}
                                           @elseif(isset($featureValue['limit']))
                                               {{ $featureValue['limit'] }}
                                           @endif
                                           {{ Str::title($featureValue['description']) }}
                                           @if(isset($featureValue['limit_duration_title']))
                                                {{ Str::title($featureValue['limit_duration_title']) }}
                                            @endif
                                       </div>
                                   @endforeach
                               </fieldset>
                           @else
                               <div class="alert alert-warning">
                                   {{ __tr('There are no active plan') }}
                               </div>
                           @endif
                       @endif
                       @if(getAppSettings('enable_stripe') and $isValidStripeKeys)
                       <a class="btn btn-default" href="{{ route('subscription.read.billing_portal') }}">
                           {{ __tr('Go to Billing Portal') }}
                       </a>
                       @if ($currentPlan and $subscriber->subscription($currentPlan['id']) and $subscriber->subscription($currentPlan['id'])->canceled() and $subscriber->subscription($currentPlan['id'])->onGracePeriod())
                           <a data-show-processing="true" class="lw-ajax-link-action btn btn-success"
                               href="{{ route('subscription.write.resume') }}">
                               {{ __tr('Resume Subscription') }}
                           </a>
                           <div class="note text-muted my-2">
                               {{ __tr('You will be able to resume subscription while on grace period') }}</div>
                       @endif

                       @if ($currentPlan and $subscriber->hasIncompletePayment($currentPlan['id']))
                           <div>
                               <a data-show-processing="true" class="lw-ajax-link-action btn btn-primary"
                                   href="{{ route('cashier.payment', $subscriber->latestPayment()->id) }}">
                                   {{ __tr('Please confirm your payment.') }}
                               </a>
                           </div>
                       @endif
                       @endif
                   </div>
               </div>
               @if(getAppSettings('enable_stripe') and $isValidStripeKeys)
               @if ($currentPlan and $hasPlansForPurchase)
                   <div class="card">
                       <div class="card-header">
                           {{ __tr('Change Plan') }}
                       </div>
                       <div class="card-body">
                           <form class="lw-ajax-form" data-show-processing="true" action="{{ route('subscription.write.change') }}" method="post">
                               @csrf
                               @foreach ($planStructure as $planKey => $plan)
                                   @php
                                       $planId = $plan['id'];
                                       $features = $plan['features'];
                                       $plan = $planDetails[$planKey];
                                       if (!$plan['enabled']) {
                                           continue;
                                       }
                                   @endphp
                                   <fieldset class="col-xl-4">
                                       <legend>{{ $plan['title'] }}</legend>
                                       @foreach ($features as $featureKey => $featureValue)
                                           @php
                                               $featureValue = $planDetails[$planKey]['features'][$featureKey];
                                           @endphp
                                           <div class="my-2">
                                               <i class="fa fa-check text-success mr-2"></i>
                                               @if (isset($featureValue['limit']) and $featureValue['limit'] < 0)
                                                   {{ __tr('Unlimited') }}
                                               @elseif(isset($featureValue['limit']))
                                                   {{ $featureValue['limit'] }}
                                                   @if(isset($featureValue['limit_duration']))
                                                {{ Str::title($featureValue['limit_duration']) }}
                                            @endif
                                               @endif
                                               {{ Str::title($featureValue['description']) }}
                                           </div>
                                       @endforeach
                                       <div class="text-lg mt-4">
                                           @foreach ($plan['charges'] as $itemKey => $itemValue)
                                           @php
                                               if(!$itemValue['enabled']) {
                                                   continue;
                                               }
                                           @endphp
                                               @if ($planSelectorId !== $planId . '___' . $itemKey)
                                                   <div class="form-group my-2 text-primary">
                                                       <label class="control-label" for="{{ $planId }}{{ $itemKey }}">
                                                           <input class="form-control-radio" type="radio" name="plan"
                                                           id="{{ $planId }}{{ $itemKey }}"
                                                           value="{{ $planId }}___{{ $itemKey }}">
                                                           {{ formatAmount($itemValue['charge'], true) }} /
                                                           {{ $itemKey }}
                                                       </label>
                                                   </div>
                                               @endif
                                           @endforeach
                                       </div>
                                   </fieldset>
                               @endforeach
                               <button type="submit" class="mt-4 btn btn-primary">
                                   {{ __tr('Change Plan') }}
                               </button>
                           </form>
                       </div>
                   </div>
               @endif
               @if (!$currentPlan)
                   <div class="card">
                       <div class="card-body">
                           <form action="{{ route('subscription.write.create') }}" method="post" id="payment-form"
                               data-secret="{{ $intent->client_secret }}">
                               @csrf
                               <div class="form-group">
                                   <div class="mt-4">
                                       @foreach ($planStructure as $planKey => $plan)
                                           @php
                                               $planId = $plan['id'];
                                               $features = $plan['features'];
                                               $charges = $planDetails[$planKey]['charges'];
                                               if (!$planDetails[$planKey]['enabled']) {
                                                   continue;
                                               }
                                           @endphp
                                           <fieldset class="col-xl-4">
                                               <legend>{{ $plan['title'] }}</legend>
                                               @foreach ($features as $featureKey => $featureValue)
                                                   @php
                                                       $featureValue = $planDetails[$planKey]['features'][$featureKey];
                                                   @endphp
                                                   <div class="my-2">
                                                       <i class="fa fa-check text-success mr-2"></i>
                                                       @if (isset($featureValue['limit']) and $featureValue['limit'] < 0)
                                                           {{ __tr('Unlimited') }}
                                                       @elseif(isset($featureValue['limit']))
                                                           {{ $featureValue['limit'] }}
                                                           @if(isset($featureValue['limit_duration']))
                                                {{ Str::title($featureValue['limit_duration']) }}
                                            @endif
                                                       @endif
                                                       {{ Str::title($featureValue['description']) }}
                                                   </div>
                                               @endforeach
                                               <div class="text-lg mt-4">
                                                   @foreach ($charges as $itemKey => $itemValue)
                                                       @php
                                                           if(!$itemValue['enabled']) {
                                                               continue;
                                                           }
                                                       @endphp
                                                       @if ($planSelectorId !== $planId . '___' . $itemKey)
                                                           <div class="my-2 text-primary">
                                                               <input type="radio" name="plan"
                                                                   id="{{ $planId }}{{ $itemKey }}"
                                                                   value="{{ $planId }}___{{ $itemKey }}">
                                                               <label for="{{ $planId }}{{ $itemKey }}">
                                                                   {{ formatAmount($itemValue['charge'], true) }} /
                                                                   {{ $itemKey }}</label>
                                                           </div>
                                                       @endif
                                                   @endforeach
                                               </div>
                                           </fieldset>
                                       @endforeach
                                   </div>
                                   @if($hasPlansForPurchase)
                                   <fieldset>
                                       <legend for="card-element">
                                           {{ __tr('Credit or debit card') }}
                                       </legend>
                                       <div id="card-element" class="rounded d-block mb-3 border p-3 col-sm-6 bg-white">
                                           <!-- A Stripe Element will be inserted here. -->
                                       </div>
                                       <!-- Used to display form errors. -->
                                       <div id="card-errors" role="alert" class="alert alert-danger d-none"></div>
                                   </fieldset>
                               </div>
                               <button type="submit" class="mt-4 btn btn-primary">
                                   {{ __tr('Subscribe Now') }}
                               </button>
                               @else
                               <div class="alert alert-warning">
                                   {{  __tr('No plans to subscribe') }}
                               </div>
                               @endif
                           </form>
                       </div>
                   </div>
               @endif
               @endif
               <div class="card mt-4">
                   <div class="card-body">
                       <div class="card-header">
                           {{  __tr('Invoices') }}
                       </div>
                       <div class="table-responsive">
                           <table class="table mt-4 table-striped" id="invoicesTable">
                               <thead>
                                   <tr>
                                       <th>{{  __tr('Number') }}</th>
                                       <th>{{  __tr('Date') }}</th>
                                       <th>{{  __tr('Total') }}</th>
                                       <th>{{  __tr('Invoice Download') }}</th>
                                   </tr>
                               </thead>
                               <tbody>
                               @foreach ($invoices as $invoice)
                                   <tr>
                                       <td>{{ $invoice->number }}</td>
                                       <td>{{ $invoice->date()->toDayDateTimeString() }}</td>
                                       <td>{{ $invoice->total() }}</td>
                                       <td><a
                                               href="{{ route('subscription.read.download_invoice', [$invoice->id]) }}">{{ __tr('Download') }}</a>
                                       </td>
                                   </tr>
                               @endforeach
                               </tbody>
                           </table>
                       </div>
                   </div>
               </div>
           </div>
       </div>
   </div>
   @endif
@endsection
@if(!isset($message))
@push('appScripts')
<script>
    $(document).ready(function() {
    'use strict';
    $('#invoicesTable').DataTable({
            ajax:false,
            serverSide: false,
            // "ordering": false,
            "order": [[ 1, "desc" ]],
            processing: false,
            formatNumber: function (numberValue) {
                return __Utils.formatAsLocaleNumber(numberValue);
            },
        });
    } );
</script>
@if(getAppSettings('enable_stripe') and $isValidStripeKeys)
    @if(!$currentPlan and $hasPlansForPurchase)
    <script src="https://js.stripe.com/v3/"></script>
    @endif
    <script>
        (function(){
        'use strict';
        @if(!$currentPlan and $hasPlansForPurchase)
        var stripe = Stripe('{{ config("cashier.key") }}');
        // Create an instance of Elements.
        var elements = stripe.elements();
        // Custom styling can be passed to options when creating an Element.
        // (Note that this demo uses a wider set of styles than the guide below.)
        var style = {
            base: {
                color: '#32325d',
                fontFamily: '"Helvetica Neue", Helvetica, sans-serif',
                fontSmoothing: 'antialiased',
                fontSize: '16px',
                '::placeholder': {
                    color: '#aab7c4'
                }
            },
            invalid: {
                color: '#fa755a',
                iconColor: '#fa755a'
            }
        };

        // Create an instance of the card Element.
        var card = elements.create('card', {
            style: style
        });

        // Add an instance of the card Element into the `card-element` <div>.
        card.mount('#card-element');
        // Handle real-time validation errors from the card Element.
        card.on('change', function(event) {
            var displayError = document.getElementById('card-errors');
            if (event.error) {
                displayError.textContent = event.error.message;
            } else {
                displayError.textContent = '';
            }
        });

        // Handle form submission.
        var form = document.getElementById('payment-form'),
            cardHolderName = document.getElementById('cardholder-name'),
            clientSecret = form.dataset.secret;

        form.addEventListener('submit', async function(event) {
            event.preventDefault();
            if ($(form).serializeArray().length < 2) {
                showWarnMessage('{{ __tr('Please select plan first') }}');
                return;
            }
            // check if has required information
            @if (!getVendorSettings('city') or !getVendorSettings('country_code') or !getVendorSettings('address') or !getVendorSettings('postal_code') or !getVendorSettings('state') or !getVendorSettings('contact_email') or !getVendorSettings('contact_phone'))
                showAlert("{{ __tr('Please check that you have fulfilled business information in General settings like address, city etc') }}", 'error');
                __Utils.throwError("{{ __tr('Missing business information.') }}");
            @endif

            const {
                setupIntent,
                error
            } = await stripe.confirmCardSetup(
                clientSecret, {
                    payment_method: {
                        card,
                         billing_details: {
                             "address": {
                                    "city": "{{ getVendorSettings('city') }}",
                                    "country": "{{ getVendorSettings('country_code') }}",
                                    "line1": "{{ getVendorSettings('address') }}",
                                    // "line2": null,
                                    "postal_code": "{{ getVendorSettings('postal_code') }}",
                                    "state": "{{ getVendorSettings('state') }}"
                                },
                                "email": "{{ getVendorSettings('contact_email') }}",
                                name: "{{ getUserAuthInfo('profile.full_name') }}",
                                "phone": "{{ getVendorSettings('contact_phone') }}"
                         }
                    }
                }
            );

            if (error) {
                // Inform the user if there was an error.
                var errorElement = document.getElementById('card-errors');
                errorElement.textContent = error.message;
                showAlert(error.message, "error");
            } else {
                // Send the token to your server.
                stripeTokenHandler(setupIntent);
            }
        });

        // Submit the form with the token ID.
        function stripeTokenHandler(setupIntent) {
            // Insert the token ID into the form so it gets submitted to the server
            var form = document.getElementById('payment-form');
            var hiddenInput = document.createElement('input');
            hiddenInput.setAttribute('type', 'hidden');
            hiddenInput.setAttribute('name', 'paymentMethod');
            hiddenInput.setAttribute('value', setupIntent.payment_method);
            form.appendChild(hiddenInput);
            // Submit the form
            form.submit();
        }
        @endif
    })();
    </script>
     @endif
@endpush
@endif