import sqlite3
import hashlib
import re
import uuid
from datetime import datetime
from flask import session

class UserManager:
    def __init__(self, db_path='users.db'):
        self.db_path = db_path
        self.init_database()
    
    def init_database(self):
        """Kullanıcı veritabanını oluştur"""
        conn = sqlite3.connect(self.db_path)
        cursor = conn.cursor()
        
        # Kullanıcılar tablosu
        cursor.execute('''
            CREATE TABLE IF NOT EXISTS users (
                id INTEGER PRIMARY KEY AUTOINCREMENT,
                email TEXT UNIQUE NOT NULL,
                password_hash TEXT NOT NULL,
                full_name TEXT NOT NULL,
                company TEXT,
                phone TEXT,
                profile_image TEXT,
                user_uuid TEXT UNIQUE,
                created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
                last_login DATETIME,
                is_active BOOLEAN DEFAULT 1,
                is_admin BOOLEAN DEFAULT 0,
                created_by INTEGER
            )
        ''')
        
        # Eğer profile_image sütunu yoksa ekle
        try:
            cursor.execute('ALTER TABLE users ADD COLUMN profile_image TEXT')
        except sqlite3.OperationalError:
            # Sütun zaten varsa hata vermez
            pass
        # Eğer created_by sütunu yoksa ekle
        try:
            cursor.execute('ALTER TABLE users ADD COLUMN created_by INTEGER')
        except sqlite3.OperationalError:
            pass
        
        # Eğer timezone sütunu yoksa ekle
        try:
            cursor.execute('ALTER TABLE users ADD COLUMN timezone TEXT DEFAULT "Europe/Istanbul"')
        except sqlite3.OperationalError:
            # Sütun zaten varsa hata vermez
            pass
        
        # Yeni kullanıcı sistemi için alanları ekle
        try:
            cursor.execute('ALTER TABLE users ADD COLUMN user_type TEXT DEFAULT "standart"')
        except sqlite3.OperationalError:
            pass
            
        try:
            cursor.execute('ALTER TABLE users ADD COLUMN access_type TEXT DEFAULT "nfc"')
        except sqlite3.OperationalError:
            pass
            
        try:
            cursor.execute('ALTER TABLE users ADD COLUMN card_uuid TEXT')
        except sqlite3.OperationalError:
            pass
            
        try:
            cursor.execute('ALTER TABLE users ADD COLUMN time_limit_start DATETIME')
        except sqlite3.OperationalError:
            pass
            
        try:
            cursor.execute('ALTER TABLE users ADD COLUMN time_limit_end DATETIME')
        except sqlite3.OperationalError:
            pass
        
        # Kullanıcı cihazları tablosu
        cursor.execute('''
            CREATE TABLE IF NOT EXISTS user_devices (
                id INTEGER PRIMARY KEY AUTOINCREMENT,
                user_id INTEGER NOT NULL,
                device_name TEXT NOT NULL,
                device_type TEXT NOT NULL,
                ip_address TEXT,
                serial_number TEXT,
                created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
                updated_at DATETIME DEFAULT CURRENT_TIMESTAMP,
                is_active BOOLEAN DEFAULT 1,
                FOREIGN KEY (user_id) REFERENCES users (id)
            )
        ''')
        
        # Eğer updated_at sütunu yoksa ekle
        try:
            cursor.execute('ALTER TABLE user_devices ADD COLUMN updated_at DATETIME')
            # Mevcut kayıtlar için updated_at değerini created_at'e eşitle
            cursor.execute('UPDATE user_devices SET updated_at = created_at WHERE updated_at IS NULL')
        except sqlite3.OperationalError:
            # Sütun zaten varsa hata vermez
            pass
        
        # Kullanıcı geçiş kayıtları tablosu
        cursor.execute('''
            CREATE TABLE IF NOT EXISTS user_access_logs (
                id INTEGER PRIMARY KEY AUTOINCREMENT,
                user_id INTEGER NOT NULL,
                device_id INTEGER,
                person_name TEXT NOT NULL,
                region TEXT,
                access_type TEXT,
                notes TEXT,
                access_status TEXT,
                access_time DATETIME DEFAULT CURRENT_TIMESTAMP,
                FOREIGN KEY (user_id) REFERENCES users (id),
                FOREIGN KEY (device_id) REFERENCES user_devices (id)
            )
        ''')
        
        # Varsayılan admin ekleme kaldırıldı. Ana hesap zaten admin olacaktır.
        # Eski kurulumlardan kalan varsayılan admin kaydını temizle
        try:
            cursor.execute("DELETE FROM users WHERE email = ?", ('admin@gecis.com',))
        except Exception:
            pass
        
        # Kullanıcı-cihaz erişim izinleri tablosu
        cursor.execute('''
            CREATE TABLE IF NOT EXISTS user_device_permissions (
                id INTEGER PRIMARY KEY AUTOINCREMENT,
                user_id INTEGER NOT NULL,
                device_serial TEXT NOT NULL,
                granted_at DATETIME DEFAULT CURRENT_TIMESTAMP,
                granted_by INTEGER,
                is_active BOOLEAN DEFAULT 1,
                FOREIGN KEY (user_id) REFERENCES users (id),
                FOREIGN KEY (granted_by) REFERENCES users (id)
            )
        ''')
        
        conn.commit()
        conn.close()
    
    def hash_password(self, password):
        """Şifreyi hash'le"""
        return hashlib.sha256(password.encode()).hexdigest()
 
    def _generate_unique_numeric_user_uuid_12(self) -> str:
        """Sadece rakamlardan oluşan 12 haneli benzersiz user_uuid üretir."""
        import random
        while True:
            candidate = str(random.randint(0, 10**12 - 1)).zfill(12)
            try:
                conn = sqlite3.connect(self.db_path)
                cur = conn.cursor()
                row = cur.execute('SELECT 1 FROM users WHERE user_uuid = ? LIMIT 1', (candidate,)).fetchone()
                conn.close()
                if not row:
                    return candidate
            except Exception:
                # Her ihtimale karşı, çakışma kabul etme ve tekrar dene
                continue

    def ensure_mobile_uuid(self, user_id: int) -> str:
        """Verilen kullanıcı için 12 haneli numerik user_uuid yoksa oluşturur ve döndürür."""
        try:
            conn = sqlite3.connect(self.db_path); conn.row_factory = sqlite3.Row
            cur = conn.cursor()
            row = cur.execute('SELECT user_uuid FROM users WHERE id = ?', (user_id,)).fetchone()
            if not row:
                conn.close()
                return ''
            existing = (row['user_uuid'] or '').strip() if row else ''
            if existing:
                conn.close()
                return existing
            # Oluştur ve yaz
            new_uuid = self._generate_unique_numeric_user_uuid_12()
            cur.execute('UPDATE users SET user_uuid = ? WHERE id = ?', (new_uuid, user_id))
            conn.commit(); conn.close()
            # data.db'ye yansıt (aynı id varsa)
            try:
                dconn = sqlite3.connect('data.db'); dconn.row_factory = sqlite3.Row
                dcur = dconn.cursor()
                dcur.execute('UPDATE users SET user_uuid = ? WHERE id = ?', (new_uuid, user_id))
                dconn.commit(); dconn.close()
            except Exception:
                pass
            return new_uuid
        except Exception:
            return ''

    def validate_email(self, email):
        """Email formatını kontrol et"""
        pattern = r'^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$'
        return re.match(pattern, email) is not None
    
    def generate_user_uuid(self):
        """Benzersiz kullanıcı UUID'si oluştur (32 bit tamsayı)"""
        # Direkt 32 bit tamsayı üret (0-4294967295 arası)
        import random
        uuid_int = random.randint(0, 2**32 - 1)
        return str(uuid_int)
    
    def validate_password(self, password):
        """Şifre güvenliğini kontrol et"""
        if len(password) < 6:
            return False, "password_too_short"
        return True, "OK"
    
    def register_user(self, email, password, full_name, company=None, phone=None):
        try:
            conn = sqlite3.connect(self.db_path)
            conn.row_factory = sqlite3.Row
            cursor = conn.cursor()
            # Tabloları oluştur
            cursor.execute('''
                CREATE TABLE IF NOT EXISTS users (
                    id INTEGER PRIMARY KEY AUTOINCREMENT,
                    email TEXT UNIQUE,
                    password_hash TEXT,
                    full_name TEXT,
                    company TEXT,
                    phone TEXT,
                    user_type TEXT DEFAULT 'standart',
                    access_type TEXT,
                    is_active INTEGER DEFAULT 1,
                    created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
                    last_login DATETIME,
                    profile_image TEXT,
                    user_uuid TEXT,
                    card_uuid TEXT,
                    is_admin BOOLEAN DEFAULT 0
                )
            ''')
            # İlk admin kontrolü
            admin_row = cursor.execute('SELECT COUNT(*) AS c FROM users WHERE is_admin=1').fetchone()
            make_admin = (admin_row and int(admin_row['c'] or 0) == 0)
            # İlk admin için 12 haneli numerik user_uuid üret
            admin_user_uuid = None
            if make_admin:
                admin_user_uuid = self._generate_unique_numeric_user_uuid_12()
            # Kullanıcı ekle
            try:
                from flask import session as _sess
                created_by = _sess.get('user_id')
            except Exception:
                created_by = None
            cursor.execute('''
                INSERT INTO users (email, password_hash, full_name, company, phone, user_type, access_type, is_active, is_admin, user_uuid, created_by)
                VALUES (?, ?, ?, ?, ?, 'standart', NULL, 1, ?, ?, ?)
            ''', (email, self.hash_password(password), full_name, company, phone, 1 if make_admin else 0, admin_user_uuid, created_by))
            conn.commit()
            conn.close()
            return True, 'Kayıt başarılı! Şimdi giriş yapabilirsiniz.'
        except sqlite3.IntegrityError:
            return False, 'email_already_exists'
        except Exception as e:
            return False, f'registration_error: {str(e)}'
    
    def authenticate_user(self, email, password):
        """Kullanıcı girişi"""
        try:
            conn = sqlite3.connect(self.db_path)
            cursor = conn.cursor()
            
            email_norm = (email or '').strip().lower()
            cursor.execute('''
                SELECT id, email, password_hash, full_name, is_admin, is_active, company
                FROM users WHERE lower(email) = ?
            ''', (email_norm,))
            
            user = cursor.fetchone()
            conn.close()
            
            if not user:
                return False, "user_not_found"
            
            user_id, user_email, password_hash, full_name, is_admin, is_active, company = user
            
            if not is_active:
                return False, "account_inactive"
            
            if password_hash != self.hash_password(password):
                return False, "invalid_password"

            # Tek-admin kuralı: Admin dışında giriş engellensin (isteğe bağlı, admin varsa)
            try:
                conn2 = sqlite3.connect(self.db_path); conn2.row_factory = sqlite3.Row
                c2 = conn2.cursor()
                adm = c2.execute('SELECT email FROM users WHERE is_admin=1 ORDER BY id ASC LIMIT 1').fetchone()
                conn2.close()
                if adm and adm['email']:
                    # Sadece ilk admin hesabına giriş izni ver
                    if user_email != adm['email']:
                        return False, "login_error"  # Lokalizasyonlu genel mesaj
            except Exception:
                pass
            
            # Son giriş zamanını güncelle
            self.update_last_login(user_id)
            
            return True, {
                'id': user_id,
                'email': user_email,
                'full_name': full_name,
                'is_admin': bool(is_admin),
                'company': company if company else ''
            }
            
        except Exception as e:
            return False, "login_error_generic"
    
    def update_last_login(self, user_id):
        """Son giriş zamanını güncelle"""
        try:
            conn = sqlite3.connect(self.db_path)
            cursor = conn.cursor()
            
            cursor.execute('''
                UPDATE users SET last_login = ? WHERE id = ?
            ''', (datetime.now(), user_id))
            
            conn.commit()
            conn.close()
        except Exception as e:
            print(f"Son giriş güncelleme hatası: {e}")
    
    def get_user_by_email(self, email):
        """Email'e göre kullanıcı getir"""
        try:
            conn = sqlite3.connect(self.db_path)
            cursor = conn.cursor()
            
            cursor.execute('SELECT * FROM users WHERE email = ?', (email,))
            user = cursor.fetchone()
            
            conn.close()
            return user
        except Exception as e:
            print(f"Kullanıcı getirme hatası: {e}")
            return None
    
    def get_user_by_id(self, user_id):
        """ID'ye göre kullanıcı getir"""
        try:
            conn = sqlite3.connect(self.db_path)
            conn.row_factory = sqlite3.Row
            cursor = conn.cursor()
            
            cursor.execute('''
                SELECT id, email, full_name, company, phone, profile_image, user_uuid, created_at, last_login, is_admin, access_type, card_uuid, is_active
                FROM users WHERE id = ?
            ''', (user_id,))
            
            user = cursor.fetchone()
            conn.close()
            
            if user:
                return dict(user)
            return None
            
        except Exception as e:
            print(f"Kullanıcı getirme hatası: {e}")
            return None
    
    def get_user_devices(self, user_id):
        """Kullanıcının cihazlarını getir"""
        try:
            conn = sqlite3.connect(self.db_path)
            conn.row_factory = sqlite3.Row
            cursor = conn.cursor()
            
            # user_device_access tablosundan kullanıcının cihaz ID'lerini al
            cursor.execute('''
                SELECT device_id FROM user_device_access 
                WHERE user_id = ?
            ''', (user_id,))
            
            device_access = cursor.fetchall()
            conn.close()
            
            if not device_access:
                return []
            
            # data.db'den cihaz bilgilerini al
            data_conn = sqlite3.connect('data.db')
            data_conn.row_factory = sqlite3.Row
            data_cursor = data_conn.cursor()
            
            devices = []
            for access in device_access:
                device_id = access['device_id']
                data_cursor.execute('''
                    SELECT id, ad as device_name, seri_no 
                    FROM cihazlar 
                    WHERE id = ?
                ''', (device_id,))
                
                device_row = data_cursor.fetchone()
                if device_row:
                    devices.append({
                        'id': str(device_row['id']),
                        'name': device_row['device_name'] or f'Cihaz {device_row["id"]}',
                        'serial_number': device_row['seri_no'] or str(device_row['id'])
                    })
            
            data_conn.close()
            return devices
        except Exception as e:
            print(f"Cihaz getirme hatası: {e}")
            return []
    
    def get_all_user_devices(self):
        """Tüm kullanıcı cihazlarını getir"""
        try:
            conn = sqlite3.connect(self.db_path)
            conn.row_factory = sqlite3.Row  # Dictionary-like access için
            cursor = conn.cursor()
            
            cursor.execute('''
                SELECT * FROM user_devices 
                WHERE is_active = 1
                ORDER BY created_at DESC
            ''')
            
            devices = cursor.fetchall()
            conn.close()
            return devices
        except Exception as e:
            print(f"Tüm cihaz getirme hatası: {e}")
            return []
    
    def add_user_device(self, user_id, device_name, device_type, ip_address=None, serial_number=None):
        """Kullanıcıya cihaz ekle"""
        try:
            conn = sqlite3.connect(self.db_path)
            cursor = conn.cursor()
            
            # Aynı seri numarasına sahip cihaz var mı kontrol et (tüm kullanıcılar arasında)
            cursor.execute('''
                SELECT id FROM user_devices 
                WHERE serial_number = ? AND is_active = 1
            ''', (serial_number,))
            
            existing_device = cursor.fetchone()
            if existing_device:
                return False, "device_serial_exists"
            
            cursor.execute('''
                INSERT INTO user_devices (user_id, device_name, device_type, ip_address, serial_number)
                VALUES (?, ?, ?, ?, ?)
            ''', (user_id, device_name, device_type, ip_address, serial_number))
            
            device_id = cursor.lastrowid
            conn.commit()
            conn.close()
            
            # data.db dosyasındaki user_devices tablosunu da güncelle
            try:
                data_conn = sqlite3.connect('data.db')
                data_cursor = data_conn.cursor()
                data_cursor.execute('''
                    INSERT OR REPLACE INTO user_devices 
                    (id, user_id, device_name, device_type, ip_address, serial_number, created_at, updated_at, is_active)
                    VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
                ''', (device_id, user_id, device_name, device_type, ip_address, serial_number, datetime.now(), datetime.now(), 1))
                data_conn.commit()
                data_conn.close()
            except Exception as e:
                print(f"data.db user_devices tablosu güncelleme hatası: {e}")
            
            return True, "device_added_successfully"
        except Exception as e:
            return False, f"device_add_error: {str(e)}"
    
    def get_user_access_logs(self, user_id, limit=100):
        """Kullanıcının geçiş kayıtlarını getir"""
        try:
            conn = sqlite3.connect(self.db_path)
            conn.row_factory = sqlite3.Row  # Dictionary-like access için
            cursor = conn.cursor()
            
            # Tablo yapısı kontrolü (debug için gerekirse açılabilir)
            # cursor.execute("PRAGMA table_info(user_access_logs)")
            # table_info = cursor.fetchall()
            
            # Kayıt sayısını kontrol et
            cursor.execute("SELECT COUNT(*) as count FROM user_access_logs WHERE user_id = ?", (user_id,))
            count_result = cursor.fetchone()
            print(f"Kullanıcı {user_id} için kayıt sayısı: {count_result['count'] if count_result else 0}")
            
            # Eğer kayıt yoksa boş liste döndür
            if not count_result or count_result['count'] == 0:
                conn.close()
                return []
            
            cursor.execute('''
                SELECT * FROM user_access_logs 
                WHERE user_id = ?
                ORDER BY access_time DESC
                LIMIT ?
            ''', (user_id, limit))
            
            logs = cursor.fetchall()
            conn.close()
            return logs
        except Exception as e:
            print(f"Geçiş kayıtları getirme hatası: {e}")
            print(f"Hata detayı: {type(e).__name__}")
            import traceback
            traceback.print_exc()
            return []
    
    def add_access_log(self, user_id, device_id, person_name, region, access_type, notes, access_status):
        """Geçiş kaydı ekle"""
        try:
            conn = sqlite3.connect(self.db_path)
            cursor = conn.cursor()
            
            # Opsiyonel access_time desteği (tablo sütunu varsa)
            has_access_time = False
            try:
                cursor.execute("PRAGMA table_info(user_access_logs)")
                cols = [row[1] for row in cursor.fetchall()]
                has_access_time = 'access_time' in cols
            except Exception:
                has_access_time = False

            if has_access_time and hasattr(self, 'last_access_time') and getattr(self, 'last_access_time'):
                cursor.execute('''
                    INSERT INTO user_access_logs 
                    (user_id, device_id, person_name, region, access_type, notes, access_status, access_time)
                    VALUES (?, ?, ?, ?, ?, ?, ?, ?)
                ''', (user_id, device_id, person_name, region, access_type, notes, access_status, getattr(self, 'last_access_time')))
            else:
                cursor.execute('''
                    INSERT INTO user_access_logs 
                    (user_id, device_id, person_name, region, access_type, notes, access_status)
                    VALUES (?, ?, ?, ?, ?, ?, ?)
                ''', (user_id, device_id, person_name, region, access_type, notes, access_status))
            
            conn.commit()
            conn.close()
            return True
        except Exception as e:
            print(f"Geçiş kaydı ekleme hatası: {e}")
            return False
    
    def get_user_device_by_id(self, user_id, device_id):
        """Kullanıcının belirli bir cihazını getir"""
        try:
            conn = sqlite3.connect(self.db_path)
            conn.row_factory = sqlite3.Row  # Dictionary-like access için
            cursor = conn.cursor()
            
            cursor.execute('''
                SELECT * FROM user_devices 
                WHERE id = ? AND user_id = ? AND is_active = 1
            ''', (device_id, user_id))
            
            device = cursor.fetchone()
            conn.close()
            return device
        except Exception as e:
            print(f"Cihaz getirme hatası: {e}")
            return None
    
    def update_user_device(self, user_id, serial_number, device_name, device_type, ip_address=None):
        """Kullanıcının cihazını güncelle"""
        try:
            conn = sqlite3.connect(self.db_path)
            cursor = conn.cursor()
            
            # Önce cihazın var olup olmadığını kontrol et
            cursor.execute('''
                SELECT id FROM user_devices 
                WHERE serial_number = ? AND user_id = ? AND is_active = 1
            ''', (serial_number, user_id))
            
            device = cursor.fetchone()
            if not device:
                conn.close()
                return False, "device_not_found"
            
            # Aynı seri numarasına sahip başka cihaz var mı kontrol et (kendi cihazı hariç)
            cursor.execute('''
                SELECT id FROM user_devices 
                WHERE serial_number = ? AND id != ? AND is_active = 1
            ''', (serial_number, device[0]))
            
            existing_device = cursor.fetchone()
            if existing_device:
                conn.close()
                return False, "device_serial_exists"
            
            cursor.execute('''
                UPDATE user_devices 
                SET device_name = ?, device_type = ?, ip_address = ?, updated_at = ?
                WHERE serial_number = ? AND user_id = ?
            ''', (device_name, device_type, ip_address, datetime.now(), serial_number, user_id))
            
            if cursor.rowcount == 0:
                conn.close()
                return False, "device_update_failed"
            
            conn.commit()
            conn.close()
            
            # data.db dosyasındaki user_devices tablosunu da güncelle
            try:
                data_conn = sqlite3.connect('data.db')
                data_cursor = data_conn.cursor()
                data_cursor.execute('''
                    UPDATE user_devices 
                    SET device_name = ?, device_type = ?, ip_address = ?, updated_at = ?
                    WHERE serial_number = ? AND user_id = ?
                ''', (device_name, device_type, ip_address, datetime.now(), serial_number, user_id))
                data_conn.commit()
                data_conn.close()
            except Exception as e:
                print(f"data.db user_devices tablosu güncelleme hatası: {e}")
            
            return True, "device_updated_successfully"
        except Exception as e:
            return False, f"device_update_error: {str(e)}"
    
    def delete_user_device(self, user_id, serial_number):
        """Kullanıcının cihazını sil (soft delete)"""
        try:
            conn = sqlite3.connect(self.db_path)
            cursor = conn.cursor()
            
            cursor.execute('''
                UPDATE user_devices 
                SET is_active = 0, updated_at = ?
                WHERE serial_number = ? AND user_id = ?
            ''', (datetime.now(), serial_number, user_id))
            
            if cursor.rowcount == 0:
                conn.close()
                return False, "device_not_found"
            
            conn.commit()
            conn.close()
            
            # data.db dosyasındaki user_devices tablosunu da güncelle
            try:
                data_conn = sqlite3.connect('data.db')
                data_cursor = data_conn.cursor()
                data_cursor.execute('''
                    UPDATE user_devices 
                    SET is_active = 0, updated_at = ?
                    WHERE serial_number = ? AND user_id = ?
                ''', (datetime.now(), serial_number, user_id))
                data_conn.commit()
                data_conn.close()
            except Exception as e:
                print(f"data.db user_devices tablosu güncelleme hatası: {e}")
            
            return True, "device_deleted_successfully"
        except Exception as e:
            return False, f"device_delete_error: {str(e)}"

    def update_user_profile(self, user_id, full_name, email, company, phone, 
                           current_password, new_password, confirm_password, profile_image=None):
        """Kullanıcı profilini güncelle"""
        try:
            conn = sqlite3.connect(self.db_path)
            cursor = conn.cursor()
            
            # Kullanıcıyı kontrol et
            cursor.execute('SELECT password_hash FROM users WHERE id = ?', (user_id,))
            user = cursor.fetchone()
            
            if not user:
                conn.close()
                return False, "Kullanıcı bulunamadı"
            
            # Şifre değişikliği varsa kontrol et
            if new_password:
                if not current_password:
                    conn.close()
                    return False, "Mevcut şifre gerekli"
                
                if self.hash_password(current_password) != user[0]:
                    conn.close()
                    return False, "Mevcut şifre yanlış"
                
                if new_password != confirm_password:
                    conn.close()
                    return False, "Yeni şifreler eşleşmiyor"
                
                # Şifre güvenliğini kontrol et
                is_valid, message = self.validate_password(new_password)
                if not is_valid:
                    conn.close()
                    return False, "Şifre çok kısa (en az 6 karakter)"
                
                password_hash = self.hash_password(new_password)
            else:
                password_hash = user[0]  # Mevcut şifreyi koru
            
            # Email benzersizliğini kontrol et
            cursor.execute('SELECT id FROM users WHERE email = ? AND id != ?', (email, user_id))
            if cursor.fetchone():
                conn.close()
                return False, "Bu e-posta adresi zaten kullanılıyor"
            
            # Profili güncelle
            print(f"Profil güncelleme - profile_image: {profile_image}")
            if profile_image:
                cursor.execute('''
                    UPDATE users 
                    SET full_name = ?, email = ?, company = ?, phone = ?, password_hash = ?, profile_image = ?
                    WHERE id = ?
                ''', (full_name, email, company, phone, password_hash, profile_image, user_id))
                print(f"Profil resmi ile güncelleme yapıldı: {profile_image}")
            else:
                cursor.execute('''
                    UPDATE users 
                    SET full_name = ?, email = ?, company = ?, phone = ?, password_hash = ?
                    WHERE id = ?
                ''', (full_name, email, company, phone, password_hash, user_id))
                print("Profil resmi olmadan güncelleme yapıldı")
            
            conn.commit()
            conn.close()
            
            # data.db dosyasındaki users tablosunu da güncelle
            try:
                data_conn = sqlite3.connect('data.db')
                data_cursor = data_conn.cursor()
                data_cursor.execute('''
                    INSERT OR REPLACE INTO users (id, full_name, user_uuid)
                    SELECT id, full_name, user_uuid FROM users WHERE id = ?
                ''', (user_id,))
                data_conn.commit()
                data_conn.close()
            except Exception as e:
                print(f"data.db users tablosu güncelleme hatası: {e}")
            
            return True, "Profil başarıyla güncellendi"
            
        except Exception as e:
            return False, f"Profil güncelleme hatası: {str(e)}"
    
    def delete_user_account(self, user_id):
        """Kullanıcı hesabını ve tüm verilerini sil"""
        try:
            conn = sqlite3.connect(self.db_path)
            cursor = conn.cursor()
            
            # Kullanıcının cihazlarını al
            cursor.execute('SELECT serial_number FROM user_devices WHERE user_id = ?', (user_id,))
            user_devices = cursor.fetchall()
            device_serials = [device[0] for device in user_devices]
            
            # Ana veritabanından da sil
            main_conn = sqlite3.connect('data.db')
            main_cursor = main_conn.cursor()
            
            # Kullanıcının cihazlarını ana tablodan sil
            for serial in device_serials:
                main_cursor.execute('DELETE FROM cihazlar WHERE id = ?', (serial,))
            
            # Kullanıcının access log'larını sil
            if device_serials:
                placeholders = ','.join(['?' for _ in device_serials])
                main_cursor.execute(f'DELETE FROM access_logs WHERE device_id IN ({placeholders})', device_serials)
                main_cursor.execute(f'DELETE FROM device_cards WHERE device_id IN ({placeholders})', device_serials)
            
            main_conn.commit()
            main_conn.close()
            
            # Kullanıcı veritabanından tüm verilerini sil
            cursor.execute('DELETE FROM user_access_logs WHERE user_id = ?', (user_id,))
            cursor.execute('DELETE FROM user_devices WHERE user_id = ?', (user_id,))
            cursor.execute('DELETE FROM users WHERE id = ?', (user_id,))
            
            conn.commit()
            conn.close()
            
            return True, "Hesabınız ve tüm verileriniz başarıyla silindi"
            
        except Exception as e:
            return False, f"Hesap silme hatası: {str(e)}"
    
    def get_user_timezone(self, user_id):
        """Kullanıcının timezone'ını getir"""
        try:
            conn = sqlite3.connect(self.db_path)
            cursor = conn.cursor()
            
            cursor.execute('SELECT timezone FROM users WHERE id = ?', (user_id,))
            result = cursor.fetchone()
            conn.close()
            
            if result and result[0]:
                return result[0]
            else:
                return "Europe/Istanbul"  # Varsayılan timezone
                
        except Exception as e:
            print(f"Timezone getirme hatası: {e}")
            return "Europe/Istanbul"  # Varsayılan timezone
    
    def update_user_timezone(self, user_id, timezone):
        """Kullanıcının timezone'ını güncelle"""
        try:
            conn = sqlite3.connect(self.db_path)
            cursor = conn.cursor()
            
            cursor.execute('UPDATE users SET timezone = ? WHERE id = ?', (timezone, user_id))
            conn.commit()
            conn.close()
            
            return True, "Timezone başarıyla güncellendi"
            
        except Exception as e:
            return False, f"Timezone güncelleme hatası: {str(e)}"

    def generate_random_nfc_users(self, count: int = 50):
        import random, string, sqlite3
        created = []
        for _ in range(int(count)):
            # 32-bit decimal UUID for NFC card
            card_uuid = str(random.randint(1, 2**32 - 1))
            full_name = 'NFC User ' + ''.join(random.choices(string.ascii_uppercase + string.digits, k=5))
            email = f"nfc_{card_uuid}@example.com"
            try:
                # Register basic user in data.db
                self.register_user(email=email, password='P@ssw0rd!', full_name=full_name, company='NFC', phone='')
                # Ensure card_uuid and access_type='nfc'
                conn = sqlite3.connect(self.db_path); conn.row_factory = sqlite3.Row
                cur = conn.cursor()
                cur.execute("UPDATE users SET card_uuid = ?, access_type = CASE WHEN access_type IS NULL OR TRIM(access_type) = '' THEN 'nfc' WHEN instr(access_type, 'nfc')=0 THEN access_type||',nfc' ELSE access_type END WHERE email = ?", (card_uuid, email))
                conn.commit(); conn.close()
            except Exception:
                pass
            created.append({'full_name': full_name, 'card_uuid': card_uuid, 'email': email})
        return created

# Global user manager instance
user_manager = UserManager('users.db') 