
import uuid
import json
import logging
from datetime import datetime
from typing import List, Dict, Any, Optional

from PyQt6.QtWidgets import (
    QWidget, QVBoxLayout, QHBoxLayout, QTabWidget, QPushButton,
    QTableWidget, QTableWidgetItem, QHeaderView, QGroupBox,
    QFormLayout, QLabel, QLineEdit, QComboBox, QDialog, QListWidget,
    QDialogButtonBox, QMessageBox, QDoubleSpinBox, QCompleter, QFileDialog,
    QInputDialog, QDateEdit
)
from PyQt6.QtCore import Qt, QTimer, QDate
from PyQt6.QtGui import QColor, QIcon

from core.db import DataManager, BaseManager, ServiceDefinition, ServiceJob, FinancialTransaction, CustomerHistoryEvent, StockItem
from core.config import SUPPORTED_CURRENCIES, format_number, logger, get_default_depot_name
from modules.sales import PaymentDialog

class ServiceDefinitionManager(BaseManager):
    """
    [AI_DOC]
    Hizmet (Service) tanimlarini MySQL veritabanindan ceker ve kaydeder.
    FAZ 5 Guncellemesi: `stages` (Asamalar) eklendi ve JSON'a cevrildi.
    Eger veritabaninda `stages_json` kolonu yoksa otomatik olarak olusturur (Migration).
    [/AI_DOC]
    """
    def __init__(self, data_manager: DataManager):
        super().__init__(data_manager, "service_definitions", ServiceDefinition)
        
        # FAZ 5: Otomatik Migration (Eger stages_json kolonu yoksa ekle)
        try:
            if not self.db.has_column("service_definitions", "stages_json"):
                logger.info("Service Definitions tablosuna 'stages_json' kolonu ekleniyor (Migration).")
                with self.db.get_connection() as conn:
                    with conn.cursor() as cursor:
                        cursor.execute("ALTER TABLE service_definitions ADD COLUMN stages_json LONGTEXT NULL")
                    conn.commit()
                self.db.invalidate_table_columns_cache("service_definitions")
        except Exception as e:
            logger.error(f"Migration error for stages_json: {e}")

    def _custom_map_to_sql(self, item: Any, sql_data: Dict[str, Any]) -> Optional[Dict[str, Any]]:
        if "custom_columns" in sql_data:
            sql_data["custom_columns_json"] = sql_data.pop("custom_columns") or []
        if "stages" in sql_data:
            sql_data["stages_json"] = sql_data.pop("stages") or []
        return sql_data

    def _custom_map_from_sql(self, row: Dict[str, Any]) -> Optional[Any]:
        cols: List[str] = []
        raw_cols = row.get("custom_columns_json")
        if raw_cols:
            try:
                cols = json.loads(raw_cols) if isinstance(raw_cols, str) else raw_cols
            except Exception:
                cols = []
                
        stages: List[str] = ["Alindi", "Islemde", "Hazir", "Teslim Edildi"]
        raw_stages = row.get("stages_json")
        if raw_stages:
            try:
                stages = json.loads(raw_stages) if isinstance(raw_stages, str) else raw_stages
            except Exception:
                pass
                
        if not stages:
            stages = ["Alindi", "Islemde", "Hazir", "Teslim Edildi"]

        return self.data_class(
            name=row.get("name", "") or "",
            custom_columns=cols or [],
            stages=stages,
            id=row.get("id") or str(uuid.uuid4()),
            profile_id=row.get("profile_id") or "",
        )

class ServiceJobManager(BaseManager):
    def __init__(self, data_manager: DataManager):
        super().__init__(data_manager, "service_jobs", ServiceJob)

    def _custom_map_to_sql(self, item: Any, sql_data: Dict[str, Any]) -> Optional[Dict[str, Any]]:
        if "dynamic_data" in sql_data:
            sql_data["dynamic_data_json"] = sql_data.pop("dynamic_data") or {}
        return sql_data

    def _custom_map_from_sql(self, row: Dict[str, Any]) -> Optional[Any]:
        def to_float(val, default=0.0):
            try:
                if val is None: return default
                return float(val)
            except Exception: return default

        def fmt_date(val):
            if not val: return ""
            if hasattr(val, "strftime"): return val.strftime("%d.%m.%Y")
            return str(val)

        dynamic_data: Dict[str, Any] = {}
        raw = row.get("dynamic_data_json")
        if raw:
            try: dynamic_data = json.loads(raw) if isinstance(raw, str) else raw
            except Exception: dynamic_data = {}

        return self.data_class(
            service_def_id=row.get("service_def_id", "") or "",
            customer_name=row.get("customer_name", "") or "",
            description=row.get("description", "") or "",
            status=row.get("status", "") or "",
            fee=to_float(row.get("fee")),
            currency=row.get("currency", "") or "",
            dynamic_data=dynamic_data or {},
            start_date=fmt_date(row.get("start_date")),
            delivery_date=fmt_date(row.get("delivery_date")),
            id=row.get("id") or str(uuid.uuid4()),
            profile_id=row.get("profile_id") or "",
        )

class ServiceManager:
    def __init__(self, data_manager: DataManager):
        self.data_manager = data_manager
        self.def_manager = ServiceDefinitionManager(data_manager)
        self.job_manager = ServiceJobManager(data_manager)

    @property
    def definitions(self) -> List[ServiceDefinition]:
        return self.def_manager.get_all()

    @property
    def jobs(self) -> List[ServiceJob]:
        return self.job_manager.get_all()

    def add_definition(self, definition: ServiceDefinition):
        self.def_manager.add_item(definition)

    def delete_definition(self, def_id: str):
        linked_jobs = self.get_jobs_by_def_id(def_id)
        for job in linked_jobs:
            self.job_manager.delete_item(job.id)
        self.def_manager.delete_item(def_id)

    def add_job(self, job: ServiceJob):
        self.job_manager.add_item(job)

    def update_job(self, job_id: str, new_data: dict):
        self.job_manager.update_item(job_id, new_data)

    def delete_job(self, job_id: str):
        self.job_manager.delete_item(job_id)

    def save_definitions(self): pass
    def save_jobs(self): pass

    def get_jobs_by_def_id(self, def_id: str) -> List[ServiceJob]:
        return [j for j in self.jobs if j.service_def_id == def_id]


class ServiceTabWidget(QWidget):
    """
    Tek bir hizmet turu icin (Orn: Lazer) arayuz.
    FAZ 5: 'status_action_combo' artik dinamik olarak tablonun 'stages' listesinden yuklenir.
    """
    def __init__(self, main_app, service_def: ServiceDefinition, manager: ServiceManager):
        super().__init__()
        self.main_app = main_app
        self.service_def = service_def
        self.manager = manager
        self.current_job_id = None 
        self.dynamic_inputs = {}   
        self._init_ui()
        self._load_data()

    def _init_ui(self):
        layout = QVBoxLayout(self)
        layout.setContentsMargins(10, 10, 10, 10)

        self.form_group = QGroupBox(self.main_app.lang.get("new_service_record", "New {service_name} Record").format(service_name=self.service_def.name))
        self.form_group.setStyleSheet("""
            QGroupBox { font-weight: bold; border: 1px solid #aaa; border-radius: 5px; margin-top: 10px; }
            QGroupBox::title { subcontrol-origin: margin; subcontrol-position: top center; padding: 0 5px; }
        """)
        form_layout = QFormLayout(self.form_group)

        self.customer_combo = QComboBox()
        self.customer_combo.setEditable(True)
        self.customer_combo.setPlaceholderText(self.main_app.lang.get("customer_name_ph", "Customer Name (Type or Select)"))
        form_layout.addRow(self.main_app.lang.get("customer_name_colon", "Customer Name:"), self.customer_combo)

        self.desc_edit = QLineEdit()
        self.desc_edit.setPlaceholderText(self.main_app.lang.get("general_desc_ph", "General description..."))
        form_layout.addRow(self.main_app.lang.get("description_colon", "Description:"), self.desc_edit)

        self.date_edit = QDateEdit()
        self.date_edit.setCalendarPopup(True)
        self.date_edit.setDisplayFormat("dd.MM.yyyy")
        self.date_edit.setDate(QDate.currentDate())
        form_layout.addRow(self.main_app.lang.get("date_colon", "Date:"), self.date_edit)

        fee_layout = QHBoxLayout()
        self.fee_spin = QDoubleSpinBox()
        self.fee_spin.setRange(0, 99999999)
        self.fee_spin.setButtonSymbols(QDoubleSpinBox.ButtonSymbols.NoButtons)
        self.fee_spin.setDecimals(2)
        
        self.currency_combo = QComboBox()
        self.currency_combo.addItems(SUPPORTED_CURRENCIES)
        self.currency_combo.setCurrentText(self.main_app.display_currency)
        self.currency_combo.setFixedWidth(70)
        
        fee_layout.addWidget(self.fee_spin)
        fee_layout.addWidget(self.currency_combo)
        form_layout.addRow(self.main_app.lang.get("estimated_fee_colon", "Estimated Fee:"), fee_layout)

        cols = self.service_def.custom_columns
        if isinstance(cols, str):
            try: cols = json.loads(cols)
            except: cols = []

        for col_name in cols:
            if col_name == "Tarih": continue
            if "Tarih" in col_name:
                inp = QDateEdit()
                inp.setCalendarPopup(True)
                inp.setDisplayFormat("dd.MM.yyyy")
                inp.setDate(QDate.currentDate())
                self.dynamic_inputs[col_name] = inp
                form_layout.addRow(f"{col_name}:", inp)
            else:
                inp = QLineEdit()
                inp.setPlaceholderText(f"{col_name} giriniz...")
                self.dynamic_inputs[col_name] = inp
                form_layout.addRow(f"{col_name}:", inp)

        btn_layout = QHBoxLayout()
        self.add_update_btn = QPushButton(self.main_app.lang.get("add", "Add"))
        self.add_update_btn.setObjectName("primaryButton")
        self.add_update_btn.setIcon(QIcon.fromTheme("list-add"))
        self.add_update_btn.setMinimumHeight(40)
        self.add_update_btn.clicked.connect(self._save_record)
        
        self.clear_btn = QPushButton(self.main_app.lang.get("clear_form", "Clear Form"))
        self.clear_btn.setIcon(QIcon.fromTheme("edit-clear"))
        self.clear_btn.setMinimumHeight(40)
        self.clear_btn.clicked.connect(self._clear_form)
        
        btn_layout.addWidget(self.add_update_btn)
        btn_layout.addWidget(self.clear_btn)
        form_layout.addRow(btn_layout)
        layout.addWidget(self.form_group)

        list_group = QGroupBox(self.main_app.lang.get("service_tracking_module", "{service_name} Tracking Module").format(service_name=self.service_def.name))
        list_layout = QVBoxLayout(list_group)

        filter_layout = QHBoxLayout()
        filter_layout.addWidget(QLabel(self.main_app.lang.get("filter_by_person", "Filter by Person:")))
        self.filter_combo = QComboBox()
        self.filter_combo.setEditable(True)
        self.filter_combo.addItem(self.main_app.lang.get("show_all", "Show All"))
        self.filter_combo.currentIndexChanged.connect(self._load_data)
        filter_layout.addWidget(self.filter_combo)
        
        pdf_btn = QPushButton(self.main_app.lang.get("export_pdf", "Export PDF"))
        pdf_btn.setIcon(QIcon.fromTheme("document-print"))
        pdf_btn.clicked.connect(self._export_pdf)
        filter_layout.addWidget(pdf_btn)
        
        excel_btn = QPushButton(self.main_app.lang.get("export_excel", "Export Excel"))
        excel_btn.setIcon(QIcon.fromTheme("x-office-spreadsheet"))
        excel_btn.clicked.connect(self._export_excel)
        filter_layout.addWidget(excel_btn)
        filter_layout.addStretch()
        list_layout.addLayout(filter_layout)

        static_headers = [self.main_app.lang.get("customer_name", "Customer Name"), self.main_app.lang.get("description", "Description"), self.main_app.lang.get("date", "Date"), self.main_app.lang.get("estimated_fee", "Estimated Fee")]
        dynamic_headers = [c for c in cols if c != "Tarih"]
        final_headers = static_headers + dynamic_headers + [self.main_app.lang.get("status_col", "Status")]
        
        self.table = QTableWidget(0, len(final_headers))
        self.table.setHorizontalHeaderLabels(final_headers)
        self.table.horizontalHeader().setSectionResizeMode(QHeaderView.ResizeMode.Stretch)
        self.table.setSelectionBehavior(QTableWidget.SelectionBehavior.SelectRows)
        self.table.setEditTriggers(QTableWidget.EditTrigger.NoEditTriggers)
        self.table.setAlternatingRowColors(True)
        self.table.itemSelectionChanged.connect(self._on_row_selected)
        list_layout.addWidget(self.table)

        action_layout = QHBoxLayout()
        action_layout.addWidget(QLabel(self.main_app.lang.get("change_status_lbl", "Change Status:")))
        
        self.status_action_combo = QComboBox()
        # FAZ 5: Dinamik asamalari ComboBox'a yukluyoruz.
        self.status_action_combo.addItems(self.service_def.stages)
        
        action_layout.addWidget(self.status_action_combo)
        
        self.change_status_btn = QPushButton(self.main_app.lang.get("change_status_btn", "Change Status"))
        self.change_status_btn.clicked.connect(self._change_status)
        action_layout.addWidget(self.change_status_btn)
        action_layout.addStretch()
        
        self.deliver_btn = QPushButton(self.main_app.lang.get("deliver_collect_btn", "Deliver & Collect"))
        self.deliver_btn.setObjectName("primaryButton")
        self.deliver_btn.clicked.connect(self._deliver_and_pay)
        action_layout.addWidget(self.deliver_btn)
        
        self.delete_btn = QPushButton(self.main_app.lang.get("delete", "Delete"))
        self.delete_btn.setObjectName("dangerButton")
        self.delete_btn.clicked.connect(self._delete_record)
        action_layout.addWidget(self.delete_btn)
        
        list_layout.addLayout(action_layout)
        layout.addWidget(list_group)
        layout.setStretch(0, 0)
        layout.setStretch(1, 1)

        self._refresh_customers()
        self._update_button_states()

    def _export_pdf(self):
        filename, _ = QFileDialog.getSaveFileName(self, "PDF Olarak Kaydet", f"{self.service_def.name}_Listesi.pdf", "PDF Files (*.pdf)")
        if not filename: return
        headers = []
        for i in range(self.table.columnCount()): headers.append(self.table.horizontalHeaderItem(i).text())
        data_rows = []
        for row in range(self.table.rowCount()):
            row_data = []
            for col in range(self.table.columnCount()):
                item = self.table.item(row, col)
                row_data.append(item.text() if item else "")
            data_rows.append(row_data)
        summary_data = {
            "Rapor Turu": f"{self.service_def.name} Hizmet Listesi",
            "Tarih": datetime.now().strftime("%d.%m.%Y"),
            "Toplam Kayit": str(len(data_rows))
        }
        self.main_app.pdf_report_generator.generate_report(f"{self.service_def.name} Raporu", headers, data_rows, summary_data, filename)

    def _export_excel(self):
        filename, _ = QFileDialog.getSaveFileName(self, "Excel Olarak Kaydet", f"{self.service_def.name}_Listesi.xlsx", "Excel Files (*.xlsx)")
        if not filename: return
        headers = []
        for i in range(self.table.columnCount()): headers.append(self.table.horizontalHeaderItem(i).text())
        data_rows = []
        for row in range(self.table.rowCount()):
            row_data = []
            for col in range(self.table.columnCount()):
                item = self.table.item(row, col)
                row_data.append(item.text() if item else "")
            data_rows.append(row_data)
        summary_data = {
            "Rapor Turu": f"{self.service_def.name} Hizmet Listesi",
            "Tarih": datetime.now().strftime("%d.%m.%Y"),
            "Toplam Kayit": str(len(data_rows))
        }
        self.main_app.excel_report_generator.generate_report(f"{self.service_def.name} Raporu", headers, data_rows, summary_data, filename)

    def _refresh_customers(self):
        if not hasattr(self, 'filter_combo') or not hasattr(self, 'customer_combo'): return
        persons = self.main_app.person_manager.get_person_names()
        curr_text = self.customer_combo.currentText()
        self.customer_combo.clear()
        self.customer_combo.addItems([""] + persons)
        self.customer_combo.setEditText(curr_text)
        completer = QCompleter(persons)
        completer.setCaseSensitivity(Qt.CaseSensitivity.CaseInsensitive)
        completer.setFilterMode(Qt.MatchFlag.MatchContains)
        self.customer_combo.setCompleter(completer)
        self.filter_combo.blockSignals(True)
        self.filter_combo.clear()
        self.filter_combo.addItem(self.main_app.lang.get("show_all", "Show All"))
        self.filter_combo.addItems(persons)
        self.filter_combo.setCompleter(completer)
        self.filter_combo.blockSignals(False)

    def _load_data(self):
        filter_name = self.filter_combo.currentText()
        show_all = (filter_name == "Tumunu Goster" or filter_name == "")
        jobs = self.manager.get_jobs_by_def_id(self.service_def.id)
        jobs.sort(key=lambda x: datetime.strptime(x.start_date, "%d.%m.%Y") if x.start_date else datetime.min, reverse=True)
        filtered_jobs = [j for j in jobs if show_all or j.customer_name == filter_name]
        
        self.table.setRowCount(0)
        self.table.setRowCount(len(filtered_jobs))
        cols = self.service_def.custom_columns
        if isinstance(cols, str):
            try: cols = json.loads(cols)
            except: cols = []
            
        # Dinamik renk bulma islemi
        stages = self.service_def.stages
        second_to_last = stages[-2] if len(stages) > 1 else "Hazir"
        
        for row, job in enumerate(filtered_jobs):
            col = 0
            self.table.setItem(row, col, QTableWidgetItem(job.customer_name)); col += 1
            self.table.setItem(row, col, QTableWidgetItem(job.description)); col += 1
            self.table.setItem(row, col, QTableWidgetItem(job.start_date)); col += 1
            fee_str = f"{format_number(job.fee)} {job.currency}"
            self.table.setItem(row, col, QTableWidgetItem(fee_str)); col += 1
            
            dyn_data = job.dynamic_data
            if isinstance(dyn_data, str):
                try: dyn_data = json.loads(dyn_data)
                except: dyn_data = {}
            if not isinstance(dyn_data, dict): dyn_data = {}
            
            for key in cols:
                if key == "Tarih": continue
                val = dyn_data.get(key, "")
                self.table.setItem(row, col, QTableWidgetItem(str(val))); col += 1
                
            status_item = QTableWidgetItem(job.status)
            if job.status == "Teslim Edildi": status_item.setForeground(QColor("gray"))
            elif job.status == second_to_last: status_item.setForeground(QColor("green"))
            else: status_item.setForeground(QColor("blue"))
            font = status_item.font(); font.setBold(True); status_item.setFont(font)
            
            self.table.setItem(row, col, status_item); col += 1
            self.table.item(row, 0).setData(Qt.ItemDataRole.UserRole, job.id)

    def _on_row_selected(self):
        selected_items = self.table.selectedItems()
        if not selected_items:
            self._update_button_states()
            return
        row = selected_items[0].row()
        job_id = self.table.item(row, 0).data(Qt.ItemDataRole.UserRole)
        job = next((j for j in self.manager.jobs if j.id == job_id), None)
        if not job: return
        
        self.current_job_id = job_id
        self.customer_combo.setEditText(job.customer_name)
        self.desc_edit.setText(job.description)
        self.fee_spin.setValue(job.fee)
        self.currency_combo.setCurrentText(job.currency)
        if job.start_date:
            try: self.date_edit.setDate(QDate.fromString(job.start_date, "dd.MM.yyyy"))
            except: pass
            
        dyn_data = job.dynamic_data
        if isinstance(dyn_data, str):
            try: dyn_data = json.loads(dyn_data)
            except: dyn_data = {}
        if not isinstance(dyn_data, dict): dyn_data = {}
        
        for key, inp in self.dynamic_inputs.items():
            val = dyn_data.get(key, "")
            if isinstance(inp, QDateEdit):
                try: inp.setDate(QDate.fromString(val, "dd.MM.yyyy"))
                except: pass
            elif isinstance(inp, QLineEdit):
                inp.setText(str(val))
                
        self.form_group.setTitle(f"Kaydi Duzenle: {job.customer_name}")
        self.add_update_btn.setText("Guncelle")
        self.add_update_btn.setIcon(QIcon.fromTheme("document-save"))
        self._update_button_states()

    def _save_record(self):
        customer = self.customer_combo.currentText().strip()
        if not customer:
            QMessageBox.warning(self, "Eksik Bilgi", "Musteri adi zorunludur.")
            return
            
        record_date = self.date_edit.date().toString("dd.MM.yyyy")
        dyn_data = {}
        for key, inp in self.dynamic_inputs.items():
            if isinstance(inp, QDateEdit): dyn_data[key] = inp.date().toString("dd.MM.yyyy")
            else: dyn_data[key] = inp.text().strip()
            
        if self.current_job_id:
            self.manager.update_job(self.current_job_id, {
                "customer_name": customer, "description": self.desc_edit.text().strip(),
                "fee": self.fee_spin.value(), "currency": self.currency_combo.currentText(),
                "dynamic_data_json": json.dumps(dyn_data), "start_date": record_date
            })
            self.main_app._show_status_message("Kayit guncellendi.")
        else:
            first_stage = self.service_def.stages[0] if self.service_def.stages else "Alindi"
            new_job = ServiceJob(
                service_def_id=self.service_def.id, customer_name=customer,
                description=self.desc_edit.text().strip(), status=first_stage,
                fee=self.fee_spin.value(), currency=self.currency_combo.currentText(),
                dynamic_data=dyn_data, start_date=record_date
            )
            self.manager.add_job(new_job)
            self.main_app._show_status_message("Yeni kayit eklendi.")
            
        self._clear_form()
        self._load_data()

    def _clear_form(self):
        self.current_job_id = None
        self.customer_combo.setCurrentIndex(-1)
        self.customer_combo.setEditText("")
        self.desc_edit.clear()
        self.fee_spin.setValue(0)
        self.currency_combo.setCurrentText(self.main_app.display_currency)
        self.date_edit.setDate(QDate.currentDate())
        
        for inp in self.dynamic_inputs.values():
            if isinstance(inp, QDateEdit): inp.setDate(QDate.currentDate())
            elif isinstance(inp, QLineEdit): inp.clear()
            
        self.form_group.setTitle(f"Yeni {self.service_def.name} Kaydi")
        self.add_update_btn.setText("Ekle")
        self.add_update_btn.setIcon(QIcon.fromTheme("list-add"))
        self.table.clearSelection()
        self._update_button_states()

    def _update_button_states(self):
        has_selection = len(self.table.selectedItems()) > 0
        self.change_status_btn.setEnabled(has_selection)
        self.deliver_btn.setEnabled(has_selection)
        self.delete_btn.setEnabled(has_selection)

    def _get_selected_job(self) -> Optional[ServiceJob]:
        selected_items = self.table.selectedItems()
        if not selected_items: return None
        row = selected_items[0].row()
        job_id = self.table.item(row, 0).data(Qt.ItemDataRole.UserRole)
        return next((j for j in self.manager.jobs if j.id == job_id), None)

    def _change_status(self):
        job = self._get_selected_job()
        if not job: return
        new_status = self.status_action_combo.currentText()
        if job.status == new_status: return
        updates = {"status": new_status}
        if new_status == "Teslim Edildi":
            updates["delivery_date"] = datetime.now().strftime("%d.%m.%Y")
        self.manager.update_job(job.id, updates)
        self._load_data()
        self.main_app._show_status_message(f"Durum guncellendi: {new_status}")

    def _delete_record(self):
        job = self._get_selected_job()
        if not job: return
        if QMessageBox.question(self, "Sil", "Bu kaydi silmek istediginize emin misiniz?") == QMessageBox.StandardButton.Yes:
            self.manager.delete_job(job.id)
            self._load_data()
            self._clear_form()
            self.main_app._show_status_message("Kayit silindi.")

    def _deliver_and_pay(self):
        job = self._get_selected_job()
        if not job: return
        if job.status == "Teslim Edildi":
            QMessageBox.information(self, "Bilgi", "Bu is zaten teslim edilmis.")
            return
            
        if job.fee <= 0:
            if QMessageBox.question(self, "Ucretsiz Teslimat", "Ucret 0.00 gorunuyor. Tahsilat yapmadan teslim edilsin mi?") == QMessageBox.StandardButton.Yes:
                self.manager.update_job(job.id, {"status": "Teslim Edildi", "delivery_date": datetime.now().strftime("%d.%m.%Y")})
                self._load_data()
            return
            
        payment_dialog = PaymentDialog(
            total_amount=job.fee,
            display_currency=job.currency,
            person_name=job.customer_name,
            cash_accounts=self.main_app._get_accessible_cash_accounts(),
            card_accounts=self.main_app._get_accessible_card_accounts(),
            depot_manager=self.main_app.depot_manager,
            product_manager=self.main_app.product_manager,
            stock_manager=self.main_app.stock_manager,
            lang=self.main_app.lang,
            currency_manager=self.main_app.currency_manager,
            allowed_depots=self.main_app._get_accessible_depots(),
            product_trade_direction="in",
            allow_installments=False, # Taksit hizmetlerde yok.
            parent=self
        )
        
        if not payment_dialog.exec(): return
        try:
            breakdown = payment_dialog.get_payment_breakdown()
            trans_date = datetime.now().strftime("%d.%m.%Y")
            iso_date = datetime.now().isoformat()
            service_desc = f"Hizmet Bedeli ({self.service_def.name}) - {job.description}"
            db = self.main_app.data_manager.db
            
            with db.transaction_scope() as cursor:
                self.main_app.customer_history_manager.add_item(
                    CustomerHistoryEvent(
                        person_full_name=job.customer_name, event_date=iso_date,
                        event_type="Hizmet (Borclandirma)", debt_original=job.fee, credit_original=0,
                        currency=job.currency, description=service_desc, related_id=job.id,
                    ), cursor=cursor,
                )
                
                for p in breakdown:
                    method = p["method_type"]
                    if method == "On Credit":
                        continue
                    amt = p.get("amount", p.get("total_val", 0))
                    curr = p.get("currency", self.main_app.display_currency)
                    base_amt = float(
                        p.get(
                            "base_amount",
                            self.main_app.currency_manager._convert_to_base_currency(amt, curr)
                        ) or 0.0
                    )
                    desc = f"Hizmet Tahsilati ({self.service_def.name})"
                    
                    if method in ["cash", "card"]:
                        manager = self.main_app.cash_managers.get(p["account_id"]) if method == "cash" else self.main_app.card_managers.get(p["account_id"])
                        if manager:
                            fin_trans = FinancialTransaction(
                                transaction_date=trans_date, transaction_type="Income", original_amount=amt,
                                currency=curr, base_amount=base_amt, description=f"{desc} - {job.customer_name}", person_full_name=job.customer_name,
                            )
                            manager.add_item(fin_trans, cursor=cursor)
                            self.main_app.customer_history_manager.add_item(
                                CustomerHistoryEvent(
                                    person_full_name=job.customer_name, event_date=iso_date, event_type="Hizmet Tahsilati",
                                    credit_original=amt, debt_original=0, currency=curr,
                                    description=f"{desc} ({p.get('account_name','Kasa')})", related_id=fin_trans.id,
                                ), cursor=cursor,
                            )
                    elif method == "product":
                        prod_name = p.get("account_id")
                        depot = p.get("depot_name", get_default_depot_name())
                        gold_details = p.get("gold_details") or []
                        p_def = self.main_app.product_manager.find_by_attribute("product_name", prod_name)
                        p_base = 0
                        if p_def: p_base = self.main_app.currency_manager._convert_to_base_currency(p_def.default_purchase_price, p_def.purchase_currency)
                        if gold_details:
                            for detail in gold_details:
                                barcode = str(detail.get("barcode") or "").strip()
                                gram_val = float(detail.get("gram") or 0)
                                karat_val = str(detail.get("karat") or "").strip()
                                if not barcode or gram_val <= 0:
                                    continue
                                self.main_app.stock_manager.add_item(StockItem(
                                    item_type=prod_name,
                                    quantity=1.0,
                                    quantity_gr=gram_val,
                                    unique_barcode=barcode,
                                    depot_name=depot,
                                    purchase_price_base=p_base,
                                ), cursor=cursor)
                                self.main_app.barcode_history_manager.register_buy(
                                    barcode=barcode,
                                    p_type=prod_name,
                                    gram=gram_val,
                                    karat=karat_val,
                                    source=job.customer_name,
                                    price=p_base,
                                    method="Hizmet Tahsilatı (Takas)",
                                    cursor=cursor,
                                )
                        else:
                            self.main_app.stock_manager.add_or_update_stock(prod_name, amt, p_base, depot, cursor=cursor)
                        self.main_app.customer_history_manager.add_item(
                            CustomerHistoryEvent(
                                person_full_name=job.customer_name, event_date=iso_date, event_type="Hizmet Tahsilati (Takas)",
                                credit_original=amt, debt_original=0, currency=curr,
                                description=f"{desc} - {amt} {prod_name} alindi", related_id=None,
                            ), cursor=cursor,
                        )
                        
                self.manager.job_manager.update_item(job.id, {"status": "Teslim Edildi", "delivery_date": trans_date}, cursor=cursor)
                
            self.main_app.refresh_cash_table()
            self.main_app.refresh_current_account_table()
            self.main_app.refresh_dashboard_cards()
            self._load_data()
            QMessageBox.information(self, "Basarili", "Hizmet teslim edildi ve tahsilat islendi.")
        except Exception as e:
            logger.error(f"Hizmet teslim hatasi: {e}")
            QMessageBox.critical(self, "Hata", f"Islem sirasinda hata olustu: {e}")

class ServiceDefDialog(QDialog):
    """
    [AI_DOC]
    Yeni Hizmet Turu Tanimlama (Popup)
    FAZ 5: Bu pencereye Asamalar (Durumlar) ekleme ve silme listesi eklendi.
    "Teslim Edildi" asamasi sabittir ve silinemez.
    [/AI_DOC]
    """
    def __init__(self, parent=None):
        super().__init__(parent)
        self.lang = parent.main_app.lang if hasattr(parent, "main_app") else getattr(parent, "lang", {})
        self.setWindowTitle(self.lang.get("define_new_service", "Define New Service Type"))
        self.setMinimumWidth(450)
        self.setMinimumHeight(450)
        layout = QVBoxLayout(self)
        
        form_layout = QFormLayout()
        self.name_edit = QLineEdit()
        self.name_edit.setPlaceholderText(self.lang.get("service_name_ph", "e.g. Repair, Custom Order, Diamond Setting"))
        form_layout.addRow(self.lang.get("service_name_colon", "Service Name:"), self.name_edit)
        layout.addLayout(form_layout)
        
        # --- OZEL ALANLAR (Custom Columns) ---
        col_group = QGroupBox(self.lang.get("custom_fields", "Custom Fields (Information requested from Customer)"))
        col_layout = QVBoxLayout(col_group)
        self.col_list = QListWidget()
        col_layout.addWidget(self.col_list)
        
        btn_layout = QHBoxLayout()
        add_col_btn = QPushButton(self.lang.get("add_field", "Add Field"))
        add_col_btn.clicked.connect(self._add_column)
        del_col_btn = QPushButton(self.lang.get("delete_field", "Delete Field"))
        del_col_btn.clicked.connect(self._del_column)
        btn_layout.addWidget(add_col_btn)
        btn_layout.addWidget(del_col_btn)
        col_layout.addLayout(btn_layout)
        layout.addWidget(col_group)

        # --- ASAMALAR (Stages) - FAZ 5 YENI ---
        stage_group = QGroupBox(self.lang.get("stages_workflow", "Stages / Statuses (Workflow)"))
        stage_layout = QVBoxLayout(stage_group)
        self.stage_list = QListWidget()
        self.stage_list.addItems(["Alindi", "Islemde", "Hazir", "Teslim Edildi"])
        stage_layout.addWidget(self.stage_list)
        
        btn_layout2 = QHBoxLayout()
        add_stage_btn = QPushButton(self.lang.get("add_stage", "Add Stage"))
        add_stage_btn.clicked.connect(self._add_stage)
        del_stage_btn = QPushButton(self.lang.get("delete_stage", "Delete Stage"))
        del_stage_btn.clicked.connect(self._del_stage)
        btn_layout2.addWidget(add_stage_btn)
        btn_layout2.addWidget(del_stage_btn)
        stage_layout.addLayout(btn_layout2)
        layout.addWidget(stage_group)

        buttons = QDialogButtonBox(QDialogButtonBox.StandardButton.Ok | QDialogButtonBox.StandardButton.Cancel)
        buttons.accepted.connect(self.accept)
        buttons.rejected.connect(self.reject)
        ok_btn = buttons.button(QDialogButtonBox.StandardButton.Ok)
        if ok_btn:
            ok_btn.setDefault(True)
            ok_btn.setAutoDefault(True)
        self.name_edit.returnPressed.connect(self.accept)
        layout.addWidget(buttons)

    def _add_column(self):
        text, ok = QInputDialog.getText(self, "Alan Ekle", "Kolon Adi (Orn: Model No, Renk, Boyut):")
        if ok and text:
            self.col_list.addItem(text)

    def _del_column(self):
        row = self.col_list.currentRow()
        if row >= 0:
            self.col_list.takeItem(row)

    def _add_stage(self):
        text, ok = QInputDialog.getText(self, "Asama Ekle", "Asama Adi (Orn: Cilada, Atolyeye Gonderildi):")
        if ok and text:
            # Her zaman 'Teslim Edildi'nin (son asama) bir oncesine ekle
            count = self.stage_list.count()
            if count > 0 and self.stage_list.item(count-1).text() == "Teslim Edildi":
                self.stage_list.insertItem(count-1, text)
            else:
                self.stage_list.addItem(text)

    def _del_stage(self):
        row = self.stage_list.currentRow()
        if row >= 0:
            item = self.stage_list.item(row)
            if item.text() == "Teslim Edildi":
                QMessageBox.warning(self, "Uyari", "'Teslim Edildi' asamasi sistemin ana kapatma mekanizmasidir, silinemez!")
                return
            self.stage_list.takeItem(row)

    def get_data(self) -> ServiceDefinition:
        cols = [self.col_list.item(i).text() for i in range(self.col_list.count())]
        stages = [self.stage_list.item(i).text() for i in range(self.stage_list.count())]
        
        # Teslim edildi garanti olsun
        if "Teslim Edildi" not in stages:
            stages.append("Teslim Edildi")
            
        return ServiceDefinition(name=self.name_edit.text().strip(), custom_columns=cols, stages=stages)

class ServicesWidget(QWidget):
    """Ana Hizmetler Konteyneri"""
    def __init__(self, main_app):
        super().__init__()
        self.main_app = main_app
        self.manager = ServiceManager(main_app.data_manager)
        self._init_ui()

    def _init_ui(self):
        main_layout = QVBoxLayout(self)
        top_layout = QHBoxLayout()
        top_layout.addWidget(QLabel(self.main_app.lang.get("services_workshop_title", "<h2>Services & Workshop Operations</h2>")))
        top_layout.addStretch()
        
        add_type_btn = QPushButton(self.main_app.lang.get("define_new_service_btn", "Define New Service Type"))
        add_type_btn.setIcon(QIcon.fromTheme("list-add"))
        add_type_btn.clicked.connect(self._add_service_type)
        top_layout.addWidget(add_type_btn)
        
        del_type_btn = QPushButton(self.main_app.lang.get("delete_service_type_btn", "Delete Service Type"))
        del_type_btn.setObjectName("dangerButton")
        del_type_btn.setIcon(QIcon.fromTheme("edit-delete"))
        del_type_btn.clicked.connect(self._delete_current_service_type)
        top_layout.addWidget(del_type_btn)
        
        main_layout.addLayout(top_layout)
        self.tabs = QTabWidget()
        main_layout.addWidget(self.tabs)
        self._refresh_tabs()

    def _refresh_tabs(self):
        current_index = self.tabs.currentIndex()
        self.tabs.clear()
        for s_def in self.manager.definitions:
            tab_widget = ServiceTabWidget(self.main_app, s_def, self.manager)
            self.tabs.addTab(tab_widget, s_def.name)
            
        if current_index >= 0 and current_index < self.tabs.count():
            self.tabs.setCurrentIndex(current_index)
        elif self.tabs.count() > 0:
            self.tabs.setCurrentIndex(0)

    def _add_service_type(self):
        dialog = ServiceDefDialog(self)
        if dialog.exec():
            definition = dialog.get_data()
            if definition.name:
                self.manager.add_definition(definition)
                self._refresh_tabs()
                self.main_app.reload_definition_tables()
                self.tabs.setCurrentIndex(self.tabs.count() - 1)

    def _delete_current_service_type(self):
        idx = self.tabs.currentIndex()
        if idx < 0:
            QMessageBox.warning(self, "Uyari", "Silinecek bir hizmet turu yok.")
            return
        current_tab = self.tabs.widget(idx)
        if not current_tab: return
        service_def = current_tab.service_def
        msg = f"'{service_def.name}' hizmet turunu ve icindeki TUM kayitlari silmek istediginize emin misiniz?\n\n(Not: Bu hizmete ait gecmis finansal kasa/stok hareketleri korunacaktir.)"
        
        if QMessageBox.question(self, "Hizmet Turunu Sil", msg) == QMessageBox.StandardButton.Yes:
            self.manager.delete_definition(service_def.id)
            self._refresh_tabs()
            self.main_app.reload_definition_tables()
            self.main_app._show_status_message(f"'{service_def.name}' hizmeti silindi.")




