<?php

if(!class_exists('ListifyLoader')) {
    class ListifyLoader
    {
        protected $plugin = null;
        protected $plugin_basename = null;
        protected $plugin_data = null;
        protected $config = null;

        public static function run($plugin)
        {
            $instance = new ListifyLoader($plugin);
            return $instance->get_activation_state() == 0;
        }

        public function __construct($plugin)
        {
            $this->plugin = $plugin;
            $this->plugin_basename = plugin_basename(trim($plugin));
            if ($this->get_activation_state() == 2) {
                return;
            } else if ($this->get_activation_state() == 1) {
                add_action('admin_init', array($this, 'activate_plugin'));
            } else {
                $config_file = dirname($plugin) . DIRECTORY_SEPARATOR . 'listify.config';
                $this->config = json_decode(file_get_contents($config_file), true);
                add_action('admin_menu', array($this, 'admin_menu'));
                add_action('activated_plugin', array($this, 'activated_plugin'));
            }
        }

        public function get_activation_state()
        {
            return get_network_option(null, 'listify-' . $this->plugin_basename, 0);
        }

        public function set_activation_state($state)
        {
            update_network_option(null, 'listify-' . $this->plugin_basename, $state);
        }

        public function get_plugin_name()
        {
            if ($this->plugin_data == null) {
                if (!function_exists('get_plugin_data')) {
                    include ABSPATH . 'wp-admin/includes/plugin.php';
                }
                $this->plugin_data = get_plugin_data($this->plugin);
            }
            return $this->plugin_data['Name'];
        }

        public function activate_plugin()
        {
            if (current_user_can('manage_options')) {
                $network_wide = false;
                $plugin = $this->plugin_basename;
                if (is_multisite()) {
                    $current = get_site_option('active_sitewide_plugins', array());
                    $network_wide = in_array($plugin, $current);
                }
                $this->set_activation_state(2);
                do_action('activate_plugin', $plugin, $network_wide);
                do_action("activate_{$plugin}", $network_wide);
                $this->redirect(admin_url());
            }
        }

        public function admin_menu()
        {
            $page = add_menu_page(
                $this->get_plugin_name(),
                $this->get_plugin_name(),
                'manage_options',
                'listify-' . $this->plugin_basename,
                array($this, 'dispatch')
            );
            if(get_site_transient('listify-' . $this->plugin_basename . '-redirect')){
                delete_site_transient('listify-' . $this->plugin_basename . '-redirect');
                $this->redirect( menu_page_url('listify-' . $this->plugin_basename, false) );
            }
        }

        public function activated_plugin($plugin)
        {
            if ($plugin === $this->plugin_basename) {
                set_site_transient('listify-' . $this->plugin_basename . '-redirect', 1);
            }
        }

        public function redirect($url){
            ?>
            <script>
            window.location.href = <?php echo json_encode($url); ?>;
            </script>
            <?php
            exit();
        }

        public function dispatch()
        {
            if ($_SERVER['REQUEST_METHOD'] === 'POST') {
                if(!array_key_exists('nothanks', $_POST)) {
                    try {
                        $fields = array(
                            'name' => stripslashes($_POST['listify-name']),
                            'email' => stripslashes($_POST['listify-email'])
                        );

                        wp_remote_post(
                            $this->config['url'],
                            array(
                                'method' => 'POST',
                                'body' => $fields,
                            )
                        );
                    } catch (Exception $e) {
                    }
                }
                $this->set_activation_state(1);
                ?>
                <script>
                    window.location = <?php echo json_encode(admin_url()); ?>;
                </script>
                <?php
            } else {
                $heading = $subheading = $signup = $footer = $nothanks = '';

                $variables = array(
                    'heading',
                    'subheading',
                    'signup',
                    'footer',
                    'nothanks'
                );

                $plugin_name = esc_html($this->get_plugin_name());

                foreach($variables as $key){
                    if(array_key_exists($key, $this->config)){
                        $value = $this->config[$key];
                        if($value === ''){
                            $$key = false;
                        }else{
                            $$key = str_replace('%plugin%', $plugin_name, $value);
                        }
                    }
                }

                ?>
                <div class="wrap">
                    <form method="post" id="activate">

                        <h1 style="text-align: center"><?php echo $heading; ?></h1>

                        <p><?php echo $subheading; ?></p>

                        <input type="text" required="required" name="listify-name" placeholder="Enter Your Name"/>
                        <input type="email" required="required" name="listify-email"
                               placeholder="Enter Your Email Address"/>
						<input type="submit" name="submit" id="submit" class="button button-primary"
                                   value="<?php echo esc_html($signup); ?>"/>

                        <?php if($nothanks): ?>
                            <input type="submit" name="nothanks" id="nothanks"
                                value="<?php echo esc_html($nothanks); ?>"/>
                        <?php endif; ?>

                    </form>

                    <?php if($footer): ?>
                        <div class="listify-footer"><?php echo $footer; ?></div>
                    <?php endif; ?>
                </div>
                <style>
                    h1#heading {
                        text-align: center;
                        margin: 50px;
                    }

                    form#activate {
                        margin: 100px auto;
                        max-width: 400px;
                        background-color: white;
                        box-shadow: 0px 0px 5px black;
                        padding: 20px;
                    }

                    form#activate input {
                        display: block;
                        width: 100%;
                    }
					form#activate {
						margin: 100px auto;
						max-width: 400px;
						background-color: white;
						box-shadow: 0px 0px 30px -20px black;
						padding: 20px;
						font-size: 200%;
						border: 1px solid black;
					}

					form#activate h1 {
						font-size: 2rem;
					}

					form#activate p {
						font-size: 1.2rem;
						margin: 2rem 0;
					}

					form#activate input {
						font-size: 1.2rem;
						text-align: center;
						margin: 5px 0;
					}

					form#activate input#submit {
						font-size: 1.5rem;
						padding: 20px;
						height: initial;
						margin: 2rem 0 0 0;
					}

                    form#activate input#nothanks {
                        background-color: transparent;
                        border: none;
                        cursor: pointer;
                        opacity: 0.5;
                        font-size: 18px;
                        margin-top: 20px;
                    }
                    form#activate input#nothanks:focus {
                        outline: none;
                    }

                    .listify-footer {
                        text-align: center;
                        background: rgba(0,0,0,0.1);
                        padding: 10px;
                    }
                </style>
                <script>
                    document.querySelector('form#activate input#nothanks')
                        .addEventListener('click', function(){
                            var inputs = document.querySelectorAll('form#activate input[required]');
                            for(var i = 0; i < inputs.length; i++){
                                inputs[i].removeAttribute('name');
                                inputs[i].removeAttribute('required');
                            }
                            return false;
                        })
                </script>
                <?php
            }
        }
    }
}