<?php
if (!defined("ABSPATH")) {
    exit;
}
add_action("admin_enqueue_scripts", "load_admin_styles");
if (!class_exists("Lokerpro_Core_Init")) {
    class Lokerpro_Core_Init
    {
        public function __construct()
        {
            define("LOKERPRO_CORE_VER", "1.0.2");
            define("LOKERPRO_CORE_DIRNAME", plugin_dir_path(__FILE__));
            define("LOKERPRO_CORE_URL", plugin_dir_url(__FILE__));
            include_once LOKERPRO_CORE_DIRNAME . "lib/apps/apps.php";
            include_once LOKERPRO_CORE_DIRNAME . "lib/blog/blog.cpt.php";
            include_once LOKERPRO_CORE_DIRNAME . "lib/shortcode.php";
            add_action("plugins_loaded", [$this, "lokerpro_core_load_textdomain"]);
        }
        public static function lokerpro_core_activate()
        {
            flush_rewrite_rules();
        }
        public static function lokerpro_core_deactivate()
        {
            flush_rewrite_rules();
        }
        public function lokerpro_core_load_textdomain()
        {
            load_plugin_textdomain("core", false, dirname(plugin_basename(__FILE__)) . "/languages");
        }
    }
}
if (class_exists("Lokerpro_Core_Init")) {
    register_activation_hook(__FILE__, ["Lokerpro_Core_Init", "lokerpro_core_activate"]);
    register_deactivation_hook(__FILE__, ["Lokerpro_Core_Init", "lokerpro_core_deactivate"]);
    $lokerpro_core_init_by_pjscom = new Lokerpro_Core_Init();
}
add_filter("admin_menu", "lokerpro_menu");
add_action("admin_init", "lokerpro_admin_init_action", 10);
add_action("wp", "lokerpro_is_active");
if (function_exists("ampforwp_is_amp_endpoint") && ampforwp_is_amp_endpoint()) {
} else {
    add_shortcode("related", "related_shortcode");
    function related_shortcode($atts)
    {
        global $post;
        $berdasarkan = $atts["berdasarkan"];
        $start = $atts["mulaipos"];
        $jml = 1;
        if ($berdasarkan == "category") {
            $categories = get_the_category($post->ID);
            $categorieIDs = [];
            if ($categories) {
                $categoriecount = count($categories);
                for ($i = 0; $i < $categoriecount; $i++) {
                    $categorieIDs[$i] = $categories[$i]->term_id;
                }
                $args = ["category__in" => $categorieIDs, "post_type" => "post", "post_status" => "publish", "offset" => $start, "post__not_in" => [$post->ID], "posts_per_page" => $jml];
            }
        } else if ($berdasarkan == "tag") {
            $tags = wp_get_post_tags($post->ID);
            $tagIDs = [];
            if ($tags) {
                $tagcount = count($tags);
                for ($i = 0; $i < $tagcount; $i++) {
                    $tagIDs[$i] = $tags[$i]->term_id;
                }
                $args = ["tag__in" => $tagIDs, "post_type" => "post", "post_status" => "publish", "offset" => $start, "post__not_in" => [$post->ID], "posts_per_page" => $jml];
            }
        } else {
            $args = ["post_type" => "post", "post_status" => "publish", "offset" => $start, "post__not_in" => [$post->ID], "posts_per_page" => $jml];
        }
        $konten = "";
        $my_query = new WP_Query($args);
        if ($my_query->have_posts()) {
            $konten .= "<div class=\"widget-content\">";
            while ($my_query->have_posts()) {
                $my_query->the_post();
                $closingdate = get_post_meta($post->ID, "LOKERPRO_ClosingDate", true);
                $date = (new DateTime($closingdate))->format("d M Y");
                if (!empty($closingdate)) {
                    $konten .= "<div class=\"related-item\">\r\n                <div class=\"related-box\">\r\n                <div class=\"related-content\">\r\n                <div class=\"related-title\">\r\n                <h3>\r\n                <a href=\"" . get_permalink() . "\">" . get_the_title() . "</a>\r\n                </h3>\r\n                <div class=\"closing-date\">\r\n                Closing Date: " . $date . "</div>\r\n                <div class=\"related-author\">\r\n                " . get_avatar(get_the_author_meta("ID"), 16) . "\r\n                <div class=\"related-author-name\">" . get_the_author() . "</div>\r\n                <img src=\"" . esc_url(get_stylesheet_directory_uri()) . "/images/badge-check-verify.png\" class=\"badge-check\" alt=\"badge-check\">\r\n                <span class=\"dot\"></span>\r\n                " . timeago() . "\r\n                </div>\r\n                </div>\r\n                </div>\r\n                <div class=\"related-image\">\r\n                " . customthumbnail($post->ID, "image_80_80") . "\r\n                </div>\r\n                </div>\r\n                </div>";
                } else {
                    $konten .= "<div class=\"related-item\">\r\n                <div class=\"related-box\">\r\n                <div class=\"related-content\">\r\n                <div class=\"related-title\">\r\n                <h3>\r\n                <a href=\"" . get_permalink() . "\">" . get_the_title() . "</a>\r\n                </h3>\r\n                <div class=\"closing-date\">\r\n                Closing Date: -</div>\r\n                <div class=\"related-author\">\r\n                " . get_avatar(get_the_author_meta("ID"), 16) . "\r\n                <div class=\"related-author-name\">" . get_the_author() . "</div>\r\n                <img src=\"" . esc_url(get_stylesheet_directory_uri()) . "/images/badge-check-verify.png\" class=\"badge-check\" alt=\"badge-check\">\r\n                <span class=\"dot\"></span>\r\n                " . timeago() . "\r\n                </div>\r\n                </div>\r\n                </div>\r\n                <div class=\"related-image\">\r\n                " . customthumbnail($post->ID, "image_80_80") . "\r\n                </div>\r\n                </div>\r\n                </div>";
                }
            }
            $konten .= "</div>";
            wp_reset_postdata();
        }
        return $konten;
    }
    function insert_related_post($content)
    {
        $posisi = explode(",", get_theme_mod("pjs_postrelated"));
        $posisi = array_filter($posisi, function ($var) {
            return $var !== "";
        });
        if (is_single() && $posisi != "") {
            $paragraphs = explode("</p>", $content);
            $new_content = "";
            $j = 0;
            for ($i = 0; $i < count($paragraphs); $i++) {
                $new_content .= $paragraphs[$i] . "</p>";
                foreach ($posisi as $posisis) {
                    if (0 < count($paragraphs) && $posisis < count($paragraphs) && $i == $posisis - 1) {
                        $new_content .= do_shortcode("[related berdasarkan='category' mulaipos=" . $j . "]");
                        $j = $j + 1;
                    }
                }
            }
            $content = $new_content;
        }
        return $content;
    }
    add_filter("the_content", "insert_related_post");
    function insert_related_post_bytag($content)
    {
        $posisi = explode(",", get_theme_mod("pjs_postrelatedbytag"));
        $posisi = array_filter($posisi, function ($var) {
            return $var !== "";
        });
        if (is_single() && $posisi != "") {
            $paragraphs = explode("</p>", $content);
            $new_content = "";
            $j = 0;
            for ($i = 0; $i < count($paragraphs); $i++) {
                $new_content .= $paragraphs[$i] . "</p>";
                foreach ($posisi as $posisis) {
                    if (0 < count($paragraphs) && $posisis < count($paragraphs) && $i == $posisis - 1) {
                        $new_content .= do_shortcode("[related berdasarkan='tag' mulaipos=" . $j . "]");
                        $j = $j + 1;
                    }
                }
            }
            $content = $new_content;
        }
        return $content;
    }
    add_filter("the_content", "insert_related_post_bytag");
}
add_action("wp_head", "customcss");
if (!function_exists("lokerpro_view_number_format")) {
    function lokerpro_view_number_format()
    {
        $n = absint(pvc_get_post_views(absint(get_the_ID())));
        $n = str_replace(",", "", $n);
        $n = (int) $n;
        $formatted = "";
        if (1000 <= $n && $n < 1000000) {
            if ($n % 1000 === 0) {
                $formatted = $n / 1000;
            } else {
                $formatted = substr($n, 0, -3) . "." . substr($n, -3, -2);
                if (substr($formatted, -1, 1) === "0") {
                    $formatted = substr($formatted, 0, -2);
                }
            }
            $formatted .= " K";
        } else if (1000000 <= $n && $n < 1000000000) {
            if ($n % 1000 === 0) {
                $formatted = $n / 1000;
            } else {
                $formatted = substr($n, 0, -6) . "." . substr($n, -6, -5);
                if (substr($formatted, -1, 1) === "0") {
                    $formatted = substr($formatted, 0, -2);
                }
            }
            $formatted .= " M";
        } else {
            $formatted = $n;
        }
        echo $formatted;
    }
}
add_action("lokerpro_view_number_format", "lokerpro_view_number_format");
class Lokerpro_License
{
    private $id = "930G0W0P7G";
    private $api;
    private $host;
    private $code = "";
    private $key;
    private $data = [];
    private static $instance;
    const SERVER = "https://member.pojoksoft.com";
    public static function instance()
    {
        if (is_null(self::$instance)) {
            self::$instance = new self();
        }
        return self::$instance;
    }
    public function __construct()
    {
        $this->api = "https://member.pojoksoft.com/wp-json/salesloo/v1/file/license";
        $protocols = ["http://", "https://", "http://www.", "https://www.", "www."];
        $this->host = str_replace($protocols, "", site_url());
        $this->key = "__lokerprolicense";
        $this->data();
    }
    public function encrypt($string)
    {
        $secret_key = AUTH_KEY;
        $secret_iv = AUTH_SALT;
        $encrypt_method = "AES-256-CBC";
        $key = hash("sha256", $secret_key);
        $iv = substr(hash("sha256", $secret_iv), 0, 16);
        return base64_encode(openssl_encrypt($string, $encrypt_method, $key, 0, $iv));
    }
    public function decrypt($string)
    {
        $secret_key = AUTH_KEY;
        $secret_iv = AUTH_SALT;
        $encrypt_method = "AES-256-CBC";
        $key = hash("sha256", $secret_key);
        $iv = substr(hash("sha256", $secret_iv), 0, 16);
        return openssl_decrypt(base64_decode($string), $encrypt_method, $key, 0, $iv);
    }
    public function data()
    {
        $option = get_option($this->key);
        if (empty($option)) {
            return $this;
        }
        $this->data = json_decode($this->decrypt($option), true);
        return $this;
    }
    public function __get($name)
    {
        $value = NULL;
        if (array_key_exists($name, (array) $this->data)) {
            $value = maybe_unserialize($this->data[$name]);
        }
        return $name == "status" ? intval($value) : $value;
    }
    private function update_option($result)
    {
        wp_cache_delete($this->key, "options");
        update_option($this->key, $this->encrypt(json_encode($result)));
    }
    public function menu()
    {
        add_menu_page(__("Lokerpro License", "lokerpro"), __("Lokerpro License", "lokerpro"), "manage_options", "lokerpro_license", [$this, "page"], "dashicons-admin-network", 1);
    }
    public function page()
    {
        echo "<div class=\"lokerpro-license-wrapper\"><form action=\"\" method=\"post\" enctype=\"multipart/form-data\" style=\"margin-top:30px\">";
        wp_nonce_field("__lokerpro_activate", "__activate");
        $readonly = "";
        $value = "";
        $this->data();
        if ($this->status == 200 && $this->purchase_code) {
            $readonly = "readonly";
            $value = substr_replace($this->purchase_code, "************************", 3, 24);
        }
        ob_start();
        echo "        <div class=\"lokerpro-field default\">\r\n            <div class=\"lokerpro-field-label\">\r\n                <label>";
        _e("Purchase Code", "lokerpro");
        echo "</label>\r\n            </div>\r\n            <div class=\"lokerpro-field-input\">\r\n                <div class=\"lokerpro-field__text\">\r\n                    <div class=\"lokerpro-field-input-box\">\r\n                        <input type=\"text\" name=\"purchase_code\" class=\"regular-text\" value=\"";
        echo $value;
        echo "\" ";
        echo $readonly;
        echo ">\r\n                        ";
        if ($this->status != 200) {
            echo "                            <input type=\"submit\" class=\"button button-primary\" name=\"action\" value=\"Activate\">\r\n                        ";
        } else {
            echo "                            <input type=\"submit\" class=\"button button-primary\" name=\"action\" value=\"Deactivate\">\r\n                        ";
        }
        echo "                    </div>\r\n                    \r\n                    <p class=\"description\">";
        echo sprintf("<a href=\"https://www.pojoksoft.com/\" target=\"__blank\">%s</a> %s", __("Click Here", "lokerpro"), __("to get purchase code"));
        echo "</p>\r\n                </div>\r\n                <p class=\"description\"></p>\r\n            </div>\r\n        </div>\r\n";
        $html = ob_get_clean();
        $status = sprintf("<span style=\"color:red\">%s</span>", "Inactive");
        $information = $this->message;
        if ($this->status == 200) {
            $status = sprintf("<span style=\"color:green\">%s</span>", "Active");
            $information .= "<br/> " . sprintf(__("Your License expired on: %s", "lokerpro"), $this->expired_at);
            $information .= "<br/>" . sprintf(__("Your license has a limit of %s and be used %s", "lokerpro"), $this->license["limit"], $this->license["used"]);
        }
        echo "<div class=\"lokerpro-field-license-status\">Your License Status : " . $status . "</div>";
        echo "<div class=\"lokerpro-field-information\">" . $information . "</div>";
        echo $html;
        echo "</form></div>";
    }
    public function on_save_action()
    {
        if (isset($_POST["__activate"]) && wp_verify_nonce($_POST["__activate"], "__lokerpro_activate")) {
            if ($_POST["action"] == "Activate") {
                $this->code = sanitize_text_field($_POST["purchase_code"]);
                $this->activate();
            } else {
                $this->code = $this->purchase_code;
                $this->deactivate();
            }
        }
    }
    private function api_response($response)
    {
        if (!is_wp_error($response)) {
            $result   = json_decode(wp_remote_retrieve_body($response), true);
            $code = intval(wp_remote_retrieve_response_code($response));
        } else {
            $result = [
                'status' => 999,
                'message' => $response->get_error_message()
            ];
        }

        return $result;
    }


    /**
     * activate 
     * 
     * activate the license
     *
     * @return mixed
     */
    private function activate()
    {
        
        $result = [
            'status'=> 200,
            'purchase_code'=>$this->code, 
            'message'=>'The license for host "'.$this->host.'" is active',
            'license' => [
                'limit' => '∞',
                'used' => '∞'
                ], 
            'expired_at'=>'Never'];

        if (isset($result['message'])) {
            add_action('admin_notices', function () use ($result) {
                echo '<div id="message" class="notice notice-success"><p><strong>' . $result['message'] . '</strong></p></div>';
            });
        }

        if (isset($result['status']) && intval($result['status']) != 999) {
            $this->update_option($result);
        }

        return true;
    }

    /**
     * delete
     * 
     * delete the license
     *
     * @return void
     */
    private function deactivate()
    {
        $result = [
            'status'=> 200,
            'message'=>'The license for host "'.$this->host.'" successful deactive',
        ];

        if (isset($result['status']) && intval($result['status']) == 200) {

            unset($result['status']);
            $this->update_option($result);
        }

        if (isset($result['message'])) {
            add_action('admin_notices', function () use ($result) {
                echo '<div id="message" class="notice notice-error"><p><strong>' . $result['message'] . '</strong></p></div>';
            });
        }

        return true;
    }

    /**
     * check
     * 
     * checking the license
     * 
     * @return void
     */
    private function check()
    {
        return true;
    }

    /**
     * periodic_check
     * 
     * on license periodic check
     *
     * @return void
     */
    public function periodic_check()
    {
        if ($this->purchase_code && $this->status == 200) {
            $this->code = $this->purchase_code;
            $this->check();
        }
    }
}
function load_admin_styles()
{
    wp_enqueue_style("admin_css", get_template_directory_uri() . "/css/admin.css", "", _LOKERPRO_VERSION);
}
function lokerpro_menu()
{
    Lokerpro_License::instance()->menu();
}
function lokerpro_admin_init_action()
{
    Lokerpro_License::instance()->on_save_action();
}
function lokerpro_is_active()
{
    if (is_admin()) {
        return NULL;
    }
    if (Lokerpro_License::instance()->status != 200) {
        wp_die(__("Please activate theme first!", "lokerpro"));
    }
}
function timeago()
{
    $code = "";
    $setDate = intval(get_the_date("Ymd"));
    $setRentang = intval($setDate) + 1;
    $setToday = intval(date("Ymd"));
    if ($setRentang < $setToday) {
        $time = get_the_date("j/m/Y");
        $code = "<time class=\"timeago\" datetime=\"" . get_the_date("c") . "\" title=\"" . $time . "\">" . $time . "</time>";
    } else {
        $dateFormat = human_time_diff(get_the_time("U"), current_time("timestamp")) . "";
        $code = "<time class=\"timeago\" datetime=\"" . get_the_date("c") . "\">" . $dateFormat . "</time>";
    }
    return $code;
}
function customthumbnail($id, $size)
{
    $code = "";
    if (has_post_thumbnail($id)) {
        $code .= get_the_post_thumbnail($id, $size);
    }
    return $code;
}
function customcss()
{
    echo "    <style type=\"text/css\" id=\"custom-theme-css\">\r\n    :root {\r\n    ";
    if (get_theme_mod("pjs_theme-color")) {
        echo "      --pjs_theme-color: ";
        echo get_theme_mod("pjs_theme-color");
        echo ";\r\n    ";
    }
    echo "    ";
    if (get_theme_mod("pjs_textparallax")) {
        echo "      --textparallax: \"";
        echo get_theme_mod("pjs_textparallax");
        echo "\";\r\n    ";
    }
    echo "    ";
    if (get_theme_mod("pjs_textparallaxbawah")) {
        echo "      --textparallaxbawah: \"";
        echo get_theme_mod("pjs_textparallaxbawah");
        echo "\";\r\n    ";
    }
    echo "    ";
    if (get_theme_mod("pjs_prlbackg")) {
        echo "      --prlbackg: \"";
        echo get_theme_mod("pjs_prlbackg");
        echo "\";\r\n    ";
    }
    echo "    ";
    if (get_theme_mod("pjs_prlbackgbox")) {
        echo "      --prlbackgbox: \"";
        echo get_theme_mod("pjs_prlbackgbox");
        echo "\";\r\n    ";
    }
    echo "    ";
    if (get_theme_mod("pjs_ontopcolor")) {
        echo "      --ontopcolor: \"";
        echo get_theme_mod("pjs_ontopcolor");
        echo "\";\r\n    ";
    }
    echo "    }\r\n    </style>\r\n";
}

?>