<?php
define('VIDEOFLY_VERSION', time());

function videofly_activation_settings($theme)
{

    $first_activation = get_option('videofly_first_activation', 'yes');

    if ($first_activation === 'yes') {

        $header = '[{"settings":{"rowName":"","bgColor":"transparent","textColor":"inherit","rowMaskColor":"inherit","rowMask":"no","rowShadow":"no","bgImage":"","bgVideoMp":"","bgVideoWebm":"","bgPositionX":"left","bgPositionY":"top","bgAttachement":"fixed","bgRepeat":"repeat","bgSize":"auto","rowMarginTop":"0","rowMarginBottom":"40","rowPaddingTop":"50","rowPaddingBottom":"20","expandRow":"no","specialEffects":"none","rowTextAlign":"auto","fullscreenRow":"no","rowVerticalAlign":"top","customCss":"","rowParallax":"no","scrollDownButton":"no","borderTop":"n","borderBottom":"y","borderTopColor":"#fff","borderBottomColor":"#f6f6f6","borderTopWidth":"3","borderBottomWidth":"1","rowCarousel":"no","gradientMaskMode":"radial","rowMaskGradient":"#fff","transparent":"y","rowOpacity":1,"sliderBackground":"no"},"columns":[{"size":12,"elements":[{"type":"logo","logo-align":"text-center"},{"type":"spacer","height":20,"admin-label":""},{"type":"menu","element-style":"style1","menu-custom":"n","menu-bg-color":"#DDDDDD","menu-text-color":"#FFFFFF","menu-bg-color-hover":"#DDDDDD","menu-text-color-hover":"#FFFFFF","submenu-bg-color":"#DDDDDD","submenu-text-color":"#FFFFFF","submenu-bg-color-hover":"#DDDDDD","submenu-text-color-hover":"#FFFFFF","menu-text-align":"menu-text-align-center","admin-label":"","uppercase":"menu-uppercase","name":"39","icons":"n","description":"n","font-type":"std","font-name":"0","font-weight":"400","font-style":"normal","font-size":"15","font-demo":"Videofly"}],"settingsColumn":{"columnName":"","bgColor":"transparent","textColor":"inherit","columnMaskColor":"inherit","columnMask":"no","columnOpacity":0,"bgImage":"","bgVideoMp":"","bgVideoWebm":"","bgPosition":"auto","bgAttachement":"","bgRepeat":"","bgSize":"auto","columnPaddingTop":"0","columnPaddingRight":"0","columnPaddingLeft":"0","columnPaddingBottom":"0","gutterRight":"20","gutterLeft":"20","columnTextAlign":"auto","gradientMaskMode":"radial","maskGradient":"#fff","transparent":"y"}}]}]';

        $header = json_decode($header, true);

        $header_templates = array(
            'default' => array(
                'name' => esc_html__('Default template', 'videofly'),
                'elements' => $header
            )
        );

        update_option('videofly_header', $header);
        update_option('videofly_header_template_id', 'default');
        update_option('videofly_header_templates', $header_templates);

        $footer = '[{"settings":{"rowName":"","bgColor":"#f6f6f6","textColor":"inherit","rowMaskColor":"inherit","rowMask":"no","rowShadow":"no","bgImage":"","bgVideoMp":"","bgVideoWebm":"","bgPositionX":"left","bgPositionY":"top","bgAttachement":"fixed","bgRepeat":"repeat","bgSize":"auto","rowMarginTop":"40","rowMarginBottom":"0","rowPaddingTop":"40","rowPaddingBottom":"40","expandRow":"no","specialEffects":"none","rowTextAlign":"auto","fullscreenRow":"no","rowVerticalAlign":"top","customCss":"","rowParallax":"no","scrollDownButton":"no","borderTop":"n","borderBottom":"n","borderTopColor":"#fff","borderBottomColor":"#fff","borderTopWidth":"3","borderBottomWidth":"3","rowCarousel":"no","gradientMaskMode":"radial","rowMaskGradient":"#fff","transparent":"n","rowOpacity":1,"sliderBackground":0},"columns":[{"size":12,"elements":[{"type":"text","text":"Copyright TouchSize. All rights reserved. www.touchsize.com<\/p>","admin-label":""}],"settingsColumn":{"columnName":"","bgColor":"transparent","textColor":"inherit","columnMaskColor":"inherit","columnMask":"no","columnOpacity":0,"bgImage":"","bgVideoMp":"","bgVideoWebm":"","bgPosition":"left","bgAttachement":"fixed","bgRepeat":"repeat","bgSize":"auto","columnPaddingTop":"0","columnPaddingRight":"0","columnPaddingLeft":"0","columnPaddingBottom":"0","gutterRight":"20","gutterLeft":"20","columnTextAlign":"auto","gradientMaskMode":"radial","maskGradient":"#fff","transparent":"y"}}]}]';
        $footer = json_decode($footer, true);
        $footer_templates = array(
            'default' => array(
                'name' => esc_html__('Default template', 'videofly'),
                'elements' => $footer
            )
        );

        update_option('videofly_footer', $footer);
        update_option('videofly_footer_template_id', 'default');
        update_option('videofly_footer_templates', $footer_templates);

        update_option('videofly_first_activation', 'no');
    }
}


add_action('after_switch_theme', 'videofly_activation_settings');

function vdf_after_setup_theme()
{
    /*
     * Makes Videofly available for translation.
     *
     * Translations can be added to the /languages/ directory.
     */
    load_theme_textdomain('videofly', get_template_directory() . '/languages');

    // Enables the navigation menu ability
    add_theme_support('menus');

    // Add default posts and comments RSS feed links to head
    add_theme_support('automatic-feed-links');

    // Enables post-thumbnail support
    add_theme_support('post-thumbnails', array('video', 'post', 'page', 'portfolio', 'product', 'event', 'ts-gallery', 'ts_teams'));

    add_theme_support('post-formats', array('video', 'gallery', 'image', 'audio'));

    set_post_thumbnail_size(400, 400, TRUE);

    // additional sizes
    add_image_size('vdf_grid', 450, 300, TRUE);
    add_image_size('vdf_list', 680, 300, TRUE);
    add_image_size('vdf_thumb', 180, 110, TRUE);

    add_theme_support('title-tag');
}

add_action('after_setup_theme', 'vdf_after_setup_theme');

if (!function_exists('_wp_render_title_tag')) {

    function vdf_slug_render_title()
    {
        ?>
<title><?php wp_title('|', true, 'right'); ?></title>
<?php
    }

    add_action('wp_head', 'vdf_slug_render_title');
}

// This theme uses wp_nav_menu()
function register_videofly_menu()
{
    register_nav_menus(array(
        'primary' => esc_html__('Primary', 'videofly')
    ));
}

add_action('init', 'register_videofly_menu');

// Verify if more than one page exists
function show_posts_nav()
{
    global $wp_query;
    return ($wp_query->max_num_pages > 1);
}

/**
 * Render image gallery from attached images to post
 */
if (!function_exists('red_get_post_img_slideshow')) {
    function red_get_post_img_slideshow($post_id, $size = "grid")
    {

        /*check the meta data where the attached image ids are stored*/

        if (metadata_exists('post', $post_id, '_post_image_gallery')) {

            $product_image_gallery = get_post_meta($post_id, '_post_image_gallery', true);

            $img_id_array = array_filter(explode(',', $product_image_gallery));
        }

        if (isset($img_id_array) && is_array($img_id_array)) {
            foreach ($img_id_array as $value) {
                $attachments[$value] = $value; // create attachments array in hte format that will work for us
            }
        }
        if (isset($attachments) && count($attachments) > 0) {

            tsIncludeScripts(array('flexslider'));

            $additional_items = ''; /*in this string we will store the images that are left after loading the number of images defined in $images_to_show_first var*/
            $counter = 0; ?>
<div class="flexslider" data-animation="slider">
    <ul class="slides">
        <?php
                    foreach ($attachments as $att_id => $attachment) {
                        $full_img_url = wp_get_attachment_url($att_id);
                        $title = get_the_title($att_id);

                        $thumbnail_url = aq_resize($full_img_url, '1170', '9999', false, false); //resize img, Return an array containing url, width, and height.

                        $src = esc_url($thumbnail_url[0]);

                        ?>
        <li>
            <img src="<?php echo vdf_var_sanitize($src); ?>" data-layzr="<?php echo vdf_var_sanitize($src); ?>" alt="" data-width="<?php echo esc_attr($thumbnail_url[1]); ?>" data-height="<?php echo esc_attr($thumbnail_url[2]); ?>" />
            <?php if (vdf_overlay_effect_is_enabled()) : ?>
            <div class="dotted"></div>
            <?php endif ?>
            <a class="zoom-in-icon" href="<?php echo vdf_var_sanitize($src); ?>" rel="fancybox-[<?php echo vdf_var_sanitize($post_id); ?>]"><i class="icon-search"></i>
                <img class="hidden" src="<?php echo vdf_var_sanitize($src); ?>" alt="" />
            </a>
        </li>

        <?php } ?>
    </ul>
</div>
<?php }
    }
}

add_action('media_buttons',  'videofly_toggle_editor');

function videofly_toggle_editor()
{

    global $post, $wp_version;

    if (version_compare($wp_version, '5.0', '<=') || class_exists('Classic_Editor')) {

        $state = 'enabled';

        if (isset($post)) {

            if ($post->post_type === 'page') {

                $use_template = get_post_meta($post->ID, 'ts_use_template', true);

                if ($use_template == '') {
                    add_post_meta($post->ID, 'ts_use_template', '0', true);
                    $use_template = 0;
                }

                if ((int) $use_template === 1) {
                    $builder_status = 'enabled';
                } else {
                    $builder_status = 'disabled';
                }

                $button = '<div class="icon-blocks" id="ts-toggle-layout-builder" data-state="' . $builder_status . '">' . __('Toggle Layout Builder', 'esquise') . '</div>';
                ?>
<script id="toggle-builder-script">
    if (typeof hide_editor === 'undefined') {
        var hide_editor = function(button) {

            jQuery('#postcustom').find('input[value="ts_use_template"]').closest('td').siblings('td').find('textarea').val(1);

            jQuery('#content-tmce').hide();
            jQuery('#insert-media-button').hide();
            jQuery('#content-html').hide();
            jQuery('#wp-content-editor-container').hide();
            jQuery('#ts_layout_id').show();
            jQuery('#ts_page_options').hide();
            jQuery('#post-status-info').hide();
            jQuery('#ts-import-export').show();
            jQuery('#ts_sidebar').hide();
            button.attr('data-state', 'enabled');

        };
    }

    if (typeof show_editor === 'undefined') {
        var show_editor = function(button) {

            jQuery('#postcustom').find('input[value="ts_use_template"]').closest('td').siblings('td').find('textarea').val(0);

            jQuery('#content-tmce').show();
            jQuery('#content-html').show();
            jQuery('#wp-content-editor-container').show();
            jQuery('#post-status-info').show();
            jQuery('#ts_layout_id').hide();
            jQuery('#ts_page_options').show();
            jQuery('#ts-import-export').hide();
            jQuery('#ts_sidebar').show();
            jQuery('#insert-media-button').show();
            button.attr('data-state', 'disabled');
        };
    }

    jQuery(window).on('load', function($) {

        var builderStatus = jQuery('#ts-toggle-layout-builder').attr('data-state');

        if (builderStatus === 'enabled') {
            var button = jQuery('#ts-toggle-layout-builder');
            hide_editor(button);
            jQuery('#ts_layout_id').show();
            jQuery('#ts_page_options').hide();
            jQuery('#ts_sidebar').hide();
            jQuery('#ts-import-export').show();
        } else {
            var button = jQuery('#ts-toggle-layout-builder');
            show_editor(button);
            jQuery('#ts_layout_id').hide();
            jQuery('#ts_page_options').show();
            jQuery('#ts_sidebar').show();
            jQuery('#ts-import-export').hide();
        }

        // Toggle Layout builder
        jQuery(document).on('click', '#ts-toggle-layout-builder', function(e) {
            var button = jQuery(e.target);

            console.log(button.attr('data-state'));

            if (button.attr('data-state') == 'enabled') {
                show_editor(button);
            } else {
                hide_editor(button);
            }
        });

    });
</script>

<?php
                echo $button;
            }
        }
    }
}


/**
 * Function to add the builder button in the top bar for WP5.0+
 * @param type !function_exists('airkit_add_builder_button') 
 * @return type
 */
if (!function_exists('airkit_add_builder_button')) {

    global $wp_version;
    if (version_compare($wp_version, '5.0') >= 0 && !class_exists('Classic_Editor')) {
        add_filter('admin_footer', 'airkit_add_builder_button');
    }


    function airkit_add_builder_button()
    {
        global $post;

        if (get_post_type($post) !== 'page') return false;
        // Check if builder is being used
        $use_template = get_post_meta($post->ID, 'ts_use_template', true);

        if ($use_template == '') {
            add_post_meta($post->ID, 'ts_use_template', '0', true);
            $use_template = 0;
        }

        if ((int) $use_template === 1) {
            $builder_status = 'enabled';
        } else {
            $builder_status = 'disabled';
        }

        $buider_text = $builder_status == 'enabled' ? 'Disable Layout Builder' : 'Activate Layout Builder';

        $button = '<div class="icon-blocks airkit_builder_btn" id="ts-toggle-layout-builder" style="display: none;" data-post-id="' . esc_attr($post->ID) . '" data-state="' . esc_attr($builder_status) . '">' . esc_html($buider_text) . '</div>';

        echo $button;
    }
}

add_filter('admin_body_class', 'airkit_admin_body_classes');
function airkit_admin_body_classes($classes)
{

    global $wp_version;

    if (version_compare($wp_version, '5.0') >= 0)
        $classes .= ' wp5 ';

    return $classes;
}


if (function_exists('load_child_theme_textdomain')) {
    load_child_theme_textdomain('videofly');
}


function airkit_verify_ls()
{

    // Check if key exists in database
    $key_status = get_option('videofly_license_status');
    $key_verification = get_option('videofly_key_last_verification');

    if (empty($key_status)) {
        // Set the new verification
        update_option('videofly_key_last_verification', strtotime('+31 days', strtotime(date('Y-m-d'))));
        update_option('videofly_license_status', 'pending');
    } else {
        if ( 'valid' != get_transient( 'videofly_license_status' ) ) {
          // this code runs when there is no valid transient set
          $key = get_option('videofly_key');
          $verification = wp_safe_remote_get( 'https://touchsize.com/verify/?code=' . esc_attr($key) );
          if ( !is_wp_error($verification) && strpos( strtolower( $verification['body'] ), 'is valid' ) !== false ) {
              if ( strpos( strtolower( $verification['body'] ), 'videofly' ) !== false ) {
                  update_option('videofly_license_status', 'valid');
                  set_transient( 'videofly_license_status', 'valid', 480 * HOUR_IN_SECONDS );
              } else {
                  delete_option('videofly_key');
                  update_option('videofly_license_status', 'invalid');
              }
          }
        }
    }
}
add_action('admin_notices', 'airkit_verify_ls');
function airkit_ls_notice()
{
    $key_verification = get_option('videofly_key_last_verification');
    $ls_status = get_option('videofly_license_status');
    if ($ls_status == 'valid') return;
    ?>
<div class="notice notice-error key-notice">
    <h3><?php esc_html_e('You need to activate Videofly', 'videofly') ?></h3>
    <?php if (!airkit_verify_ls_activation()) : ?>
    <p>
        <?php echo esc_attr__('To use or keep using this product, you will have to register your license. Please make sure you add and validate your license before ', 'videofly') . '<strong>' . date('M d, Y', $key_verification) . '</strong>' . esc_html__(' or the theme options will not work after that date.'); ?>
    </p>
    <?php else : ?>
    <p>
        <?php echo esc_attr__('The period for activating the product has passed. The theme options have been deactivated.', 'videofly'); ?>
    </p>
    <?php endif; ?>
    <p>Don't know where to find your license key? <a href="https://help.touchsize.com/knowledgebase/how-to-get-your-themeforest-purchase-key/" target="_blank">Here is a tutorial</a>.</p>
    <p>
        <strong><?php esc_html_e('To activate please paste the purchase code and click save', 'videofly'); ?></strong>
        <input size="60" placeholder="ex: b32b82-432vbb2-3284v234824b23842" type="text" name="airkit-license-code" id="airkit-license-code" autocomplete="off" />
        <a href="#" id="airkit-license-saver" class="button button-primary"><?php esc_html_e('Save License Code', 'videofly'); ?></a>
    </p>
</div>
<?php
}
add_action('admin_notices', 'airkit_ls_notice');

function airkit_verify_ls_activation()
{
    $key_verification = get_option('videofly_key_last_verification');
    $key_status = get_option('videofly_license_status');
    if (strtotime(date('Y-m-d')) < $key_verification || $key_status == 'valid') {
        $out = false;
    } else {
        $out = true;
    }

    return $out;
}


function airkit_save_ls_code()
{
    $license = esc_attr(trim($_POST['license']));
    if (!empty($license)) {

        $verification = wp_remote_get('https://touchsize.com/verify/?code=' . esc_attr($license));

        if (strpos(strtolower($verification['body']), 'is valid') !== false && strpos(strtolower($verification['body']), 'videofly') !== false) {

            $status = 'success';
            $message = esc_html__('Key Saved Sucessfully', 'videofly');

            update_option('videofly_key', $license);

            // Make the confirmation
            $admin_email = get_option('admin_email');

            $response = wp_remote_post(
                'https://touchsize.com/red-area/activate.php',
                array(
                    'method' => 'POST',
                    'timeout' => 45,
                    'redirection' => 5,
                    'httpversion' => '1.0',
                    'blocking' => true,
                    'headers' => array(),
                    'body' => array('theme' => 'Videofly', 'url' => home_url(), 'license' => $license, 'email' => $admin_email),
                    'cookies' => array()
                )
            );
        } else {
            $status = 'error';
            $message = esc_html__('The key you entered is invalid or your did not copy it right.', 'videofly');
        }
    } else {
        $status = 'error';
        $message = 'There was no key entered';
    }
    $response = array('status' => $status, 'message' => $message);
    wp_send_json($response);
    die();
}

add_action('wp_ajax_airkit_save_ls_code', 'airkit_save_ls_code');

?>