import pymysql, time, requests
import urllib.parse
from multiprocessing import Pool
import phpserialize
import json
from datetime import datetime

# تابع کمکی برای گرفتن کانکشن جدید
def get_connection():
    return pymysql.connect(
        host='127.0.0.1',
        user='sql_seo2024_ir',
        password='1bd0d20735dfd8',
        database='sql_seo2024_ir',
        connect_timeout=10
    )

def movie_update_text(postid, txt):
    try:
        connection = get_connection()
        with connection.cursor() as cursor:
            check_query = """
                SELECT meta_value
                FROM wp_postmeta
                WHERE post_id = %s AND meta_key = %s
            """
            cursor.execute(check_query, (postid, 'movie_update_text'))
            result = cursor.fetchone()

            if result:
                sql_update_meta = """
                    UPDATE wp_postmeta
                    SET meta_value = %s
                    WHERE post_id = %s AND meta_key = %s
                """
                cursor.execute(sql_update_meta, (str(txt), postid, 'movie_update_text'))
            else:
                sql_insert_meta = """
                    INSERT INTO wp_postmeta (post_id, meta_key, meta_value)
                    VALUES (%s, %s, %s)
                """
                cursor.execute(sql_insert_meta, (postid, 'movie_update_text', str(txt)))
            connection.commit()
    except Exception as e:
        print(f"Error in movie_update_text for postid {postid}: {e}")
    finally:
        connection.close()

def doble(postid, txt):
    try:
        connection = get_connection()
        with connection.cursor() as cursor:
            sql_insert_meta = """
                UPDATE wp_posts
                SET post_content = %s
                WHERE ID = %s 
            """
            cursor.execute(sql_insert_meta, (str(txt), postid))
            connection.commit()
    except Exception as e:
        print(e)
    finally:
        connection.close()

def has_dubbed(links, post_id):
    try:
        connection = get_connection()
        with connection.cursor() as cursor:
            print(f"Checking dubbed status for post_id {post_id}")
            for l in links:
                if 'dubbed' in str(l[-3]).lower():
                    sql_insert_meta_post = """
                        INSERT INTO wp_postmeta (post_id, meta_key, meta_value)
                        VALUES (%s, %s, %s)
                    """
                    cursor.execute(sql_insert_meta_post, (post_id, 'has_dubbed', 'on'))
                    connection.commit()
                    print(f"Set has_dubbed to 'on' for post_id {post_id}")
                    return
    except Exception as e:
        print(f"Error in has_dubbed for post_id {post_id}: {e}")
    finally:
        connection.close()

def old_txt(postid):
    try:
        connection = get_connection()
        with connection.cursor() as cursor:
            query = "SELECT * FROM wp_postmeta WHERE post_id = %s AND meta_key = %s"
            cursor.execute(query, (postid, 'movies_dlbox'))
            result = cursor.fetchall()
            if not result:
                return
            links = result[0][3]
            python_data = phpserialize.loads(links.encode(), decode_strings=True)
            json_data = json.loads(json.dumps(python_data, ensure_ascii=False, indent=4))
            for key, value in json_data.items():
                link = value['dl_link']
                if 'Dubbed' not in link:
                    go = True
                    with open('linkss.txt', 'r') as lines:
                        for line in lines:
                            if str(link.split('/')[-1].replace('.mp4', '')) in line:
                                go = False
                                break
                    if go:
                        with open('old.txt', 'a') as add:
                            add.write(link.strip() + '\n')
    except Exception as e:
        print(f"Error in old_txt for postid {postid}: {e}")
    finally:
        connection.close()

def update_date(post_id):
    try:
        connection = get_connection()
        new_post_date = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
        new_post_date_gmt = datetime.utcnow().strftime('%Y-%m-%d %H:%M:%S')
        with connection.cursor() as cursor:
            query = """
                UPDATE wp_posts
                SET post_date = %s, post_date_gmt = %s
                WHERE ID = %s
            """
            cursor.execute(query, (new_post_date, new_post_date_gmt, post_id))
            connection.commit()
    except Exception as e:
        print(f"Error updating post {post_id}: {e}")
    finally:
        connection.close()
