<?php

/**
************************************************************************
Copyright [2015] [PagSeguro Internet Ltda.]

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
************************************************************************
*/

?>
<?php
    $helper = Mage::helper('pagseguro/canceled');
    $html   = Mage::helper('pagseguro/html');
?>

<div id="pagseguro-module">
    <?php echo $html->getHeader(); ?>
    <div id="pagseguro-module-content">
        <div class="wrapper">
            <?php echo $html->getSideMenu();?>
            <div id="pagseguro-module-contents">
                <h2 class="title"><?php echo $helper->__('Cancelamento'); ?></h2>
                <p>
                    <?php
                        $string .= 'Com esta funcionalidade você poderá listar e cancelar transações que ainda estão
                            nos status “Em análise” e “Aguardando Pagamento”. É aconselhável que antes de usar esta
                            funcionalidade você faça a conciliação de suas transações para obter os status mais atuais.';
                        echo $helper->__($string);
                     ?>
                </p>

                <div class="pagseguro-search-tools">
                    <form action="javascript:void(0)" method="post" >
                        <input type="hidden" name="form_key" value="<?php echo Mage::getSingleton('core/session')->getFormKey();?>" />
                        <input type="submit" class="pagseguro-button" id="canceled-search-button" value="<?php echo $helper->__('Pesquisar');?>" />
                        <select class="pagseguro-field" name="pagseguro-days" id="pagseguro-canceled-days-input">
                            <option value='5'>5</option>
                            <option value='10'>10</option>
                            <option value='15'>15</option>
                            <option value='20'>20</option>
                            <option value='25'>25</option>
                            <option value='30'>30</option>
                        </select>
                        <label><?php echo $helper->__('últimos dias'); ?></label>
                    </form>
                </div>

                <table id="canceled-table" class="pagseguro-table">
                    <thead>
                        <tr>
                            <th width="14%"><?php echo $helper->__('Data');?></th>
                            <th width="20%"><?php echo $helper->__('ID Magento');?></th>
                            <th width="35%"><?php echo $helper->__('ID PagSeguro');?></th>
                            <th width="20%"><?php echo $helper->__('Status Magento');?></th>
                            <th width="11%"><?php echo $helper->__('Ação');?></th>
                        </tr>
                    </thead>
                </table>

                <?php
                    $noTransaction = 'Nenhum resultado.';
                    $canceledSuccess = $helper->__("Transação cancelada com sucesso!");
                    $canceledError = $helper->__("Não foi possível executar esta ação. <br /> Utilize a conciliação de transações primeiro ou tente novamente mais tarde.");
                ?>

                <div id="canceled-info" class="pagseguro-msg pagseguro-msg-info pagseguro-msg-micro">
                    <p><?php echo $helper->__('Somente transações geradas a partir da versão 2.3 do módulo serão listadas.'); ?></p>
                </div>
            </div>
        </div>
    </div>
</div>

<script type="text/javascript">
    var i = 0;

    jQuery(document).ready(function(){
        Menu.init();
        PageCanceled.init();
    });

    var PageCanceled = new function(){
        var requestTransactions = function() {

            // calls the modal of loading
            Modal.showLoading('<?php echo $helper->__('Aguarde...');?>');

            jQuery.ajax({
                url: "<?php echo Mage::getSingleton('adminhtml/url')->getUrl('pagseguro/adminhtml_canceled/doPost'); ?>",
                type: "POST",
                data: {
                    form_key: "<?php echo Mage::getSingleton('core/session')->getFormKey();?>",
                    days: jQuery('#pagseguro-canceled-days-input').find(":selected").text()
                },
                success: function(xhrResult) {

                    xhrResult = JSON.parse(xhrResult);

                    if (xhrResult.status == false && xhrResult.err == "[HTTP 401] - UNAUTHORIZED") {

                        Modal.message('error', "Não foi possível realizar a consulta.");
                    } else {

                        // Ajax result handler and populates dataTable
                        if (xhrResult.status == false) {

                            jQuery('#canceled-table').dataTable().fnClearTable(true);
                            Modal.message('alert', "Sem resultados para o período solicitado.");

                        } else {

                            jQuery('#canceled-table').dataTable().fnClearTable(true);
                            jQuery('#canceled-table').dataTable().fnAddData(xhrResult);
                            jQuery('#canceled-table').dataTable()._fnInitComplete();
                            //After reassembling the table removes the modal of loading
                            Modal.hideLoading();

                        }
                    }
                },
                error: function(xhrErr) {
                    Modal.message('error', xhrErr);
                }
            });
        }
        
        var doCanceled = function(config){

            var id = '';
            var code = '';
            var status = '';
            var jsonArr = [];

            config = config.split('/');
            jsonArr.push({
                id: config[0],
                code: config[1],
                status: config[2]
            });

            Modal.showLoading('<?php echo $helper->__('Aguarde...');?>');

            jQuery.ajax({
                url: "<?php echo Mage::getSingleton('adminhtml/url')->getUrl('pagseguro/adminhtml_canceled/doCanceled'); ?>",
                type: "POST",
                data: {
                    form_key: "<?php echo Mage::getSingleton('core/session')->getFormKey();?>",
                    data: jsonArr,
                    days: jQuery('#pagseguro-canceled-days-input').find(":selected").text()
                },
                success: function(xhrResult) {

                    xhrResult = JSON.parse(xhrResult);

                    if (xhrResult.status == false && xhrResult.err == true) {
                        
                        jQuery('#canceled-table').dataTable().fnClearTable(true);
                        Modal.message('error', 'Não foi possível executar esta ação. Utilize a conciliação de transações primeiro ou tente novamente mais tarde.');
                    } else if (xhrResult.status == false && xhrResult.err == "[HTTP 403] - FORBIDDEN") {
                        
                        Modal.message('error', "Sua conta PagSeguro não tem permissão para realizar esta ação. Em caso de dúvidas acesse <a href='http://forum.pagseguro.uol.com.br' target='_blank'>http://forum.pagseguro.uol.com.br</a>");
                    } else if (xhrResult.status == false) {

                        jQuery('#canceled-table').dataTable().fnClearTable(true);
                        Modal.message('success', '<?php echo $canceledSuccess; ?>');
                    }else {

                        var oTable = jQuery('#canceled-table').dataTable();
                        oTable.fnClearTable(true);
                        oTable.fnAddData(xhrResult, true);
                        oTable.fnStandingRedraw();
                        Modal.message('success', '<?php echo $canceledSuccess; ?>');
                    }
                },
                error: function() {
                    Modal.message('error', '<?php echo $canceledError; ?>');
                }
            });
        };

        var prepareTable = function(){
            var flow = 0;
            var totalRows = 0;
            var page = 0;
            var currentPage = 0;
            var oTable;

            jQuery.fn.dataTableExt.oApi.fnStandingRedraw = function(oSettings) {
                //redraw to account for filtering and sorting
                // concept here is that (for client side) there is a row got inserted at the end (for an add)
                // or when a record was modified it could be in the middle of the table
                // that is probably not supposed to be there - due to filtering / sorting
                // so we need to re process filtering and sorting
                // BUT - if it is server side - then this should be handled by the server - so skip this step
                if(oSettings.oFeatures.bServerSide === false){
                    var before = oSettings._iDisplayStart;
                    oSettings.oApi._fnReDraw(oSettings);
                    //iDisplayStart has been reset to zero - so lets change it back
                    oSettings._iDisplayStart = before;
                    oSettings.oApi._fnCalculateEnd(oSettings);
                }

                //draw the 'current' page
                oSettings.oApi._fnDraw(oSettings);
            };

            // Initiates the creation of the table dataTable
            jQuery('#canceled-table').dataTable({
                "info": false,
                "lengthChange": false,
                "searching": false,
                "bStateSave": true,
                "pageLength": 10,
                "aaSorting": [[ 0, "desc" ]],
                "aoColumnDefs": [
                    { 'bSortable': false, 'aTargets': [ 4 ] },
                    { "sClass": "tabela", 'aTargets': [ 1, 2, 3, 4 ] }
                ],

                // Creates paging and notifies when there is no record
                "oLanguage": {
                    "sEmptyTable":"<?php echo $helper->__($noTransaction); ?>",
                    "oPaginate": {
                        "sNext": '<?php echo $helper->__('Próximo');?>',
                        "sLast": '<?php echo $helper->__('Último');?>',
                        "sFirst": '<?php echo $helper->__('Primeiro');?>',
                        "sPrevious": '<?php echo $helper->__('Anterior');?>'
                    }
                },

                // Every interaction with the table it is called
                "fnDrawCallback": function(oSettings) {
                    // Makes when clicked on a registry is redirected to the editing order of Magento
                    oTable = this;
                    totalRows = oTable.fnGetData().length;
                    var table = jQuery('#canceled-table').DataTable();
                    var info = table.page.info();

                    //trClick
                    if (totalRows >= 1) {
                        var href;
                        jQuery('#canceled-table tbody tr').unbind('click');

                        jQuery('#canceled-table tbody tr').bind('click', function () {
                            href = jQuery(table.row( this ).data()[4])[0].href;
                            jQuery('#canceled-table tbody').off();
                            jQuery('#canceled-table tbody').on('click', 'td', function () {
                                if (jQuery(this).index() != 4){
                                    window.open(href, '_blank');
                                }
                            } );
                        } );
                    }

                    // Only if greater than 10 records show paging
                    if (totalRows > 10) {
                        jQuery('.dataTables_paginate').css('display','block');
                        flow = 1;
                    } else {
                        jQuery('.dataTables_paginate').css('display','none');
                        flow = 0;
                    }

                    // If the home page does not display the previous page button
                    if (info.page == 0) {
                        jQuery('a#canceled-table_previous').css('display','none');
                    }

                    // If the last page does not display the next page button
                    if ((info.page+1) == info.pages) {
                        jQuery('a#canceled-table_next').css('display','none');
                    }

                    i++;

                    // Stores which is the page that appears after update
                    if (i == 1) {
                        if (page >= 1 && totalRows < 1) {
                            currentPage = page - 1;
                        } else {
                            currentPage = page;
                        }
                    }

                    // Stores the current page, calculated by number of records and number of records per page
                    page  = Math.ceil(oSettings._iDisplayStart / oSettings._iDisplayLength);
                },

                // When it completes assembly of the table is executed
                "initComplete": function (oSettings) {
                    oTable = this;

                    if (currentPage != 0) {
                        // When upgraded back on the page that was
                        oTable.fnPageChange(currentPage);
                    }
                }
            });
        }

        this.init = function() {
            prepareTable();

            jQuery('#canceled-search-button').click(function () {
                requestTransactions();
            });

            jQuery('#canceled-table').on('click', 'a.action', function(e) {
            
                var cancel = jQuery(this);

                Modal.confirm('Não será possível reverter esta ação. \nDeseja continuar?');
                
                jQuery('.pagseguro-confirm-button').on('click', function(target) {
                    if (target.currentTarget.id == 'accept') {
                        doCanceled(cancel.data('config'));
                    } else {
                        Modal.hideLoading();
                    }
                });
            });
            
            
        };
    }
</script>
<script type="text/javascript" src="<?php echo $this->getSkinUrl('uol/pagseguro/js/pagseguro-module.js');?>"></script>
