from flask import Flask, render_template_string, request, jsonify, redirect, url_for, flash
from flask_sqlalchemy import SQLAlchemy
from flask_login import LoginManager, UserMixin, login_user, login_required, logout_user, current_user
from werkzeug.security import generate_password_hash, check_password_hash
from difflib import SequenceMatcher
import os
import re
import uuid
import random

app = Flask(__name__)
app.config['SECRET_KEY'] = 'super-gizli-anahtar'
app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql+pymysql://root:Mmty2676*@localhost/arapca_app'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False

UPLOAD_FOLDER = 'static/uploads'
os.makedirs(UPLOAD_FOLDER, exist_ok=True)
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER

db = SQLAlchemy(app)
login_manager = LoginManager()
login_manager.init_app(app)
login_manager.login_view = 'login'

class User(UserMixin, db.Model):
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(50), unique=True, nullable=False)
    password = db.Column(db.String(255), nullable=False)
    role = db.Column(db.String(20), default='user')
    score = db.Column(db.Integer, default=0)

class Unit(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    title = db.Column(db.String(100), nullable=False)
    lessons = db.relationship('Lesson', backref='unit', cascade="all, delete-orphan", lazy=True)

class Lesson(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    unit_id = db.Column(db.Integer, db.ForeignKey('unit.id'), nullable=False)
    title = db.Column(db.String(100), nullable=False)
    words = db.relationship('Word', backref='lesson', cascade="all, delete-orphan", lazy=True)

class Word(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    lesson_id = db.Column(db.Integer, db.ForeignKey('lesson.id'), nullable=False)
    ar = db.Column(db.String(100), nullable=False)
    tr = db.Column(db.String(100), nullable=False)
    q_type = db.Column(db.String(20), nullable=False)
    audio_file = db.Column(db.String(255), nullable=True)

# YENİ: Kullanıcının tamamladığı dersleri tutan tablo
class CompletedLesson(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    user_id = db.Column(db.Integer, db.ForeignKey('user.id'), nullable=False)
    lesson_id = db.Column(db.Integer, db.ForeignKey('lesson.id'), nullable=False)

@login_manager.user_loader
def load_user(user_id):
    return User.query.get(int(user_id))

def strip_tashkeel(text):
    tashkeel = re.compile(r'[\u0617-\u061A\u064B-\u0652]')
    return re.sub(tashkeel, '', text)

GLOBAL_HTML_START = """
<!DOCTYPE html>
<html lang="tr">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
    <style>
        @import url('https://fonts.googleapis.com/css2?family=Nunito:wght@400;700;900&family=Tajawal:wght@700&display=swap');
        :root { --primary: #1CB0F6; --primary-dark: #1899D6; --success: #58CC02; --success-dark: #58A700; --danger: #FF4B4B; --danger-dark: #EA1538; --bg: #F7F7F7; --text: #4B4B4B; --warning: #FFC800; --warning-dark: #E5B400; }
        * { box-sizing: border-box; font-family: 'Nunito', sans-serif; }
        body { background-color: var(--bg); color: var(--text); margin: 0; padding: 15px; display: flex; flex-direction: column; align-items: center; min-height: 100vh; }
        .card { background: white; border-radius: 20px; box-shadow: 0 10px 25px rgba(0,0,0,0.05); padding: 25px; width: 100%; max-width: 600px; margin-bottom: 20px; text-align: center; border: 2px solid #E5E5E5; }
        h1, h2, h3 { color: #3C3C3C; }
        input[type="text"], input[type="password"], select { width: 100%; padding: 15px; margin: 8px 0; border: 2px solid #E5E5E5; border-radius: 12px; font-size: 16px; outline: none; transition: 0.2s; background: #fff; }
        input[type="text"]:focus, input[type="password"]:focus, select:focus { border-color: var(--primary); }
        .btn { display: inline-block; padding: 15px; border-radius: 12px; font-size: 18px; font-weight: bold; color: white; cursor: pointer; border: none; text-decoration: none; margin-top: 5px; width: 100%; text-align:center; transition:0.2s; }
        .btn-blue { background-color: var(--primary); box-shadow: 0 4px 0 var(--primary-dark); }
        .btn-blue:active { transform: translateY(4px); box-shadow: none; }
        .btn-green { background-color: var(--success); box-shadow: 0 4px 0 var(--success-dark); }
        .btn-green:active { transform: translateY(4px); box-shadow: none; }
        .btn-red { background-color: var(--danger); box-shadow: 0 4px 0 var(--danger-dark); }
        .btn-red:active { transform: translateY(4px); box-shadow: none; }
        .btn-yellow { background-color: var(--warning); box-shadow: 0 4px 0 var(--warning-dark); color: #B38C00; }
        .btn-yellow:active { transform: translateY(4px); box-shadow: none; }
        .btn:disabled { background-color: #E5E5E5; box-shadow: 0 4px 0 #CECECE; cursor: not-allowed; color: #AFAFAF; }
        .arabic-text { font-family: 'Tajawal', sans-serif; font-size: 3.5rem; color: #2C3E50; direction: rtl; margin: 20px 0; }
        .badge { background: #FFC800; color: #B38C00; padding: 8px 15px; border-radius: 20px; font-weight: 900; display: inline-block; margin-bottom: 15px; }
        .admin-box { background: #f9f9f9; border: 2px solid #eee; padding: 15px; border-radius: 15px; margin-bottom: 15px; text-align: left; overflow: hidden; }
        table { width: 100%; border-collapse: collapse; margin-top: 10px; font-size:14px; }
        th, td { padding: 8px; border-bottom: 1px solid #ddd; text-align: left; }
        
        .avatar-wrapper { position: relative; width: 140px; height: 140px; margin: 0 auto 10px; perspective: 500px; }
        .avatar { position: absolute; bottom: 0; left: 50%; transform: translateX(-50%); width: 100px; height: 130px; transition: all 0.4s cubic-bezier(0.175, 0.885, 0.32, 1.275); transform-origin: bottom center; }
        .head { background: #ffccb4; width: 80px; height: 90px; border-radius: 40px 40px 30px 30px; position: absolute; top: 10px; left: 10px; z-index: 2; transition: all 0.3s; box-shadow: inset -4px -6px 10px rgba(0,0,0,0.1); }
        .hair { background: #3b2818; width: 84px; height: 35px; border-radius: 40px 40px 10px 10px; position: absolute; top: -5px; left: -2px; }
        .ear { background: #ffccb4; width: 20px; height: 26px; border-radius: 10px; position: absolute; top: 38px; z-index: 1; transition: all 0.3s; box-shadow: inset -2px -2px 5px rgba(0,0,0,0.1); }
        .ear.left { left: 0px; }
        .ear.right { right: 0px; }
        .eye { background: #2c3e50; width: 10px; height: 12px; border-radius: 50%; position: absolute; top: 42px; transition: all 0.2s; }
        .eye.left { left: 22px; }
        .eye.right { right: 22px; }
        .mouth { background: #8b3e3e; width: 22px; height: 6px; border-radius: 10px; position: absolute; top: 68px; left: 29px; transition: all 0.1s; }
        .torso { background: var(--primary); width: 100px; height: 45px; border-radius: 40px 40px 10px 10px; position: absolute; bottom: 0; left: 0; z-index: 0; box-shadow: inset 0 5px 10px rgba(0,0,0,0.1); }
        .avatar.talking .mouth { animation: talkAnim 0.25s infinite alternate; height: 18px; border-radius: 10px 10px 20px 20px; top: 63px; background: #5c1b1b; }
        @keyframes talkAnim { 0% { height: 6px; top: 68px; } 100% { height: 18px; top: 63px; } }
        .avatar.listening { transform: translateX(-50%) scale(1.15) rotate(4deg); }
        .avatar.listening .head { transform: translateY(5px); }
        .avatar.listening .ear { transform: scale(1.4) rotate(15deg); background: #ffb595; }
        .avatar.listening .ear.left { transform: scale(1.4) rotate(-15deg); left: -5px; }
        .avatar.listening .ear.right { transform: scale(1.4) rotate(15deg); right: -5px; }
        .avatar.listening .eye { height: 16px; top: 40px; } 
        .flash { background: var(--danger); color: white; padding: 10px; border-radius: 10px; margin-bottom: 15px; font-weight: bold; }
    </style>
</head>
<body>
"""
GLOBAL_HTML_END = "</body></html>"

HTML_DASHBOARD = GLOBAL_HTML_START + """
<title>Yol Haritası</title>
<div class="card">
    <h2>Merhaba, {{ user.username }}! 🌟</h2>
    <div class="badge" style="font-size:18px;">Puanın: {{ user.score }} XP</div>
    {% if user.role == 'admin' %}<a href="/admin" class="btn btn-red" style="margin-bottom:20px;">👑 ADMİN PANELİNE GİT</a>{% endif %}
    <a href="/logout" style="color:#AFAFAF; font-weight:bold; text-decoration:none; display:block; margin-bottom:20px; padding:10px;">Çıkış Yap</a>

    {% for u in units %}
        <div style="background:#F0F9FF; border:2px solid var(--primary); padding:15px; border-radius:20px; margin-bottom:20px; text-align:left;">
            <h3 style="margin:0 0 10px 0; color:var(--primary-dark);">📚 {{ u.title }}</h3>
            {% for lesson in u.lessons %}
                <div style="background:white; padding:15px; border-radius:12px; margin-bottom:10px; display:flex; flex-direction:column; gap:10px; border:1px solid #eee;">
                    <span style="font-weight:bold; font-size:16px;">
                        {% if lesson.id in completed_ids %}✅{% else %}⚪{% endif %} 
                        {{ lesson.title }} ({{ lesson.words|length }} Kelime)
                    </span>
                    
                    {% if lesson.id in completed_ids %}
                        <a href="/lesson/{{ lesson.id }}" class="btn btn-yellow" style="padding:10px;">Tekrar Et (+ Az XP)</a>
                    {% else %}
                        <a href="/lesson/{{ lesson.id }}" class="btn btn-green" style="padding:10px;">Derse Başla</a>
                    {% endif %}
                </div>
            {% endfor %}
            {% if not u.lessons %}<p style="color:#777; font-size:14px;">Henüz ders eklenmedi.</p>{% endif %}
        </div>
    {% endfor %}
    {% if not units %}<p>Henüz hiç ünite eklenmemiş.</p>{% endif %}
</div>
""" + GLOBAL_HTML_END

HTML_LESSON = GLOBAL_HTML_START + """
<title>Ders Ekranı</title>
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
<div class="card">
    <div class="avatar-wrapper">
        <div id="avatar" class="avatar">
            <div class="torso"></div><div class="ear left"></div><div class="ear right"></div>
            <div class="head"><div class="hair"></div><div class="eye left"></div><div class="eye right"></div><div class="mouth"></div></div>
        </div>
    </div>
    
    <div id="soru-tipi" class="badge">Yükleniyor...</div>
    <div id="kelime" class="arabic-text"></div>
    <h3 id="anlam" style="color:#AFAFAF;"></h3>
    
    <button id="aksiyonBtn" class="btn btn-blue" onclick="aksiyonYap()">BAŞLA</button>
    <p id="durum" style="font-weight:bold; margin-top:15px; font-size:16px;"></p>
    <a href="/dashboard" style="display:block; margin-top:20px; color:#AFAFAF; font-weight:bold; text-decoration:none; padding:10px;">Dersi Terk Et</a>
</div>

<script>
    const kelimeler = {{ words|tojson }};
    const lesson_id = {{ lesson_id }};
    let index = 0;

    const kelimeDiv = document.getElementById("kelime");
    const anlamDiv = document.getElementById("anlam");
    const durumDiv = document.getElementById("durum");
    const aksiyonBtn = document.getElementById("aksiyonBtn");
    const soruTipiDiv = document.getElementById("soru-tipi");
    const avatar = document.getElementById("avatar"); 

    const SpeechRecognition = window.SpeechRecognition || window.webkitSpeechRecognition;
    const recognition = new SpeechRecognition();
    recognition.lang = 'ar-SA';
    recognition.interimResults = false;
    recognition.continuous = false; 

    function setIdle() { avatar.className = "avatar"; }
    function setTalking() { avatar.className = "avatar talking"; }
    function setListening() { avatar.className = "avatar listening"; }

    function ekraniGuncelle() {
        setIdle(); 
        if(kelimeler.length === 0) {
            Swal.fire('Hata', 'Bu derste hiç kelime yok.', 'error').then(()=>window.location.href='/dashboard');
            return;
        }
        if(index >= kelimeler.length) {
            // Ders bitti, sunucuya bildir.
            fetch('/finish_lesson/' + lesson_id, {method: 'POST'}).then(() => {
                Swal.fire('Tebrikler!', 'Dersi tamamladın!', 'success').then(() => window.location.href = '/dashboard');
            });
            return;
        }
        
        let current = kelimeler[index];
        anlamDiv.innerText = current.tr;
        
        if(current.q_type === 'speaking') {
            soruTipiDiv.innerText = "Ekranda yazanı oku.";
            kelimeDiv.innerText = current.ar;
            aksiyonBtn.innerText = "🎤 KONUŞ";
            aksiyonBtn.className = "btn btn-blue";
        } else if (current.q_type === 'listening') {
            soruTipiDiv.innerText = "Duyduğunu Arapça söyle.";
            kelimeDiv.innerText = "🔊 ❓❓❓"; 
            aksiyonBtn.innerText = "▶️ DİNLE VE SÖYLE";
            aksiyonBtn.className = "btn btn-green";
        } else if (current.q_type === 'repeat') {
            soruTipiDiv.innerText = "Benden sonra tekrar et.";
            kelimeDiv.innerText = current.ar;
            aksiyonBtn.innerText = "🔁 DİNLE VE TEKRAR ET";
            aksiyonBtn.className = "btn btn-blue";
        }
    }

    function gercekSesOku(audioUrl, callback) {
        if(!audioUrl) {
            durumDiv.innerText = "HATA: Bu kelimenin ses dosyası yüklenmemiş!";
            durumDiv.style.color = "var(--danger)";
            setTimeout(callback, 2500);
            return;
        }
        setTalking(); 
        let ses = new Audio("/static/uploads/" + audioUrl);
        ses.play().catch(e => { durumDiv.innerText = "Oynatma hatası. Tıklama yapın."; callback(); });
        ses.onended = function() { setIdle(); callback(); };
    }

    function aksiyonYap() {
        let current = kelimeler[index];
        if(current.q_type === 'speaking') { dinlemeyeBasla(); } 
        else {
            durumDiv.innerText = "🔊 Sistem konuşuyor...";
            durumDiv.style.color = "var(--primary)";
            aksiyonBtn.disabled = true;
            gercekSesOku(current.audio_file, () => { dinlemeyeBasla(); });
        }
    }

    function dinlemeyeBasla() {
        setListening(); 
        durumDiv.innerText = "Sıra sende, konuş! 🎤";
        durumDiv.style.color = "var(--primary)";
        aksiyonBtn.disabled = true;
        try { recognition.start(); } catch(e) {}
    }

    recognition.onresult = function(event) {
        setIdle(); 
        const soylenenMetin = event.results[0][0].transcript;
        durumDiv.innerText = "Yapay Zeka Analiz Ediyor... 🤖";
        
        fetch('/kontrol', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({ 'hedef_kelime': kelimeler[index].ar, 'soylenen': soylenenMetin, 'lesson_id': lesson_id })
        }).then(res => res.json()).then(data => {
            if(data.durum === 'basarili') {
                Swal.fire({ title: 'Harika!', text: data.mesaj, icon: 'success', timer: 1500, showConfirmButton: false });
                index++;
                setTimeout(() => { aksiyonBtn.disabled = false; durumDiv.innerText=""; ekraniGuncelle(); }, 1500);
            } else {
                Swal.fire({ title: 'Yanlış Telaffuz!', html: data.mesaj, icon: 'error' });
                aksiyonBtn.disabled = false;
                durumDiv.innerText = "Tekrar deneyin.";
                durumDiv.style.color = "var(--danger)";
            }
        });
    };

    recognition.onerror = function(event) {
        setIdle(); 
        if(event.error === 'no-speech') { durumDiv.innerText = "Ses duyulmadı. Butona basıp tekrar dene."; } 
        else { durumDiv.innerText = "Mikrofon hatası: " + event.error; }
        durumDiv.style.color = "var(--danger)";
        aksiyonBtn.disabled = false;
    };

    recognition.onend = function() {
        if(aksiyonBtn.disabled && durumDiv.innerText.includes("konuş!")) {
            setIdle(); aksiyonBtn.disabled = false;
            durumDiv.innerText = "Süre doldu, tekrar butona basın.";
            durumDiv.style.color = "var(--danger)";
        }
    };

    ekraniGuncelle();
</script>
""" + GLOBAL_HTML_END

HTML_ADMIN = GLOBAL_HTML_START + """
<title>Admin Paneli</title>
<div class="card" style="max-width:800px; padding:15px;">
    <h2 style="color:var(--danger);">👑 ADMİN PANELİ</h2>
    <a href="/dashboard" class="btn btn-blue" style="margin-bottom:20px;">Ana Sayfaya Dön</a>
    
    {% with messages = get_flashed_messages() %}
        {% if messages %}<div class="flash">{{ messages[0] }}</div>{% endif %}
    {% endwith %}

    <div class="admin-box">
        <h3>1. Yeni Ünite Ekle</h3>
        <form action="/admin/add_unit" method="POST" style="display:flex; gap:10px;">
            <input type="text" name="title" placeholder="Ünite Adı (Örn: Ünite 1: Aile)" required style="margin:0;">
            <button type="submit" class="btn btn-blue" style="margin:0; width:150px;">Ekle</button>
        </form>
    </div>

    <h3>Mevcut Eğitim İçeriği (Düzenle/Sil)</h3>
    {% for u in units %}
        <div class="admin-box" style="border-color:var(--primary);">
            <div style="display:flex; justify-content:space-between; align-items:center; background:#e0f2fe; padding:10px; border-radius:10px;">
                <h3 style="color:var(--primary); margin:0;">📂 {{ u.title }}</h3>
                <div>
                    <button onclick="editItem('unit', {{ u.id }}, '{{ u.title }}')" class="btn btn-yellow" style="padding:5px 10px; width:auto; margin:0;">✏️</button>
                    <a href="/admin/delete_unit/{{ u.id }}" onclick="return confirm('Bu üniteyi ve içindeki TÜM dersleri silmek istediğine emin misin?')" class="btn btn-red" style="padding:5px 10px; width:auto; margin:0;">🗑️</a>
                </div>
            </div>
            
            <form action="/admin/add_lesson" method="POST" style="display:flex; gap:10px; margin-top:10px;">
                <input type="hidden" name="unit_id" value="{{ u.id }}">
                <input type="text" name="title" placeholder="Bu üniteye Yeni Ders Ekle" required style="margin:0;">
                <button type="submit" class="btn btn-green" style="margin:0; width:150px;">Ders Ekle</button>
            </form>

            {% for lesson in u.lessons %}
                <div style="background:white; border:1px solid #ccc; padding:10px; margin-top:15px; border-radius:10px;">
                    <div style="display:flex; justify-content:space-between; align-items:center; border-bottom:2px solid #eee; padding-bottom:10px; margin-bottom:10px;">
                        <h4 style="margin:0; color:var(--success-dark);">📄 {{ lesson.title }}</h4>
                        <div>
                            <button onclick="editItem('lesson', {{ lesson.id }}, '{{ lesson.title }}')" class="btn btn-yellow" style="padding:5px 10px; width:auto; margin:0;">✏️</button>
                            <a href="/admin/delete_lesson/{{ lesson.id }}" onclick="return confirm('Dersi ve içindeki kelimeleri silmek istediğine emin misin?')" class="btn btn-red" style="padding:5px 10px; width:auto; margin:0;">🗑️</a>
                        </div>
                    </div>
                    
                    <form action="/admin/add_word" method="POST" enctype="multipart/form-data" style="display:flex; flex-direction:column; gap:8px; margin-bottom:10px; background:#f0f9ff; padding:10px; border-radius:10px;">
                        <input type="hidden" name="lesson_id" value="{{ lesson.id }}">
                        <input type="text" name="ar" placeholder="Arapça Kelime" required style="direction:rtl; font-family:'Tajawal'; font-size:20px;">
                        <input type="text" name="tr" placeholder="Türkçe Anlamı" required>
                        <select name="q_type" onchange="this.nextElementSibling.style.display = (this.value == 'speaking') ? 'none' : 'block';">
                            <option value="speaking">Konuşma (Speaking - Ekranda Oku)</option>
                            <option value="listening">Dinleme (Listening - Sesten Duy ve Söyle)</option>
                            <option value="repeat">Tekrar (Repeat - Duy ve Tekrar Et)</option>
                        </select>
                        <div style="display:none;">
                            <label style="font-weight:bold; color:var(--danger); font-size:14px;">🔊 Ses Dosyası Yükle (Zorunlu):</label>
                            <input type="file" name="audio" accept="audio/*">
                        </div>
                        <button type="submit" class="btn btn-blue">Kelimeyi Ekle</button>
                    </form>

                    {% if lesson.words %}
                    <div style="overflow-x:auto;">
                        <table>
                            <tr><th>Arapça</th><th>Türkçe</th><th>Tür</th><th>İşlem</th></tr>
                            {% for w in lesson.words %}
                            <tr>
                                <td style="direction:rtl; font-weight:bold; font-size:18px;">{{ w.ar }}</td>
                                <td>{{ w.tr }}</td>
                                <td>{{ w.q_type }}</td>
                                <td><a href="/admin/delete_word/{{ w.id }}" class="btn btn-red" style="padding:5px; width:auto; margin:0;" onclick="return confirm('Kelime silinsin mi?')">🗑️</a></td>
                            </tr>
                            {% endfor %}
                        </table>
                    </div>
                    {% endif %}
                </div>
            {% endfor %}
        </div>
    {% endfor %}
</div>
<script>
function editItem(type, id, oldName) {
    let newName = prompt("Yeni ismi girin:", oldName);
    if (newName && newName !== oldName) {
        window.location.href = `/admin/edit_${type}/${id}?new_title=${encodeURIComponent(newName)}`;
    }
}
</script>
""" + GLOBAL_HTML_END

@app.route('/')
def index():
    return redirect(url_for('dashboard')) if current_user.is_authenticated else redirect(url_for('login'))

@app.route('/login', methods=['GET', 'POST'])
def login():
    if current_user.is_authenticated: return redirect(url_for('dashboard'))
    if request.method == 'POST':
        user = User.query.filter_by(username=request.form['username']).first()
        if user and check_password_hash(user.password, request.form['password']):
            remember_me = True if request.form.get('remember') else False
            login_user(user, remember=remember_me)
            return redirect(url_for('dashboard'))
        flash('Hatalı kullanıcı adı veya şifre!')
    html = GLOBAL_HTML_START + "<title>Giriş</title><div class='card'><h2>Giriş Yap</h2>{% with messages = get_flashed_messages() %}{% if messages %}<div class='flash'>{{ messages[0] }}</div>{% endif %}{% endwith %}<form method='POST'><input type='text' name='username' placeholder='Kullanıcı Adı' required><input type='password' name='password' placeholder='Şifre' required><div style='display:flex; align-items:center; margin: 15px 5px; justify-content:left;'><input type='checkbox' name='remember' id='remember' style='width:20px; height:20px; margin:0 10px 0 0; cursor:pointer;'><label for='remember' style='cursor:pointer; font-weight:bold; font-size:16px; color:var(--text);'>Beni Hatırla</label></div><button class='btn btn-blue'>GİRİŞ</button></form><a href='/register' style='display:block; margin-top:20px; color:var(--primary); font-weight:bold;'>Kayıt Ol</a></div>" + GLOBAL_HTML_END
    return render_template_string(html)

@app.route('/register', methods=['GET', 'POST'])
def register():
    if current_user.is_authenticated: return redirect(url_for('dashboard'))
    if request.method == 'POST':
        if User.query.filter_by(username=request.form['username']).first(): flash('Bu kullanıcı adı zaten alınmış!')
        else:
            yeni = User(username=request.form['username'], password=generate_password_hash(request.form['password']))
            db.session.add(yeni)
            db.session.commit()
            flash('Kayıt başarılı! Şimdi giriş yapabilirsiniz.')
            return redirect(url_for('login'))
    html = GLOBAL_HTML_START + "<title>Kayıt</title><div class='card'><h2>Kayıt Ol</h2>{% with messages = get_flashed_messages() %}{% if messages %}<div class='flash'>{{ messages[0] }}</div>{% endif %}{% endwith %}<form method='POST'><input type='text' name='username' placeholder='Kullanıcı Adı' required><input type='password' name='password' placeholder='Şifre' required><button class='btn btn-green'>KAYIT OL</button></form><a href='/login' style='display:block; margin-top:20px; color:var(--primary); font-weight:bold;'>Zaten hesabım var (Giriş)</a></div>" + GLOBAL_HTML_END
    return render_template_string(html)

@app.route('/logout')
@login_required
def logout():
    logout_user()
    return redirect(url_for('login'))

@app.route('/dashboard')
@login_required
def dashboard():
    units = Unit.query.all()
    # Kullanıcının tamamladığı derslerin ID'lerini bir listeye al (Arayüzde ✅ göstermek için)
    completed = CompletedLesson.query.filter_by(user_id=current_user.id).all()
    completed_ids = [c.lesson_id for c in completed]
    return render_template_string(HTML_DASHBOARD, user=current_user, units=units, completed_ids=completed_ids)

@app.route('/lesson/<int:lesson_id>')
@login_required
def lesson(lesson_id):
    lesson_data = Lesson.query.get_or_404(lesson_id)
    words = [{"ar": w.ar, "tr": w.tr, "q_type": w.q_type, "audio_file": w.audio_file} for w in lesson_data.words]
    # YENİ: Kelimeleri tamamen RASTGELE sırala
    random.shuffle(words)
    return render_template_string(HTML_LESSON, words=words, lesson_id=lesson_id)

@app.route('/kontrol', methods=['POST'])
@login_required
def kontrol():
    veri = request.get_json()
    hedef = veri.get('hedef_kelime', '')
    soylenen = veri.get('soylenen', '')
    lesson_id = veri.get('lesson_id')
    
    benzerlik = SequenceMatcher(None, strip_tashkeel(hedef.replace('ة', 'ه')), strip_tashkeel(soylenen.replace('ة', 'ه'))).ratio()

    if benzerlik >= 0.85:
        # YENİ: Tamamlanan ders için az (2 XP), yeni ders için tam (10 XP) puan ver.
        is_completed = CompletedLesson.query.filter_by(user_id=current_user.id, lesson_id=lesson_id).first()
        kazanilan_puan = 2 if is_completed else 10
        current_user.score += kazanilan_puan
        db.session.commit()
        return jsonify({'durum': 'basarili', 'mesaj': f'Doğru! (+{kazanilan_puan} XP)<br>Söylediğin: {soylenen}'})
    return jsonify({'durum': 'hata', 'mesaj': f'Söylediğin: {soylenen}<br>Olması Gereken: {hedef}'})

@app.route('/finish_lesson/<int:lesson_id>', methods=['POST'])
@login_required
def finish_lesson(lesson_id):
    # Kullanıcı dersi bitirdiğinde veritabanına kaydet
    if not CompletedLesson.query.filter_by(user_id=current_user.id, lesson_id=lesson_id).first():
        db.session.add(CompletedLesson(user_id=current_user.id, lesson_id=lesson_id))
        db.session.commit()
    return "OK"

# --- ADMİN İŞLEMLERİ ---
@app.route('/admin')
@login_required
def admin():
    if current_user.role != 'admin': return redirect(url_for('dashboard'))
    units = Unit.query.all()
    return render_template_string(HTML_ADMIN, units=units)

@app.route('/admin/add_unit', methods=['POST'])
@login_required
def add_unit():
    if current_user.role == 'admin':
        db.session.add(Unit(title=request.form['title']))
        db.session.commit()
        flash("Ünite eklendi!")
    return redirect(url_for('admin'))

@app.route('/admin/add_lesson', methods=['POST'])
@login_required
def add_lesson():
    if current_user.role == 'admin':
        db.session.add(Lesson(unit_id=request.form['unit_id'], title=request.form['title']))
        db.session.commit()
        flash("Ders eklendi!")
    return redirect(url_for('admin'))

@app.route('/admin/add_word', methods=['POST'])
@login_required
def add_word():
    if current_user.role == 'admin':
        audio_filename = None
        if request.form['q_type'] in ['listening', 'repeat']:
            file = request.files.get('audio')
            if file and file.filename != '':
                ext = file.filename.rsplit('.', 1)[-1].lower()
                audio_filename = str(uuid.uuid4()) + '.' + ext
                file.save(os.path.join(app.config['UPLOAD_FOLDER'], audio_filename))
        db.session.add(Word(lesson_id=request.form['lesson_id'], ar=request.form['ar'], tr=request.form['tr'], q_type=request.form['q_type'], audio_file=audio_filename))
        db.session.commit()
        flash("Kelime başarıyla eklendi!")
    return redirect(url_for('admin'))

@app.route('/admin/delete_unit/<int:id>')
@login_required
def delete_unit(id):
    if current_user.role == 'admin':
        Unit.query.filter_by(id=id).delete()
        db.session.commit()
        flash("Ünite silindi!")
    return redirect(url_for('admin'))

@app.route('/admin/delete_lesson/<int:id>')
@login_required
def delete_lesson(id):
    if current_user.role == 'admin':
        Lesson.query.filter_by(id=id).delete()
        db.session.commit()
        flash("Ders silindi!")
    return redirect(url_for('admin'))

@app.route('/admin/delete_word/<int:id>')
@login_required
def delete_word(id):
    if current_user.role == 'admin':
        Word.query.filter_by(id=id).delete()
        db.session.commit()
        flash("Kelime silindi!")
    return redirect(url_for('admin'))

@app.route('/admin/edit_unit/<int:id>')
@login_required
def edit_unit(id):
    if current_user.role == 'admin':
        unit = Unit.query.get(id)
        if unit:
            unit.title = request.args.get('new_title')
            db.session.commit()
            flash("Ünite adı güncellendi!")
    return redirect(url_for('admin'))

@app.route('/admin/edit_lesson/<int:id>')
@login_required
def edit_lesson(id):
    if current_user.role == 'admin':
        lesson = Lesson.query.get(id)
        if lesson:
            lesson.title = request.args.get('new_title')
            db.session.commit()
            flash("Ders adı güncellendi!")
    return redirect(url_for('admin'))

with app.app_context():
    db.create_all()
    if not User.query.filter_by(username='Mervan').first(): db.session.add(User(username='Mervan', password=generate_password_hash('Mmty2676*'), role='admin'))
    if not User.query.filter_by(username='Merve').first(): db.session.add(User(username='Merve', password=generate_password_hash('2676274'), role='admin'))
    db.session.commit()

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=8080)
