<?php
if(!function_exists('theme_woocommerce_enabled')) {
    function theme_woocommerce_enabled() {
        global $woocommerce;
        return $woocommerce != null;
    }
}

function getThemeVersions(){
    global $wp_version, $woocommerce;
    $wc_version = '';
    if (theme_woocommerce_enabled())
        $wc_version = $woocommerce->version;

    return array('wordpress' => $wp_version, 'woocommerce' => $wc_version);
}

function getThemeTemplates(){
    $templates = array();

    $templates['product_url'] = '';
    $query_args = array(
        'post_type'      => 'product',
        'post_status'    => 'publish',
        'posts_per_page' => 1,
        'orderby' => 'title',
        'order' => 'ASC'
    );
    $query = new WP_Query( $query_args );
    if ( $query->have_posts() ) {
        while ($query->have_posts()) : $query->the_post();
            $product_link = get_permalink();
            if (strpos($product_link, '?') > 0){
                $templates['product_url'] = substr ($product_link, strpos($product_link, '?') + 1) . '&';
            }
            break;
        endwhile;
    }

    $templates['blogpage_url'] = '';
    if ( 'page' == get_option('show_on_front') && get_option('page_for_posts') ){
        $templates['blogpage_url'] = 'page_id=' . get_option('page_for_posts') . '&';
    }

    $templates['singlepost_url'] = '';
    $all_posts = get_posts(array('order' => 'ASC'));
    if ( isset($all_posts[0])){
        $single_post = $all_posts[0];
        $templates['singlepost_url'] = 'p=' . $single_post->ID . '&';
    }

    $pages = array();
    $pages[] = 'page' == get_option('show_on_front') ? (int) get_option( 'page_on_front' ) : 0; // front page
    $pages[] = (int) get_option( 'page_for_posts' ); // page for posts
    if (theme_woocommerce_enabled()){
        $cart_page  = (int) woocommerce_get_page_id('cart');
        $templates['cart_url'] = 'p=' . $cart_page . '&';
        $pages[] = $cart_page;
        $pages[] = (int) woocommerce_get_page_id('shop'); // shop page
    }

    $templates['page_url'] = '';
    $all_pages = get_pages( array( 'sort_column' => 'ID', 'exclude' => implode(', ', $pages) ) );
    if ( isset($all_pages[0])){
        $single_page = $all_pages[0];
        $templates['page_url'] = 'page_id=' . $single_page->ID . '&';
    }

    return $templates;
}

function setThemeHashes($current_theme_path, $data = array()){
    $hashesfile = $current_theme_path . '/export/hashes.json';
    $hashes_content = file_exists($hashesfile) ? file_get_contents($hashesfile) : '';
    $hashes = json_decode($hashes_content, true);

    foreach ($data as $file => $content) {
        if ('[DELETED]' === $content) {
            if (isset($hashes[$file]))
                unset($hashes[$file]);
        } else {
            $hashes[$file] = $content;
        }
    }

    file_put_contents($hashesfile, json_encode($hashes));
}

function getThemeHashes($current_theme_path){
    $hashesfile = $current_theme_path . '/export/hashes.json';
    return json_decode(file_exists($hashesfile) ? file_get_contents($hashesfile) : '{}');
}

function setThemeCache($current_theme_path, $data = array()){
    $cachefile = $current_theme_path . '/export/cache.json';
    $cache_content = file_exists($cachefile) ? file_get_contents($cachefile) : '';
    $cache = json_decode($cache_content, true);

    if (!is_array($data))
        return;

    foreach ($data as $control => $storage) {
        if (!is_array($storage))
            continue;

        foreach ($storage as $file => $content) {
            if ('[DELETED]' === $content) {
                if (isset($cache[$control]) && isset($cache[$control][$file]))
                    unset($cache[$control][$file]);
            } else {
                $cache[$control][$file] = $content;
            }
        }
    }

    file_put_contents($cachefile, json_encode($cache));
}

function getThemeCache($current_theme_path){
    $cachefile = $current_theme_path . '/export/cache.json';
    return json_decode(file_exists($cachefile) ? file_get_contents($cachefile) : '{}');
}

function getThemeProject($current_theme_path){
    $projectfile = $current_theme_path . '/export/project.json';
    $project = file_exists($projectfile) ? json_decode(file_get_contents($projectfile), true) : array();
    if(is_array($project['project_data']['project'])) {
        $project['project_data']['project'] = json_encode($project['project_data']['project']);
    }
    return $project;
}

function setThemeProject($current_theme_path, $project){
    $projectfile = $current_theme_path . '/export/project.json';
    file_put_contents($projectfile, json_encode($project));
}

function setThemeProjectData($current_theme_path, $project_data){
    $project = getThemeProject($current_theme_path);
    $project['project_data'] = $project_data;
    setThemeProject($current_theme_path, $project);
}

function validateTemplateName($themeName) {
    if (preg_match("/^\b(?=.*[A-Za-z])[A-Za-z\d_]+\b$/", $themeName))
        return $themeName;
    return 'untitled';
}

function theme_get_preview_changed_files() {
    $base_template_dir = get_template_directory();
    $changed_files_file = $base_template_dir . '/export/preview_changed_files.json';
    if (!is_file($changed_files_file))
        return null;
    $changed_files_file_content = file_get_contents($changed_files_file);
    if (!$changed_files_file_content)
        return null;
    $changed_files = json_decode($changed_files_file_content, true);
    return $changed_files;
}

function theme_set_preview_changed_files($changed_files) {
    $base_template_dir = get_template_directory();
    $preview_template_dir = FilesHelper::normalize_path($base_template_dir . '_preview');

    $changed_files_file = $base_template_dir . '/export/preview_changed_files.json';
    $_changed_files = $changed_files;
    $changed_files = array();
    foreach($_changed_files as $path) {
        $file = FilesHelper::normalize_path($path);
        if (substr($file, 0, strlen($preview_template_dir)) == $preview_template_dir)
            $changed_files[] = substr($file, strlen($preview_template_dir));
        else
            $changed_files[] = $file;
    }
    $changed_files_file_content = json_encode(array_unique($changed_files));
    file_put_contents($changed_files_file, $changed_files_file_content);
}