import sys
from typing import Optional
from functools import partial
from datetime import datetime, timedelta
from pathlib import Path
import locale
from core.db import CashAccount
try:
    locale.setlocale(locale.LC_TIME, 'tr_TR.UTF-8')
except:
    pass # Sistemde Türkçe dil paketi yoksa hata vermesin
from PyQt6.QtWidgets import (
    QApplication, QMessageBox, QWidget, QVBoxLayout, QHBoxLayout, QFormLayout,
    QPushButton, QLabel, QLineEdit, QTextEdit, QComboBox, QTabWidget, QGroupBox,
    QTableWidget, QTableWidgetItem, QHeaderView, QCalendarWidget, QCheckBox,
    QDialog, QGridLayout, QDateEdit, QStyle, QSizePolicy, QToolButton,
    QFrame, QCompleter, QScrollArea, QFontComboBox, QStatusBar, QListWidget, QDoubleSpinBox
)
from PyQt6.QtCore import Qt, QSize, QLocale, QTimer, QDate, QEvent, QObject
from PyQt6.QtGui import QIcon, QPixmap, QFont, QTextCharFormat, QFontDatabase, QColor
from core.config import SUPPORTED_CURRENCIES, RESOURCES_DIR, format_number, get_available_languages
from core.tenant_manager import TenantManager
from ui.tabs.ai_tab import AITab
from modules.stock import ManualStockDialog, BulkBarcodeDialog
from modules.sales import PaymentDialog
from modules.cash import EditScheduledTransactionDialog
class InterfaceBuilder:
    """
    Handles the creation of UI elements and Tabs for the JewelryStoreApp.
    Separates View logic from Business Logic.
    """
    def __init__(self, main_app):
        self.main_app = main_app
    def get_main_tabs_config(self):
        """Ana sekme yapılandırmasını döndürür."""
        is_boss = getattr(self.main_app, "is_boss_mode", False)
        tabs = []
        if not is_boss:
            tabs.append((1, self.main_app.lang.get("cat_shopping", "Alışveriş")))
        tabs.append((2, self.main_app.lang.get("cat_money", "Para İşlemleri")))
        tabs.append((3, self.main_app.lang.get("cat_stocks", "Stok İşlemleri")))
        if not is_boss:
            tabs.append((4, self.main_app.lang.get("cat_customers", "Müşteri İşlemleri")))
        if not is_boss:
            tabs.append((5, self.main_app.lang.get("cat_services", "Hizmetler")))
        tabs.append((6, self.main_app.lang.get("cat_tools", "Araçlar")))
        license_data = self.main_app.tenant_manager.load_license()
        if int(license_data.get("is_ai_enabled", 0)) == 1 and self.main_app.tenant_manager.get_api_token():
            tabs.append((7, "AI Asistan"))
        return tabs

    def create_ai_tab(self) -> QWidget:
        return AITab(self.main_app)
    def create_dashboard_tab(self) -> QWidget:
        """
        YENİ TASARIM (REVİZE V8 - Hiyerarşik Yerleşim):
        - Ekran Üst ve Alt olarak ikiye ayrıldı.
        - Üst kısım Sol (Bilgi+Kartlar) ve Sağ (Logo) olarak ayrıldı.
        - Kartlar artık tam genişlikte ve daha ferah.
        """
        widget = QWidget()
        main_layout = QVBoxLayout(widget)
        main_layout.setContentsMargins(20, 20, 20, 20)
        main_layout.setSpacing(0)
        self.main_app.dashboard_ui_helper = self
        self.dashboard_widgets = {}
        top_half_widget = QWidget()
        bottom_half_widget = QWidget()
        main_layout.addWidget(top_half_widget, 50)
        main_layout.addWidget(bottom_half_widget, 50)
        top_layout = QHBoxLayout(top_half_widget)
        left_panel = QWidget()
        left_panel_layout = QVBoxLayout(left_panel)
        shop_info_layout = QVBoxLayout()
        shop_name = self.main_app.settings_manager.get_setting("shop_name", "GOLDER KUYUMCU MUHASEBE PROGRAMI")
        theme_name = self.main_app.settings_manager.get_setting("theme_name", "Green Harmony")
        theme_colors = self.main_app.all_themes.get(theme_name, {})
        primary_color = theme_colors.get('primary', '#2c3e50')
        lbl_shop = QLabel(shop_name)
        lbl_shop.setStyleSheet(f"font-size: 32px; font-weight: bold; color: {primary_color};")
        self.main_app.dashboard_date_label = QLabel()
        self.main_app.dashboard_date_label.setStyleSheet("font-size: 16px; color: #7f8c8d;")
        shop_info_layout.addWidget(lbl_shop)
        shop_info_layout.addWidget(self.main_app.dashboard_date_label)
        left_panel_layout.addLayout(shop_info_layout)
        scroll_area = QScrollArea()
        scroll_area.setWidgetResizable(True)
        scroll_area.setFrameShape(QFrame.Shape.NoFrame)
        scroll_area.setStyleSheet("background: transparent;")
        self.cards_area = QWidget()
        self.cards_area.setStyleSheet("background: transparent;")
        self.cards_layout = QGridLayout(self.cards_area)
        self.cards_layout.setSpacing(20)
        scroll_area.setWidget(self.cards_area)
        left_panel_layout.addWidget(scroll_area)
        self.main_app.dashboard_logo_label = QLabel()
        logo_path = RESOURCES_DIR / "golder.png"
        if logo_path.exists():
            pix = QPixmap(str(logo_path)).scaledToWidth(350, Qt.TransformationMode.SmoothTransformation)
            self.main_app.dashboard_logo_label.setPixmap(pix)
            self.main_app.dashboard_logo_label.setAlignment(Qt.AlignmentFlag.AlignRight | Qt.AlignmentFlag.AlignVCenter)
        top_layout.addWidget(left_panel, 65)
        top_layout.addWidget(self.main_app.dashboard_logo_label, 35)
        bottom_layout = QHBoxLayout(bottom_half_widget)
        trans_group = QGroupBox(self.main_app.lang.get("recent_transactions_live", "Recent Transactions (Live)"))
        trans_layout = QVBoxLayout(trans_group)
        self.dash_trans_table = QTableWidget(0, 4)
        self.dash_trans_table.setHorizontalHeaderLabels([
            self.main_app.lang.get("time_col", "Time"),
            self.main_app.lang.get("type_col", "Type"),
            self.main_app.lang.get("amount_col", "Amount"),
            self.main_app.lang.get("description_col", "Description")
        ])
        header = self.dash_trans_table.horizontalHeader()
        header.setSectionResizeMode(0, QHeaderView.ResizeMode.Fixed); self.dash_trans_table.setColumnWidth(0, 60)
        header.setSectionResizeMode(1, QHeaderView.ResizeMode.Fixed); self.dash_trans_table.setColumnWidth(1, 110)
        header.setSectionResizeMode(2, QHeaderView.ResizeMode.Fixed); self.dash_trans_table.setColumnWidth(2, 130)
        header.setSectionResizeMode(3, QHeaderView.ResizeMode.Stretch)
        self.dash_trans_table.verticalHeader().setVisible(False)
        self.dash_trans_table.setEditTriggers(QTableWidget.EditTrigger.NoEditTriggers)
        self.dash_trans_table.setSelectionMode(QTableWidget.SelectionMode.NoSelection)
        self.dash_trans_table.setAlternatingRowColors(True)
        trans_layout.addWidget(self.dash_trans_table)
        rates_group = QGroupBox(self.main_app.lang.get("market_rates", "Market / Exchange Rates"))
        rates_layout = QVBoxLayout(rates_group)
        self.dash_rates_table = QTableWidget(0, 3)
        self.dash_rates_table.setHorizontalHeaderLabels([
            self.main_app.lang.get("unit_col", "Unit"),
            self.main_app.lang.get("buy_rate", "Buy"),
            self.main_app.lang.get("sell_rate", "Sell")
        ])
        self.dash_rates_table.horizontalHeader().setSectionResizeMode(QHeaderView.ResizeMode.Stretch)
        self.dash_rates_table.verticalHeader().setVisible(False)
        self.dash_rates_table.setEditTriggers(QTableWidget.EditTrigger.NoEditTriggers)
        rates_layout.addWidget(self.dash_rates_table)
        bottom_layout.addWidget(trans_group, 65)
        bottom_layout.addWidget(rates_group, 35)
        if hasattr(self.main_app, "_refresh_dashboard_widgets"):
            QTimer.singleShot(0, self.main_app._refresh_dashboard_widgets)
        else:
            self.update_dashboard_data()
        return widget

    def update_dashboard_data(self):
        """
        Legacy sync yol: dashboard verisini toplar ve render eder.
        """
        snapshot = {
            "cards": [],
            "recent_transactions": [],
            "rates": dict(self.main_app.currency_manager.rates_cache or {}),
            "display_currency": self.main_app.display_currency,
        }

        cash_label = self.main_app.lang.get("cash", "Nakit")
        card_label = self.main_app.lang.get("card", "Kart")
        for acc in self.main_app._get_accessible_cash_accounts():
            manager = self.main_app.cash_managers.get(acc.id)
            snapshot["cards"].append(
                {
                    "id": f"cash_{acc.id}",
                    "title": acc.name,
                    "subtitle": cash_label,
                    "balances": dict((manager.calculate_balance() if manager else {}) or {}),
                }
            )
        for acc in self.main_app._get_accessible_card_accounts():
            manager = self.main_app.card_managers.get(acc.id)
            snapshot["cards"].append(
                {
                    "id": f"card_{acc.id}",
                    "title": acc.name,
                    "subtitle": card_label,
                    "balances": dict((manager.calculate_balance() if manager else {}) or {}),
                }
            )

        all_trans = []
        for mgr in list(self.main_app.cash_managers.values()) + list(self.main_app.card_managers.values()):
            for trans in mgr.get_all():
                all_trans.append(
                    {
                        "created_at": str(getattr(trans, "created_at", "") or ""),
                        "transaction_type": str(getattr(trans, "transaction_type", "") or ""),
                        "original_amount": float(getattr(trans, "original_amount", 0.0) or 0.0),
                        "currency": str(getattr(trans, "currency", "") or ""),
                        "description": str(getattr(trans, "description", "") or ""),
                    }
                )
        all_trans.sort(key=lambda x: x.get("created_at", ""), reverse=True)
        snapshot["recent_transactions"] = all_trans[:15]

        self.render_dashboard_snapshot(snapshot)

    def render_dashboard_snapshot(self, snapshot: dict) -> None:
        """UI-only dashboard render. Ağ/DB işlemi yapmaz."""
        if hasattr(self, "cards_layout") and self.cards_layout is not None:
            while self.cards_layout.count():
                child = self.cards_layout.takeAt(0)
                if child.widget():
                    child.widget().deleteLater()
        self.dashboard_widgets.clear()

        cards = snapshot.get("cards", []) if isinstance(snapshot, dict) else []
        max_cols = 2
        row, col = 0, 0
        for item in cards:
            balances = item.get("balances", {}) if isinstance(item, dict) else {}
            balance_parts = []
            for currency, value in (balances or {}).items():
                try:
                    amount = float(value or 0.0)
                except (TypeError, ValueError):
                    continue
                if abs(amount) > 0.01:
                    balance_parts.append(f"{format_number(amount)} {currency}")
            balance_str = " | ".join(balance_parts) if balance_parts else "0.00"
            self._update_or_create_card(
                str(item.get("id", "")),
                str(item.get("title", "")),
                str(item.get("subtitle", "")),
                balance_str,
                "",
                row,
                col,
            )
            col += 1
            if col >= max_cols:
                col = 0
                row += 1

        if hasattr(self, "dash_trans_table"):
            recent = snapshot.get("recent_transactions", []) if isinstance(snapshot, dict) else []
            self.dash_trans_table.setRowCount(len(recent))
            for i, trans in enumerate(recent):
                created_at = str(trans.get("created_at", "") or "")
                try:
                    time_str = datetime.fromisoformat(created_at.replace("Z", "")).strftime("%H:%M")
                except Exception:
                    time_str = "-"

                raw_type = str(trans.get("transaction_type", "") or "")
                type_tr = self.main_app.lang.get("entry_income", "Entry") if raw_type == "Income" else self.main_app.lang.get("exit_expense", "Exit")
                item_time = QTableWidgetItem(time_str)
                item_type = QTableWidgetItem(type_tr)
                if raw_type == "Income":
                    item_type.setForeground(QColor("green"))
                    item_type.setFont(QFont("Segoe UI", 9, QFont.Weight.Bold))
                else:
                    item_type.setForeground(QColor("#D32F2F"))
                    item_type.setFont(QFont("Segoe UI", 9, QFont.Weight.Bold))

                amount = float(trans.get("original_amount", 0.0) or 0.0)
                currency = str(trans.get("currency", "") or "")
                desc = str(trans.get("description", "") or "")
                item_amt = QTableWidgetItem(f"{format_number(amount)} {currency}")
                item_amt.setTextAlignment(Qt.AlignmentFlag.AlignRight | Qt.AlignmentFlag.AlignVCenter)
                item_desc = QTableWidgetItem(desc)
                self.dash_trans_table.setItem(i, 0, item_time)
                self.dash_trans_table.setItem(i, 1, item_type)
                self.dash_trans_table.setItem(i, 2, item_amt)
                self.dash_trans_table.setItem(i, 3, item_desc)

        rates = snapshot.get("rates", {}) if isinstance(snapshot, dict) else {}
        if not hasattr(self, "dash_rates_table"):
            return
        self.dash_rates_table.setRowCount(0)
        if not rates:
            return

        target_currency = str(snapshot.get("display_currency") or self.main_app.display_currency)
        display_keys = [
            "USD", "EUR", "GBP",
            "gram-altin", "ceyrek-altin", "yarim-altin",
            "tam-altin", "cumhuriyet-altini", "22-ayar-bilezik",
        ]
        target_rate = 1.0
        if target_currency != "TRY":
            target_data = rates.get(target_currency)
            if target_data:
                try:
                    target_buy, target_sell = self.main_app.currency_manager._extract_buy_sell(target_data)
                    target_rate = target_buy or target_sell or 1.0
                except Exception:
                    target_rate = 1.0
        if target_rate == 0:
            target_rate = 1.0

        self.dash_rates_table.setHorizontalHeaderLabels(
            [
                f"{self.main_app.lang.get('unit_col', 'Unit')} ({target_currency})",
                self.main_app.lang.get("buy_rate", "Buy"),
                self.main_app.lang.get("sell_rate", "Sell"),
            ]
        )
        row_idx = 0
        for key in display_keys:
            if key == target_currency:
                continue
            if key in rates and isinstance(rates[key], dict):
                row_data = rates[key]
                name = key.replace("-", " ").title().replace("Usd", "USD").replace("Eur", "EUR").replace("Gbp", "GBP")
                try:
                    raw_buy, raw_sell = self.main_app.currency_manager._extract_buy_sell(row_data)
                    self.dash_rates_table.insertRow(row_idx)
                    self.dash_rates_table.setItem(row_idx, 0, QTableWidgetItem(name))
                    self.dash_rates_table.setItem(row_idx, 1, QTableWidgetItem(format_number(raw_buy / target_rate)))
                    self.dash_rates_table.setItem(row_idx, 2, QTableWidgetItem(format_number(raw_sell / target_rate)))
                    row_idx += 1
                except (ValueError, TypeError):
                    continue

    def _update_or_create_card(self, card_id, title, subtitle, value, default_color_hex, row, col):
        """
        Her zaman yeni bir dashboard kartı oluşturur ve grid'e ekler.
        """
        theme_name = self.main_app.settings_manager.get_setting("theme_name", "Green Harmony")
        theme_data = self.main_app.all_themes.get(theme_name, {})
        base_color_hex = theme_data.get('primary' if "cash" in card_id else 'secondary', '#285430')
        c1 = QColor(base_color_hex)
        c2 = c1.darker(140)
        style = f"""
            QFrame {{
                background: qlineargradient(x1:0, y1:0, x2:1, y2:1, stop:0 {c1.name()}, stop:1 {c2.name()});
                border-radius: 12px;
                color: white;
            }}
            QLabel {{ color: white; background: transparent; }}
        """
        frame = QFrame()
        frame.setMinimumHeight(110)
        frame.setSizePolicy(QSizePolicy.Policy.Expanding, QSizePolicy.Policy.Fixed)
        frame.setStyleSheet(style)
        layout = QVBoxLayout(frame)
        layout.setContentsMargins(15, 15, 15, 15)
        lbl_title = QLabel(title); lbl_title.setStyleSheet("font-size: 15px; font-weight: bold;")
        lbl_sub = QLabel(subtitle); lbl_sub.setStyleSheet("font-size: 11px; opacity: 0.8;")
        lbl_val = QLabel(value); lbl_val.setObjectName("val"); lbl_val.setStyleSheet("font-size: 16px; font-weight: bold;");
        lbl_val.setAlignment(Qt.AlignmentFlag.AlignRight | Qt.AlignmentFlag.AlignBottom)
        lbl_val.setWordWrap(True)
        layout.addWidget(lbl_title)
        layout.addWidget(lbl_sub)
        layout.addStretch()
        layout.addWidget(lbl_val)
        self.cards_layout.addWidget(frame, row, col)
        self.dashboard_widgets[card_id] = frame
    def create_zakat_tab(self) -> QWidget:
        """
        Zekat Modülü Ana Konteyner.
        Yetkiye göre 'Mağaza Zekatı' ve 'Müşteri Zekatı' sekmelerini içerir.
        """
        tabs = QTabWidget()
        if self.main_app.has_permission("perm_zakat"):
            tabs.addTab(self._create_store_zakat_ui(), self.main_app.lang.get("store_calculation", "Store Calculation"))
        if self.main_app.has_permission("perm_zakat_guest"):
            tabs.addTab(self._create_guest_zakat_ui(), self.main_app.lang.get("quick_calc_guest", "Quick Calculate for Customer"))
        return tabs
    def _create_store_zakat_ui(self) -> QWidget:
        """Mağaza Zekatı Arayüzü - GÜNCELLENDİ"""
        widget = QWidget()
        layout = QVBoxLayout(widget)
        
        info_frame = QFrame()
        info_frame.setStyleSheet("background-color: #E8F5E9; border: 1px solid #4CAF50; border-radius: 5px;")
        info_layout = QHBoxLayout(info_frame)
        curr = self.main_app.display_currency
        
        info_lbl = QLabel(f"Bu ekran, <b>Has (Saf) Ağırlık</b> üzerinden hesaplama yapar. Ziynetler gramaja, diğer ürünler milyeme göre dönüştürülür.\n"
                          f"Para Birimi: <b>{curr}</b> | Nisap: 85gr Has Altın")
        info_lbl.setStyleSheet("color: #2E7D32; font-weight: bold;")
        info_layout.addWidget(info_lbl)
        layout.addWidget(info_frame)
        
        settings_group = QGroupBox("Mağaza ZekÃ¢t Ayarları")
        settings_layout = QHBoxLayout(settings_group)
        settings_layout.addWidget(QLabel(self.main_app.lang.get("nisab_start_date_bold", "<b>Nisab Start Date:</b>")))
        
        self.main_app.zakat_start_date = QDateEdit()
        self.main_app.zakat_start_date.setCalendarPopup(True)
        self.main_app.zakat_start_date.setDisplayFormat("dd.MM.yyyy")
        saved_date = self.main_app.settings_manager.get_setting("zakat_nisap_date")
        if saved_date: self.main_app.zakat_start_date.setDate(QDate.fromString(saved_date, "dd.MM.yyyy"))
        else: self.main_app.zakat_start_date.setDate(QDate.currentDate())
        
        settings_layout.addWidget(self.main_app.zakat_start_date)
        btn_assume = QPushButton(self.main_app.lang.get("1_year_nisab", "1 Year in Nisab")); btn_assume.clicked.connect(self._set_zakat_date_last_year)
        settings_layout.addWidget(btn_assume)
        
        btn_calc = QPushButton(self.main_app.lang.get("calculate", "Calculate")); btn_calc.setObjectName("primaryButton"); btn_calc.clicked.connect(self.main_app._calculate_zakat) # <-- Doğrudan bağlandı
        settings_layout.addWidget(btn_calc)
        layout.addWidget(settings_group)
        
        # Kartlar
        cards_layout = QHBoxLayout()
        self.main_app.lbl_zakat_assets = self.create_summary_card()
        self.main_app.lbl_zakat_debts = self.create_summary_card()
        self.main_app.lbl_zakat_net = self.create_summary_card()
        self.main_app.lbl_zakat_result = self.create_summary_card()
        
        for c in [self.main_app.lbl_zakat_assets, self.main_app.lbl_zakat_debts, self.main_app.lbl_zakat_net, self.main_app.lbl_zakat_result]:
            cards_layout.addWidget(c)
        layout.addLayout(cards_layout)
        
        # --- TABLO YAPISI DEÄİŞTİ (Detaylı Görünüm) ---
        self.main_app.zakat_table = QTableWidget(0, 6)
        self.main_app.zakat_table.setHorizontalHeaderLabels([
            self.main_app.lang.get("group", "Group"), self.main_app.lang.get("asset_name", "Asset Name"), self.main_app.lang.get("karat_detail", "Karat/Detail"), self.main_app.lang.get("gross_amount", "Gross Amount"), self.main_app.lang.get("pure_gram", "Pure Gram"), f"{self.main_app.lang.get('value', 'Value')} ({curr})"
        ])
        header = self.main_app.zakat_table.horizontalHeader()
        header.setSectionResizeMode(QHeaderView.ResizeMode.Stretch)
        header.setSectionResizeMode(0, QHeaderView.ResizeMode.ResizeToContents) # Grup dar olsun
        
        layout.addWidget(self.main_app.zakat_table)
        return widget
    def _create_guest_zakat_ui(self) -> QWidget:
        """Müşteri için manuel veri giriş ekranı."""
        widget = QWidget()
        layout = QVBoxLayout(widget)
        form_group = QGroupBox(self.main_app.lang.get("guest_asset_decl", "Customer Asset Declaration"))
        form = QFormLayout(form_group)
        self.main_app.guest_asset_rows = []
        assets_wrapper = QWidget()
        assets_wrapper_layout = QVBoxLayout(assets_wrapper)
        assets_wrapper_layout.setContentsMargins(0, 0, 0, 0)
        assets_wrapper_layout.setSpacing(6)

        header_layout = QHBoxLayout()
        header_layout.setContentsMargins(0, 0, 0, 0)
        header_layout.setSpacing(8)
        header_color = self.main_app.all_themes.get(
            self.main_app.settings_manager.get_setting("theme_name", "Green Harmony"),
            {},
        ).get("text_dark", "#111111")
        lbl_type = QLabel(self.main_app.lang.get("type", "Type"))
        lbl_detail = QLabel(self.main_app.lang.get("karat_currency", "Karat / Currency"))
        lbl_amount = QLabel(self.main_app.lang.get("quantity_amount", "Quantity/Amount"))
        lbl_action = QLabel("")
        for lbl in (lbl_type, lbl_detail, lbl_amount):
            lbl.setStyleSheet(f"font-weight: 600; color: {header_color};")
        header_layout.addWidget(lbl_type, 2)
        header_layout.addWidget(lbl_detail, 2)
        header_layout.addWidget(lbl_amount, 2)
        header_layout.addWidget(lbl_action, 1)
        assets_wrapper_layout.addLayout(header_layout)

        self.main_app.guest_asset_rows_layout = QVBoxLayout()
        self.main_app.guest_asset_rows_layout.setContentsMargins(0, 0, 0, 0)
        self.main_app.guest_asset_rows_layout.setSpacing(6)
        assets_wrapper_layout.addLayout(self.main_app.guest_asset_rows_layout)

        add_item_btn = QPushButton(self.main_app.lang.get("add_item", "Add Item"))
        add_item_btn.clicked.connect(self.main_app._add_guest_asset_row)
        assets_wrapper_layout.addWidget(add_item_btn, alignment=Qt.AlignmentFlag.AlignRight)
        form.addRow(self.main_app.lang.get("asset_items_colon", "Asset Items:"), assets_wrapper)

        debt_layout = QHBoxLayout()
        self.main_app.guest_debt_spin = QDoubleSpinBox()
        self.main_app.guest_debt_spin.setRange(0, 999999999); self.main_app.guest_debt_spin.setButtonSymbols(QDoubleSpinBox.ButtonSymbols.NoButtons)
        self.main_app.guest_debt_currency = QComboBox(); self.main_app.guest_debt_currency.addItems(SUPPORTED_CURRENCIES)
        self.main_app.guest_debt_currency.setCurrentText(self.main_app.display_currency)
        debt_layout.addWidget(self.main_app.guest_debt_spin); debt_layout.addWidget(self.main_app.guest_debt_currency)
        form.addRow(self.main_app.lang.get("deductible_debts_colon", "Deductible Debts:"), debt_layout)
        btn_calc = QPushButton(self.main_app.lang.get("calculate_upper", "CALCULATE")); btn_calc.setObjectName("primaryButton"); btn_calc.setMinimumHeight(40)
        btn_calc.clicked.connect(self.main_app._calculate_guest_zakat)
        form.addRow(btn_calc)
        layout.addWidget(form_group)
        self.main_app._add_guest_asset_row()
        res_group = QGroupBox(self.main_app.lang.get("calculation_result", "Calculation Result"))
        res_layout = QVBoxLayout(res_group)
        self.main_app.guest_result_label = QLabel(self.main_app.lang.get("enter_values_press_calc", "Please enter values and press 'Calculate'."))
        self.main_app.guest_result_label.setAlignment(Qt.AlignmentFlag.AlignCenter)
        self.main_app.guest_result_label.setStyleSheet("font-size: 14px; padding: 10px;")
        res_layout.addWidget(self.main_app.guest_result_label)
        curr = self.main_app.display_currency
        disclaimer = QLabel(f"âš ï¸ {self.main_app.lang.get('zakat_disclaimer', 'This calculation is based on the customer declaration and instant exchange rate in <b>{curr}</b>. It is not recorded.').format(curr=curr)}")
        disclaimer.setStyleSheet("color: gray; font-style: italic;")
        res_layout.addWidget(disclaimer, alignment=Qt.AlignmentFlag.AlignRight)
        layout.addWidget(res_group)
        layout.addStretch()
        return widget
    def _set_zakat_date_last_year(self):
        """Kullanıcı 1 yıldır zenginim derse tarihi 355 gün geriye çeker."""
        target_date = QDate.currentDate().addDays(-355)
        self.main_app.zakat_start_date.setDate(target_date)
    def refresh_dashboard_theme(self, dashboard_widget: QWidget) -> None:
        """Dashboard'daki butonların tema renklerini günceller."""
        if not hasattr(dashboard_widget, 'left_panel'):
            return
        theme_name = self.main_app.settings_manager.get_setting("theme_name", "Green Harmony")
        all_themes = getattr(self.main_app, 'all_themes', {})
        if not all_themes:
            from core.config import APP_THEMES
            all_themes = {**APP_THEMES}
        theme_data = all_themes.get(theme_name, list(all_themes.values())[0] if all_themes else {})
        primary_color = theme_data.get('primary', '#285430')
        secondary_color = theme_data.get('secondary', '#5F8D4E')
        background_color = theme_data.get('background', '#F1F8E9')
        text_dark = theme_data.get('text_dark', '#000000')
        text_light = theme_data.get('text_light', '#FFFFFF')
        try:
            hover_color_qcolor = QColor(secondary_color).lighter(120)
            hover_color = hover_color_qcolor.name()
            hover_text_color = text_light if hover_color_qcolor.lightness() < 128 else text_dark
        except:
            hover_color = secondary_color
            hover_text_color = text_light
        btn_style = f"""
            QPushButton {{
                background-color: {secondary_color};
                color: {text_light};
                font-size: 16px;
                font-weight: bold;
                border: 2px solid {secondary_color};
                border-radius: 4px;
                text-align: left;
                padding-left: 20px;
            }}
            QPushButton:hover {{
                background-color: {hover_color};
                color: {hover_text_color};
                border: 2px solid {primary_color};
            }}
            QPushButton:pressed {{
                background-color: {primary_color};
        color: {text_light};
                border: 2px solid {primary_color};
            }}
        """
        left_panel = dashboard_widget.left_panel
        layout = left_panel.layout()
        if layout:
            for i in range(layout.count()):
                item = layout.itemAt(i)
                if item and item.widget():
                    widget = item.widget()
                    if isinstance(widget, QPushButton):
                        widget.setStyleSheet(btn_style)
    def create_sidebar_widget(self, buttons_config) -> QScrollArea:
        """
        Kalıcı sidebar menüsü oluşturur.
        buttons_config: [(index, label), ...] listesi.
        """
        sidebar = QScrollArea()
        sidebar.setWidgetResizable(True)
        sidebar.setFrameShape(QFrame.Shape.NoFrame)
        sidebar.setHorizontalScrollBarPolicy(Qt.ScrollBarPolicy.ScrollBarAlwaysOff)
        theme_name = self.main_app.settings_manager.get_setting("theme_name", "Green Harmony")
        try:
           all_themes = getattr(self.main_app, 'all_themes', {})
           if not all_themes:
               from core.config import APP_THEMES
               all_themes = APP_THEMES
           theme_data = all_themes.get(theme_name, list(all_themes.values())[0] if all_themes else {})
        except:
            theme_data = {}
        primary = theme_data.get('primary', '#285430')
        secondary = theme_data.get('secondary', '#5F8D4E')
        bg_color = theme_data.get('background', '#F1F8E9')
        text_light = theme_data.get('text_light', '#FFFFFF')
        sidebar.setStyleSheet(f"background-color: {primary}; border-right: 1px solid {secondary};")
        content = QWidget()
        content.setStyleSheet(f"background-color: {primary};")
        layout = QVBoxLayout(content)
        layout.setContentsMargins(5, 10, 5, 10)
        layout.setSpacing(8)
        sidebar_btn_style = f"""
            QPushButton {{
                background-color: {secondary};
                color: {text_light};
                font-size: 14px;
                font-weight: bold;
                border: none;
                border-radius: 4px;
                text-align: left;
                padding: 10px;
            }}
            QPushButton:hover {{
                background-color: {text_light};
                color: {primary};
            }}
            QPushButton:checked {{
                background-color: {bg_color};
                color: {primary};
                border-left: 4px solid {text_light};
            }}
        """
        btn_dash = QPushButton(self.main_app.lang.get("dashboard_tab", "Dashboard"))
        btn_dash.setCursor(Qt.CursorShape.PointingHandCursor)
        btn_dash.setStyleSheet(sidebar_btn_style)
        btn_dash.setCheckable(True)
        btn_dash.setMinimumHeight(50)
        btn_dash.setAttribute(Qt.WidgetAttribute.WA_Hover) # <--- EKLENDİ (Hover tetikleyici)
        btn_dash.setProperty("tab_index", 0)
        layout.addWidget(btn_dash)
        for idx, label in buttons_config:
            btn = QPushButton(f"{idx}. {label}")
            btn.setCursor(Qt.CursorShape.PointingHandCursor)
            btn.setStyleSheet(sidebar_btn_style)
            btn.setCheckable(True)
            btn.setMinimumHeight(50)
            btn.setAttribute(Qt.WidgetAttribute.WA_Hover) # <--- EKLENDİ (Hover tetikleyici)
            btn.setProperty("tab_index", idx)
            layout.addWidget(btn)
        layout.addStretch()
        if hasattr(self.main_app, 'current_user') and self.main_app.current_user.get("role") == "admin":
             btn_settings = QPushButton(self.main_app.lang.get("settings_tab", "Ayarlar"))
             btn_settings.setCursor(Qt.CursorShape.PointingHandCursor)
             btn_settings.setStyleSheet(sidebar_btn_style)
             btn_settings.setCheckable(True)
             btn_settings.setMinimumHeight(50)
             settings_index = -1
             if hasattr(self.main_app, "tabs") and hasattr(self.main_app, "settings_category_widget"):
                 try:
                     settings_index = self.main_app.tabs.indexOf(self.main_app.settings_category_widget)
                 except Exception:
                     settings_index = -1
             if settings_index is None or settings_index < 0:
                 try:
                     settings_index = max([idx for idx, _ in buttons_config] + [0]) + 1
                 except Exception:
                     settings_index = 7
             btn_settings.setProperty("tab_index", settings_index)
             layout.addWidget(btn_settings)
        sidebar.setWidget(content)
        return sidebar
    def build_shopping_category(self) -> QWidget:
        """1. ALIŞVERİŞ Kategorisi - Hızlı Altın Sekmesi KALDIRILDI"""
        tabs = QTabWidget()
        if self.main_app.has_permission("perm_product_purchase"):
            tabs.addTab(self.create_pos_style_tab("Product", "Purchase"), self.main_app.lang.get("gold_purchase_pos", "Gold Purchase (POS)"))
        if self.main_app.has_permission("perm_product_sale"):
            tabs.addTab(self.create_pos_style_tab("Product", "Sale"), self.main_app.lang.get("gold_sale_pos", "Gold Sale (POS)"))
        if self.main_app.has_permission("perm_scrap_purchase"):
            tabs.addTab(self.create_pos_style_tab("Scrap", "Purchase"), self.main_app.lang.get("scrap_purchase", "Scrap Purchase"))
        if self.main_app.has_permission("perm_scrap_sale"):
            tabs.addTab(self.create_pos_style_tab("Scrap", "Sale"), self.main_app.lang.get("scrap_sale", "Scrap Sale"))
        if self.main_app.has_permission("perm_ziynet_purchase"):
            tabs.addTab(self.create_pos_style_tab("Ziynet", "Purchase"), self.main_app.lang.get("ziynet_purchase", "Ziynet Purchase"))
        if self.main_app.has_permission("perm_ziynet_sale"):
            tabs.addTab(self.create_pos_style_tab("Ziynet", "Sale"), self.main_app.lang.get("ziynet_sale", "Ziynet Sale"))
        self.main_app.shopping_tab_widget = tabs
        self.main_app.trading_tab_widget = tabs

        return tabs

    def _maybe_prompt_empty_pos_setup(self, widget: Optional[QWidget]) -> None:
        if widget is None:
            return
        try:
            if bool(widget.property("_empty_pos_setup_prompt_shown")):
                return
        except Exception:
            pass

        stock_type = widget.property("pos_stock_type")
        transaction_type = widget.property("pos_transaction_type")
        if not stock_type or not transaction_type:
            return

        def _combo_has_real_items(combo: Optional[QComboBox]) -> bool:
            if combo is None:
                return False
            for i in range(combo.count()):
                if (combo.itemText(i) or "").strip():
                    return True
            return False

        widgets = (
            self.main_app.stock_widgets.get(str(stock_type), {}).get(str(transaction_type), {})
            if hasattr(self.main_app, "stock_widgets")
            else {}
        )
        product_combo = widgets.get("product_combo")
        depot_combo = widgets.get("pos_depot_combo")

        if isinstance(product_combo, QComboBox) and not _combo_has_real_items(product_combo):
            widget.setProperty("_empty_pos_setup_prompt_shown", True)
            if str(stock_type) == "Product":
                def_page = self.main_app.lang.get("product_def_tab", "Product Definitions")
            elif str(stock_type) == "Scrap":
                def_page = self.main_app.lang.get("scrap_def_tab", "Scrap Definitions")
            else:
                def_page = self.main_app.lang.get("ziynet_def_tab", "Ziynet Definitions")
            self.main_app._show_empty_combo_prompt(def_page, lambda: self.main_app._open_stock_definitions(stock_type))
            return

        if isinstance(depot_combo, QComboBox) and depot_combo.count() == 0:
            widget.setProperty("_empty_pos_setup_prompt_shown", True)
            self.main_app._show_empty_combo_prompt(
                self.main_app.lang.get("manage_depots", "Manage Depots"),
                getattr(self.main_app, "_open_depots_tab", None),
            )
    def build_finance_category(self) -> QWidget:
        """2. PARA İŞLEMLERİ Kategorisi - Yetki Kontrollü"""
        tabs = QTabWidget()
        is_boss = getattr(self.main_app, "is_boss_mode", False)
        if not is_boss and self.main_app.has_permission("perm_add_income"):
            tabs.addTab(self.create_income_subtab(), self.main_app.lang.get("tab_add_income", "Add Income"))
        if not is_boss and self.main_app.has_permission("perm_add_expense"):
            tabs.addTab(self.create_expense_subtab(), self.main_app.lang.get("tab_add_expense", "Add Expense"))
        if not is_boss and self.main_app.has_permission("perm_transfer"):
            tabs.addTab(self.create_account_transfer_subtab(), self.main_app.lang.get("tab_account_transfer", "Inter-Account Transfer"))
        if not is_boss and self.main_app.has_permission("perm_scheduled"):
            tabs.addTab(self.create_scheduled_transactions_subtab(), self.main_app.lang.get("tab_scheduled_transactions", "Scheduled Transactions"))
        if self.main_app.has_permission("perm_cash_view"):
            tabs.addTab(self._create_cash_content(), self.main_app.lang.get("tab_cash_accounts", "Cash Accounts"))
        if self.main_app.has_permission("perm_card_view"):
            tabs.addTab(self._create_cards_content(), self.main_app.lang.get("tab_card_accounts", "Card Accounts"))
        if not is_boss and self.main_app.has_permission("perm_exchange"):
            tabs.addTab(self.create_currency_exchange_tab(), self.main_app.lang.get("tab_currency_exchange", "Currency Exchange"))
        self.main_app.finance_tab_widget = tabs
        self.main_app.cash_tab_widget = tabs # Backward compatibility reference if needed
        return tabs
    def create_income_subtab(self) -> QWidget:
        """Gelir Ekle sekmesi içeriği"""
        widget = QWidget()
        layout = QVBoxLayout(widget)
        group = QGroupBox(self.main_app.lang["add_income"])
        form = QFormLayout(group)
        self.main_app.daily_income_amount = QLineEdit()
        self.main_app.daily_income_amount.setValidator(self.main_app._create_float_validator())
        self.main_app.daily_income_currency = QComboBox()
        self.main_app.daily_income_currency.addItems(SUPPORTED_CURRENCIES)
        self.main_app.daily_income_currency.setCurrentText(self.main_app.display_currency)
        amt_lo = QHBoxLayout()
        amt_lo.addWidget(self.main_app.daily_income_amount)
        amt_lo.addWidget(self.main_app.daily_income_currency)
        self.main_app.daily_income_desc = QLineEdit()
        self.main_app.daily_income_dest_account_combo = QComboBox()
        form.addRow(f"{self.main_app.lang['amount']}:", amt_lo)
        form.addRow(f"{self.main_app.lang['description']}:", self.main_app.daily_income_desc)
        form.addRow(f"{self.main_app.lang['destination_account']}:", self.main_app.daily_income_dest_account_combo)
        btn = QPushButton(self.main_app._get_icon("SP_DialogSaveButton"), self.main_app.lang["save"])
        btn.setObjectName("primaryButton")
        btn.setAutoDefault(True)
        btn.clicked.connect(lambda: self.main_app.finance_manager._add_daily_transaction("Income"))
        form.addRow(btn)
        layout.addWidget(group)
        layout.addStretch()
        self.main_app.setTabOrder(self.main_app.daily_income_amount, self.main_app.daily_income_currency)
        self.main_app.setTabOrder(self.main_app.daily_income_currency, self.main_app.daily_income_desc)
        self.main_app.setTabOrder(self.main_app.daily_income_desc, self.main_app.daily_income_dest_account_combo)
        self.main_app.setTabOrder(self.main_app.daily_income_dest_account_combo, btn)
        return widget
    def create_expense_subtab(self) -> QWidget:
        """Gider Ekle sekmesi içeriği"""
        widget = QWidget()
        layout = QVBoxLayout(widget)
        group = QGroupBox(self.main_app.lang["add_expense"])
        form = QFormLayout(group)
        self.main_app.daily_expense_amount = QLineEdit()
        self.main_app.daily_expense_amount.setValidator(self.main_app._create_float_validator())
        self.main_app.daily_expense_currency = QComboBox()
        self.main_app.daily_expense_currency.addItems(SUPPORTED_CURRENCIES)
        self.main_app.daily_expense_currency.setCurrentText(self.main_app.display_currency)
        amt_lo = QHBoxLayout()
        amt_lo.addWidget(self.main_app.daily_expense_amount)
        amt_lo.addWidget(self.main_app.daily_expense_currency)
        self.main_app.daily_expense_desc = QLineEdit()
        self.main_app.daily_expense_source_account_combo = QComboBox()
        form.addRow(f"{self.main_app.lang['amount']}:", amt_lo)
        form.addRow(f"{self.main_app.lang['description']}:", self.main_app.daily_expense_desc)
        form.addRow(f"{self.main_app.lang['source_account']}:", self.main_app.daily_expense_source_account_combo)
        btn = QPushButton(self.main_app._get_icon("SP_DialogSaveButton"), self.main_app.lang["save"])
        btn.setObjectName("primaryButton")
        btn.setAutoDefault(True)
        btn.clicked.connect(lambda: self.main_app.finance_manager._add_daily_transaction("Expense"))
        form.addRow(btn)
        layout.addWidget(group)
        layout.addStretch()
        self.main_app.setTabOrder(self.main_app.daily_expense_amount, self.main_app.daily_expense_currency)
        self.main_app.setTabOrder(self.main_app.daily_expense_currency, self.main_app.daily_expense_desc)
        self.main_app.setTabOrder(self.main_app.daily_expense_desc, self.main_app.daily_expense_source_account_combo)
        self.main_app.setTabOrder(self.main_app.daily_expense_source_account_combo, btn)
        return widget
    def create_accounts_tab(self) -> QWidget:
        widget = QWidget()
        main_layout = QVBoxLayout(widget)
        main_layout.setContentsMargins(10, 10, 10, 10)
        main_layout.setSpacing(10)
        search_group = QGroupBox(self.main_app.lang.get("customer_transactions", "Müşteri İşlemleri"))
        search_layout = QHBoxLayout(search_group)
        lbl_search = QLabel(self.main_app.lang.get("select_person", "Kişi Seç:"))
        lbl_search.setStyleSheet("font-weight: bold;")
        search_layout.addWidget(lbl_search)
        self.main_app.acc_search_combo = QComboBox()
        self.main_app.acc_search_combo.setEditable(True)
        self.main_app.acc_search_combo.setMinimumWidth(300)
        person_names = self.main_app.person_manager.get_person_names()
        self.main_app.acc_search_combo.addItems(person_names)
        self.main_app.acc_search_combo.setCurrentIndex(-1)
        self.main_app.acc_search_combo.setStyleSheet("""
            QComboBox::drop-down {
                border: 0px;
                width: 0px;
            }
            QComboBox::down-arrow {
                image: none;
                border: none;
            }
            QComboBox {
                padding-right: 0px;
            }
        """)
        completer = QCompleter(person_names)
        completer.setCaseSensitivity(Qt.CaseSensitivity.CaseInsensitive)
        completer.setFilterMode(Qt.MatchFlag.MatchContains)
        self.main_app.acc_search_combo.setCompleter(completer)
        self.main_app.acc_search_combo.currentIndexChanged.connect(self.main_app.crm_manager._update_excel_account_view)
        search_layout.addWidget(self.main_app.acc_search_combo)
        btn_prev = QPushButton()
        btn_prev.setIcon(self.main_app.style().standardIcon(QStyle.StandardPixmap.SP_ArrowLeft))
        btn_prev.setFixedSize(40, 30)
        btn_prev.setToolTip(self.main_app.lang.get("prev_customer", "Previous Customer"))
        btn_prev.clicked.connect(self.main_app.crm_manager._select_previous_person)
        btn_next = QPushButton()
        btn_next.setIcon(self.main_app.style().standardIcon(QStyle.StandardPixmap.SP_ArrowRight))
        btn_next.setFixedSize(40, 30)
        btn_next.setToolTip(self.main_app.lang.get("next_customer", "Next Customer"))
        btn_next.clicked.connect(self.main_app.crm_manager._select_next_person)
        search_layout.addWidget(btn_prev)
        search_layout.addWidget(btn_next)
        btn_pdf = QPushButton(self.main_app.lang.get("export_pdf", "PDF Aktar"))
        btn_pdf.setIcon(self.main_app._get_icon("SP_FilePrint"))
        btn_pdf.clicked.connect(self.main_app.crm_manager._export_account_pdf)
        btn_excel = QPushButton(self.main_app.lang.get("export_excel", "Excel Aktar"))
        btn_excel.setIcon(self.main_app._get_icon("SP_DialogSaveButton"))
        btn_excel.clicked.connect(self.main_app.crm_manager._export_account_excel)
        search_layout.addWidget(btn_pdf)
        search_layout.addWidget(btn_excel)
        search_layout.addStretch()
        main_layout.addWidget(search_group)
        checkbox_layout = QHBoxLayout()
        checkbox_layout.addStretch()
        self.main_app.affect_cash_checkbox = QCheckBox(self.main_app.lang.get("affect_cash", "Kasayı Etkilesin"))
        self.main_app.affect_cash_checkbox.setToolTip(self.main_app.lang.get("affect_cash_desc", "İşaretliyse, işlemler kasayı da etkiler"))
        affect_cash_default = self.main_app.settings_manager.get_setting("affect_cash_in_accounts", True)
        self.main_app.affect_cash_checkbox.setChecked(affect_cash_default)
        self.main_app.affect_cash_checkbox.stateChanged.connect(
            lambda state: self.main_app.settings_manager.set_setting("affect_cash_in_accounts", state == Qt.CheckState.Checked.value)
        )
        checkbox_layout.addWidget(self.main_app.affect_cash_checkbox)
        main_layout.addLayout(checkbox_layout)
        btn_layout = QHBoxLayout()
        buttons = [
            (self.main_app.lang.get("cash", "NAKİT"), self.main_app.crm_manager._open_cash_transactions_dialog, "SP_ArrowDown", "Ctrl+Shift+N", self.main_app.lang.get("quick_cash", "Quick Cash")),
            (self.main_app.lang.get("product", "Altın"), self.main_app.crm_manager._open_product_transactions_dialog, "SP_FileDialogNewFolder", "Ctrl+Shift+A", self.main_app.lang.get("quick_gold", "Quick Gold")),
            (self.main_app.lang.get("ziynet", "Ziynet"), self.main_app.crm_manager._open_ziynet_transactions_dialog, "SP_FileDialogBack", "Ctrl+Shift+Z", self.main_app.lang.get("quick_ziynet", "Quick Ziynet")),
            (self.main_app.lang.get("scrap", "Hurda"), self.main_app.crm_manager._open_scrap_transactions_dialog, "SP_FileDialogBack", "Ctrl+Shift+H", self.main_app.lang.get("quick_scrap", "Quick Scrap")),
            (self.main_app.lang.get("exchange_transaction", "ÇEVİRİ"), self.main_app.crm_manager._excel_action_exchange, "SP_BrowserReload", "Ctrl+Shift+C", self.main_app.lang.get("quick_exchange", "Quick Exchange")),
            (self.main_app.lang.get("transfer_transaction", "VİRMAN"), self.main_app.crm_manager._excel_action_virman, "SP_DirLinkIcon", "Ctrl+Shift+V", self.main_app.lang.get("quick_transfer", "Quick Transfer"))
        ]
        for text, func, icon_name, shortcut_key, shortcut_desc in buttons:
            btn = QPushButton(text)
            btn.setIcon(self.main_app._get_icon(icon_name))
            btn.setFixedHeight(40)
            btn.clicked.connect(func)
            btn_layout.addWidget(btn)
            if hasattr(self.main_app, "shortcut_manager"):
                self.main_app.shortcut_manager.add(widget, shortcut_key, func, shortcut_desc)
        main_layout.addLayout(btn_layout)
        info_balance_layout = QHBoxLayout()
        info_group = QGroupBox(self.main_app.lang.get("person_info", "Kişi Bilgileri"))
        info_layout = QFormLayout(info_group)
        self.main_app.lbl_ad_soyad = QLabel("-")
        self.main_app.lbl_telefon = QLabel("-")
        self.main_app.lbl_adres = QLabel("-")
        info_layout.addRow(self.main_app.lang.get("full_name", "Ad Soyad:"), self.main_app.lbl_ad_soyad)
        info_layout.addRow(self.main_app.lang.get("phone", "Telefon:"), self.main_app.lbl_telefon)
        info_layout.addRow(self.main_app.lang.get("address", "Adres:"), self.main_app.lbl_adres)
        info_balance_layout.addWidget(info_group, 1)
        balance_group = QGroupBox(self.main_app.lang.get("balance_status", "Bakiye Durumu"))
        balance_layout = QGridLayout(balance_group)
        balance_layout.addWidget(QLabel(f"<b>{self.main_app.lang.get('debtor', 'BORÇLU')}</b>"), 0, 0)
        balance_layout.addWidget(QLabel(f"<b>{self.main_app.lang.get('creditor', 'ALACAKLI')}</b>"), 0, 1)
        self.main_app.lbl_borclu_val = QLabel("0.00")
        self.main_app.lbl_borclu_val.setStyleSheet("color: #D32F2F; font-size: 14px; font-weight: bold;")
        self.main_app.lbl_borclu_val.setAlignment(Qt.AlignmentFlag.AlignTop | Qt.AlignmentFlag.AlignLeft)
        self.main_app.lbl_borclu_val.setWordWrap(True)
        self.main_app.lbl_alacakli_val = QLabel("0.00")
        self.main_app.lbl_alacakli_val.setStyleSheet("color: #388E3C; font-size: 14px; font-weight: bold;")
        self.main_app.lbl_alacakli_val.setAlignment(Qt.AlignmentFlag.AlignTop | Qt.AlignmentFlag.AlignLeft)
        self.main_app.lbl_alacakli_val.setWordWrap(True)

        debtor_scroll = QScrollArea()
        debtor_scroll.setWidgetResizable(True)
        debtor_scroll.setFrameShape(QFrame.Shape.NoFrame)
        debtor_scroll.setHorizontalScrollBarPolicy(Qt.ScrollBarPolicy.ScrollBarAlwaysOff)
        debtor_scroll.setVerticalScrollBarPolicy(Qt.ScrollBarPolicy.ScrollBarAsNeeded)
        debtor_wrap = QWidget()
        debtor_wrap_layout = QVBoxLayout(debtor_wrap)
        debtor_wrap_layout.setContentsMargins(0, 0, 0, 0)
        debtor_wrap_layout.addWidget(self.main_app.lbl_borclu_val)
        debtor_wrap_layout.addStretch()
        debtor_scroll.setWidget(debtor_wrap)

        creditor_scroll = QScrollArea()
        creditor_scroll.setWidgetResizable(True)
        creditor_scroll.setFrameShape(QFrame.Shape.NoFrame)
        creditor_scroll.setHorizontalScrollBarPolicy(Qt.ScrollBarPolicy.ScrollBarAlwaysOff)
        creditor_scroll.setVerticalScrollBarPolicy(Qt.ScrollBarPolicy.ScrollBarAsNeeded)
        creditor_wrap = QWidget()
        creditor_wrap_layout = QVBoxLayout(creditor_wrap)
        creditor_wrap_layout.setContentsMargins(0, 0, 0, 0)
        creditor_wrap_layout.addWidget(self.main_app.lbl_alacakli_val)
        creditor_wrap_layout.addStretch()
        creditor_scroll.setWidget(creditor_wrap)

        visible_rows = 5
        row_height = self.main_app.lbl_borclu_val.fontMetrics().lineSpacing()
        scroll_height = (visible_rows * row_height) + 8
        debtor_scroll.setFixedHeight(scroll_height)
        creditor_scroll.setFixedHeight(scroll_height)

        balance_layout.addWidget(debtor_scroll, 1, 0)
        balance_layout.addWidget(creditor_scroll, 1, 1)
        balance_layout.setRowStretch(1, 1)
        info_balance_layout.addWidget(balance_group, 2)
        main_layout.addLayout(info_balance_layout)
        self.main_app.excel_table = QTableWidget()
        headers = [
            self.main_app.lang.get("transaction_col", "İŞLEM"),
            self.main_app.lang.get("date_col", "TARİH"),
            self.main_app.lang.get("description_col", "AÇIKLAMA"),
            self.main_app.lang.get("type_col", "TÜR"),
            self.main_app.lang.get("amount_col", "TUTAR"),
            self.main_app.lang.get("detail_col", "DETAIL") # 6. Sütun (Index 5)
        ]
        self.main_app.excel_table.setColumnCount(len(headers))
        self.main_app.excel_table.setHorizontalHeaderLabels(headers)
        self.main_app.excel_table.horizontalHeader().setSectionResizeMode(QHeaderView.ResizeMode.Stretch)
        self.main_app.excel_table.horizontalHeader().setSectionResizeMode(len(headers)-1, QHeaderView.ResizeMode.ResizeToContents)
        self.main_app.excel_table.setAlternatingRowColors(True)
        self.main_app.excel_table.setEditTriggers(QTableWidget.EditTrigger.NoEditTriggers)
        self.main_app.excel_table.setSelectionBehavior(QTableWidget.SelectionBehavior.SelectRows)
        self.main_app.excel_table.setSelectionMode(QTableWidget.SelectionMode.SingleSelection)
        self.main_app.excel_table.itemSelectionChanged.connect(self.main_app.crm_manager._acc_excel_update_buttons)
        self.main_app.acc_tab_history_table = self.main_app.excel_table
        main_layout.addWidget(self.main_app.excel_table, 1)
        manage_layout = QHBoxLayout()
        manage_layout.addStretch()
        self.main_app.acc_excel_edit_btn = QPushButton(self.main_app.lang.get("edit_selected_transaction", "Seçili İşlemi Düzenle"))
        self.main_app.acc_excel_edit_btn.setIcon(self.main_app._get_icon("SP_DialogResetButton"))
        self.main_app.acc_excel_edit_btn.setEnabled(False)
        self.main_app.acc_excel_edit_btn.clicked.connect(self.main_app.crm_manager._acc_excel_edit_transaction)
        self.main_app.acc_excel_delete_btn = QPushButton(self.main_app.lang.get("delete_selected_transaction", "Seçili İşlemi Sil"))
        self.main_app.acc_excel_delete_btn.setIcon(self.main_app._get_icon("SP_TrashIcon"))
        self.main_app.acc_excel_delete_btn.setObjectName("dangerButton")
        self.main_app.acc_excel_delete_btn.setEnabled(False)
        self.main_app.acc_excel_delete_btn.clicked.connect(self.main_app.crm_manager._acc_excel_delete_transaction)
        manage_layout.addWidget(self.main_app.acc_excel_edit_btn)
        manage_layout.addWidget(self.main_app.acc_excel_delete_btn)
        main_layout.addLayout(manage_layout)
        return widget
    def build_customer_category(self) -> QWidget:
        """4. MÜŞTERİ İŞLEMLERİ Kategorisi - Yetki Kontrollü"""
        tabs = QTabWidget()
        if self.main_app.has_permission("perm_accounts"):
            accounts_widget = self.create_accounts_tab()
            tabs.addTab(accounts_widget, self.main_app.lang.get("tab_current_accounts", "Current Accounts"))
        if self.main_app.has_permission("perm_contacts"):
            manage_widget = self.create_contacts_manage_subtab()
            tabs.addTab(manage_widget, self.main_app.lang.get("tab_customer_management", "Customer Management"))
        self.main_app.contacts_tab_widget = tabs
        self.main_app.customers_tab_widget = tabs
        return tabs
    def build_services_category(self) -> QWidget:
        """5. HİZMETLER Kategorisi - Yetki Kontrollü"""
        tabs = QTabWidget()
        if self.main_app.has_permission("perm_repair"):
            repair_widget = self.create_repair_tab()
            tabs.addTab(repair_widget, self.main_app.lang.get("tab_repair_tracking", "Repair Tracking (Legacy)"))
        if self.main_app.has_permission("perm_services"):
            try:
                from modules.services import ServicesWidget
                services_widget = ServicesWidget(self.main_app)
                tabs.addTab(services_widget, self.main_app.lang.get("tab_services_operations", "Services & Operations"))
            except ImportError as e:
                print(f"Hizmetler modülü yüklenemedi: {e}")
        self.main_app.services_tab_widget = tabs
        self.main_app.repair_tab_widget = tabs # Geriye dönük uyumluluk
        return tabs
    def build_tools_category(self) -> QWidget:
        """6. ARAÇLAR Kategorisi - Yetki Kontrollü"""
        tabs = QTabWidget()
        if self.main_app.has_permission("perm_reports"):
            tabs.addTab(self.create_report_tab(), self.main_app.lang.get("tab_reporting", "Reporting"))
        if self.main_app.has_permission("perm_agenda"):
            tabs.addTab(self.create_agenda_tab(), self.main_app.lang.get("tab_agenda", "Agenda"))
        if self.main_app.has_permission("perm_search"):
            tabs.addTab(self.create_search_tab(), self.main_app.lang.get("tab_search", "Search"))
        if self.main_app.has_permission("perm_calculator"):
            tabs.addTab(self.create_calculator_tab(), self.main_app.lang.get("tab_calculator", "Calculator"))
        if self.main_app.has_permission("perm_zakat"):
            tabs.addTab(self.create_zakat_tab(), self.main_app.lang.get("tab_zakat_calculator", "Zakat Calculator"))
        self.main_app.tools_tab_widget = tabs
        return tabs
    def build_settings_category(self) -> QWidget:
        """AYARLAR Kategorisi (İçerik aynı, sadece çağırıyoruz)"""
        return self.create_settings_tab()
    def create_agenda_tab(self) -> QWidget:
        widget = QWidget()
        main_layout = QHBoxLayout(widget)
        left_panel = QWidget()
        left_layout = QVBoxLayout(left_panel)
        self.main_app.calendar = QCalendarWidget()
        try:
            is_tr = getattr(self.main_app, 'current_lang_code', 'TR') == 'TR'
            self.main_app.calendar.setLocale(QLocale(QLocale.Language.Turkish) if is_tr else QLocale(QLocale.Language.English))
        except:
            pass
        self.main_app.calendar.selectionChanged.connect(self.main_app.utility_manager._load_calendar_note)
        self.main_app.calendar.currentPageChanged.connect(self.main_app._update_calendar_markers)
        button_layout = QHBoxLayout()
        save_note_btn = QPushButton(self.main_app._get_icon("SP_DialogSaveButton"), self.main_app.lang["save"])
        save_note_btn.setObjectName("primaryButton")
        save_note_btn.setAutoDefault(True)
        save_note_btn.clicked.connect(self.main_app._save_calendar_note)
        delete_note_btn = QPushButton(self.main_app._get_icon("SP_TrashIcon"), self.main_app.lang["delete"])
        delete_note_btn.setObjectName("dangerButton")
        delete_note_btn.clicked.connect(self.main_app._delete_calendar_note)
        button_layout.addWidget(save_note_btn)
        button_layout.addWidget(delete_note_btn)
        self.main_app.agenda_reminder_checkbox = QCheckBox(self.main_app.lang["set_as_reminder"])
        left_layout.addWidget(self.main_app.calendar)
        left_layout.addLayout(button_layout)
        left_layout.addWidget(self.main_app.agenda_reminder_checkbox)
        right_panel = QWidget()
        right_layout = QVBoxLayout(right_panel)
        notes_group = QGroupBox(self.main_app.lang["notes"])
        notes_layout = QVBoxLayout(notes_group)
        toolbar_layout = QHBoxLayout()
        self.main_app.font_combo = QFontComboBox()
        self.main_app.font_combo.currentFontChanged.connect(self.main_app._apply_font_family)
        self.main_app.font_size_combo = QComboBox()
        self.main_app.font_size_combo.addItems([str(s) for s in QFontDatabase.standardSizes()])
        self.main_app.font_size_combo.setCurrentText("12")
        self.main_app.font_size_combo.currentIndexChanged.connect(self.main_app._apply_font_size)
        color_btn = QPushButton(self.main_app.lang["color"])
        color_btn.clicked.connect(self.main_app._apply_font_color)
        self.main_app.bold_btn = QPushButton(self.main_app.lang["bold"])
        self.main_app.bold_btn.setCheckable(True)
        self.main_app.bold_btn.clicked.connect(self.main_app._apply_bold_style)
        toolbar_layout.addWidget(self.main_app.font_combo, 2)
        toolbar_layout.addWidget(self.main_app.font_size_combo, 1)
        toolbar_layout.addWidget(color_btn)
        toolbar_layout.addWidget(self.main_app.bold_btn)
        notes_layout.addLayout(toolbar_layout)
        self.main_app.notes_text = QTextEdit()
        self.main_app.notes_text.setFontPointSize(12)
        notes_layout.addWidget(self.main_app.notes_text)
        right_layout.addWidget(notes_group)
        main_layout.addWidget(left_panel, 1)
        main_layout.addWidget(right_panel, 2)
        QTimer.singleShot(100, self.main_app.utility_manager._load_calendar_note)
        return widget
    def create_repair_tab(self) -> QWidget:
        widget = QWidget()
        main_layout = QVBoxLayout(widget)
        form_group = QGroupBox(self.main_app.lang["new_repair_record"])
        form_layout = QFormLayout(form_group)
        self.main_app.repair_customer_combo = QComboBox()
        self.main_app.repair_customer_combo.setEditable(True)
        self.main_app.repair_customer_combo.setPlaceholderText(self.main_app.lang["customer_name_placeholder"])
        person_names = self.main_app.person_manager.get_person_names()
        self.main_app.repair_customer_combo.addItems([""] + person_names)
        completer = QCompleter(person_names)
        completer.setCaseSensitivity(Qt.CaseSensitivity.CaseInsensitive)
        completer.setFilterMode(Qt.MatchFlag.MatchContains)
        self.main_app.repair_customer_combo.setCompleter(completer)
        self.main_app.repair_product_description_entry = QLineEdit()
        self.main_app.repair_complaint_entry = QTextEdit()
        self.main_app.repair_complaint_entry.setFixedHeight(60)
        fee_layout = QHBoxLayout()
        self.main_app.repair_estimated_fee_entry = QLineEdit()
        self.main_app.repair_estimated_fee_entry.setValidator(self.main_app._create_float_validator())
        self.main_app.repair_fee_currency_combo = QComboBox()
        self.main_app.repair_fee_currency_combo.addItems(SUPPORTED_CURRENCIES)
        self.main_app.repair_fee_currency_combo.setCurrentText(self.main_app.display_currency)
        fee_layout.addWidget(self.main_app.repair_estimated_fee_entry)
        fee_layout.addWidget(self.main_app.repair_fee_currency_combo)
        form_layout.addRow(f"{self.main_app.lang['customer_name']}:", self.main_app.repair_customer_combo)
        form_layout.addRow(f"{self.main_app.lang['product_desc']}:", self.main_app.repair_product_description_entry)
        form_layout.addRow(f"{self.main_app.lang['complaint']}:", self.main_app.repair_complaint_entry)
        form_layout.addRow(f"{self.main_app.lang['estimated_fee']}:", fee_layout)
        btn_layout = QHBoxLayout()
        add_btn = QPushButton(self.main_app._get_icon("SP_DialogApplyButton"), self.main_app.lang["add"])
        add_btn.setObjectName("primaryButton")
        add_btn.setAutoDefault(True)
        add_btn.clicked.connect(self.main_app._add_repair_record)
        clear_btn = QPushButton(self.main_app._get_icon("SP_DialogResetButton"), self.main_app.lang["clear_form"])
        clear_btn.clicked.connect(self.main_app._clear_repair_form)
        btn_layout.addWidget(add_btn)
        btn_layout.addWidget(clear_btn)
        form_layout.addRow(btn_layout)
        main_layout.addWidget(form_group)
        list_group = QGroupBox(self.main_app.lang["repair_module"])
        list_layout = QVBoxLayout(list_group)
        filter_layout = QHBoxLayout()
        filter_layout.addWidget(QLabel(self.main_app.lang["filter_by_person"]))
        self.main_app.repair_filter_combo = QComboBox()
        self.main_app.repair_filter_combo.setEditable(True)
        person_names = self.main_app.person_manager.get_person_names()
        show_all_text = self.main_app.lang.get("show_all", "Tümünü Göster")
        self.main_app.repair_filter_combo.addItem(show_all_text)
        self.main_app.repair_filter_combo.addItems(person_names)
        completer = QCompleter([show_all_text] + person_names)
        completer.setCaseSensitivity(Qt.CaseSensitivity.CaseInsensitive)
        completer.setFilterMode(Qt.MatchFlag.MatchContains)
        self.main_app.repair_filter_combo.setCompleter(completer)
        self.main_app.repair_filter_combo.currentIndexChanged.connect(self.main_app.update_repair_list_display)
        filter_layout.addWidget(self.main_app.repair_filter_combo)
        filter_layout.addStretch()
        list_layout.addLayout(filter_layout)
        self.main_app.repair_table = QTableWidget(0, 6)
        self.main_app.repair_table.setHorizontalHeaderLabels([self.main_app.lang["customer_name"], self.main_app.lang["product_desc"], self.main_app.lang["complaint"], self.main_app.lang["date"], self.main_app.lang["estimated_fee"], self.main_app.lang["status"]])
        self.main_app.repair_table.horizontalHeader().setSectionResizeMode(QHeaderView.ResizeMode.Stretch)
        self.main_app.repair_table.setEditTriggers(QTableWidget.EditTrigger.NoEditTriggers)
        self.main_app.repair_table.setSelectionBehavior(QTableWidget.SelectionBehavior.SelectRows)
        self.main_app.repair_table.setSelectionMode(QTableWidget.SelectionMode.SingleSelection)
        self.main_app.repair_table.setAlternatingRowColors(True)
        try:
            self.main_app.repair_table.selectionModel().selectionChanged.connect(lambda *_: self.main_app._repair_record_selected())
        except Exception:
            pass
        self.main_app.repair_table.itemSelectionChanged.connect(self.main_app._update_repair_button_states)
        list_layout.addWidget(self.main_app.repair_table)
        manage_layout = QHBoxLayout()
        self.main_app.repair_status_combo = QComboBox()
        self.main_app.repair_status_combo.addItems([self.main_app.lang["received"], self.main_app.lang["in_repair"], self.main_app.lang["ready"], self.main_app.lang["delivered"]])
        self.main_app.repair_change_status_btn = QPushButton(self.main_app.lang["mark_as"]); self.main_app.repair_change_status_btn.clicked.connect(self.main_app._update_repair_status)
        self.main_app.repair_deliver_collect_btn = QPushButton(self.main_app.lang["deliver_and_collect"]); self.main_app.repair_deliver_collect_btn.setObjectName("primaryButton"); self.main_app.repair_deliver_collect_btn.clicked.connect(self.main_app._deliver_and_collect_repair)
        self.main_app.repair_delete_btn = QPushButton(self.main_app._get_icon("SP_TrashIcon"), self.main_app.lang["delete"]); self.main_app.repair_delete_btn.setObjectName("dangerButton"); self.main_app.repair_delete_btn.clicked.connect(self.main_app._delete_repair_record)
        manage_layout.addWidget(QLabel(f"{self.main_app.lang['mark_as']}:"))
        manage_layout.addWidget(self.main_app.repair_status_combo)
        manage_layout.addWidget(self.main_app.repair_change_status_btn)
        manage_layout.addStretch()
        manage_layout.addWidget(self.main_app.repair_deliver_collect_btn)
        manage_layout.addWidget(self.main_app.repair_delete_btn)
        list_layout.addLayout(manage_layout)
        main_layout.addWidget(list_group)
        self.main_app._update_repair_button_states()
        self.main_app.setTabOrder(self.main_app.repair_customer_combo, self.main_app.repair_product_description_entry)
        self.main_app.setTabOrder(self.main_app.repair_product_description_entry, self.main_app.repair_complaint_entry)
        self.main_app.setTabOrder(self.main_app.repair_complaint_entry, self.main_app.repair_estimated_fee_entry)
        self.main_app.setTabOrder(self.main_app.repair_estimated_fee_entry, self.main_app.repair_fee_currency_combo)
        self.main_app.setTabOrder(self.main_app.repair_fee_currency_combo, add_btn)
        self.main_app.setTabOrder(add_btn, clear_btn)
        self.main_app.setTabOrder(clear_btn, self.main_app.repair_filter_combo)
        self.main_app.setTabOrder(self.main_app.repair_filter_combo, self.main_app.repair_table)
        self.main_app.setTabOrder(self.main_app.repair_table, self.main_app.repair_status_combo)
        self.main_app.setTabOrder(self.main_app.repair_status_combo, self.main_app.repair_change_status_btn)
        self.main_app.setTabOrder(self.main_app.repair_change_status_btn, self.main_app.repair_deliver_collect_btn)
        self.main_app.setTabOrder(self.main_app.repair_deliver_collect_btn, self.main_app.repair_delete_btn)
        return widget
    def _create_cash_content(self) -> QWidget:
        """Nakit içeriğini oluşturan yardımcı fonksiyon."""
        widget = QWidget()
        layout = QVBoxLayout(widget)
        account_group = QGroupBox(self.main_app.lang["select_cash_account"])
        account_layout = QHBoxLayout(account_group)
        self.main_app.cash_account_selector_combo = QComboBox()
        self.main_app.cash_account_selector_combo.currentIndexChanged.connect(self.main_app.finance_manager.update_cash_transaction_display)
        self.main_app.cash_account_selector_combo.currentIndexChanged.connect(self.main_app.finance_manager._update_cash_account_button_states)
        add_account_btn = QPushButton(self.main_app._get_icon("SP_DialogApplyButton"), self.main_app.lang["add_cash_account"])
        add_account_btn.clicked.connect(self.main_app.finance_manager._add_cash_account)
        self.main_app.edit_cash_account_btn = QPushButton(self.main_app.lang["edit_cash_account"])
        self.main_app.edit_cash_account_btn.clicked.connect(self.main_app.finance_manager._edit_cash_account)
        self.main_app.delete_cash_account_btn = QPushButton(self.main_app._get_icon("SP_TrashIcon"), self.main_app.lang["delete_cash_account"])
        self.main_app.delete_cash_account_btn.setObjectName("dangerButton")
        self.main_app.delete_cash_account_btn.clicked.connect(self.main_app.finance_manager._delete_cash_account)
        account_layout.addWidget(self.main_app.cash_account_selector_combo, 1)
        account_layout.addWidget(add_account_btn)
        account_layout.addWidget(self.main_app.edit_cash_account_btn)
        account_layout.addWidget(self.main_app.delete_cash_account_btn)
        layout.addWidget(account_group)
        list_group = QGroupBox(self.main_app.lang["all_cash_movements"])
        list_layout = QVBoxLayout(list_group)
        self.main_app.cash_transaction_table = QTableWidget(0, 5)
        self.main_app.cash_transaction_table.setHorizontalHeaderLabels(["", self.main_app.lang["date"], self.main_app.lang["transaction_type"], self.main_app.lang["amount"], self.main_app.lang["description"]])
        self.main_app.cash_transaction_table.horizontalHeader().setSectionResizeMode(QHeaderView.ResizeMode.Stretch)
        self.main_app.cash_transaction_table.setEditTriggers(QTableWidget.EditTrigger.NoEditTriggers)
        self.main_app.cash_transaction_table.setColumnWidth(0, 30)
        self.main_app.cash_transaction_table.itemSelectionChanged.connect(lambda: self.main_app._update_transaction_button_states(self.main_app.cash_edit_btn, self.main_app.cash_delete_btn, self.main_app.cash_transaction_table))
        btn_layout = QHBoxLayout()
        self.main_app.cash_edit_btn = QPushButton(self.main_app._get_icon("SP_DialogResetButton"), self.main_app.lang["edit"])
        self.main_app.cash_edit_btn.clicked.connect(self.main_app.finance_manager._edit_cash_transaction)
        self.main_app.cash_delete_btn = QPushButton(self.main_app._get_icon("SP_TrashIcon"), self.main_app.lang["delete"])
        self.main_app.cash_delete_btn.setObjectName("dangerButton")
        self.main_app.cash_delete_btn.clicked.connect(self.main_app.finance_manager._delete_cash_transaction)
        for w in [self.main_app.cash_edit_btn, self.main_app.cash_delete_btn]: btn_layout.addWidget(w)
        btn_layout.addStretch()
        list_layout.addWidget(self.main_app.cash_transaction_table)
        list_layout.addLayout(btn_layout)
        layout.addWidget(list_group)
        self.main_app._update_transaction_button_states(self.main_app.cash_edit_btn, self.main_app.cash_delete_btn, self.main_app.cash_transaction_table)
        summary_group = QGroupBox(self.main_app.lang["overall_cash_summary"])
        self.main_app.cash_summary_widget = QWidget()
        summary_layout = QVBoxLayout(summary_group)
        summary_layout.addWidget(self.main_app.cash_summary_widget)
        layout.addWidget(summary_group)
        self.main_app.finance_manager._update_cash_account_button_states()
        self.main_app.setTabOrder(self.main_app.cash_account_selector_combo, add_account_btn)
        self.main_app.setTabOrder(add_account_btn, self.main_app.edit_cash_account_btn)
        self.main_app.setTabOrder(self.main_app.edit_cash_account_btn, self.main_app.delete_cash_account_btn)
        self.main_app.setTabOrder(self.main_app.delete_cash_account_btn, self.main_app.cash_transaction_table)
        self.main_app.setTabOrder(self.main_app.cash_transaction_table, self.main_app.cash_edit_btn)
        self.main_app.setTabOrder(self.main_app.cash_edit_btn, self.main_app.cash_delete_btn)
        return widget
    def _create_cards_content(self) -> QWidget:
        """Kart içeriğini oluşturan yardımcı fonksiyon."""
        widget = QWidget()
        layout = QVBoxLayout(widget)
        account_group = QGroupBox(self.main_app.lang["select_card_account"])
        account_layout = QHBoxLayout(account_group)
        self.main_app.card_account_selector_combo = QComboBox()
        self.main_app.card_account_selector_combo.currentIndexChanged.connect(self.main_app.finance_manager.update_card_transaction_display)
        self.main_app.card_account_selector_combo.currentIndexChanged.connect(self.main_app.finance_manager._update_card_account_button_states)
        add_account_btn = QPushButton(self.main_app._get_icon("SP_DialogApplyButton"), self.main_app.lang["add_card_account"])
        add_account_btn.clicked.connect(self.main_app.finance_manager._add_card_account)
        self.main_app.edit_card_account_btn = QPushButton(self.main_app.lang["edit_card_account"])
        self.main_app.edit_card_account_btn.clicked.connect(self.main_app.finance_manager._edit_card_account)
        self.main_app.delete_card_account_btn = QPushButton(self.main_app._get_icon("SP_TrashIcon"), self.main_app.lang["delete_card_account"])
        self.main_app.delete_card_account_btn.setObjectName("dangerButton")
        self.main_app.delete_card_account_btn.clicked.connect(self.main_app.finance_manager._delete_card_account)
        account_layout.addWidget(self.main_app.card_account_selector_combo, 1)
        account_layout.addWidget(add_account_btn)
        account_layout.addWidget(self.main_app.edit_card_account_btn)
        account_layout.addWidget(self.main_app.delete_card_account_btn)
        layout.addWidget(account_group)
        list_group = QGroupBox(self.main_app.lang["all_card_movements"])
        list_layout = QVBoxLayout(list_group)
        self.main_app.card_transaction_table = QTableWidget(0, 5)
        self.main_app.card_transaction_table.setHorizontalHeaderLabels(["", self.main_app.lang["date"], self.main_app.lang["transaction_type"], self.main_app.lang["amount"], self.main_app.lang["description"]])
        self.main_app.card_transaction_table.horizontalHeader().setSectionResizeMode(QHeaderView.ResizeMode.Stretch)
        self.main_app.card_transaction_table.setEditTriggers(QTableWidget.EditTrigger.NoEditTriggers)
        self.main_app.card_transaction_table.setColumnWidth(0, 30)
        self.main_app.card_transaction_table.itemSelectionChanged.connect(lambda: self.main_app._update_transaction_button_states(self.main_app.card_edit_btn, self.main_app.card_delete_btn, self.main_app.card_transaction_table))
        btn_layout = QHBoxLayout()
        self.main_app.card_edit_btn = QPushButton(self.main_app._get_icon("SP_DialogResetButton"), self.main_app.lang["edit"])
        self.main_app.card_edit_btn.clicked.connect(self.main_app.finance_manager._edit_card_transaction)
        self.main_app.card_delete_btn = QPushButton(self.main_app._get_icon("SP_TrashIcon"), self.main_app.lang["delete"])
        self.main_app.card_delete_btn.setObjectName("dangerButton")
        self.main_app.card_delete_btn.clicked.connect(self.main_app.finance_manager._delete_card_transaction)
        for w in [self.main_app.card_edit_btn, self.main_app.card_delete_btn]: btn_layout.addWidget(w)
        btn_layout.addStretch()
        list_layout.addWidget(self.main_app.card_transaction_table)
        list_layout.addLayout(btn_layout)
        layout.addWidget(list_group)
        self.main_app._update_transaction_button_states(self.main_app.card_edit_btn, self.main_app.card_delete_btn, self.main_app.card_transaction_table)
        summary_group = QGroupBox(self.main_app.lang["overall_card_summary"])
        self.main_app.card_summary_widget = QWidget()
        summary_layout = QVBoxLayout(summary_group)
        summary_layout.addWidget(self.main_app.card_summary_widget)
        layout.addWidget(summary_group)
        self.main_app.finance_manager._update_card_account_button_states()
        self.main_app.setTabOrder(self.main_app.card_account_selector_combo, add_account_btn)
        self.main_app.setTabOrder(add_account_btn, self.main_app.edit_card_account_btn)
        self.main_app.setTabOrder(self.main_app.edit_card_account_btn, self.main_app.delete_card_account_btn)
        self.main_app.setTabOrder(self.main_app.delete_card_account_btn, self.main_app.card_transaction_table)
        self.main_app.setTabOrder(self.main_app.card_transaction_table, self.main_app.card_edit_btn)
        self.main_app.setTabOrder(self.main_app.card_edit_btn, self.main_app.card_delete_btn)
        return widget
    def create_depots_tab(self) -> QWidget:
        """Depolar sekmesini oluşturur (Gelişmiş Transfer Paneli)."""
        widget = QWidget()
        widget.setObjectName("depots_tab")
        layout = QVBoxLayout(widget)
        manage_group = QGroupBox(self.main_app.lang["manage_depots"])
        manage_layout = QHBoxLayout(manage_group)
        self.main_app.depot_selector_combo = QComboBox()
        self.main_app.depot_selector_combo.currentIndexChanged.connect(self.main_app.update_depot_content_display)
        self.main_app.depot_selector_combo.currentIndexChanged.connect(self.main_app._update_depot_manage_buttons)
        self.main_app.depot_selector_combo.currentIndexChanged.connect(self.main_app._update_depot_transfer_products_list) # <-- YENİ BAÄLANTI
        add_btn = QPushButton(self.main_app._get_icon("SP_DialogApplyButton"), self.main_app.lang["add_depot"])
        add_btn.clicked.connect(self.main_app._add_depot)
        self.main_app.edit_depot_btn = QPushButton(self.main_app.lang["edit_depot"])
        self.main_app.edit_depot_btn.clicked.connect(self.main_app._edit_depot)
        self.main_app.delete_depot_btn = QPushButton(self.main_app._get_icon("SP_TrashIcon"), self.main_app.lang["delete_depot"])
        self.main_app.delete_depot_btn.setObjectName("dangerButton")
        self.main_app.delete_depot_btn.clicked.connect(self.main_app._delete_depot)
        manage_layout.addWidget(QLabel(self.main_app.lang.get("source_depot_bold", "<b>Source Depot:</b>"))) # Netlik için etiket eklendi
        manage_layout.addWidget(self.main_app.depot_selector_combo, 1)
        manage_layout.addWidget(add_btn)
        manage_layout.addWidget(self.main_app.edit_depot_btn)
        manage_layout.addWidget(self.main_app.delete_depot_btn)
        layout.addWidget(manage_group)
        content_group = QGroupBox(self.main_app.lang.get("depot_content", "Depot Content"))
        content_layout = QVBoxLayout(content_group)
        self.main_app.depot_content_table = QTableWidget(0, 5)
        headers = [self.main_app.lang.get("type_col", "Type"), self.main_app.lang.get("product_name_col", "Product Name"), self.main_app.lang.get("detail_barcode_col", "Detail / Barcode"), self.main_app.lang.get("quantity_col", "Quantity"), self.main_app.lang.get("cost_value_col", "Cost Value")]
        self.main_app.depot_content_table.setHorizontalHeaderLabels(headers)
        self.main_app.depot_content_table.horizontalHeader().setSectionResizeMode(QHeaderView.ResizeMode.Stretch)
        self.main_app.depot_content_table.setSelectionBehavior(QTableWidget.SelectionBehavior.SelectRows)
        self.main_app.depot_content_table.setEditTriggers(QTableWidget.EditTrigger.NoEditTriggers)
        content_layout.addWidget(self.main_app.depot_content_table)
        self.main_app.depot_total_value_label = QLabel(f"{self.main_app.lang.get('total_value', 'Total Value')}: 0.00")
        self.main_app.depot_total_value_label.setAlignment(Qt.AlignmentFlag.AlignRight)
        font = self.main_app.depot_total_value_label.font(); font.setBold(True); self.main_app.depot_total_value_label.setFont(font)
        content_layout.addWidget(self.main_app.depot_total_value_label)
        layout.addWidget(content_group, 2)
        transfer_group = QGroupBox(self.main_app.lang.get("manual_depot_transfer", "Manual Depot Transfer"))
        transfer_layout = QHBoxLayout(transfer_group)
        transfer_layout.setSpacing(10)
        self.main_app.depot_trans_dest_combo = QComboBox()
        self.main_app.depot_trans_dest_combo.setMinimumWidth(120)
        self.main_app.depot_trans_type_combo = QComboBox()
        self.main_app.depot_trans_type_combo.addItems([self.main_app.lang.get("gold", "Gold"), self.main_app.lang.get("scrap", "Scrap"), self.main_app.lang.get("ziynet", "Ziynet")])
        self.main_app.depot_trans_type_combo.setFixedWidth(80)
        self.main_app.depot_trans_type_combo.currentIndexChanged.connect(self.main_app._update_depot_transfer_products_list)
        self.main_app.depot_trans_product_combo = QComboBox()
        self.main_app.depot_trans_product_combo.setEditable(True)
        self.main_app.depot_trans_product_combo.setMinimumWidth(150)
        self.main_app.depot_trans_product_combo.setPlaceholderText(self.main_app.lang.get("select_product", "Select Product"))
        self.main_app.depot_trans_qty_entry = QLineEdit()
        self.main_app.depot_trans_qty_entry.setPlaceholderText(self.main_app.lang.get("quantity", "Quantity"))
        self.main_app.depot_trans_qty_entry.setValidator(self.main_app._create_float_validator(3))
        self.main_app.depot_trans_qty_entry.setFixedWidth(80)
        transfer_btn = QPushButton(self.main_app.lang.get("transfer_btn", "Transfer"))
        transfer_btn.setIcon(self.main_app._get_icon("SP_ArrowRight"))
        transfer_btn.setObjectName("primaryButton")
        transfer_btn.clicked.connect(self.main_app._execute_general_depot_transfer)
        transfer_layout.addWidget(QLabel(self.main_app.lang.get("target_bold", "<b>Target:</b>")))
        transfer_layout.addWidget(self.main_app.depot_trans_dest_combo)
        transfer_layout.addWidget(QLabel(self.main_app.lang.get("type_bold", "<b>Type:</b>")))
        transfer_layout.addWidget(self.main_app.depot_trans_type_combo)
        transfer_layout.addWidget(QLabel(self.main_app.lang.get("product_bold", "<b>Product:</b>")))
        transfer_layout.addWidget(self.main_app.depot_trans_product_combo, 1) # Esnek genişlik
        transfer_layout.addWidget(QLabel(self.main_app.lang.get("quantity_bold", "<b>Quantity:</b>")))
        transfer_layout.addWidget(self.main_app.depot_trans_qty_entry)
        transfer_layout.addWidget(transfer_btn)
        layout.addWidget(transfer_group)
        self.main_app._update_depot_manage_buttons()
        self.main_app.update_depot_displays()
        QTimer.singleShot(200, self.main_app._update_depot_transfer_products_list)
        return widget
    def create_contacts_tab(self) -> QWidget:
        widget = QTabWidget()
        manage_tab = self.create_contacts_manage_subtab()
        widget.addTab(manage_tab, self.main_app.lang["customer_management"])
        return widget
    def create_exchange_tab(self) -> QWidget:
        widget = QWidget()
        layout = QVBoxLayout(widget)
        exchange_group = QGroupBox(self.main_app.lang["exchange_title"])
        form_layout = QFormLayout(exchange_group)
        self.main_app.exchange_source_account_combo = QComboBox()
        self.main_app.exchange_dest_account_combo = QComboBox()
        form_layout.addRow(f"{self.main_app.lang['source_account']}:", self.main_app.exchange_source_account_combo)
        form_layout.addRow(f"{self.main_app.lang['destination_account']}:", self.main_app.exchange_dest_account_combo)
        sold_layout = QHBoxLayout()
        self.main_app.exchange_sold_amount = QLineEdit()
        self.main_app.exchange_sold_amount.setValidator(self.main_app._create_float_validator())
        self.main_app.exchange_sold_currency = QComboBox()
        self.main_app.exchange_sold_currency.addItems(SUPPORTED_CURRENCIES)
        sold_layout.addWidget(self.main_app.exchange_sold_amount)
        sold_layout.addWidget(self.main_app.exchange_sold_currency)
        form_layout.addRow(f"{self.main_app.lang['sold_amount']}:", sold_layout)
        bought_layout = QHBoxLayout()
        self.main_app.exchange_bought_amount = QLineEdit()
        self.main_app.exchange_bought_amount.setValidator(self.main_app._create_float_validator())
        self.main_app.exchange_bought_currency = QComboBox()
        self.main_app.exchange_bought_currency.addItems(SUPPORTED_CURRENCIES)
        bought_layout.addWidget(self.main_app.exchange_bought_amount)
        bought_layout.addWidget(self.main_app.exchange_bought_currency)
        form_layout.addRow(f"{self.main_app.lang['bought_amount']}:", bought_layout)
        execute_btn = QPushButton(self.main_app._get_icon("SP_DialogApplyButton"), self.main_app.lang["execute_exchange"])
        execute_btn.setObjectName("primaryButton")
        execute_btn.setAutoDefault(True)
        execute_btn.clicked.connect(self.main_app.finance_manager._execute_exchange_transaction)
        form_layout.addRow(execute_btn)
        layout.addWidget(exchange_group)
        rates_group = QGroupBox(self.main_app.lang["exchange_rates_tab"])
        rates_layout = QVBoxLayout(rates_group)
        top_layout = QHBoxLayout()
        refresh_btn = QPushButton(self.main_app._get_icon("SP_BrowserReload"), self.main_app.lang["refresh"])
        refresh_btn.clicked.connect(self.main_app.finance_manager._update_exchange_rates_display)
        top_layout.addWidget(refresh_btn)
        top_layout.addStretch()
        self.main_app.rates_last_updated_label = QLabel("")
        top_layout.addWidget(self.main_app.rates_last_updated_label)
        rates_layout.addLayout(top_layout)
        self.main_app.rates_table = QTableWidget(0, 3)
        self.main_app.rates_table.setHorizontalHeaderLabels([self.main_app.lang["currency"], self.main_app.lang.get("buy_rate", "Buy"), self.main_app.lang.get("sell_rate", "Sell")])
        self.main_app.rates_table.horizontalHeader().setSectionResizeMode(QHeaderView.ResizeMode.Stretch)
        self.main_app.rates_table.setEditTriggers(QTableWidget.EditTrigger.NoEditTriggers)
        rates_layout.addWidget(self.main_app.rates_table)
        layout.addWidget(rates_group, 1)
        QTimer.singleShot(1000, self.main_app.finance_manager._update_exchange_rates_display)
        self.main_app.setTabOrder(self.main_app.exchange_source_account_combo, self.main_app.exchange_dest_account_combo)
        self.main_app.setTabOrder(self.main_app.exchange_dest_account_combo, self.main_app.exchange_sold_amount)
        self.main_app.setTabOrder(self.main_app.exchange_sold_amount, self.main_app.exchange_sold_currency)
        self.main_app.setTabOrder(self.main_app.exchange_sold_currency, self.main_app.exchange_bought_amount)
        self.main_app.setTabOrder(self.main_app.exchange_bought_amount, self.main_app.exchange_bought_currency)
        self.main_app.setTabOrder(self.main_app.exchange_bought_currency, execute_btn)
        self.main_app.setTabOrder(execute_btn, refresh_btn)
        self.main_app.setTabOrder(refresh_btn, self.main_app.rates_table)
        return widget
    def create_report_tab(self) -> QWidget:
        widget = QWidget()
        layout = QVBoxLayout(widget)
        filter_group = QGroupBox(self.main_app.lang["filter_report"])
        filter_layout = QHBoxLayout(filter_group)
        type_layout = QVBoxLayout()
        type_layout.addWidget(QLabel(self.main_app.lang.get("report_type_bold", "<b>Report Type:</b>")))
        self.main_app.report_type_combo = QComboBox()
        self.main_app.report_type_combo.addItems([
            self.main_app.lang.get("rep_fin_reports", "--- FINANCIAL REPORTS ---"),
            self.main_app.lang["profit_loss_report"],
            self.main_app.lang["cash_flow_report"],
            self.main_app.lang.get("rep_stock_reports", "--- STOCK REPORTS ---"),
            self.main_app.lang["product_stock_report"],
            self.main_app.lang["scrap_stock_report"],
            self.main_app.lang["ziynet_stock_report"],
            self.main_app.lang.get("rep_cust_reports", "--- CUSTOMER REPORTS ---"),
            self.main_app.lang["customer_statement_report"],
            self.main_app.lang.get("rep_service_reports", "--- SERVICE REPORTS ---"),
            self.main_app.lang.get("rep_gen_service", "General Service Report"),
            "--- DİÄER ---",
            self.main_app.lang.get("rep_tax_report", "Tax Report") # <-- Eklendi
        ])
        self.main_app.report_type_combo.currentIndexChanged.connect(self.main_app.report_manager._report_type_changed)
        type_layout.addWidget(self.main_app.report_type_combo)
        self.main_app.report_customer_combo = QComboBox()
        self.main_app.report_customer_combo.setEditable(True)
        all_persons = self.main_app.person_manager.get_person_names()
        self.main_app.report_customer_combo.addItems(all_persons)
        completer = QCompleter(all_persons)
        completer.setCaseSensitivity(Qt.CaseSensitivity.CaseInsensitive)
        completer.setFilterMode(Qt.MatchFlag.MatchContains)
        self.main_app.report_customer_combo.setCompleter(completer)
        self.main_app.report_customer_combo.setVisible(False)
        self.main_app.report_customer_combo.currentIndexChanged.connect(self.main_app.report_manager._filter_report)
        type_layout.addWidget(self.main_app.report_customer_combo)
        self.main_app.report_depot_combo = QComboBox()
        self.main_app.report_depot_combo.addItem(self.main_app.lang.get("show_all", "Tümünü Göster"))
        if hasattr(self.main_app, 'depot_manager'):
            self.main_app.report_depot_combo.addItems(self.main_app.depot_manager.get_depot_names())
        self.main_app.report_depot_combo.setVisible(False)
        self.main_app.report_depot_combo.currentIndexChanged.connect(self.main_app.report_manager._filter_report)
        type_layout.addWidget(self.main_app.report_depot_combo)
        filter_layout.addLayout(type_layout, 1)
        self.main_app.report_date_filter_widget = QWidget()
        date_layout = QVBoxLayout(self.main_app.report_date_filter_widget)
        date_layout.setContentsMargins(0,0,0,0)
        date_inputs = QHBoxLayout()
        self.main_app.report_start_date_entry = QDateEdit(datetime.now().replace(day=1)); self.main_app.report_start_date_entry.setCalendarPopup(True); self.main_app.report_start_date_entry.setDisplayFormat("dd.MM.yyyy")
        self.main_app.report_end_date_entry = QDateEdit(datetime.now()); self.main_app.report_end_date_entry.setCalendarPopup(True); self.main_app.report_end_date_entry.setDisplayFormat("dd.MM.yyyy")
        date_inputs.addWidget(QLabel(self.main_app.lang['start_date'])); date_inputs.addWidget(self.main_app.report_start_date_entry)
        date_inputs.addWidget(QLabel(self.main_app.lang['end_date'])); date_inputs.addWidget(self.main_app.report_end_date_entry)
        quick_btns = QHBoxLayout()
        for label, func in [(self.main_app.lang.get("today", "Today"), self.main_app.report_manager._report_today), (self.main_app.lang.get("this_month", "This Month"), self.main_app.report_manager._report_this_month), (self.main_app.lang.get("this_year", "This Year"), self.main_app.report_manager._report_this_year)]:
            btn = QPushButton(label)
            btn.clicked.connect(func)
            btn.setMinimumHeight(40)
            quick_btns.addWidget(btn)
        date_layout.addLayout(date_inputs)
        date_layout.addLayout(quick_btns)
        filter_layout.addWidget(self.main_app.report_date_filter_widget, 2)
        action_layout = QVBoxLayout()
        filter_btn = QPushButton(self.main_app._get_icon("SP_BrowserReload"), self.main_app.lang["filter"])
        filter_btn.setObjectName("primaryButton"); filter_btn.setFixedHeight(35)
        filter_btn.clicked.connect(self.main_app.report_manager._filter_report)
        export_layout = QHBoxLayout()
        pdf_btn = QPushButton("PDF"); pdf_btn.clicked.connect(lambda: self.main_app.report_manager._export_report("pdf"))
        excel_btn = QPushButton("Excel"); excel_btn.clicked.connect(lambda: self.main_app.report_manager._export_report("excel"))
        export_layout.addWidget(pdf_btn); export_layout.addWidget(excel_btn)
        action_layout.addWidget(filter_btn)
        action_layout.addLayout(export_layout)
        filter_layout.addLayout(action_layout, 1)
        layout.addWidget(filter_group)
        self.main_app.report_results_group = QGroupBox(self.main_app.lang["report_results"])
        results_layout = QVBoxLayout(self.main_app.report_results_group)
        self.main_app.report_summary_widget = QWidget()
        summary_card_layout = QHBoxLayout(self.main_app.report_summary_widget)
        summary_card_layout.setSpacing(20)
        self.main_app.card1 = self.main_app.report_manager.create_summary_card()
        self.main_app.card2 = self.main_app.report_manager.create_summary_card()
        self.main_app.card3 = self.main_app.report_manager.create_summary_card()
        summary_card_layout.addWidget(self.main_app.card1)
        summary_card_layout.addWidget(self.main_app.card2)
        summary_card_layout.addWidget(self.main_app.card3)
        summary_card_layout.addStretch()
        results_layout.addWidget(self.main_app.report_summary_widget)
        self.main_app.report_transactions_table = QTableWidget()
        self.main_app.report_transactions_table.setEditTriggers(QTableWidget.EditTrigger.NoEditTriggers)
        self.main_app.report_transactions_table.setAlternatingRowColors(True)
        results_layout.addWidget(self.main_app.report_transactions_table)
        layout.addWidget(self.main_app.report_results_group)
        return widget
    def create_search_tab(self) -> QWidget:
        widget = QWidget()
        layout = QVBoxLayout(widget)
        search_group = QGroupBox(self.main_app.lang["search"])
        search_layout = QHBoxLayout(search_group)
        self.main_app.search_input = QLineEdit()
        self.main_app.search_input.setPlaceholderText(self.main_app.lang["quick_search"])
        self.main_app.search_input.returnPressed.connect(self.main_app.utility_manager._perform_search)
        search_button = QPushButton(self.main_app._get_icon("SP_FileDialogContentsView"), self.main_app.lang["search"])
        search_button.setAutoDefault(True)
        search_button.clicked.connect(self.main_app.utility_manager._perform_search)
        search_layout.addWidget(self.main_app.search_input)
        search_layout.addWidget(search_button)
        barcode_query_btn = QPushButton(self.main_app._get_icon("SP_FileDialogInfoView"), "Barkod Sorgula")
        barcode_query_btn.clicked.connect(self.main_app._open_barcode_query_dialog)
        search_layout.addWidget(barcode_query_btn)
        layout.addWidget(search_group)
        results_group = QGroupBox(self.main_app.lang["results"])
        results_layout = QVBoxLayout(results_group)
        self.main_app.search_results_table = QTableWidget()
        self.main_app.search_results_table.setColumnCount(4)
        self.main_app.search_results_table.setHorizontalHeaderLabels([self.main_app.lang["product_type"], self.main_app.lang["product_name_type"], self.main_app.lang["details"], ""])
        self.main_app.search_results_table.horizontalHeader().setSectionResizeMode(0, QHeaderView.ResizeMode.ResizeToContents)
        self.main_app.search_results_table.horizontalHeader().setSectionResizeMode(1, QHeaderView.ResizeMode.Stretch)
        self.main_app.search_results_table.horizontalHeader().setSectionResizeMode(2, QHeaderView.ResizeMode.Stretch)
        self.main_app.search_results_table.horizontalHeader().setSectionResizeMode(3, QHeaderView.ResizeMode.ResizeToContents)
        results_layout.addWidget(self.main_app.search_results_table)
        layout.addWidget(results_group)
        self.main_app.setTabOrder(self.main_app.search_input, search_button)
        self.main_app.setTabOrder(search_button, self.main_app.search_results_table)
        return widget
    def create_calculator_tab(self) -> QWidget:
        widget = QWidget()
        main_layout = QVBoxLayout(widget)
        main_layout.addStretch()
        self.main_app.calc_display = QLineEdit()
        self.main_app.calc_display.setReadOnly(True)
        self.main_app.calc_display.setAlignment(Qt.AlignmentFlag.AlignRight)
        self.main_app.calc_display.setMaxLength(20)
        font = self.main_app.calc_display.font()
        font.setPointSize(22)
        font.setBold(True)
        self.main_app.calc_display.setFont(font)
        self.main_app.calc_display.setMinimumHeight(60)
        grid_layout = QGridLayout()
        buttons = [
            ('C', 0, 0, 1, 1, "dangerButton"), ('<-', 0, 1, 1, 1, ""), ('(', 0, 2, 1, 1, ""), (')', 0, 3, 1, 1, ""),
            ('7', 1, 0, 1, 1, ""), ('8', 1, 1, 1, 1, ""), ('9', 1, 2, 1, 1, ""), ('/', 1, 3, 1, 1, ""),
            ('4', 2, 0, 1, 1, ""), ('5', 2, 1, 1, 1, ""), ('6', 2, 2, 1, 1, ""), ('*', 2, 3, 1, 1, ""),
            ('1', 3, 0, 1, 1, ""), ('2', 3, 1, 1, 1, ""), ('3', 3, 2, 1, 1, ""), ('-', 3, 3, 1, 1, ""),
            ('0', 4, 0, 1, 2, ""), ('.', 4, 2, 1, 1, ""), ('+', 4, 3, 1, 1, ""),
            ('=', 5, 0, 1, 4, "primaryButton"),
        ]
        for text, row, col, rowspan, colspan, obj_name in buttons:
            button = QPushButton(text)
            button.setSizePolicy(QSizePolicy.Policy.Expanding, QSizePolicy.Policy.Expanding)
            button.setMinimumHeight(50)
            if obj_name:
                button.setObjectName(obj_name)
            button.clicked.connect(partial(self.main_app.utility_manager._on_calc_button_click, text))
            grid_layout.addWidget(button, row, col, rowspan, colspan)
        calc_widget = QWidget()
        calc_layout = QVBoxLayout(calc_widget)
        calc_layout.addWidget(self.main_app.calc_display)
        calc_layout.addLayout(grid_layout)
        calc_widget.setMaximumWidth(450)
        calc_widget.setMaximumHeight(500)
        main_layout.addWidget(calc_widget, 0, Qt.AlignmentFlag.AlignCenter)
        main_layout.addStretch()
        return widget
    def create_settings_tab(self) -> QWidget:
        main_widget = QWidget()
        main_layout = QVBoxLayout(main_widget)
        settings_tabs = QTabWidget()
        settings_tabs.setIconSize(QSize(24, 24))
        self.main_app.settings_category_widget = main_widget
        self.main_app.settings_tabs_widget = settings_tabs
        general_tab = QWidget()
        general_layout = QVBoxLayout(general_tab)
        logo_group = QGroupBox(self.main_app.lang.get("company_logo", "Company Logo"))
        logo_layout = QHBoxLayout(logo_group)
        self.main_app.logo_preview_label = QLabel()
        self.main_app.logo_preview_label.setFixedSize(100, 100)
        self.main_app.logo_preview_label.setScaledContents(True)
        self.main_app.logo_preview_label.setStyleSheet("border: 1px solid gray; background-color: #eee;")
        current_logo_path = RESOURCES_DIR / "golder.png"
        if current_logo_path.exists():
            self.main_app.logo_preview_label.setPixmap(QPixmap(str(current_logo_path)))
        else:
            self.main_app.logo_preview_label.setText("Logo Yok")
            self.main_app.logo_preview_label.setAlignment(Qt.AlignmentFlag.AlignCenter)
        btn_layout_logo = QVBoxLayout()
        select_logo_btn = QPushButton(self.main_app.lang.get("select_logo", "Select Logo"))
        select_logo_btn.setIcon(self.main_app._get_icon("SP_FileDialogListView"))
        select_logo_btn.clicked.connect(self.main_app.admin_manager._select_and_update_logo)
        restore_logo_btn = QPushButton(self.main_app.lang.get("restore_default_logo", "Restore Default / Backup"))
        restore_logo_btn.setIcon(self.main_app._get_icon("SP_BrowserReload"))
        restore_logo_btn.clicked.connect(self.main_app.admin_manager._restore_backup_logo)
        btn_layout_logo.addWidget(select_logo_btn)
        btn_layout_logo.addWidget(restore_logo_btn)
        btn_layout_logo.addStretch()
        logo_layout.addWidget(self.main_app.logo_preview_label)
        logo_layout.addLayout(btn_layout_logo)
        logo_layout.addStretch()
        general_layout.addWidget(logo_group)
        # --- Genel Ayarlar: Belge gibi genel konfigürasyonlar ---
        document_group = QGroupBox(self.main_app.lang.get("document_settings", "Document Settings"))
        document_layout = QFormLayout(document_group)
        curr_document_prefix = self.main_app.settings_manager.get_setting("document_prefix", "DOC")
        self.main_app.document_prefix_edit = QLineEdit(curr_document_prefix)
        self.main_app.document_prefix_edit.setPlaceholderText("Örn: INV")
        document_layout.addRow(self.main_app.lang.get("document_prefix", "Document Prefix:"), self.main_app.document_prefix_edit)
        general_layout.addWidget(document_group)

        # --- Dükkan Bilgileri: Şirket/Dükkan alanları ayrı sekmeye taşındı ---
        shop_info_tab = QWidget()
        shop_info_layout = QVBoxLayout(shop_info_tab)
        shop_group = QGroupBox(self.main_app.lang.get("shop_info_title", "Shop Information (For Receipt and Tag)"))
        shop_layout = QFormLayout(shop_group)
        curr_shop_name = self.main_app.settings_manager.get_setting("shop_name", "GOLDER KUYUMCU MUHASEBE PROGRAMI")
        curr_shop_phone = self.main_app.settings_manager.get_setting("shop_phone", "")
        self.main_app.shop_name_edit = QLineEdit(curr_shop_name)
        self.main_app.shop_name_edit.setPlaceholderText(self.main_app.lang.get("ph_shop_name", "e.g., GOLDER JEWELER"))
        self.main_app.shop_phone_edit = QLineEdit(curr_shop_phone)
        self.main_app.shop_phone_edit.setPlaceholderText(self.main_app.lang.get("ph_phone", "e.g., +1 234..."))
        shop_layout.addRow(self.main_app.lang.get("shop_name_label", "Shop Name:"), self.main_app.shop_name_edit)
        shop_layout.addRow(self.main_app.lang.get("phone_no_label", "Phone No:"), self.main_app.shop_phone_edit)
        shop_info_layout.addWidget(shop_group)

        company_group = QGroupBox(self.main_app.lang.get("company_invoice_info", "Company / Invoice Information"))
        company_layout = QFormLayout(company_group)
        curr_company_name = self.main_app.settings_manager.get_setting("company_name", "") or curr_shop_name
        curr_company_address = self.main_app.settings_manager.get_setting("company_address", "")
        curr_tax_office = self.main_app.settings_manager.get_setting("tax_office", "")
        curr_tax_number = self.main_app.settings_manager.get_setting("tax_number", "")
        curr_company_phone = self.main_app.settings_manager.get_setting("company_phone", "") or curr_shop_phone
        curr_company_email = self.main_app.settings_manager.get_setting("company_email", "")
        self.main_app.company_name_edit = QLineEdit(curr_company_name)
        self.main_app.company_name_edit.setPlaceholderText(self.main_app.lang.get("ph_company_title", "e.g., GOLDER JEWELRY"))
        self.main_app.company_address_edit = QTextEdit()
        self.main_app.company_address_edit.setPlaceholderText(self.main_app.lang.get("ph_address", "Address"))
        self.main_app.company_address_edit.setFixedHeight(60)
        self.main_app.company_address_edit.setPlainText(curr_company_address or "")
        self.main_app.tax_office_edit = QLineEdit(curr_tax_office)
        self.main_app.tax_office_edit.setPlaceholderText(self.main_app.lang.get("ph_tax_office", "e.g., Central"))
        self.main_app.tax_number_edit = QLineEdit(curr_tax_number)
        self.main_app.tax_number_edit.setPlaceholderText(self.main_app.lang.get("ph_tax_number", "Tax Number"))
        self.main_app.company_phone_edit = QLineEdit(curr_company_phone)
        self.main_app.company_phone_edit.setPlaceholderText(self.main_app.lang.get("ph_phone_simple", "Phone"))
        self.main_app.company_email_edit = QLineEdit(curr_company_email)
        self.main_app.company_email_edit.setPlaceholderText(self.main_app.lang.get("ph_email", "E-mail"))
        company_layout.addRow(self.main_app.lang.get("company_title_label", "Company Title*:"), self.main_app.company_name_edit)
        company_layout.addRow(self.main_app.lang.get("company_address_label", "Company Address:"), self.main_app.company_address_edit)
        company_layout.addRow(self.main_app.lang.get("tax_office_label", "Tax Office*:"), self.main_app.tax_office_edit)
        company_layout.addRow(self.main_app.lang.get("tax_number_label", "Tax No*:"), self.main_app.tax_number_edit)
        company_layout.addRow(self.main_app.lang.get("company_phone_label", "Company Phone:"), self.main_app.company_phone_edit)
        company_layout.addRow(self.main_app.lang.get("company_email_label", "Company E-mail:"), self.main_app.company_email_edit)
        shop_info_layout.addWidget(company_group)
        shop_info_layout.addStretch()
        appearance_group = QGroupBox(self.main_app.lang.get("appearance_and_language", "Appearance and Language"))
        appearance_layout = QFormLayout(appearance_group)
        theme_layout = QHBoxLayout()
        self.main_app.theme_combo = QComboBox()
        self.main_app.theme_combo.currentTextChanged.connect(self.main_app._update_theme_buttons_state)
        self.main_app.theme_combo.activated.connect(self.main_app._on_theme_selected)
        self.main_app.edit_theme_btn = QPushButton(self.main_app._get_icon("SP_DialogResetButton"), self.main_app.lang["edit_theme"])
        self.main_app.edit_theme_btn.clicked.connect(self.main_app._edit_selected_theme)
        self.main_app.delete_theme_btn = QPushButton(self.main_app._get_icon("SP_TrashIcon"), self.main_app.lang["delete_theme"])
        self.main_app.delete_theme_btn.setObjectName("dangerButton")
        self.main_app.delete_theme_btn.clicked.connect(self.main_app._delete_selected_theme)
        theme_layout.addWidget(self.main_app.theme_combo, 1)
        theme_layout.addWidget(self.main_app.edit_theme_btn)
        theme_layout.addWidget(self.main_app.delete_theme_btn)
        appearance_layout.addRow(QLabel(f'{self.main_app.lang["theme"]}:'), theme_layout)
        self.main_app._populate_theme_combo()
        self.main_app.language_combo = QComboBox()
        available_langs = get_available_languages()
        self.main_app.language_combo.addItems(available_langs)
        if self.main_app.current_lang_code in available_langs:
            self.main_app.language_combo.setCurrentText(self.main_app.current_lang_code)
        appearance_layout.addRow(QLabel(f'{self.main_app.lang.get("language", "Dil")}:'), self.main_app.language_combo)
        self.main_app.display_currency_combo = QComboBox()
        self.main_app.display_currency_combo.addItems(SUPPORTED_CURRENCIES)
        self.main_app.display_currency_combo.setCurrentText(self.main_app.display_currency)
        appearance_layout.addRow(QLabel(f'{self.main_app.lang["display_currency"]}:'), self.main_app.display_currency_combo)
        self.main_app.tab_position_combo = QComboBox()
        self.main_app.tab_position_combo.addItem(self.main_app.lang.get("tab_top", "Top"), "Üst")
        self.main_app.tab_position_combo.addItem(self.main_app.lang.get("tab_left", "Left"), "Sol")
        self.main_app.tab_position_combo.addItem(self.main_app.lang.get("tab_right", "Right"), "Sağ")
        self.main_app.tab_position_combo.addItem(self.main_app.lang.get("tab_bottom", "Bottom"), "Alt")
        
        current_tab_position = self.main_app.settings_manager.get_setting("tab_position", "Üst")
        index = self.main_app.tab_position_combo.findData(current_tab_position)
        if index >= 0:
            self.main_app.tab_position_combo.setCurrentIndex(index)
        appearance_layout.addRow(QLabel(self.main_app.lang.get("tab_position", "Tab Position:")), self.main_app.tab_position_combo)
        general_layout.addWidget(appearance_group)
        general_layout.addStretch()
        security_tab = QWidget()
        security_layout = QVBoxLayout(security_tab)
        self.main_app.security_settings_tab = security_tab
        profile_group = QGroupBox(self.main_app.lang.get("profile_management", "Profile Management"))
        profile_layout = QFormLayout(profile_group)
        profile_name_layout = QHBoxLayout()
        self.main_app.profile_name_display = QLineEdit(self.main_app.profile_name)
        self.main_app.profile_name_display.setReadOnly(True)
        change_profile_name_btn = QPushButton(self.main_app._get_icon("SP_FileIcon"), self.main_app.lang.get("change_profile_name", "Change Profile Name"))
        change_profile_name_btn.clicked.connect(self.main_app._change_profile_name)
        profile_name_layout.addWidget(self.main_app.profile_name_display)
        profile_name_layout.addWidget(change_profile_name_btn)
        profile_layout.addRow(self.main_app.lang.get("active_profile", "Active Profile:"), profile_name_layout)
        export_profile_btn = QPushButton(self.main_app._get_icon("SP_DialogSaveButton"), self.main_app.lang.get("export_profile", "Export Profile"))
        export_profile_btn.setToolTip("Mevcut profil dosyasını (.golder) bir klasöre yedekler/kopyalar.")
        export_profile_btn.clicked.connect(self.main_app.admin_manager._export_current_profile)
        profile_layout.addRow(export_profile_btn)
        security_layout.addWidget(profile_group)
        security_layout.addWidget(profile_group)
        password_group = QGroupBox(self.main_app.lang["password_settings"])
        password_layout = QFormLayout(password_group)
        self.main_app.password_edit = QLineEdit()
        self.main_app.password_edit.setEchoMode(QLineEdit.EchoMode.Password)
        self.main_app.password_edit.setPlaceholderText("Şifre belirlemek için yazın (Kaldırmak için silin)")
        if self.main_app.settings_manager.get_setting("password_enabled", False):
            self.main_app.password_edit.setText("******")
        password_layout.addRow(self.main_app.lang.get("profile_password", "Profile Password:"), self.main_app.password_edit)
        security_layout.addWidget(password_group)
        security_layout.addStretch()
        staff_tab = QWidget()
        staff_layout = QVBoxLayout(staff_tab)
        self.main_app.staff_settings_tab = staff_tab
        if self.main_app.current_user["role"] == "admin":
            emp_group = QGroupBox(self.main_app.lang.get("staff_management", "Staff Management (Personnel)"))
            emp_layout = QVBoxLayout(emp_group)
            self.main_app.staff_group = emp_group
            self.main_app.emp_list = QListWidget()
            self.main_app._refresh_employee_list()
            emp_layout.addWidget(self.main_app.emp_list)
            emp_btn_layout = QHBoxLayout()
            add_emp_btn = QPushButton(self.main_app.lang.get("add_staff", "Add Staff"))
            add_emp_btn.setIcon(self.main_app._get_icon("SP_FileDialogNewFolder"))
            add_emp_btn.setAttribute(Qt.WidgetAttribute.WA_AlwaysShowToolTips, True)
            add_emp_btn.clicked.connect(self.main_app.admin_manager._add_employee)
            edit_emp_btn = QPushButton(self.main_app.lang.get("edit", "Edit"))
            edit_emp_btn.setIcon(self.main_app._get_icon("SP_FileDialogDetailedView"))
            edit_emp_btn.setAttribute(Qt.WidgetAttribute.WA_AlwaysShowToolTips, True)
            edit_emp_btn.clicked.connect(self.main_app.admin_manager._edit_employee)
            del_emp_btn = QPushButton(self.main_app.lang.get("delete", "Delete"))
            del_emp_btn.setIcon(self.main_app._get_icon("SP_TrashIcon"))
            del_emp_btn.setAttribute(Qt.WidgetAttribute.WA_AlwaysShowToolTips, True)
            del_emp_btn.setObjectName("dangerButton")
            del_emp_btn.clicked.connect(self.main_app.admin_manager._delete_employee)
            self.main_app.add_staff_btn = add_emp_btn
            self.main_app.edit_staff_btn = edit_emp_btn
            self.main_app.del_staff_btn = del_emp_btn
            self.main_app.staff_list = self.main_app.emp_list
            emp_btn_layout.addWidget(add_emp_btn)
            emp_btn_layout.addWidget(edit_emp_btn)
            emp_btn_layout.addWidget(del_emp_btn)
            emp_layout.addLayout(emp_btn_layout)
            staff_layout.addWidget(emp_group)
        else:
            lbl_no_access = QLabel(self.main_app.lang.get("admin_only_access", "Only administrators (Admin) can access this area."))
            lbl_no_access.setAlignment(Qt.AlignmentFlag.AlignCenter)
            staff_layout.addWidget(lbl_no_access)
        staff_layout.addStretch()
        user_tab = QWidget()
        user_layout = QVBoxLayout(user_tab)
        self.main_app.user_settings_tab = user_tab
        user_info_group = QGroupBox(self.main_app.lang.get("active_session", "Active Session"))
        user_info_layout = QFormLayout(user_info_group)
        tenant = TenantManager()
        license_data = tenant.load_license()
        offline_mode = tenant.is_offline_mode_enabled()
        active_username = str(license_data.get("customer_username") or self.main_app.current_user.get("username") or "-")
        active_email = str(license_data.get("customer_email") or "-")
        active_phone = str(license_data.get("customer_phone") or "-")
        active_plan = str(license_data.get("plan_type") or "-")
        if offline_mode:
            active_plan = f"{active_plan} (Offline)" if active_plan != "-" else "Offline"
        active_expiry = tenant.get_license_expiry_display()
        sync_expiry = tenant.get_sync_expiry_display()
        sync_status = tenant.get_sync_status()
        self.main_app.current_username_display = QLineEdit(active_username)
        self.main_app.current_username_display.setReadOnly(True)
        self.main_app.current_email_display = QLineEdit(active_email)
        self.main_app.current_email_display.setReadOnly(True)
        self.main_app.current_phone_display = QLineEdit(active_phone)
        self.main_app.current_phone_display.setReadOnly(True)
        self.main_app.current_plan_display = QLineEdit(active_plan)
        self.main_app.current_plan_display.setReadOnly(True)
        self.main_app.current_expiry_display = QLineEdit(active_expiry)
        self.main_app.current_expiry_display.setReadOnly(True)
        self.main_app.current_sync_expiry_display = QLineEdit(sync_expiry)
        self.main_app.current_sync_expiry_display.setReadOnly(True)
        self.main_app.current_sync_status_display = QLineEdit(sync_status)
        self.main_app.current_sync_status_display.setReadOnly(True)
        user_info_layout.addRow(self.main_app.lang.get("username_label", "Username:"), self.main_app.current_username_display)
        user_info_layout.addRow(self.main_app.lang.get("email_label", "E-Mail:"), self.main_app.current_email_display)
        user_info_layout.addRow(self.main_app.lang.get("phone_no_short", "Phone No:"), self.main_app.current_phone_display)
        user_info_layout.addRow(self.main_app.lang.get("plan_label", "Plan:"), self.main_app.current_plan_display)
        user_info_layout.addRow(self.main_app.lang.get("license_expiry", "License Expiry Date:"), self.main_app.current_expiry_display)
        user_info_layout.addRow("Sync Expiry:", self.main_app.current_sync_expiry_display)
        user_info_layout.addRow("Sync Status:", self.main_app.current_sync_status_display)
        user_layout.addWidget(user_info_group)
        session_group = QGroupBox(self.main_app.lang.get("session_operations", "Session Operations"))
        session_layout = QVBoxLayout(session_group)
        logout_btn = QPushButton(self.main_app._get_icon("SP_DialogCloseButton"), self.main_app.lang.get("log_out", "Log Out"))
        logout_btn.setObjectName("dangerButton")
        logout_btn.setToolTip("Mevcut kullanıcı oturumunu kapatır ve giriş ekranına döner.")
        logout_btn.clicked.connect(self.main_app._logout_current_user)
        self.main_app.logout_user_btn = logout_btn
        session_layout.addWidget(logout_btn, alignment=Qt.AlignmentFlag.AlignLeft)
        user_layout.addWidget(session_group)
        user_layout.addStretch()

        plan_type = str(license_data.get("plan_type") or "A-SOLO").strip()
        try:
            max_pc_devices = int(license_data.get("max_pc_devices") or license_data.get("max_devices") or 1)
        except Exception:
            max_pc_devices = 1
        try:
            max_web_sessions = 0 if offline_mode else int(license_data.get("max_web_sessions") or 0)
        except Exception:
            max_web_sessions = 0

        device_tab = QWidget()
        device_layout = QVBoxLayout(device_tab)
        device_group = QGroupBox(self.main_app.lang.get("device_management", "Device Management"))
        device_group_layout = QFormLayout(device_group)
        self.main_app.device_plan_display = QLineEdit(plan_type or "-")
        self.main_app.device_plan_display.setReadOnly(True)
        self.main_app.device_pc_limit_display = QLineEdit(str(max_pc_devices))
        self.main_app.device_pc_limit_display.setReadOnly(True)
        self.main_app.device_web_limit_display = QLineEdit(str(max_web_sessions))
        self.main_app.device_web_limit_display.setReadOnly(True)
        device_group_layout.addRow(self.main_app.lang.get("plan_label", "Plan:"), self.main_app.device_plan_display)
        device_group_layout.addRow(self.main_app.lang.get("max_pc", "Max. Computer:"), self.main_app.device_pc_limit_display)
        device_group_layout.addRow(self.main_app.lang.get("max_web_session", "Max. Web Session:"), self.main_app.device_web_limit_display)
        device_layout.addWidget(device_group)

        # --- Barkod ve Yazıcı Ayarları ---
        barcode_group = QGroupBox(self.main_app.lang.get("barcode_and_printer", "Barcode & Printer"))
        barcode_layout = QFormLayout(barcode_group)

        self.main_app.use_barcode_checkbox = QCheckBox(self.main_app.lang.get("i_use_barcode_system", "I use a barcode system"))
        use_barcode_current = self.main_app.settings_manager.get_setting("use_barcode_system", True)
        self.main_app.use_barcode_checkbox.setChecked(bool(use_barcode_current))
        barcode_layout.addRow("Barkod Kullanımı:", self.main_app.use_barcode_checkbox)

        self.main_app.printer_type_combo = QComboBox()
        self.main_app.printer_type_combo.addItems(["ZPL", "TSPL"])
        current_printer_type = self.main_app.settings_manager.get_setting("printer_type", "ZPL")
        if current_printer_type in ("ZPL", "TSPL"):
            self.main_app.printer_type_combo.setCurrentText(current_printer_type)
        barcode_layout.addRow(self.main_app.lang.get("thermal_printer_lang", "Thermal Printer Lang:"), self.main_app.printer_type_combo)

        self.main_app.printer_name_entry = QLineEdit()
        self.main_app.printer_name_entry.setPlaceholderText("Yazıcı Adı veya IP (örn: Zebra 2844 / 192.168.1.50)")
        self.main_app.printer_name_entry.setText(
            str(self.main_app.settings_manager.get_setting("printer_name", "") or "")
        )
        printer_row = QHBoxLayout()
        printer_row.addWidget(self.main_app.printer_name_entry, 1)

        self.main_app.printer_scan_btn = QPushButton("Agi Tara")
        self.main_app.printer_scan_btn.setToolTip("Yerel agda 9100 portu acik termal yazicilari bulur.")
        self.main_app.printer_scan_btn.clicked.connect(self.main_app._open_thermal_printer_discovery_dialog)
        printer_row.addWidget(self.main_app.printer_scan_btn)

        barcode_layout.addRow(self.main_app.lang.get("printer_name_ip", "Printer Name / IP:"), printer_row)

        device_layout.addWidget(barcode_group)
        
        # --- YENİ EKLENEN CİHAZ BAĞLAMA BUTONU ---
        pair_btn = QPushButton(self.main_app.lang.get("pair_new_web_device", "📷 Pair New Web Device (QR Code)"))
        pair_btn.setObjectName("primaryButton")
        pair_btn.setMinimumHeight(50)
        pair_btn.setStyleSheet("font-size: 15px; font-weight: bold; margin-top: 10px;")
        pair_btn.clicked.connect(self.main_app._open_device_pairing_dialog)
        self.main_app.pair_new_device_btn = pair_btn
        if not tenant.is_web_mobile_enabled():
            pair_btn.setEnabled(False)
            pair_btn.setToolTip(
                "Senkronizasyon süresi doldu." if tenant.get_sync_status() == "expired" else "Bu lisans planinda telefon ve web erisimi kapali."
            )
        device_layout.addWidget(pair_btn)
        # ---------------------------------------

        list_group = QGroupBox(self.main_app.lang.get("active_devices", "Active Devices"))
        list_layout = QVBoxLayout(list_group)
        self.main_app.device_list_widget = QListWidget()
        self.main_app.device_list_widget.setMinimumHeight(170)
        list_layout.addWidget(self.main_app.device_list_widget)

        list_btn_row = QHBoxLayout()
        self.main_app.device_refresh_btn = QPushButton(self.main_app.lang.get("refresh_list", "Refresh List"))
        self.main_app.device_delete_btn = QPushButton(self.main_app.lang.get("delete_selected_device", "Delete Selected Device"))
        self.main_app.device_delete_btn.setObjectName("dangerButton")
        self.main_app.device_delete_btn.setEnabled(False)
        list_btn_row.addWidget(self.main_app.device_refresh_btn)
        list_btn_row.addStretch()
        list_btn_row.addWidget(self.main_app.device_delete_btn)
        list_layout.addLayout(list_btn_row)
        device_layout.addWidget(list_group)

        self.main_app.device_refresh_btn.clicked.connect(self.main_app._refresh_device_management_view)
        self.main_app.device_delete_btn.clicked.connect(self.main_app._delete_selected_linked_device)
        self.main_app.device_list_widget.currentRowChanged.connect(self.main_app._on_device_list_selection_changed)
        QTimer.singleShot(50, self.main_app._refresh_device_management_view)

        device_layout.addWidget(QLabel(self.main_app.lang.get("device_list_info", "Active web, computer, and phone devices are listed here. You can select and delete them.")))
        device_layout.addStretch()

        backup_tab = QWidget()
        backup_layout = QVBoxLayout(backup_tab)

        if tenant.can_use_backup_features():
            backup_group = QGroupBox(self.main_app.lang.get("manual_backup", "Take Manual Backup & Download"))
            backup_group_layout = QVBoxLayout(backup_group)
            backup_group_layout.addWidget(
                QLabel(self.main_app.lang.get("backup_info_text", "Aktif lisansinizda otomatik ve manuel yedekleme kullanilabilir.\nDilediginiz profilleri secip verilerinizi (.golder) formatinda indirebilirsiniz."))
            )
            from core.backup_service import (
                manual_backup_daily_count,
                manual_restore_daily_count,
                MANUAL_BACKUP_DAILY_LIMIT,
                MANUAL_RESTORE_DAILY_LIMIT,
            )
            from PyQt6.QtWidgets import QProgressBar

            backup_used = manual_backup_daily_count()
            restore_used = manual_restore_daily_count()

            def _make_quota_widget(label_text: str, used: int, limit: int) -> QWidget:
                widget = QWidget()
                layout = QVBoxLayout(widget)
                layout.setContentsMargins(0, 4, 0, 4)
                layout.setSpacing(4)
                top = QHBoxLayout()
                top.addWidget(QLabel(label_text))
                top.addStretch()
                top.addWidget(QLabel(self.main_app.lang.get("quota_used", "{used} / {limit} used").format(used=used, limit=limit)))
                layout.addLayout(top)
                bar = QProgressBar()
                bar.setRange(0, limit)
                bar.setValue(min(used, limit))
                bar.setTextVisible(False)
                bar.setFixedHeight(8)
                pct = (used / limit) if limit else 0
                if pct >= 1.0:
                    color = "#e53935"
                elif pct >= 0.66:
                    color = "#fb8c00"
                else:
                    color = "#43a047"
                bar.setStyleSheet(
                    "QProgressBar { background:#ddd; border-radius:4px; }"
                    f"QProgressBar::chunk {{ background:{color}; border-radius:4px; }}"
                )
                layout.addWidget(bar)
                return widget

            backup_group_layout.addWidget(
                _make_quota_widget(self.main_app.lang.get("backup_quota", "Backup Quota"), backup_used, MANUAL_BACKUP_DAILY_LIMIT)
            )
            backup_group_layout.addWidget(
                _make_quota_widget(self.main_app.lang.get("restore_quota", "Restore Quota"), restore_used, MANUAL_RESTORE_DAILY_LIMIT)
            )
            backup_btn_row = QHBoxLayout()
            manual_backup_btn = QPushButton(
                self.main_app._get_icon("SP_DialogSaveButton"), self.main_app.lang.get("manual_backup", "Take Manual Backup & Download")
            )
            manual_backup_btn.clicked.connect(self.main_app.admin_manager._backup_manual_download)
            manual_backup_btn.setEnabled(backup_used < MANUAL_BACKUP_DAILY_LIMIT)
            if backup_used >= MANUAL_BACKUP_DAILY_LIMIT:
                manual_backup_btn.setToolTip(
                    f"Günlük limit doldu ({MANUAL_BACKUP_DAILY_LIMIT}/gün). Gece yarısı sıfırlanır."
                )
            backup_btn_row.addWidget(manual_backup_btn)
            backup_btn_row.addStretch()
            backup_group_layout.addLayout(backup_btn_row)
            backup_layout.addWidget(backup_group)

            restore_group = QGroupBox(self.main_app.lang.get("restore_from_file", "Restore from File"))
            restore_group_layout = QVBoxLayout(restore_group)
            restore_group_layout.addWidget(
                QLabel(self.main_app.lang.get("restore_info_text", "You can restore your data by selecting a previously downloaded .golder file."))
            )
            restore_btn_row = QHBoxLayout()
            restore_backup_btn = QPushButton(
                self.main_app._get_icon("SP_DialogOpenButton"), self.main_app.lang.get("select_file_restore", "Select File & Restore")
            )
            restore_backup_btn.clicked.connect(self.main_app.admin_manager._restore_backup_from_file)
            restore_backup_btn.setEnabled(restore_used < MANUAL_RESTORE_DAILY_LIMIT)
            if restore_used >= MANUAL_RESTORE_DAILY_LIMIT:
                restore_backup_btn.setToolTip(
                    f"Günlük limit doldu ({MANUAL_RESTORE_DAILY_LIMIT}/gün). Gece yarısı sıfırlanır."
                )
            restore_btn_row.addWidget(restore_backup_btn)
            restore_btn_row.addStretch()
            restore_group_layout.addLayout(restore_btn_row)
            backup_layout.addWidget(restore_group)

            history_group = QGroupBox(self.main_app.lang.get("my_old_backups", "My Old Backups"))
            history_layout = QVBoxLayout(history_group)

            from PyQt6.QtWidgets import QTableWidget, QTableWidgetItem, QHeaderView, QAbstractItemView
            from PyQt6.QtCore import Qt as _Qt

            backup_table = QTableWidget()
            backup_table.setColumnCount(6)
            backup_table.setHorizontalHeaderLabels([
                self.main_app.lang.get("file_name", "File Name"),
                self.main_app.lang.get("profiles", "Profiles"),
                self.main_app.lang.get("type", "Type"),
                self.main_app.lang.get("size_kb", "Size (KB)"),
                self.main_app.lang.get("created_at", "Created At"),
                self.main_app.lang.get("action", "Action")
            ])
            backup_table.setEditTriggers(QAbstractItemView.EditTrigger.NoEditTriggers)
            backup_table.setSelectionBehavior(QAbstractItemView.SelectionBehavior.SelectRows)
            backup_table.setAlternatingRowColors(True)
            backup_table.verticalHeader().setVisible(False)
            backup_table.horizontalHeader().setStretchLastSection(False)
            backup_table.horizontalHeader().setSectionResizeMode(0, QHeaderView.ResizeMode.Stretch)
            backup_table.horizontalHeader().setSectionResizeMode(1, QHeaderView.ResizeMode.ResizeToContents)
            backup_table.horizontalHeader().setSectionResizeMode(2, QHeaderView.ResizeMode.ResizeToContents)
            backup_table.horizontalHeader().setSectionResizeMode(3, QHeaderView.ResizeMode.ResizeToContents)
            backup_table.horizontalHeader().setSectionResizeMode(4, QHeaderView.ResizeMode.ResizeToContents)
            backup_table.horizontalHeader().setSectionResizeMode(5, QHeaderView.ResizeMode.ResizeToContents)

            try:
                from core.backup_service import list_all_backups

                backup_rows = list_all_backups(limit=30)
            except Exception:
                backup_rows = []

            backup_table.setRowCount(len(backup_rows))

            for row_idx, bk in enumerate(backup_rows):
                backup_table.setItem(row_idx, 0, QTableWidgetItem(str(bk.get("file_name", "-"))))
                backup_table.setItem(
                    row_idx,
                    1,
                    QTableWidgetItem(
                        f"{bk.get('profile_names', '-')} ({bk.get('profile_count', 1)} profil)"
                    ),
                )
                backup_table.setItem(row_idx, 2, QTableWidgetItem(str(bk.get("backup_type", "-"))))
                backup_table.setItem(row_idx, 3, QTableWidgetItem(str(bk.get("file_size_kb", 0))))
                backup_table.setItem(row_idx, 4, QTableWidgetItem(str(bk.get("created_at", "-"))))

                btn_widget = QWidget()
                btn_layout = QHBoxLayout(btn_widget)
                btn_layout.setContentsMargins(4, 2, 4, 2)
                btn_layout.setSpacing(6)

                file_path = str(bk.get("file_path", ""))

                indir_btn = QPushButton(self.main_app._get_icon("SP_DialogSaveButton"), self.main_app.lang.get("download", "Download"))

                def _make_download(fp):
                    def _download():
                        from PyQt6.QtWidgets import QFileDialog
                        import shutil
                        from pathlib import Path as _P

                        dest, _ = QFileDialog.getSaveFileName(
                            self.main_app,
                            "Yedeği Kaydet",
                            str(_P.home() / _P(fp).name),
                            "Golder Yedek (*.golder)",
                        )
                        if dest:
                            try:
                                shutil.copy2(fp, dest)
                                QMessageBox.information(
                                    self.main_app, "Başarılı", f"Yedek kopyalandı:\n{dest}"
                                )
                            except Exception as exc:
                                QMessageBox.critical(
                                    self.main_app, "Hata", f"Dosya kopyalanamadı: {exc}"
                                )

                    return _download

                indir_btn.clicked.connect(_make_download(file_path))
                btn_layout.addWidget(indir_btn)

                geri_btn = QPushButton(self.main_app._get_icon("SP_DialogOpenButton"), self.main_app.lang.get("restore", "Restore"))
                if restore_used >= MANUAL_RESTORE_DAILY_LIMIT:
                    geri_btn.setEnabled(False)
                    geri_btn.setToolTip(
                        f"Günlük limit doldu ({MANUAL_RESTORE_DAILY_LIMIT}/gün). Gece yarısı sıfırlanır."
                    )

                def _make_restore(fp):
                    def _restore():
                        reply = QMessageBox.question(
                            self.main_app,
                            "Onay",
                            "Seçili yedek yeni profil(ler) olarak geri yüklensin mi?\nMevcut profiller etkilenmez.",
                            QMessageBox.StandardButton.Yes | QMessageBox.StandardButton.No,
                        )
                        if reply != QMessageBox.StandardButton.Yes:
                            return
                        try:
                            from core.backup_service import restore_backup_bundle

                            result = restore_backup_bundle(self.main_app.admin_manager.db, fp)
                        except Exception as exc:
                            QMessageBox.critical(self.main_app, "Hata", f"Yedek geri yüklenemedi: {exc}")
                            return
                        restored = result.get("restored_profiles") or []
                        names = [
                            str(p.get("profile_name") or p.get("profile_id") or "").strip()
                            for p in restored
                            if isinstance(p, dict)
                        ]
                        names = [n for n in names if n]
                        msg = "Yedek geri yükleme tamamlandı."
                        if names:
                            msg += "\n\nEklenen Profiller:\n" + "\n".join(names)
                        msg += "\n\nYeni profiller için uygulamayı yeniden başlatmanız gerekebilir."
                        QMessageBox.information(self.main_app, "Başarılı", msg)

                    return _restore

                geri_btn.clicked.connect(_make_restore(file_path))
                btn_layout.addWidget(geri_btn)

                backup_table.setCellWidget(row_idx, 5, btn_widget)

            if not backup_rows:
                backup_table.setRowCount(1)
                empty_item = QTableWidgetItem(self.main_app.lang.get("no_backups_found", "No backups found yet."))
                empty_item.setTextAlignment(_Qt.AlignmentFlag.AlignCenter)
                backup_table.setItem(0, 0, empty_item)
                backup_table.setSpan(0, 0, 1, 6)

            history_layout.addWidget(backup_table)
            backup_layout.addWidget(history_group)

        else:
            no_plan_group = QGroupBox(self.main_app.lang.get("backup", "Backup"))
            no_plan_layout = QVBoxLayout(no_plan_group)
            no_plan_layout.addWidget(QLabel(self.main_app.lang.get("backup_disabled_plan", "Backup feature is disabled for this license plan.")))
            backup_layout.addWidget(no_plan_group)

        backup_layout.addStretch()

        about_tab = QWidget()
        about_layout = QVBoxLayout(about_tab)
        about_group = QGroupBox(self.main_app.lang.get("about", "About"))
        about_group_layout = QVBoxLayout(about_group)
        ver_lbl = QLabel(f"{self.main_app.lang['app_title']}")
        ver_lbl.setStyleSheet("font-weight: bold; font-size: 12px;")
        about_group_layout.addWidget(ver_lbl)
        copy_lbl = QLabel(self.main_app.lang.get("copyright_text", "© 2026 Golder Kuyumcu Yazılım Sistemleri. All Rights Reserved."))
        about_group_layout.addWidget(copy_lbl)
        about_layout.addWidget(about_group)
        about_layout.addStretch()
        settings_tabs.addTab(general_tab, self.main_app._get_icon("SP_ComputerIcon"), self.main_app.lang.get("general_settings", "General Settings"))
        if self.main_app.current_user["role"] == "admin":
            taxes_tab = self.create_taxes_tab()
            settings_tabs.addTab(taxes_tab, self.main_app._get_icon("SP_DialogApplyButton"), self.main_app.lang.get("taxes", "Taxes"))
        settings_tabs.addTab(security_tab, self.main_app._get_icon("SP_DriveHDIcon"), self.main_app.lang.get("security", "Security"))
        settings_tabs.addTab(user_tab, self.main_app._get_icon("SP_FileIcon"), self.main_app.lang.get("user", "User"))
        settings_tabs.addTab(device_tab, self.main_app._get_icon("SP_ComputerIcon"), self.main_app.lang.get("device_management", "Device Management"))
        if tenant.can_use_backup_features():
            settings_tabs.addTab(backup_tab, self.main_app._get_icon("SP_DriveHDIcon"), self.main_app.lang.get("backup", "Backup"))
        if self.main_app.current_user["role"] == "admin":
            transfer_tab = self.create_data_transfer_tab() 
            settings_tabs.addTab(transfer_tab, self.main_app._get_icon("SP_DirLinkIcon"), self.main_app.lang.get("data_transfer", "Data Transfer"))
        if self.main_app.current_user["role"] == "admin":
            settings_tabs.addTab(staff_tab, self.main_app._get_icon("SP_DirHomeIcon"), self.main_app.lang.get("personnel", "Personnel"))
        settings_tabs.addTab(shop_info_tab, self.main_app._get_icon("SP_DirOpenIcon"), self.main_app.lang.get("shop_information", "Shop Information"))
        settings_tabs.addTab(about_tab, self.main_app._get_icon("SP_MessageBoxInformation"), self.main_app.lang.get("about", "About"))
        main_layout.addWidget(settings_tabs)
        if hasattr(self.main_app, "_on_settings_tabs_changed"):
            settings_tabs.currentChanged.connect(self.main_app._on_settings_tabs_changed)
        if hasattr(self.main_app, "_apply_staff_creation_guard"):
            self.main_app._apply_staff_creation_guard(show_dialog=False)
        save_btn = QPushButton(self.main_app._get_icon("SP_DialogSaveButton"), self.main_app.lang["save_settings"])
        save_btn.setObjectName("primaryButton")
        save_btn.setAutoDefault(True)
        save_btn.clicked.connect(self.main_app.admin_manager._save_and_apply_settings)
        main_layout.addWidget(save_btn)
        self.main_app.setTabOrder(self.main_app.shop_name_edit, self.main_app.shop_phone_edit)
        self.main_app.setTabOrder(self.main_app.shop_phone_edit, self.main_app.company_name_edit)
        self.main_app.setTabOrder(self.main_app.company_name_edit, self.main_app.company_address_edit)
        self.main_app.setTabOrder(self.main_app.company_address_edit, self.main_app.tax_office_edit)
        self.main_app.setTabOrder(self.main_app.tax_office_edit, self.main_app.tax_number_edit)
        self.main_app.setTabOrder(self.main_app.tax_number_edit, self.main_app.company_phone_edit)
        self.main_app.setTabOrder(self.main_app.company_phone_edit, self.main_app.company_email_edit)
        self.main_app.setTabOrder(self.main_app.company_email_edit, self.main_app.document_prefix_edit)
        self.main_app.setTabOrder(self.main_app.document_prefix_edit, self.main_app.theme_combo)
        self.main_app.setTabOrder(self.main_app.theme_combo, self.main_app.language_combo)
        self.main_app.setTabOrder(self.main_app.language_combo, self.main_app.display_currency_combo)
        self.main_app.setTabOrder(self.main_app.display_currency_combo, self.main_app.password_edit)
        self.main_app.setTabOrder(self.main_app.password_edit, save_btn)
        return main_widget

    def create_taxes_tab(self) -> QWidget:
        """
        Ayarlar -> Vergiler sekmesini oluşturur.
        YENİ SİSTEM: Profil yönetimi kaldırıldı. Sadece Vergi Tanımları ve Vergi Defteri var.
        """
        widget = QWidget()
        layout = QVBoxLayout(widget)
        layout.setSpacing(15)
        layout.setContentsMargins(15, 15, 15, 15)

        # ---------------------------------------------------------
        # BÖLÜM 1: VERGİ TANIMLARI (Örn: KDV %20, ÖTV %5)
        # ---------------------------------------------------------
        taxes_group = QGroupBox(self.main_app.lang.get("tax_definitions", "Tax Definitions"))
        taxes_layout = QVBoxLayout(taxes_group)

        # Tablo
        self.main_app.tax_definitions_table = QTableWidget(0, 3)
        self.main_app.tax_definitions_table.setHorizontalHeaderLabels([
            self.main_app.lang.get("tax_name", "Tax Name"),
            self.main_app.lang.get("type", "Type"),
            self.main_app.lang.get("tax_value", "Value (Rate/Amount)")
        ])
        self.main_app.tax_definitions_table.horizontalHeader().setSectionResizeMode(QHeaderView.ResizeMode.Stretch)
        self.main_app.tax_definitions_table.setSelectionBehavior(QTableWidget.SelectionBehavior.SelectRows)
        self.main_app.tax_definitions_table.setSelectionMode(QTableWidget.SelectionMode.SingleSelection)
        self.main_app.tax_definitions_table.setEditTriggers(QTableWidget.EditTrigger.NoEditTriggers)
        self.main_app.tax_definitions_table.setAlternatingRowColors(True)
        taxes_layout.addWidget(self.main_app.tax_definitions_table)

        # Butonlar
        btn_layout = QHBoxLayout()
        
        add_btn = QPushButton(self.main_app.lang.get("add_tax", "Add Tax"))
        add_btn.setIcon(self.main_app._get_icon("SP_DialogApplyButton"))
        add_btn.clicked.connect(self.main_app._add_tax_definition)
        
        edit_btn = QPushButton(self.main_app.lang.get("edit", "Edit"))
        edit_btn.setIcon(self.main_app._get_icon("SP_FileDialogDetailedView"))
        edit_btn.clicked.connect(self.main_app._edit_tax_definition)
        
        del_btn = QPushButton(self.main_app.lang.get("delete", "Delete"))
        del_btn.setIcon(self.main_app._get_icon("SP_TrashIcon"))
        del_btn.setObjectName("dangerButton") # Kırmızı stil için
        del_btn.clicked.connect(self.main_app._delete_tax_definition)

        btn_layout.addWidget(add_btn)
        btn_layout.addWidget(edit_btn)
        btn_layout.addWidget(del_btn)
        taxes_layout.addLayout(btn_layout)
        
        layout.addWidget(taxes_group, 1) # Esnek yükseklik

        # ---------------------------------------------------------
        # BÖLÜM 2: VERGİ DEFTERİ (Geçmiş İşlemler)
        # ---------------------------------------------------------
        ledger_group = QGroupBox(self.main_app.lang.get("tax_ledger", "Tax Ledger (Recent Transactions)"))
        ledger_layout = QVBoxLayout(ledger_group)

        # Tablo
        self.main_app.tax_ledger_table = QTableWidget(0, 7)
        headers = [
            self.main_app.lang.get("date", "Date"),
            self.main_app.lang.get("transaction_source", "Source"),
            self.main_app.lang.get("customer", "Customer"),
            self.main_app.lang.get("applied_taxes", "Applied Taxes"),
            self.main_app.lang.get("tax_base_amount", "Base Amount"),
            self.main_app.lang.get("tax_amount_col", "Tax Amount"),
            self.main_app.lang.get("grand_total", "Grand Total")
        ]
        self.main_app.tax_ledger_table.setHorizontalHeaderLabels(headers)
        self.main_app.tax_ledger_table.horizontalHeader().setSectionResizeMode(QHeaderView.ResizeMode.Stretch)
        self.main_app.tax_ledger_table.setEditTriggers(QTableWidget.EditTrigger.NoEditTriggers)
        self.main_app.tax_ledger_table.setAlternatingRowColors(True)
        ledger_layout.addWidget(self.main_app.tax_ledger_table)

        # Yenile Butonu
        refresh_layout = QHBoxLayout()
        refresh_layout.addStretch()
        refresh_btn = QPushButton(self.main_app.lang.get("refresh_table", "Refresh Table"))
        refresh_btn.setIcon(self.main_app._get_icon("SP_BrowserReload"))
        refresh_btn.clicked.connect(self.main_app._refresh_taxes_ui)
        refresh_layout.addWidget(refresh_btn)
        ledger_layout.addLayout(refresh_layout)

        layout.addWidget(ledger_group, 2) # Daha fazla alan kaplasın

        # İlk açılışta verileri yükle
        QTimer.singleShot(100, self.main_app._refresh_taxes_ui)

        return widget
    def create_data_transfer_tab(self) -> QWidget:
        """Ayarlar içinde yer alacak 'Profiller Arası Veri Transferi' sekmesini oluşturur."""
        widget = QWidget()
        layout = QVBoxLayout(widget)
        layout.setSpacing(15)
        target_group = QGroupBox(self.main_app.lang.get("step1_transfer", "Step 1: Select Target Profile and Action Type"))
        target_layout = QFormLayout(target_group)
        self.main_app.transfer_target_profile_combo = QComboBox()
        target_layout.addRow(f"<b>{self.main_app.lang.get('target_profile', 'Target Profile')}:</b>", self.main_app.transfer_target_profile_combo)
        self.main_app.transfer_action_combo = QComboBox()
        self.main_app.transfer_action_combo.addItems([self.main_app.lang.get("copy_transfer", "Copy (Keep at source)"), self.main_app.lang.get("move_transfer", "Move (Delete from source)")])
        target_layout.addRow(f"<b>{self.main_app.lang.get('action_type', 'Action Type')}:</b>", self.main_app.transfer_action_combo)
        layout.addWidget(target_group)
        data_group = QGroupBox(self.main_app.lang.get("step2_transfer", "Step 2: Select Data Packages to Transfer"))
        data_layout = QVBoxLayout(data_group)
        self.main_app.transfer_chk_customers = QCheckBox(self.main_app.lang.get("all_customer_defs", "All Customer Definitions"))
        data_layout.addWidget(self.main_app.transfer_chk_customers)
        def_frame = QFrame()
        def_layout = QHBoxLayout(def_frame)
        def_layout.setContentsMargins(0,0,0,0)
        def_layout.addWidget(QLabel(f"<b>{self.main_app.lang.get('product_defs', 'Product Definitions')}:</b>"))
        self.main_app.transfer_chk_def_product = QCheckBox(self.main_app.lang.get("gold", "Gold"))
        self.main_app.transfer_chk_def_scrap = QCheckBox(self.main_app.lang.get("scrap", "Scrap"))
        self.main_app.transfer_chk_def_ziynet = QCheckBox(self.main_app.lang.get("ziynet", "Ziynet"))
        for chk in [self.main_app.transfer_chk_def_product, self.main_app.transfer_chk_def_scrap, self.main_app.transfer_chk_def_ziynet]:
            chk.setChecked(True) # Varsayılan olarak seçili
            def_layout.addWidget(chk)
        def_layout.addStretch()
        data_layout.addWidget(def_frame)
        customer_transfer_frame = QFrame()
        customer_transfer_layout = QHBoxLayout(customer_transfer_frame)
        customer_transfer_layout.setContentsMargins(0,0,0,0)
        self.main_app.transfer_chk_single_customer = QCheckBox(self.main_app.lang.get("specific_customer_data", "All Data of a Specific Customer (including Current Account)"))
        self.main_app.transfer_customer_select_combo = QComboBox()
        self.main_app.transfer_customer_select_combo.setEditable(True)
        self.main_app.transfer_customer_select_combo.setEnabled(False)
        self.main_app.transfer_chk_single_customer.toggled.connect(self.main_app.transfer_customer_select_combo.setEnabled)
        customer_transfer_layout.addWidget(self.main_app.transfer_chk_single_customer)
        customer_transfer_layout.addWidget(self.main_app.transfer_customer_select_combo, 1)
        data_layout.addWidget(customer_transfer_frame)
        stock_transfer_frame = QFrame()
        stock_transfer_layout = QHBoxLayout(stock_transfer_frame)
        stock_transfer_layout.setContentsMargins(0,0,0,0)
        self.main_app.transfer_chk_stock = QCheckBox(self.main_app.lang.get("transfer_depot_stocks", "Transfer Stocks in Depot"))
        self.main_app.transfer_stock_depot_combo = QComboBox()
        self.main_app.transfer_stock_depot_combo.setEnabled(False)
        self.main_app.transfer_chk_stock.toggled.connect(self.main_app.transfer_stock_depot_combo.setEnabled)
        stock_transfer_layout.addWidget(self.main_app.transfer_chk_stock)
        stock_transfer_layout.addWidget(self.main_app.transfer_stock_depot_combo, 1)
        data_layout.addWidget(stock_transfer_frame)
        self.main_app.transfer_chk_services = QCheckBox(self.main_app.lang.get("all_service_defs", "All Service Definitions and Job Records"))
        data_layout.addWidget(self.main_app.transfer_chk_services)
        layout.addWidget(data_group)
        finance_transfer_group = QGroupBox(self.main_app.lang.get("financial_transfer_between_profiles", "Financial Transfer Between Profiles"))
        finance_transfer_group.setToolTip("Bu işlem, yukarıdaki veri paketlerinden bağımsız olarak sadece para transferi yapar.")
        self.main_app.transfer_grp_finance = finance_transfer_group
        finance_layout = QFormLayout(finance_transfer_group)
        self.main_app.transfer_finance_source_combo = QComboBox()
        finance_layout.addRow(f"<b>{self.main_app.lang.get('from_source', 'From Source')}:</b>", self.main_app.transfer_finance_source_combo)
        amount_layout = QHBoxLayout()
        self.main_app.transfer_finance_amount = QLineEdit("0.00")
        self.main_app.transfer_finance_amount.setValidator(self.main_app._create_float_validator())
        self.main_app.transfer_finance_currency = QComboBox()
        self.main_app.transfer_finance_currency.addItems(SUPPORTED_CURRENCIES)
        amount_layout.addWidget(self.main_app.transfer_finance_amount)
        amount_layout.addWidget(self.main_app.transfer_finance_currency)
        finance_layout.addRow(f"<b>{self.main_app.lang.get('amount', 'Amount')}:</b>", amount_layout)
        self.main_app.transfer_finance_target_combo = QComboBox()
        finance_layout.addRow(f"<b>{self.main_app.lang.get('to_target', 'To Target')}:</b>", self.main_app.transfer_finance_target_combo)
        layout.addWidget(finance_transfer_group)
        execute_btn = QPushButton(self.main_app.lang.get("start_transfer", "Start Transfer"))
        execute_btn.setObjectName("primaryButton")
        execute_btn.setMinimumHeight(40)
        execute_btn.setIcon(self.main_app._get_icon("SP_DialogApplyButton"))
        execute_btn.clicked.connect(self.main_app._execute_data_transfer)
        layout.addWidget(execute_btn)
        layout.addStretch()
        self.main_app.transfer_target_profile_combo.currentIndexChanged.connect(self.main_app._on_transfer_target_profile_changed)
        return widget
    def create_pos_style_tab(self, stock_type: str, transaction_type: str) -> QWidget:
        """
        Creates a generic POS-style tab for either Sales or Purchases.
        Refactor: StockType ve OperationType Enum kullanımı.
        """
        from core.constants import StockType, OperationType
        from functools import partial

        is_sale = (transaction_type == "Sale")
        pos_key = f"{stock_type}_{transaction_type}"
        widget = QWidget()
        widget.setProperty("pos_stock_type", stock_type)
        widget.setProperty("pos_transaction_type", transaction_type)
        main_layout = QHBoxLayout(widget)
        left_panel = QWidget()
        left_layout = QVBoxLayout(left_panel)
        title_key = "pos_title" if is_sale else "purchase_pos_tab"
        form_group = QGroupBox(self.main_app.lang[title_key])
        form_layout = QFormLayout(form_group)
        pos_depot_combo = QComboBox()
        form_layout.addRow(f"<b>{self.main_app.lang['pos_transaction_depot']}:</b>", pos_depot_combo)
        product_combo = QComboBox()
        product_combo.setEditable(True)
        product_combo.setPlaceholderText(self.main_app.lang["product_name_type"])
        quantity_entry = QLineEdit("1")
        if stock_type in (StockType.PRODUCT, StockType.ZIYNET):
            quantity_entry.setValidator(self.main_app._create_float_validator(0))
        else:
            quantity_entry.setValidator(self.main_app._create_float_validator(3))
        price_layout = QHBoxLayout()
        price_entry = QLineEdit()
        price_entry.setPlaceholderText(self.main_app.lang.get("unit_price_ph", "Unit Price"))
        price_entry.setValidator(self.main_app._create_float_validator())
        total_price_entry = QLineEdit()
        total_price_entry.setPlaceholderText(self.main_app.lang.get("total_amount_ph", "Total Amount"))
        total_price_entry.setValidator(self.main_app._create_float_validator())
        price_currency_combo = QComboBox()
        price_currency_combo.addItems(SUPPORTED_CURRENCIES)
        price_currency_combo.setCurrentText(self.main_app.display_currency)
        price_layout.addWidget(price_entry)
        price_layout.addWidget(total_price_entry)
        price_layout.addWidget(price_currency_combo)
        workmanship_checkbox = QCheckBox(self.main_app.lang["include_workmanship"])
        price_label = self.main_app.lang['unit_sale_price'] if is_sale else self.main_app.lang['unit_purchase_price']
        quantity_label = "Adet" if stock_type in (StockType.PRODUCT, StockType.ZIYNET) else self.main_app.lang['quantity']
        gram_info_label = QLabel("") if stock_type == StockType.PRODUCT else None
        if gram_info_label:
            gram_info_label.setStyleSheet("color: #666; font-style: italic;")
        form_layout.addRow(f"{self.main_app.lang['product_name_type']}:", product_combo)
        form_layout.addRow(f"{quantity_label}:", quantity_entry)
        if stock_type == StockType.PRODUCT and gram_info_label:
            form_layout.addRow(self.main_app.lang.get("gram_info", "Gram Info:"), gram_info_label)
        lbl_layout = QHBoxLayout()
        lbl_layout.addWidget(QLabel(price_label))
        lbl_layout.addWidget(QLabel(self.main_app.lang.get("total_value_lbl", "Total Value")))
        lbl_layout.addWidget(QLabel(self.main_app.lang.get("currency_short", "Cur.")))
        form_layout.addRow("", lbl_layout)
        form_layout.addRow(self.main_app.lang.get("values_lbl", "Values:"), price_layout)
        if stock_type == StockType.PRODUCT:
            form_layout.addRow("", workmanship_checkbox)
        add_btn_text = self.main_app.lang["add_to_cart"] if is_sale else self.main_app.lang["add_to_purchase_list"]
        add_btn = QPushButton(self.main_app._get_icon("SP_DialogApplyButton"), add_btn_text)
        add_btn.setAutoDefault(True)
        add_btn.clicked.connect(partial(self.main_app._add_to_cart, stock_type, transaction_type))
        form_layout.addRow(add_btn)
        left_layout.addWidget(form_group)
        left_layout.addStretch()
        right_panel = QWidget()
        right_layout = QVBoxLayout(right_panel)
        cart_group_title = self.main_app.lang["cart"] if is_sale else self.main_app.lang["purchase_cart"]
        cart_group = QGroupBox(cart_group_title)
        cart_layout = QVBoxLayout(cart_group)
        column_count = 6 if stock_type == StockType.PRODUCT else 5
        cart_table = QTableWidget(0, column_count)
        if stock_type == StockType.PRODUCT:
            header_label = self.main_app.lang['product']
            cart_table.setHorizontalHeaderLabels([header_label, self.main_app.lang.get("pieces", "Pieces"), self.main_app.lang.get("gram", "Gram"), price_label, self.main_app.lang["currency"], self.main_app.lang["total_amount"]])
        elif stock_type == StockType.ZIYNET:
            header_label = self.main_app.lang['ziynet']
            cart_table.setHorizontalHeaderLabels([header_label, self.main_app.lang.get("pieces", "Pieces"), price_label, self.main_app.lang["currency"], self.main_app.lang["total_amount"]])
        else: # SCRAP
            header_label = self.main_app.lang['scrap']
            cart_table.setHorizontalHeaderLabels([header_label, self.main_app.lang["quantity"], price_label, self.main_app.lang["currency"], self.main_app.lang["total_amount"]])
        cart_table.horizontalHeader().setSectionResizeMode(QHeaderView.ResizeMode.Stretch)
        cart_table.setEditTriggers(QTableWidget.EditTrigger.NoEditTriggers)
        cart_btn_layout = QHBoxLayout()
        remove_btn_text = self.main_app.lang["remove_from_cart"] if is_sale else self.main_app.lang["remove_from_purchase_list"]
        remove_btn = QPushButton(self.main_app._get_icon("SP_TrashIcon"), remove_btn_text)
        remove_btn.setObjectName("dangerButton")
        remove_btn.clicked.connect(partial(self.main_app._remove_from_cart, pos_key))
        cart_btn_layout.addWidget(remove_btn)
        cart_btn_layout.addStretch()
        cart_layout.addWidget(cart_table)
        cart_layout.addLayout(cart_btn_layout)
        summary_form = QFormLayout()
        total_amount_label = QLabel(f"0.00 {self.main_app.display_currency}")
        font = total_amount_label.font(); font.setPointSize(14); font.setBold(True); total_amount_label.setFont(font)
        summary_form.addRow(QLabel(f'{self.main_app.lang["total_amount"]}:'), total_amount_label)
        person_layout = QHBoxLayout()
        person_combo = QComboBox()
        person_combo.setEditable(True)
        person_placeholder = self.main_app.lang["customer_name_placeholder"] if is_sale else self.main_app.lang["person_name_placeholder"]
        person_combo.setPlaceholderText(person_placeholder)
        person_names = self.main_app.person_manager.get_person_names()
        person_combo.addItems([""] + person_names)
        completer = QCompleter(person_names)
        completer.setCaseSensitivity(Qt.CaseSensitivity.CaseInsensitive)
        completer.setFilterMode(Qt.MatchFlag.MatchContains)
        person_combo.setCompleter(completer)
        add_person_shortcut_btn = QPushButton("+")
        add_person_shortcut_btn.setFixedSize(30, 30)
        add_person_shortcut_btn.setToolTip(self.main_app.lang["add_person"])
        add_person_shortcut_btn.clicked.connect(lambda: self.main_app._safe_navigate_to_tab("contacts_tab_widget"))
        person_layout.addWidget(person_combo, 1)
        person_layout.addWidget(add_person_shortcut_btn)
        person_label_text = self.main_app.lang["customer_name"] if is_sale else self.main_app.lang["supplier_person"]
        summary_form.addRow(QLabel(f"{person_label_text}:"), person_layout)

        # --- Vergi Kısmı (YENİLENMİŞ) ---
        apply_taxes_checkbox = QCheckBox(self.main_app.lang.get("apply_tax", "Apply Tax"))
        apply_taxes_checkbox.setChecked(False)
        
        # Bilgi etiketi (Hangi vergiler seçili?)
        tax_info_label = QLabel(self.main_app.lang.get("selected_none", "Selected: None"))
        tax_info_label.setStyleSheet("color: #1976D2; font-style: italic; margin-left: 10px;")
        
        # Checkbox tıklandığında (veya değiştirildiğinde) tetiklenecek fonksiyon sales.py içinde
        apply_taxes_checkbox.clicked.connect(
            partial(self.main_app._on_tax_checkbox_clicked, stock_type, transaction_type)
        )
        
        tax_row = QHBoxLayout()
        tax_row.addWidget(apply_taxes_checkbox)
        tax_row.addWidget(tax_info_label)
        tax_row.addStretch()
        
        summary_form.addRow(self.main_app.lang.get("tax_operations", "Tax Operations:"), tax_row)

        def _combo_has_real_items(combo: QComboBox) -> bool:
            for i in range(combo.count()):
                if (combo.itemText(i) or "").strip():
                    return True
            return False

        def _install_empty_combo_guard(combo: QComboBox, on_empty) -> None:
            class _Guard(QObject):
                def eventFilter(self, obj, event):  # type: ignore[override]
                    if obj is combo and event.type() == QEvent.Type.MouseButtonPress:
                        if not _combo_has_real_items(combo):
                            try:
                                on_empty()
                            except Exception:
                                pass
                            return True
                    return super().eventFilter(obj, event)

            guard = _Guard(combo)
            combo.installEventFilter(guard)
            # Keep a strong reference so the guard isn't garbage-collected.
            setattr(combo, "_empty_combo_guard", guard)

        if stock_type == StockType.PRODUCT:
            def_page = self.main_app.lang.get("product_def_tab", "Product Definitions")
        elif stock_type == StockType.SCRAP:
            def_page = self.main_app.lang.get("scrap_def_tab", "Scrap Definitions")
        else:
            def_page = self.main_app.lang.get("ziynet_def_tab", "Ziynet Definitions")

        _install_empty_combo_guard(
            product_combo,
            lambda: self.main_app._show_empty_combo_prompt(def_page, lambda: self.main_app._open_stock_definitions(stock_type)),
        )
        _install_empty_combo_guard(
            pos_depot_combo,
            lambda: self.main_app._show_empty_combo_prompt(
                self.main_app.lang.get("manage_depots", "Manage Depots"),
                getattr(self.main_app, "_open_depots_tab", None),
            ),
        )
        _install_empty_combo_guard(
            person_combo,
            lambda: self.main_app._show_empty_combo_prompt(
                self.main_app.lang.get("customer_management", "Customer Management"),
                lambda: self.main_app._safe_navigate_to_tab("contacts_tab_widget"),
            ),
        )
        complete_btn_text = self.main_app.lang["complete_sale"] if is_sale else self.main_app.lang["complete_purchase"]
        complete_btn = QPushButton(self.main_app._get_icon("SP_DialogOkButton"), complete_btn_text)
        complete_btn.setObjectName("primaryButton")
        complete_btn.setAutoDefault(True)
        complete_btn.clicked.connect(partial(self.main_app._complete_transaction, stock_type, transaction_type))
        print_invoice_btn = QPushButton(self.main_app._get_icon("SP_FilePrint"), self.main_app.lang.get("print_receipt_invoice", "Print Receipt/Invoice"))
        print_invoice_btn.clicked.connect(partial(self.main_app._print_pos_invoice, stock_type, transaction_type))
        right_layout.addWidget(cart_group)
        right_layout.addLayout(summary_form)
        action_btn_layout = QHBoxLayout()
        action_btn_layout.addWidget(print_invoice_btn)
        action_btn_layout.addWidget(complete_btn)
        right_layout.addLayout(action_btn_layout)
        main_layout.addWidget(left_panel, 1)
        main_layout.addWidget(right_panel, 2)
        widgets_dict = {
            'product_combo': product_combo,
            'quantity_entry': quantity_entry,
            'price_entry': price_entry,
            'total_price_entry': total_price_entry,
            'price_currency_combo': price_currency_combo,
            'cart_table': cart_table,
            'total_amount_label': total_amount_label,
            'person_combo': person_combo,
            'apply_taxes_checkbox': apply_taxes_checkbox,
            'tax_info_label': tax_info_label,
            'selected_taxes': [],
            'workmanship_checkbox': workmanship_checkbox,
            'current_workmanship_fee': 0.0,
            'current_workmanship_currency': self.main_app.display_currency,
            'pos_depot_combo': pos_depot_combo
        }
        if stock_type == StockType.PRODUCT:
            widgets_dict['gram_info_label'] = gram_info_label
        self.main_app.stock_widgets[stock_type][transaction_type] = widgets_dict
        product_combo.currentTextChanged.connect(partial(self.main_app._pos_product_selected, stock_type, transaction_type))
        workmanship_checkbox.toggled.connect(partial(self.main_app._toggle_workmanship, stock_type, transaction_type))
        quantity_entry.textEdited.connect(lambda text: self.main_app._pos_update_prices(stock_type, transaction_type, 'qty'))
        price_entry.textEdited.connect(lambda text: self.main_app._pos_update_prices(stock_type, transaction_type, 'unit'))
        total_price_entry.textEdited.connect(lambda text: self.main_app._pos_update_prices(stock_type, transaction_type, 'total'))
        self.main_app.setTabOrder(pos_depot_combo, product_combo)
        self.main_app.setTabOrder(product_combo, quantity_entry)
        self.main_app.setTabOrder(quantity_entry, price_entry)
        self.main_app.setTabOrder(price_entry, total_price_entry)
        self.main_app.setTabOrder(total_price_entry, price_currency_combo)
        self.main_app.setTabOrder(price_currency_combo, workmanship_checkbox)
        self.main_app.setTabOrder(workmanship_checkbox, add_btn)
        return widget
    def create_stock_status_subtab(self, stock_type: str) -> QWidget:
        """
        Stok Durumu Sekmesi - VERİ ODAKLI FİLTRE YAPILANDIRMASI
        Bu fonksiyon, filtrelerin görsel metinden bağımsız olarak 'None' verisi taşımasını sağlar.
        """
        widget = QWidget()
        layout = QVBoxLayout(widget)
        filter_layout = QHBoxLayout()
        filter_label = QLabel(f"{self.main_app.lang['depot']}:")
        depot_filter_combo = QComboBox()
        depot_filter_combo.addItem(self.main_app.lang["show_all"], None)
        if hasattr(self.main_app, '_get_accessible_depots'):
            for d_name in self.main_app._get_accessible_depots():
                depot_filter_combo.addItem(d_name, d_name)
        depot_filter_combo.currentIndexChanged.connect(partial(self.main_app._update_generic_stock_list, stock_type))
        filter_layout.addWidget(filter_label)
        filter_layout.addWidget(depot_filter_combo, 1)
        self.main_app.stock_widgets[stock_type]['depot_filter_combo'] = depot_filter_combo
        if stock_type == "Product":
            type_filter_label = QLabel(self.main_app.lang.get("product_type_lbl", "Product Type:"))
            type_filter_combo = QComboBox()
            type_filter_combo.addItem(self.main_app.lang.get("all_items", "All"), None)
            product_names = self.main_app.product_manager.get_product_names()
            for p_name in product_names:
                type_filter_combo.addItem(p_name, p_name)
            type_filter_combo.currentIndexChanged.connect(partial(self.main_app._update_generic_stock_list, stock_type))
            filter_layout.addWidget(type_filter_label)
            filter_layout.addWidget(type_filter_combo, 1)
            self.main_app.stock_widgets[stock_type]['type_filter_combo'] = type_filter_combo
        layout.addLayout(filter_layout)
        list_group = QGroupBox(self.main_app.lang["stock_status"])
        list_layout = QVBoxLayout(list_group)
        if stock_type == 'Product':
            is_boss = getattr(self.main_app, "is_boss_mode", False)
            column_count = 9 if is_boss else 8
            header_label = self.main_app.lang['product_type']
            headers = [
                header_label, self.main_app.lang.get("barcode", "Barcode"), self.main_app.lang["depot"],
                self.main_app.lang.get("total_pieces", "Total Pieces"), self.main_app.lang.get("total_quantity_gr", "Total Quantity (gr)"),
                f"{self.main_app.lang['average_purchase']} ({self.main_app.display_currency})",
                f"{self.main_app.lang['total_value']} ({self.main_app.display_currency})",
                self.main_app.lang.get("action", "Action")
            ]
            if is_boss:
                headers.insert(0, self.main_app.lang.get("branch_profile", "Branch (Profile)"))
        else:
            is_boss = getattr(self.main_app, "is_boss_mode", False)
            column_count = 6 if is_boss else 5
            header_label = self.main_app.lang['ziynet'] if stock_type == 'Ziynet' else self.main_app.lang['scrap']
            qty_header = self.main_app.lang.get("total_pieces", "Total Pieces") if stock_type == 'Ziynet' else f"{self.main_app.lang.get('total_quantity', 'Total')} {self.main_app.lang['quantity']}"
            headers = [
                header_label,
                self.main_app.lang["depot"],
                qty_header,
                self.main_app.lang.get("average_purchase_short", self.main_app.lang["average_purchase"]),
                f"{self.main_app.lang['total_value']} ({self.main_app.display_currency})"
            ]
            if is_boss:
                headers.insert(0, self.main_app.lang.get("branch_profile", "Branch (Profile)"))
        stock_table = QTableWidget(0, column_count)
        stock_table.setHorizontalHeaderLabels(headers)
        stock_table.horizontalHeader().setSectionResizeMode(QHeaderView.ResizeMode.Stretch)
        stock_table.setEditTriggers(QTableWidget.EditTrigger.NoEditTriggers)
        stock_table.itemSelectionChanged.connect(partial(self.main_app._update_stock_button_states, stock_type))
        list_layout.addWidget(stock_table)
        btn_layout = QHBoxLayout()
        update_price_btn = QPushButton(self.main_app._get_icon("SP_BrowserReload"), self.main_app.lang["update_stock_price"])
        update_price_btn.clicked.connect(partial(self.main_app._update_stock_item_price, stock_type))
        delete_stock_btn = QPushButton(self.main_app._get_icon("SP_TrashIcon"), self.main_app.lang["delete_selected_stock"])
        delete_stock_btn.setObjectName("dangerButton")
        delete_stock_btn.clicked.connect(partial(self.main_app._delete_stock_item, stock_type))
        manual_in_btn = QPushButton(self.main_app._get_icon("SP_ArrowDown"), self.main_app.lang.get("manual_entry", "Manual Entry"))
        manual_in_btn.setStyleSheet("background-color: #2E7D32; color: white;")
        manual_in_btn.clicked.connect(partial(self.main_app._manual_stock_action, stock_type, "In"))
        manual_out_btn = QPushButton(self.main_app._get_icon("SP_ArrowUp"), self.main_app.lang.get("manual_exit", "Manual Exit"))
        manual_out_btn.setStyleSheet("background-color: #C62828; color: white;")
        manual_out_btn.clicked.connect(partial(self.main_app._manual_stock_action, stock_type, "Out"))
        btn_layout.addWidget(manual_in_btn)
        btn_layout.addWidget(manual_out_btn)
        btn_layout.addStretch()
        btn_layout.addWidget(update_price_btn)
        btn_layout.addWidget(delete_stock_btn)
        list_layout.addLayout(btn_layout)
        layout.addWidget(list_group)
        if stock_type == 'Product':
            sold_group = QGroupBox(self.main_app.lang.get("daily_sold_barcodes", "Daily Sold Barcodes"))
            sold_layout = QVBoxLayout(sold_group)
            sold_filter_layout = QHBoxLayout()
            sold_filter_layout.addWidget(QLabel(f"<b>{self.main_app.lang.get('date', 'Date')}:</b>"))
            self.main_app.sold_barcode_date_edit = QDateEdit(datetime.now())
            self.main_app.sold_barcode_date_edit.setCalendarPopup(True)
            self.main_app.sold_barcode_date_edit.setDisplayFormat("dd.MM.yyyy")
            self.main_app.sold_barcode_date_edit.dateChanged.connect(self.main_app._update_sold_barcodes_table)
            sold_filter_layout.addWidget(self.main_app.sold_barcode_date_edit)
            sold_filter_layout.addWidget(QLabel(f"<b>{self.main_app.lang.get('depot', 'Depot')}:</b>"))
            sold_depot_filter = QComboBox()
            sold_depot_filter.addItem(self.main_app.lang.get("all_items", "All"), None)
            for d in self.main_app._get_accessible_depots():
                sold_depot_filter.addItem(d, d)
            sold_depot_filter.currentIndexChanged.connect(self.main_app._update_sold_barcodes_table)
            sold_filter_layout.addWidget(sold_depot_filter)
            sold_filter_layout.addStretch()
            sold_layout.addLayout(sold_filter_layout)
            sold_barcodes_table = QTableWidget(0, 5)
            sold_barcodes_table.setHorizontalHeaderLabels([self.main_app.lang.get("sale_time", "Sale Time"), self.main_app.lang.get("barcode", "Barcode"), self.main_app.lang.get("product_name_type", "Product Name"), self.main_app.lang.get("sold_to", "Sold To"), self.main_app.lang.get("sale_method", "Sale Method")])
            sold_barcodes_table.horizontalHeader().setSectionResizeMode(QHeaderView.ResizeMode.Stretch)
            sold_barcodes_table.setEditTriggers(QTableWidget.EditTrigger.NoEditTriggers)
            sold_layout.addWidget(sold_barcodes_table)
            self.main_app.stock_widgets[stock_type]['sold_barcodes_table'] = sold_barcodes_table
            self.main_app.stock_widgets[stock_type]['sold_depot_filter'] = sold_depot_filter
            layout.addWidget(sold_group)
        else:
            ledger_group = QGroupBox(self.main_app.lang.get("stock_movement_history", "Stock Movement History (Log)"))
            ledger_layout = QVBoxLayout(ledger_group)
            ledger_filter_layout = QHBoxLayout()
            ledger_depot_combo = QComboBox()
            ledger_depot_combo.addItem(self.main_app.lang.get("show_all", "Show All"), None) # Güvenli Ekleme
            if hasattr(self.main_app, '_get_accessible_depots'):
                for d in self.main_app._get_accessible_depots():
                    ledger_depot_combo.addItem(d, d)
            ledger_depot_combo.currentIndexChanged.connect(lambda: self.main_app._update_stock_movement_table(stock_type))
            ledger_date_enabled = QCheckBox(self.main_app.lang.get("date_filter", "Date Filter:"))
            ledger_date_enabled.setChecked(False)
            ledger_date_enabled.toggled.connect(lambda: self.main_app._update_stock_movement_table(stock_type))
            ledger_date_filter = QDateEdit(datetime.now())
            ledger_date_filter.setCalendarPopup(True)
            ledger_date_filter.setDisplayFormat("dd.MM.yyyy")
            ledger_date_filter.setEnabled(False)
            ledger_date_filter.dateChanged.connect(lambda: self.main_app._update_stock_movement_table(stock_type))
            ledger_date_enabled.toggled.connect(ledger_date_filter.setEnabled)
            ledger_filter_layout.addWidget(QLabel(self.main_app.lang.get("depot_filter", "Depot Filter:")))
            ledger_filter_layout.addWidget(ledger_depot_combo)
            ledger_filter_layout.addWidget(ledger_date_enabled)
            ledger_filter_layout.addWidget(ledger_date_filter)
            ledger_filter_layout.addStretch()
            ledger_layout.addLayout(ledger_filter_layout)
            movement_table = QTableWidget(0, 7)
            movement_table.setHorizontalHeaderLabels([
                self.main_app.lang.get("date_time", "Date/Time"), self.main_app.lang.get("product", "Product"), self.main_app.lang.get("action", "Action"), self.main_app.lang.get("quantity", "Quantity"), self.main_app.lang.get("source", "Source"), self.main_app.lang.get("target", "Target"), self.main_app.lang.get("user", "User")
            ])
            movement_table.horizontalHeader().setSectionResizeMode(QHeaderView.ResizeMode.Stretch)
            movement_table.setEditTriggers(QTableWidget.EditTrigger.NoEditTriggers)
            movement_table.setAlternatingRowColors(True)
            ledger_layout.addWidget(movement_table)
            self.main_app.stock_widgets[stock_type]['movement_table'] = movement_table
            self.main_app.stock_widgets[stock_type]['movement_depot_filter'] = ledger_depot_combo
            self.main_app.stock_widgets[stock_type]['movement_date_filter'] = ledger_date_filter
            self.main_app.stock_widgets[stock_type]['movement_date_filter_enabled'] = ledger_date_enabled
            layout.addWidget(ledger_group)
            summary_group = QGroupBox(self.main_app.lang["stock_summary"])
            summary_layout = QFormLayout(summary_group)
            total_stock_value_label = QLabel(f"0.00 {self.main_app.display_currency}")
            font = total_stock_value_label.font(); font.setBold(True); total_stock_value_label.setFont(font)
            summary_layout.addRow(self.main_app.lang["overall_stock_value"], total_stock_value_label)
            layout.addWidget(summary_group)
            self.main_app.stock_widgets[stock_type]['total_stock_value_label'] = total_stock_value_label
            QTimer.singleShot(500, lambda: self.main_app._update_stock_movement_table(stock_type))
        self.main_app.stock_widgets[stock_type]['stock_table'] = stock_table
        self.main_app.stock_widgets[stock_type]['delete_stock_btn'] = delete_stock_btn
        self.main_app.stock_widgets[stock_type]['update_price_btn'] = update_price_btn
        self.main_app._update_stock_button_states(stock_type)
        return widget
    def create_product_definitions_subtab(self, stock_type: str) -> QWidget:
        """
        Ürün Tanımlama Sekmesi.
        Kategori ve Ziynet için Gramaj alanı eklendi.
        """
        is_product = stock_type == "Product"
        is_ziynet = stock_type == "Ziynet"
        widget = QWidget()
        widget.setObjectName(f"product_definitions_{stock_type}")
        layout = QVBoxLayout(widget)
        group = QGroupBox(self.main_app.lang["add_product_definition"])
        form = QFormLayout(group)
        product_name_entry = QLineEdit()
        form.addRow(f"{self.main_app.lang['product_name_type']}*:", product_name_entry)
        category_combo = QComboBox()
        if hasattr(self.main_app, 'category_manager'):
            category_combo.addItems(self.main_app.category_manager.get_category_names())
        else:
            category_combo.addItems(["Altın", "Gümüş", "Pırlanta", "Saat"])
        form.addRow(self.main_app.lang.get("category_for_zakat", "Category (For Zakat):"), category_combo)
        karat_entry = QLineEdit()
        karat_entry.setPlaceholderText("Örn: 22, 14, 925")
        form.addRow(f"{self.main_app.lang['product_karat']}:", karat_entry)
           # --- ZİYNET İÇİN GRAMAJ ALANI (DEÄİŞİKLİK BURADA) ---
        ziynet_gram_entry = None
        if is_ziynet:
            ziynet_gram_entry = QLineEdit()
            ziynet_gram_entry.setPlaceholderText(self.main_app.lang.get("eg_ziynet_gram", "e.g. 1.75 (Quarter)"))
            ziynet_gram_entry.setValidator(self.main_app._create_float_validator(3))
            # Ziynet için özel etiket
            form.addRow(self.main_app.lang.get("pure_gram_for_zakat", "Pure Grams (For Zakat Only):"), ziynet_gram_entry)
        
        purchase_layout = QHBoxLayout()
        default_purchase_entry = QLineEdit()
        default_purchase_entry.setValidator(self.main_app._create_float_validator())
        purchase_currency_combo = QComboBox(); purchase_currency_combo.addItems(SUPPORTED_CURRENCIES)
        purchase_layout.addWidget(default_purchase_entry); purchase_layout.addWidget(purchase_currency_combo)
        sale_layout = QHBoxLayout()
        default_sale_entry = QLineEdit()
        default_sale_entry.setValidator(self.main_app._create_float_validator())
        sale_currency_combo = QComboBox(); sale_currency_combo.addItems(SUPPORTED_CURRENCIES)
        sale_layout.addWidget(default_sale_entry); sale_layout.addWidget(sale_currency_combo)
        form.addRow(f"{self.main_app.lang['default_purchase_price']}:", purchase_layout)
        form.addRow(f"{self.main_app.lang['default_sale_price']}:", sale_layout)
        workmanship_entry = None
        workmanship_curr_combo = None
        if is_product:
            work_layout = QHBoxLayout()
            workmanship_entry = QLineEdit()
            workmanship_curr_combo = QComboBox(); workmanship_curr_combo.addItems(SUPPORTED_CURRENCIES)
            work_layout.addWidget(workmanship_entry); work_layout.addWidget(workmanship_curr_combo)
            form.addRow(f"{self.main_app.lang['product_workmanship']}:", work_layout)
        btn_layout = QHBoxLayout()
        add_btn = QPushButton(self.main_app.lang["add"])
        add_btn.setAutoDefault(True)
        add_btn.clicked.connect(partial(self.main_app._add_product_definition, stock_type))

        update_btn = QPushButton(self.main_app.lang.get("update", "Update"))
        update_btn.setAutoDefault(True)
        update_btn.clicked.connect(partial(self.main_app._update_product_definition, stock_type))

        delete_btn = QPushButton(self.main_app.lang["delete"])
        delete_btn.setAutoDefault(True)
        delete_btn.setObjectName("dangerButton")
        delete_btn.clicked.connect(partial(self.main_app._delete_product_definition, stock_type))

        clear_btn = QPushButton(self.main_app.lang.get("clear_form", "Clear"))
        clear_btn.setAutoDefault(True)
        clear_btn.clicked.connect(partial(self.main_app._clear_product_form, stock_type))

        # ENTER -> default action (Ekle). Avoid UI-side filtering / state guessing.
        for entry in [
            product_name_entry,
            karat_entry,
            ziynet_gram_entry,
            default_purchase_entry,
            default_sale_entry,
            workmanship_entry,
        ]:
            if isinstance(entry, QLineEdit):
                entry.returnPressed.connect(add_btn.click)

        if hasattr(self.main_app, "shortcut_manager"):
            # Keyboard Shortcut Layer (Widget scoped, collision-safe)
            self.main_app.shortcut_manager.add(
                widget,
                "Ctrl+L",
                partial(self.main_app._update_generic_product_definition_list, stock_type),
                "Tanımları listele/yenile",
            )
            self.main_app.shortcut_manager.add(
                widget,
                "Ctrl+G",
                partial(self.main_app._update_product_definition, stock_type),
                "Tanımı güncelle",
            )
            self.main_app.shortcut_manager.add(
                widget,
                "Ctrl+Shift+E",
                partial(self.main_app._add_product_definition, stock_type),
                "Tanım ekle",
            )
            self.main_app.shortcut_manager.add(
                widget,
                "Ctrl+Shift+S",
                partial(self.main_app._delete_product_definition, stock_type),
                "Tanımı sil",
            )
            self.main_app.shortcut_manager.add(
                widget,
                "Ctrl+Shift+T",
                partial(self.main_app._clear_product_form, stock_type),
                "Formu temizle",
            )

        for w in (add_btn, update_btn, delete_btn, clear_btn):
            btn_layout.addWidget(w)
        form.addRow(btn_layout)
        layout.addWidget(group)
        list_group = QGroupBox(self.main_app.lang.get("definitions", "Definitions"))
        list_l = QVBoxLayout(list_group)
        table = QTableWidget()
        table.setSelectionBehavior(QTableWidget.SelectionBehavior.SelectRows)
        table.setSelectionMode(QTableWidget.SelectionMode.SingleSelection)
        table.setEditTriggers(QTableWidget.EditTrigger.NoEditTriggers)
        table.setAlternatingRowColors(True)
        try:
            table.selectionModel().selectionChanged.connect(lambda *_: self.main_app._product_definition_selected(stock_type))
        except Exception:
            pass
        list_l.addWidget(table)
        layout.addWidget(list_group)
        self.main_app.stock_widgets[stock_type]['def_form'] = {
            'product_name': product_name_entry,
            'category': category_combo,
            'karat': karat_entry,
            'ziynet_gram': ziynet_gram_entry, # ARTIK None DEÄİL (Ziynet ise QLineEdit)
            'workmanship': workmanship_entry,
            'workmanship_curr': workmanship_curr_combo,
            'purchase': default_purchase_entry,
            'purchase_curr': purchase_currency_combo,
            'sale': default_sale_entry,
            'sale_curr': sale_currency_combo,
            'table': table,
            'update_btn': update_btn,
            'delete_btn': delete_btn
        }
        self.main_app._update_generic_product_definition_list(stock_type)
        return widget
    def create_category_manage_tab(self) -> QWidget:
        """Kategori Ekleme/Silme Sekmesi."""
        widget = QWidget()
        layout = QVBoxLayout(widget)
        form_grp = QGroupBox(self.main_app.lang.get("add_category_group", "Add Category"))
        f_layout = QHBoxLayout(form_grp)
        self.main_app.cat_name_entry = QLineEdit()
        self.main_app.cat_name_entry.setPlaceholderText(self.main_app.lang.get("eg_category_name", "e.g. Diamond"))
        add_btn = QPushButton(self.main_app.lang["add"])
        add_btn.setAutoDefault(True)
        add_btn.clicked.connect(self.main_app._add_category)
        self.main_app.cat_name_entry.returnPressed.connect(add_btn.click)
        f_layout.addWidget(QLabel(self.main_app.lang.get("category_name_lbl", "Category Name:")))
        f_layout.addWidget(self.main_app.cat_name_entry)
        f_layout.addWidget(add_btn)
        layout.addWidget(form_grp)
        list_grp = QGroupBox(self.main_app.lang.get("existing_categories", "Existing Categories"))
        l_layout = QVBoxLayout(list_grp)
        self.main_app.category_list_widget = QListWidget()
        if hasattr(self.main_app, 'category_manager'):
            self.main_app.category_list_widget.addItems(self.main_app.category_manager.get_category_names())
        del_btn = QPushButton(self.main_app.lang.get("delete_selected_category", "Delete Selected Category"))
        del_btn.setAutoDefault(True)
        del_btn.clicked.connect(self.main_app._delete_category)
        l_layout.addWidget(self.main_app.category_list_widget)
        l_layout.addWidget(del_btn)
        layout.addWidget(list_grp)

        if hasattr(self.main_app, "shortcut_manager"):
            self.main_app.shortcut_manager.add(
                widget,
                "Ctrl+L",
                self.main_app._refresh_category_list,
                "Kategori listesini yenile",
            )
            self.main_app.shortcut_manager.add(
                widget,
                "Ctrl+Shift+E",
                self.main_app._add_category,
                "Kategori ekle",
            )
            self.main_app.shortcut_manager.add(
                widget,
                "Ctrl+Shift+S",
                self.main_app._delete_category,
                "Kategori sil",
            )

        return widget
    def build_stock_category(self) -> QWidget:
        """3. STOK İŞLEMLERİ Kategorisi - Yetki Kontrollü (Kategoriler Sekmesi Dahil)"""
        tabs = QTabWidget()
        if self.main_app.has_permission("perm_stock_product"):
            tabs.addTab(self.create_stock_status_subtab("Product"), self.main_app.lang.get("product_status_tab", "Gold Stock"))
        if self.main_app.has_permission("perm_def_product"):
            tabs.addTab(self.create_product_definitions_subtab("Product"), self.main_app.lang.get("product_def_tab", "Gold Definitions"))
        if self.main_app.has_permission("perm_stock_scrap"):
            tabs.addTab(self.create_stock_status_subtab("Scrap"), self.main_app.lang.get("scrap_status_tab", "Scrap Stock"))
        if self.main_app.has_permission("perm_def_scrap"):
            tabs.addTab(self.create_product_definitions_subtab("Scrap"), self.main_app.lang.get("scrap_def_tab", "Scrap Definitions"))
        if self.main_app.has_permission("perm_stock_ziynet"):
            tabs.addTab(self.create_stock_status_subtab("Ziynet"), self.main_app.lang.get("ziynet_status_tab", "Ziynet Stock"))
        if self.main_app.has_permission("perm_def_ziynet"):
            tabs.addTab(self.create_product_definitions_subtab("Ziynet"), self.main_app.lang.get("ziynet_def_tab", "Ziynet Definitions"))
        if self.main_app.has_permission("perm_depots"):
            depots_widget = self.create_depots_tab()
            tabs.addTab(depots_widget, self.main_app.lang.get("manage_depots", "Depots"))
        if self.main_app.has_permission("perm_def_product"):
            tabs.addTab(self.create_category_manage_tab(), self.main_app.lang.get("categories_tab", "Categories"))
        tabs.setCurrentIndex(0)
        self.main_app.stocks_tab_widget = tabs
        return tabs
    def create_stock_report_subtab(self, stock_type: str) -> QWidget:
        """Creates the Stock Report sub-tab UI."""
        widget = QWidget()
        layout = QVBoxLayout(widget)
        group = QGroupBox(self.main_app.lang["stock_value_report"])
        group_layout = QVBoxLayout(group)
        btn_layout = QHBoxLayout()
        update_btn = QPushButton(self.main_app.lang["update_report"])
        update_btn.setAutoDefault(True)
        update_btn.clicked.connect(partial(self.main_app._generate_stock_report_text, stock_type))
        btn_layout.addWidget(update_btn); btn_layout.addStretch()
        report_display = QTextEdit(); report_display.setReadOnly(True); report_display.setFont(QFont("Consolas" if sys.platform == "win32" else "Courier", 10))
        group_layout.addLayout(btn_layout)
        group_layout.addWidget(report_display)
        layout.addWidget(group)
        self.main_app.stock_widgets[stock_type]['report_display'] = report_display
        return widget
    def create_account_transfer_subtab(self) -> QWidget:
        """Creates the UI for transferring funds between any two accounts."""
        widget = QWidget()
        layout = QVBoxLayout(widget)
        group = QGroupBox(self.main_app.lang["account_transfer_tab"])
        form = QFormLayout(group)
        self.main_app.transfer_source_combo = QComboBox()
        self.main_app.transfer_dest_combo = QComboBox()
        self.main_app.transfer_amount_entry = QLineEdit()
        self.main_app.transfer_amount_entry.setValidator(self.main_app._create_float_validator())
        self.main_app.transfer_currency_combo = QComboBox()
        self.main_app.transfer_currency_combo.addItems(SUPPORTED_CURRENCIES)
        self.main_app.transfer_currency_combo.setCurrentText(self.main_app.display_currency)
        self.main_app.transfer_desc_entry = QLineEdit()
        amount_layout = QHBoxLayout()
        amount_layout.addWidget(self.main_app.transfer_amount_entry)
        amount_layout.addWidget(self.main_app.transfer_currency_combo)
        form.addRow(f"{self.main_app.lang['source_account']}:", self.main_app.transfer_source_combo)
        form.addRow(f"{self.main_app.lang['destination_account']}:", self.main_app.transfer_dest_combo)
        form.addRow(f"{self.main_app.lang['amount']}:", amount_layout)
        form.addRow(f"{self.main_app.lang['description']}:", self.main_app.transfer_desc_entry)
        transfer_btn = QPushButton(self.main_app._get_icon("SP_DialogApplyButton"), self.main_app.lang["execute_transfer"])
        transfer_btn.setObjectName("primaryButton")
        transfer_btn.setAutoDefault(True)
        transfer_btn.clicked.connect(self.main_app.finance_manager._execute_account_transfer)
        form.addRow(transfer_btn)
        self.main_app.setTabOrder(self.main_app.transfer_source_combo, self.main_app.transfer_dest_combo)
        self.main_app.setTabOrder(self.main_app.transfer_dest_combo, self.main_app.transfer_amount_entry)
        self.main_app.setTabOrder(self.main_app.transfer_amount_entry, self.main_app.transfer_currency_combo)
        self.main_app.setTabOrder(self.main_app.transfer_currency_combo, self.main_app.transfer_desc_entry)
        self.main_app.setTabOrder(self.main_app.transfer_desc_entry, transfer_btn)
        layout.addWidget(group)
        layout.addStretch()
        return widget
    def create_scheduled_transactions_subtab(self) -> QWidget:
        widget = QWidget()
        layout = QVBoxLayout(widget)
        form_group = QGroupBox(self.main_app.lang["add_scheduled_transaction"])
        form = QFormLayout(form_group)
        self.main_app.st_due_date = QDateEdit(datetime.now() + timedelta(days=7))
        self.main_app.st_due_date.setCalendarPopup(True)
        self.main_app.st_due_date.setDisplayFormat("dd.MM.yyyy")
        self.main_app.st_type_combo = QComboBox(); self.main_app.st_type_combo.addItems([self.main_app.lang["income"], self.main_app.lang["expense"]])
        amount_layout = QHBoxLayout()
        self.main_app.st_amount_entry = QLineEdit(); self.main_app.st_amount_entry.setValidator(self.main_app._create_float_validator())
        self.main_app.st_currency_combo = QComboBox(); self.main_app.st_currency_combo.addItems(SUPPORTED_CURRENCIES); self.main_app.st_currency_combo.setCurrentText(self.main_app.display_currency)
        amount_layout.addWidget(self.main_app.st_amount_entry); amount_layout.addWidget(self.main_app.st_currency_combo)
        self.main_app.st_description_entry = QLineEdit()
        self.main_app.st_target_account_combo = QComboBox()
        self.main_app.st_person_combo = QComboBox()
        self.main_app.st_person_combo.setEditable(True)
        self.main_app.st_person_combo.setPlaceholderText(self.main_app.lang["person_name_placeholder"])
        form.addRow(f"{self.main_app.lang['due_date']}:", self.main_app.st_due_date)
        form.addRow(f"{self.main_app.lang['transaction_type']}:", self.main_app.st_type_combo)
        form.addRow(f"{self.main_app.lang['amount']}:", amount_layout)
        form.addRow(f"{self.main_app.lang['description']}:", self.main_app.st_description_entry)
        form.addRow(f"{self.main_app.lang['source_account']}:", self.main_app.st_target_account_combo)
        form.addRow(f"{self.main_app.lang['person']}:", self.main_app.st_person_combo)
        add_btn = QPushButton(self.main_app.lang["add"]); add_btn.clicked.connect(self.main_app._add_scheduled_transaction)
        add_btn.setObjectName("primaryButton")
        form.addRow(add_btn)
        layout.addWidget(form_group)
        list_group = QGroupBox(self.main_app.lang["all_scheduled_transactions"])
        list_layout = QVBoxLayout(list_group)
        self.main_app.scheduled_transactions_table = QTableWidget(0, 7)
        self.main_app.scheduled_transactions_table.setHorizontalHeaderLabels([self.main_app.lang["due_date"], self.main_app.lang["transaction_type"], self.main_app.lang["amount"], self.main_app.lang["person"], self.main_app.lang["description"], self.main_app.lang["source"], self.main_app.lang["status"]])
        self.main_app.scheduled_transactions_table.horizontalHeader().setSectionResizeMode(QHeaderView.ResizeMode.Stretch)
        self.main_app.scheduled_transactions_table.setEditTriggers(QTableWidget.EditTrigger.NoEditTriggers)
        self.main_app.scheduled_transactions_table.itemSelectionChanged.connect(self.main_app._update_scheduled_transaction_button_states)
        btn_layout = QHBoxLayout()
        self.main_app.st_complete_btn = QPushButton(self.main_app.lang["complete_now"])
        self.main_app.st_complete_btn.setObjectName("primaryButton")
        self.main_app.st_complete_btn.clicked.connect(self.main_app._complete_selected_scheduled_transaction)
        self.main_app.st_edit_btn = QPushButton(self.main_app.lang["edit"])
        self.main_app.st_edit_btn.clicked.connect(self.main_app._edit_scheduled_transaction)
        self.main_app.st_delete_btn = QPushButton(self.main_app.lang["delete"])
        self.main_app.st_delete_btn.setObjectName("dangerButton")
        self.main_app.st_delete_btn.clicked.connect(self.main_app._delete_scheduled_transaction)
        btn_layout.addStretch()
        btn_layout.addWidget(self.main_app.st_complete_btn)
        btn_layout.addWidget(self.main_app.st_edit_btn)
        btn_layout.addWidget(self.main_app.st_delete_btn)
        list_layout.addWidget(self.main_app.scheduled_transactions_table)
        list_layout.addLayout(btn_layout)
        layout.addWidget(list_group)
        self.main_app._update_scheduled_transaction_button_states()
        self.main_app.setTabOrder(self.main_app.st_due_date, self.main_app.st_type_combo)
        self.main_app.setTabOrder(self.main_app.st_type_combo, self.main_app.st_amount_entry)
        self.main_app.setTabOrder(self.main_app.st_amount_entry, self.main_app.st_currency_combo)
        self.main_app.setTabOrder(self.main_app.st_currency_combo, self.main_app.st_description_entry)
        self.main_app.setTabOrder(self.main_app.st_description_entry, self.main_app.st_target_account_combo)
        self.main_app.setTabOrder(self.main_app.st_target_account_combo, self.main_app.st_person_combo)
        self.main_app.setTabOrder(self.main_app.st_person_combo, add_btn)
        self.main_app.setTabOrder(add_btn, self.main_app.scheduled_transactions_table)
        self.main_app.setTabOrder(self.main_app.scheduled_transactions_table, self.main_app.st_complete_btn)
        self.main_app.setTabOrder(self.main_app.st_complete_btn, self.main_app.st_edit_btn)
        self.main_app.setTabOrder(self.main_app.st_edit_btn, self.main_app.st_delete_btn)
        return widget
    def create_contacts_manage_subtab(self) -> QWidget:
        """
        Creates the sub-tab for adding/editing contacts.
        FAZ 8: Tab sıralaması (Tab Order) düzeltildi.
        """
        widget = QWidget()
        layout = QVBoxLayout(widget)
        form_group = QGroupBox(self.main_app.lang["add_person"])
        form_layout = QFormLayout(form_group)
        self.main_app.contact_full_name_entry = QLineEdit()
        self.main_app.contact_full_name_entry.setMaxLength(150)
        self.main_app.contact_full_name_entry.setPlaceholderText(self.main_app.lang.get("max_150_chars", "Max. 150 characters"))
        self.main_app.contact_phone_entry = QLineEdit()
        self.main_app.contact_phone_entry.setMaxLength(50)
        self.main_app.contact_address_text_edit = QTextEdit()
        self.main_app.contact_address_text_edit.setFixedHeight(60)
        self.main_app.contact_notes_text_edit = QTextEdit()
        self.main_app.contact_notes_text_edit.setFixedHeight(60)
        form_layout.addRow(f"{self.main_app.lang['first_name_last_name']}*:", self.main_app.contact_full_name_entry)
        form_layout.addRow(f"{self.main_app.lang['phone']}:", self.main_app.contact_phone_entry)
        form_layout.addRow(f"{self.main_app.lang['address_first_line']}:", self.main_app.contact_address_text_edit)
        form_layout.addRow(f"{self.main_app.lang['notes']}:", self.main_app.contact_notes_text_edit)
        btn_layout = QHBoxLayout()
        add_btn = QPushButton(self.main_app._get_icon("SP_DialogApplyButton"), self.main_app.lang["add"])
        add_btn.setObjectName("primaryButton")
        add_btn.setAutoDefault(True)
        add_btn.clicked.connect(lambda: self.main_app.crm_manager._add_update_person())
        self.main_app.update_person_btn = QPushButton(self.main_app._get_icon("SP_DialogSaveButton"), self.main_app.lang["update"])
        self.main_app.update_person_btn.clicked.connect(lambda: self.main_app.crm_manager._add_update_person(update=True))
        self.main_app.delete_person_btn = QPushButton(self.main_app._get_icon("SP_TrashIcon"), self.main_app.lang["delete"])
        self.main_app.delete_person_btn.setObjectName("dangerButton")
        self.main_app.delete_person_btn.clicked.connect(self.main_app.crm_manager._delete_person)
        clear_btn = QPushButton(self.main_app._get_icon("SP_DialogResetButton"), self.main_app.lang["clear_form"])
        clear_btn.clicked.connect(self.main_app.crm_manager._clear_person_form)
        for w in [add_btn, self.main_app.update_person_btn, self.main_app.delete_person_btn, clear_btn]:
            btn_layout.addWidget(w)
        form_layout.addRow(btn_layout)
        layout.addWidget(form_group)
        list_group = QGroupBox(self.main_app.lang["registered_persons"])
        list_layout = QVBoxLayout(list_group)
        search_layout = QHBoxLayout()
        self.main_app.contact_search_entry = QLineEdit()
        self.main_app.contact_search_entry.setPlaceholderText(self.main_app.lang["search"])
        self.main_app.contact_search_entry.textChanged.connect(self.main_app.crm_manager._filter_person_list)
        search_layout.addWidget(QLabel(f"{self.main_app.lang['search']}:"))
        search_layout.addWidget(self.main_app.contact_search_entry)
        list_layout.addLayout(search_layout)
        self.main_app.person_table = QTableWidget(0, 3)
        self.main_app.person_table.setHorizontalHeaderLabels([self.main_app.lang["first_name_last_name"], self.main_app.lang["phone"], self.main_app.lang["address_first_line"]])
        self.main_app.person_table.horizontalHeader().setSectionResizeMode(QHeaderView.ResizeMode.Stretch)
        self.main_app.person_table.setEditTriggers(QTableWidget.EditTrigger.NoEditTriggers)
        self.main_app.person_table.itemSelectionChanged.connect(self.main_app.crm_manager._person_selected)
        list_layout.addWidget(self.main_app.person_table)
        layout.addWidget(list_group)
        self.main_app.crm_manager._update_person_button_states()
        self.main_app.setTabOrder(self.main_app.contact_full_name_entry, self.main_app.contact_phone_entry)
        self.main_app.setTabOrder(self.main_app.contact_phone_entry, self.main_app.contact_address_text_edit)
        self.main_app.setTabOrder(self.main_app.contact_address_text_edit, self.main_app.contact_notes_text_edit)
        self.main_app.setTabOrder(self.main_app.contact_notes_text_edit, add_btn)
        self.main_app.setTabOrder(add_btn, self.main_app.update_person_btn)
        self.main_app.setTabOrder(self.main_app.update_person_btn, self.main_app.delete_person_btn)
        self.main_app.setTabOrder(self.main_app.delete_person_btn, clear_btn)
        self.main_app.setTabOrder(clear_btn, self.main_app.contact_search_entry)
        self.main_app.setTabOrder(self.main_app.contact_search_entry, self.main_app.person_table)
        return widget
    def create_summary_card(self):
        """Rapor sekmesi için şık bir bilgi kartı oluşturur."""
        frame = QFrame()
        frame.setStyleSheet("background-color: rgba(0,0,0,0.05); border-radius: 8px; border: 1px solid #ccc;")
        frame.setMinimumWidth(200)
        l = QVBoxLayout(frame)
        title = QLabel("-")
        title.setObjectName("cardTitle")
        title.setStyleSheet("font-size: 12px; color: #666; font-weight: bold;")
        val = QLabel("0.00")
        val.setObjectName("cardValue")
        val.setStyleSheet(f"font-size: 18px; color: {self.main_app.all_themes[self.main_app.settings_manager.get_setting('theme_name')]['primary']}; font-weight: bold;")
        l.addWidget(title, alignment=Qt.AlignmentFlag.AlignCenter)
        l.addWidget(val, alignment=Qt.AlignmentFlag.AlignCenter)
        return frame
    def create_generic_stock_tab(self, stock_type: str) -> QWidget:
        """ Creates a generic tab for managing stock (Product or Scrap). """
        is_product = stock_type == "Product"
        widget = QTabWidget()
        self.main_app.stock_widgets[stock_type]['tab_widget'] = widget
        stock_status_tab = self.create_stock_status_subtab(stock_type)
        product_def_tab = self.create_product_definitions_subtab(stock_type)
        sales_pos_tab = self.create_pos_style_tab(stock_type, "Sale")
        purchase_pos_tab = self.create_pos_style_tab(stock_type, "Purchase")
        depot_transfer_tab = self.create_stock_transfer_subtab(stock_type)
        stock_report_tab = self.create_stock_report_subtab(stock_type)
        widget.addTab(stock_status_tab, self.main_app.lang["stock_status"])
        def_label = self.main_app.lang["add_product_definition"] if is_product else self.main_app.lang["scrap_definition"]
        widget.addTab(product_def_tab, def_label)
        widget.addTab(sales_pos_tab, self.main_app.lang["sales_pos_tab"])
        widget.addTab(purchase_pos_tab, self.main_app.lang["purchase_pos_tab"])
        widget.addTab(depot_transfer_tab, self.main_app.lang["depot_transfer_tab"])
        widget.addTab(stock_report_tab, self.main_app.lang["stock_value_report"])
        return widget
    def create_stock_transfer_subtab(self, stock_type: str) -> QWidget:
        """Creates the new Depot Transfer sub-tab UI."""
        widget = QWidget()
        layout = QVBoxLayout(widget)
        group = QGroupBox(self.main_app.lang["depot_transfer_tab"])
        form = QFormLayout(group)
        source_depot_combo = QComboBox()
        dest_depot_combo = QComboBox()
        product_combo = QComboBox()
        quantity_entry = QLineEdit()
        if stock_type in ("Product", "Ziynet"):
            quantity_entry.setValidator(self.main_app._create_float_validator(precision=0))
        else:
            quantity_entry.setValidator(self.main_app._create_float_validator(precision=3))
        form.addRow(f"{self.main_app.lang['source_depot']}:", source_depot_combo)
        form.addRow(f"{self.main_app.lang['destination_depot']}:", dest_depot_combo)
        form.addRow(f"{self.main_app.lang['product']}:", product_combo)
        qty_label = "Adet" if stock_type in ("Product", "Ziynet") else self.main_app.lang['quantity']
        form.addRow(f"{qty_label}:", quantity_entry)
        transfer_btn = QPushButton(self.main_app._get_icon("SP_DialogApplyButton"), self.main_app.lang["execute_depot_transfer"])
        transfer_btn.setObjectName("primaryButton")
        transfer_btn.setAutoDefault(True)
        transfer_btn.clicked.connect(partial(self.main_app._execute_stock_transfer, stock_type))
        form.addRow(transfer_btn)
        layout.addWidget(group)
        layout.addStretch()
        self.main_app.stock_widgets[stock_type]['transfer'] = {
            'source_combo': source_depot_combo,
            'dest_combo': dest_depot_combo,
            'product_combo': product_combo,
            'quantity_entry': quantity_entry,
        }
        source_depot_combo.currentIndexChanged.connect(partial(self.main_app._update_transfer_product_combo, stock_type))
        self.main_app.setTabOrder(source_depot_combo, dest_depot_combo)
        self.main_app.setTabOrder(dest_depot_combo, product_combo)
        self.main_app.setTabOrder(product_combo, quantity_entry)
        self.main_app.setTabOrder(quantity_entry, transfer_btn)
        return widget
    def create_currency_exchange_tab(self) -> QWidget:
        """Creates the tab for performing currency exchanges and viewing live rates."""
        widget = QWidget()
        layout = QVBoxLayout(widget)
        exchange_group = QGroupBox(self.main_app.lang["exchange_title"])
        form_layout = QFormLayout(exchange_group)
        self.main_app.exchange_source_account_combo = QComboBox()
        self.main_app.exchange_dest_account_combo = QComboBox()
        form_layout.addRow(f"{self.main_app.lang['source_account']}:", self.main_app.exchange_source_account_combo)
        form_layout.addRow(f"{self.main_app.lang['destination_account']}:", self.main_app.exchange_dest_account_combo)
        sold_layout = QHBoxLayout()
        self.main_app.exchange_sold_amount = QLineEdit()
        self.main_app.exchange_sold_amount.setValidator(self.main_app._create_float_validator())
        self.main_app.exchange_sold_currency = QComboBox()
        self.main_app.exchange_sold_currency.addItems(SUPPORTED_CURRENCIES)
        sold_layout.addWidget(self.main_app.exchange_sold_amount)
        sold_layout.addWidget(self.main_app.exchange_sold_currency)
        form_layout.addRow(f"{self.main_app.lang['sold_amount']}:", sold_layout)
        bought_layout = QHBoxLayout()
        self.main_app.exchange_bought_amount = QLineEdit()
        self.main_app.exchange_bought_amount.setValidator(self.main_app._create_float_validator())
        self.main_app.exchange_bought_currency = QComboBox()
        self.main_app.exchange_bought_currency.addItems(SUPPORTED_CURRENCIES)
        bought_layout.addWidget(self.main_app.exchange_bought_amount)
        bought_layout.addWidget(self.main_app.exchange_bought_currency)
        form_layout.addRow(f"{self.main_app.lang['bought_amount']}:", bought_layout)
        execute_btn = QPushButton(self.main_app._get_icon("SP_DialogApplyButton"), self.main_app.lang["execute_exchange"])
        execute_btn.setObjectName("primaryButton")
        execute_btn.setAutoDefault(True)
        execute_btn.clicked.connect(self.main_app.finance_manager._execute_exchange_transaction)
        form_layout.addRow(execute_btn)
        layout.addWidget(exchange_group)
        rates_group = QGroupBox(self.main_app.lang["exchange_rates_tab"])
        rates_layout = QVBoxLayout(rates_group)
        top_layout = QHBoxLayout()
        refresh_btn = QPushButton(self.main_app._get_icon("SP_BrowserReload"), self.main_app.lang["refresh"])
        refresh_btn.clicked.connect(self.main_app.finance_manager._update_exchange_rates_display)
        top_layout.addWidget(refresh_btn)
        top_layout.addStretch()
        self.main_app.rates_last_updated_label = QLabel("")
        top_layout.addWidget(self.main_app.rates_last_updated_label)
        rates_layout.addLayout(top_layout)
        self.main_app.rates_table = QTableWidget(0, 3)
        self.main_app.rates_table.setHorizontalHeaderLabels([self.main_app.lang["currency"], self.main_app.lang.get("buy_rate", "Buy"), self.main_app.lang.get("sell_rate", "Sell")])
        self.main_app.rates_table.horizontalHeader().setSectionResizeMode(QHeaderView.ResizeMode.Stretch)
        self.main_app.rates_table.setEditTriggers(QTableWidget.EditTrigger.NoEditTriggers)
        rates_layout.addWidget(self.main_app.rates_table)
        layout.addWidget(rates_group, 1)
        QTimer.singleShot(1000, self.main_app.finance_manager._update_exchange_rates_display)
        self.main_app.setTabOrder(self.main_app.exchange_source_account_combo, self.main_app.exchange_dest_account_combo)
        self.main_app.setTabOrder(self.main_app.exchange_dest_account_combo, self.main_app.exchange_sold_amount)
        self.main_app.setTabOrder(self.main_app.exchange_sold_amount, self.main_app.exchange_sold_currency)
        self.main_app.setTabOrder(self.main_app.exchange_sold_currency, self.main_app.exchange_bought_amount)
        self.main_app.setTabOrder(self.main_app.exchange_bought_amount, self.main_app.exchange_bought_currency)
        self.main_app.setTabOrder(self.main_app.exchange_bought_currency, execute_btn)
        self.main_app.setTabOrder(execute_btn, refresh_btn)
        self.main_app.setTabOrder(refresh_btn, self.main_app.rates_table)
        return widget





