from odoo import models, fields, api


class LaundrySettings(models.TransientModel):
    """Laundry Management settings panel (PART 9).

    Extends res.config.settings to add laundry-specific configuration:
    - WhatsApp Business API credentials and behaviour
    - Commission tracking rates, rules, and default account
    - Session enforcement and default cash journal
    - Print format defaults
    - Cash control: default difference account
    """
    _inherit = 'res.config.settings'

    # ── WhatsApp ──────────────────────────────────────────────────────
    laundry_wa_token = fields.Char(
        string='WhatsApp Cloud API Token',
        config_parameter='laundry.whatsapp_api_token',
    )
    laundry_wa_phone_id = fields.Char(
        string='Phone Number ID',
        config_parameter='laundry.whatsapp_phone_id',
    )
    laundry_wa_store_number = fields.Char(
        string='Store WhatsApp Number',
        config_parameter='laundry.whatsapp_store_number',
        help='E.164 format without + (e.g. 966501234567). Used as fallback number.',
    )
    laundry_wa_auto_send = fields.Boolean(
        string='Auto-send WhatsApp on Order Confirm',
    )

    # ── Commission ────────────────────────────────────────────────────
    laundry_commission_enabled = fields.Boolean(
        string='Enable Staff Commission Tracking',
    )
    laundry_commission_type = fields.Selection([
        ('percentage', 'Percentage of Order Total (%)'),
        ('fixed',      'Fixed Amount per Order'),
    ], string='Commission Type')
    laundry_commission_reception_rate = fields.Float(
        string='Reception Commission', digits=(10, 2),
    )
    laundry_commission_processing_rate = fields.Float(
        string='Processing Commission', digits=(10, 2),
    )
    laundry_commission_delivery_rate = fields.Float(
        string='Delivery Commission', digits=(10, 2),
    )
    laundry_commission_account_id = fields.Many2one(
        'account.account',
        string='Commission Expense Account',
        domain="[('account_type', 'in', ['expense', 'expense_direct_cost']), ('company_ids', 'in', [company_id])]",
        help='Account for booking commission expenses (for future accounting integration).',
    )

    # ── Session / Cash Control ────────────────────────────────────────
    laundry_require_session = fields.Boolean(
        string='Require Open Session to Confirm Orders',
    )
    laundry_cash_journal_id = fields.Many2one(
        'account.journal',
        string='Default Cash Journal',
        domain="[('type', '=', 'cash'), ('company_id', '=', company_id)]",
        help='Default cash journal used in the payment wizard.',
    )
    laundry_difference_account_id = fields.Many2one(
        'account.account',
        string='Cash Difference Account',
        domain="[('company_ids', 'in', [company_id])]",
        help='Default account for posting session cash count variances.',
    )

    # ── Print ─────────────────────────────────────────────────────────
    laundry_default_paper = fields.Selection([
        ('a4',      'A4 Full Receipt'),
        ('thermal', 'Thermal / 80mm Roll'),
    ], string='Default Print Format')

    # company_id helper for domain filtering
    company_id = fields.Many2one(
        'res.company', string='Company',
        default=lambda self: self.env.company,
        readonly=True,
    )

    # ── Load & Save ───────────────────────────────────────────────────
    def get_values(self):
        res = super().get_values()
        ICP = self.env['ir.config_parameter'].sudo()

        def _bool(key, default='False'):
            return ICP.get_param(key, default) == 'True'

        def _float(key, default='0.0'):
            try:
                return float(ICP.get_param(key, default))
            except (ValueError, TypeError):
                return 0.0

        def _int_record(key):
            val = ICP.get_param(key, '')
            try:
                return int(val) if val else False
            except (ValueError, TypeError):
                return False

        res.update({
            'laundry_wa_auto_send':                  _bool('laundry_management.wa_auto_send'),
            'laundry_commission_enabled':             _bool('laundry_management.commission_enabled'),
            'laundry_commission_type':                ICP.get_param('laundry_management.commission_type', 'percentage'),
            'laundry_commission_reception_rate':      _float('laundry_management.commission_reception_rate'),
            'laundry_commission_processing_rate':     _float('laundry_management.commission_processing_rate'),
            'laundry_commission_delivery_rate':       _float('laundry_management.commission_delivery_rate'),
            'laundry_commission_account_id':          _int_record('laundry_management.commission_account_id'),
            'laundry_require_session':                _bool('laundry_management.require_session'),
            'laundry_cash_journal_id':                _int_record('laundry_management.cash_journal_id'),
            'laundry_difference_account_id':          _int_record('laundry_management.difference_account_id'),
            'laundry_default_paper':                  ICP.get_param('laundry_management.default_paper', 'a4'),
        })
        return res

    def set_values(self):
        super().set_values()
        ICP = self.env['ir.config_parameter'].sudo()
        ICP.set_param('laundry_management.wa_auto_send',                 str(self.laundry_wa_auto_send))
        ICP.set_param('laundry_management.commission_enabled',           str(self.laundry_commission_enabled))
        ICP.set_param('laundry_management.commission_type',              self.laundry_commission_type or 'percentage')
        ICP.set_param('laundry_management.commission_reception_rate',    str(self.laundry_commission_reception_rate))
        ICP.set_param('laundry_management.commission_processing_rate',   str(self.laundry_commission_processing_rate))
        ICP.set_param('laundry_management.commission_delivery_rate',     str(self.laundry_commission_delivery_rate))
        ICP.set_param('laundry_management.commission_account_id',        str(self.laundry_commission_account_id.id or ''))
        ICP.set_param('laundry_management.require_session',              str(self.laundry_require_session))
        ICP.set_param('laundry_management.cash_journal_id',              str(self.laundry_cash_journal_id.id or ''))
        ICP.set_param('laundry_management.difference_account_id',        str(self.laundry_difference_account_id.id or ''))
        ICP.set_param('laundry_management.default_paper',                self.laundry_default_paper or 'a4')
