<?php
// Assuming these variables are already defined elsewhere:
// $gets_data['title_GP']    - Title from Google Play / source
// $post_article             - Post content
// $opt_themes['apk_status'] - publish/draft/etc
// $types                    - Your custom post type, e.g. 'apk'

global $opt_themes;

// Determine the primary title source (prefer Google Play data if available)
if (!empty($gets_data['title_GP'])) {
    //$post_title_source 		= trim($gets_data['title_GP']);
} elseif (!empty($gets_data['app_name'])) {
    //$post_title_source 		= trim($gets_data['app_name']);
} else {
    //$post_title_source 		= trim($arr['app_name']);
}

$post_title_source 			= trim($gets_data['title_GP']);

$post_status				= $opt_themes['apk_status'];
$post_title					= $opt_themes['apk_title']; 
$types         				= 'post';
$post_type         			= $types;

// Clean and standardize title to avoid duplicates due to formatting
$title_post					= $gets_data[$post_title];
$clean_title 				= wp_strip_all_tags($title_post);
$clean_title 				= html_entity_decode($clean_title, ENT_QUOTES, 'UTF-8');

// Better duplicate check using WP_Query (works with any post type)
$existing_post		= get_posts(array(
    'post_type'              => $post_type,
    'post_status'            => array('publish'),
    'title'                  => $clean_title,
    'posts_per_page'         => 1,
    'fields'                 => 'ids',
    'no_found_rows'          => true,
    'update_post_meta_cache' => false,
    'update_post_term_cache' => false,
));

$post_id			= 0;

if (empty($existing_post)) {
    // Create new post
    $post_args = array(
        'post_title'   => $post_title_source,
        'post_content' => $post_article,
        'post_status'  => $post_status,
        'post_type'    => $post_type,
        'post_author'  => get_current_user_id(), // optional
    );

    $post_id 	= wp_insert_post($post_args, true); // true = return WP_Error on failure

    //if (is_wp_error($post_id)) {
        //error_log('WP Insert Post Error: ' . $post_id->get_error_message());
    //} else {
        //error_log("New post created: ID $post_id - $post_title_source");
    //}

} else {
    // Update existing post
    $post_id 	= $existing_post[0];

    $post_args 	= array(
        'ID'           => $post_id,
        'post_title'   => $post_title_source,
        'post_content' => $post_article,
        'post_status'  => $post_status,
    );

    $updated 	= wp_update_post($post_args, true);

    //if (is_wp_error($updated)) {
        //error_log('WP Update Post Error: ' . $updated->get_error_message());
    //} else {
        //error_log("Post updated: ID $post_id - $post_title_source");
    //}
}
