<?php
    
    /*
    Plugin Name: Dynamic Catalog
    Plugin URI:
    Description: Виртуальные страницы
    Author: Dr.Yurets
    Author URI: mailto:dr.yurets@gmail.com
    Version: 0.3
    */
    
    defined('ABSPATH') or die('');
    
    include_once "installer.php";
    include_once "menus.php";
    include_once "shortcodes.php";
    include_once "settings.php";
    include_once "sitemap.php";
    include_once "schema.php";
    include_once "indexing.php";
    
    //register_activation_hook(__FILE__, 'dc_install');
    //register_deactivation_hook(__FILE__, 'dc_deactivated');
    
    /**
     * CONSTANTS Definition
     */
    global $wpdb;
    define('DC_SERVICES', $wpdb->prefix . 'services');
    define('DC_TEMPLATES', $wpdb->prefix . 'page_templates');
    define('DC_REGIONS', $wpdb->prefix . 'regions');
    define('DC_CITIES', $wpdb->prefix . 'new_cities');
    define('DC_COMPANIES', $wpdb->prefix . 'companies');
    define('DC_ADDRESSES', $wpdb->prefix . 'addresses');
    define('DC_ZIPCODES', $wpdb->prefix . 'zip_codes');
    define('DC_INDEXING', $wpdb->prefix . 'indexing');
    
    /**
     * REWRITE RULES
     */
    
    function custom_rewrite_rules()
    {
        $services = get_all_services();
        foreach ($services as $service) {
            $regions = get_regions_whitelist($service->id);
            foreach ($regions as $region) {
                add_rewrite_rule('^(' . $region->alias . ')/([^/]+)/?$', 'index.php?region=$matches[1]&city=$matches[2]', 'top'); //region/city
                add_rewrite_rule('^(' . $region->alias . ')/([^/]+)/([^/]+)/?$', 'index.php?region=$matches[1]&city=$matches[2]&company=$matches[3]', 'top'); //region/city/kvg/
            }
        }
    }
    
    function add_custom_slugs($vars)
    {
        $vars[] = 'service';
        $vars[] = 'region';
        $vars[] = 'city';
        $vars[] = 'company';
        $vars[] = 'dc_sitemap';
        
        return $vars;
    }
    
    add_filter('query_vars', 'add_custom_slugs');
    add_action('init', 'custom_rewrite_rules');
    
    
    /**
     * AJAX Calls
     */
    if (wp_doing_ajax()) {
        add_action('wp_ajax_search_zipcode', 'search_zipcode');
        add_action('wp_ajax_nopriv_search_zipcode', 'search_zipcode');
        add_action('wp_ajax_is_region_serviced', 'is_region_serviced');
        add_action('wp_ajax_nopriv_is_region_serviced', 'is_region_serviced');
        add_action('wp_ajax_generate_sitemap', 'generate_sitemap');
        
        // Google Indexing API
        add_action('wp_ajax_filter_gsc_links', 'filter_gsc_links');
    }
    function add_admin_ajax_url()
    {
        wp_localize_script('jquery', 'ajaxout',
            array(
                'url' => admin_url('admin-ajax.php')
            )
        );
    }
    
    add_action('admin_enqueue_scripts', 'add_admin_ajax_url');
    
    
    function dc_custom_admin_styles()
    {
        wp_enqueue_style('custom-styles', plugins_url('/css/admin-style.css', __FILE__));
    }
    
    add_action('admin_enqueue_scripts', 'dc_custom_admin_styles');
    
    function dc_custom_styles_scripts()
    {
        if ( ! wp_script_is('jquery', 'enqueued')) {
            wp_enqueue_script('jquery');
        }
        
        wp_localize_script('jquery', 'ajaxout',
            array(
                'url' => admin_url('admin-ajax.php')
            )
        );
        // TODO: minified versions in production
        wp_enqueue_script('pagegen_front', plugins_url('/js/dc_scripts.min.js', __FILE__), false, true);
        wp_enqueue_style('pagegen_front', plugins_url('/css/style.css', __FILE__), array(), null, 'all');
    }
    
    add_action('wp_enqueue_scripts', 'dc_custom_styles_scripts');
    
    function dc_custom_admin_js()
    {
        wp_enqueue_script('pgen-js', plugins_url('/js/dc.min.js', __FILE__), false, true);
    }
    
    add_action('admin_enqueue_scripts', 'dc_custom_admin_js');
    
    function dc_plugin_load_textdomain()
    {
        load_plugin_textdomain('dc', false, basename(dirname(__FILE__)) . '/languages');
    }
    
    add_action('plugins_loaded', 'dc_plugin_load_textdomain');
    
    function dc_admin_templates_page()
    {
        require "template.php";
        require 'includes/metabox-templates.php';
        dc_templates_page_handler();
    }
    
    function dc_templates_form_page()
    {
        require 'includes/metabox-templates.php';
        dc_templates_form_page_handler();
    }
    
    function dc_admin_services_page()
    {
        require "service.php";
        require 'includes/metabox-services.php';
        dc_services_page_handler();
    }
    
    function dc_services_form_page()
    {
        require 'includes/metabox-services.php';
        dc_services_form_page_handler();
    }
    
    function dc_admin_regions_page()
    {
        require "region.php";
        require 'includes/metabox-regions.php';
        dc_regions_page_handler();
    }
    
    function dc_regions_form_page()
    {
        require 'includes/metabox-regions.php';
        dc_regions_form_page_handler();
    }
    
    function dc_admin_cities_page()
    {
        require "city.php";
        require 'includes/metabox-cities.php';
        dc_cities_page_handler();
    }
    
    function dc_cities_form_page()
    {
        require 'includes/metabox-cities.php';
        dc_cities_form_page_handler();
    }
    
    function dc_admin_companies_page()
    {
        require "company.php";
        require 'includes/metabox-companies.php';
        dc_companies_page_handler();
    }
    
    function dc_companies_form_page()
    {
        require 'includes/metabox-companies.php';
        dc_companies_form_page_handler();
    }
    
    $plugin_options = get_option('dc_option');
    
    $inst_type = isset($plugin_options['dc_installation_type']) ? $plugin_options['dc_installation_type'] : null;
    if (isset($inst_type) && $inst_type == 1) {
        add_filter('wp_nav_menu_items', 'single_service_menu_fill', 10, 2);
    } elseif (isset($inst_type) && $inst_type == 2) {
        add_filter('wp_nav_menu_items', 'service_menu_fill', 10, 2);
    }
    
    /*
     * VIRTUAL PAGES Engine v5.0
     */
    
    add_filter('pre_handle_404', 'prepare_virtual_object');
    function prepare_virtual_object()
    {
        global $wp_query, $wpdb;
        $qry     = $wp_query->query;
        $region  = get_query_var('region', null);
        $city    = get_query_var('city', null);
        $company = get_query_var('company', null);
        $chunks  = array();
        
        if (isset($region)) {
            $chunks['region'] = $region;
        }
        if (isset($city)) {
            $chunks['city'] = $city;
        }
        if (isset($company)) {
            $chunks['company'] = $company;
        }
        
        $post_id = array(
            'ID'             => 0,
            'post_title'     => 'Default title',
            'seo_h1'         => 'Default H1',
            'post_name'      => '',
            'post_content'   => '',
            'post_excerpt'   => '',
            'post_parent'    => 0,
            'menu_order'     => 0,
            'post_type'      => 'page',
            'post_status'    => 'publish',
            'comment_status' => 'closed',
            'ping_status'    => 'closed',
            'comment_count'  => 0,
            'post_password'  => '',
            'to_ping'        => '',
            'pinged'         => '',
            'guid'           => home_url('/'),
            'post_date'      => current_time('mysql'),
            'post_date_gmt'  => current_time('mysql', 1),
            'post_author'    => is_user_logged_in() ? get_current_user_id() : 0,
            'is_virtual'     => true,
            'filter'         => 'raw'
        );
        
        if (is_front_page() || isset($qry['pagename'])) {
            return false;
        } // или главная или какая-то PAGE
        $permalink_structure = get_option('permalink_structure');
        switch ($permalink_structure) {
            case '/%postname%/':
            default:
                $permalink_structure = 1;
                break;
            case '/%category%/%postname%/':
                $permalink_structure = 2;
                break;
        }
        
        if ($permalink_structure == 1) { // site/postname, site/region/city/company
            
            if (isset($qry['name'])) { // WP rewrite rules
                $content_slug = $qry['name'];
                $service      = get_service_by_alias($content_slug);
                
                if ( ! isset($service) && ! is_object($service)) { // нет такой услуги, значит это REGION, POST или 404
                    // пробуем искать регион
                    $region         = get_region_by_alias($content_slug);
                    $parent_company = get_company_by_alias($content_slug);
                    
                    if (isset($region) && is_object($region) && ! isset($company)) { // site/REGION
                        $service = get_single_service(); // TODO: чек-сервис для мультисервиса
                        if ($region->services <> $service->id) return false; // сервис запрещен в этом регионе
                        $service = prepare_service_page($service, $post_id);
                        
                        return virtual_post_endpoint(prepare_region_page($region, $service, $post_id));
                    } elseif (isset($parent_company) && is_object($parent_company)) { // страница компании-родителя
                        $company = prepare_parent_company_page($parent_company, $post_id);
                        
                        return virtual_post_endpoint($company);
                    } else {
                        return false;
                    }
                } else { // site/SERVICE
                    
                    return virtual_post_endpoint(prepare_service_page($service, $post_id));
                }
            }
            // custom rewrite rules
            if (isset($chunks['region']) && isset($chunks['city']) && ! isset($chunks['company'])) { // site/region/CITY
                $city = get_city_object($chunks['city'], $chunks['region']);
                if (isset($city) && is_object($city)) { // CITY page
                    $service = get_single_service();
                    if ( ! is_city_serviced($city->id, $service->id)) {
                        return false; // сервис запрещен в этом городе
                    }
                    $service = prepare_service_page($service, $post_id);
                    $city    = prepare_city_page($city, $service, $post_id);
                    
                    return virtual_post_endpoint($city);
                }
                
            } elseif (isset($chunks['company'])) { // site/region/city/COMPANY
                $company = get_company_by_alias($chunks['company']);
                if ( ! is_object($company)) {
                    return false;
                } // нет такой компании
                $city      = get_city_object($chunks['city'], $chunks['region']);
                $addresses = get_addresses($company->id, $city->id);
                $service   = get_single_service();
                $service   = prepare_service_page($service, $post_id);
                
                $company = prepare_company_page($company, $addresses, $city, $service, $post_id);
                
                return virtual_post_endpoint($company);
            } else {
                return false;
            }
        } // permalink structure /category/postname END
        elseif ($permalink_structure == 2) { // site/category/postname
            /**
             * site/category_name
             * rewrite правило WP
             * категория, сервис или штат
             */
            if (isset($qry['category_name'])) {
                $content_slug = $qry['category_name'];
                
                if (get_category_by_slug($content_slug)) return false; // категория WP
                
                $service = get_service_by_alias($content_slug);
                
                if ( ! isset($service) && ! is_object($service)) { // нет такой услуги — значит это REGION, POST или 404
                    // пробуем искать регион
                    $region         = get_region_by_alias($content_slug);
                    $parent_company = get_company_by_alias($content_slug);
                    
                    if (isset($region) && is_object($region) && ! isset($company)) { // site/REGION
                        $service = get_single_service(); // TODO: чек-сервис для мультисервиса
                        if ($region->services <> $service->id) return false; // сервис запрещен в этом регионе
                        $service = prepare_service_page($service, $post_id);
                        
                        return virtual_post_endpoint(prepare_region_page($region, $service, $post_id));
                    } elseif (isset($parent_company) && is_object($parent_company)) { // страница компании-родителя
                        $company = prepare_parent_company_page($parent_company, $post_id);
                        
                        return virtual_post_endpoint($company);
                    } else {
                        return false;
                    }
                } else { // site/SERVICE
                    return virtual_post_endpoint(prepare_service_page($service, $post_id));
                }
            } /**
             * site/region/city
             * custom rewrite
             * CITY
             */
            
            elseif (isset($qry['region']) && isset($qry['city'])) { // site/region/city
                $city = get_city_object($chunks['city'], $chunks['region']);
                if (isset($city) && is_object($city)) { // CITY page
                    $service = get_single_service();
                    if ( ! is_city_serviced($city->id, $service->id)) {
                        return false; // сервис запрещен в этом городе
                    }
                    $service = prepare_service_page($service, $post_id);
                    $city    = prepare_city_page($city, $service, $post_id);
                    $city_ready_page = virtual_post_endpoint($city);
                    return $city_ready_page;
                }
            }
            
        } //permalink structure /category/postname END
        else {
            echo 'method not defined yet';
            die;
        }
        /*
        if ($installation_type == 1) {
            $service = get_single_service();
        } elseif ($installation_type == 2 && ! is_front_page()) {
            $service = get_service_by_alias(strtolower($chunks[0]));
        } else {
            $service = null;
        }*/
        
        //if (have_posts()) return false;
        
        return true;
    }
    function get_service_by_alias($service_alias)
    {
        global $wpdb;
        $services_table = DC_SERVICES;
        $service_alias  = (string)trim(esc_sql($service_alias));
        $query          = "SELECT * FROM $services_table WHERE `alias`=%s";
        
        return $wpdb->get_row($wpdb->prepare($query, $service_alias));
    }
    
    function get_regions_by_service_id($service_id)
    {
        global $wpdb;
        $regions_table = DC_REGIONS;
        $query         = "SELECT * FROM $regions_table WHERE `services`=%d";
        
        return $wpdb->get_results($wpdb->prepare($query, $service_id));
    }
    
    /**
     * @return object|null
     */
    function get_single_service()
    {
        global $wpdb;
        $services_table = DC_SERVICES;
        $query          = "SELECT * FROM $services_table";
        
        return $wpdb->get_row($query);
    }
    
    function get_service_by_id($id)
    {
        global $wpdb;
        $services_table = DC_SERVICES;
        $service_id     = (int)trim(esc_sql($id));
        $query          = "SELECT * FROM $services_table WHERE `id`=%d";
        
        return $wpdb->get_row($wpdb->prepare($query, $service_id));
    }
    
    /**
     * @return object
     */
    function get_all_services()
    {
        global $wpdb;
        $services_table = DC_SERVICES;
        $query          = "SELECT * FROM $services_table";
        
        return $wpdb->get_results($query);
    }
    
    function get_instanse_by_id($table, $imploded_ids, $as_array = null)
    {
        global $wpdb;
        $table_name = $wpdb->prefix . $table;
        $query      = "SELECT * FROM $table_name WHERE `id` IN ($imploded_ids)";
        if (isset($as_array)) return $wpdb->get_results($query, ARRAY_A);
        
        return $wpdb->get_results($query);
    }
    
    function get_region_by_alias($region_alias)
    {
        global $wpdb;
        $regions_table = DC_REGIONS;
        $region_alias  = (string)trim(esc_sql($region_alias));
        $query         = "SELECT * FROM $regions_table WHERE `alias`=%s";
        
        return $wpdb->get_row($wpdb->prepare($query, $region_alias));
    }
    
    function get_company_by_alias($alias)
    {
        global $wpdb;
        $companies_table = DC_COMPANIES;
        $query           = "SELECT * FROM $companies_table WHERE `alias`=%s";
        
        return $wpdb->get_row($wpdb->prepare($query, $alias));
    }
    
    /**
     * @return object
     */
    function get_regions()
    {
        global $wpdb;
        $regions_table = DC_REGIONS;
        $query         = "SELECT * FROM $regions_table";
        
        return $wpdb->get_results($query);
    }
    
    function get_regions_whitelist($service_id, $as_array = null)
    {
        global $wpdb;
        $regions_table = DC_REGIONS;
        $query         = "SELECT * FROM $regions_table WHERE `services` IN (%d)";
        $results       = ( ! isset($as_array)) ? $wpdb->get_results($wpdb->prepare($query, $service_id)) :
            $wpdb->get_results($wpdb->prepare($query, $service_id), ARRAY_A);
        
        return $results;
    }
    
    function get_regions_whitelist_ids($service_id, $as_comma_separated_list = null)
    {
        global $wpdb;
        $regions_table = DC_REGIONS;
        $query         = "SELECT `id` FROM $regions_table WHERE `services` IN (%d)";
        $result        = $wpdb->get_results($wpdb->prepare($query, $service_id), ARRAY_A);
        
        if (isset($as_comma_separated_list)) {
            $whitelist = array();
            foreach ($result as $region) {
                $whitelist[] = $region['id'];
            }
            $result = implode(",", $whitelist);
        }
        
        return $result;
    }
    
    function get_companies()
    {
        global $wpdb;
        $companies_table = DC_COMPANIES;
        $query           = "SELECT * FROM $companies_table";
        
        return $wpdb->get_results($query);
    }
    
    function get_template_by_id($template_id)
    {
        global $wpdb;
        $templates_table = DC_TEMPLATES;
        $query           = "SELECT * FROM $templates_table WHERE `id`=%d";
        
        return $wpdb->get_row($wpdb->prepare($query, $template_id));
    }
    
    function get_templates()
    {
        global $wpdb;
        $templates_table = DC_TEMPLATES;
        $query           = "SELECT * FROM $templates_table ORDER BY `id`";
        
        return $wpdb->get_results($query);
    }
    
    function get_city_object($city_slug, $region_slug)
    {
        global $wpdb;
        $cities_table = DC_CITIES;
        $query        = "SELECT * FROM $cities_table";
        if ($city_slug <> '') {
            $city_slug = esc_sql((string)$city_slug);
            $query     .= " WHERE `alias`='$city_slug'";
        }
        if ($region_slug <> '') {
            $region_slug = esc_sql((string)$region_slug);
            $query       .= " AND `region_alias`='$region_slug'";
        }
        $query .= " LIMIT 1";
        
        return $wpdb->get_row($query);
    }
    
    function is_city_serviced($city_id, $service_id)
    {
        global $wpdb;
        $regions_table = DC_REGIONS;
        $cities_table  = DC_CITIES;
        $query         = "SELECT `services` FROM $regions_table AS r INNER JOIN $cities_table AS c ON r.id=c.region_id WHERE c.id=%d";
        $city          = $wpdb->get_var($wpdb->prepare($query, $city_id));
        
        return $city == $service_id;
    }
    
    
    
    function virtual_post_endpoint($post)
    {
        global $wp_query;
        $virtual_post = new WP_Post((object)$post);
        
        $wp_query->post           = $virtual_post;
        $wp_query->posts          = [$virtual_post];
        $wp_query->queried_object = $virtual_post;
        $wp_query->post_count     = 1;
        $wp_query->found_post     = 1;
        $wp_query->max_num_pages  = 1;
        $wp_query->is_singular    = true;
        $wp_query->is_page        = true;
        
        //generate_custom_schema($post);
        
        return true;
    }
    
    function prepare_service_page($service, $post)
    {
        $template = get_template_by_id($service->template_id);
        
        /* Title */
        if ($service->title) {
            $title = $service->title;
        } elseif ($template->title) {
            $title = $template->title;
        } else {
            $title = $service->service_name;
        }
        
        /* H1 */
        if ($service->seo_h1) {
            $seo_h1 = $service->seo_h1;
        } elseif ($template->seo_h1) {
            $seo_h1 = $template->seo_h1;
        } else {
            $seo_h1 = $service->service_name;
        }
        
        /* Description */
        if ($service->seo_description) {
            $seo_description = $service->seo_description;
        } elseif ($template->seo_description) {
            $seo_description = $template->seo_description;
        } else {
            $seo_description = $service->service_name;
        }
        
        /* Excerpt */
        if ($service->seo_excerpt) {
            $seo_excerpt = $service->seo_excerpt;
        } elseif ($template->seo_excerpt) {
            $seo_excerpt = $template->seo_excerpt;
        } else {
            $seo_excerpt = $service->service_name;
        }
        
        /* CONTENT */
        if ($service->content) {
            $content = $service->content;
        } elseif ($template->content) {
            $content = $template->content;
        } else {
            $content = $service->service_name;
        }
        
        $post['post_title']      = $title;
        $post['seo_h1']          = $seo_h1;
        $post['seo_description'] = $seo_description;
        $post['seo_excerpt']     = $seo_excerpt;
        $post['post_name']       = $title;
        $post['post_content']    = $content;
        $post['post_excerpt']    = $seo_excerpt;
        $post['guid']            = home_url($service->alias);
        $post['v_id']            = $service->id;
        $post['alias']           = $service->alias;
        $post['service']         = $service;
        $post['post_format']     = 'service';
        
        return $post;
    }
    
    function prepare_region_page($region, $service, $post)
    {
        $template = get_template_by_id($region->template_id);
        
        /* Title */
        if ($region->title) {
            $title = $region->title;
        } elseif ($template->title) {
            $title = $template->title;
        } else {
            $title = $region->region_name;
        }
        
        /* H1 */
        if ($region->seo_h1) {
            $seo_h1 = $region->seo_h1;
        } elseif ($template->seo_h1) {
            $seo_h1 = $template->seo_h1;
        } else {
            $seo_h1 = $region->region_name;
        }
        
        /* Description */
        if ($region->seo_description) {
            $seo_description = $region->seo_description;
        } elseif ($template->seo_description) {
            $seo_description = $template->seo_description;
        } else {
            $seo_description = $region->region_name;
        }
        
        /* Excerpt */
        if ($region->seo_excerpt) {
            $seo_excerpt = $region->seo_excerpt;
        } elseif ($template->seo_excerpt) {
            $seo_excerpt = $template->seo_excerpt;
        } else {
            $seo_excerpt = $region->region_name;
        }
        
        /* CONTENT */
        if ($region->content) {
            $content = $region->content;
        } elseif ($template->content) {
            $content = $template->content;
        } else {
            $content = $region->region_name;
        }
        
        $post['post_title']      = $title;
        $post['seo_description'] = $seo_description;
        $post['seo_h1']          = $seo_h1;
        $post['post_name']       = $title;
        $post['post_content']    = $content;
        $post['post_excerpt']    = $seo_excerpt;
        $post['guid']            = home_url($region->alias);
        $post['v_id']            = $region->id;
        $post['alias']           = $region->alias;
        $post['region']          = $region;
        $post['region']->service = $service;
        $post['post_format']     = 'region';
        
        return $post;
    }
    
    function prepare_city_page($city, $service, $post)
    {
        $template = get_template_by_id($city->template_id);
        
        /* Title */
        if ($city->title) {
            $title = $city->title;
        } elseif ($template->title) {
            $title = $template->title;
        } else {
            $title = $city->city_name;
        }
        
        /* H1 */
        if ($city->seo_h1) {
            $seo_h1 = $city->seo_h1;
        } elseif ($template->seo_h1) {
            $seo_h1 = $template->seo_h1;
        } else {
            $seo_h1 = $city->city_name;
        }
        
        /* Description */
        if ($city->seo_description) {
            $seo_description = $city->seo_description;
        } elseif ($template->seo_description) {
            $seo_description = $template->seo_description;
        } else {
            $seo_description = $city->city_name;
        }
        
        /* Excerpt */
        if ($city->seo_excerpt) {
            $seo_excerpt = $city->seo_excerpt;
        } elseif ($template->seo_excerpt) {
            $seo_excerpt = $template->seo_excerpt;
        } else {
            $seo_excerpt = $city->city_name;
        }
        
        /* CONTENT */
        if ($city->content) {
            $content = $city->content;
        } elseif ($template->content) {
            $content = $template->content;
        } else {
            $content = $city->city_name;
        }
        
        $region = get_region_by_alias($city->region_alias);
        
        $post['post_title']      = $title;
        $post['seo_h1']          = $seo_h1;
        $post['seo_description'] = $seo_description;
        $post['post_name']       = $title;
        $post['post_content']    = $content;
        $post['post_excerpt']    = $seo_excerpt;
        $post['guid']            = home_url($city->alias);
        $post['v_id']            = $city->id;
        $post['region']          = $city->region;
        $post['region_alias']    = $city->region_alias;
        $post['alias']           = $city->alias;
        $post['city']            = $city;
        $post['city']->service   = $service;
        $post['city']->region    = $region;
        $post['post_format']     = 'city';
        
        return $post;
    }
    
    function prepare_company_page($company, $addresses, $city, $service, $post)
    {
        
        $template = get_template_by_id($company->template_id);
        
        /* Title */
        if ($company->title) {
            $title = $company->title;
        } elseif ($template->title) {
            $title = $template->title;
        } else {
            $title = $company->company_name;
        }
        
        /* H1 */
        if ($company->seo_h1) {
            $seo_h1 = $company->seo_h1;
        } elseif ($template->seo_h1) {
            $seo_h1 = $template->seo_h1;
        } else {
            $seo_h1 = $company->company_name;
        }
        
        /* Description */
        if ($company->seo_description) {
            $seo_description = $company->seo_description;
        } elseif ($template->seo_description) {
            $seo_description = $template->seo_description;
        } else {
            $seo_description = $company->company_name;
        }
        
        /* Excerpt */
        if ($company->seo_excerpt) {
            $seo_excerpt = $company->seo_excerpt;
        } elseif ($template->seo_excerpt) {
            $seo_excerpt = $template->seo_excerpt;
        } else {
            $seo_excerpt = $company->company_name;
        }
        
        /* CONTENT */
        if ($company->content) {
            $content = $company->content;
        } elseif ($template->content) {
            $content = $template->content;
        } else {
            $content = $company->company_name;
        }
        
        $region = get_region_by_alias($city->region_alias);
        
        $post['post_title']      = $title;
        $post['seo_h1']          = $seo_h1;
        $post['seo_description'] = $seo_description;
        $post['post_name']       = $title;
        $post['post_content']    = $content;
        $post['post_excerpt']    = $seo_excerpt;
        $post['guid']            = home_url($company->alias);
        $post['v_id']            = $company->id;
        $post['region']          = $city->region;
        $post['region_alias']    = $city->region_alias;
        $post['alias']           = $company->alias;
        $post['company']         = $company;
        $post['city']            = $city;
        $post['city']->service   = $service;
        $post['city']->region    = $region;
        $post['post_format']     = 'company';
        
        return $post;
    }
    
    function prepare_parent_company_page($company, $post)
    {
        
        $template = get_template_by_id($company->parent_template);
        
        /* Title */
        if ($company->title) {
            $title = $company->title;
        } elseif ($template->title) {
            $title = $template->title;
        } else {
            $title = $company->company_name;
        }
        
        /* H1 */
        if ($company->seo_h1) {
            $seo_h1 = $company->seo_h1;
        } elseif ($template->seo_h1) {
            $seo_h1 = $template->seo_h1;
        } else {
            $seo_h1 = $company->company_name;
        }
        
        /* Description */
        if ($company->seo_description) {
            $seo_description = $company->seo_description;
        } elseif ($template->seo_description) {
            $seo_description = $template->seo_description;
        } else {
            $seo_description = $company->company_name;
        }
        
        /* Excerpt */
        if ($company->seo_excerpt) {
            $seo_excerpt = $company->seo_excerpt;
        } elseif ($template->seo_excerpt) {
            $seo_excerpt = $template->seo_excerpt;
        } else {
            $seo_excerpt = $company->company_name;
        }
        
        /* CONTENT */
        if ($company->content) {
            $content = $company->content;
        } elseif ($template->content) {
            $content = $template->content;
        } else {
            $content = $company->company_name;
        }
        
        $post['post_title']      = $title;
        $post['seo_h1']          = $seo_h1;
        $post['seo_description'] = $seo_description;
        $post['post_name']       = $title;
        $post['post_content']    = $content;
        $post['post_excerpt']    = $seo_excerpt;
        $post['guid']            = home_url($company->alias);
        $post['v_id']            = $company->id;
        $post['alias']           = $company->alias;
        $post['company']         = $company;
        $post['post_format']     = 'parent-company';
        
        return $post;
    }
    
    function search_zipcode()
    {
        $zipcode    = (int)$_POST['zipcode'];
        $service_id = (int)$_POST['service_id'];
        if ( ! isset($zipcode) || ! isset($service_id)) {
            wp_die();
        }
        global $wpdb;
        $regions_whitelist = get_regions_whitelist_ids($service_id, true);
        $cities_table      = DC_CITIES;
        $zipcodes_table    = DC_ZIPCODES;
        
        $cities_query = "SELECT * FROM $zipcodes_table AS zips INNER JOIN $cities_table AS cities ON cities.id=zips.id WHERE zips.zip=%d AND cities.region_id IN ($regions_whitelist) ORDER BY population DESC";
        $get_res      = $wpdb->prepare($cities_query, $zipcode);
        $cities       = $wpdb->get_results($get_res, ARRAY_A);
        if (count($cities) > 0) {
            draw_zip_search_results($cities);
        } else {
            echo '<span><i class="fas fa-exclamation-triangle"></i>&nbsp;Cities not found</span>';
        }
        wp_die();
    }
    
    function is_region_serviced()
    {
        $zipcode    = (int)$_POST['zipcode'];
        $service_id = (int)$_POST['service_id'];
        if ( ! isset($zipcode) || ! isset($service_id)) {
            wp_die();
        }
        global $wpdb;
        $zip_codes_table = DC_ZIPCODES;
        $cities_table    = DC_CITIES;
        $regions_table   = DC_REGIONS;
        
        $is_serviced_region_query = "SELECT c.region_id, c.region, r.services FROM $zip_codes_table AS z
                            INNER JOIN $cities_table As c
                            ON c.id=z.id
                            INNER JOIN $regions_table AS r
                            ON r.id=c.region_id
                            WHERE z.zip=%d
                            LIMIT 0,1";
        
        $get_res        = $wpdb->prepare($is_serviced_region_query, $zipcode);
        $blocked_region = $wpdb->get_row($get_res);
        if ($blocked_region) echo json_encode($blocked_region);
        else echo 0;
        die;
    }
    
    add_action('activated_plugin', 'activation_step2');
    function activation_step2($plugin)
    {
        if ($plugin == plugin_basename(__FILE__)) {
            exit(wp_redirect(admin_url('admin.php?page=dc-catalog')));
        }
    }
    
    function get_addresses($company_id, $city_id)
    {
        global $wpdb;
        $companies_table = DC_COMPANIES;
        $cities_table    = DC_CITIES;
        $addresses_table = DC_ADDRESSES;
        
        $addresses = "SELECT a.company_id, c.company_name, c.alias AS company_alias,
                        a.address, a.phone, a.website, a.opened, a.days, a.alias,
                        ct.city_name, ct.alias AS city_alias, ct.region, ct.region_alias AS region_alias
                        FROM $addresses_table AS a INNER JOIN $companies_table AS c
                        ON a.company_id = c.id
                        INNER JOIN $cities_table AS ct
                        ON a.city_id = ct.id
                        WHERE a.city_id=%d AND c.id=%d
                        ORDER BY c.company_name";
        $get_res   = $wpdb->prepare($addresses, $city_id, $company_id);
        $addresses = $wpdb->get_results($get_res, ARRAY_A);
        
        if (count($addresses) > 0) {
            return $addresses;
        }
        
        return false;
    }