<?php if ($this->showPendingCCWarning == true) { ?>
<div class="alert alert-warning">
    <?php
        echo $this->user->lang(
            "You currently have credit cards pending validation. You should %svalidate%s them before you continue.",
            '<a href="index.php?fuse=clients&controller=user&view=viewusers&filter=99">',
            '</a>'
        );
    ?>
</div>
<?php } ?>


<?php if (isset($this->summary) && $this->summary != '') { ?>
<div class="alert alert-success">
    <h1 class="text-dark"><?php echo $this->user->lang("Summary"); ?></h1>
    <?php echo html_entity_decode($this->summary); ?>
</div>
<?php } ?>


<?php if ($this->passphraseDoNotMatch) { ?>
<div class="alert alert-danger">
    <?php echo $this->user->lang("You have entered an invalid passphrase, please try again"); ?>
</div>
<?php } ?>


<?php if (
    !$this->passphraseDoNotMatch &&
    ($this->phase == 'create_invoice' || $this->phase == 'process_invoice')
) { ?>

<div class="alert alert-success">
    <?php echo $this->user->lang("Your recurring billing actions are currently in progress"); ?>
</div>

<script data-cfasync="false">
$(document).ready(function() {
    <?php if ($this->phase == 'create_invoice') { ?>
        startCreateInvoices();
    <?php } ?>

    <?php if ($this->phase == 'process_invoice') { ?>
        startProcessingInvoices('<?php echo $this->include_declined ?>', '<?php echo $this->passphrase ?>');
    <?php } ?>
});
</script>

<?php } else { ?>


<?php if ($this->passphraseInLimbo) { ?>

<div class="alert alert-success">
    <?php echo $this->inLimboMsg; ?>
</div>

<?php } else { ?>

<!-- CREATE INVOICES -->
<form action="index.php" name="generateinvoice" method="GET">
    <input type="hidden" name="fuse" value="billing">
    <input type="hidden" name="controller" value="invoice">
    <input type="hidden" name="view" value="processinvoices">
    <input type="hidden" name="batchtype" value="0">
    <input type="hidden" name="phase" value="create_invoice">

    <div class="alert alert-light p-4">
        <h5 class="alert-heading"><?php echo $this->user->lang("Create Invoices"); ?></h5>

        <p>
            <?php
                echo $this->user->lang(
                    'This task can be automated using the generate invoice service. Please enable it in the %sservice settings%s',
                    '<a href="index.php?fuse=admin&controller=settings&settings=plugins_services&type=Services&view=plugins&setting=invoicegenerator">',
                    '</a>'
                );
            ?>.
            <br>
            <?php
                echo $this->user->lang(
                    'If you do not wish to enable it and generate invoices manually you can do so by clicking on the create invoices button'
                );
            ?>.
        </p>

        <button type="submit" class="btn btn-primary">
            <?php echo $this->user->lang("Create Invoices"); ?>
        </button>

        <div class="mt-2 text-muted">
            <?php echo $this->user->lang("Last Generated"); ?>:
            <?php echo $this->lastGeneratedDate; ?>
        </div>
    </div>
</form>


<!-- PROCESS CREDIT CARD PAYMENTS -->
<form action="index.php" name="generateinvoice" method="GET">
    <input type="hidden" name="fuse" value="billing">
    <input type="hidden" name="controller" value="invoice">
    <input type="hidden" name="view" value="processinvoices">
    <input type="hidden" name="batchtype" value="1">
    <input type="hidden" name="phase" value="process_invoice">

    <div class="alert alert-success p-4">

        <h5 class="alert-heading"><?php echo $this->user->lang("Process Credit Card Payments"); ?></h5>

        <p>
            <?php echo $this->user->lang(
                "Click here to process your client's credit cards for invoices that are due or past-due."
            ); ?>
            <br>
            <em>
                <?php echo $this->user->lang(
                    "If your client's credit card is stored in Clientexec you must enter your passphrase."
                ); ?>
            </em>
        </p>

        <div class="form-check mt-3">
            <input class="form-check-input" name="include_declined" id="include_declined" type="checkbox" value="1">
            <label class="form-check-label" for="include_declined">
                <?php echo $this->user->lang("Include invoices previously declined"); ?>
            </label>
        </div>

        <div id="passphrasediv">

            <div class="form-check">
                <input class="form-check-input" name="include_passphrase" id="include_passphrase" type="checkbox" value="1">
                <label class="form-check-label" for="include_passphrase">
                    <?php echo $this->user->lang("Process credit cards that require passphrase"); ?>
                </label>
            </div>

            <div id="cc_passphrase" class="mt-2" style="display:none;">
                <label class="form-label text-danger">
                    <?php echo $this->user->lang("Passphrase"); ?>
                </label>
                <input type="password" name="passphrase" class="form-control w-auto">
            </div>

        </div>

        <button type="submit" class="btn btn-primary mt-3">
            <?php echo $this->user->lang("Process Credit Cards"); ?>
        </button>

        <div class="mt-2 text-muted">
            <?php echo $this->user->lang("Last Processed"); ?>:
            <?php echo $this->lastRunBatch; ?>
        </div>

    </div>
</form>

<?php } ?>

<?php } ?>


<script>
processinvoice = {};
processinvoice.initial = 0;
processinvoice.actionperformed = "";

processinvoice.processing_win = new RichHTML.window({
    height: '60',
    title: clientexec.lang("Please wait"),
    content:
        "<span class='processing-label'>" +
        clientexec.lang("Preparing data") +
        "...</span><br/>" +
        '<div class="invoice-progress progress">' +
            '<div class="progress-bar progress-bar-striped progress-bar-animated" style="width: 0%;"></div>' +
        "</div>",
    hideButtons: true,
    escClose: false,
    buttons: {
        button1: {
            text: clientexec.lang("Stop Processing"),
            class: 'cm-btns red rich-button',
            onclick: function(a) {
                goCompleted();
            }
        }
    }
});


function startCreateInvoices()
{
    processinvoice.processing_win.show();
    processinvoice.pollingInvoiceCreator();
}

processinvoice.pollingInvoiceCreator = function()
{
    processinvoice.actionperformed = "generate";

    $.post(
        "index.php?fuse=billing&controller=invoice&action=generateinvoice",
        { initialnum: processinvoice.initial },
        function(xhr) {

            res = clientexec.parseResponse(xhr);
            res.percentage = res.percentage * 100;

            if (res.doaction == "close") {

                $('.processing-label').text(clientexec.lang("Completed"));
                $('.invoice-progress .progress-bar').css('width', '100%');

                timerID = setTimeout("goCompleted();", res.timer);

            } else if (res.doaction == "gonext") {

                $('.processing-label').text(
                    clientexec.lang("Generating Invoice(s)") + res.invoice + " for " + res.statusline
                );

                $('.invoice-progress .progress-bar').css('width', parseInt(res.percentage) + '%');

                processinvoice.initial = res.initial;

                timerID = setTimeout("processinvoice.pollingInvoiceCreator();", res.timer);
            }
        }
    );
}


function startProcessingInvoices(tIncludeDeclined, tPassphrase)
{
    processinvoice.processing_win.show();

    processinvoice.includeDeclined = tIncludeDeclined;
    processinvoice.passphrase = tPassphrase;

    processinvoice.pollingInvoiceProcessor();
}

processinvoice.pollingInvoiceProcessor = function()
{
    processinvoice.actionperformed = "process";

    $.post(
        "index.php?fuse=billing&controller=invoice&action=processinvoice",
        {
            initialnum: processinvoice.initial,
            include_declined: processinvoice.includeDeclined,
            passphrase: processinvoice.passphrase
        },
        function(xhr) {

            res = clientexec.parseResponse(xhr);
            res.percentage = res.percentage * 100;

            if (res.doaction == "close") {

                $('.processing-label').text(clientexec.lang("Completed"));
                $('.invoice-progress .progress-bar').css('width','100%');

                timerID = setTimeout("goCompleted();", res.timer);

            } else if (res.doaction == "gonext") {

                $('.processing-label').text(
                    clientexec.lang("Processing Invoice(s)") + res.invoice + " for " + res.statusline
                );

                $('.invoice-progress .progress-bar').css('width', parseInt(res.percentage) + '%');

                processinvoice.initial = res.initial;

                timerID = setTimeout("processinvoice.pollingInvoiceProcessor();", res.timer);
            }
        }
    );
}


function goCompleted() {
    this.location = "index.php?fuse=billing&controller=invoice&view=processinvoices&phase=completed&performed=" + processinvoice.actionperformed;
}


$(document).ready(function() {

    $('#include_passphrase').on('click', function() {

        if ($(this).is(":checked")) {
            $('#cc_passphrase').show();
        } else {
            $('#cc_passphrase input').val('');
            $('#cc_passphrase').hide();
        }
    });

});

</script>