<?php

class APEX_Google_Play
{
	public $base_url = 'https://play.google.com/';
	private $is_advanced_options;
	private $post_language = 'en-US';

	function __construct()
	{
		$this->is_advanced_options = at_options('is_advanced_options', false);

		if ($this->is_advanced_options) {
			$this->post_language = at_options('post_language', 'en-US');
		}
	}

	private function validate_gplay_url($gplay_url)
	{
		if (empty($gplay_url) || !strpos($gplay_url, 'play.google.com')) {
			return false;
		}
		return true;
	}

	private function validate_gplay_id($gplay_url)
	{
		if (preg_match("/\bid=([^\&]+)/", $gplay_url, $matches)) {
			return true;
		}
		return false;
	}

	private function validate_url_response_code($gplay_url)
	{
		return get_http_response_code($gplay_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 multiple_map_data($script_data, $mapping_values)
	{
		$mapped_data = [];
		foreach ($script_data as $item) {
			$mapped_item = [];
			foreach ($mapping_values as $key => $mapping) {
				if (is_array($mapping)) {
					if (isset($mapping['fun'])) {
						$value = $this->extract_path_value($item, $mapping['path']);
						$mapped_item[$key] = $mapping['fun']($value);
					} else {
						$mapped_item[$key] = $this->extract_path_value($item, $mapping);
					}
				}
			}
		$mapped_data[] = $mapped_item;
		}
		return $mapped_data;
	}

	public function search_single_map_data($script_data, $mapping_values)
	{
		$mapped_data = [];
		foreach ($script_data as $item) {
			$mapped_item = [];
				foreach ($mapping_values as $key => $mapping) {
					if (is_array($mapping)) {
						if (isset($mapping['fun'])) {
							$value = $this->extract_path_value($item, $mapping['path']);
							$mapped_item[$key] = $mapping['fun']($value);
						} else {
							$mapped_item[$key] = $this->extract_path_value($item, $mapping);
						}
					}
				}
		$mapped_data[] = $mapped_item;
		}
		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_description_text($description)
	{
		$html = '<div>' . str_replace('<br>', "\r\n", $description) . '</div>';

		$dom = new DOMDocument();
		$dom->loadHTML($html);

		$div_content = $dom->getElementsByTagName('div')[0]->textContent;

		return $div_content;
	}

	private function description_html_localized($search_array)
	{
		$description_translation = isset($search_array[12][0][0][1]) ? $search_array[12][0][0][1] : null;
		$description_original = $search_array[72][0][1];

		return $description_translation ?? $description_original;
	}

	private function generate_histogram_rating($container)
	{
		if (!$container) {
			return array(1 => 0, 2 => 0, 3 => 0, 4 => 0, 5 => 0);
		}

		return array(
			1 => $container[1][1],
			2 => $container[2][1],
			3 => $container[3][1],
			4 => $container[4][1],
			5 => $container[5][1],
		);
	}

	private function get_android_version($android_version_text)
	{
		if (!$android_version_text) {
			return '9.0';
		}

		$parts = explode(' ', $android_version_text);
		$number = $parts[0];

		if (is_numeric($number)) {
			return $number;
		}
	
		return '9.0';
	}

	private function extract_categories($search_array, $categories = [])
	{
		if ($search_array === null || count($search_array) === 0) {
			return $categories;
		}

		if (count($search_array) >= 4 && is_string($search_array[0])) {
			$categories[] = [
				'name' => $search_array[0],
				'id' => $search_array[2],
			];
		} else {
			foreach ($search_array as $sub) {
				$categories = $this->extract_categories($sub, $categories);
			}
		}

		return $categories;
    }

	private function apk_datas()
	{}
	
	
	private function apk_mappings()
	{
		$apk_mappings = [
			'apk_name' => [1, 2, 0, 0],
			'apk_id' => [1, 11, 0, 0],
			'apk_id_alt' => [1, 2, 77, 0],
			'apk_content' => [
				'path' => [1, 2],
				'fun' => function ($value) {
					return $this->get_description_text($this->description_html_localized($value));
				},
			],
			'apk_content_html' => [
				'path' => [1, 2],
				'fun' => function ($value) {
					return $this->description_html_localized($value);
				},
			],
			'apk_description' => [1, 2, 73, 0, 1],
			'apk_installs' => [1, 2, 13, 0],
			'apk_min_installs' => [1, 2, 13, 1],
			'apk_max_installs' => [1, 2, 13, 2],
			'apk_rating' => [1, 2, 51, 0, 1],
			'apk_rating_text' => [1, 2, 51, 0, 0],
			'apk_total_rating' => [1, 2, 51, 2, 1],
			'apk_total_votes' => [1, 2, 51, 3, 1],
			'apk_histogram' => [
				'path' => [1, 2, 51, 1],
				'fun' => function ($value) {
					return $this->generate_histogram_rating($value);
				},
			],
			'apk_price' => [
				'path' => [1, 2, 57, 0, 0, 0, 0, 1, 0, 0],
				'fun' => function ($price) {
					if (!isset($price) || $price === '') {
						return 0;
					} else {
					return $price / 1000000;
					}
				},
			],
			'apk_original_price' => [
				'path' => [1, 2, 57, 0, 0, 0, 0, 1, 1, 0],
				'fun' => function ($price) {
					if (!isset($price) || $price === '') {
						return 0;
					} else {
						return $price / 1000000;
					}
				},
			],
			'apk_discount_end_date' => [1, 2, 57, 0, 0, 0, 0, 14, 1],
			'apk_is_free' => [
				'path' => [1, 2, 57, 0, 0, 0, 0, 1, 0, 0],
				'fun' => function ($value) {
					return $value === 0;
				},
			],
			'apk_currency' => [1, 2, 57, 0, 0, 0, 0, 1, 0, 1],
			'apk_price_text' => [
				'path' => [1, 2, 57, 0, 0, 0, 0, 1, 0, 2],
				'fun' => function ($value) {
					return $value ?: '0';
				},
			],
			'apk_is_available' => [
				'path' => [1, 2, 18, 0],
				'fun' => function ($value) {
					return (bool) $value;
				},
			],
			'apk_offers_IAP' => [
				'path' => [1, 2, 19, 0],
				'fun' => function ($value) {
					return (bool) $value;
				},
			],
			'apk_IAP_range' => [1, 2, 19, 0],
			'apk_required_version' => [
				'path' => [1, 2, 140, 1, 1, 0, 0, 1],
				'fun' => function ($version) {
					return $this->get_android_version($version);
				},
			],
			'apk_required_version_text' => [
				'path' => [1, 2, 140, 1, 1, 0, 0, 1],
				'fun' => function ($version) {
					return $version ?: '9.0';
				},
			],
			'apk_required_max_version' => [
				'path' => [1, 2, 140, 1, 1, 0, 1, 1],
				'fun' => function ($version) {
					return $this->get_android_version($version);
				},
			],
			'apk_developer' => [1, 2, 68, 0],
			'apk_developer_id' => [
				'path' => [1, 2, 68, 1, 4, 2],
				'fun' => function ($developer_url) {
					$parts = explode('id=', $developer_url);
					return isset($parts[1]) ? $parts[1] : null;
				},
			],
			'apk_developer_email' => [1, 2, 69, 1, 0],
			'apk_developer_website' => [1, 2, 69, 0, 5, 2],
			'apk_developer_address' => [1, 2, 69, 2, 0],
			'apk_privacy_policy' => [1, 2, 99, 0, 5, 2],
			'apk_developer_internal_id' => [
				'path' => [1, 2, 68, 1, 4, 2],
				'fun' => function ($developer_url) {
					$parts = explode('id=', $developer_url);
					return isset($parts[1]) ? $parts[1] : null;
				},
			],
			'apk_category' => [1, 2, 79, 0, 0, 2], // It to parse the category
			'apk_sub_category' => [1, 2, 79, 0, 0, 0],
			'categories' => [
				'path' => [1, 2],
				'fun' => function ($array_data) {
					$categories = $this->extract_categories($array_data[118]);

					if (count($categories) === 0) {
						$categories[] = [
							'name' => $array_data[79][0][0][0],
							'id' => $array_data[79][0][0][2],
						];
					}
                    return $categories;
				}
			],
			'apk_thumbnail' => [1, 2, 95, 0, 3, 2],
			'apk_banner' => [1, 2, 96, 0, 3, 2],
			'apk_screenshots' => [
				'path' => [1, 2, 78, 0],
				'fun' => function ($screenshots) {
					if ($screenshots === null) {
						return [];
					}

					$result = [];
					foreach ($screenshots as $screenshot) {
						if (isset($screenshot[3][2])) {
							$result[] = $screenshot[3][2];
						}
					}
                    return $result;
				}
			],
			'apk_yt_video' => [1, 2, 100, 0, 0, 3, 2],
			'apk_video_image' => [1, 2, 100, 1, 0, 3, 2],
			'apk_preview_video' => [1, 2, 100, 1, 2, 0, 2],
			'apk_content_rating' => [1, 2, 9, 0],
			'apk_content_rating_description' => [1, 2, 9, 2, 1],
			'apk_ad_supported' => [
				'path' => [1, 2, 48],
				'fun' => function ($val) {
					return (bool) $val;
				},
			],
			'apk_released' => [1, 2, 10, 0],
			'apk_updated' => [
				'path' => [1, 2, 145, 0, 1, 0],
				'fun' => function ($timestamp) {
					return date("M j, Y", $timestamp);
				},
			],
			'apk_version' => [
				'path' => [1, 2, 140, 0, 0, 0],
				'fun' => function ($value) {
					return $value ?: '';
				},
			],
			'apk_whats_new' => [1, 2, 144, 1, 1],
			'apk_pre_register' => [
				'path' => [1, 2, 18, 0],
				'fun' => function ($value) {
					return $value === 1;
				},
			],
			'apk_is_early_access_enabled' => [
				'path' => [1, 2, 18, 2],
				'fun' => function ($value) {
					return is_string($value);
				},
			],
			'apk_is_available_in_playpass' => [
				'path' => [1, 2, 62],
				'fun' => function ($field) {
					return !!$field;
				},
			],
			'apt_id' => '',
			'apk_updatex' => '',
		];

		return $apk_mappings;
	}
   
	private function search_mappings($index)
	{
        if ($index === 23) {

            $search_mappings = [
    			'apk_name' => [0, 3],
    			'apk_id' => [0, 0, 0],
    			//'apk_id' => [16, 11, 0, 0],
    			'apk_url' => [
                    'path' => [0, 10, 4, 2],
                    'fun' => function ($path) {
                        $url = rtrim($this->base_url, '/') . '/' . ltrim($path, '/');
                        return $url;
                    },
                ],
    			'apk_thumbnail' => [
                    'path' => [0, 1, 3, 2],
                    'fun' => function ($thumbnail) {
                        return $thumbnail . '=w96-rw';
                    },
                ],
    			'apk_banner' => [0, 100, 1, 0, 3, 2],
    			'apk_developer' => [0, 14],
    			'apk_currency' => [0, 8, 1, 0, 1],
    			'apk_price' => [
                    'path' => [0, 8, 1, 0, 0],
                    'fun' => function ($price) {
                        return $price / 1000000;
                    },
                ],
    			'apk_is_free' => [
                    'path' => [0, 8, 1, 0, 0],
                    'fun' => function ($price) {
                        return $price === 0;
                    },
                ],
    			'apk_description' => [0, 13, 1],
    			'apk_downloads' => [0, 15],
    			'apk_rating_text' => [0, 4, 0],
    			'apk_rating' => [0, 4, 1],
            ];

            return $search_mappings;

        } elseif ($index === 24) {

            $search_mappings_1 = [
    			'apk_name' => [16, 2, 0, 0],
    			'apk_id' => [0, 0, 0],
			//'apk_id' => [1, 11, 0, 0],
			//'apk_id' => [1, 2, 77, 0],
				
    			//'apk_name' => [0, 3],
    			//'apk_id' => [0, 0, 0],
    			'apk_url' => [
                    'path' => [17, 0, 0, 4, 2],
                    'fun' => function ($path) {
                        $url = rtrim('https://play.google.com/', '/') . '/' . ltrim($path, '/');
                        return $url;
                    },
                ],
    			'apk_thumbnail' => [
                    'path' => [16, 2, 95, 0, 3, 2],
                    'fun' => function ($thumbnail) {
                        return $thumbnail . '=w96-rw';
                    },
                ],
    			'apk_banner' => [16, 2, 96, 0, 3, 2],
    			'apk_developer' => [16, 2, 68, 0],
    			'apk_currency' => [17, 0, 2, 0, 1, 0, 1],
    			'apk_price' => [
                    'path' => [17, 0, 2, 0, 1, 0, 0],
                    'fun' => function ($price) {
                        return $price / 1000000;
                    },
                ],
    			'apk_is_free' => [
                    'path' => [17, 0, 2, 0, 1, 0, 0],
                    'fun' => function ($price) {
                        return $price === 0;
                    },
                ],
    			'apk_description' => [16, 2, 73, 0, 1],
    			'apk_downloads' => [16, 2, 13, 0],
    			'apk_rating_text' => [16, 2, 51, 0, 0],
    			'apk_rating' => [16, 2, 51, 0, 1],
            ];

            $search_mappings_2 = [
    			'apk_name' => [0, 3],
    			'apk_id' => [0, 0, 0],
    			'apk_url' => [
                    'path' => [0, 10, 4, 2],
                    'fun' => function ($path) {
                        $url = rtrim('https://play.google.com/', '/') . '/' . ltrim($path, '/');
                        return $url;
                    },
                ],
    			'apk_thumbnail' => [
                    'path' => [0, 1, 3, 2],
                    'fun' => function ($thumbnail) {
                        return $thumbnail . '=w96-rw';
                    },
                ],
    			'apk_banner' => [0, 22, 3, 2],
    			'apk_developer' => [0, 14],
    			'apk_currency' => [0, 8, 1, 0, 1],
    			'apk_price' => [
                    'path' => [0, 8, 1, 0, 0],
                    'fun' => function ($price) {
                        return $price / 1000000;
                    },
                ],
    			'apk_is_free' => [
                    'path' => [0, 8, 1, 0, 0],
                    'fun' => function ($price) {
                        return $price === 0;
                    },
                ],
    			'apk_description' => [0, 13, 1],
    			'apk_downloads' => [0, 15],
    			'apk_rating_text' => [0, 4, 0],
    			'apk_rating' => [0, 4, 1],
            ];

            $search_mappings[] = $search_mappings_1;
            $search_mappings[] = $search_mappings_2;

            return $search_mappings;

        } elseif ($index === 26) {

            $search_mappings = [
                'no_results' => [0, 0, 1],
                'no_results_description' => [1, 0, 1],
            ];

            return $search_mappings;

        }
    }

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

        $scraper = new Scraper();
        $gp_html = $scraper->scrape($gp_url);
	
        $html = new simple_html_dom();
        $html->load($gp_html);

        $script_data = $html->find('script[type="application/ld+json"]', 0);
		 
        $get_scripts = $html->find('script');

        $apk_icon_url = null;

        if ($script_data) {

            $script_data = $script_data->innertext;
            $script_data = json_decode($script_data);
            $apk_icon_url = isset($script_data->image) ? $script_data->image : null;

        } else {
            $response['status'] = 'error';
            $response['data'] = [
                'message' => 'Main script not found!',
            ];

            return $response;
        }

        $scripts_count = 0;

        if ($get_scripts) {

            foreach ($get_scripts as $script) {

				if (strpos($script, '[[[[]]],[null,null,[[')) {

					$scripts_count++;

					$data_pattern = "/'ds:([\d]+)'\s*,\s*hash:\s*'(\d+)'\s*,\s*data:\[([^\[\]]*(?:\[(?:[^\[\]]*|(?3))*\][^\[\]]*)*)\]/";

					if (preg_match($data_pattern, $script, $matches)) {
						//$ds = $matches[1];
						////$hash = $matches[2];
						$data = '[' . $matches[3] . ']';
						$data = substr($data, 1, -1);
						$data = json_decode("[$data]", true);

						$response['status'] = 'success';
						$response['data'] = $this->single_map_data($data, $this->apk_mappings());
					} else {
						$response['status'] = 'error';
						$response['data'] = [
							'message' => 'Pattern not matched to script data!',
						];
					}

                }
            }

        } else {

            $response['status'] = 'error';
            $response['data'] = [
                'message' => 'No one script files not available in play store!',
            ];

        }

        return $response;
    }

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

        $scraper = new Scraper();
        $gp_html = $scraper->scrape($url);

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

        $scripts = $html->find('script');

        if ($scripts) {

            foreach ($scripts as $script) {

                if (strpos($script->innertext, "key: 'ds:4'") !== false) {

                    $search_script = $script->innertext;

                    $start_pos = strpos($search_script, "data:[[");

                    if ($start_pos !== false) {

                        $start_pos += strlen("data:");

                        $end_pos = strpos($search_script, ", sideChannel: {}}", $start_pos);

                        if ($end_pos !== false) {
                            $length = $end_pos - $start_pos;

                            $search_data = substr($search_script, $start_pos, $length);

                            $search_data = substr($search_data, 1, -1);

                            $search_data = json_decode("[$search_data]", true);

                            $search_data_length = count($search_data[0][1][0]);

                            if ($search_data_length === 23) {

                                $search_data = $this->search_single_map_data($search_data[0][1][0][22][0], $this->search_mappings(23));

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

                            } elseif ($search_data_length === 24) {
                                $search_mappings = $this->search_mappings(24);

                                $searched_data_1 = [$this->single_map_data($search_data[0][1][0][23], $search_mappings[0])];
                                $searched_data_2 = $this->multiple_map_data($search_data[0][1][1][22][0], $search_mappings[1]);

                                $search_data = array_merge($searched_data_1, $searched_data_2);

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

                            } elseif ($search_data_length === 26) {

                                $search_data = $this->single_map_data($search_data[0][1][0][25][0], $this->search_mappings(26));

                                $response['status'] = 'error';
                                $response['data'] = [
                                    'message' => 'No results found :(',
                                ];

                            } else {

                                $response['status'] = 'error';
                                $response['data'] = [
                                    'message' => 'Requested data not found in script data.',
                                ];

                            }

                        } else {

                            $response['status'] = 'error';
                            $response['data'] = [
                                'message' => 'Data found but sideChannel not found in script.',
                            ];

                        }

                    } else {

                        $response['status'] = 'error';
                        $response['data'] = [
                            'message' => 'Script not found in play store.',
                        ];

                    }

                }

            }

        } else {

            $response['status'] = 'error';
            $response['data'] = [
                'message' => 'No one script files not available in play store!',
            ];

        }

        return $response;
    }

	public function extract($gp_url, $type = '')
    {
        //$lic = new AT_License();
        //if ($lic->is_valid_license()) {
        //    $response = [
        //        'status' => 'error',
        //        'data' => [
        //            'message' => __('3 License Key is invalid or expired.', TEXT_DOMAIN),
        //        ],
        //    ];
        //    return $response;
        //}
        
        $gplay_url = $gp_url . '&gl=US';

        if (!empty($this->post_language) && $this->post_language != '0') {
            $gplay_url = $gp_url . '&hl=' . $this->post_language . '&gl=US';
        }

        $gp_url_validation = $this->validate_gplay_url($gplay_url);

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

            return $response;
        }

        $gp_url_response = $this->validate_url_response_code($gplay_url);

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

            return $response;
        }

        if (!empty($type) && $type === 'apk') {
            $gp_id_validation = $this->validate_gplay_id($gplay_url);

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

                return $response;
            }

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

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

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

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

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

        return $response;
    }

}

class APEX_Create_GP_Post
{
	private $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_installs;
	private $apk_id;
	private $apk_id_alt;
	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_content_rating;
	private $apk_required;
	private $apk_price;
	private $apk_updates;
	private $apk_updated;
	private $apt_id = "";
	private $post_id;
	private $parent_cat;
	private $child_cat;
	private $post_status = 'draft'; 
	private $post_thumbnail_format = 'png';
	private $post_thumbnail_quality = 'raw';
	private $import_screenshots = false;
	private $post_screenshots_format = 'jpg';
	private $import_ss_limit = '5';
	private $post_language = 'en-US'; 
  	    
	private function apkID()
	{ 		 
		$post_language 	= at_options('post_language', 'en-US');
		$gp			= 'https://play.google.com/store/apps/details?id='.$this->apk_id_alt.'&hl='.$post_language;
		
		$scraper 		= new Scraper(); 
		$get_infos	= $scraper->scrape_site($gp);	
		 
			 
		//$scraper = new APEX_Google_Play();
		//$apkID = $scraper->validate_gplay_id($gp_url);
	
		//$apkID1		= $_POST['at_gp_url'];
		$apkID		= $scraper->match('/<link rel="alternate" href=".*?\?id=(.*?)" hreflang="x-default">/', $get_infos, 1);
		
		return $apkID;
	}
	
	private function youtubeID()
	{ 		
		$post_language 	= at_options('post_language', 'en-US');
		$gp			= 'https://play.google.com/store/apps/details?id='.$this->apk_id_alt.'&hl='.$post_language;
		
		$scraper 		= new Scraper(); 
		$get_infos	= $scraper->scrape_site($gp);	
		 
		$apk_youtube	= $scraper->match('/<button.*?class="cvriud ".*?data-trailer-url=".*?yt:movie:(.*?)\?.*?>/ms', $get_infos, 1);  
		
		return $apk_youtube;
	}

	private function nVersion()
	{ 		
		$post_language 	= at_options('post_language', 'en-US');
		
		$gp			= 'https://play.google.com/store/apps/details?id='.$this->apk_id_alt.'&hl='.$post_language;
		$urlz		= 'https://a-a.my.id/gps.php?pkgid='.$this->apk_id_alt; 
		//$urlz1		= 'https://zplay.demos.web.id/gps/?pkgid='.$this->apk_id; 
		
		$scraper 		= new Scraper(); 
		$get_infos	= $scraper->scrape_site($gp);	
		$g_data		= $scraper->scrape_site($urlz);	
		 
		$n_version	= $scraper->match('/<div class="version">(.*?)<\/div>/ms', $g_data, 1);  
		
		return $n_version;
	}

	private function aSize()
	{ 		
		$post_language 	= at_options('post_language', 'en-US');
		$gp			= 'https://play.google.com/store/apps/details?id='.$this->apk_id_alt.'&hl='.$post_language;
		$urlz		= 'https://a-a.my.id/gps.php?pkgid='.$this->apk_id_alt;  
		
		$scraper 		= new Scraper(); 
		$get_infos	= $scraper->scrape_site($gp);	
		$g_data		= $scraper->scrape_site($urlz);	
		 
		$apk_sizes	= $scraper->match('/<div class="size">(.*?)<\/div>/ms', $g_data, 1);  
		
		return $apk_sizes;
	}
	
	private function aUpdate()
	{ 		
		$post_language 	= at_options('post_language', 'en-US');
		$gp			= 'https://play.google.com/store/apps/details?id='.$this->apk_id_alt.'&hl='.$post_language;
		$urlz		= 'https://a-a.my.id/gps.php?pkgid='.$this->apk_id_alt; 
		//$urlz1			= 'https://zplay.demos.web.id/gps/?pkgid='.$this->apk_id; 	
		
		$gplay		= new \Nelexa\GPlay\GPlayApps( $defaultLocale = $post_language, $defaultCountry = '' ); 
		$appinfo		= $gplay->getAppInfo( $this->apk_id_alt );


		$scraper 		= new Scraper(); 
		$get_infos	= $scraper->scrape_site($gp);	
		$g_data		= $scraper->scrape_site($urlz);	
		 
		$apk_updatez	= $scraper->match('/<div class="TKjAsc"><div><div class="lXlx5">.*?<\/div><div class="xg1aie">(.*?)<\/div><\/div><div><div class="lXlx5">.*?<\/div>.*?<div class="Uc6QCc">/ms', $get_infos, 1);  
		
		//$apk_updatez	= $appinfo->getUpdated()->format('M j, Y');
		
		
		return $apk_updatez;
	}

	private function aName()
	{ 		
		$post_language 	= at_options('post_language', 'en-US');
		$gp			= 'https://play.google.com/store/apps/details?id='.$this->apk_id_alt.'&hl='.$post_language;
		$urlz		= 'https://a-a.my.id/gps.php?pkgid='.$this->apk_id_alt; 
		//$urlz1		= 'https://zplay.demos.web.id/gps/?pkgid='.$this->apk_id; 	
		

		$scraper 		= new Scraper(); 
		$get_infos	= $scraper->scrape_site($gp);	
		$g_data		= $scraper->scrape_site($urlz);	
		 
		$app_names2	= $scraper->match('/<h1><span class="AfwdI" itemprop="name">(.*?)<\/span><\/h1>/ms', $get_infos, 1);  
		
		$gplay		= new \Nelexa\GPlay\GPlayApps( $defaultLocale = $post_language, $defaultCountry = '' ); 
		$appinfo		= $gplay->getAppInfo( $this->apk_id_alt );

		$app_names	= $appinfo->getName(); 
		
		
		return $app_names;
    }

	private function aArticles()
	{ 		
		$post_language 	= at_options('post_language', 'en-US');
		$gp			= 'https://play.google.com/store/apps/details?id='.$this->apk_id_alt.'&hl='.$post_language;
		$urlz		= 'https://a-a.my.id/gps.php?pkgid='.$this->apk_id_alt; 
		//$urlz1		= 'https://zplay.demos.web.id/gps/?pkgid='.$this->apk_id; 	
		
		$scraper 		= new Scraper(); 
		$get_infos	= $scraper->scrape_site($gp);	
		$g_data		= $scraper->scrape_site($urlz);	
		 
		$apk_articles2	= $scraper->match('/<div class="bARER".*?>(.*?)<\/div>.*?<div class="TKjAsc">/ms', $get_infos, 1);
		
		$gplay		= new \Nelexa\GPlay\GPlayApps( $defaultLocale = $post_language, $defaultCountry = '' ); 
		$appinfo		= $gplay->getAppInfo( $this->apk_id_alt );

		$apk_articles	= $appinfo->getDescription();
		
		return $apk_articles;
	}

	private function aTags()
	{ 		
		$post_language 	= at_options('post_language', 'en-US');
		$gp			= 'https://play.google.com/store/apps/details?id='.$this->apk_id_alt.'&hl='.$post_language;
		$urlz		= 'https://a-a.my.id/gps.php?pkgid='.$this->apk_id_alt; 
		//$urlz1		= 'https://zplay.demos.web.id/gps/?pkgid='.$this->apk_id; 	
		
		$scraper 		= new Scraper(); 
		$get_infos	= $scraper->scrape_site($gp);	
		$g_data		= $scraper->scrape_site($urlz);	

		$apk_tags		= $scraper->match_all('/<div.*?data-idom-class="Rj2Mlf OLiIxf PDpWxe P62QJc LQeN7 LMoCf">.*?<a.*?aria-label="(.*?)".*?><\/a>/ms', $scraper->match('/<div class="Uc6QCc">(.*?)<\/section>/ms', $get_infos, 1), 1);
				
		return $apk_tags;
	}

	public function __construct($post_meta)
	{
        $default_meta = [
			'apk_description' => '',
			'apk_whats_new' => '',
			'apk_name' => '',
			'apk_developer' => '',
			'apk_size' => '',
			'apk_version' => '',
			'apk_installs' => '',
			'apk_id' => '',
			'apk_id_alt' => '',
			'apk_rating_text' => '',
			'apk_total_votes' => '',
			'apk_screenshots' => [],
			'apk_thumbnail' => '',
			'apk_banner' => '',
			'apk_category' => '',
			'apk_sub_category' => '',
			'apk_content' => '',
			'apk_content_html' => '',
			'apk_content_rating' => '',
			'apk_required_version_text' => '',
			'apk_price' => '',
            'apt_id' => '',
			'apk_file_url' => '',
			'apk_updated' => '',
			'apk_updatex' => '',
			'apk_articles' => '',
			'apk_tags' => '',
			'apk_youtube' => '',
            'youtubeID' => '',
            'nVersion' => '',
            'aSize' => '',
            'aUpdate' => '',
            'aName' => '',
            'aArticles' => '',
            'aTags' => '',
            'apkID' => '',
        ];
 
		$data			= array_merge($default_meta, $post_meta['data']);
		
		$post_language 		= at_options('post_language', 'en-US');
		
		$this->is_advanced_options = at_options('is_advanced_options', false);
		 
		$this->apk_id 		= $data['apk_id']; 
		$this->apk_id_alt	= $data['apk_id_alt']; 
		//$this->apk_id		= $gp_url; 
		 
		
		if ($this->is_advanced_options) {
			
		$aArticles		= $this->aArticles();
		$aUpdate			= $this->aUpdate();
		$aName			= $this->aName();
		$nVersion			= $this->nVersion();
		$aSize			= $this->aSize();
		
		}
		
		$aTags			= $this->aTags();
		$youtubeID		= $this->youtubeID();
		$apkID			= $this->apkID();
		
		if(!empty($aTags)){
			$this->apk_tags	= $aTags;		
		} else {
			$this->apk_tags 	= '';
		}		
		
		if(!empty($data['apk_youtube'])){
			$this->apk_youtube 	= $data['apk_youtube'];		
		} else {
			$this->apk_youtube 	= $youtubeID;
		}		
		
		if(!empty($data['apk_content_html'])){
			$this->apk_articles = $data['apk_content_html'];
		} else {
			$this->apk_articles = $aArticles;
		}		
		
		if(!empty($data['apk_updated'])){
			$this->apk_updatex 	= $data['apk_updated'];		
		} else {
			$this->apk_updatex 	= $aUpdate;
		}		
		
		if(!empty($data['apk_name'])){
			$this->apk_name 	= $data['apk_name'];
		} else {
			$this->apk_name 	= $aName;
		}		
				
		if(!empty($data['apk_size'])){
			$this->apk_size 	= $data['apk_size'];
		} else {
			$this->apk_size 	= $aSize;
		}
		
		if(!empty($data['apk_version'])){
			$this->apk_version 	= $data['apk_version'];
		} else {
			$this->apk_version 	= $nVersion;
		}
		
		$this->apk_description 		= $data['apk_description'];
		$this->apk_whats_new 		= $data['apk_whats_new'];
		$this->apk_developer 		= $data['apk_developer'];
		$this->apk_rating 			= $data['apk_rating_text'];
		$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_content_html 	= $data['apk_content_html'];
		$this->apk_content_rating 	= $data['apk_content_rating'];
		$this->apk_required 		= $data['apk_required_version_text'];
		$this->apk_price 			= $data['apk_price']; 
		$this->apt_id 				= $data['apt_id'];
		$this->apk_file_url 		= $data['apk_file_url'];
		$this->apk_installs 		= $data['apk_installs'];


        if ($this->is_advanced_options) {
            $post_status 					= at_options('post_status');
            $post_thumbnail_format 			= at_options('post_thumbnail_format');
            $post_thumbnail_quality 		= at_options('post_thumbnail_quality');

            $import_screenshots 			= at_options('import_screenshots', false);
            $post_screenshots_format 		= at_options('post_screenshots_format');
            $import_ss_limit 				= at_options('import_ss_limit');

            $this->post_status 				= !empty($post_status) ? $post_status : '';
            $this->post_thumbnail_format 	= !empty($post_thumbnail_format) ? $post_thumbnail_format : '';
            $this->post_thumbnail_quality 	= !empty($post_thumbnail_quality) ? $post_thumbnail_quality : '';

            $this->import_screenshots 		= $import_screenshots ? $import_screenshots : false;
            $this->post_screenshots_format 	= $post_screenshots_format ? $post_screenshots_format : 'jpg';
            $this->import_ss_limit 			= $import_ss_limit ? $import_ss_limit : '5';
			
        }		 

    }

	private function generate_post_title()
    { 
        $main_title		= $this->apk_name;
        $post_title 	= $this->apk_name;       

        return $post_title;
    }

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

        $parent_cat_name = get_parsed_category($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 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()
    {
        update_post_meta( $this->post_id, "wp_title_GP", $this->apk_name);
		
		if(!empty($this->apk_id)){
        update_post_meta( $this->post_id, "wp_playstore_link", 'https://play.google.com/store/apps/details?id='.$this->apk_id);
        update_post_meta( $this->post_id, "wp_GP_ID", $this->apk_id);
		} else {
        update_post_meta( $this->post_id, "wp_playstore_link", 'https://play.google.com/store/apps/details?id='.$this->apk_id_alt);
        update_post_meta( $this->post_id, "wp_GP_ID", $this->apk_id_alt);
		}
		
        update_post_meta( $this->post_id, "wp_developers_GP", $this->apk_developer);
        update_post_meta( $this->post_id, "wp_version_GP", $this->apk_version);
        update_post_meta( $this->post_id, "wp_sizes_GP", $this->apk_size);
        update_post_meta( $this->post_id, "wp_sizes", $this->apk_size);
        update_post_meta( $this->post_id, "wp_contentrated_GP", $this->apk_content_rating);
        update_post_meta( $this->post_id, "wp_requires_GP", $this->apk_required);
        update_post_meta( $this->post_id, "wp_desck_GP", $this->apk_description);
        update_post_meta( $this->post_id, "wp_whatnews_GP", $this->apk_whats_new);
        update_post_meta( $this->post_id, "wp_updates_GP", $this->apk_updatex); 
        update_post_meta( $this->post_id, "wp_youtube_GP", $this->apk_youtube); 
		
        update_post_meta ($this->post_id, "wp_installs_GP", $this->apk_installs); 
		
		wp_set_object_terms( $this->post_id, $this->apk_tags, 'post_tag', true ); 
		$apk_prices				= '$'.$this->apk_price;
		$apk_prices				= str_replace('$0', '', $apk_prices);
        update_post_meta( $this->post_id, "wp_prices_gp", $apk_prices);
		
        update_post_meta( $this->post_id, "wp_rated_GP", floatval($this->apk_rating));
        update_post_meta( $this->post_id, "wp_ratings_GP", intval($this->apk_votes));

		wp_set_object_terms( $this->post_id, $this->apk_developer, 'developer', true ); 
		wp_set_object_terms( $this->post_id, $this->apk_name, 'post_tag', true ); 
		
		update_post_meta( $this->post_id, "wp_poster_GP", $this->apk_thumbnail_url);
		update_post_meta( $this->post_id, "wp_backgrounds_GP", $this->apk_banner_url);
		
		
    }

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

        if ($this->is_advanced_options) {
            if ($this->post_thumbnail_format === 'webp') {
                $image_quality = ($this->post_thumbnail_quality === 'raw') ? '=rw' : '-rw';
            }

            switch ($this->post_thumbnail_quality) {
                case '512':
                    $image_size = '=s512';
                    break;
                case '256':
                    $image_size = '=s256';
                    break;
                case '128':
                    $image_size = '=s128';
                    break;
            };
        }

        $thumbnail_id = $this->upload_image_to_wp($this->apk_thumbnail_url . $image_size . $image_quality, $this->post_thumbnail_format);

        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 . '=w1024-h500', 'jpg', 'banner');
            $banner_image = wp_get_attachment_url($banner_id);
            //update_post_meta($this->post_id, "wp_backgrounds_GP", $banner_image);			
			update_post_meta( $this->post_id, '_background_image_id', $banner_id);
			update_post_meta( $this->post_id, 'background_images', $banner_id);
        }
    }

	private function add_gallery_screenshots()
    { 
	 
		$post_language 		= at_options('post_language', 'en-US');
        $get_screenshots	= $this->apk_screenshots;
		 
        $image_quality = '';

        if ($this->post_screenshots_format === 'webp') {
            $image_quality = '=rw';
        }

		if ( !empty($get_screenshots) ) { 
		$gallery_image	= array(); 
			for ($i = 0; $i < count( $get_screenshots ); $i++ ) {
				if ( '' != $get_screenshots[$i] ) {$ss_name = 'screenshot-' . ($i + 1);
                    $ss_id = $this->upload_image_to_wp(esc_url($get_screenshots[$i]) . $image_quality, $this->post_screenshots_format, $ss_name);
					//$gallery_image['image_url'][] = $get_screenshots[$i];
					$gallery_image['image_url'][] = esc_url(wp_get_attachment_url($ss_id));
				}
			}
		add_post_meta( $this->post_id, 'gallery_data', $gallery_image ); 
		} 
		
    }
	 
	private function add_screenshots_meta()
    { 
		$import_ss_limit	= at_options('import_ss_limit', '5');
		$import_ss_limit2 	= (int) at_options('import_ss_limit', '5');
        $screenshots = array();
        $get_screenshots = $this->apk_screenshots;
        $image_quality = '';

        if ($this->post_screenshots_format === 'webp') {
            $image_quality = '=rw';
        }

        if ($this->is_advanced_options && $this->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]) . $image_quality, $this->post_screenshots_format, $ss_name);
                    $screenshots['image_url'][] = esc_url(wp_get_attachment_url($ss_id));
                }
            }
        } else {
            for ($i = 0; $i < $import_ss_limit; $i++) {
                if (!empty($get_screenshots[$i])) {
                    $screenshots['image_url'][] = esc_url($get_screenshots[$i] . $image_quality);
                }
            }
        }

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

    }
 
	private function ouo_io_exhemes($url) 
	{
		$apikey		= 'mH4aOrLs'; 
		$url 		= "http://ouo.io/api/{$apikey}?s=".urlencode($url);
		$ch 		= curl_init();
		curl_setopt($ch, CURLOPT_URL, $url);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
		curl_setopt($ch, CURLOPT_HEADER, FALSE);
		curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
		$response 	= curl_exec($ch);
		curl_close($ch);
		$html 		= @file_get_contents($url);
		if( $html ){
			return $html;
		}
	}

	private function add_download_meta()
    {
        $download_info = [];
        //$mod_feature = '';

        //if ($this->is_advanced_options && !empty($this->post_mod_feature)) {
        //    $mod_feature = $this->post_mod_feature;
        //}
		
		
		$link_apkz1	= 'https://play.google.com/store/apps/details?id='.$this->apk_id_alt; 
		$link_apkz	= 'https://exthem.es/apk.php?pkg='.$this->apk_id_alt; 
		$linkapks	= $this->ouo_io_exhemes($link_apkz); 
			
        $download_info_data = [
		
			'name'		=> ucfirst($this->apk_name).' APK ',
			'title' 	=> ucfirst($this->apk_name),
			'url'		=> $linkapks,
			'links' 	=> $linkapks,
			'sizes1' 	=> $this->apk_size,
			'sizes' 	=> $this->apk_size,
			'size' 		=> $this->apk_size,
			'tipes' 	=> '',
			'notes' 	=> '',
			
			/* 
            'download_name' => strtoupper($this->apk_name),
            'download_version' => $this->apk_version,
            'download_mod_info' => $mod_feature,
            'download_size' => $this->apk_size,
            'download_url' => 'https://play.google.com/store/apps/details?id=' . $this->apk_id,
			 */
			 
        ];

        array_push($download_info, $download_info_data);

        update_post_meta($this->post_id, "repeatable_fields", $download_info);
        update_post_meta($this->post_id, "group_downloads_links", $download_info);
    }


	public function create_post()
	{
		// 1. FIRST: CHECK FOR DUPLICATES
		$existing_post_id = $this->post_already_exists();

		if ($existing_post_id) {
        $permalink   = get_permalink($existing_post_id);
        $edit_link   = get_edit_post_link($existing_post_id);
        $image_id    = get_post_thumbnail_id($existing_post_id);
        $image_url   = $image_id ? wp_get_attachment_image_url($image_id, 'thumbnail') : '';

			return [
				'status' => 'info',
				'data'   => [
					'post_id'  => $existing_post_id,
					'message'  => '
					<div class="alert alert-info" style="background: white;border: 3px solid red;">
						<div class="icon hidden-xs">
							<img src="' . esc_url($image_url) . '" width="75" height="75" />
						</div>
						<h3>' . esc_html($this->apk_name) . ' - <b style="color: red;font-weight: bolder;">Already Exists!</b></h3> 
						<a href="' . esc_url($permalink) . '" target="_blank">View Post</a> -
						<a href="' . esc_url($edit_link) . '" target="_blank">Edit Post</a>
					</div>',
					'message2' => 'Duplicate prevented: ' . esc_html($this->apk_name) . ' (v' . esc_html($this->apk_version) . ') already exists.'
				]
			];
		}

		// 2. NO DUPLICATE → CONTINUE CREATING
		$post_permalink = $this->apk_name;
		$category       = $this->get_category();

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

		$post_id = wp_insert_post($new_post, true);

		if (is_wp_error($post_id)) {
			return [
				'status' => 'error',
				'data'   => ['message' => 'Insert failed: ' . $post_id->get_error_message()]
			];
		}

		$this->post_id = $post_id;

		// Save your unique identifier right after post creation (very important!)
		// update_post_meta( $post_id, 'wp_GP_ID', $this->apk_package_name); // e.g. com.whatsapp
		// update_post_meta( $post_id, 'wp_version_GP', $this->apk_version); // e.g. 2.25.100
		// or if you have a mod ID:
		// update_post_meta($post_id, '_apk_mod_id', $this->apk_mod_id);

		// Continue with the rest
		$this->add_meta_data();
		$this->upload_thumbnail();
		$this->upload_banner_image();
		$this->add_screenshots_meta();
		$this->add_download_meta();

		// Success message (same as before, just cleaned up)
		$image_id   = get_post_thumbnail_id($post_id);
		$image_url  = $image_id ? wp_get_attachment_image_url($image_id, 'thumbnail') : '';

		$response = [
			'status' => 'success',
			'data'   => [
				'post_id' => $post_id,
				'message' => '
	<div class="alert alert-success">
		<div class="icon hidden-xs">
			<img src="' . esc_url($image_url) . '" width="75" height="75" />
		</div>
		<h3>' . esc_html($this->apk_name) . '</h3>
		<a href="' . esc_url(get_permalink($post_id)) . '" target="_blank">View Post</a> -
		<a href="' . esc_url(get_edit_post_link($post_id)) . '" target="_blank">Edit Post</a>
	</div>',
				'message2' => '<strong><a href="' . esc_url(get_edit_post_link($post_id)) . '" target="_blank">' . esc_html($this->apk_name) . '</a></strong> uploaded successfully.'
			]
		];
		
		
		
		return $response;
	}

	private function post_already_exists()
	{
		// METHOD 1: Best – Check by package name + version (100% unique for APKs)
		if (!empty($this->apk_id_alt) && !empty($this->apk_version)) {
			$existing = get_posts([
				'post_type'   => 'post',
				'post_status' => 'any',
				'meta_query'  => [
					'relation' => 'AND',
					[
						'key'     => 'wp_GP_ID',
						'value'   => $this->apk_id_alt,
						'compare' => '='
					],
					[
						'key'     => 'wp_version_GP',
						'value'   => $this->apk_version,
						'compare' => '='
					]
				],
				'posts_per_page' => 1,
				'fields'         => 'ids'
			]);

			if (!empty($existing)) {
				return $existing[0];
			}
		}

		// METHOD 2: Fallback – Check by exact post title (less reliable but safe)
		$existing_by_title = get_posts([
			'post_type'   => 'post',
			'post_status' => 'any',
			'title'       => $this->generate_post_title(),
			'posts_per_page' => 1,
			'fields'         => 'ids'
		]);

		if (!empty($existing_by_title)) {
			return $existing_by_title[0];
		}

		return false; // No duplicate found
	}


	public function create_post2()
    {
        //$lic = new AT_License();

        //if ($lic->is_valid_license()) {
        //    $response = [
        //        'status' => 'error',
        //        'data' => [
        //            'message' => __('4 License Key is invalid or expired.', TEXT_DOMAIN),
        //        ],
        //    ];
        //    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);
        $post_content = $this->apk_content_html;
        //$post_content = $this->apk_articles;

        $new_post = [
            "post_title" => $this->generate_post_title(),
            "post_name" => $post_permalink,
            "post_content" => $post_content,
            "post_status" => $this->post_status,
            //"post_category" => [$category['parent_id'], $category['child_id']],
            "post_category" => [$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_gallery_screenshots();
		
        $this->add_screenshots_meta();

        $this->add_download_meta();
 
		$urlX				= get_permalink( $this->post_id );
		
		$image_id_alt		= get_post_thumbnail_id($post->ID); 
		$image_idx			= get_post_thumbnail_id($this->post_id); 
		$fullx				= 'thumbnail'; 
		$image_urlx			= wp_get_attachment_image_src($image_idx, $fullx, true); 
		$imagex				= $image_urlx[0]; 
		
        $response = [
            'status' => 'success',
            'data' => [
                'message' => '
<div class="alert alert-success" >  
    <div class="icon hidden-xs">
	<img src="' . $imagex . '" width="75" height="75">
    </div>
    <h3>' . $this->apk_name . '</h3>  
	<a style="text-decoration: none;" href="' . get_permalink( $this->post_id ) . '" target="_blank">view</a> - 
	<a style="text-decoration: none;" href="' . get_edit_post_link( $this->post_id ) . '" target="_blank">edit</a>
</div>',
				
                'message2' => '<strong><a href="' . get_edit_post_link( $this->post_id ) . '" target="_blank">' . $this->apk_name . '</a></strong> post uploaded.',
            ],
        ];

        return $response;
    }

}

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

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

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

    update_option('at_is_advanced_options', $is_advanced_options) || add_option('at_is_advanced_options', $is_advanced_options);

    $is_advanced_options = at_options('is_advanced_options', false);

    if ($is_advanced_options) {
        $post_status = sanitize_text_field($_POST['post_status']); 
        $post_thumbnail_format = sanitize_text_field($_POST['post_thumbnail_format']);
        $post_thumbnail_quality = sanitize_text_field($_POST['post_thumbnail_quality']);
        $import_screenshots = filter_var($_POST['import_screenshots'], FILTER_VALIDATE_BOOLEAN);
        $post_screenshots_format = sanitize_text_field($_POST['post_screenshots_format']);
        $post_language = sanitize_text_field($_POST['post_language']);
        $import_ss_limit = sanitize_text_field($_POST['import_ss_limit']);
 
        update_option('at_post_status', $post_status); 
        update_option('at_post_thumbnail_format', $post_thumbnail_format);
        update_option('at_post_thumbnail_quality', $post_thumbnail_quality);
        update_option('at_import_screenshots', $import_screenshots);
        update_option('at_post_screenshots_format', $post_screenshots_format);
        update_option('at_post_language', $post_language);
        update_option('at_import_ss_limit', $import_ss_limit);
    }

    $apk_data = new APEX_Google_Play();
    $response = $apk_data->extract($apk_url, 'apk');
    $response = json_encode($response);

    echo $response;
    exit;
}
add_action('wp_ajax_apex_gp_create_post', 'apex_gp_create_post');

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

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

    $search_query = strtolower($_POST['search_query']);
    $base_url = 'https://play.google.com/store/search?c=apps&q=';
    $search_url = $base_url . urlencode($search_query);

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

    exit;
}
add_action('wp_ajax_apex_gp_search_posts', 'apex_gp_search_posts');

function menu_gp_importer()
{
    $is_advanced_options 		= at_options('is_advanced_options', false);
    $post_status 				= at_options('post_status', 'draft');
    $post_thumbnail_format 		= at_options('post_thumbnail_format', 'png');
    $post_thumbnail_quality 	= at_options('post_thumbnail_quality', 'large');
    $import_screenshots 		= at_options('import_screenshots', false);
    $post_screenshots_format 	= at_options('post_screenshots_format', 'jpg');
    $post_language 				= at_options('post_language', 'en-US');
    $import_ss_limit 			= at_options('import_ss_limit', '5');
	
	
?>
 
 
  
<div id="at-importer">
    <div class="at-importer-container">
        <form method="POST" id="at-gp-importer-form">
            <div class="at-importer at-mb-3">
                <h2>Google Play Importer</h2>
                <div class="at-inline-ipt at-mt-2">
                    <input type="url" name="at_gp_url" id="at-gp-url" class="at-ipt-url" min="3"
                        placeholder="https://play.google.com/store/apps/details?id=com.roblox.client" required />
                    <button id="grab_button" type="submit" class="at-btn at-btn-success">
                        Import Content
                    </button>
                </div>
				
			<h2 style="text-align: left;margin: 10px 0;">How To</h2>
			
			<p class='howto'>
				Just insert <strong style="color: #2271b1;">Link Playstore</strong> from Google Play Store Apps. 
				<br>
				For example this link <strong style="color: #2271b1;">https://play.google.com/store/apps/details?id=com.roblox.client</strong> 
				<br>
				Go To Google Play Store <a href="https://play.google.com/store/games?device=phone" target="_blank">New Games</a> or <a href="https://play.google.com/store/apps?device=phone" target="_blank">New Apps </a>
			</p>
						
						
            </div>
			
            <div class="at-importer-results at-mb-3" style="display: none">
                <h3 class="at-mb-1" style="display: none">Log</h3>
                <ul class="alert process-log at-mb-1" style="display: none">

                </ul>
                <ul class="process-error-log" style="display: none">

                </ul>
            </div>
			
			<style>
			.alert.process-log.at-mb-1{
				    border: unset!important;
			}
			</style>
			
						
            <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_advanced_options" id="at_advanced_options"
                                <?php checked($is_advanced_options);?>>
                            <span class="at-switch"></span>
                        </label>
                    </div>
                </div>
				
                <table class="at-import-table at-mt-2" <?php if (!$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.  
                                    </code>
                                </p>
							</td>
						</tr>
                        <tr>
                            <td>
                                <h3>
                                    <?php esc_html_e('Post status', TEXT_DOMAIN);?>
                                </h3>
                                <select name="at_post_status" class="at-select">
                                    <option value="draft" <?php selected($post_status, 'draft'); ?>>Draft</option>
                                    <option value="publish" <?php selected($post_status, 'publish'); ?>>Publish</option>
                                </select>
                            </td>
                           
                            <td>
                                <h3>
                                    <?php esc_html_e('Post language', TEXT_DOMAIN);?>
                                </h3>
                                <select name="at_post_language" class="at-select">
                                    <option value="af" <?php selected($post_language, 'af');?>>Afrikaans</option>
                                    <option value="am" <?php selected($post_language, 'am');?>>Amharic</option>
                                    <option value="ar" <?php selected($post_language, 'ar');?>>Arabic</option>
                                    <option value="bg" <?php selected($post_language, 'bg');?>>Bulgarian</option>
                                    <option value="pt_BR" <?php selected($post_language, 'pt_BR');?>>Brazil</option>
		 
                                    <option value="ca" <?php selected($post_language, 'ca');?>>Catalan</option>
                                    <option value="zh-HK" <?php selected($post_language, 'zh-HK');?>>Chinese (Hong Kong)
                                    </option>
                                    <option value="zh-CN" <?php selected($post_language, 'zh-CN');?>>Chinese (PRC)</option>
                                    <option value="zh-TW" <?php selected($post_language, 'zh-TW');?>>Chinese (Taiwan)
                                    </option>
                                    <option value="hr" <?php selected($post_language, 'hr');?>>Croatian</option>
                                    <option value="cs" <?php selected($post_language, 'cs');?>>Czech</option>
                                    <option value="da" <?php selected($post_language, 'da');?>>Danish</option>
                                    <option value="nl" <?php selected($post_language, 'nl');?>>Dutch</option>
                                    <option value="en-GB" <?php selected($post_language, 'en-GB');?>>English (UK)</option>
                                    <option value="en-US" <?php selected($post_language, 'en-US');?>>English (US)</option>
                                    <option value="et" <?php selected($post_language, 'et');?>>Estonian</option>
                                    <option value="fil" <?php selected($post_language, 'fil');?>>Filipino</option>
                                    <option value="fi" <?php selected($post_language, 'fi');?>>Finnish</option>
                                    <option value="fr-CA" <?php selected($post_language, 'fr-CA');?>>French (Canada)
                                    </option>
                                    <option value="fr-FR" <?php selected($post_language, 'fr-FR');?>>French (France)
                                    </option>
                                    <option value="de" <?php selected($post_language, 'de');?>>German</option>
                                    <option value="el" <?php selected($post_language, 'el');?>>Greek</option>
                                    <option value="he" <?php selected($post_language, 'he');?>>Hebrew</option>
                                    <option value="hi" <?php selected($post_language, 'hi');?>>Hindi</option>
                                    <option value="hu" <?php selected($post_language, 'hu');?>>Hungarian</option>
                                    <option value="is" <?php selected($post_language, 'is');?>>Icelandic</option>
                                    <option value="id" <?php selected($post_language, 'id');?>>Indonesian</option>
                                    <option value="it" <?php selected($post_language, 'it');?>>Italian</option>
                                    <option value="ja" <?php selected($post_language, 'ja');?>>Japanese</option>
                                    <option value="ko" <?php selected($post_language, 'ko');?>>Korean</option>
                                    <option value="lv" <?php selected($post_language, 'lv');?>>Latvian</option>
                                    <option value="lt" <?php selected($post_language, 'lt');?>>Lithuanian</option>
                                    <option value="ms" <?php selected($post_language, 'ms');?>>Malay</option>
                                    <option value="ne" <?php selected($post_language, 'ne');?>>Netherlands</option>
                                    <option value="nl" <?php selected($post_language, 'nl');?>>Nepali</option>
                                    <option value="no" <?php selected($post_language, 'no');?>>Norwegian</option>
                                    <option value="fa" <?php selected($post_language, 'fa');?>>Persian</option>
                                    <option value="pl" <?php selected($post_language, 'pl');?>>Polish</option>
                                    
                                    <option value="pt-PT" <?php selected($post_language, 'pt-PT');?>>Portugal
                                    </option>
                                    <option value="pa" <?php selected($post_language, 'pa');?>>Punjabi</option>
                                    <option value="ro" <?php selected($post_language, 'ro');?>>Romanian</option>
                                    <option value="ru" <?php selected($post_language, 'ru');?>>Russian</option>
                                    <option value="sr" <?php selected($post_language, 'sr');?>>Serbian</option>
                                    <option value="sk" <?php selected($post_language, 'sk');?>>Slovak</option>
                                    <option value="sl" <?php selected($post_language, 'sl');?>>Slovenian</option>
                                    <option value="es-419" <?php selected($post_language, 'es-419');?>>Spanish (Latin America)</option>
                                    <option value="es-ES" <?php selected($post_language, 'es-ES');?>>Spanish (Spain)
                                    </option>
                                    <option value="sw" <?php selected($post_language, 'sw');?>>Swahili</option>
                                    <option value="sv" <?php selected($post_language, 'sv');?>>Swedish</option>
                                    <option value="ta" <?php selected($post_language, 'ta');?>>Tamil</option>
                                    <option value="te" <?php selected($post_language, 'te');?>>Telugu</option>
                                    <option value="th" <?php selected($post_language, 'th');?>>Thai</option>
                                    <option value="tr" <?php selected($post_language, 'tr');?>>Turkish</option>
                                    <option value="uk" <?php selected($post_language, 'uk');?>>Ukrainian</option>
                                    <option value="vi" <?php selected($post_language, 'vi');?>>Vietnamese</option>
                                    <option value="zu" <?php selected($post_language, 'zu');?>>Zulu</option>
                                </select>
                            </td>
							<!--<td style="display:none">
                                <h3>
                                    <?php esc_html_e('Post title starting text', TEXT_DOMAIN);?>
                                </h3>
                                <input type="text" name="at_post_title_start" class="at-ipt-text"
                                    value="<?php echo esc_attr($post_title_start); ?>"
                                    placeholder="Eg. [Start text] Spotify MOD APK" />
                            </td>
							<td style="display:none">
                                <h3>
                                    <?php esc_html_e('Post title ending text', TEXT_DOMAIN);?>
                                </h3>
                                <input type="text" name="at_post_title_end" class="at-ipt-text"
                                    value="<?php echo esc_attr($post_title_end); ?>"
                                    placeholder="Eg. Spotify MOD APK [End text]" />
                            </td>
                            <td style="display:none">
                                <h3>
                                    <?php esc_html_e('MOD Feature', TEXT_DOMAIN);?>
                                </h3>
                                <input type="text" name="at_mod_feature" class="at-ipt-text"
                                    value="<?php echo esc_attr($mod_feature); ?>"
                                    placeholder="Eg. Premium Unlocked">
                            </td>-->
                            <td>
                                <h3>
                                    <?php esc_html_e('Thumbnail format', TEXT_DOMAIN);?>
                                </h3>
                                <select name="at_post_thumbnail_format" class="at-select">
                                    <option value="png" <?php selected($post_thumbnail_format, 'png'); ?>>PNG (.png)</option>
                                    <option value="webp" <?php selected($post_thumbnail_format, 'webp'); ?>>WEBP (.webp)</option>
                                </select>
                            </td>
                            <td>
                                <h3>
                                    <?php esc_html_e('Thumbnail quality', TEXT_DOMAIN);?>
                                </h3>
                                <select name="at_post_thumbnail_quality" class="at-select">
                                    <option value="raw" <?php selected($post_thumbnail_quality, 'raw'); ?>>Original</option>
                                    <option value="512" <?php selected($post_thumbnail_quality, '512'); ?>>Large (512x512)</option>
                                    <option value="256" <?php selected($post_thumbnail_quality, '256'); ?>>Medium (256x256)</option>
                                    <option value="128" <?php selected($post_thumbnail_quality, '128'); ?>>Small (128x128) Recommeded</option>
                                </select>
                            </td>
                            <td>
                                <h3>
                                    <?php esc_html_e('Import Screenshots', TEXT_DOMAIN);?>
                                </h3>
                                <div class="at-btn-container">
                                    <label class="at-switch-btn">
                                        <input type="checkbox" name="at_import_screenshots" id="at_import_screenshots"
                                            <?php checked($import_screenshots);?>>
                                        <span class="at-switch"></span>
                                    </label>
                                </div>
                            </td>
                            <td>
                                <h3>
                                    <?php esc_html_e('Screenshots format', TEXT_DOMAIN);?>
                                </h3>
                                <select name="at_post_screenshots_format" class="at-select">
                                    <option value="jpg" <?php selected($post_screenshots_format, 'jpg'); ?>>JPEG (.jpg)</option>
                                    <option value="webp" <?php selected($post_screenshots_format, 'webp'); ?>>WEBP (.webp)</option>
                                </select>
                            </td> 
                            <td>
                                <h3>
                                    <?php esc_html_e('Screenshots Limit', TEXT_DOMAIN);?>
                                </h3>
								 <input type="number" name="at_import_ss_limit" id="at_import_ss_limit" min="1" max="50" value="<?php echo esc_html($import_ss_limit); ?>" />
                                 
                            </td> 
							
                        </tr>
                    </tbody>
                </table>
            </div>
        </form>
        <div class="at-apk-search">
            <div class="at-search-title">
                <h2>Search</h2>
            </div>
            <div class="at-inline-ipt at-mt-2 at-mb-2">
                <input type="url" id="at-gp-search-query" class="at-ipt-url" min="3" placeholder="E.g Spotify" required />
                <button id="at-gp-search-submit" class="at-btn at-btn-success">
                    Search
                </button>
            </div>
            <div id="at-gp-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
}

/* Initializations */
function at_options($option, $default = false)
{
    $value = get_option('at_' . $option, false);

    if ($value !== false) {
        return $value;
    } else {
        return ($default !== false) ? $default : '';
    }
}
   
function 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://m.apkpure.com",
    ));

    curl_exec($ch);

    $response_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);

    curl_close($ch);

    return $response_code === 200;
}

function validate_gplay_url($gplay_url)
{
    if (empty($gplay_url) || !strpos($gplay_url, 'play.google.com')) {
        return false;
    } else {
        return true;
    }
}

//https://play.google.com/store/apps/details?id=com.star.union.planetant&pcampaignid=merch_published_cluster_promotion_battlestar_evergreen_dynasty_games

function validate_gplay_id_in_url($gplay_url)
{
    if (preg_match("/\bid=([^\&]+)/", $gplay_url, $matches)) {
        return true;
    } else {
        return false;
    }
}

function get_parsed_category($category)
{
    $parent_category = __('Apps', TEXT_DOMAIN);

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

    return $parent_category;
}

function get_parsed_subcategory($category)
{
    $sub_category = '';

    if (!empty($category)) {
        $sub_category = strtolower(str_replace('GAME_', '', $category));
        $sub_category = str_replace('_', '-', $sub_category);
    }

    return $sub_category;
}

function get_android_version_by_sdk($sdk_version)
{
    $android_versions = [
        1 => '1.0',
        2 => '1.1',
        3 => '1.5',
        4 => '1.6',
        5 => '2.0',
        6 => '2.0.1',
        7 => '2.1',
        8 => '2.2',
        9 => '2.3',
        10 => '2.3.3',
        11 => '3.0',
        12 => '3.1',
        13 => '3.2',
        14 => '4.0',
        15 => '4.0.3',
        16 => '4.1',
        17 => '4.2',
        18 => '4.3',
        19 => '4.4',
        20 => '4.4W',
        21 => '5.0',
        22 => '5.1',
        23 => '6.0',
        24 => '7.0',
        25 => '7.1',
        26 => '8.0',
        27 => '8.1',
        28 => '9.0',
        29 => '10.0',
        30 => '11.0',
        31 => '12.0',
        32 => '12.1',
        33 => '13.0',
        34 => '14.0',
    ];

    return isset($android_versions[$sdk_version]) ? $android_versions[$sdk_version] : '';
}

/* Panel */
function is_server_setting_valid($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 get_term_name_by_id($term_id)
{
    $term_info = get_term(intval($term_id));

    if (!is_wp_error($term_info) && isset($term_info->name)) {
        return esc_html($term_info->name);
    }

    return '';
}

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

function 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));
}
