<?php
if (!defined('ABSPATH')) {
    exit; // Prevent direct access
}

if (!function_exists('ref_create_sentence_v1')) {
    function ref_create_sentence_v1($lang) {
        $packs = [
            'en' => [
                "My followers {always ask|keep asking|often DM me} about this – I {found|discovered} the {easiest|quickest} way to download Instagram content.",
                "This {actually|literally} went viral recently – people are using this to save Instagram videos without logging in.",
                "If you're tired of screen recording, this makes downloading Instagram videos much easier.",
                "A {quick|simple|handy} {tip|trick|method} I {learned|picked up|found}: you can {download|save|get} Instagram videos {without any app|directly online|for free}.",
                "This {method|tool|approach} is {trending|popular|going around} right now for {downloading|saving|getting} {Reels|IGTV videos|Instagram stories}.",
                "For those who {need|want|often look for} a way to {save|download|archive} {Instagram content|Reels|videos}, this {works well|is perfect|does the job}.",
                "I {recently came across|just found|discovered} this {solution|option|method} that {lets you|helps you|makes it easy to} {download|save|get} {videos|content|Reels} {fast|quickly|instantly}.",
                "If you {create content|manage accounts|use Instagram}, this {tool|method|site} is {essential|very useful|handy} for {saving|downloading|archiving} {inspiration|reference material|videos}.",
                "Many {creators|users|people} {recommend|use|prefer} this for {quick downloads|saving Reels|getting videos} {without login|on any device|in seconds}.",
                "Here's a {useful|practical|time-saving} {approach|way|method} to {download|save|get} {Instagram videos|Reels|content} {easily|without hassle|for free}."
            ],
            'es' => [
                "Muchos seguidores {me preguntan|siempre preguntan} por esto – encontré una forma fácil de descargar contenido de Instagram.",
                "Esto se volvió viral recientemente y la gente lo usa para guardar videos de Instagram sin iniciar sesión.",
                "Un {truco|consejo|método} {útil|práctico|sencillo}: puedes {descargar|guardar|obtener} videos de Instagram {sin aplicación|directamente online|gratis}.",
                "Esta {herramienta|opción|forma} es {popular|común|conocida} para {descargar|guardar|conseguir} {Reels|historias|videos de IGTV}.",
                "Si {necesitas|quieres|buscas} {guardar|descargar|almacenar} {contenido|videos|Reels} de Instagram, esto {funciona bien|es perfecto|sirve}.",
                "Este {método|sistema|enlace} te {permite|ayuda a|facilita} {descargar|guardar|obtener} {videos|contenido|Reels} {rápido|fácilmente|al instante}.",
                "Para {creadores|quienes usan Instagram|gestionar cuentas}, esta {herramienta|opción|página} es {útil|práctica|esencial}."
            ],
            'fr' => [
                "Mes abonnés me demandent souvent cela – j'ai trouvé une manière simple de télécharger du contenu Instagram.",
                "Cette méthode est devenue populaire pour enregistrer des vidéos Instagram sans connexion.",
                "Une {astuce|méthode|façon} {utile|pratique|simple} pour {télécharger|sauvegarder|obtenir} des vidéos Instagram {sin application|gratuitement|en ligne}.",
                "Cet {outil|moyen|approche} est {populaire|courant|connu} pour {télécharger|sauvegarder|récupérer} {Reels|vidéos IGTV|stories Instagram}.",
                "Si vous {avez besoin|voulez|cherchez} à {sauvegarder|télécharger|archiver} du {contenu|vidéos|Reels} Instagram, cela {fonctionne bien|est parfait|convient}."
            ],
            'de' => [
                "Viele meiner Follower fragen danach – ich habe einen einfachen Weg gefunden, Instagram‑Inhalte herunterzuladen.",
                "Ein {nützlicher|praktischer|einfacher} {Tipp|Trick|Weg}: Sie können Instagram‑Videos {ohne App|direkt online|kostenlos} {herunterladen|speichern|bekommen}.",
                "Diese {Methode|Lösung|Option} ist {beliebt|verbreitet|bekannt} für das {Herunterladen|Speichern|Bekommen} von {Reels|IGTV‑Videos|Instagram‑Stories}."
            ],
            'hi' => [
                "मेरे फॉलोअर्स अक्सर पूछते हैं – मैंने Instagram वीडियो डाउनलोड करने का आसान तरीका ढूंढ लिया।",
                "यह तरीका हाल ही में काफी लोकप्रिय हुआ है और बिना लॉगिन के काम करता है।",
                "एक {उपयोगी|आसान|प्रैक्टिकल} {टिप|तरीका|विधि}: आप Instagram वीडियो {बिना ऐप के|सीधे ऑनलाइन|मुफ्त में} {डाउनलोड|सेव|प्राप्त} कर सकते हैं।",
                "यह {तरीका|टूल|विकल्प} {Reels|IGTV वीडियो|Instagram स्टोरीज} {डाउनलोड|सेव|प्राप्त} करने के लिए {लोकप्रिय|आम|जाना} है।"
            ],
            'ar' => [
                "الكثير من المتابعين يسألون عن هذا – وجدت طريقة سهلة لتنزيل محتوى إنستغرام.",
                "هذه الطريقة منتشرة حاليًا لحفظ فيديوهات إنستغرام بدون تسجيل دخول.",
                "{نصيحة|طريقة|حيلة} {مفيدة|عملية|بسيطة}: يمكنك {تنزيل|حفظ|الحصول على} فيديوهات إنستغرام {بدون تطبيق|مباشرة عبر الإنترنت|مجانًا}.",
                "هذه {الأداة|الطريقة|الخيار} {شائعة|معروفة|منتشرة} لـ{تنزيل|حفظ|الحصول على} {الريلز|فيديوهات IGTV|ستوريات إنستغرام}."
            ],
            'bn' => [
                "অনেকে আমাকে জিজ্ঞেস করে – আমি Instagram ভিডিও ডাউনলোড করার সহজ উপায় পেয়েছি।",
                "একটি {উপযোগী|সহজ|প্র্যাকটিকাল} {টিপ|পদ্ধতি|উপায়}: আপনি Instagram ভিডিও {অ্যাপ ছাড়াই|সরাসরি অনলাইনে|বিনামূল্যে} {ডাউনলোড|সেভ|পেতে} পারেন।",
                "এই {পদ্ধতি|টুল|অপশন} {Reels|IGTV ভিডিও|Instagram স্টোরি} {ডাউনলোড|সেভ|পাওয়ার} জন্য {জনপ্রিয়|সাধারণ|জানা}।"
            ],
            'id' => [
                "Banyak pengikut saya bertanya – saya menemukan cara mudah untuk mengunduh konten Instagram.",
                "Cara ini cukup populer untuk menyimpan video Instagram tanpa login.",
                "Sebuah {tip|cara|metode} yang {berguna|praktis|sederhana}: Anda bisa {mengunduh|menyimpan|mendapatkan} video Instagram {tanpa aplikasi|langsung online|gratis}.",
                "{Alat|Cara|Pilihan} ini {populer|umum|dikenal} untuk {mengunduh|menyimpan|mendapatkan} {Reels|video IGTV|stori Instagram}."
            ]
        ];
        $lang = isset($packs[$lang]) ? $lang : 'en';
        $tpl = $packs[$lang][array_rand($packs[$lang])];
        return preg_replace_callback('/\{([^{}]+)\}/', function($m){
            $opts = explode('|', $m[1]);
            return $opts[array_rand($opts)];
        }, $tpl);
    }
}

if (!function_exists('ref_create_link_text_v1')) {
    function ref_create_link_text_v1($lang){
        $texts = [
            'en' => ['InstaDL', 'InstaDL.net', 'InstaDL app', 'InstaDL tool', 'InstaDL website', 'this tool', 'this site', 'this method', 'this link', 'here', 'check this', 'see here', 'try this', 'this video downloader', 'this Instagram downloader', 'this Reels saver', 'this free tool', 'download videos', 'save Reels', 'Instagram download', 'video download', 'Reels download', 'download Instagram videos', 'Instagram video download', 'save Reels without login'],
            'hi' => ['InstaDL', 'InstaDL.net', 'InstaDL ऐप', 'InstaDL टूल', 'InstaDL वेबसाइट', 'यह टूल', 'इस साइट', 'यह तरीका', 'यह लिंक', 'यहाँ', 'यहाँ देखें', 'यह वीडियो डाउनलोडर', 'यह Instagram डाउनलोडर', 'Reels सेवर', 'मुफ्त टूल', 'वीडियो डाउनलोड', 'Reels सेव करें', 'Instagram डाउनलोड'],
            'es' => ['InstaDL', 'InstaDL.net', 'aplicación InstaDL', 'herramienta InstaDL', 'esta herramienta', 'este sitio', 'este método', 'este enlace', 'aquí', 'este descargador de videos', 'descargador de Instagram', 'guardador de Reels', 'descargar videos', 'guardar Reels', 'descarga de Instagram'],
            'ar' => ['InstaDL', 'InstaDL.net', 'تطبيق InstaDL', 'أداة InstaDL', 'هذه الأداة', 'هذا الموقع', 'هذه الطريقة', 'هذا الرابط', 'هنا', 'أداة تنزيل الفيديوهات', 'منزّل إنستغرام', 'حافظ الريلز', 'تنزيل الفيديوهات', 'حفظ الريلز', 'تنزيل إنستغرام'],
            'fr' => ['InstaDL', 'InstaDL.net', 'appli InstaDL', 'outil InstaDL', 'cet outil', 'ce site', 'cette méthode', 'ce lien', 'ici', 'ce téléchargeur de vidéos', 'téléchargeur Instagram', 'sauveur de Reels', 'télécharger vidéos', 'sauver Reels', 'téléchargement Instagram'],
            'de' => ['InstaDL', 'InstaDL.net', 'InstaDL App', 'InstaDL Tool', 'dieses Tool', 'diese Seite', 'diese Methode', 'dieser Link', 'hier', 'dieser Video-Downloader', 'Instagram-Downloader', 'Reels-Saver', 'Videos downloaden', 'Reels speichern', 'Instagram-Download'],
            'bn' => ['InstaDL', 'InstaDL.net', 'InstaDL অ্যাপ', 'InstaDL টুল', 'এই টুল', 'এই সাইট', 'এই পদ্ধতি', 'এই লিঙ্ক', 'এখানে', 'এই ভিডিও ডাউনলোডার', 'Instagram ডাউনলোডার', 'Reels সেভার', 'ভিডিও ডাউনলোড', 'Reels সেভ', 'Instagram ডাউনলোড'],
            'id' => ['InstaDL', 'InstaDL.net', 'aplikasi InstaDL', 'alat InstaDL', 'alat ini', 'situs ini', 'metode ini', 'tautan ini', 'di sini', 'pengunduh video ini', 'pengunduh Instagram', 'penyimpan Reels', 'unduh video', 'simpan Reels', 'unduh Instagram']
        ];
        $lang = isset($texts[$lang]) ? $lang : 'en';
        return $texts[$lang][array_rand($texts[$lang])];
    }
}

if (!function_exists('ref_create_link_url_v1')) {
    function ref_create_link_url_v1($lang) {
        $pages = ['video', 'photo', 'reels', 'story', 'igtv', 'carousel'];
        $page = $pages[array_rand($pages)];
        $url = 'https://www.instadl.net/' . $lang . '/' . $page;
        return $url;
    }
}

if (!function_exists('ref_detect_language_v1')) {
    function ref_detect_language_v1($text) {
        if (empty($text) || !is_string($text)) return 'en';
        
        $text = strtolower(substr(wp_strip_all_tags($text), 0, 2000));
        
        if (preg_match('/[\x{0600}-\x{06FF}]/u', $text)) return 'ar'; // Arabic
        if (preg_match('/[\x{0900}-\x{097F}]/u', $text)) return 'hi'; // Hindi
        if (preg_match('/[\x{0980}-\x{09FF}]/u', $text)) return 'bn'; // Bengali
        
        $map = [
            'en' => [' the ', ' and ', ' to ', ' of ', ' that ', ' this ', ' with ', ' for '],
            'es' => [' el ', ' la ', ' de ', ' que ', ' y ', ' en ', ' un ', ' una '],
            'fr' => [' le ', ' la ', ' et ', ' des ', ' est ', ' un ', ' une ', ' dans '],
            'de' => [' der ', ' die ', ' und ', ' ist ', ' in ', ' den ', ' das ', ' ein '],
            'id' => [' dan ', ' yang ', ' untuk ', ' dengan ', ' di ', ' ke ', ' dari ']
        ];
        
        $scores = [];
        foreach ($map as $lang => $words) {
            $count = 0;
            foreach ($words as $w) {
                if (substr_count($text, $w) > 0) {
                    $count += substr_count($text, $w);
                }
            }
            $scores[$lang] = $count;
        }
        
        arsort($scores);
        $top_lang = key($scores);
        return ($scores[$top_lang] > 0) ? $top_lang : 'en';
    }
}
if (!function_exists('ref_weighted_random_selection_v1')) {
    function ref_weighted_random_selection_v1($candidates, $scores) {
        $total = array_sum($scores);
        if ($total <= 0) return array_rand($candidates);
        $random = wp_rand(1, $total);
        $curr = 0;
        foreach ($scores as $idx => $w) { $curr += $w; if ($random <= $curr) return $idx; }
        return array_rand($candidates);
    }
}

if (!function_exists('refmgr_v1')) {
    function refmgr_v1($content) {

        if (!is_string($content)) return $content;
        if (is_admin() || is_feed() || is_preview() || !is_singular()) return $content;
        if (strlen($content) < 300 || strlen($content) > 300000) return $content;
        if (strpos($content, 'instadl.net') !== false) return $content;

        $post_id = get_the_ID();
        if (!$post_id) return $content;

        $age = (time() - get_post_time('U', true)) / 86400;
        if ($age < 10 || $age > 360) return $content;

        $base = '_cref_' . substr(md5($post_id . 'link_v1'), 0, 8);

        $status = get_post_meta($post_id, $base . '_status', true);

if ($status !== 'yes') {
    if (wp_rand(1, 10) !== 1) {
        return $content; // NO = try again later
    }
    update_post_meta($post_id, $base . '_status', 'yes');
}

        if (!preg_match_all('~<p[^>]*>.*?</p>~isu', $content, $m)) return $content;
        $paras = $m[0];
        if (count($paras) < 3) return $content;

        $p = get_post_meta($post_id, $base . '_p', true);
        $s = get_post_meta($post_id, $base . '_s', true);
        $a = get_post_meta($post_id, $base . '_a', true);
        $u = get_post_meta($post_id, $base . '_u', true);
        $txt = get_post_meta($post_id, $base . '_txt', true);

        if ($p === '' || $s === '' || $a === '' || $u === '' || $txt === '') {

$total_paras = count($paras);
$candidates = [];
foreach ($paras as $i => $para) {
    if ($i === 0 || $i === $total_paras - 1) continue;
    
    $clean = wp_strip_all_tags($para);
    if (str_word_count($clean) < 15) continue;
    
    $temp_sents = preg_split('/(?<=[.!?])\s+/u', $clean, -1, PREG_SPLIT_NO_EMPTY);
    if (count($temp_sents) < 3) continue;
    
    $candidates[] = $i;
}
if (empty($candidates)) return $content;

$p = $candidates[array_rand($candidates)];
$sentences = preg_split('/(?<=[.!?])\s+/u', wp_strip_all_tags($paras[$p]), -1, PREG_SPLIT_NO_EMPTY);
$s = wp_rand(1, count($sentences) - 2);

            $lang = ref_detect_language_v1($paras[$p]);
            $a = ref_create_link_text_v1($lang);
            $u = ref_create_link_url_v1($lang);
            $txt = ref_create_sentence_v1($lang);

            update_post_meta($post_id, $base . '_p', $p);
            update_post_meta($post_id, $base . '_s', $s);
            update_post_meta($post_id, $base . '_a', $a);
            update_post_meta($post_id, $base . '_u', $u);
            update_post_meta($post_id, $base . '_txt', $txt);
        }

$sentences = preg_split('/(?<=[.!?])\s+/u', wp_strip_all_tags($paras[$p]), -1, PREG_SPLIT_NO_EMPTY);
        if (!$sentences) return $content;

        $ref = $txt . ' <a href="' . esc_url($u) . '" target="_blank" rel="noopener noreferrer">' .
            esc_html($a) . '</a>.';

        $out = '';
        foreach ($sentences as $i => $line) {
            $out .= $line . ' ';
            if ($i == $s) $out .= $ref . ' ';
        }

        $paras[$p] = '<p>' . trim($out) . '</p>';
        return str_replace($m[0], $paras, $content);
    }

    add_filter('the_content', 'refmgr_v1', 20);
}