<?php
/**
 * Filename : manage.php
 * Created by: BlogProfitNetwork.Com <marcus@blogprofitnetwork.com> (https://BlogProfitNetwork.Com)
 * Copyright:2018 All Rights Reserved - BlogProfitNetwork.Com <marcus@blogprofitnetwork.com> (https://BlogProfitNetwork.Com)
 *
 * Skype    : andy_christian_loyola_
 * Hangouts : acl20032003@gmail.com
 * Email    : acl20032003@gmail.com
 */
defined('_IN_MAIN_MODULE') or die ('ACCESS DENIED');

global  $clickVoodooV4Database,
        $clickVoodooV4Helpers;

$options    = get_option($clickVoodooV4Database->tableOptions);
$urls       = $clickVoodooV4Database->getAllUrls();
?>


<div id="manage">
    <!-- holder - manage -->
    <div id="holder-manage">
        <div class="row cell">
            <h3>Manage <?php echo CLICKVOODOOV4_NAME; ?>
                <span style="float:right;">
                    <span data-role="hint" data-hint-position="left" data-hint="New <?php echo CLICKVOODOOV4_NAME; ?>">
                        <a href="javascript:void(0);" name="cmdAddNew" id="cmdAddNew" class="button button-primary">
                            <span class="icon mif-plus"></span>
                        </a>
                    </span>
                </span>
            </h3> <hr />
        </div>

        <div class="row cell">
            <table id="manage-table" class="table striped hovered">
                <thead>
                    <tr>
                        <th width="100" style="text-align:center;">ID</th>
                        <th>Name</th>
                        <th width="250" style="text-align:center;">Actions</th>
                    </tr>
                </thead>


                <?php
                if (0 != count($urls)) {
                    echo '<tbody>';
                        foreach ($urls as $url) {
                            $urlid      = $url['urlid'];
                            $tracking   = $clickVoodooV4Database->getTrackingByUrlId($urlid);

                            switch ($url['status']) {
                                case CLICKVOODOOV4_ENABLED :
                                    $color = 'fg-green';
                                    break;

                                case CLICKVOODOO_DISABLED :
                                    $color = 'fg-red';
                                    break;
                            }
                            ?>

                            <tr>
                                <td style="text-align:center;" valign="top"><?php echo $urlid; ?></td>
                                <td valign="top">
                                    <?php echo $url['name']; ?>

                                    <div id="holder-url-details-<?php echo $urlid; ?>" class="row cell text-small" style="display:none;">
                                        <hr />

                                        <table class="table striped border">
                                            <thead>
                                                <tr>
                                                    <th>Tracked Variables</th>
                                                    <th>Clicks</th>
                                                </tr>
                                            </thead>
                                            <tbody>
                                                <tr>
                                                    <td></td>
                                                    <td><?php echo $url['clicks']; ?></td>
                                                </tr>

                                                <?php if (0 != count($tracking)) {
                                                    foreach ($tracking as $track) {
                                                        echo '<tr>';
                                                            echo '<td>'. $track['value'] .'</td>';
                                                            echo '<td>'. $track['clicks'] .'</td>';
                                                        echo '</tr>';
                                                    }
                                                } ?>
                                            </tbody>
                                        </table>
                                    </div>
                                </td>
                                <td style="text-align:center;" valign="top">
                                    <div id="dialog-copy-url-codes-<?php echo $urlid; ?>" style="display:none;">
                                        <div class="bg-gray fg-white" style="padding:20px!important;">
                                            <strong>Shortened URL Preview</strong> <hr />

                                            <?php
                                            if (get_option('permalink_structure')) {
                                                echo get_bloginfo('home') .'/'. $options['url_parser'] .'/'. $url['url_value'] .'/<span id="preview-code-url-parser-'. $urlid .'"></span>';
                                            }
                                            else {
                                                echo get_bloginfo('home') .'/?'. $options['url_parser'] .'='. $url['url_value'] .'&<span id="preview-code-url-parser-'. $urlid .'"></span>';
                                            }
                                            ?>
                                        </div> <br /><br />

                                        <div class="row cell">
                                            <div class="input-control text full-size">
                                                <label for="" style="font-size:10px; font-weight:bold;">Enter variables to track. (NOTE: Slash(/) separated.)</label>
                                                <input type="text" name="code-url-parser" id="code-url-parser" rel="<?php echo $urlid; ?>" placeholder="Enter other variables to track. Slash (/) separated. (e.g. marcus/cambell)" value="" />
                                            </div>
                                        </div>
                                    </div>
                                    <a href="javascript:void(0);" name="cmdCopyUrlCodes" id="cmdCopyUrlCodes" rel="<?php echo $urlid; ?>" class="button button-secondary" title="Copy codes">
                                        <span class="icon mif-share"></span>
                                    </a>

                                    <a href="javascript:void(0);" name="cmdUrlDetails" id="cmdUrlDetails" rel="<?php echo $urlid; ?>" class="button button-secondary" title="Details">
                                        <span class="icon mif-menu"></span>
                                    </a>
                                    <span style="margin-left:10px;"></span>


                                    <a href="javascript:void(0);" name="cmdResetUrlStat" id="cmdResetUrlStat" rel="<?php echo $urlid; ?>" class="button button-secondary" title="Reset stats of <?php echo $url['name']; ?>">
                                        <span class="icon mif-loop2"></span>
                                    </a>

                                    <a href="javascript:void(0);" name="cmdUpdateUrlStatus" id="cmdUpdateUrlStatus" rel="<?php echo $urlid; ?>" class="button button-secondary" title="Update visibility of <?php echo $url['name']; ?>">
                                        <span id="status-<?php echo $urlid; ?>" class="icon mif-eye <?php echo $color; ?>"></span>
                                        <span id="dialog-status-<?php echo $urlid; ?>" class="icon mif-spinner2 mif-ani-spin" style="display:none;"></span>
                                    </a>

                                    <a href="<?php echo admin_url('admin.php?page='. CLICKVOODOOV4_CODE .'&action=update-url&id='. $urlid); ?>" class="button button-secondary" title="Update <?php echo $url['name']; ?>">
                                        <span class="icon mif-pencil"></span>
                                    </a>

                                    <a href="javascript:void(0);" name="cmdDeleteUrl" id="cmdDeleteUrl" rel="<?php echo $urlid; ?>" class="button button-secondary" title="Delete <?php echo $url['name']; ?>">
                                        <span class="icon mif-cross fg-red"></span>
                                    </a>
                                </td>
                            </tr>

                            <?php
                        }
                    echo '</tbody>';
                }
                ?>
            </table>
        </div>
    </div>
    <!-- // holder - manage -->


    <!-- holder - addnew -->
    <div id="holder-addnew" style="display:none;">
        <form name="addNewForm" id="addNewForm" method="POST" action="">

            <div class="row cell">
                <h3>Add New</h3> <hr />
            </div>

            <div class="row cells2">
                <div class="cell">
                    <div class="input-control text full-size">
                        <label for="click-name">Name <span class="text-bold fg-red">(NOTE: Reference only)</span></label>
                        <input type="text" name="click-name" id="click-name" placeholder="Enter name (reference only)" value="" />
                    </div>
                </div>
            </div>

            <div class="row cells2">
                <div class="cell">
                    <div class="input-control text full-size">
                        <label for="click-url">URL to Shorten</label>
                        <input type="text" name="click-url" id="click-url" placeholder="Enter URL to shorten" value="" />
                    </div>
                </div>

                <div class="cell">
                    <div class="row cells12">
                        <div class="cell colspan10">
                            <div class="input-control text full-size">
                                <label for="click-url-value">Shortened URL</label>
                                <input type="text" name="click-url-value" id="click-url-value" value="<?php echo $clickVoodooV4Helpers->generateRandomChars(); ?>" />
                            </div>
                        </div>
                        <div class="cell colspan2" style="margin-top:9px;">
                            <button name="cmdGenerateUrlValue" id="cmdGenerateUrlValue" class="button button-primary">
                                <span class="icon mif-spinner2"></span>
                            </button>
                        </div>
                    </div>
                </div>
            </div>

            <div class="row cell">
                <div class="bg-gray fg-white padding10">
                    <strong>URL Preview</strong> <br />

                    <?php
                    if (get_option('permalink_structure')) {
                        echo get_bloginfo('home') .'/<span id="preview-url-parser">'. $options['url_parser'] .'</span>/<span id="preview-click-url-value"></span>/';
                    }
                    else {
                        echo get_bloginfo('home') .'/?<span id="preview-url-parser">'. $options['url_parser'] .'</span>=<span id="preview-click-url-value"></span>';
                    }
                    ?>
                </div>
            </div> <br />


            <div class="row cell">
                <button name="cmdSubmitNew" id="cmdSubmitNew" class="button button-primary text-bold">
                    <span class="icon mif-pencil"></span> Submit
                </button>
                <a href="javascript:void(0);" name="cmdCancelNew" id="cmdCancelNew" class="button button-secondary fg-red text-bold">
                    <span class="icon mif-cross"></span> Cancel
                </a>

                <div id="dialog-addnew" style="margin-top:10px;"></div>
            </div>
        </form>
    </div>
    <!-- // holder - addnew -->
</div>


<script>
    (function($) {
        var $isUrlDetailsDown = false;


        $('#manage-table').dataTable({
            'bJqueryUI'         : true,
            'sPaginationType'   : 'full_numbers',
            'aaSorting'         : [[0, 'desc']]
        });


        $('#cmdAddNew').on('click', function() {
            $('#holder-manage').slideUp();
            $('#holder-addnew').slideDown();

            return false;
        });


        $('#cmdCancelNew').on('click', function() {
            $('#holder-manage').slideDown();
            $('#holder-addnew').slideUp();

            return false;
        })


        //* preview generated url value
        $('#preview-click-url-value').empty().append($('#click-url-value').val());


        //* generate url value
        $('#cmdGenerateUrlValue').on('click', function() {
            var $this   = $(this),
                $value  = $('#click-url-value'),

                $icon   = $this.children('span'),

                $data   = {
                    action  : '<?php echo CLICKVOODOOV4_CODE; ?>-generate-url-value'
                };


            $value.val('').prop('disabled', 'disabled').prop('placeholder', 'Generating value... Please wait.');
            $icon.addClass('mif-ani-spin');
            $.post('<?php echo admin_url('admin-ajax.php'); ?>', $data, function(res) {
                if (res.length <= 0) {
                    alert('There was a problem processing your request. Please try again.');
                    return false;
                }
                else {
                    $('#cmdGenerateUrlValue').children('span').removeClass('mif-ani-spin');
                    $('#click-url-value').prop('disabled', false).prop('placeholder', '').val(res);
                    $('#preview-click-url-value').empty().append($('#click-url-value').val());
                }
            });

            return false;
        });


        //* submit
        $('#addNewForm').on('submit', function(e) {
            e.preventDefault();
        });

        $('#cmdSubmitNew').on('click', function() {
            var $name   = $('#click-name'),
                $url    = $('#click-url'),
                $value  = $('#click-url-value'),

                $dialog = $('#dialog-addnew'),

                $data   = {
                    action  : '<?php echo CLICKVOODOOV4_CODE .'-add-url'; ?>',
                    name    : $name.val(),
                    url     : $url.val(),
                    value   : $value.val()
                };

            if ($name.val().length <= 0) {
                alert('Name is required.');
                return false;
            }

            if ($url.val().length <= 0) {
                alert('URL to shorten is required.');
                return false;
            }

            $dialog.empty().append('<span class="icon mif-spinner2 mif-ani-spin"></span> Processing your request... Please wait.');
            $.post('<?php echo admin_url('admin-ajax.php'); ?>', $data, function(res) {
                $dialog.empty();
                if (res == 'error') {
                    $dialog.empty().append('<span class="mif-cross fg-red"></span> There was a problem with your request. Please try again.');
                    return false;
                }
                else if (res == 'duplicate') {
                    $dialog.empty().append('<span class="mif-cross fg-red"></span> Duplicate record found. Please try again.');
                    return false;
                }
                else {
                    $dialog.empty().append('<span class="mif-checkmark fg-green"></span> Your request has been processed successfully.');

                    setTimeout(function() {
                        var current_index = $('.ui-tabs').tabs('option', 'active');
                        $('.ui-tabs').tabs('load', current_index);
                    }, 1000);
                }
            });

            return false;
        });


        //* copy url codes
        $('*[id^=cmdCopyUrlCodes]').on('click', function() {
            var $this   = $(this),
                $id     = $this.attr('rel'),

                $dialog = $('#dialog-copy-url-codes-'+ $id);

            $dialog.dialog({
                title       : 'URL Codes',
                autoOpen    : false,
                modal       : true,
                width       : 450,
                height      : 350
            }).dialog('open');
        });


        //* code url parser
        $('*[id^=code-url-parser]').on('keyup', function() {
            var $this       = $(this),
                $id         = $this.attr('rel'),
                $preview    = $('#preview-code-url-parser-'+ $id),

                $str        = '';

            <?php if (get_option('permalink_structure')) { ?>
                $str = $this.val().replace(/&/g, '/');
            <?php } else { ?>
                $str = $this.val().replace(/\//g, '&');
            <?php } ?>

            $preview.empty().append($str);
        });


        //* url details
        $('*[id^=cmdUrlDetails]').on('click', function() {
            var $this   = $(this),
                $id     = $this.attr('rel'),
                $holder = $('#holder-url-details-'+ $id);

            if ($isUrlDetailsDown == false) {
                $isUrlDetailsDown = true;

                $holder.slideDown();
            }
            else {
                $isUrlDetailsDown = false;

                $holder.slideUp();
            }
        });


        //* reset stat
        $('*[id^=cmdResetUrlStat]').on('click', function() {
            var $this   = $(this),
                $id     = $this.attr('rel'),
                $span   = $this.children('span'),

                $data   = {
                    action  : '<?php echo CLICKVOODOOV4_CODE; ?>-reset-url-stat',
                    id      : $id
                };


            $span.addClass('mif-ani-spin');
            $.post('<?php echo admin_url('admin-ajax.php'); ?>', $data, function(res) {
                $span.removeClass('mif-loop2 mif-ani-spin');

                if (res == 'error') {
                    $span.addClass('mif-cross fg-red');
                    return false;
                }
                else {
                    $span.addClass('mif-checkmark fg-green');
                    setTimeout(function() {
                        var current_index = $('.ui-tabs').tabs('option', 'active');
                        $('.ui-tabs').tabs('load', current_index);
                    }, 1000);
                }
            });
        });


        //* update status
        $('*[id^=cmdUpdateUrlStatus]').on('click', function() {
            var $this   = $(this),
                $id     = $this.attr('rel'),

                $status = $this.children('span#status-'+ $id),
                $dialog = $this.children('span#dialog-status-'+ $id),

                $data   = {
                    action  : '<?php echo CLICKVOODOOV4_CODE; ?>-update-status',
                    id      : $id
                };

            $status.hide();
            $dialog.show();
            $.post('<?php echo admin_url('admin-ajax.php'); ?>', $data, function(res) {
                if (res == 'error') {
                    $dialog.removeClass('mif-spinner mif-ani-spin').addClass('mif-warning mif-red');
                    setTimeout(function() {
                        $dialog.removeClass('mif-warning fg-red').addClass('mif-spinner2 mif-ani-spin');
                    }, 1000);

                    $status.show();
                    $dialog.hide();

                    return false;
                }
                else {
                    if ($status.hasClass('fg-green')) {
                        $status.removeClass('fg-green').addClass('fg-red');
                    }
                    else {
                        $status.removeClass('fg-red').addClass('fg-green');
                    }

                    $status.show();
                    $dialog.hide();
                }
            });
        });


        //* delete url
        $('*[id^=cmdDeleteUrl]').on('click', function() {
            var $this   = $(this),
                $id     = $this.attr('rel'),
                $span   = $this.children('span'),
                $tr     = $this.closest('tr'),

                $data   = {
                    action  : '<?php echo CLICKVOODOOV4_CODE; ?>-delete-url',
                    id      : $id
                },

                q       = confirm('Are you sure you want to delete this item?');


            if (q) {
                $span.removeClass('mif-cross').addClass('mif-spinner2 mif-ani-spin');
                $.post('<?php echo admin_url('admin-ajax.php'); ?>', $data, function(res) {
                    if (res == 'error') {
                        $span.removeClass('mif-spinner2 mif-ani-spin').addClass('mif-cross');
                        return false;
                    }
                    else {
                        $tr.slideUp();
                    }
                });
            }

            return false;
        });
    })(jQuery);
</script>