from flask import Blueprint, render_template, request, redirect, url_for, flash, current_app, session, jsonify
from werkzeug.utils import secure_filename
from models import db, Word, Category, EnglishSynonym, ArabicSynonym, FurSynonym, User
from flask_login import login_required, login_user, logout_user, current_user
from datetime import datetime
import os
import tempfile
import subprocess
import shutil # <--- تمت إضافة هذا الاستيراد

admin_bp = Blueprint('admin', __name__, url_prefix='/admin')

def allowed_file(filename):
    return '.' in filename and \
           filename.rsplit('.', 1)[1].lower() in current_app.config['ALLOWED_AUDIO_EXTENSIONS']

@admin_bp.route('/login', methods=['GET', 'POST'])
def login():
    """صفحة تسجيل الدخول"""
    if current_user.is_authenticated:
        return redirect(url_for('admin.dashboard'))
    
    if request.method == 'POST':
        username = request.form['username']
        password = request.form['password']
        
        user = User.query.filter_by(username=username).first()
        
        if user and user.check_password(password) and user.is_active:
            login_user(user)
            user.last_login = datetime.utcnow()
            db.session.commit()
            
            next_page = request.args.get('next')
            if next_page:
                return redirect(next_page)
            return redirect(url_for('admin.dashboard'))
        else:
            flash('اسم المستخدم أو كلمة المرور غير صحيحة', 'error')
    
    return render_template('admin/login.html')

@admin_bp.route('/logout')
@login_required
def logout():
    """تسجيل الخروج"""
    logout_user()
    flash('تم تسجيل الخروج بنجاح', 'success')
    return redirect(url_for('admin.login'))

@admin_bp.route('/')
@login_required
def dashboard():
    """لوحة التحكم الرئيسية"""
    try:
        from datetime import datetime, date
        
        total_words = Word.query.count()
        active_words = Word.query.filter_by(is_active=True).count()
        inactive_words = Word.query.filter_by(is_active=False).count()
        print(total_words, active_words, inactive_words)
        # كلمات اليوم
        today = date.today()
        words_today = Word.query.filter(
            db.func.date(Word.created_at) == today
        ).count()
        
        # الكلمات المضافة حديثاً
        recent_words = Word.query.order_by(Word.created_at.desc()).limit(10).all()
        
        # إحصائيات إضافية
        words_with_audio = Word.query.filter(
            (Word.fur_audio_url.isnot(None)) | 
            (Word.english_audio_url.isnot(None))
        ).count()
        
        return render_template('admin/dashboard.html', 
                             total_words=total_words,
                             active_words=active_words,
                             inactive_words=inactive_words,
                             words_today=words_today,
                             words_with_audio=words_with_audio,
                             recent_words=recent_words)
    except Exception as e:
        print(f"Dashboard error: {e}")
        # إرجاع قيم افتراضية في حالة الخطأ
        return render_template('admin/dashboard.html', 
                             total_words=0,
                             active_words=0,
                             inactive_words=0,
                             words_today=0,
                             words_with_audio=0,
                             recent_words=[])

@admin_bp.route('/words')
@login_required
def words_list():
    """قائمة الكلمات"""
    page = request.args.get('page', 1, type=int)
    search = request.args.get('search', '')
    
    # إضافة فلتر للكلمات النشطة فقط
    query = Word.query.filter_by(is_active=True)
    
    if search:
        search_term = f'%{search}%'
        query = query.filter(
            db.or_(
                Word.fur_word.like(search_term),
                Word.arabic_word.like(search_term),
                Word.english_word.like(search_term)
            )
        )
    
    words = query.order_by(Word.created_at.desc()).paginate(
        page=page, per_page=20, error_out=False
    )
    
    return render_template('admin/words_list.html', words=words, search=search)

@admin_bp.route('/words/add', methods=['GET', 'POST'])
@login_required
def add_word():
    """إضافة كلمة جديدة"""
    if request.method == 'POST':
        try:
            fur_word = request.form['fur_word'].strip()
            arabic_word = request.form['arabic_word'].strip()
            english_word = request.form['english_word'].strip()
            
            # التحقق من وجود كلمة بنفس المعنى الإنجليزي والعربي
            existing_word = Word.query.filter(
                Word.arabic_word == arabic_word,
                Word.english_word == english_word
            ).first()
            
            if existing_word:
                flash(f'الكلمة موجودة بالفعل بنفس المعنى: {existing_word.fur_word} - {arabic_word} - {english_word}', 'warning')
                categories = Category.query.filter_by(is_active=True).all()
                return render_template('admin/add_word.html', categories=categories)
            
            # إنشاء الكلمة أولاً للحصول على الـ ID
            word = Word(
                fur_word=fur_word,
                arabic_word=arabic_word,
                english_word=english_word,
                category=request.form.get('category', ''),
                difficulty_level=int(request.form.get('difficulty_level', 1))
            )
            
            db.session.add(word)
            db.session.flush()  # للحصول على الـ ID بدون commit
            
            # معالجة ملفات الصوت المسجلة والمرفوعة
            fur_audio_url = None
            
            # معالجة التسجيل الصوتي للكلمة الفرية
            if 'fur_audio' in request.files:
                fur_recorded = request.files['fur_audio']
                if fur_recorded and fur_recorded.filename:
                    # حذف الملف القديم إذا كان موجوداً
                    if word.fur_audio_url:
                        old_audio_path = os.path.join(current_app.config['UPLOAD_FOLDER'], 
                                                     os.path.basename(word.fur_audio_url))
                        if os.path.exists(old_audio_path):
                            os.remove(old_audio_path)
                    
                    filename = f"fur_{word.id}.mp3"
                    fur_audio_path = os.path.join(current_app.config['UPLOAD_FOLDER'], filename)
                    
                    try:
                        with tempfile.NamedTemporaryFile(delete=False, suffix='.wav') as temp_file:
                            fur_recorded.save(temp_file.name)
                            temp_file.close()
                            # os.rename(temp_file.name, fur_audio_path) # <--- السطر الذي يسبب المشكلة
                            shutil.copy2(temp_file.name, fur_audio_path) # <--- التصحيح: نسخ الملف
                            os.unlink(temp_file.name) # <--- التصحيح: حذف الملف المؤقت

                            fur_audio_url = f'/static/audio/{filename}'
                            # ضغط الملف الصوتي بعد الحفظ
                            compress_audio_with_ffmpeg(fur_audio_path, fur_audio_path)
                    except Exception as e:
                        flash(f'خطأ في معالجة الملف الصوتي للكلمة الفرية: {str(e)}', 'error')
                    finally:
                        if temp_file and os.path.exists(temp_file.name):
                            try:
                                os.unlink(temp_file.name)
                            except Exception as cleanup_error:
                                print(f"Error deleting temp file: {cleanup_error}")
            
            # معالجة الملف المرفوع العادي للكلمة الفرية
            elif 'fur_audio_upload' in request.files:
                fur_audio = request.files['fur_audio_upload']
                if fur_audio and allowed_file(fur_audio.filename):
                    # حذف الملف القديم إذا كان موجوداً
                    if word.fur_audio_url:
                        old_audio_path = os.path.join(current_app.config['UPLOAD_FOLDER'], 
                                                     os.path.basename(word.fur_audio_url))
                        if os.path.exists(old_audio_path):
                            os.remove(old_audio_path)
                    
                    filename = f"fur_{word.id}.mp3"
                    fur_audio_path = os.path.join(current_app.config['UPLOAD_FOLDER'], filename)
                    
                    try:
                        with tempfile.NamedTemporaryFile(delete=False) as temp_file:
                            fur_audio.save(temp_file.name)
                            temp_file.close()
                            # os.rename(temp_file.name, fur_audio_path) # <--- السطر الذي يسبب المشكلة
                            shutil.copy2(temp_file.name, fur_audio_path) # <--- التصحيح: نسخ الملف
                            os.unlink(temp_file.name) # <--- التصحيح: حذف الملف المؤقت

                            fur_audio_url = f'/static/audio/{filename}'
                            # ضغط الملف الصوتي بعد الحفظ
                            compress_audio_with_ffmpeg(fur_audio_path, fur_audio_path)
                    except Exception as e:
                        flash(f'خطأ في معالجة الملف الصوتي للكلمة الفرية: {str(e)}', 'error')
                    finally:
                        if temp_file and os.path.exists(temp_file.name):
                            try:
                                os.unlink(temp_file.name)
                            except Exception as cleanup_error:
                                print(f"Error deleting temp file: {cleanup_error}")
            

            
            # تحديث الكلمة بمسارات الصوت
            word.fur_audio_url = fur_audio_url
            
            # معالجة المرادفات الإنجليزية
            english_synonyms_texts = request.form.getlist('english_synonym_text[]')
            english_synonym_ids = request.form.getlist('english_synonym_id[]')
            for i, synonym_text in enumerate(english_synonyms_texts):
                synonym_text = synonym_text.strip()
                synonym_id = english_synonym_ids[i] if i < len(english_synonym_ids) else None

                if synonym_text:
                    synonym_audio_url = None
                    # التحقق إذا كان هناك ملف صوتي جديد أو تسجيل مرفق لهذا المرادف
                    if f'english_synonym_audio_{i}' in request.files and request.files[f'english_synonym_audio_{i}'].filename:
                        synonym_audio = request.files[f'english_synonym_audio_{i}']
                        if synonym_audio and allowed_file(synonym_audio.filename):
                            filename = f"english_synonym_{word.id}_{i}.mp3"
                            synonym_audio_path = os.path.join(current_app.config['UPLOAD_FOLDER'], filename)
                            try:
                                with tempfile.NamedTemporaryFile(delete=False) as temp_file:
                                    synonym_audio.save(temp_file.name)
                                    temp_file.close()
                                    # os.rename(temp_file.name, synonym_audio_path) # <--- السطر الذي يسبب المشكلة
                                    shutil.copy2(temp_file.name, synonym_audio_path) # <--- التصحيح: نسخ الملف
                                    os.unlink(temp_file.name) # <--- التصحيح: حذف الملف المؤقت

                                    synonym_audio_url = f'/static/audio/{filename}'
                                    # ضغط الملف الصوتي للمرادف الإنجليزي بعد الحفظ
                                    compress_audio_with_ffmpeg(synonym_audio_path, synonym_audio_path)
                            except Exception as e:
                                flash(f'خطأ في معالجة الملف الصوتي للمرادف الإنجليزي {synonym_text}: {str(e)}', 'error')
                                print(f"Error processing English synonym audio: {e}")
                            finally:
                                if temp_file and os.path.exists(temp_file.name):
                                    try:
                                        os.unlink(temp_file.name)
                                    except Exception as cleanup_error:
                                        print(f"Error deleting English temp file: {cleanup_error}")

                    # إذا كان هناك ملف صوتي موجود ولم يتم رفع ملف جديد، احتفظ بالملف القديم
                    elif synonym_id:
                        existing_synonym = db.session.get(EnglishSynonym, synonym_id)
                        if existing_synonym:
                            synonym_audio_url = existing_synonym.audio_url

                    # إنشاء أو تحديث المرادف
                    if synonym_id:
                        # تحديث مرادف موجود
                        synonym = db.session.get(EnglishSynonym, synonym_id)
                        if synonym:
                            synonym.synonym_text = synonym_text
                            synonym.audio_url = synonym_audio_url
                    else:
                        # إضافة مرادف جديد
                        new_english_synonym = EnglishSynonym(
                            word_id=word.id,
                            synonym_text=synonym_text,
                            audio_url=synonym_audio_url
                        )
                        db.session.add(new_english_synonym)

            # معالجة المرادفات العربية
            arabic_synonyms_texts = request.form.getlist('arabic_synonym_text[]')
            arabic_synonym_ids = request.form.getlist('arabic_synonym_id[]')
            for i, synonym_text in enumerate(arabic_synonyms_texts):
                synonym_text = synonym_text.strip()
                synonym_id = arabic_synonym_ids[i] if i < len(arabic_synonym_ids) else None

                if synonym_text:
                    if synonym_id:
                        # تحديث مرادف موجود
                        synonym = db.session.get(ArabicSynonym, synonym_id)
                        if synonym:
                            synonym.synonym_text = synonym_text
                    else:
                        # إضافة مرادف جديد
                        new_arabic_synonym = ArabicSynonym(
                            word_id=word.id,
                            synonym_text=synonym_text
                        )
                        db.session.add(new_arabic_synonym)

            # معالجة مرادفات لغة الفور
            fur_synonyms_texts = request.form.getlist('fur_synonym_text[]')
            fur_synonym_ids = request.form.getlist('fur_synonym_id[]')
            for i, synonym_text in enumerate(fur_synonyms_texts):
                synonym_text = synonym_text.strip()
                synonym_id = fur_synonym_ids[i] if i < len(fur_synonym_ids) else None

                if synonym_text:
                    synonym_audio_url = None
                    
                    # التحقق إذا كان هناك ملف صوتي جديد أو تسجيل مرفق لهذا المرادف
                    if f'fur_synonym_audio_{i}' in request.files and request.files[f'fur_synonym_audio_{i}'].filename:
                        synonym_audio = request.files[f'fur_synonym_audio_{i}']
                        if synonym_audio and allowed_file(synonym_audio.filename):
                            filename = f"fur_synonym_{word.id}_{i}.mp3"
                            synonym_audio_path = os.path.join(current_app.config['UPLOAD_FOLDER'], filename)
                            try:
                                with tempfile.NamedTemporaryFile(delete=False) as temp_file:
                                    synonym_audio.save(temp_file.name)
                                    temp_file.close()
                                    shutil.copy2(temp_file.name, synonym_audio_path)
                                    os.unlink(temp_file.name)

                                    synonym_audio_url = f'/static/audio/{filename}'
                                    # ضغط الملف الصوتي للمرادف الفوري بعد الحفظ
                                    compress_audio_with_ffmpeg(synonym_audio_path, synonym_audio_path)
                            except Exception as e:
                                flash(f'خطأ في معالجة الملف الصوتي للمرادف الفوري {synonym_text}: {str(e)}', 'error')
                                print(f"Error processing Fur synonym audio: {e}")
                            finally:
                                if temp_file and os.path.exists(temp_file.name):
                                    try:
                                        os.unlink(temp_file.name)
                                    except Exception as cleanup_error:
                                        print(f"Error deleting Fur temp file: {cleanup_error}")

                    # إذا كان هناك ملف صوتي موجود ولم يتم رفع ملف جديد، احتفظ بالملف القديم
                    elif synonym_id:
                        existing_synonym = db.session.get(FurSynonym, synonym_id)
                        if existing_synonym:
                            synonym_audio_url = existing_synonym.audio_url

                    # إنشاء أو تحديث المرادف
                    if synonym_id:
                        # تحديث مرادف موجود
                        synonym = db.session.get(FurSynonym, synonym_id)
                        if synonym:
                            synonym.synonym_text = synonym_text
                            synonym.audio_url = synonym_audio_url
                    else:
                        # إضافة مرادف جديد
                        new_fur_synonym = FurSynonym(
                            word_id=word.id,
                            synonym_text=synonym_text,
                            audio_url=synonym_audio_url
                        )
                        db.session.add(new_fur_synonym)
            
            db.session.commit()
            
            flash('تم إضافة الكلمة بنجاح!', 'success')
            # البقاء في نفس الصفحة لإضافة كلمات أخرى
            categories = Category.query.filter_by(is_active=True).all()
            return render_template('admin/add_word.html', categories=categories)
        
        except Exception as e:
            db.session.rollback()
            flash(f'خطأ في إضافة الكلمة: {str(e)}', 'error')
    
    categories = Category.query.filter_by(is_active=True).all()
    return render_template('admin/add_word.html', categories=categories)

@admin_bp.route('/words/delete/<int:word_id>', methods=['POST'])
@login_required
def delete_word(word_id):
    """حذف كلمة"""
    try:
        word = Word.query.get_or_404(word_id)
        word.is_active = False  # حذف منطقي
        db.session.commit()
        flash('تم حذف الكلمة بنجاح!', 'success')
    except Exception as e:
        flash(f'خطأ في حذف الكلمة: {str(e)}', 'error')
    
    return redirect(url_for('admin.words_list'))

@admin_bp.route('/words/restore/<int:word_id>', methods=['POST'])
@login_required
def restore_word(word_id):
    """استعادة كلمة محذوفة"""
    try:
        word = Word.query.get_or_404(word_id)
        word.is_active = True
        db.session.commit()
        flash('تم استعادة الكلمة بنجاح!', 'success')
    except Exception as e:
        flash(f'خطأ في استعادة الكلمة: {str(e)}', 'error')
    
    return redirect(url_for('admin.words_list'))

@admin_bp.route('/words/deleted')
@login_required
def deleted_words():
    """قائمة الكلمات المحذوفة"""
    page = request.args.get('page', 1, type=int)
    
    words = Word.query.filter_by(is_active=False).order_by(
        Word.created_at.desc()
    ).paginate(page=page, per_page=20, error_out=False)
    
    return render_template('admin/deleted_words.html', words=words)

@admin_bp.route('/words/delete_permanent/<int:word_id>', methods=['POST'])
@login_required
def delete_word_permanent(word_id):
    """حذف كلمة نهائياً من قاعدة البيانات - للمديرين فقط"""
    # التحقق من أن المستخدم الحالي مدير
    if not current_user.is_admin:
        flash('عذراً، هذه العملية مخصصة للمديرين فقط!', 'error')
        return redirect(url_for('admin.deleted_words'))
    
    try:
        word = Word.query.get_or_404(word_id)
        
        # حذف ملفات الصوت إذا كانت موجودة
        if word.fur_audio_url:
            audio_path = os.path.join(current_app.config['UPLOAD_FOLDER'], 
                                    os.path.basename(word.fur_audio_url))
            if os.path.exists(audio_path):
                os.remove(audio_path)
        
        if word.english_audio_url:
            audio_path = os.path.join(current_app.config['UPLOAD_FOLDER'], 
                                    os.path.basename(word.english_audio_url))
            if os.path.exists(audio_path):
                os.remove(audio_path)
        
        db.session.delete(word)
        db.session.commit()
        flash('تم حذف الكلمة نهائياً!', 'success')
    except Exception as e:
        flash(f'خطأ في الحذف النهائي: {str(e)}', 'error')
    
    return redirect(url_for('admin.deleted_words'))

@admin_bp.route('/words/edit/<int:word_id>', methods=['GET', 'POST'])
@login_required
def edit_word(word_id):
    """تعديل كلمة موجودة"""
    word = Word.query.get_or_404(word_id)
    
    if request.method == 'POST':
        try:
            fur_word = request.form['fur_word'].strip()
            arabic_word = request.form['arabic_word'].strip()
            english_word = request.form['english_word'].strip()
            
            # التحقق من وجود كلمة أخرى بنفس المعنى الإنجليزي والعربي (باستثناء الكلمة الحالية)
            existing_word = Word.query.filter(
                Word.fur_word == fur_word,
                Word.arabic_word == arabic_word,
                Word.english_word == english_word,
                Word.id != word_id
            ).first()
            
            if existing_word:
                flash(f'يوجد كلمة أخرى بنفس المعنى: {existing_word.fur_word} - {arabic_word} - {english_word}', 'warning')
                categories = Category.query.filter_by(is_active=True).all()
                return render_template('admin/edit_word.html', word=word, categories=categories)
            
            # تحديث بيانات الكلمة
            word.fur_word = fur_word
            word.arabic_word = arabic_word
            word.english_word = english_word
            word.category = request.form.get('category', '')
            word.difficulty_level = int(request.form.get('difficulty_level', 1))
            word.is_active = bool(int(request.form.get('is_active', 1)))

            # لا نحذف المرادفات الموجودة، بل سنضيف الجديدة فقط
            
            # معالجة ملفات الصوت المسجلة والمرفوعة
            fur_audio_url = word.fur_audio_url  # الاحتفاظ بالملف الحالي
            
            # معالجة التسجيل الصوتي للكلمة الفرية
            if 'fur_audio' in request.files:
                fur_recorded = request.files['fur_audio']
                if fur_recorded and fur_recorded.filename:
                    # حذف الملف القديم إذا كان موجوداً
                    if word.fur_audio_url:
                        old_audio_path = os.path.join(current_app.config['UPLOAD_FOLDER'], 
                                                     os.path.basename(word.fur_audio_url))
                        if os.path.exists(old_audio_path):
                            os.remove(old_audio_path)
                    
                    filename = f"fur_{word.id}.mp3"
                    fur_audio_path = os.path.join(current_app.config['UPLOAD_FOLDER'], filename)
                    
                    try:
                        with tempfile.NamedTemporaryFile(delete=False, suffix='.wav') as temp_file:
                            fur_recorded.save(temp_file.name)
                            temp_file.close()
                            # os.rename(temp_file.name, fur_audio_path) # <--- السطر الذي يسبب المشكلة
                            shutil.copy2(temp_file.name, fur_audio_path) # <--- التصحيح: نسخ الملف
                            os.unlink(temp_file.name) # <--- التصحيح: حذف الملف المؤقت

                            fur_audio_url = f'/static/audio/{filename}'
                            # ضغط الملف الصوتي بعد الحفظ
                            compress_audio_with_ffmpeg(fur_audio_path, fur_audio_path)
                    except Exception as e:
                        flash(f'خطأ في معالجة الملف الصوتي للكلمة الفرية: {str(e)}', 'error')
                    finally:
                        if temp_file and os.path.exists(temp_file.name):
                            try:
                                os.unlink(temp_file.name)
                            except Exception as cleanup_error:
                                print(f"Error deleting temp file: {cleanup_error}")
            
            # معالجة الملف المرفوع العادي للكلمة الفرية
            elif 'fur_audio_upload' in request.files:
                fur_audio = request.files['fur_audio_upload']
                if fur_audio and allowed_file(fur_audio.filename):
                    # حذف الملف القديم إذا كان موجوداً
                    if word.fur_audio_url:
                        old_audio_path = os.path.join(current_app.config['UPLOAD_FOLDER'], 
                                                     os.path.basename(word.fur_audio_url))
                        if os.path.exists(old_audio_path):
                            os.remove(old_audio_path)
                    
                    filename = f"fur_{word.id}.mp3"
                    fur_audio_path = os.path.join(current_app.config['UPLOAD_FOLDER'], filename)
                    
                    try:
                        with tempfile.NamedTemporaryFile(delete=False) as temp_file:
                            fur_audio.save(temp_file.name)
                            temp_file.close()
                            # os.rename(temp_file.name, fur_audio_path) # <--- السطر الذي يسبب المشكلة
                            shutil.copy2(temp_file.name, fur_audio_path) # <--- التصحيح: نسخ الملف
                            os.unlink(temp_file.name) # <--- التصحيح: حذف الملف المؤقت

                            fur_audio_url = f'/static/audio/{filename}'
                            # ضغط الملف الصوتي بعد الحفظ
                            compress_audio_with_ffmpeg(fur_audio_path, fur_audio_path)
                    except Exception as e:
                        flash(f'خطأ في معالجة الملف الصوتي للكلمة الفرية: {str(e)}', 'error')
                    finally:
                        if temp_file and os.path.exists(temp_file.name):
                            try:
                                os.unlink(temp_file.name)
                            except Exception as cleanup_error:
                                print(f"Error deleting temp file: {cleanup_error}")
            

            
            # تحديث الكلمة بمسارات الصوت
            word.fur_audio_url = fur_audio_url

            # معالجة المرادفات الإنجليزية الجديدة والمعدلة
            english_synonyms_texts = request.form.getlist('english_synonym_text[]')
            english_synonym_ids = request.form.getlist('english_synonym_id[]')
            
            # الحصول على المرادفات الموجودة لتجنب التكرار
            existing_synonyms = {syn.synonym_text.strip().lower() for syn in word.english_synonyms}
            
            for i, synonym_text in enumerate(english_synonyms_texts):
                synonym_text = synonym_text.strip()
                synonym_id = english_synonym_ids[i] if i < len(english_synonym_ids) else None

                if synonym_text:
                    # التحقق من عدم وجود المرادف مسبقاً (تجنب التكرار)
                    if synonym_text.lower() not in existing_synonyms:
                        # إضافة مرادف جديد فقط
                        new_english_synonym = EnglishSynonym(
                            word_id=word.id,
                            synonym_text=synonym_text
                        )
                        db.session.add(new_english_synonym)
                        # إضافة المرادف الجديد للقائمة لتجنب التكرار في نفس الطلب
                        existing_synonyms.add(synonym_text.lower())
                    elif synonym_id:
                        # تحديث مرادف موجود إذا كان له معرف
                        synonym = db.session.get(EnglishSynonym, synonym_id)
                        if synonym:
                            synonym.synonym_text = synonym_text

            # معالجة المرادفات العربية الجديدة والمعدلة
            arabic_synonyms_texts = request.form.getlist('arabic_synonym_text[]')
            arabic_synonym_ids = request.form.getlist('arabic_synonym_id[]')
            
            # الحصول على المرادفات العربية الموجودة لتجنب التكرار
            existing_arabic_synonyms = {syn.synonym_text.strip().lower() for syn in word.arabic_synonyms}
            
            for i, synonym_text in enumerate(arabic_synonyms_texts):
                synonym_text = synonym_text.strip()
                synonym_id = arabic_synonym_ids[i] if i < len(arabic_synonym_ids) else None

                if synonym_text:
                    # التحقق من عدم وجود المرادف مسبقاً (تجنب التكرار)
                    if synonym_text.lower() not in existing_arabic_synonyms:
                        # إضافة مرادف جديد فقط
                        new_arabic_synonym = ArabicSynonym(
                            word_id=word.id,
                            synonym_text=synonym_text
                        )
                        db.session.add(new_arabic_synonym)
                        # إضافة المرادف الجديد للقائمة لتجنب التكرار في نفس الطلب
                        existing_arabic_synonyms.add(synonym_text.lower())
                    elif synonym_id:
                        # تحديث مرادف موجود إذا كان له معرف
                        synonym = db.session.get(ArabicSynonym, synonym_id)
                        if synonym:
                            synonym.synonym_text = synonym_text

            # معالجة مرادفات لغة الفور الجديدة والمعدلة
            fur_synonyms_texts = request.form.getlist('fur_synonym_text[]')
            fur_synonym_ids = request.form.getlist('fur_synonym_id[]')
            
            # الحصول على مرادفات لغة الفور الموجودة لتجنب التكرار
            existing_fur_synonyms = {syn.synonym_text.strip().lower() for syn in word.fur_synonyms}
            
            for i, synonym_text in enumerate(fur_synonyms_texts):
                synonym_text = synonym_text.strip()
                synonym_id = fur_synonym_ids[i] if i < len(fur_synonym_ids) else None

                if synonym_text:
                    synonym_audio_url = None
                    
                    # التحقق إذا كان هناك ملف صوتي جديد أو تسجيل مرفق لهذا المرادف
                    if f'fur_synonym_audio_{i}' in request.files and request.files[f'fur_synonym_audio_{i}'].filename:
                        synonym_audio = request.files[f'fur_synonym_audio_{i}']
                        if synonym_audio and allowed_file(synonym_audio.filename):
                            filename = f"fur_synonym_{word.id}_{i}.mp3"
                            synonym_audio_path = os.path.join(current_app.config['UPLOAD_FOLDER'], filename)
                            try:
                                with tempfile.NamedTemporaryFile(delete=False) as temp_file:
                                    synonym_audio.save(temp_file.name)
                                    temp_file.close()
                                    shutil.copy2(temp_file.name, synonym_audio_path)
                                    os.unlink(temp_file.name)

                                    synonym_audio_url = f'/static/audio/{filename}'
                                    # ضغط الملف الصوتي للمرادف الفوري بعد الحفظ
                                    compress_audio_with_ffmpeg(synonym_audio_path, synonym_audio_path)
                            except Exception as e:
                                flash(f'خطأ في معالجة الملف الصوتي للمرادف الفوري {synonym_text}: {str(e)}', 'error')
                                print(f"Error processing Fur synonym audio: {e}")
                            finally:
                                if temp_file and os.path.exists(temp_file.name):
                                    try:
                                        os.unlink(temp_file.name)
                                    except Exception as cleanup_error:
                                        print(f"Error deleting Fur temp file: {cleanup_error}")
                    
                    # التحقق من عدم وجود المرادف مسبقاً (تجنب التكرار)
                    if synonym_text.lower() not in existing_fur_synonyms:
                        # إضافة مرادف جديد فقط
                        new_fur_synonym = FurSynonym(
                            word_id=word.id,
                            synonym_text=synonym_text,
                            audio_url=synonym_audio_url
                        )
                        db.session.add(new_fur_synonym)
                        # إضافة المرادف الجديد للقائمة لتجنب التكرار في نفس الطلب
                        existing_fur_synonyms.add(synonym_text.lower())
                    elif synonym_id:
                        # تحديث مرادف موجود إذا كان له معرف
                        synonym = db.session.get(FurSynonym, synonym_id)
                        if synonym:
                            synonym.synonym_text = synonym_text
                            if synonym_audio_url:
                                synonym.audio_url = synonym_audio_url
            
            db.session.commit()
            
            flash('تم تحديث الكلمة بنجاح!', 'success')
            return redirect(url_for('admin.edit_word', word_id=word.id))
        
        except Exception as e:
            db.session.rollback()
            flash(f'خطأ في تحديث الكلمة: {str(e)}', 'error')
    
    categories = Category.query.filter_by(is_active=True).all()
    return render_template('admin/edit_word.html', word=word, categories=categories)


# إضافة هذه الدوال بعد الدوال الموجودة

@admin_bp.route('/words/inactive')
@login_required
def inactive_words():
    """قائمة الكلمات غير النشطة"""
    page = request.args.get('page', 1, type=int)
    search = request.args.get('search', '')
    
    # فلتر للكلمات غير النشطة
    query = Word.query.filter_by(is_active=False)
    
    if search:
        search_term = f'%{search}%'
        query = query.filter(
            db.or_(
                Word.fur_word.like(search_term),
                Word.arabic_word.like(search_term),
                Word.english_word.like(search_term)
            )
        )
    
    words = query.order_by(Word.created_at.desc()).paginate(
        page=page, per_page=20, error_out=False
    )
    
    return render_template('admin/inactive_words.html', words=words, search=search)

@admin_bp.route('/words/no-audio')
@login_required
def words_without_audio():
    """قائمة الكلمات بدون ملفات صوتية"""
    page = request.args.get('page', 1, type=int)
    search = request.args.get('search', '')
    
    # فلتر للكلمات النشطة بدون ملفات صوتية (فور أو إنجليزي)
    query = Word.query.filter(
        Word.is_active == True,
        db.or_(
            Word.fur_audio_url.is_(None),
            Word.english_audio_url.is_(None),
            Word.fur_audio_url == '',
            Word.english_audio_url == ''
        )
    )
    
    if search:
        search_term = f'%{search}%'
        query = query.filter(
            db.or_(
                Word.fur_word.like(search_term),
                Word.arabic_word.like(search_term),
                Word.english_word.like(search_term)
            )
        )
    
    words = query.order_by(Word.created_at.desc()).paginate(
        page=page, per_page=20, error_out=False
    )
    
    return render_template('admin/words_without_audio.html', words=words, search=search)


def compress_audio(input_file, output_path, target_bitrate="64k"):
    """
    ضغط ملف صوتي وتقليل حجمه
    """
    try:
        # قراءة الملف الصوتي
        audio = AudioSegment.from_file(input_file)
        
        # تحويل إلى mono (قناة واحدة) لتقليل الحجم
        audio = audio.set_channels(1)
        
        # تقليل معدل العينة إلى 22050 Hz
        audio = audio.set_frame_rate(22050)
        
        # تصدير بجودة مضغوطة
        audio.export(
            output_path,
            format="mp3",
            bitrate=target_bitrate,
            parameters=["-q:a", "5"]  # جودة متوسطة للضغط الأفضل
        )
        
        return True
    except Exception as e:
        print(f"Audio compression error: {str(e)}")
        return False


# نظام النسخ الاحتياطي
@admin_bp.route('/backup')
@login_required
def backup_system():
    """صفحة نظام النسخ الاحتياطي - للمديرين فقط"""
    if not current_user.is_admin:
        flash('ليس لديك صلاحية للوصول إلى هذه الصفحة', 'error')
        return redirect(url_for('admin.dashboard'))
    
    # الحصول على قائمة النسخ الاحتياطية الموجودة
    backup_dir = os.path.join(current_app.root_path, 'backups')
    backups = []
    
    if os.path.exists(backup_dir):
        for filename in os.listdir(backup_dir):
            if filename.endswith('.zip'):
                filepath = os.path.join(backup_dir, filename)
                stat = os.stat(filepath)
                backups.append({
                    'filename': filename,
                    'size': round(stat.st_size / (1024 * 1024), 2),  # بالميجابايت
                    'created_at': datetime.fromtimestamp(stat.st_mtime)
                })
    
    # ترتيب النسخ حسب التاريخ (الأحدث أولاً)
    backups.sort(key=lambda x: x['created_at'], reverse=True)
    
    return render_template('admin/backup.html', backups=backups)

@admin_bp.route('/backup/create', methods=['POST'])
@login_required
def create_backup():
    """إنشاء نسخة احتياطية - للمديرين فقط"""
    if not current_user.is_admin:
        flash('ليس لديك صلاحية للوصول إلى هذه الصفحة', 'error')
        return redirect(url_for('admin.dashboard'))
    
    try:
        import zipfile
        import shutil
        import subprocess
        import os
        from datetime import datetime
        from config import Config
        
        # إنشاء مجلد النسخ الاحتياطية إذا لم يكن موجوداً
        backup_dir = os.path.join(current_app.root_path, 'backups')
        os.makedirs(backup_dir, exist_ok=True)
        
        # اسم الملف مع التاريخ والوقت
        timestamp = datetime.now().strftime('%Y%m%d_%H%M%S')
        backup_filename = f'yatoy_backup_{timestamp}.zip'
        backup_path = os.path.join(backup_dir, backup_filename)
        
        # إنشاء ملف ZIP
        with zipfile.ZipFile(backup_path, 'w', zipfile.ZIP_DEFLATED) as zipf:
            
            # نسخ قاعدة البيانات حسب النوع
            db_type = os.environ.get('DB_TYPE', 'sqlite')
            database_backed_up = False
            
            if db_type.lower() == 'mysql':
                try:
                    # إنشاء نسخة احتياطية من MySQL باستخدام Python مباشرة
                    import pymysql
                    
                    mysql_host = os.environ.get('MYSQL_HOST', 'localhost')
                    mysql_user = os.environ.get('MYSQL_USER', 'root')
                    mysql_password = os.environ.get('MYSQL_PASSWORD', '')
                    mysql_database = os.environ.get('MYSQL_DATABASE', 'yatoy_db')
                    mysql_port = int(os.environ.get('MYSQL_PORT', 3306))
                    
                    # ملف SQL مؤقت
                    sql_file = os.path.join(backup_dir, f'database_{timestamp}.sql')
                    
                    # الاتصال بقاعدة البيانات
                    connection = pymysql.connect(
                        host=mysql_host,
                        user=mysql_user,
                        password=mysql_password,
                        database=mysql_database,
                        port=mysql_port,
                        charset='utf8mb4'
                    )
                    
                    with connection.cursor() as cursor:
                        # إنشاء ملف النسخة الاحتياطية
                        with open(sql_file, 'w', encoding='utf-8') as f:
                            # كتابة رأس الملف
                            f.write(f"-- MySQL Database Backup\n")
                            f.write(f"-- Generated on: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}\n")
                            f.write(f"-- Database: {mysql_database}\n\n")
                            f.write("SET FOREIGN_KEY_CHECKS=0;\n\n")
                            
                            # الحصول على قائمة الجداول
                            cursor.execute("SHOW TABLES")
                            tables = cursor.fetchall()
                            
                            for table in tables:
                                table_name = table[0]
                                
                                # الحصول على بنية الجدول
                                cursor.execute(f"SHOW CREATE TABLE `{table_name}`")
                                create_table = cursor.fetchone()[1]
                                
                                f.write(f"-- Table structure for `{table_name}`\n")
                                f.write(f"DROP TABLE IF EXISTS `{table_name}`;\n")
                                f.write(f"{create_table};\n\n")
                                
                                # الحصول على بيانات الجدول
                                cursor.execute(f"SELECT * FROM `{table_name}`")
                                rows = cursor.fetchall()
                                
                                if rows:
                                    # الحصول على أسماء الأعمدة
                                    cursor.execute(f"DESCRIBE `{table_name}`")
                                    columns = [col[0] for col in cursor.fetchall()]
                                    
                                    f.write(f"-- Data for table `{table_name}`\n")
                                    f.write(f"INSERT INTO `{table_name}` (`{'`, `'.join(columns)}`) VALUES\n")
                                    
                                    for i, row in enumerate(rows):
                                        # تحويل القيم إلى نص آمن
                                        values = []
                                        for value in row:
                                            if value is None:
                                                values.append('NULL')
                                            elif isinstance(value, str):
                                                # تنظيف النص من الأحرف الخاصة
                                                escaped_value = value.replace('\\', '\\\\')
                                                escaped_value = escaped_value.replace("'", "\\'") 
                                                escaped_value = escaped_value.replace('\n', '\\n')
                                                escaped_value = escaped_value.replace('\r', '\\r')
                                                values.append(f"'{escaped_value}'")
                                            elif isinstance(value, (int, float)):
                                                values.append(str(value))
                                            else:
                                                values.append(f"'{str(value)}'")
                                        
                                        row_sql = f"({', '.join(values)})"
                                        if i < len(rows) - 1:
                                            row_sql += ","
                                        else:
                                            row_sql += ";"
                                        
                                        f.write(row_sql + "\n")
                                    
                                    f.write("\n")
                            
                            f.write("SET FOREIGN_KEY_CHECKS=1;\n")
                    
                    connection.close()
                    
                    # التحقق من أن الملف تم إنشاؤه وليس فارغاً
                    if not os.path.exists(sql_file) or os.path.getsize(sql_file) < 100:
                        raise Exception('ملف النسخة الاحتياطية فارغ أو لم يتم إنشاؤه بشكل صحيح.')
                    
                    # إضافة ملف SQL إلى ZIP
                    zipf.write(sql_file, 'database.sql')
                    database_backed_up = True
                    
                    # حذف الملف المؤقت
                    os.remove(sql_file)
                    
                except Exception as mysql_error:
                    current_app.logger.error(f'MySQL backup failed: {str(mysql_error)}')
                    # محاولة نسخ SQLite كبديل إذا كان موجوداً
                    sqlite_path = os.path.join(current_app.instance_path, 'database.db')
                    if os.path.exists(sqlite_path):
                        zipf.write(sqlite_path, 'database.db')
                        database_backed_up = True
                        flash(f'تحذير: فشل في نسخ MySQL ({str(mysql_error)}). تم نسخ SQLite بدلاً منه.', 'warning')
                    else:
                        raise mysql_error
                        
            else:
                # نسخ قاعدة بيانات SQLite
                db_path = os.path.join(current_app.instance_path, 'database.db')
                if os.path.exists(db_path):
                    zipf.write(db_path, 'database.db')
                    database_backed_up = True
                else:
                    # البحث عن ملف قاعدة البيانات في مواقع أخرى
                    alternative_paths = [
                        os.path.join(current_app.instance_path, 'thedatabase.db'),
                        os.path.join(current_app.root_path, 'database.db'),
                        os.path.join(current_app.root_path, 'instance', 'database.db')
                    ]
                    
                    for alt_path in alternative_paths:
                        if os.path.exists(alt_path):
                            zipf.write(alt_path, os.path.basename(alt_path))
                            database_backed_up = True
                            break
            
            if not database_backed_up:
                raise Exception('لم يتم العثور على قاعدة بيانات للنسخ الاحتياطي.')
            
            # نسخ الملفات الصوتية
            audio_files_count = 0
            audio_dir = os.path.join(current_app.root_path, 'static', 'audio')
            if os.path.exists(audio_dir):
                for root, dirs, files in os.walk(audio_dir):
                    for file in files:
                        if file.lower().endswith(('.mp3', '.wav', '.ogg', '.m4a')):
                            file_path = os.path.join(root, file)
                            arcname = os.path.relpath(file_path, current_app.root_path)
                            zipf.write(file_path, arcname)
                            audio_files_count += 1
            
            # نسخ ملفات التكوين المهمة
            config_files_count = 0
            config_files = ['config.py', 'models.py', 'requirements.txt', '.env']
            for config_file in config_files:
                config_path = os.path.join(current_app.root_path, config_file)
                if os.path.exists(config_path):
                    zipf.write(config_path, config_file)
                    config_files_count += 1
        
        # التحقق من حجم الملف المُنشأ
        backup_size = os.path.getsize(backup_path)
        if backup_size < 1024:  # أقل من 1 كيلوبايت
            raise Exception('حجم النسخة الاحتياطية صغير جداً، قد تكون فارغة.')
        
        # رسالة نجاح مفصلة
        size_mb = backup_size / (1024 * 1024)
        success_msg = f'تم إنشاء النسخة الاحتياطية بنجاح: {backup_filename} ({size_mb:.2f} ميجابايت)'
        if audio_files_count > 0:
            success_msg += f' - تم نسخ {audio_files_count} ملف صوتي'
        if config_files_count > 0:
            success_msg += f' و {config_files_count} ملف تكوين'
            
        flash(success_msg, 'success')
        
    except Exception as e:
        current_app.logger.error(f'Backup creation failed: {str(e)}')
        
        # حذف الملف المُنشأ جزئياً إذا كان موجوداً
        if 'backup_path' in locals() and os.path.exists(backup_path):
            try:
                os.remove(backup_path)
            except:
                pass
                
        # رسائل خطأ مفصلة
        error_msg = str(e)
        if 'mysqldump' in error_msg:
            error_msg += ' تأكد من تثبيت MySQL Client Tools وصحة إعدادات الاتصال.'
        elif 'Access denied' in error_msg:
            error_msg = 'خطأ في الوصول إلى قاعدة البيانات. تحقق من اسم المستخدم وكلمة المرور في ملف .env'
        elif 'Unknown database' in error_msg:
            error_msg = 'قاعدة البيانات المحددة غير موجودة. تحقق من اسم قاعدة البيانات في ملف .env'
            
        flash(f'خطأ في إنشاء النسخة الاحتياطية: {error_msg}', 'error')
    
    return redirect(url_for('admin.backup_system'))

@admin_bp.route('/backup/download/<filename>')
@login_required
def download_backup(filename):
    """تحميل نسخة احتياطية - للمديرين فقط"""
    if not current_user.is_admin:
        flash('ليس لديك صلاحية للوصول إلى هذه الصفحة', 'error')
        return redirect(url_for('admin.dashboard'))
    
    try:
        from flask import send_file
        backup_dir = os.path.join(current_app.root_path, 'backups')
        backup_path = os.path.join(backup_dir, filename)
        
        if not os.path.exists(backup_path) or not filename.endswith('.zip'):
            flash('الملف المطلوب غير موجود', 'error')
            return redirect(url_for('admin.backup_system'))
        
        return send_file(backup_path, as_attachment=True, download_name=filename)
        
    except Exception as e:
        flash(f'خطأ في تحميل النسخة الاحتياطية: {str(e)}', 'error')
        return redirect(url_for('admin.backup_system'))

@admin_bp.route('/backup/delete/<filename>', methods=['POST'])
@login_required
def delete_backup(filename):
    """حذف نسخة احتياطية - للمديرين فقط"""
    if not current_user.is_admin:
        flash('ليس لديك صلاحية للوصول إلى هذه الصفحة', 'error')
        return redirect(url_for('admin.dashboard'))
    
    try:
        backup_dir = os.path.join(current_app.root_path, 'backups')
        backup_path = os.path.join(backup_dir, filename)
        
        if os.path.exists(backup_path) and filename.endswith('.zip'):
            os.remove(backup_path)
            flash('تم حذف النسخة الاحتياطية بنجاح', 'success')
        else:
            flash('الملف المطلوب غير موجود', 'error')
            
    except Exception as e:
        flash(f'خطأ في حذف النسخة الاحتياطية: {str(e)}', 'error')
    
    return redirect(url_for('admin.backup_system'))

@admin_bp.route('/backup/restore', methods=['POST'])
@login_required
def restore_backup():
    """استعادة نسخة احتياطية - للمديرين فقط"""
    if not current_user.is_admin:
        flash('ليس لديك صلاحية للوصول إلى هذه الصفحة', 'error')
        return redirect(url_for('admin.dashboard'))
    
    try:
        import zipfile
        import shutil
        import subprocess
        import tempfile
        from datetime import datetime
        
        # التحقق من وجود ملف مرفوع
        if 'backup_file' not in request.files:
            flash('لم يتم اختيار ملف للاستعادة', 'error')
            return redirect(url_for('admin.backup_system'))
        
        file = request.files['backup_file']
        if file.filename == '' or not file.filename.endswith('.zip'):
            flash('يرجى اختيار ملف نسخة احتياطية صحيح (.zip)', 'error')
            return redirect(url_for('admin.backup_system'))
        
        # حفظ الملف مؤقتاً
        temp_dir = tempfile.mkdtemp()
        temp_file = os.path.join(temp_dir, file.filename)
        file.save(temp_file)
        
        # استخراج النسخة الاحتياطية
        with zipfile.ZipFile(temp_file, 'r') as zipf:
            
            db_type = os.environ.get('DB_TYPE', 'sqlite')
            
            if db_type.lower() == 'mysql':
                # استعادة قاعدة بيانات MySQL باستخدام pymysql
                if 'database.sql' in zipf.namelist():
                    try:
                        import pymysql
                    except ImportError:
                        raise Exception('مكتبة pymysql غير مثبتة. يرجى تثبيتها باستخدام: pip install pymysql')
                    
                    # استخراج ملف SQL
                    sql_file = os.path.join(temp_dir, 'database.sql')
                    zipf.extract('database.sql', temp_dir)
                    
                    # معلومات الاتصال بـ MySQL
                    mysql_host = os.environ.get('MYSQL_HOST', 'localhost')
                    mysql_port = int(os.environ.get('MYSQL_PORT', 3306))
                    mysql_user = os.environ.get('MYSQL_USER', 'root')
                    mysql_password = os.environ.get('MYSQL_PASSWORD', '')
                    mysql_database = os.environ.get('MYSQL_DATABASE', 'yatoy_db')
                    
                    # الاتصال بقاعدة البيانات
                    connection = pymysql.connect(
                        host=mysql_host,
                        port=mysql_port,
                        user=mysql_user,
                        password=mysql_password,
                        database=mysql_database,
                        charset='utf8mb4',
                        autocommit=False
                    )
                    
                    try:
                        cursor = connection.cursor()
                        
                        # قراءة وتنفيذ ملف SQL
                        with open(sql_file, 'r', encoding='utf-8') as f:
                            sql_content = f.read()
                        
                        # تقسيم الاستعلامات وتنفيذها
                        statements = [stmt.strip() for stmt in sql_content.split(';') if stmt.strip()]
                        
                        for statement in statements:
                            if statement:
                                cursor.execute(statement)
                        
                        connection.commit()
                        
                    finally:
                        cursor.close()
                        connection.close()
                        
            else:
                # استعادة قاعدة بيانات SQLite
                if 'database.db' in zipf.namelist():
                    # إنشاء نسخة احتياطية من قاعدة البيانات الحالية
                    current_db = os.path.join(current_app.instance_path, 'database.db')
                    if os.path.exists(current_db):
                        backup_current_db = os.path.join(current_app.instance_path, f'database_backup_{datetime.now().strftime("%Y%m%d_%H%M%S")}.db')
                        shutil.copy2(current_db, backup_current_db)
                    
                    # استعادة قاعدة البيانات الجديدة
                    zipf.extract('database.db', current_app.instance_path)
            
            # استعادة الملفات الصوتية
            audio_files = [f for f in zipf.namelist() if f.startswith('static/audio/')]
            for audio_file in audio_files:
                zipf.extract(audio_file, current_app.root_path)
        
        # تنظيف الملفات المؤقتة
        shutil.rmtree(temp_dir)
        
        flash('تم استعادة النسخة الاحتياطية بنجاح! يرجى إعادة تشغيل التطبيق.', 'success')
        
    except Exception as e:
        flash(f'خطأ في استعادة النسخة الاحتياطية: {str(e)}', 'error')
    
    return redirect(url_for('admin.backup_system'))

# صفحات إدارة المستخدمين
@admin_bp.route('/users')
@login_required
def users_list():
    """قائمة المستخدمين - للإدارة فقط"""
    if not current_user.is_admin:
        flash('ليس لديك صلاحية للوصول إلى هذه الصفحة', 'error')
        return redirect(url_for('admin.dashboard'))
    
    page = request.args.get('page', 1, type=int)
    users = User.query.order_by(User.created_at.desc()).paginate(
        page=page, per_page=20, error_out=False
    )
    
    return render_template('admin/users.html', users=users)

@admin_bp.route('/users/add', methods=['GET', 'POST'])
@login_required
def add_user():
    """إضافة مستخدم جديد - للإدارة فقط"""
    if not current_user.is_admin:
        flash('ليس لديك صلاحية للوصول إلى هذه الصفحة', 'error')
        return redirect(url_for('admin.dashboard'))
    
    if request.method == 'POST':
        try:
            username = request.form['username'].strip()
            email = request.form['email'].strip()
            password = request.form['password']
            is_admin = bool(request.form.get('is_admin'))
            
            # التحقق من عدم وجود المستخدم
            if User.query.filter_by(username=username).first():
                flash('اسم المستخدم موجود بالفعل', 'error')
                return render_template('admin/add_user.html')
            
            if User.query.filter_by(email=email).first():
                flash('البريد الإلكتروني موجود بالفعل', 'error')
                return render_template('admin/add_user.html')
            
            # إنشاء المستخدم الجديد
            user = User(
                username=username,
                email=email,
                is_admin=is_admin,
                is_active=True
            )
            user.set_password(password)
            
            db.session.add(user)
            db.session.commit()
            
            flash('تم إضافة المستخدم بنجاح!', 'success')
            return redirect(url_for('admin.users_list'))
            
        except Exception as e:
            db.session.rollback()
            flash(f'خطأ في إضافة المستخدم: {str(e)}', 'error')
    
    return render_template('admin/add_user.html')

@admin_bp.route('/users/delete/<int:user_id>', methods=['POST'])
@login_required
def delete_user(user_id):
    """حذف مستخدم - للإدارة فقط"""
    if not current_user.is_admin:
        flash('ليس لديك صلاحية للوصول إلى هذه الصفحة', 'error')
        return redirect(url_for('admin.dashboard'))
    
    try:
        user = User.query.get_or_404(user_id)
        
        # منع حذف المستخدم الحالي
        if user.id == current_user.id:
            flash('لا يمكنك حذف حسابك الخاص', 'error')
            return redirect(url_for('admin.users_list'))
        
        db.session.delete(user)
        db.session.commit()
        flash('تم حذف المستخدم بنجاح!', 'success')
        
    except Exception as e:
        db.session.rollback()
        flash(f'خطأ في حذف المستخدم: {str(e)}', 'error')
    
    return redirect(url_for('admin.users_list'))

@admin_bp.route('/profile', methods=['GET', 'POST'])
@login_required
def profile():
    """صفحة الملف الشخصي وتغيير كلمة المرور"""
    if request.method == 'POST':
        try:
            current_password = request.form.get('current_password', '').strip()
            new_password = request.form.get('new_password', '').strip()
            confirm_password = request.form.get('confirm_new_password', '').strip()  # تم تصحيح الاسم هنا
            
            # التحقق من وجود البيانات
            if not current_password or not new_password or not confirm_password:
                flash('جميع الحقول مطلوبة', 'error')
                return render_template('admin/profile.html')
            
            # التحقق من طول كلمة المرور الجديدة
            if len(new_password) < 6:
                flash('كلمة المرور الجديدة يجب أن تكون 6 أحرف على الأقل', 'error')
                return render_template('admin/profile.html')
            
            # التحقق من كلمة المرور الحالية
            if not current_user.check_password(current_password):
                flash('كلمة المرور الحالية غير صحيحة', 'error')
                return render_template('admin/profile.html')
            
            # التحقق من تطابق كلمة المرور الجديدة
            if new_password != confirm_password:
                flash('كلمة المرور الجديدة غير متطابقة', 'error')
                return render_template('admin/profile.html')
            
            # تحديث كلمة المرور
            current_user.set_password(new_password)
            db.session.commit()
            
            flash('تم تغيير كلمة المرور بنجاح!', 'success')
            return redirect(url_for('admin.profile'))
            
        except Exception as e:
            db.session.rollback()
            flash(f'خطأ في تغيير كلمة المرور: {str(e)}', 'error')
            current_app.logger.error(f'Password change error: {str(e)}')
    
    return render_template('admin/profile.html')


def compress_audio_with_ffmpeg(input_file, output_path, target_bitrate="64k"):
    """
    ضغط ملف صوتي باستخدام FFmpeg
    """
    try:
        # التحقق من وجود الملف المدخل
        if not os.path.exists(input_file):
            print(f"Input file not found: {input_file}")
            return False
        
        # التحقق من صحة مسار الإخراج
        output_dir = os.path.dirname(output_path)
        if not os.path.exists(output_dir):
            os.makedirs(output_dir, exist_ok=True)
        
        # أمر FFmpeg للضغط
        cmd = [
            'ffmpeg',
            '-i', input_file,
            '-acodec', 'mp3',
            '-ab', target_bitrate,
            '-ac', '1',  # mono
            '-ar', '22050',  # sample rate
            '-y',  # overwrite output file
            output_path
        ]
        
        # تشغيل الأمر
        result = subprocess.run(cmd, capture_output=True, text=True)
        
        if result.returncode == 0 and os.path.exists(output_path):
            print(f"File compressed successfully: {output_path}")
            return True
        else:
            print(f"Compression failed: {result.stderr}")
            return False
            
    except Exception as e:
        print(f"Audio compression error: {str(e)}")
        return False
        
        

@admin_bp.route('/audio/list', methods=['GET'])
def list_audio_files():
    """قائمة بكل ملفات الصوت المتاحة ضمن static/audio على شكل JSON للاستخدام من تطبيق الأندرويد"""
    try:
        # تحديد مجلد الصوتيات
        audio_dir = current_app.config.get(
            'UPLOAD_FOLDER',
            os.path.join(current_app.root_path, 'static', 'audio')
        )

        files = []
        if os.path.isdir(audio_dir):
            for fname in os.listdir(audio_dir):
                fpath = os.path.join(audio_dir, fname)
                if os.path.isfile(fpath):
                    try:
                        size = os.path.getsize(fpath)
                        mtime = os.path.getmtime(fpath)
                        files.append({
                            'filename': fname,
                            'url': url_for('static', filename=f'audio/{fname}', _external=False),
                            'size': size,
                            'modified': datetime.utcfromtimestamp(mtime).isoformat() + 'Z'
                        })
                    except Exception:
                        # تخطي أي ملف يسبب مشكلة في القراءة
                        continue

        files.sort(key=lambda x: x['filename'].lower())

        return jsonify({
            'success': True,
            'audio_files': files,
            'total_files': len(files),
            'server_time': datetime.utcnow().isoformat() + 'Z'
        }), 200
    except Exception as e:
        return jsonify({'success': False, 'error': str(e)}), 500

        