<?php
class MHP_YAS_Core {

    public static function run_import($base_url, $omdb_key, $bump_date = true, $only_changed = false) {
        $log = array();
        $failed_summary = array();
        $main_log = array();
        $start = microtime(true);

        if (empty($base_url) || empty($omdb_key)) {
            return "ERROR: base_url یا omdb_key خالی است.\n";
        }
        if (substr($base_url, -1) !== '/') $base_url .= '/';

        $html = self::http_get($base_url);
        if ($html === false) {
            return "ERROR: دریافت لیست از URL ناموفق بود.\n";
        }

        $folders = self::parse_directory_folders($html, $base_url);
        $log[] = "📁 پوشه‌های شناسایی‌شده: " . count($folders);
        if (empty($folders)) {
            return implode("\n", $log) . "\n✅ پایان عملیات";
        }

        foreach ($folders as $folder_name => $folder_url) {
            $main_log[] = "\n------------------------------";
            $main_log[] = "🔹 پوشه: $folder_url";
            $main_log[] = "📁 نام پوشه: $folder_name";

            list($guess_title, $guess_year) = self::extract_title_year($folder_name);
            if (!$guess_title || !$guess_year) {
                $failed_summary[] = "❗ پوشه {$folder_name} — عنوان یا سال معتبر پیدا نشد.";
                continue;
            }
            $main_log[] = "🎬 عنوان: {$guess_title} ({$guess_year})";

            $sub_html = self::http_get($folder_url);
            if ($sub_html === false) {
                $failed_summary[] = "⛔ دریافت محتویات پوشه {$folder_name} ناموفق.";
                continue;
            }

            $files = self::parse_directory_files($sub_html, $folder_url);
            $main_log[] = "🔹 فایل‌ها: " . count($files);
            if (empty($files)) {
                $failed_summary[] = "⛔ فایل یافت نشد در {$folder_name}.";
                continue;
            }

            $videos = array(); $sub_srt = '';
            foreach ($files as $furl => $fname) {
                $lname = strtolower($fname);
                if (preg_match('/\.srt$/i', $fname)) { $sub_srt = $furl; continue; }
                if (!preg_match('/\.(mp4|mkv|avi|mov)$/i', $fname)) continue;

                if (stripos($lname, 'hdts') !== false) {
                    $main_log[] = "ℹ️ رد شد (HDTS): $fname";
                    continue;
                }

                $is_trailer = (strpos($lname, 'trailer') !== false);
                $type = (strpos($lname,'dub') !== false || strpos($lname,'dubbed') !== false) ? 'dub' :
                        ((strpos($lname,'softsub') !== false || strpos($lname,'hardsub') !== false || strpos($lname,'sub') !== false) ? 'sub' : null);
                if (!$type && !$is_trailer) continue;

                $quality = self::extract_quality($lname);
                if (!$is_trailer && !$quality) continue;

                $size_text = self::get_remote_size_text_simple($furl);

                $videos[] = array(
                    'url' => $furl,
                    'type' => $type ? $type : 'sub',
                    'quality' => $quality ? $quality : 0,
                    'is_trailer' => $is_trailer,
                    'size_text' => $size_text,
                );
            }

            if (empty($videos)) {
                $failed_summary[] = "⚠️ لینک ویدیویی معتبر پیدا نشد در {$folder_name}.";
                continue;
            }

            $info = self::fetch_omdb($guess_title, $guess_year, $omdb_key);
            if (!$info || (isset($info['Response']) && $info['Response'] === 'False')) {
                $failed_summary[] = "⛔ OMDb ناموفق برای «{$guess_title} ({$guess_year})»";
                continue;
            }

            $imdb_id = !empty($info['imdbID']) ? $info['imdbID'] : '';
            $title_for_post = !empty($info['Title']) ? $info['Title'] : $guess_title;
            $year_for_post  = !empty($info['Year'])  ? $info['Year'] : $guess_year;

            $post_id = self::get_post_by_imdb($imdb_id);
            if ($post_id) {
                $main_log[] = "FOUND: پست موجود (ID={$post_id}) → بررسی و بروزرسانی";
                if ($bump_date) {
                    wp_update_post(array(
                        'ID' => $post_id,
                        'post_date' => current_time('mysql'),
                        'post_date_gmt' => get_gmt_from_date(current_time('mysql')),
                    ));
                    $main_log[] = "OK: تاریخ پست بروزرسانی شد (بامپ).";
                }
            } else {
                $post_title = "دانلود فیلم {$title_for_post} {$year_for_post}";
                $post_id = wp_insert_post(array(
                    'post_type' => 'movies',
                    'post_status' => 'publish',
                    'post_title' => wp_strip_all_tags($post_title),
                    'post_content' => '',
                ), true);

                if (is_wp_error($post_id) || !$post_id) {
                    $failed_summary[] = "ERROR: ایجاد پست ناموفق برای {$folder_name}.";
                    continue;
                }
                $main_log[] = "OK: پست ساخته شد (ID={$post_id})";

                if (!empty($info['Poster']) && filter_var($info['Poster'], FILTER_VALIDATE_URL)) {
                    $thumb_id = self::sideload_image_to_post($info['Poster'], $post_id, !empty($info['Title']) ? $info['Title'] : '');
                    if ($thumb_id) {
                        set_post_thumbnail($post_id, $thumb_id);
                        $main_log[] = "OK: پوستر sideload شد (attachment_id={$thumb_id})";
                    } else {
                        $alt_id = self::sideload_image_to_post_alternative($info['Poster'], $post_id, $info['Title'] ?? '');
                        if ($alt_id) {
                            set_post_thumbnail($post_id, $alt_id);
                            $main_log[] = "OK: پوستر sideload شد با روش جایگزین (attachment_id={$alt_id})";
                        } else {
                            $main_log[] = "WARN: sideload پوستر ناموفق بود.";
                        }
                    }
                }
            }

            self::update_meta_if_empty($post_id, 'director_movie', $info['Director'] ?? '');
            self::update_meta_if_empty($post_id, 'genre_movie', $info['Genre'] ?? '');
            self::update_meta_if_empty($post_id, 'runtime_movie', self::normalize_runtime($info['Runtime'] ?? ''));
            self::update_meta_if_empty($post_id, 'title_movie', $info['Title'] ?? $guess_title);
            self::update_meta_if_empty($post_id, 'imdbid_movie', $imdb_id);
            self::update_meta_if_empty($post_id, 'stars_movie', $info['Actors'] ?? '');
            self::update_meta_if_empty($post_id, 'imdb_rate_movie', $info['imdbRating'] ?? '');
            self::update_meta_if_empty($post_id, 'age_movie', $info['Rated'] ?? '');
            self::update_meta_if_empty($post_id, 'en_plot_movie', $info['Plot'] ?? '');
            $fa_plot = get_post_meta($post_id, 'fa_plot_movie', true);
            if (empty($fa_plot) && !empty($info['Plot'])) {
                $translated = self::google_translate($info['Plot'], 'fa');
                if (!empty($translated)) {
                    update_post_meta($post_id, 'fa_plot_movie', $translated);
                }
            }
            if (!empty($info['Year'] ?? $guess_year) && taxonomy_exists('release')) {
                wp_set_post_terms($post_id, array($info['Year'] ?? $guess_year), 'release', false);
            }
            if (!empty($info['Country'] ?? '') && taxonomy_exists('country')) {
                wp_set_post_terms($post_id, explode(',', $info['Country']), 'country', false);
            }
            if (!empty($info['Language'] ?? '') && taxonomy_exists('language')) {
                wp_set_post_terms($post_id, explode(',', $info['Language']), 'language', false);
            }

            $has_dub = false; $has_sub = false;
            foreach ($videos as $vv) {
                if (!$vv['is_trailer'] && $vv['type'] === 'dub') $has_dub = true;
                if (!$vv['is_trailer'] && $vv['type'] === 'sub') $has_sub = true;
            }
            update_post_meta($post_id, 'playonline_active', 'on');
            if ($has_sub) update_post_meta($post_id, 'has_subtitle', 'on');
            if ($has_dub) update_post_meta($post_id, 'has_dubbed', 'on');

            self::append_people_terms($post_id, 'actor', $info['Actors'] ?? '');
            self::append_people_terms($post_id, 'director', $info['Director'] ?? '');
            if (taxonomy_exists('genre')) self::append_people_terms($post_id, 'genre', $info['Genre'] ?? '');

            usort($videos, function($a, $b){ return intval($b['quality']) - intval($a['quality']); });
            list($playlinks_add, $dlbox_add, $trailers) = self::build_links($videos, $sub_srt);

            self::merge_meta_list($post_id, 'movies_playlinks', $playlinks_add, 'play_link');
            self::merge_meta_list($post_id, 'movies_dlbox', $dlbox_add, 'dl_link');

            if (!empty($trailers)) {
                $first_trailer = preg_replace('/^http:\/\//i','https://',$trailers[0]);
                $current_trailer = get_post_meta($post_id, 'trailer_movie', true);
                if ($current_trailer !== $first_trailer) {
                    update_post_meta($post_id,'trailer_movie', esc_url_raw($first_trailer));
                    self::save_trailers_to_table($post_id, array($first_trailer));
                    $main_log[] = "OK: تریلر ذخیره شد: {$first_trailer}";
                } else {
                    $main_log[] = "ℹ️ تریلر تکراری بود، تغییری انجام نشد.";
                }
            }

            $main_log[] = "✅ پایان پوشه: {$folder_name}";
        }

        $end = microtime(true);

        $final = array();
        if (!empty($failed_summary)) {
            $final[] = "❌ پوشه‌های ناموفق:";
            foreach ($failed_summary as $fs) $final[] = $fs;
            $final[] = "----------------------------";
        }

        $final = array_merge($final, $main_log);
        $final[] = "\n== پایان ==";
        $final[] = "زمان کل: " . round($end - $start, 2) . " ثانیه";

        return implode("\n", $final);
    }

    // ===================== تمام توابع کمکی yas yas =====================

    private static function http_get($url) {
        $args = array('timeout'=>20,'redirection'=>5,'headers'=>array('Accept'=>'text/html'));
        $res = wp_remote_get($url, $args);
        if (is_wp_error($res)) return false;
        if (wp_remote_retrieve_response_code($res) !== 200) return false;
        return wp_remote_retrieve_body($res);
    }

    private static function http_head($url) {
        $args = array('method'=>'HEAD','timeout'=>12,'redirection'=>3);
        $res = wp_remote_request($url, $args);
        if (is_wp_error($res)) return false;
        return $res;
    }

    private static function get_remote_size_text_simple($url) {
        $res = self::http_head($url);
        if (!$res) return '';
        $len = wp_remote_retrieve_header($res, 'content-length');
        if (!$len) return '';
        $bytes = (float) $len;
        if ($bytes <= 0) return '';
        $mb = $bytes / (1024 * 1024);
        $mb_int = (int) round($mb);
        if ($mb_int >= 1000) {
            $gb = (int) round($mb_int / 1000);
            return $gb . ' GB';
        }
        return $mb_int . ' MB';
    }

    private static function parse_directory_folders($html, $base_url) {
        $folders = array();
        if (preg_match_all('~<a\s+href="([^"]+/)"[^>]*>~i', $html, $m)) {
            foreach ($m[1] as $href) {
                if ($href === './' || $href === '../') continue;
                $full = self::abs_url($href, $base_url);
                $folder_name = trim(urldecode(basename(rtrim($href, '/'))));
                $folders[$folder_name] = $full;
            }
        }
        return $folders;
    }

    private static function parse_directory_files($html, $base_url) {
        $files = array();
        if (preg_match_all('~<a\s+href="([^"]+)"[^>]*>~i', $html, $m)) {
            foreach ($m[1] as $href) {
                if (substr($href, -1) === '/') continue;
                $files[self::abs_url($href, $base_url)] = trim(urldecode(basename($href)));
            }
        }
        return $files;
    }

    private static function abs_url($href, $base) {
        if (preg_match('~^https?://~i', $href)) return $href;
        if (substr($href,0,1) === '/') {
            $p = wp_parse_url($base);
            return $p['scheme'] . '://' . $p['host'] . $href;
        }
        return rtrim($base, '/') . '/' . ltrim($href, '/');
    }

    private static function extract_title_year($folder_name) {
        $name = preg_replace('/[._-]+/', ' ', $folder_name);
        if (preg_match('/\b(19|20)\d{2}\b/', $name, $ym)) {
            $year = $ym[0];
            $title = trim(preg_replace('/\b(19|20)\d{2}\b.*/', '', $name));
            return array($title, $year);
        }
        return array(null, null);
    }

    private static function extract_quality($lower_name) {
        if (preg_match('/\b(2160|1080|720|480|360)\s*p?\b/', $lower_name, $m)) return intval($m[1]);
        return 0;
    }

    private static function fetch_omdb($title, $year, $key) {
        $args = array('timeout'=>18,'redirection'=>3);
        $url = add_query_arg(array('t'=>$title,'y'=>$year,'plot'=>'full','apikey'=>$key), 'https://www.omdbapi.com/');
        $res = wp_remote_get($url, $args);
        if (!is_wp_error($res) && wp_remote_retrieve_response_code($res) == 200) {
            $data = json_decode(wp_remote_retrieve_body($res), true);
            if ($data && (!isset($data['Response']) || $data['Response'] !== 'False')) return $data;
        }
        $urlS = add_query_arg(array('s'=>$title,'y'=>$year,'type'=>'movie','apikey'=>$key), 'https://www.omdbapi.com/');
        $resS = wp_remote_get($urlS, $args);
        if (!is_wp_error($resS) && wp_remote_retrieve_response_code($resS) == 200) {
            $dataS = json_decode(wp_remote_retrieve_body($resS), true);
            if (!empty($dataS['Search'][0]['imdbID'])) {
                $iid = $dataS['Search'][0]['imdbID'];
                $urlI = add_query_arg(array('i'=>$iid,'plot'=>'full','apikey'=>$key), 'https://www.omdbapi.com/');
                $resI = wp_remote_get($urlI, $args);
                if (!is_wp_error($resI) && wp_remote_retrieve_response_code($resI) == 200) {
                    $dataI = json_decode(wp_remote_retrieve_body($resI), true);
                    if ($dataI && (!isset($dataI['Response']) || $dataI['Response'] !== 'False')) return $dataI;
                }
            }
        }
        return null;
    }

    private static function normalize_runtime($runtime_text) {
        if (preg_match('/(\d+)/', $runtime_text, $m)) return $m[1];
        return '';
    }

    private static function update_meta_if_empty($post_id, $key, $val) {
        if ($val === null) $val = '';
        $cur = get_post_meta($post_id, $key, true);
        if ($cur === '' || $cur === null) update_post_meta($post_id, $key, $val);
    }

    private static function sideload_image_to_post($image_url, $post_id, $desc = '') {
        if (!function_exists('media_handle_sideload')) {
            require_once ABSPATH . 'wp-admin/includes/media.php';
            require_once ABSPATH . 'wp-admin/includes/file.php';
            require_once ABSPATH . 'wp-admin/includes/image.php';
        }
        $tmp = download_url($image_url);
        if (is_wp_error($tmp)) return 0;
        $file_array = array('name' => basename(parse_url($image_url, PHP_URL_PATH)), 'tmp_name' => $tmp);
        if (is_wp_error($file_array['tmp_name'])) { @unlink($tmp); return 0; }
        $att_id = media_handle_sideload($file_array, $post_id, $desc);
        if (is_wp_error($att_id)) { @unlink($tmp); return 0; }
        return $att_id;
    }

    private static function sideload_image_to_post_alternative($image_url, $post_id, $desc = '') {
        require_once ABSPATH . 'wp-admin/includes/media.php';
        require_once ABSPATH . 'wp-admin/includes/file.php';
        require_once ABSPATH . 'wp-admin/includes/image.php';

        $tmp = download_url($image_url);
        if (is_wp_error($tmp)) return 0;
        $file = array(
            'name'     => basename(parse_url($image_url, PHP_URL_PATH)),
            'tmp_name' => $tmp
        );
        $overrides = array('test_form' => false);
        $results = wp_handle_sideload($file, $overrides);
        if (!empty($results['error'])) { @unlink($tmp); return 0; }
        $filetype = wp_check_filetype($results['file'], null);
        $attachment = array(
            'post_mime_type' => $filetype['type'],
            'post_title'     => sanitize_file_name($results['file']),
            'post_content'   => '',
            'post_status'    => 'inherit'
        );
        $attach_id = wp_insert_attachment($attachment, $results['file'], $post_id);
        if (!function_exists('wp_generate_attachment_metadata')) return 0;
        $metadata = wp_generate_attachment_metadata($attach_id, $results['file']);
        wp_update_attachment_metadata($attach_id, $metadata);
        return $attach_id;
    }

    private static function get_post_by_imdb($imdb_id) {
        global $wpdb;
        $pid = $wpdb->get_var($wpdb->prepare("SELECT post_id FROM {$wpdb->postmeta} WHERE meta_key='imdbid_movie' AND meta_value=%s LIMIT 1", $imdb_id));
        return $pid ? intval($pid) : 0;
    }

    private static function append_people_terms($post_id, $taxonomy, $csv_names) {
        if (empty($csv_names) || !taxonomy_exists($taxonomy)) return;
        $current = wp_get_post_terms($post_id, $taxonomy, array('fields' => 'names'));
        if (!is_array($current)) $current = array();
        $names = array_filter(array_map('trim', explode(',', $csv_names)));
        $to_add = array_diff($names, $current);
        if (!empty($to_add)) wp_set_object_terms($post_id, $to_add, $taxonomy, true);
    }

    private static function build_links($videos, $sub_srt) {
        $play = array(); $dl = array(); $trailers = array();
        foreach ($videos as $v) {
            if (!empty($v['is_trailer'])) { $trailers[] = $v['url']; continue; }
            $qnum = intval($v['quality']);
            $qtxt = $qnum ? ($qnum . 'p') : '';
            $type = ($v['type'] === 'dub') ? 'dub' : 'sub';

            $play[] = array(
                'play_link' => $v['url'],
                'fasub_link' => ($type === 'sub' && $sub_srt) ? $sub_srt : '',
                'ensub_link' => '',
                'quality_link' => (string) ($qnum ? $qnum : ''),
                'type_link' => $type,
            );

            $dl[] = array(
                'dl_link' => $v['url'],
                'quality_link' => $qtxt,
                'dl_capacity' => (!empty($v['size_text']) ? $v['size_text'] : self::get_remote_size_text_simple($v['url'])),
                'encoder_link' => '0',
                'dl_quality_example' => '',
                'dl_sound' => '',
                'dl_sub' => ($type === 'sub' && $sub_srt) ? $sub_srt : '',
                'link_type' => $type,
                'sub_type' => ($type === 'sub' ? 'SoftSub' : ''),
                'dl_price' => '',
            );
        }
        $trailers = array_values(array_unique($trailers));
        return array($play, $dl, $trailers);
    }

    private static function merge_meta_list($post_id, $meta_key, $add_items, $unique_field) {
        $existing = get_post_meta($post_id, $meta_key, true);
        if (!is_array($existing)) $existing = array();

        $result = array();
        foreach ($existing as $it) {
            if (is_array($it) && array_filter($it)) $result[] = $it;
        }

        foreach ($add_items as $new) {
            if (empty($new) || !is_array($new)) continue;

            if (!empty($new[$unique_field]) && stripos($new[$unique_field], 'hdts') !== false) continue;
            if (!empty($new['play_link']) && stripos($new['play_link'], 'hdts') !== false) continue;
            if (!empty($new['dl_link']) && stripos($new['dl_link'], 'hdts') !== false) continue;

            $new_quality = isset($new['quality_link']) ? (string)$new['quality_link'] : '';
            $new_type = $new['type_link'] ?? ($new['link_type'] ?? '');

            if ($new_quality !== '' && $new_type !== '') {
                $filtered = array();
                foreach ($result as $exist) {
                    $exist_quality = isset($exist['quality_link']) ? (string)$exist['quality_link'] : '';
                    $exist_type = $exist['type_link'] ?? ($exist['link_type'] ?? '');
                    if ($exist_quality === $new_quality && $exist_type === $new_type) {
                        continue;
                    }
                    $filtered[] = $exist;
                }
                $result = $filtered;
                $is_dup = false;
                if (!empty($new[$unique_field])) {
                    foreach ($result as $exist) {
                        if (!empty($exist[$unique_field]) && $exist[$unique_field] === $new[$unique_field]) { $is_dup = true; break; }
                    }
                }
                if (!$is_dup) $result[] = $new;
            } else {
                $is_duplicate = false;
                if (!empty($new[$unique_field])) {
                    foreach ($result as $exist) {
                        if (!empty($exist[$unique_field]) && $exist[$unique_field] === $new[$unique_field]) {
                            $is_duplicate = true; break;
                        }
                    }
                }
                if (!$is_duplicate) $result[] = $new;
            }
        }

        $result = array_filter($result, function($item){
            if (!is_array($item) || empty($item)) return false;
            return (bool) array_filter($item, function($v){ return $v !== '' && $v !== null; });
        });

        update_post_meta($post_id, $meta_key, array_values($result));
    }

    public static function maybe_create_trailer_table() {
        global $wpdb;
        $table = $wpdb->prefix . 'movie_trailer';
        $charset = $wpdb->get_charset_collate();
        $sql = "CREATE TABLE IF NOT EXISTS `{$table}` (
            `id` BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
            `post_id` BIGINT UNSIGNED NOT NULL,
            `url` VARCHAR(1024) NOT NULL,
            `created_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
            PRIMARY KEY (`id`),
            UNIQUE KEY `post_url_unique` (`post_id`,`url`)
        ) $charset;";
        require_once ABSPATH . 'wp-admin/includes/upgrade.php';
        dbDelta($sql);
    }

    private static function save_trailers_to_table($post_id, $urls) {
        global $wpdb;
        $table = $wpdb->prefix . 'movie_trailer';
        foreach ($urls as $u) {
            if (!filter_var($u, FILTER_VALIDATE_URL)) continue;
            $wpdb->query($wpdb->prepare("INSERT IGNORE INTO {$table} (post_id,url) VALUES (%d,%s)", $post_id, $u));
        }
    }

    private static function google_translate($text, $target = 'fa') {
        $api_url = "https://translate.googleapis.com/translate_a/single?client=gtx&sl=auto&tl={$target}&dt=t&q=" . urlencode($text);
        $response = wp_remote_get($api_url);
        if (is_wp_error($response)) return '';
        $body = wp_remote_retrieve_body($response);
        $json = json_decode($body, true);
        return $json[0][0][0] ?? '';
    }
}