<style>
    .add-head{
        padding-left: 50px!important;
    }
    .img-head{
        width: 28px;
        height: 25px
    }
    .btn-clipboard {
        border: none !important;
        padding: 0 !important;
        background: none;
        cursor: pointer;
        outline: none;
    }
    .restore-icon img {
        display: inline-block;
        width: 1.25rem;
    }
</style>
<!-- show a warning if user is not signed in -->
<?php $session_user_id = ($this->Session->read('userData.id')) ? $this->Session->read('userData.id') : '' ;
    if ($session_user_id == ''): ?>
        <?php echo $this->element('myexpense_warning'); ?>
<?php endif; ?>

<div class="block-2">
    <div class="container">

        <div class="row">

            <div class="col-sm-1"></div>
            <div class="col-sm-10 text-center">
                <div class="row">

                    <!--Grid column-->
                    <div class="col-lg-4 col-md-12 mb-4">
                        <div class="col-lg-12 py-2" style="border: 1px solid #ddd;text-align:center;background:#eee;">
                            <a href="<?php echo HTTP_SITE_URL ?>/Home/createGroupExpense"> Create Group - WeXpense </a>
                        </div>
                    </div>
                    <div class="col-lg-4 col-md-12 mb-4">
                        <div class="col-lg-12 py-2" style="border: 1px solid #ddd;text-align:center;background:#eee;">
                            <a href="<?php echo HTTP_SITE_URL ?>/Home/createMessExpense"> Create Mess - MessXpense</a>
                        </div>
                    </div>
                    <div class="col-lg-4 col-md-12 mb-4">
                        <div class="col-lg-12 py-2" style="border: 1px solid #ddd;text-align:center;background:#eee;">
                            <a href="<?php echo HTTP_SITE_URL ?>/Home/createFamilyExpense"> Create Group - MyXpense </a>
                        </div>
                    </div>
                </div>
            </div>
            <div class="col-sm-1"></div>
        </div>

        <div class="row">
            <div class="col-sm-1"></div>
            <div class="col-sm-10">
                <?php echo $this->Session->read('system.message'); ?>
                <?php echo $this->Session->flash(); ?>
            </div>

        </div>
        <div class="row">

        <div class="col-sm-1"></div>
        <div class="col-sm-10">
            <div class="my-expenses">
                <ul class="nav nav-tabs" style="text-align: left">
                    <li class="nav-item" style="margin-left: 0 !important;">
                        <a class="nav-link active" data-toggle="tab" href="#expenses"><?php echo __("LBL_EXPENSE_GROUPS"); ?></a>
                    </li>
                    <?php if(isset($user_id) && $user_id>0){ ?>
                    <li class="nav-item" style="margin-left: 0 !important;">
                        <a class="nav-link" data-toggle="tab" href="#archived"><?php echo __("LBL_ARCHIVED_GROUPS"); ?></a>
                    </li>
                    <?php } ?>
                </ul>

                <!-- Tab content -->
                <div class="tab-content" style="margin-top: 20px;">
                    <div id="expenses" class="tab-pane fade show active">
                        <table class="table table-bordered" style="margin-top: 20px;">
                            <thead>
                            <tr>
                                <th scope="col"><div style="display: flex;align-items: center;"><div><?php echo __("LBL_TITLE"); ?></div>
                                        <?php
                                        if($this->Session->read('userData.id')){
                                            ?>
                                            <div style="margin-left: 5px;">
                                                <a href="<?php echo HTTP_SITE_URL;?>/pages/myExpenses/refresh/1"><img width="17px" height="17px" src="<?php echo CDN_URL; ?>images/refresh.png" alt=""></a>
                                            </div>
                                            <?php
                                        }
                                        ?>
                                    </div></th>
                                <th scope="col" width="200"><?php echo __("LBL_CREATED_AT"); ?></th>
                                <th scope="col" width="100" class="add-head">
                                    <?php if(isset($user_id) && $user_id>0){ ?>
                                        <a href="#" title="<?php echo __('LBL_ADD_GROUP') ?>" class="js-tooltip add-icon" data-toggle="modal" data-target="#myGroupModal">
                                            <img src="<?php echo CDN_URL; ?>images/add.png" alt=""/>
                                        </a>
                                    <?php } ?>
                                </th>
                            </tr>
                            </thead>
                            <tbody>
                            <?php
                            if (!empty($my_expenses) && isset($my_expenses)) {
                                foreach($my_expenses as $key=>$expense) { ?>
                                    <tr>
                                        <td><a id="unique_url" href="<?php echo $this->webroot.$expense['unique_url']; ?>"><?php echo $expense["title"]; ?></a>

                                            <!--<a href="javascript:;" onclick="copyFunction()">Copy Link</a>-->

                                        </td>
                                        <td><?php
                                            $s = strToTime($expense['create_date']);
                                            echo date('d M, Y', $s); ?></td>
                                        <td width="150">
                                            <button type="button" class="btn-clipboard clipboard-icon btn-copy js-tooltip js-copy" data-toggle="tooltip" data-placement="bottom" data-copy="http://<?php echo $_SERVER['HTTP_HOST'].$this->webroot.$expense['unique_url']; ?>" title="<?php echo __('LBL_COPY_EXPENSE_URL'); ?>"><img src="<?php echo CDN_URL; ?>images/clipboard.png" alt=""> </button>
                                            <a onclick="return confirm('<?php echo __("LBL_ARE_YOU_SURE"); ?>')" href="<?php echo $this->Html->url(array('controller'=>'pages','action'=>'removeGroup')).'/'.$expense['unique_url'];?>"  data-placement="bottom" title="Remove Expense" class="remove-icon js-tooltip"><img src="<?php echo CDN_URL; ?>images/delete.png" alt=""></a>
                                            <a href="#" title="Send Email" class="email-icon js-tooltip js-open-expense-modal" data-placement="bottom" data-toggle="modal" data-target="#myExpenseModal" data-unique-url="<?php echo htmlspecialchars($expense['unique_url']); ?>" data-expense-title="<?php echo htmlspecialchars($expense['title']); ?>"><img src="<?php echo CDN_URL; ?>images/email.png" alt=""></a>
                                            <?php if($this->Session->check('userData.id')){ ?>
                                                <a onclick="return confirm('<?php echo __("LBL_ARE_YOU_SURE_ARCHIVE"); ?>')" href="<?php echo $this->Html->url(array('controller'=>'pages','action'=>'archiveGroup')).'/'.$expense['unique_url'];?>"  data-placement="bottom" title="Archive Expense" class="restore-icon js-tooltip"><img src="<?php echo CDN_URL; ?>images/archive.png" alt=""></a>
                                            <?php } ?>
                                        </td>
                                    </tr>
                                <?php }
                            } else {
                                ?>
                                <tr>
                                    <td colspan="3" align="center"><?php echo __("LBL_DONT_HAVE_EXPENSE"); ?></td>
                                </tr>
                            <?php } ?>
                            </tbody>
                        </table>
                    </div>
                    <?php if(isset($user_id) && $user_id>0){ ?>
                    <div id="archived" class="tab-pane fade">

                        <table class="table table-bordered" style="margin-top: 20px;">
                            <thead>
                            <tr>
                                <th scope="col">
                                    <div style="display: flex;align-items: center;">
                                        <div><?php echo __("LBL_TITLE"); ?></div>
                                    </div>
                                </th>
                                <th scope="col" width="200"><?php echo __("LBL_CREATED_AT"); ?></th>
                                <th scope="col" width="100" class="add-head"></th>
                            </tr>
                            </thead>
                            <tbody>
                            <?php
                            if (!empty($archived_expenses) && isset($archived_expenses)) {
                                foreach($archived_expenses as $archive) { ?>
                                    <tr>
                                        <td><?php echo $archive["title"]; ?></td>
                                        <td><?php
                                            $s = strToTime($archive['create_date']);
                                            echo date('d M, Y', $s); ?></td>
                                        <td width="150" style="text-align: center;">

                                            <a onclick="return confirm('<?php echo __("LBL_ARE_YOU_SURE"); ?>')" href="<?php
                                            echo $this->Html->url([
                                                            'controller' => 'pages',
                                                            'action' => 'removeGroup',
                                                            $archive['unique_url']
                                                    ]) . '#archived';
                                            ?>"  data-placement="bottom" title="<?php echo __("TITLE_REMOVE"); ?>" class="remove-icon js-tooltip"><img src="<?php echo CDN_URL; ?>images/delete.png" alt=""></a>
                                            <?php if($this->Session->check('userData.id')){ ?>
                                                <a onclick="return confirm('<?php echo __("LBL_ARE_YOU_SURE_RESTORE"); ?>')"
                                                   href="<?php
                                                   echo $this->Html->url([
                                                                   'controller' => 'pages',
                                                                   'action' => 'restoreGroup',
                                                                   $archive['unique_url']
                                                           ]) . '#archived';
                                                   ?>"
                                                   data-placement="bottom" title="<?php echo __("TITLE_RESTORE"); ?>" class="restore-icon js-tooltip"><img src="<?php echo CDN_URL; ?>images/restore.png" alt=""></a>
                                            <?php } ?>

                                        </td>
                                    </tr>
                                <?php }
                            } else {
                                ?>
                                <tr>
                                    <td colspan="3" align="center"><?php echo __("LBL_DONT_HAVE_EXPENSE"); ?></td>
                                </tr>
                            <?php } ?>
                            </tbody>
                        </table>
                    </div>
                    <?php } ?>
                </div>

            </div>

        </div>
    </div>
    </div>
</div>

 <!-- shared email modal across all expense rows -->
<div class="modal fade" id="myExpenseModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <div class="modal-header-inner">
                    <h5 class="modal-title" id="exampleModalLabel"><?php echo __("LBL_INVITE"); ?></h5>
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                        <span aria-hidden="true">&times;</span>
                    </button>
                </div>
            </div>
            <div class="modal-body">

                <?php echo $this->Form->create(null, array('id'=> 'sendEmailForm')); ?>
                <?php echo $this->Form->hidden('unique_url', array('label'=>false, 'id'=>'uniqueUrl')); ?>
                <div class="form-group">
                    <label for="email"><?php echo __("LBL_INVITE_EMAIL_ADDRESS"); ?>:</label>

                    <?php echo $this->Form->hidden('expense_title', array('id'=>'expense_title')); ?>
                    <?php echo $this->Form->input('email', array('label'=>false,'email' => __('LBL_PLEASE_PROVIDE_EMAIL'),'length'=>'200px','required'=>'true','style'=>'width:240px; height:30px;', 'id'=>'email'));    ?>
                </div>
                <?php echo $this->Form->end('Send Email', array('class'=>'myExpenseSend'));?> <img  id="loadImg1" style="display:none;float: right" src="<?php echo CDN_URL;?>images/loading.gif" />
                <button type="button" class="btn btn-secondary modal-footer-close" data-dismiss="modal">Close</button>

            </div>

        </div>
    </div>
</div>

<div class="modal fade" id="myGroupModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <div class="modal-header-inner" style="background: #025aa5 !important;">
                    <h5 class="modal-title" id="exampleModalLabel"><?php echo __("LBL_ADD_GROUP"); ?></h5>
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                        <span aria-hidden="true">&times;</span>
                    </button>
                </div>
            </div>
            <div class="modal-body">

                <?php echo $this->Form->create(false, array('id'=> 'addGroupForm',
                    'url' => [
                        'controller' => 'pages',
                        'action' => 'addGroup'
                    ]
                ));?>

                <div class="form-group">
                    <label for="AddURL"><?php echo __("LBL_Add_URL"); ?></label>
                    <?php echo $this->Form->control('unique_url', array('label'=>false,'unique_url' =>'<?php echo __("LBL_MESSAGE_UNIQUE_URL"); ?>','required' => true,'class'=>'form-control'));    ?>
                </div>


            </div>
            <div class="modal-footer">
                <button type="submit" class="btn btn-primary" ><?php echo __("LBL_ADD_GROUP"); ?></button>
                <?php  echo $this->Form->end(); ?>
                <button type="button" class="btn btn-secondary modal-footer-close" data-dismiss="modal"><?php echo __("LBL_CLOSE"); ?></button>
            </div>

        </div>
    </div>
</div>
<script>
    $(document).ready(function () {
        // Activate tab from URL hash
        var hash = window.location.hash;
        if (hash) {
            $('.nav-link[href="' + hash + '"]').tab('show');
        }

        // Update URL when tab is clicked
        $('.nav-link').on('click', function () {
            history.replaceState(null, null, this.getAttribute('href'));
        });
    });
// Populate shared email modal with selected expense data
    $(document).on('click', '.js-open-expense-modal', function () {
        var uniqueUrl = $(this).data('unique-url');
        var expenseTitle = $(this).data('expense-title');
        $('#uniqueUrl').val(uniqueUrl);
        $('#expense_title').val(expenseTitle);
    });

    $('#sendEmailForm').submit(function(){
        document.getElementById('loadImg1').style.display='inline-block';
        $(".submit").css("float","right");

        var uniqueUrl = $("#uniqueUrl").val();
        var email = $("#email").val();
        var title = $("#expense_title").val();
        console.log(uniqueUrl);

        //document.getElementById("dvLoading").style.display = "block";
        //serialize form data
        var formData = {
            unique_url: uniqueUrl,
            email : email,
            expense_title : title
        };
        //get form action
        var formUrl = '<?php echo $this->Html->url(array("controller"=>"Expense","action"=>"sendMyExpenseEmail"));?>';
        console.log(formData);
        $.ajax({
            type: 'POST',
            url: formUrl,
            data: formData,
            success: function(data,textStatus,xhr){
                alert("Email Sent!");
                document.getElementById('loadImg1').style.display='none';
                $(".submit input[type=submit]").css("opacity","0");
            },
            error: function(xhr,textStatus,error){
                alert("Email Sending Failed!");

                document.getElementById('loadImg1').style.display='none';
            }
        });
        return false;
    });

    $(".modal-footer-close").on('click', function () {
        $(".submit input[type=submit]").css("opacity","1");
    });

    function copyToClipboard(text, el) {
        var copyTest = document.queryCommandSupported('copy');
        var elOriginalText = el.attr('data-original-title');

        if (copyTest === true) {
            var copyTextArea = document.createElement("textarea");
            copyTextArea.value = text;
            document.body.appendChild(copyTextArea);
            copyTextArea.select();
            try {
                var successful = document.execCommand('copy');
                var msg = successful ? 'Copied!' : 'Whoops, not copied!';
                el.attr('data-original-title', msg).tooltip('show');
            } catch (err) {
                console.log('Oops, unable to copy');
            }
            document.body.removeChild(copyTextArea);
            el.attr('data-original-title', elOriginalText);
        } else {
            // Fallback if browser doesn't support .execCommand('copy')
            window.prompt("Copy to clipboard: Ctrl+C or Command+C, Enter", text);
        }
    }

    $(document).ready(function() {
        window.setTimeout(function() {
                $(".alert").fadeTo(500, 0).slideUp(500, function(){
                    $(this).remove();
                });
            }, 3000);

        // Initialize
        // ---------------------------------------------------------------------

        // Tooltips
        // Requires Bootstrap 3 for functionality
        $('.js-tooltip').tooltip();

        // Copy to clipboard
        // Grab any text in the attribute 'data-copy' and pass it to the
        // copy function
        $('.js-copy').click(function() {
            var text = $(this).attr('data-copy');
            var el = $(this);
            copyToClipboard(text, el);
        });
    });

</script>

