<!DOCTYPE html>
<html>
<head>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">

	<!--
		NOTE:
		1. You can reference the file in SDK via relative path
		2. The Control and Widget Should NOT share resources. Only the Widget folder will make it to the device
		3. You may include any JS framework you want with your Widget and Control folders. However, keep in mind
		    to keep you plugin as light weight as possible for performance and transport reasons
	-->

	<link href="../../../styles/helper.css" rel="stylesheet">
	<!-- JS -->
   <script type="text/javascript" src="../../../scripts/angular/angular.min.js"></script>
	<script type="text/javascript" src="../../../scripts/buildfire.js"></script>  
   <script type="text/javascript" src="../../../scripts/angular/ui-bootstrap.min.js"></script>
    <link rel="stylesheet" href="style.css"/>
</head>
<body>
<div ng-app="app">
    <div ng-controller="paidApp">
        <div ng-repeat="plugin in pluginList" class="plugin">
            <div style="width: 100%; height: 25%;">
             <img style="width:100%; height: 100%;" ng-if="plugin.iconUrl" src="{{plugin.iconUrl}}" /><i ng-if="plugin.iconClassName" style="font-size:200px;" class="{{plugin.iconClassName}}"></i>
            </div>
            <div style="padding: 0;" ng-if="allPlugins.indexOf(plugin.instanceId) === -1">
                <button class="pluginButton" ng-click="selectPlan(plugin,plan)" style="width:{{100/plugin.plans.length}}%;" ng-repeat="plan in plugin.plans">{{plan.name}}</button>
                <hr/>
            </div>
            <div ng-if="livePlugins.indexOf(plugin.instanceId) >= 0">
            <button ng-click="navigate(plugin)" class="pluginButton" style="width:49.2%">Go to Plugin</button>
            <button ng-click="viewSub(plugin.instanceId)" class="pluginButton" style="width:49.3%">View Subscription</button>
                <hr/>
            </div>
        </div>
        
        <div ng-hide="paymentShow" style="background: rgba({{red}},{{green}},{{blue}},{{opacity}});" class="paymentPopUp">
            <style>
                .pluginButton{
                    height:40px;
                    background: none;
                    border-bottom: 1px solid;
                    border-right: 1px solid;
                    margin: 0;
                    border-radius: 5px;
                }
                .paymentPopUp{
                    padding:3px;
                    position: fixed;
                    bottom: 0;
                    left: 0;
                    height: 35vh;
                    width: 100%;
                    border-radius: 5px;
                    border: 1px solid;
                    -webkit-animation-name: example; /* Safari 4.0 - 8.0 */
                    -webkit-animation-duration: 1s; /* Safari 4.0 - 8.0 */
                    animation-name: example;
                    animation-duration: 1s;
                }
                @-webkit-keyframes example {
                    from {
                        width: 1px;
                        border-radius: 50%;
                        height: 1px;
                    }
                    to {
                        width: 100%;
                        height: 35vh;
                    }
                }
                
                /* Standard syntax */
                @keyframes example {
                    from {
                        width: 1px;
                        height: 1px;
                        border-radius: 50%;
                    }
                    to {
                        width: 100%;
                        height: 35vh;
                    }
                }
                .paymentPopUp input{
                    width: 100%;
                    height: 30px;
                    font-size: 18px;
                    background: none;
                    border: none;
                    border-bottom: 1px solid;
                    text-align: center;
                }
                .paymentPopUp button{
                    width: 100%;
                    height: 40px;
                    font-size: 18px;
                    background: none;
                    border: none;
                    border-top: 1px solid;
                    border-bottom: 1px solid;
                }
                }
                #card-element{
                    border-bottom: 1px solid;
                }
            </style>
            <button ng-click = "paymentShow = true;" class="btn btn-danger" style="width:20px; height: 20px; float: right; font-size: 18px; padding: 0;">X</button><br/>
            <input  placeholder="email" ng-model="email"/>
            <div ng-hide="customerId != undefined">
                <form method="post" id="payment-form">
                <div class="form-row">
                    <div id="card-element">
                     <!-- a Stripe Element will be inserted here. -->
                    </div>
                    <!-- Used to display form errors -->
                    <div id="card-errors"></div>
        </div>
                    <button ng-click="submitPayment()">Subscribe Now</button>
                </form>
            </div>
            <div ng-show="customerId != undefined">
               <button ng-click="submitAgain()">Subscibe Now</button>
                <button style="height: 30px; font-size: 13px;" ng-click="forget()">Forget My Account</button>
                <button class="btn btn-danger" ng-show="confirm" ng-click = "forgetCustomer()" style="font-size: 10px; height: 50px; padding: 0;">WARNING: All Active Subscriptions will be canceled. <br/>CLICK HERE to forget Account and Cancel Subscriptions</button>
            </div>
            <div class="details" ng-hide="confirm">
                <span>Subscribed Plugin:</span><span style="float: right;">{{currentPlugin}}</span><br/>
                <span>Subscription Plan:</span><span style="float: right;">{{currentPlan}}</span>
            </div>
        </div>
        
        <div class="paymentPopUp"  style="background: rgba({{red}},{{green}},{{blue}},{{opacity}});" ng-hide="subscriptionShow">
        <div ng-repeat="plan in allSubscriptions | filter: currentSubscription">
            <button ng-click = "hideSubscription()" class="btn btn-danger" style="width:20px; height: 20px; float: right; font-size: 18px; padding: 0;">X</button><br/>
            <div ng-if="plan.status==='active'" style="height: 30px; font-size: 18px;" class="alert alert-success transition-half">{{plan.status}}</div>
            <div ng-if="plan.status==='trialing'" style="height: 30px; font-size: 18px;" class="alert alert-warning transition-half">{{plan.status}}</div>
                <span>Subscription Plan:</span><span style="float: right;">
                {{plan.plan.amount/100}} {{plan.plan.currency}} every {{plan.plan.interval_count}} {{plan.plan.interval}}(s)
            </span><br/>
            <div ng-if="plan.status==='active'">
                <span>Next Payment Due:</span><span style="float: right;">
                {{plan.current_period_end*1000 | date:'shortDate' }}
            </span><br/>
            </div>
            <div ng-if="plan.status==='trialing'">
                <span>First Payment Due:</span><span style="float: right;">
                {{plan.current_period_end*1000 | date:'shortDate' }}
            </span><br/>
            </div>
            <div ng-if="plan.cancel_at_period_end===true"  style="height: 30px;" class="alert alert-danger transition-half">Subscription Canceled on {{plan.canceled_at*1000 | date:'shortDate' }} <br/> You will have Access until  next Payment Period</div><br/>
                <button ng-hide="plan.cancel_at_period_end===true" style="width:60%; height: 40px; float: left; font-size: 16px;" ng-click="cancelSubscription(plan.id)" class="btn btn-danger">Cancel Subscription</button>
            </div>
        </div>
        
        
    </div>
    </div>
</body>
    <script>
            var app = angular.module('app', []);
        app.controller('paidApp', function($scope,$http) {
            $scope.paymentShow=true;
            $scope.confirm=false;
            
            var e = buildfire.datastore.onUpdate(function(event){   
                console.log(event);
                $scope.getPlugins();
                $scope.getColor();
                $scope.$apply();
            });
            
                        $scope.getColor = function(){
                buildfire.datastore.get("color",function(err,data){
                    if(err){
                        console.log(err);
                    }
                    if(data){
                        console.log(data);
                       $scope.red = data.data.red;
                       $scope.green = data.data.green;
                       $scope.blue = data.data.blue;
                        $scope.opacity = data.data.opacity;
                        $scope.$apply();
                       }
                });
            };$scope.getColor();
            
               $scope.getStripe = function(){
                buildfire.datastore.get("stripe",function(err,data){
                    if(err){
                        console.log(err);
                    }
                    if(data){
                        console.log(data);
                       $scope.stripeID = data.data.stripeId;
                       $scope.stripePKey = data.data.pKey;
                       $scope.stripeSKey = data.data.sKey;
                        localStorage.sKey = data.data.sKey;
                        $scope.$apply();
                        $scope.cardHandler();
                        $scope.doIt();
                        $scope.getCustomer();
                       }
                });
            };$scope.getStripe();
            $scope.forget=function(){
                $scope.confirm=true;
                $scope.deleteStatus="Are you sure you want to forget your account.";
            }
            $scope.forgetCustomer=function(){
                    var planData ="id="+$scope.customerId+"&clientSecretKey="+$scope.stripeSKey;
              var config = {
                headers : {
                    'Content-Type': 'application/x-www-form-urlencoded;'
                }
                };
                $http.post('https://liquorifittraining.com/php/deleteCustomer.php', planData, config)
            .success(function (data, status, headers, config) {
                  var customerData ={};
                  buildfire.userData.save (customerData, 'customer', function(err,data){
                    if(err){
                        console.log(err);
                    }
                    else{
                        localStorage.removeItem("cId");
                       $scope.getCustomer();
                        $scope.paymentShow=true;
                    }
                }); 
            })
            .error(function (data, status, header, config) {
                  var customerData ={};
                  buildfire.userData.save (customerData, 'customer', function(err,data){
                    if(err){
                        console.log(err);
                    }
                    else{
                       $scope.getCustomer();
                        $scope.paymentShow=true;
                    }
                }); 
            }); 
            };
            
               $scope.navigate=function(x){
                buildfire.navigation.navigateTo(x);                
            };
            
            $scope.hideSubscription=function(){
                $scope.subscriptionShow=true;
            };
                $scope.doIt = function () {
                    var logoptions = [];
                    buildfire.auth.login(logoptions, 
                    function (err, user) {
                        console.log(user);
                        $scope.email = user.email;
                    });
                };
            $scope.cardHandler=function(){
            $scope.stripe = Stripe($scope.stripePKey);
            var elements = $scope.stripe.elements();
            // Custom Styling
            var style = {
                base: {
                    color: '#32325d',
                    lineHeight: '24px',
                    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
            $scope.card = elements.create('card', {style: style});
            // Add an instance of the card Element into the `card-element` <div>
            $scope.card.mount('#card-element');
            // Handle real-time validation errors from the card Element.
            $scope.card.addEventListener('change', function(event) {
                var displayError = document.getElementById('card-errors');
                if (event.error) {
                    displayError.textContent = event.error.message;
                } else {
                    displayError.textContent = '';
                }
            });
            }
            //Existing Customer
            $scope.submitAgain=function(){
                var planData ="customerId="+$scope.customerId+"&plan="+$scope.paymentPlan+"&plugin="+$scope.paidPlugin+"&pluginTitle="+$scope.paidTitle+"&stripeId="+$scope.stripeID;
               console.log(planData);
                var config = {
                headers : {
                    'Content-Type': 'application/x-www-form-urlencoded;'
                }
                };
                $http.post('https://liquorifittraining.com/php/liquoriFitSubscribe.php', planData, config).success(function(data,status,headers,config){
                        $scope.paymentShow = true;
                        $scope.getCustomer();
                }).error(function(data,status){
                    console.log("Error in Subscibing");
                    console.log(data);
                    console.log(status);
                });
            };
            // Handle form submission
            $scope.submitPayment=function(token){
                var form = document.getElementById('payment-form');
                  $scope.stripe.createToken($scope.card).then(function(result) {
                    if (result.error) {
                        // Inform the user if there was an error
                        var errorElement = document.getElementById('card-errors');
                        errorElement.textContent = result.error.message;
                    } else {
                var planData ="form="+form+"&token="+result.token.id+"&email="+$scope.email+"&plan="+$scope.paymentPlan+"&plugin="+$scope.paidPlugin+"&pluginTitle="+$scope.paidTitle+"&stripeId="+$scope.stripeID+"&clientSecretKey="+$scope.stripeSKey;
                var config = {
                headers : {
                    'Content-Type': 'application/x-www-form-urlencoded;'
                }
                };
                $http.post('https://liquorifittraining.com/php/createCustomer.php', planData, config)
            .success(function (data, status, headers, config) {
                $scope.paymentShow = true;
                var customerData = {
                    id : data.id,
                    last4: data.sources.data[0].last4,
                    card: data.sources.data[0].brand,
                    zip: data.sources.data[0].zip
                };
                    $scope.customerId = data.id;
                buildfire.userData.save (customerData, 'customer', function(err,data){
                    if(err){
                        console.log(err);
                    }
                    else{
                        $scope.submitAgain();
                    }
                });
            })
            .error(function (message, status, header, config) {
            });  }
                });
            };
            $scope.getPlugins=function(){
                     buildfire.datastore.search( {
                        "page":0,
                        "pageSize":50
                    } , 'plugins2', function(err,data){
                    $scope.pluginList =[];
                        data.map(function(x){
                            x.data.id=x.id;
                            $scope.pluginList.push(x.data)
                        });
                         $scope.$apply;
                         });
            };
            $scope.selectPlan = function(plugin,plan){
                $scope.paymentShow = false;
                $scope.currentPlugin = plugin.title;
                $scope.currentPlan= (plan.amount/100) + " " + plan.currency+ " every " +plan.interval_count+" "+plan.interval+"(s)";
                $scope.paymentPlan = plan.id;
                $scope.paidPlugin = plugin.instanceId;
                $scope.paidTitle = plugin.title;
                console.log(plugin);
                console.log(plan);
            };
            $scope.getCustomer=function(){
                buildfire.userData.get('customer',function(err,data){
                    console.log(data);
                    if(data.data.id === undefined){
                        $scope.customerId=undefined;
                    }
                    if(data.data.id != undefined){
                    $scope.customerId = data.data.id;
                        localStorage.cId = data.data.id;
                    var planData ="id="+data.data.id+"&clientSecretKey="+$scope.stripeSKey;
                var config = {
                headers : {
                    'Content-Type': 'application/x-www-form-urlencoded;'
                }
                };
                $http.post('https://liquorifittraining.com/php/getCustomer.php', planData, config)
            .success(function (data, status, headers, config) {
                    console.log(data);
                    $scope.liveSubscriptions = [];
                    $scope.livePlugins = [];
                    $scope.deadSubscriptions = [];
                    $scope.deadPlugins=[];
                    $scope.allSubscriptions=[];
                    $scope.allPlugins=[];
                    
                    if(data.subscriptions != undefined){
                    data.subscriptions.data.map(function(x){
                        $scope.allSubscriptions.push(x);
                        $scope.allPlugins.push(x.metadata.pluginId);
                        if(x.status === "active"){
                            $scope.livePlugins.push(x.metadata.pluginId);
                        }
                        if(x.status === "trialing"){
                            $scope.livePlugins.push(x.metadata.pluginId);
                        }
                        if(x.status != "active"){
                            $scope.deadPlugins.push(x.metadata.pluginId);
                        }
                    });}
                    $scope.getPlugins();
                    
            })
            .error(function (data, status, header, config) {
                    $scope.allPlugins=[];
                    $scope.customerId = undefined;
                    $scope.getPlugins();
            });    
                    }
                    else{
                      $scope.allPlugins=[];
                    $scope.getPlugins();
                    }
                });
            };
            $scope.subscriptionShow = true;
            $scope.viewSub=function(id){
                $scope.currentSubscription = id;
                $scope.subscriptionShow = false;
                console.log($scope.currentSubscription);
                
            };
            $scope.cancelSubscription = function(id){
                var planData ="id="+id+"&stripeId="+$scope.stripeID;
                var config = {
                headers : {
                    'Content-Type': 'application/x-www-form-urlencoded;'
                }
                };
                $http.post('https://liquorifittraining.com/php/cancelPlan.php', planData, config)
            .success(function (data, status, headers, config){
                    $scope.getCustomer();
            })
            .error(function (data, status, header, config) {
                    console.log("Error Unsubscribing");
                    console.log(status);
            });
            };
        });
    </script>
    <script src="https://js.stripe.com/v3/"></script>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
</html>