@{
    ViewData["Title"] = "index";
}

<div class="app-content container center-layout mt-2">
    <div class="content-wrapper">
        <!-- Alert Section Starts -->
        @{
            if (ViewBag.flash_message != null)
            {
                <div class="alert alert-primary" role="alert">
                    @ViewBag.flash_message

                    <button type="button" class="close" data-dismiss="alert" aria-label="Close">
                        <span aria-hidden="true">&times;</span>
                    </button>
                </div>
            }
        }
        <!-- Alert Section Ends -->
        <div class="content-body">
            <div class="row">
                <div class="col-lg-12 col-md-12 col-12">
                    <div class="card">
                        <div class="card-header border-0-bottom">
                            <h4 class="card-title">Your Accounts</h4>
                        </div>
                        <div class="card-content">
                            <div class="card-body">
                                @{
                                    if (ViewBag.Accounts.Count == 0)
                                    {
                                        <p>You have no accounts at this time</p>
                                    }
                                    else
                                    {
                                        <ul>
                                            @{
                                                for (int i = 0; i < ViewBag.Accounts.Count; i++)
                                                {
                                            <li>
                                                ID: @ViewBag.Accounts[i].AccountId
                                                @{
                                                    if (ViewBag.Accounts[i].Type == "PRIMARY")
                                                    {
                                                        <span>(@ViewBag.Accounts[i].Type)</span>
                                                        <span> - Available Balance: <span class="badge badge-success">$@String.Format("{0:0.00}", @ViewBag.Accounts[i].Balance)</span></span>
                                                    }
                                                    else if (ViewBag.Accounts[i].ExternalAccountType == "STRIPE_CONNECT")
                                                    {
                                                        <span>(@ViewBag.Accounts[i].ExternalAccountType)</span>
                                                        <button type="button" class="btn btn-default btn-sm js-withdraw-balance" data-url="@Url.Action("WithdrawBalanceAPI", "Stripe", new { AccountId = @ViewBag.Accounts[i].AccountId })"><span class="ficon ft-minus"></span> Withdraw Balance</button>
                                                        <button type="button" class="btn btn-warning btn-sm js-delete-account" data-url="@Url.Action("DeleteExternalAccountAPI", "Stripe", new { AccountId = @ViewBag.Accounts[i].AccountId })"><span class="ficon ft-trash"></span> Delete</button>
                                                    }
                                                    else
                                                    {
                                                        <span>(EXTERNAL)</span>
                                                        <button type="button" class="btn btn-primary btn-sm js-add-balance" data-url="@Url.Action("AddBalanceAPI", "Stripe", new { AccountId = @ViewBag.Accounts[i].AccountId })"><span class="ficon ft-plus"></span> Add Balance From Account</button>
                                                        <button type="button" class="btn btn-warning btn-sm js-delete-account" data-url="@Url.Action("DeleteExternalAccountAPI", "Stripe", new { AccountId = @ViewBag.Accounts[i].AccountId })"><span class="ficon ft-trash"></span> Delete</button>
                                                    }
                                                }
                                            </li>
                                                }
                                            }
                                            @{
                                                if (ViewBag.has_stripe == false)
                                                {
                                                    <br><a class="btn btn-secondary" href="https://connect.stripe.com/oauth/authorize?response_type=code&client_id=@ViewBag.stripe_client_id&scope=read_write&state=@ViewBag.stripe_oauth_secret@ViewBag.stripe_oauth_token_separator@ViewBag.user_id">Add Stripe Account To Withdraw Funds</a>
                                                }
                                            }
                                        </ul>
                                    }
                                }
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            @{
                if (ViewBag.Accounts.Count == 0)
                {
                    <button class="btn btn-primary js-create-primary-account">Create Your Internal Account</button>
                }
            }
            <button id="linkButton" class="btn btn-default">Add A Bank Account</button>
            <script src="https://cdn.plaid.com/link/v2/stable/link-initialize.js"></script>
            <script>
                var linkHandler = Plaid.create({
                    selectAccount: true,
                    env: 'sandbox',
                    clientName: 'EFORT Client',
                    key: '@ViewBag.plaid_public_key',
                    product: ['auth'],
                    onLoad: function() {
                        // The Link module finished loading.
                    },
                    onSuccess: function (public_token, metadata)
                    {
                        $.ajax(
                        {
                            'url': "@Url.Action("SavePlaidTokenAPI", "Stripe")",
                            'method': "POST",
                            'data': { public_token: public_token, plaid_account_id: metadata.account_id }
                        }).done(function (data)
                        {
                            data = JSON.parse(data);
                            if (typeof (data.status) !== 'undefined' && data.status == 'OK')
                            {
                                alert(data.message);
                                window.location.reload();
                            }
                            else
                            {
                                alert(data.message);
                            }
                        }).fail(function (data)
                        {
                                alert('There was an error processing this request. Please contact the system administrator. Error code: 7V01');
                            });
                        },
                    onExit: function(err, metadata) {
                        // The user exited the Link flow.
                        if (err != null) {
                            // The user encountered a Plaid API error prior to exiting.
                        }
                        // metadata contains information about the institution
                        // that the user selected and the most recent API request IDs.
                        // Storing this information can be helpful for support.
                    },
                });

                // Trigger the standard Institution Select view
                document.getElementById('linkButton').onclick = function() {
                        linkHandler.open();
                };

                window.addEventListener('load', function ()
                {
                    //Account management
                    $('.js-create-primary-account').on('click', function () {
                        $.ajax(
                        {
                            "url": "@Url.Action("CreatePrimaryAccountAPI", "Stripe")"
                        }).done(function (data)
                        {
                            data = JSON.parse(data);
                            if (typeof (data.status) !== 'undefined' && data.status == 'OK') {
                                alert(data.message);
                                window.location.reload();
                            }
                            else {
                                alert(data.message);
                            }
                        });
                    });

                    $('.js-delete-account').on('click', function () {
                        $.ajax(
                        {
                            "url": $(this).data('url')
                        }).done(function (data)
                        {
                            data = JSON.parse(data);
                            if (typeof (data.status) !== 'undefined' && data.status == 'OK')
                            {
                                alert(data.message);
                                window.location.reload();
                            }
                            else {
                                alert(data.message);
                            }
                        });
                    });

                    //Add balance
                    $('.js-add-balance').on('click', function ()
                    {
                        $('.js-add-balance-modal').modal('toggle');
                        $('.js-add-balance-action-url').val( $(this).data('url') );
                    });

                    $('.js-add-balance-submit').on('click', function ()
                    {
                        $.ajax(
                        {
                            "url": $('.js-add-balance-action-url').val(),
                            "method": "POST",
                            "data": { balance: $('.js-add-balance-input').val() }
                        }).done(function (data) {
                            data = JSON.parse(data);
                            if (typeof (data.status) !== 'undefined' && data.status == 'OK') {
                                alert(data.message);
                                window.location.reload();
                            }
                            else {
                                alert(data.message);
                            }
                        });
                    });

                    //Withdraw balance
                    $('.js-withdraw-balance').on('click', function () {
                        $('.js-withdraw-balance-modal').modal('toggle');
                        $('.js-withdraw-balance-action-url').val($(this).data('url'));
                    });

                    $('.js-withdraw-balance-submit').on('click', function () {
                        $.ajax(
                        {
                            "url": $('.js-withdraw-balance-action-url').val(),
                            "method": "POST",
                            "data": { balance: $('.js-withdraw-balance-input').val() }
                        }).done(function (data) {
                            data = JSON.parse(data);
                            if (typeof (data.status) !== 'undefined' && data.status == 'OK') {
                                alert(data.message);
                                window.location.reload();
                            }
                            else {
                                alert(data.message);
                            }
                        });
                    });
                });
            </script>
        </div>
    </div>
</div>

<!-- Add Balance Modal Starts -->
<div class="modal js-add-balance-modal" tabindex="-1" role="dialog">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">Add Balance</h5>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>
            <div class="modal-body">
                <p>How much balance do you want to add?</p>
                <input type="text" class="js-add-balance-input" value="" placeholder="0.00">
                <input type="hidden" class="js-add-balance-action-url" value="">
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
                <button type="button" class="btn btn-primary js-add-balance-submit">Add Balance</button>
            </div>
        </div>
    </div>
</div>
<!-- Add Balance Modal Ends -->
<!-- Withdraw Balance Modal Starts -->
<div class="modal js-withdraw-balance-modal" tabindex="-1" role="dialog">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">Withdraw Balance</h5>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>
            <div class="modal-body">
                <p>How much balance do you want to withdraw to this account?</p>
                <input type="text" class="js-withdraw-balance-input" value="" placeholder="0.00">
                <input type="hidden" class="js-withdraw-balance-action-url" value="">
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
                <button type="button" class="btn btn-primary js-withdraw-balance-submit">Withdraw Balance</button>
            </div>
        </div>
    </div>
</div>
<!-- Withdraw Balance Modal Ends -->
