<?php
/**
 * Class APK_Post_Importer
 * 
 * Class utama untuk mengimpor data aplikasi/game dari scraping (Google Play + situs lain)
 * ke dalam WordPress post, termasuk gambar, meta, kategori, dan link download.
 */

class APK_Post_Importer {

    private $data;           // Data hasil scraping ($gets_data)
    private $options;        // $opt_themes (pengaturan tema/Redux)
    private $post_id = 0;
    private $errors = [];

    public function __construct(array $scraped_data, array $theme_options = []) {
        global $opt_themes;
        
        $this->data    = $scraped_data;
        $this->options = !empty($theme_options) ? $theme_options : $opt_themes;
    }

    /**
     * Method utama: Jalankan seluruh proses import
     * 
     * @return int|WP_Error Post ID jika berhasil, WP_Error jika gagal
     */
    public function run() {
        if (empty($this->data) || !empty($this->data['error'])) {
            return new WP_Error('scrape_failed', 'Scrape failed: ' . ($this->data['error'] ?? 'Unknown error'));
        }

        // 1. Tentukan judul dan konten
        $title_source   = $this->get_primary_title();
        $post_content   = $this->get_post_content();
        $post_status    = $this->options['apk_status'] ?? 'publish';
        $post_type      = 'post';

        // 2. Cek duplikat berdasarkan judul yang sudah dibersihkan
        $clean_title = $this->clean_title($title_source);

        $existing = get_posts([
            'post_type'      => $post_type,
            'post_status'    => 'publish',
            'title'          => $clean_title,
            'posts_per_page' => 1,
            'fields'         => 'ids',
            'no_found_rows'  => true,
        ]);

        if (!empty($existing)) {
            // Update post yang sudah ada
            $this->post_id = $existing[0];
            $result = wp_update_post([
                'ID'           => $this->post_id,
                'post_title'   => $title_source,
                'post_content' => $post_content,
                'post_status'  => $post_status,
            ], true);
        } else {
            // Buat post baru
            $this->post_id = wp_insert_post([
                'post_title'   => $title_source,
                'post_content' => $post_content,
                'post_status'  => $post_status,
                'post_type'    => $post_type,
                'post_author'  => get_current_user_id() ?: 1,
            ], true);
        }

        if (is_wp_error($this->post_id)) {
            return $this->post_id; // Langsung return error dari wp_insert_post / wp_update_post
        }

        // 3. Proses gambar & gallery
        $this->handle_featured_image();
        $this->handle_background_image();
        $this->handle_screenshots();

        // 4. Simpan semua meta data
        $this->save_all_meta();

        // 5. Atur kategori (parent + child)
        $this->set_categories();

        // 6. Proses & simpan download links		 
		$this->add_external_apk_link();
		
        //$this->_5play_download();
		
        // 7. Set tag judul aplikasi
        if (!empty($this->data['title_GP'])) {
            wp_set_object_terms($this->post_id, $this->data['title_GP'], 'post_tag', true);
        }

        return $this->post_id;
    }

    // ────────────────────────────────────────────────────────────────────────────────
    // HELPER METHODS
    // ────────────────────────────────────────────────────────────────────────────────

    private function get_primary_title() {
        return !empty($this->data['title_GP']) 
            ? trim($this->data['title_GP']) 
            : trim($this->data['app_name'] ?? '');
    }

    private function clean_title($title) {
        $clean = wp_strip_all_tags($title);
        $clean = html_entity_decode($clean, ENT_QUOTES, 'UTF-8');
        return trim($clean);
    }

    private function get_post_content() {
        if (!empty($this->options['content_post'])) {
            return $this->data['article_content'] ?? '';
        }
        return !empty($this->data['articlebody_GP']) 
            ? $this->data['articlebody_GP'] 
            : ($this->data['article_content'] ?? '');
    }

    private function handle_featured_image() {
        $poster = !empty($this->data['poster_GP']) ? $this->data['poster_GP'] : ($this->data['poster_sc'] ?? '');
        if (empty($poster)) return;

        $title_GP = $this->get_primary_title();
        $filename = $this->post_id . '-' . sanitize_title_with_dashes_and_no_special_chars($title_GP) . '.webp';

        $attach_id = $this->upload_remote_image($poster, $filename);
        if ($attach_id && !is_wp_error($attach_id)) {
            set_post_thumbnail($this->post_id, $attach_id);
        }
    }

    private function handle_background_image() {
        if (empty($this->data['backgrounds_GP'])) return;

        $title_GP = $this->get_primary_title();
        $filename = $this->post_id . '-' . sanitize_title_with_dashes_and_no_special_chars($title_GP) . '-bg.webp';

        $attach_id = $this->upload_remote_image($this->data['backgrounds_GP'], $filename);
        if ($attach_id && !is_wp_error($attach_id)) {
            update_post_meta($this->post_id, '_background_image_id', $attach_id);
            update_post_meta($this->post_id, 'background_images', $attach_id);
        }
    }

    private function handle_screenshots() {
        if (empty($this->data['images_GP'])) return;

        $limit = (int) ($this->options['import_ss_limit'] ?? 5);
        $gallery = ['image_url' => []];

        for ($i = 0; $i < $limit && isset($this->data['images_GP'][$i]); $i++) {
            $img_url = $this->data['images_GP'][$i];
            if (empty($img_url)) continue;

            if (!empty($this->options['import_screenshots'])) {
                $name = $this->generate_screenshot_name($i);
                $attach_id = upload_images_to_wp(esc_url($img_url), 'webp', $name);
                if ($attach_id && !is_wp_error($attach_id)) {
                    $gallery['image_url'][] = wp_get_attachment_url($attach_id);
                }
            } else {
                $gallery['image_url'][] = $img_url;
            }
        }

        if (!empty($gallery['image_url'])) {
            update_post_meta($this->post_id, 'gallery_data', $gallery);
        }
    }

    private function generate_screenshot_name($index) {
        $title = sanitize_title_with_dashes_and_no_special_chars($this->get_primary_title());
        $alpha = $this->random_alpha_numeric(5);
        return "{$title}-{$alpha}=screenshot-" . ($index + 1);
    }

    private function random_alpha_numeric($length = 5) {
        $chars = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
        return substr(str_shuffle($chars), 0, $length);
    }

    private function upload_remote_image($url, $filename) {
        $upload_dir = wp_upload_dir();
        $upload_path = $upload_dir['path'] . '/' . $filename;

        $contents = @file_get_contents($url);
        if ($contents === false) return new WP_Error('download_failed', 'Failed to download image');

        $saved = @file_put_contents($upload_path, $contents);
        if ($saved === false) return new WP_Error('save_failed', 'Failed to save image');

        $filetype = wp_check_filetype(basename($filename), null);

        $attachment = [
            'post_mime_type' => $filetype['type'],
            'post_title'     => $filename,
            'post_content'   => '',
            'post_status'    => 'inherit'
        ];

        $attach_id = wp_insert_attachment($attachment, $upload_path);
        if (is_wp_error($attach_id)) return $attach_id;

        require_once ABSPATH . 'wp-admin/includes/image.php';
        $attach_data = wp_generate_attachment_metadata($attach_id, $upload_path);
        wp_update_attachment_metadata($attach_id, $attach_data);

        return $attach_id;
    }

    private function save_all_meta() {
        $fields = [
            'GP_ID'            => 'wp_GP_ID',
            'title_GP'         => 'wp_title_GP',
            'images_GP'        => 'wp_images_GP',
            'backgrounds_GP'   => 'wp_backgrounds_GP',
            'poster_GP'        => 'wp_poster_GP',
            'poster_sc'        => 'wp_poster_GP', // fallback
            'youtube_GP'       => 'wp_youtube_GP',
            'whatnews_GP'      => 'wp_whatnews_GP',
            'installs_GP'      => 'wp_installs_GP',
            'updates_GP'       => 'wp_updates_GP',
            'numbervoters'     => 'wp_ratings_GP',
            'numberrates'      => 'wp_rated_GP',
            'desck_GP'         => 'wp_desck_GP',
            'summary_sc'       => 'wp_desck_GP', // fallback
            'articlebody_GP'   => 'wp_articlebody_GP',
            'version_GP'       => 'wp_version_GP',
            'sizes_GP'         => ['wp_sizes_GP', 'wp_sizes'],
            'requires_GP'      => 'wp_requires_GP',
            'mods'             => 'wp_mods',
            'full_mod_title'   => 'wp_title_wp_mods',
            'full_mod'         => ['wp_mods_post', 'wp_mods2'],
        ];

        foreach ($fields as $key => $meta_key) {
            if (!isset($this->data[$key])) continue;

            $value = $this->data[$key];

            if ($key === 'developers_GP' || $key === 'developer_sc') {
                $value = str_replace([',', '.'], ' ', $value);
                wp_set_post_terms($this->post_id, $value, 'developer');
                wp_set_object_terms($this->post_id, $value, 'developer', true);
            }

            if (is_array($meta_key)) {
                foreach ($meta_key as $m) {
                    update_post_meta($this->post_id, $m, $value);
                }
            } else {
                update_post_meta($this->post_id, $meta_key, $value);
            }
        }

        // Play Store link
        if (!empty($this->data['GP_ID'])) {
            update_post_meta($this->post_id, 'wp_playstore_link', 'https://play.google.com/store/apps/details?id=' . $this->data['GP_ID']);
        }
    }

    private function set_categories() {
        $parent_name = trim($this->data['p_category'] ?? '');
        $child_name  = trim($this->data['genres_GP'] ?? '');

        if (empty($parent_name)) return;

        $parent = get_term_by('slug', sanitize_title($parent_name), 'category');
        if (!$parent) {
            $result = wp_insert_term($parent_name, 'category', ['slug' => sanitize_title($parent_name)]);
            if (!is_wp_error($result)) {
                $parent_id = $result['term_id'];
            } else {
                return;
            }
        } else {
            $parent_id = $parent->term_id;
        }

        wp_set_object_terms($this->post_id, [$parent_id], 'category', true);

        if (empty($child_name)) return;

        $child = get_term_by('slug', sanitize_title($child_name), 'category');
        if (!$child) {
            $result = wp_insert_term($child_name, 'category', [
                'parent' => $parent_id,
                'slug'   => sanitize_title($child_name)
            ]);
            if (!is_wp_error($result)) {
                $child_id = $result['term_id'];
            } else {
                return;
            }
        } else {
            $child_id = $child->term_id;
        }

        wp_set_object_terms($this->post_id, [$child_id], 'category', false);
    }
	
	private function add_external_apk_link() {
		// Pastikan GP_ID ada, kalau tidak maka skip
		if (empty($this->data['GP_ID'])) {
			return;
		}

		// Tentukan ukuran file
		$size_dwz = !empty($this->data['sizes_GP'])
			? $this->data['sizes_GP']
			: ($this->data['size_sc'] ?? '');

		// Tentukan judul link
		$title_dwz = !empty($this->data['title_GP'])
			? $this->data['title_GP'] . ' Apk'
			: ($this->data['app_name'] . ' Apk' );

		// Generate link dengan shortener ouo_io_exhemes
		$linkapkz = ouo_io_exhemes('https://exthem.es/apk.php?pkg=' . $this->data['GP_ID']);

		// (opsional) Jika ingin menyimpan varian lain, bisa diaktifkan kembali
		// $linkapkz1 = adurl_exhemes('https://exthem.es/apk.php?pkg=' . $this->data['GP_ID']);
		// $linkapkz2 = ouo_io_exhemes('https://play.google.com/store/apps/details?id=' . $this->data['GP_ID']);

		// Struktur data link eksternal
		$external_link = [
			'name'   => $title_dwz,
			'title'  => $title_dwz,
			'url'    => $linkapkz,
			'links'  => $linkapkz,
			'sizes1' => $size_dwz,
			'sizes'  => $size_dwz,
			'size'   => $size_dwz,
			'tipes'  => '',
			'notes'  => '',
		];

		// Tambahkan ke array download links
		$download_links[] = $external_link;

		// Simpan ulang ke post meta (karena array sudah berubah)
		update_post_meta($this->post_id, 'repeatable_fields', $download_links);
		update_post_meta($this->post_id, 'group_downloads_links', $download_links);
	}
	
	/* 
    private function _5play_download() {
        $download_links = [];

        $count = count($this->data['downloadlinks_gma'] ?? []);
        for ($i = 0; $i < $count; $i++) {
            $original_url = trim($this->data['downloadlinks_gma'][$i] ?? '');
            if (empty($original_url)) continue;

            $original_url = esc_url_raw($original_url);

            // Size logic
            $size = !empty($this->data['size_downloadlinks_gma'][$i])
                ? wp_strip_all_tags($this->data['size_downloadlinks_gma'][$i])
                : (!empty($this->data['size_sc'])
                    ? wp_strip_all_tags($this->data['size_sc'])
                    : wp_strip_all_tags($this->data['sizes_GP'] ?? ''));

            // Extension
            $full_path = $this->data['types_downloadlinks_gma'][$i] ?? $original_url;
            $ext = pathinfo(parse_url($full_path, PHP_URL_PATH), PATHINFO_EXTENSION);
            $type = !empty($ext) ? strtoupper($ext) : '';

            // Upload APK jika diaktifkan
            $final_url = $original_url;
            if (!empty($this->options['import_apk'])) {
                $attach_id = upload_remote_file_apk($original_url, $this->post_id);
                if (!is_wp_error($attach_id)) {
                    $final_url = wp_get_attachment_url($attach_id);
                }
            }

            // Shortlink
            $short_url = $final_url;
            if (!empty($this->options['enable_shortlinks'])) {
                $service = $this->options['auto_shortlink'] ?? 'ouo_sl';
                switch ($service) {
                    case 'ouo_sl':       $short_url = ouo_io_user($original_url); break;
                    case 'shrinkearn_sl': $short_url = shrinkearn_user($original_url); break;
                    case 'paid4link_sl':  $short_url = paid4link_user($original_url); break;
                    case 'adurl_sl':      $short_url = adurl_user($original_url); break;
                }
            }

            $link_url = esc_url($short_url) ?: $final_url;

            $download_links[] = [
                'name'  => sanitize_text_field($this->data['name_downloadlinks_gma'][$i] ?? ''),
                'title' => sanitize_text_field($this->data['name_downloadlinks_gma'][$i] ?? ''),
                'url'   => $link_url,
                'links' => $link_url,
                'size'  => $size,
                'tipes' => $type,
                'notes' => sanitize_text_field($this->data['notes_downloadlinks_gma'][$i] ?? ''),
            ];
        }
		
		$this->add_external_apk_link($download_links);
    }
	*/
 
    /**
     * Mendapatkan post ID yang berhasil dibuat/diperbarui
     */
    public function get_post_id() {
        return $this->post_id;
    }

    /**
     * Mendapatkan error jika ada
     */
    public function get_errors() {
        return $this->errors;
    }
}