<?php

namespace ElementPress\Modules\Header_Footer;

defined('ABSPATH') || exit;

class Activator
{
    public static $instance = null;

    protected $templates;
    public $header_template;
    public $footer_template;
    public $single_template;
    public $archive_template;
    public $page_404_template;
    public $maintanencepage;
    public $search_template;
    public $blog_template;
    protected $current_theme;
    protected $current_template;

    protected $post_type = 'elementpresstemplate';

    public function __construct()
    {
        add_action('wp', array($this, 'hooks'));
    }

    public function hooks()
    {
        $this->current_template = basename(get_page_template_slug());
        if ($this->current_template == 'elementor_canvas') {
            return;
        }

        $this->current_theme = get_template();

        switch ($this->current_theme) {
            case 'astra':
                new Theme_Hooks\Theme_Support(self::template_ids());
                //new Theme_Hooks\Astra(self::template_ids());
                break;

            case 'generatepress':
            case 'generatepress-child':
                new Theme_Hooks\Theme_Support(self::template_ids());
                //new Theme_Hooks\Generatepress(self::template_ids());
                break;

            case 'oceanwp':
            case 'oceanwp-child':
                new Theme_Hooks\Theme_Support(self::template_ids());
                //new Theme_Hooks\Oceanwp(self::template_ids());
                break;

            case 'bb-theme':
            case 'bb-theme-child':
                new Theme_Hooks\Theme_Support(self::template_ids());
                // new Theme_Hooks\Bbtheme(self::template_ids());
                break;

            case 'genesis':
            case 'genesis-child':
                new Theme_Hooks\Theme_Support(self::template_ids());
                //new Theme_Hooks\Genesis(self::template_ids());
                break;

            case 'twentynineteen':
                new Theme_Hooks\Theme_Support(self::template_ids());
                break;

            case 'my-listing':
            case 'my-listing-child':
                new Theme_Hooks\MyListing(self::template_ids());
                break;

            default:
                new Theme_Hooks\Theme_Support(self::template_ids());
                break;
        }

    }

    public static function template_ids()
    {
        $cached = wp_cache_get('elementpresstemplate_ids');
        if (false !== $cached) {
            return $cached;
        }

        $instance = self::instance();
        $instance->the_filter();

        $ids = [
            $instance->header_template,
            $instance->footer_template,
            $instance->single_template,
            $instance->archive_template,
            $instance->page_404_template,
            $instance->maintanencepage,
            $instance->search_template,
            $instance->blog_template,
        ];

        wp_cache_set('elementpresstemplate_ids', $ids);
        return $ids;
    }

    protected function the_filter()
    {
        $arg = [
            'posts_per_page' => -1,
            'orderby' => 'id',
            'order' => 'DESC',
            'post_status' => 'publish',
            'post_type' => $this->post_type,
            'meta_query' => [
                [
                    'key' => 'elementpresstemplate_activation',
                    'value' => 'yes',
                    'compare' => '=',
                ],
            ],
        ];
        $this->templates = get_posts($arg);

//        echo "<pre> this->templates: " . print_r(get_the_ID(), true);


        // entire site
        if (!is_admin()) {
            $filters = [[
                'key' => 'condition_a',
                'value' => 'entire_site',
            ]];
            $this->get_header_footer($filters);
            $this->get_single($filters);
            $this->get_archive($filters);
            $this->get_page_404($filters);
            $this->get_maintenance($filters);
            $this->get_search($filters);
            $this->get_blog($filters);
        }

        // all archive
        if (is_archive() || is_home()) {
            $filters = [[
                'key' => 'condition_a',
                'value' => 'archive',
            ]];
            $this->get_header_footer($filters);
            $this->get_single($filters);
            $this->get_archive($filters);
            $this->get_page_404($filters);
            $this->get_maintenance($filters);
            $this->get_search($filters);
            $this->get_blog($filters);
        }

        // all singular
        if (is_page() || is_single() || is_404()) {
            $filters = [
                [
                    'key' => 'condition_a',
                    'value' => 'singular',
                ],
                [
                    'key' => 'condition_singular',
                    'value' => 'all',
                ]
            ];
            $this->get_header_footer($filters);
            $this->get_single($filters);
            $this->get_archive($filters);
            $this->get_page_404($filters);
            $this->get_maintenance($filters);
            $this->get_search($filters);
            $this->get_blog($filters);
        }

        // all pages, all posts, 404 page
        if (is_page()) {
            $filters = [
                [
                    'key' => 'condition_a',
                    'value' => 'singular',
                ],
                [
                    'key' => 'condition_singular',
                    'value' => 'all_pages',
                ]
            ];
            $this->get_header_footer($filters);
            $this->get_single($filters);
            $this->get_archive($filters);
            $this->get_page_404($filters);
            $this->get_maintenance($filters);
            $this->get_search($filters);
            $this->get_blog($filters);
        } elseif (is_single()) {
            $filters = [
                [
                    'key' => 'condition_a',
                    'value' => 'singular',
                ],
                [
                    'key' => 'condition_singular',
                    'value' => 'all_posts',
                ]
            ];
            $this->get_header_footer($filters);
            $this->get_single($filters);
            $this->get_archive($filters);
            $this->get_page_404($filters);
            $this->get_maintenance($filters);
            $this->get_search($filters);
            $this->get_blog($filters);
        } elseif (is_404()) {
            $filters = [
                [
                    'key' => 'condition_a',
                    'value' => 'singular',
                ],
                [
                    'key' => 'condition_singular',
                    'value' => '404page',
                ]
            ];
            $this->get_header_footer($filters);
            $this->get_single($filters);
            $this->get_archive($filters);
            $this->get_page_404($filters);
            $this->get_maintenance($filters);
            $this->get_search($filters);
            $this->get_blog($filters);
        }
        // singular selective
        if (is_page() || is_single()) {
            $filters = [
                [
                    'key' => 'condition_a',
                    'value' => 'singular',
                ],
                [
                    'key' => 'condition_singular',
                    'value' => 'selective',
                ],
                [
                    'key' => 'condition_singular_id',
                    'value' => get_the_ID(),
                ]
            ];
            $this->get_header_footer($filters);
            $this->get_single($filters);
            $this->get_archive($filters);
            $this->get_page_404($filters);
            $this->get_maintenance($filters);
            $this->get_search($filters);
            $this->get_blog($filters);
        }

        // homepage
        if (is_home()) {
            $filters = [
                [
                    'key' => 'condition_a',
                    'value' => 'singular',
                ],
                [
                    'key' => 'condition_singular',
                    'value' => 'front_page',
                ]
            ];
            $this->get_header_footer($filters);
            $this->get_single($filters);
            $this->get_archive($filters);
            $this->get_page_404($filters);
            $this->get_maintenance($filters);
            $this->get_search($filters);
            $this->get_blog($filters);
        }
    }

    protected function get_header_footer($filters)
    {

        if ($this->templates != null) {
            foreach ($this->templates as $template) {
                $template = $this->get_full_data($template);
//                echo "<pre> this->filters: " . print_r($filters, true);
                $match_found = true;
                foreach ($filters as $filter) {
                    if ($filter['key'] == 'condition_singular_id') {
                        $ids = explode(',', $template[$filter['key']]);
                        if (!in_array($filter['value'], $ids)) {
                            $match_found = false;
                        }
                    } elseif ($template[$filter['key']] != $filter['value']) {
                        $match_found = false;
                    }
                    if ($filter['key'] == 'condition_a' && $template[$filter['key']] == 'singular' && count($filters) < 2) {
                        $match_found = false;
                    }
                }

                if ($match_found == true) {
                    if ($template['type'] == 'header') {
                        $this->header_template = $template['ID'];
                    }
                    if ($template['type'] == 'footer') {
                        $this->footer_template = $template['ID'];
                    }
                }
            }
        }
    }

    protected function get_single($filters)
    {
        if ($this->templates != null) {
            foreach ($this->templates as $template) {
                $template = $this->get_full_data($template);
                $match_found = true;
                //echo 'template: <pre>'.print_r($template,true).'</pre><br>';
                foreach ($filters as $filter) {

                    if ($filter['key'] == 'condition_singular_id') {

                        $ids = explode(',', $template[$filter['key']]);
                        if (!in_array($filter['value'], $ids)) {
                            $match_found = false;
                        }
                    } elseif ($template[$filter['key']] != $filter['value']) {
                        $match_found = false;
                    }
                    if ($filter['key'] == 'condition_a' && $template[$filter['key']] == 'singular' && count($filters) < 2) {
                        $match_found = false;
                    }
                }
                if ($match_found == true) {
                    if ($template['type'] == 'single') {
                        $this->single_template = $template['ID'];
                    }
                }
            }
        }
    }

    protected function get_archive($filters)
    {
        //echo "this->templates: ".print_r($this->templates,true);
        if ($this->templates != null) {
            foreach ($this->templates as $template) {
                $template = $this->get_full_data($template);
                $match_found = true;
                //echo 'template: <pre>'.print_r($template,true).'</pre><br>';
                foreach ($filters as $filter) {
                    //echo 'filter: <pre>'.print_r($filter,true).'</pre><br>';
                    if ($filter['key'] == 'condition_singular_id') {
                        //echo 'template[$filter[key]]<pre>'.print_r($template[$filter['key']],true).'</pre><br>';
                        $ids = explode(',', $template[$filter['key']]);
                        if (!in_array($filter['value'], $ids)) {
                            $match_found = false;
                        }
                    } elseif ($template[$filter['key']] != $filter['value']) {
                        $match_found = false;
                    }
                    if ($filter['key'] == 'condition_a' && $template[$filter['key']] == 'singular' && count($filters) < 2) {
                        $match_found = false;
                    }
                }
                if ($match_found == true) {
                    if ($template['type'] == 'archive') {
                        $this->archive_template = $template['ID'];
                    }
                }
            }
        }
    }

    protected function get_page_404($filters)
    {
        //echo "this->templates: ".print_r($this->templates,true);
        if ($this->templates != null) {
            foreach ($this->templates as $template) {
                $template = $this->get_full_data($template);
                $match_found = true;
                //echo 'template: <pre>'.print_r($template,true).'</pre><br>';
                foreach ($filters as $filter) {
                    //echo 'filter: <pre>'.print_r($filter,true).'</pre><br>';
                    if ($filter['key'] == 'condition_singular_id') {
                        //echo 'template[$filter[key]]<pre>'.print_r($template[$filter['key']],true).'</pre><br>';
                        $ids = explode(',', $template[$filter['key']]);
                        if (!in_array($filter['value'], $ids)) {
                            $match_found = false;
                        }
                    } elseif ($template[$filter['key']] != $filter['value']) {
                        $match_found = false;
                    }
                    if ($filter['key'] == 'condition_a' && $template[$filter['key']] == 'singular' && count($filters) < 2) {
                        $match_found = false;
                    }
                }
                if ($match_found == true) {
                    if ($template['type'] == 'page_404') {
                        $this->page_404_template = $template['ID'];
                    }
                }
            }
        }
    }

    protected function get_maintenance($filters)
    {
        //echo "this->templates: ".print_r($this->templates,true);
        if ($this->templates != null) {
            foreach ($this->templates as $template) {
                $template = $this->get_full_data($template);
                $match_found = true;
                //echo 'template: <pre>'.print_r($template,true).'</pre><br>';
                //echo 'filters: <pre>'.print_r($filters,true).'</pre><br>';
                foreach ($filters as $filter) {
                    //echo 'filter: <pre>'.print_r($filter,true).'</pre><br>';
                    if ($filter['key'] == 'condition_singular_id') {
                        //echo 'template[$filter[key]]<pre>'.print_r($template[$filter['key']],true).'</pre><br>';
                        $ids = explode(',', $template[$filter['key']]);
                        if (!in_array($filter['value'], $ids)) {
                            $match_found = false;
                        }
                    } elseif ($template[$filter['key']] != $filter['value']) {
                        $match_found = false;
                    }
                    if ($filter['key'] == 'condition_a' && $template[$filter['key']] == 'singular' && count($filters) < 2) {
                        $match_found = false;
                    }
                }
                if ($match_found == true) {
                    if ($template['type'] == 'maintenance') {
                        $this->maintanencepage = $template['ID'];
                    }
                }
            }
        }
    }

    protected function get_search($filters)
    {
        //echo "this->templates: ".print_r($this->templates,true);
        if ($this->templates != null) {
            foreach ($this->templates as $template) {
                $template = $this->get_full_data($template);
                $match_found = true;
                //echo 'template: <pre>'.print_r($template,true).'</pre><br>';
                foreach ($filters as $filter) {
                    //echo 'filter: <pre>'.print_r($filter,true).'</pre><br>';
                    if ($filter['key'] == 'condition_singular_id') {
                        //echo 'template[$filter[key]]<pre>'.print_r($template[$filter['key']],true).'</pre><br>';
                        $ids = explode(',', $template[$filter['key']]);
                        if (!in_array($filter['value'], $ids)) {
                            $match_found = false;
                        }
                    } elseif ($template[$filter['key']] != $filter['value']) {
                        $match_found = false;
                    }
                    if ($filter['key'] == 'condition_a' && $template[$filter['key']] == 'singular' && count($filters) < 2) {
                        $match_found = false;
                    }
                }
                if ($match_found == true) {
                    if ($template['type'] == 'search') {
                        $this->search_template = $template['ID'];
                    }
                }
            }
        }
    }

    protected function get_blog($filters)
    {
        //echo "this->templates: ".print_r($this->templates,true);
        if ($this->templates != null) {
            foreach ($this->templates as $template) {
                $template = $this->get_full_data($template);
                $match_found = true;
                //echo 'template: <pre>'.print_r($template,true).'</pre><br>';
                foreach ($filters as $filter) {
                    //echo 'filter: <pre>'.print_r($filter,true).'</pre><br>';
                    if ($filter['key'] == 'condition_singular_id') {
                        //echo 'template[$filter[key]]<pre>'.print_r($template[$filter['key']],true).'</pre><br>';
                        $ids = explode(',', $template[$filter['key']]);
                        if (!in_array($filter['value'], $ids)) {
                            $match_found = false;
                        }
                    } elseif ($template[$filter['key']] != $filter['value']) {
                        $match_found = false;
                    }
                    if ($filter['key'] == 'condition_a' && $template[$filter['key']] == 'singular' && count($filters) < 2) {
                        $match_found = false;
                    }
                }
                if ($match_found == true) {
                    if ($template['type'] == 'blog') {
                        $this->blog_template = $template['ID'];
                    }
                }
            }
        }
    }

    protected function get_full_data($post)
    {
        if ($post != null) {
            return array_merge((array)$post, [
                'type' => get_post_meta($post->ID, 'elementpresstemplate_type', true),
                'condition_a' => get_post_meta($post->ID, 'elementpresstemplate_condition_a', true),
                'condition_singular' => get_post_meta($post->ID, 'elementpresstemplate_condition_singular', true),
                'condition_singular_id' => get_post_meta($post->ID, 'elementpresstemplate_condition_singular_id', true),
            ]);
        }
    }

    public static function instance()
    {
        if (is_null(self::$instance)) {
            self::$instance = new self();
        }

        return self::$instance;
    }
}