<?php

function apkt_options($option, $default = false)
{
    $value = get_option('at_' . $option, false);

    if ($value !== false) {
        return $value;
    } else {
        return ($default !== false) ? $default : '';
    }
}

function apkt_get_http_response_code($url)
{
    if (filter_var($url, FILTER_VALIDATE_URL) === false) {
        return false;
    }

    $ch = curl_init($url);

    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_NOBODY, true);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
    curl_setopt($ch, CURLOPT_TIMEOUT, 5);

    $ip = rand(0, 255) . '.' . rand(0, 255) . '.' . rand(0, 255) . '.' . rand(0, 255);

    curl_setopt($ch, CURLOPT_HTTPHEADER, array(
        "REMOTE_ADDR: $ip",
        "HTTP_X_FORWARDED_FOR: $ip",
        "User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36",
        "Referer: http://www.google.com",
    ));

    curl_exec($ch);

    $response_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);

    curl_close($ch);

    return $response_code === 200;
}

function apkt_get_parsed_category($category)
{
    $parent_category = __('Apps', 'apktemplates');

    if (!empty($category) && strpos($category, 'GAME_') !== false) {
        $parent_category = __('Games', 'apktemplates');
    }

    return $parent_category;
}

function apkt_is_valid_server_settings($value, $limit)
{
    if ($value == -1) {
        return 999999;
    }

    if (preg_match('/^(\d+)(.)$/', $value, $matches)) {
        if ($matches[2] == 'G') {
            $value = $matches[1] * 1024 * 1024 * 1024;
        } else if ($matches[2] == 'M') {
            $value = $matches[1] * 1024 * 1024;
        } else if ($matches[2] == 'K') {
            $value = $matches[1] * 1024;
        }
    }
    return ($value >= $limit * 1024 * 1024);
}

function apkt_removeslashes_deep($string)
{
    return stripslashes(str_replace('\\', '', $string));
}

function apkt_get_remote_filesize($url)
{
    static $regex = '/^Content-Length: *+\K\d++$/im';
    if (!$fp = @fopen($url, 'rb')) {
        return false;
    }
    if (
        isset($http_response_header) &&
        preg_match($regex, implode("\n", $http_response_header), $matches)
    ) {
        return (int) $matches[0];
    }
    return strlen(stream_get_contents($fp));
}

function apkt_format_bytes($get_bytes)
{
    $bytes = (int) $get_bytes;
    if ($bytes >= 1073741824) {
        $bytes = number_format($bytes / 1073741824, 2) . ' GB';
    } elseif ($bytes >= 1048576) {
        $bytes = number_format($bytes / 1048576, 2) . ' MB';
    } elseif ($bytes >= 1024) {
        $bytes = number_format($bytes / 1024, 2) . ' KB';
    } elseif ($bytes > 1) {
        $bytes = $bytes . ' Bytes';
    } elseif ($bytes == 1) {
        $bytes = $bytes . ' Bytes';
    } else {
        $bytes = '0 Bytes';
    }

    return $bytes;
}

function apkt_set_post_thumbnail_from_url($post_id, $url)
{
    $image_id = media_sideload_image($url, $post_id, null, 'id');

    if (!is_wp_error($image_id)) {
        return $image_id;
    }

    return 0;
}

function at_apt_upload_apk()
{
    $nonce = sanitize_text_field($_POST['nonce']);

    if (!wp_verify_nonce($nonce, 'aptoide_nonce')) {
        return json_encode([
            'status' => 'error',
            'data' => [
                'message' => 'Khatam! Tata! Good Bye!',
            ],
        ]);
    }

    $post_id = sanitize_text_field($_POST['post_id']);
    $apk_url = isset($_POST['apk_url']) ? $_POST['apk_url'] : null;
    $apk_version = isset($_POST['apk_version']) ? $_POST['apk_version'] : null;
    $apk_size = isset($_POST['apk_size']) ? $_POST['apk_size'] : null;

    $apk_file_data = new AT_Upload_APK($post_id, $apk_url, $apk_version, $apk_size);
    $response = $apk_file_data->upload();
    $response = json_encode($response);

    echo $response;
    exit;
}
add_action('wp_ajax_at_apt_upload_apk', 'at_apt_upload_apk');

function at_apt_get_process()
{
    $nonce = sanitize_text_field($_POST['nonce']);

    if (!wp_verify_nonce($nonce, 'aptoide_nonce')) {
        return json_encode([
            'status' => 'error',
            'data' => [
                'message' => 'Khatam! Tata! Good Bye!',
            ],
        ]);
    }

    $apk_url = isset($_POST['apk_url']) ? $_POST['apk_url'] : null;
    $apk_version = isset($_POST['apk_version']) ? $_POST['apk_version'] : null;

    $apk_file_data = new AT_Upload_APK('', $apk_url, $apk_version, '');
    $response = $apk_file_data->calculate_progress();
    $response = json_encode($response);

    echo $response;
    exit;
}
add_action('wp_ajax_at_get_process', 'at_apt_get_process');


class APKT_Aptoide
{
    private $post_id;
    private $apt_url;

    function __construct()
    {
        
    }

    private function validate_apt_url($apt_url)
    {
        if (empty($apt_url) || !strpos($apt_url, 'aptoide.com')) {
            return false;
        }

        return true;
    }

    private function validate_apt_id($apt_url)
    {
        if (preg_match('/https:\/\/([^\.]+)\.[a-z]+\.aptoide\.com\/app/', $apt_url, $matches)) {
            return true;
        }

        return false;
    }

    private function validate_url_status_code($apt_url)
    {
        return apkt_get_http_response_code($apt_url) !== false;
    }

    private function single_map_data($script_data, $mapping_values)
    {
        $mapped_data = [];
        foreach ($mapping_values as $key => $mapping) {
            if (is_array($mapping)) {
                if (isset($mapping['fun'])) {
                    $value = $this->extract_path_value($script_data, $mapping['path']);
                    $mapped_data[$key] = $mapping['fun']($value);
                } else {
                    $mapped_data[$key] = $this->extract_path_value($script_data, $mapping);
                }
            }
        }
        return $mapped_data;
    }

    private function extract_path_value($script_data, $mapping_path)
    {
        $current_data = $script_data;
        foreach ($mapping_path as $key) {
            if (isset($current_data[$key])) {
                $current_data = $current_data[$key];
            } else {
                return null;
            }
        }
        return $current_data;
    }

    private function get_apk_data($apt_url)
    {
        $response = [
            'status' => '',
            'data' => '',
        ];

        $scraper = new APKT_Scraper();
        $apt_html = $scraper->scrape($apt_url);

        $html = new simple_html_dom();
        $html->load($apt_html);

        $script_data = $html->find('script[id="__NEXT_DATA__"]', 0);

        if ($script_data) {
            $script_data = $script_data->innertext;
            $script_data = json_decode($script_data, true);
        } else {
            $response['status'] = 'error';
            $response['data'] = [
                'message' => 'Main script not found!',
            ];

            return $response;
        }

        $apk_mappings = [
            'apk_name' => ['app', 'name'],
            'apk_id' => ['app', 'package'],
            'apk_thumbnail' => ['app', 'icon'],
            'apk_banner' => ['app', 'graphic'],
            'apk_version' => ['app', 'file', 'vername'],
            'apk_category' => [
                'path' => ['groups', '0', 'parent', 'title'],
                'fun' => function ($category) {
                    if ($category === 'Applications') {
                        return 'Apps';
                    } else {
                        return $category;
                    }
                },
            ],
            'apk_sub_category' => ['groups', '0', 'title'],
            'apk_required_version' => [
                'path' => ['app', 'file', 'hardware', 'version', 'number'],
                'fun' => function ($version) {
                    $pattern = '/^(\d+(?:\.\d+)?)/';

                    preg_match($pattern, $version, $matches);

                    if (!empty($matches[1])) {
                        $required_version = $matches[1];
                    } else {
                        $required_version = $version;
                    }

                    return $required_version;
                },
            ],
            'apk_size' => ['app', 'size'],
			'apk_content_rating' => ['app', 'age', 'title'],
            'apk_price' => '0',
            'apk_developer' => ['app', 'developer', 'name'],
            'apk_rating' => ['app', 'stats', 'prating', 'avg'],
            'apk_total_votes' => ['app', 'stats', 'prating', 'total'],
            'apk_whats_new' => ['app', 'media', 'news'],
            'apk_screenshots' => [
                'path' => ['app', 'media', 'screenshots'],
                'fun' => function ($screenshots) {
                    if ($screenshots === null) {
                        return [];
                    }

                    $result = [];
                    foreach ($screenshots as $screenshot) {
                        if (isset($screenshot['url'])) {
                            $result[] = $screenshot['url'];
                        }
                    }
                    return $result;
                }
            ],
            'apk_content' => ['app', 'media', 'description'],
            'apk_description' => ['app', 'media', 'summary'],
            'apk_file_url' => ['app', 'file', 'path'],
            'apk_file_version' => ['app', 'file', 'vername'],
            'apk_file_size' => ['app', 'file', 'filesize'],
            'apt_id' => ['app', 'uname'],
        ];

        $response['status'] = 'success';
        $response['data'] = $this->single_map_data($script_data['props'], $apk_mappings);

        return $response;
    }

    private function get_search_data($apt_search_url)
    {
        $scraper = new APKT_Scraper();
        $apt_json = $scraper->scrape($apt_search_url);

        if ($apt_json) {
            $apt_data_list = json_decode($apt_json, true);
            $apt_data_list = $apt_data_list['datalist']['list'];
        } else {
            $response['status'] = 'error';
            $response['data'] = [
                'message' => 'JSON not found!',
            ];

            return $response;
        }

        $apt_search_data_list = [];

        foreach ($apt_data_list as $apt_data) {
            $apt_search_data = [
                'apk_name' => $apt_data['name'],
                'apk_id' => $apt_data['package'],
                'apk_url' => $apt_data['uname'] . '.' . 'en.aptoide.com/app',
                'apk_thumbnail' => $apt_data['icon'] . '?w=92',
                'apk_banner' => $apt_data['graphic'],
                'apk_developer' => $apt_data['developer']['name'],
                'apk_downloads' => $apt_data['stats']['pdownloads'],
                'apk_rating' => $apt_data['stats']['prating']['avg'],
            ];

            $apt_search_data_list[] = $apt_search_data;
        }

        $response['status'] = 'success';
        $response['data'] = $apt_search_data_list;

        return $response;
    }

    public function extract($apt_url, $type = '')
    {
        //$lic = new APKT_MODW();

        //if (!$lic->is_valid_license()) {
        //    $response = [
        //        'status' => 'error',
        //        'data' => [
        //            'message' => __('License Key is invalid or expired.', 'apktemplates'),
        //        ],
        //    ];

        //    return $response;
        //}

        $atp_url_validation = $this->validate_apt_url($apt_url);

        if ($atp_url_validation === false) {
            $response = [
                'status' => 'error',
                'data' => [
                    'message' => 'Please enter a valid Aptoide URL!',
                ],
            ];

            return $response;
        }

        $atp_url_response = $this->validate_url_status_code($apt_url);

        if (!$atp_url_response) {
            $response = [
                'status' => 'error',
                'data' => [
                    'message' => 'URL not available on Aptoide.',
                ],
            ];

            return $response;
        }

        if (!empty($type) && $type === 'apk') {
            $apt_id_validation = $this->validate_apt_id($apt_url);

            if (!$apt_id_validation) {
                $response = [
                    'status' => 'error',
                    'data' => [
                        'message' => 'Aptoide APK ID not found in URL!',
                    ],
                ];

                return $response;
            }

            $response = $this->get_apk_data($apt_url);

            if ($response['status'] === 'success') {
                $apk_post_creator = new AT_Create_APT_Post($response);
                $response = $apk_post_creator->create_post();

                return $response;
            } else {
                return $response;
            }

        } elseif (!empty($type) && $type === 'search') {
            return $this->get_search_data($apt_url);
        }

        $response = [
            'status' => 'error',
            'data' => [
                'message' => 'Something went wrong!',
            ],
        ];

        return $response;
    }
}

class AT_Create_APT_Post
{
    private $apt_is_advanced_options = false;

    private $apk_description;
    private $apk_whats_new;
    private $apk_name;
    private $apk_developer;
    private $apk_size;
    private $apk_version;
    private $apk_id;
    private $apk_rating;
    private $apk_votes;
    private $apk_screenshots;
    private $apk_thumbnail_url;
    private $apk_banner_url;
    private $apk_category;
    private $apk_sub_category;
    private $apk_content;
    private $apk_file_url = "";
    private $apk_file_version = "";
    private $apk_file_size = "";
    private $apt_id = "";

    private $post_id;
    private $parent_cat;
    private $child_cat;

    private $apt_post_status = 'draft';
    private $apt_post_title_start = '';
    private $apt_post_title_end = '';
    private $apt_mod_feature = '';
    private $apt_post_thumbnail_quality = 'raw';
    private $apt_import_screenshots = false;
    private $apt_import_apk_file = false;

    public function __construct($post_meta)
    {
        $default_meta = [
            'apk_description' => '',
            'apk_whats_new' => '',
            'apk_name' => '',
            'apk_developer' => '',
            'apk_size' => '',
            'apk_version' => '',
            'apk_id' => '',
            'apk_rating' => '',
            'apk_total_votes' => '',
            'apk_screenshots' => [],
            'apk_thumbnail' => '',
            'apk_banner' => '',
            'apk_category' => '',
            'apk_sub_category' => '',
            'apk_content' => '',
            'apk_file_url' => '',
            'apk_file_version' => '',
            'apk_file_size' => '',
            'apt_id' => '',
        ];

        $data = array_merge($default_meta, $post_meta['data']);

        $this->apk_description = $data['apk_description'];
        $this->apk_whats_new = $data['apk_whats_new'];
        $this->apk_name = $data['apk_name'];
        $this->apk_developer = $data['apk_developer'];
        $this->apk_size = $data['apk_size'];
        $this->apk_version = $data['apk_version'];
        $this->apk_id = $data['apk_id'];
        $this->apk_rating = $data['apk_rating'];
        $this->apk_votes = $data['apk_total_votes'];
        $this->apk_screenshots = $data['apk_screenshots'];
        $this->apk_thumbnail_url = $data['apk_thumbnail'];
        $this->apk_banner_url = $data['apk_banner'];
        $this->apk_category = $data['apk_category'];
        $this->apk_sub_category = $data['apk_sub_category'];
        $this->apk_content = $data['apk_content'];
        $this->apk_file_url = $data['apk_file_url'];
        $this->apk_file_version = $data['apk_file_version'];
        $this->apk_file_size = $data['apk_file_size'];
        $this->apt_id = $data['apt_id'];

        $this->apt_is_advanced_options = apkt_options('apt_is_advanced_options', false);

        if ($this->apt_is_advanced_options) {
            $apt_post_status = apkt_options('apt_post_status');
            $apt_post_title_start = apkt_options('apt_post_title_start');
            $apt_post_title_end = apkt_options('apt_post_title_end');
            $apt_mod_feature = apkt_options('apt_mod_feature');
            $apt_post_thumbnail_quality = apkt_options('apt_post_thumbnail_quality');
            $apt_import_screenshots = apkt_options('apt_import_screenshots', false);
            $is_get_apk = apkt_options('is_get_apk', false);

            $this->apt_post_status = !empty($apt_post_status) ? $apt_post_status : '';
            $this->apt_post_title_start = !empty($apt_post_title_start) ? $apt_post_title_start : '';
            $this->apt_post_title_end = !empty($apt_post_title_end) ? $apt_post_title_end : '';
            $this->apt_mod_feature = !empty($apt_mod_feature) ? $apt_mod_feature : '';
            $this->apt_post_thumbnail_quality = !empty($apt_post_thumbnail_quality) ? $apt_post_thumbnail_quality : '';
            $this->apt_import_screenshots = $apt_import_screenshots ? $apt_import_screenshots : false;
            $this->apt_import_apk_file = $is_get_apk ? $is_get_apk : false;
        }
    }

    private function generate_post_title()
    {
        $start_title = '';
        $end_title = '';
        $mod_feature_title = '';
        $is_mod_title = apkt_options('is_mod_title', false);
        $is_title_version = apkt_options('is_title_version', false);
        $is_mod_feature_title = apkt_options('is_mod_feature_title', false);

        if ($this->apt_is_advanced_options) {
            $start_title = (!empty($this->apt_post_title_start)) ? $this->apt_post_title_start . ' ' : '';
            $end_title = (!empty($this->apt_post_title_end)) ? $this->apt_post_title_end : '';
            $mod_feature_title = ($is_mod_feature_title && !empty($this->apt_mod_feature)) ? '(' . $this->apt_mod_feature . ') ' : '';
        }

        $main_title = $this->apk_name . ' ';

        $mod_title = ($is_mod_title) ? 'MOD APK' . ' ' : '';

        $title_version = $this->apk_version;
        $version_title = ($is_title_version && !empty($title_version)) ? 'v' . $title_version . ' ' : '';

        $post_title = $start_title . $main_title . $mod_title . $mod_feature_title . $version_title . $end_title;

        return $post_title;
    }

    private function get_category()
    {
        $categories = [
            'parent_id' => null,
            'child_id' => null,
        ];

        $parent_cat_name = $this->apk_category;
        $child_cat_name = $this->apk_sub_category;

        $parent_cat_slug = sanitize_title_with_dashes_and_no_special_chars(ex_themes_clean($parent_cat_name));
        $child_cat_slug = sanitize_title_with_dashes_and_no_special_chars(ex_themes_clean($child_cat_name));

        $parent_category = get_term_by("slug", $parent_cat_slug, "category");

        if ($parent_category) {
            $categories['parent_id'] = $parent_category->term_id;
        } else {
            $parent_id = wp_insert_term($parent_cat_name, "category", ['slug' => $parent_cat_slug]);

            if (!is_wp_error($parent_id)) {
                $categories['parent_id'] = $parent_id["term_id"];
            }
        }

        $child_category = get_term_by("slug", $child_cat_slug, "category");

        if ($child_category) {
            $categories['child_id'] = $child_category->term_id;
        } else {
            $child_id = wp_insert_term($child_cat_name, "category", ["parent" => $categories['parent_id'], "slug" => $child_cat_slug]);

            if (!is_wp_error($child_id)) {
                $categories['child_id'] = $child_id["term_id"];
            }
        }

        return $categories;
    }

    private function upload_image_to_wp($image_url, $format = 'png', $name = 'thumbnail')
    {
        if (!empty($image_url)) {
            $upload_dir = wp_upload_dir();

            $image_name = sanitize_title_with_dashes_and_no_special_chars(ex_themes_clean($this->apk_name));

            $image_full_name = "{$image_name}-{$name}." . $format;
            $image_path = $upload_dir["path"] . "/" . $image_full_name;

            $scraper = new APKT_Scraper();
            $fetch_image = $scraper->scrape($image_url);

            $existing_attachment_id = attachment_url_to_postid($upload_dir["url"] . "/" . $image_full_name);

            if ($existing_attachment_id) {
                return $existing_attachment_id;
            } else {
                file_put_contents($image_path, $fetch_image);

                $file_type = wp_check_filetype(basename($image_full_name), null);

                $image_attachment = [
                    "post_mime_type" => $file_type['type'],
                    "post_title" => $image_name,
                    "post_content" => "",
                    "post_status" => "inherit",
                ];

                $image_id = wp_insert_attachment(
                    $image_attachment,
                    $image_path
                );

                require_once ABSPATH . "wp-admin/includes/image.php";

                $image_data = wp_generate_attachment_metadata(
                    $image_id,
                    $image_path
                );

                wp_update_attachment_metadata($image_id, $image_data);

                return $image_id;
            }
        }
    }

    private function add_meta_data()
    {
        add_post_meta($this->post_id, "wp_description_GP", $this->apk_description);
        add_post_meta($this->post_id, "wp_whatnews_GP", $this->apk_whats_new);
        add_post_meta($this->post_id, "wp_title_GP", $this->apk_name);
        add_post_meta($this->post_id, "wp_version_GP", $this->apk_version);
        add_post_meta($this->post_id, "wp_developers_GP", $this->apk_developer);
        add_post_meta($this->post_id, "wp_sizes_GP", apkt_format_bytes($this->apk_size));
        add_post_meta($this->post_id, "wp_GP_ID", $this->apk_id);

        if ($this->apt_is_advanced_options && !empty($this->apt_mod_feature)) {
            add_post_meta($this->post_id, "wp_mods", $this->apt_mod_feature);
        }

        add_post_meta($this->post_id, "avg_rating", floatval($this->apk_rating));
        add_post_meta($this->post_id, "total_votes", intval($this->apk_votes));
        add_post_meta($this->post_id, "apt_id", $this->apt_id);
    }

    private function upload_thumbnail()
    {
        $image_quality = '';

        if ($this->apt_is_advanced_options) {

            if ($this->apt_post_thumbnail_quality) {
                $image_quality = '';
            }

            switch ($this->apt_post_thumbnail_quality) {
                case '512':
                    $image_quality = '?w=512';
                    break;
                case '256':
                    $image_quality = '?w=256';
                    break;
                case '128':
                    $image_quality = '?w=128';
                    break;
            };
        }

        $thumbnail_id = $this->upload_image_to_wp($this->apk_thumbnail_url . $image_quality, 'png');

        set_post_thumbnail($this->post_id, $thumbnail_id);

    }

    private function upload_banner_image()
    {
        if (!empty($this->apk_banner_url)) {
            $banner_id = $this->upload_image_to_wp($this->apk_banner_url, 'jpg', 'banner');
            $banner_image = wp_get_attachment_url($banner_id);

            add_post_meta($this->post_id, "wp_poster_GP", $banner_image);
        }
    }

    private function add_screenshots_meta()
    {
		$import_ss_limit = (int) apkt_options('import_ss_limit', '7');
        $screenshots = array();
        $get_screenshots = $this->apk_screenshots;

        if ($this->apt_is_advanced_options && $this->apt_import_screenshots) {
            for ($i = 0; $i < $import_ss_limit; $i++) {
                if (!empty($get_screenshots[$i])) {
                    $ss_name = 'screenshot-' . ($i + 1);
                    $ss_id = $this->upload_image_to_wp(esc_url($get_screenshots[$i]), 'png', $ss_name);
                    $screenshots[$i]["ss_url"] = esc_url(wp_get_attachment_url($ss_id));
                }
            }
        } else {
            for ($i = 0; $i < $import_ss_limit; $i++) {
                if (!empty($get_screenshots[$i])) {
                    $screenshots[$i]["ss_url"] = esc_url($get_screenshots[$i]);
                }
            }
        }

        add_post_meta($this->post_id, "ss_images", $screenshots);
    }

    private function is_apk_file_exist($apk_url, $apk_version)
    {
        $upload_dir = wp_upload_dir();
        $file_base_name = basename($apk_url);

        $pattern = '/^(.*?)-\d+/';

        preg_match($pattern, $file_base_name, $matches);

        if (!empty($matches[1])) {
            $file_name = $matches[1] . '-' . str_replace('.', '-', $apk_version);
        } else {
            $file_name = pathinfo($file_base_name, PATHINFO_FILENAME);
        }

        $file_extension = pathinfo($apk_url, PATHINFO_EXTENSION);
        $file_full_name = $file_name . '.' . $file_extension;
        $file_url = $upload_dir["apk_path_url"] . '/' . $file_full_name;
        $existing_attachment_id = attachment_url_to_postid($file_url);
        return $existing_attachment_id;
        if ($existing_attachment_id) {
            return true;
        } else {
            return $existing_attachment_id;
        }

    }

    public function create_post()
    {
        //$lic = new APKT_MODW();

        //if (!$lic->is_valid_license()) {
        //    $response = [
        //        'status' => 'error',
        //        'data' => [
        //            'message' => __('License Key is invalid or expired.', 'apktemplates'),
        //        ],
        //    ];

        //    return $response;
        //}

        $post_permalink = sanitize_title_with_dashes_and_no_special_chars(ex_themes_clean($this->apk_name));

        $category = $this->get_category();
		$post_content = wp_encode_emoji($this->apk_content);

        $new_post = [
            "post_title" => $this->generate_post_title(),
            "post_name" => $post_permalink,
            "post_content" => $post_content,
            "post_status" => $this->apt_post_status,
            "post_category" => [$category['parent_id'], $category['child_id']],
            "post_type" => "post",
        ];

        $post_id = wp_insert_post($new_post);

        $this->post_id = $post_id;

        $this->add_meta_data();

        $this->upload_thumbnail();

        $this->upload_banner_image();

        $this->add_screenshots_meta();

        $response = [
            'status' => 'success',
            'data' => [
                'message' => '<strong><a href="' . get_edit_post_link($this->post_id) . '" target="_blank">' . $this->apk_name . '</a></strong> post uploaded.',
            ],
        ];

        if ($this->apt_is_advanced_options && $this->apt_import_apk_file) {
            $response['data']['get_apk'] = true;
            $response['data']['is_apk_exist'] = false;
            $response['data']['file_check'] = $this->is_apk_file_exist($this->apk_file_url, $this->apk_file_version);
            if (isset($this->apk_file_url)) {
                $response['data']['has_apk_file'] = true;
                $response['data']['apk_file_url'] = $this->apk_file_url;
                $response['data']['apk_file_version'] = $this->apk_file_version;
                $response['data']['apk_file_size'] = $this->apk_file_size;
                $response['data']['post_id'] = $this->post_id;
            } else {
                $response['data']['has_apk_file'] = false;
            }
        }

        return $response;
    }
}


function apkt_apt_importer()
{
    $apt_is_advanced_options = apkt_options('apt_is_advanced_options', false);
    $apt_post_status = apkt_options('apt_post_status', 'draft');
    $apt_post_title_start = apkt_options('apt_post_title_start');
    $apt_post_title_end = apkt_options('apt_post_title_end');
    $apt_mod_feature = apkt_options('apt_mod_feature');
    $apt_post_thumbnail_quality = apkt_options('apt_post_thumbnail_quality', '512');
    $apt_import_screenshots = apkt_options('apt_import_screenshots', false);
    $is_get_apk = apkt_options('is_get_apk', false);
?>
    <div id="at-importer">
        <div class="at-importer-container">
            <form method="POST" id="at-apt-importer-form">
                <div class="at-importer at-mb-3">
                    <h2>Aptoide Importer</h2>
                    <div class="at-inline-ipt at-mt-2">
                        <input type="url" name="at_apt_url" id="at-apt-url" class="at-ipt-url" min="3" placeholder="https://clash-of-clans.en.aptoide.com/app" required />
                        <button type="submit" class="at-btn at-btn-orange">Import Content</button>
                    </div>
                </div>
                <div class="at-importer-results at-mb-3" style="display: none">
                    <h3 class="at-mb-1"><?php echo esc_html('Log', 'apktemplates'); ?></h3>
                    <ul class="process-log at-mb-1" style="display: none"></ul>
                    <ul class="process-error-log" style="display: none"></ul>
                </div>
                <div class="at-importer-advance at-mb-3 ">
                    <div class="at-inline-container">
                        <h2>Advanced Options</h2>
                        <div>
                            <label class="at-switch-btn">
                                <input type="checkbox" name="at_apt_advanced_options" id="at_apt_advanced_options" <?php checked($apt_is_advanced_options); ?>>
                                <span class="at-switch at-apt-switch"></span>
                            </label>
                        </div>
                    </div>
                    <table class="at-import-table at-mt-2" <?php if (!$apt_is_advanced_options) echo 'style="display: none"'; ?>>
                        <tbody>
                            <tr style="grid-template-columns: 1fr">
                                <td>
                                    <p>
                                        <code><strong>Note: </strong> If you enabled advanced options,
                                            it will take some extra time to import content. Because of
                                            import screenshots to your server and import apk files to
                                            the selected server.
                                        </code>
                                    </p>
                                </td>
                            </tr>
                            <tr>
                                <td>
                                    <h3><?php esc_html_e('Post status', 'apktemplates'); ?></h3>
                                    <select name="at_apt_post_status" class="at-select">
                                        <option value="draft" <?php selected($apt_post_status, 'draft'); ?>>Draft</option>
                                        <option value="publish" <?php selected($apt_post_status, 'publish'); ?>>Publish
                                        </option>
                                    </select>
                                </td>
                                <td>
                                    <h3><?php esc_html_e('Post title starting text', 'apktemplates'); ?></h3>
                                    <input type="text" name="at_apt_post_title_start" class="at-ipt-text" value="<?php echo esc_attr($apt_post_title_start); ?>" placeholder="Eg. [Start text] Spotify MOD APK" />
                                </td>
                                <td>
                                    <h3>
                                        <?php esc_html_e('Post title ending text', 'apktemplates'); ?>
                                    </h3>
                                    <input type="text" name="at_apt_post_title_end" class="at-ipt-text" value="<?php echo esc_attr($apt_post_title_end); ?>" placeholder="Eg. Spotify MOD APK [End text]" />
                                </td>
                                <td>
                                    <h3>
                                        <?php esc_html_e('MOD Feature', 'apktemplates'); ?>
                                    </h3>
                                    <input type="text" name="at_apt_mod_feature" class="at-ipt-text" value="<?php echo esc_attr($apt_mod_feature); ?>" placeholder="Eg. Premium Unlocked">
                                </td>
                                <td>
                                    <h3>
                                        <?php esc_html_e('Import Screenshots', 'apktemplates'); ?>
                                    </h3>
                                    <div class="at-btn-container">
                                        <label class="at-switch-btn">
                                            <input type="checkbox" name="at_apt_import_screenshots" id="at_apt_import_screenshots" <?php checked($apt_import_screenshots); ?>>
                                            <span class="at-switch at-apt-switch"></span>
                                        </label>
                                    </div>
                                </td>
                                <td>
                                    <h3>
                                        <?php esc_html_e('Import APK file', 'apktemplates'); ?>
                                    </h3>
                                    <div class="at-btn-container">
                                        <label class="at-switch-btn">
                                            <input type="checkbox" name="is_get_apk" id="is_get_apk" <?php checked($is_get_apk); ?>>
                                            <span class="at-switch at-apt-switch"></span>
                                        </label>
                                    </div>
                                </td>
                                <td>
                                    <h3><?php esc_html_e('Thumbnail quality', 'apktemplates'); ?></h3>
                                    <select name="at_apt_post_thumbnail_quality" class="at-select">
                                        <option value="raw" <?php selected($apt_post_thumbnail_quality, 'raw'); ?>>Original</option>
                                        <option value="512" <?php selected($apt_post_thumbnail_quality, '512'); ?>>Large (512x512)</option>
                                        <option value="256" <?php selected($apt_post_thumbnail_quality, '256'); ?>>Medium (256x256)</option>
                                        <option value="128" <?php selected($apt_post_thumbnail_quality, '128'); ?>>Small (128x128) Recommeded</option>
                                    </select>
                                </td>
                        </tbody>
                    </table>
                </div>
            </form>
            <div class="at-apk-search">
                <div class="at-search-title">
                    <h2>Search Games & Apps</h2>
                </div>
                <div class="at-inline-ipt at-mt-2 at-mb-2">
                    <input type="url" id="at-apt-search-query" class="at-ipt-url" min="3" placeholder="E.g Spotify" required />
                    <button id="at-apt-search-submit" class="at-btn at-btn-orange">Search</button>
                </div>
                <div id="at-apt-apk-results">
                    <div class="at-apk-results-container">
                        <div class="at-apk-no-results">
                            <p>Search your favorite Games & Apps</p>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
<?php
}


function apkt_apt_create_post()
{
    $nonce = sanitize_text_field($_POST['nonce']);

    if (!wp_verify_nonce($nonce, 'aptoide_nonce')) {
        return json_encode([
            'status' => 'error',
            'data' => [
                'message' => 'Khatam! Tata! Good Bye!',
            ],
        ]);
    }

    $apt_url = filter_input(INPUT_POST, 'apt_url', FILTER_SANITIZE_URL);
    $is_advanced_options = filter_input(INPUT_POST, 'is_advanced_options', FILTER_VALIDATE_BOOLEAN);

    update_option('at_apt_is_advanced_options', $is_advanced_options) || add_option('at_apt_is_advanced_options', $is_advanced_options);
    update_option('at_wp_uploading_file_size', 0) || add_option('at_wp_uploading_file_size', 0);
    update_option('at_gp_uploaded_file_size', 0) || add_option('at_gp_uploaded_file_size', 0);
    update_option('at_ftp_uploaded_file_size', 0) || add_option('at_ftp_uploaded_file_size', 0);
    update_option('at_is_file_import_to_wp', false) || add_option('at_is_file_import_to_wp', false);

    $storage = apkt_options('upload_storage', 'my-server');

    if ($storage == 'gdrive' || $storage == 'ftp') {
        update_option('at_is_file_import_to_wp', true);
    }

    $is_advanced_options = apkt_options('apt_is_advanced_options', false);

    if ($is_advanced_options) {
        $post_status = sanitize_text_field($_POST['post_status']);
        $post_title_start = sanitize_text_field($_POST['post_title_start']);
        $post_title_end = sanitize_text_field($_POST['post_title_end']);
        $mod_feature = sanitize_text_field($_POST['mod_feature']);
        $import_screenshots = filter_var($_POST['import_screenshots'], FILTER_VALIDATE_BOOLEAN);
        $is_get_apk = filter_var($_POST['is_get_apk'], FILTER_VALIDATE_BOOLEAN);
        $post_thumbnail_quality = sanitize_text_field($_POST['post_thumbnail_quality']);

        update_option('at_apt_post_status', $post_status);
        update_option('at_apt_post_title_start', $post_title_start);
        update_option('at_apt_post_title_end', $post_title_end);
        update_option('at_apt_mod_feature', $mod_feature);
        update_option('at_apt_post_thumbnail_quality', $post_thumbnail_quality);
        update_option('at_apt_import_screenshots', $import_screenshots);
        update_option('at_is_get_apk', $is_get_apk);
    }

    $apk_data = new APKT_Aptoide();
    $response = $apk_data->extract($apt_url, 'apk');
    $response = json_encode($response);

    echo $response;
    exit;
}
add_action('wp_ajax_apkt_apt_create_post', 'apkt_apt_create_post');

function apkt_apt_search_posts()
{
    $nonce = sanitize_text_field($_POST['nonce']);

    if (!wp_verify_nonce($nonce, 'aptoide_nonce')) {
        return json_encode([
            'status' => 'error',
            'data' => [
                'message' => 'Khatam! Tata! Good Bye!',
            ],
        ]);
    }

    $search_query = strtolower($_POST['search_query']);
    $base_url = 'https://web-api-cache.aptoide.com/search?query=';
    $search_url = $base_url . urlencode($search_query) . '&mature=true';

    $search_data = new APKT_Aptoide();
    $response = $search_data->extract($search_url, 'search');
    $response = json_encode($response);
    echo $response;

    exit;
}
add_action('wp_ajax_apkt_apt_search_posts', 'apkt_apt_search_posts');

function apkt_apt_upload_apk()
{
    $nonce = sanitize_text_field($_POST['nonce']);

    if (!wp_verify_nonce($nonce, 'aptoide_nonce')) {
        return json_encode([
            'status' => 'error',
            'data' => [
                'message' => 'Khatam! Tata! Good Bye!',
            ],
        ]);
    }

    $post_id = sanitize_text_field($_POST['post_id']);
    $apk_url = isset($_POST['apk_url']) ? $_POST['apk_url'] : null;
    $apk_version = isset($_POST['apk_version']) ? $_POST['apk_version'] : null;
    $apk_size = isset($_POST['apk_size']) ? $_POST['apk_size'] : null;

    $apk_file_data = new APKT_Upload_APK($post_id, $apk_url, $apk_version, $apk_size);
    $response = $apk_file_data->upload();
    $response = json_encode($response);

    echo $response;
    exit;
}
add_action('wp_ajax_apkt_apt_upload_apk', 'apkt_apt_upload_apk');

function apkt_apt_upload_process()
{
    $nonce = sanitize_text_field($_POST['nonce']);

    if (!wp_verify_nonce($nonce, 'aptoide_nonce')) {
        return json_encode([
            'status' => 'error',
            'data' => [
                'message' => 'Khatam! Tata! Good Bye!',
            ],
        ]);
    }

    $apk_url = isset($_POST['apk_url']) ? $_POST['apk_url'] : null;
    $apk_version = isset($_POST['apk_version']) ? $_POST['apk_version'] : null;

    $apk_file_data = new APKT_Upload_APK('', $apk_url, $apk_version, '');
    $response = $apk_file_data->calculate_progress();
    $response = json_encode($response);

    echo $response;
    exit;
}
add_action('wp_ajax_apkt_apt_upload_process', 'apkt_apt_upload_process');

/* Panel Ajax */
function apkt_panel_get_all_terms()
{
    $nonce = sanitize_text_field($_POST['nonce']);
    if (!wp_verify_nonce($nonce, 'panel_nonce')) {
        wp_send_json_error(['message' => 'Invalid nonce']);
        wp_die();
    }

    $query = sanitize_text_field($_POST['search']);
    if (empty($query) || strlen($query) < 3) {
        wp_send_json_error(['message' => 'Enter at least 3 letters']);
        wp_die();
    }

    $page = isset($_POST['page']) ? intval($_POST['page']) : 1;
    $items_per_page = 10;
    $offset = ($page - 1) * $items_per_page;

    $query_term = new WP_Term_Query(
        array(
            'taxonomy'   => array('category', 'post_tag'),
            'hide_empty' => false,
            'name__like' => $query,
            'number'     => $items_per_page,
            'offset'     => $offset,
        )
    );

    $results = [];
    if (!empty($query_term->terms)) {
        foreach ($query_term->terms as $term) {
            $results[] = [
                'id'   => $term->term_id,
                'text' => $term->name,
            ];
        }
    }

    $total_terms = $query_term->get_terms();
    $has_more = count($query_term->terms) === $items_per_page;

    wp_send_json_success(['results' => $results, 'has_more' => $has_more]);
    wp_die();
}
add_action('wp_ajax_apkt_panel_get_all_terms', 'apkt_panel_get_all_terms');

function apkt_panel_get_all_posts()
{
    $search = isset($_POST['search']) ? sanitize_text_field($_POST['search']) : '';
    $page = isset($_POST['page']) ? intval($_POST['page']) : 1;
    $items_per_page = 10;
    $offset = ($page - 1) * $items_per_page;

    $args = [
        's'              => $search,
        'post_type'      => 'post',
        'posts_per_page' => $items_per_page,
        'offset'         => $offset,
        'post_status'    => 'publish'
    ];

    $posts = get_posts($args);
    $results = [];

    foreach ($posts as $post) {
        $results[] = [
            'post_id'    => $post->ID,
            'post_title' => $post->post_title
        ];
    }

    $has_more = count($posts) === $items_per_page;

    wp_send_json(['posts' => $results, 'has_more' => $has_more]);
    wp_die();
}
add_action('wp_ajax_apkt_panel_get_all_posts', 'apkt_panel_get_all_posts');

//new APKT_MODW();

function apkt_save_panel_settings()
{
    $nonce = sanitize_text_field($_POST['nonce']);

    if (!wp_verify_nonce($nonce, 'panel_nonce')) {
        return wp_send_json_error('Khatam! Tata! Good Bye!');
    }

    $data = $_POST['data'];

    $new_data = [];
    $repeater_data = [];
    $multi_select_data = [];
    $options_data = [];

    $options = [
        'import_ss_limit',
        'is_mod_title',
        'is_mod_feature_title',
        'is_title_version',
        'upload_storage',
        'gdrive_client_id',
        'gdrive_client_secret',
        'gdrive_folder_name',
        'ftp_server_ip',
        'ftp_port',
        'ftp_username',
        'ftp_password',
        'ftp_directory',
        'ftp_url',
    ];

    $single_data = array_filter($data, function ($item) {
        return strpos($item['name'], '[') === false;
    });

    $repeater_datas = array_filter($data, function ($item) {
        return strpos($item['name'], '[') !== false;
    });

    foreach ($single_data as $item) {
        if ($item['value'] === 'true' || $item['value'] === 'false') {
            $item['value'] = filter_var($item['value'], FILTER_VALIDATE_BOOLEAN);
        } else {
            $item['value'] = apkt_removeslashes_deep($item['value']);
        }

        if (!in_array($item['name'], $options)) {
            $new_data[$item['name']] = $item['value'];
        } else {
            $options_data[$item['name']] = $item['value'];
        }
    }
    // for normal repeater with array (download faq and home terms)
    foreach ($repeater_datas as $item) {

        if ($item['value'] === 'true' || $item['value'] === 'false') {
            $item['value'] = filter_var($item['value'], FILTER_VALIDATE_BOOLEAN);
        } else {
            $item['value'] = apkt_removeslashes_deep($item['value']);
        }

        if (!in_array($item['name'], $options)) {
            if (strpos($item['name'], '[]') !== false) {
                $main_name = str_replace('[]', '', $item['name']);
                $repeater_data[$main_name] = array();
            } else {
                preg_match('/^([^\[]+)\[([\d]+)\]\[([^\]]+)\]$/', $item['name'], $matches);

                if (count($matches) === 4) {
                    $main_name = $matches[1];
                    $index = $matches[2];
                    $field_name = $matches[3];

                    if (!isset($repeater_data[$main_name])) {
                        $repeater_data[$main_name] = array();
                    }

                    if (!isset($repeater_data[$main_name][$index])) {
                        $repeater_data[$main_name][$index] = array();
                    }

                    $repeater_data[$main_name][$index][$field_name] = $item['value'];
                }
            }
        }
    }
    // For multi selected options repeater (App Info)
    foreach ($repeater_datas as $item) {
        if ($item['value'] === 'true' || $item['value'] === 'false') {
            $item['value'] = filter_var($item['value'], FILTER_VALIDATE_BOOLEAN);
        }

        if (!in_array($item['name'], $options)) {
            preg_match('/^([^\[]+)(\[[^\]]+\])?$/', $item['name'], $matches);

            if (count($matches) === 3) {
                $main_name = $matches[1];
                $multi_select_suffix = $matches[2];

                if (!isset($multi_select_data[$main_name])) {
                    $multi_select_data[$main_name] = [];
                }

                if ($multi_select_suffix) {
                    $value_key = trim($multi_select_suffix, '[]');

                    if ($item['value'] === true) {
                        $multi_select_data[$main_name][] = $value_key;
                    }
                }
            }
        }
    }

    foreach ($repeater_data as $main_name => $values) {
        $new_data[$main_name] = $values;
    }

    foreach ($multi_select_data as $main_name => $values) {
        $new_data[$main_name] = $values;
    }

    foreach ($new_data as $main_name => $values) {
        set_theme_mod($main_name, $values);
    }

    foreach ($options_data as $main_name => $values) {
        update_option('at_' . $main_name, $values);
    }

    wp_send_json_success('Changes saved!');
    wp_die();
}

add_action('wp_ajax_apkt_save_panel_settings', 'apkt_save_panel_settings');

function apkt_import_demo()
{
    if (!isset($_FILES['import_file']) || $_FILES['import_file']['error'] !== UPLOAD_ERR_OK) {
        wp_send_json_error('No file uploaded or error occurred');
        exit;
    }

    if (!isset($_POST['nonce']) || !wp_verify_nonce($_POST['nonce'], 'apktemplates_nonce')) {
        wp_send_json_error('Invalid nonce');
        exit;
    }

    $import_file = $_FILES['import_file']['tmp_name'];
    $import_json = file_get_contents($import_file);

    if ($import_json === false) {
        wp_send_json_error('Unable to read file');
        exit;
    }

    $demo_data = json_decode($import_json, true);
    if (!is_array($demo_data)) {
        wp_send_json_error('Invalid JSON format');
        exit;
    }

    if (!isset($demo_data['info']) || strtolower($demo_data['info']['theme_name']) !== strtolower(APKT_THEME_NAME)) {
        wp_send_json_error('The imported demo is not for this theme.');
        exit;
    }

    function insert_demo_post($post_data, $post_type = 'post')
    {
        $title = $post_data['title'];
        $description = wp_encode_emoji($post_data['description']);
        $thumbnail_url = $post_data['thumbnail'];

        $post_id = wp_insert_post([
            'post_title'   => $title,
            'post_content' => $description,
            'post_type'    => $post_type,
            'post_status'  => 'publish',
            'meta_input'   => $post_data['apktemplates'] ?? []
        ]);

        if ($post_id && !is_wp_error($post_id)) {
            if (!empty($thumbnail_url)) {
                $image_id = apkt_set_post_thumbnail_from_url($post_id, $thumbnail_url);
                set_post_thumbnail($post_id, $image_id);
            }
        }
        return $post_id;
    }

    foreach (['posts' => 'post', 'articles' => 'articles', 'news' => 'news'] as $key => $post_type) {
        if (isset($demo_data[$key])) {
            foreach ($demo_data[$key] as $post_data) {
                insert_demo_post($post_data, $post_type);
            }
        }
    }

    wp_send_json_success('Import demo successful :)');
    exit;
}

add_action('wp_ajax_apkt_import_demo', 'apkt_import_demo');

function apkt_import_settings()
{
    if (isset($_FILES['import_file']) && $_FILES['import_file']['error'] === UPLOAD_ERR_OK) {
        $import_file = $_FILES['import_file']['tmp_name'];

        $import_json = file_get_contents($import_file);

        if ($import_json !== false) {
            $backup_data = json_decode($import_json, true);

            if (is_array($backup_data)) {
                if (isset($backup_data['info']) && $backup_data['info']['theme_name'] === strtolower(APKT_THEME_NAME)) {
                    foreach ($backup_data as $option_name => $option_value) {
                        if ($option_name !== 'info') {
                            if ($option_value['is_option']) {
                                update_option($option_name, $option_value['value']);
                            } else {
                                set_theme_mod($option_name, $option_value['value']);
                            }
                        }
                    }

                    wp_send_json_success('Import successful :)');
                } else {
                    wp_send_json_error('The imported backup is not for this theme.');
                }
            } else {
                wp_send_json_error('Invalid JSON format');
            }
        } else {
            wp_send_json_error('Unable to read file');
        }
    } else {
        wp_send_json_error('No file uploaded or error occurred');
    }
    exit;
}
add_action('wp_ajax_apkt_import_settings', 'apkt_import_settings');

function apkt_export_settings()
{
    if (!isset($_POST['nonce']) || !wp_verify_nonce(sanitize_text_field($_POST['nonce']), 'panel_nonce')) {
        wp_send_json_error('Nonce verification failed');
        exit;
    }

    $date = date('Y-m-d_H-i-s');
    $backup_data = [];

    $backup_data['info'] = [
        'theme_name' => strtolower(APKT_THEME_NAME),
        'theme_version' => APKT_THEME_VERSION,
        'author' => 'apktemplates',
        'created' => $date
    ];

    $option_names = [
        'at_import_ss_limit',
        'at_is_mod_title',
        'at_is_mod_feature_title',
        'at_is_title_version',
        'at_upload_storage',
        'at_gdrive_client_id',
        'at_gdrive_client_secret',
        'at_gdrive_folder_name',
        'at_ftp_server_ip',
        'at_ftp_port',
        'at_ftp_username',
        'at_ftp_password',
        'at_ftp_directory',
        'at_ftp_url'
    ];

    $theme_mods_names = [
        'logo_img',
        'enable_live_search',
        'head_code',
        'menu_select_1',
        'menu_select_2',
        'hero_img',
        'hero_title',
        'hero_btn_name',
        'hero_btn_url',
        'home_featured_posts_swt',
        'featured_posts',
        'terms',
        'home_recommend_swt',
        'home_recommend_logo',
        'recommend_posts',
        'home_seo_swt',
        'home_seo_title',
        'home_seo_description',
        'screenshots_limit',
        'security_check_swt',
        'recommend_swt',
        'recommend_post_limit',
        'archive_sort',
        'archive_posts_limit',
        'download_timer',
        'faqs',
        'home_top_ads_swt',
        'home_top_ads',
        'home_botm_ads_swt',
        'home_botm_ads',
        'single_top_ads_swt',
        'single_top_ads',
        'single_botm_ads_swt',
        'single_botm_ads',
        'archive_top_ads_swt',
        'archive_top_ads',
        'archive_botm_ads_swt',
        'archive_botm_ads',
        'download_top_ads_swt',
        'download_top_ads',
        'download_botm_ads_swt',
        'download_botm_ads',
        'facebook_url',
        'x_url',
        'youtube_url',
        'telegram_url',
        'tiktok_url',
        'pinterest_url',
        'whatsapp_url',
        'instagram_url',
        'github_url',
        'linkedin_url',
        'skype_url',
        'tumblr_url',
        'twitch_url',
        'vk_url',
        'reddit_url',
        'threads_url',
        'footer_copyright',
        'footer_code',
    ];

    foreach ($option_names as $option_name) {
        $backup_data[$option_name] = [
            'value' => get_option($option_name),
            'is_option' => true,
        ];
    }

    foreach ($theme_mods_names as $theme_mod_name) {
        $backup_data[$theme_mod_name] = [
            'value' => get_theme_mod($theme_mod_name),
            'is_option' => false,
        ];
    }

    $backup_json = json_encode($backup_data);
    if ($backup_json === false) {
        wp_send_json_error('JSON encoding error');
        exit;
    }

    $upload_dir = wp_upload_dir();
    $export_dir = $upload_dir['basedir'] . '/apkt_cache_dir';
    if (!file_exists($export_dir)) {
        wp_mkdir_p($export_dir); // Safely create directory if it doesn't exist
    }

    $export_json_path = $export_dir . '/' . strtolower(APKT_THEME_NAME) . '_' . $date . '.json';
    file_put_contents($export_json_path, $backup_json);

    $export_json_url = $upload_dir['baseurl'] . '/apkt_cache_dir/' . strtolower(APKT_THEME_NAME) . '_' . $date . '.json';
    wp_send_json_success($export_json_url);
    exit;
}
add_action('wp_ajax_apkt_export_settings', 'apkt_export_settings');

function apkt_delete_folder_action()
{
    if (!isset($_POST['nonce']) || !wp_verify_nonce(sanitize_text_field($_POST['nonce']), 'panel_nonce')) {
        wp_send_json_error('Invalid nonce, action unauthorized.');
        exit;
    }

    $upload_dir = apply_filters('upload_dir', wp_upload_dir());
    $cache_dir = $upload_dir['apkt_cache_dir'];

    if (!file_exists($cache_dir)) {
        wp_send_json_error('Cache directory does not exist.');
        exit;
    }

    if (apkt_delete_files($cache_dir)) {
        wp_send_json_success('Cache cleared successfully.');
    } else {
        wp_send_json_error('Failed to delete cache files.');
    }
    exit;
}

add_action('wp_ajax_apkt_delete_folder_action', 'apkt_delete_folder_action');
