# -*- coding: utf-8 -*-
"""
Cheque Number Wizard
====================
Wizard to allow changing cheque number before printing.
"""

from odoo import api, fields, models, _
from odoo.exceptions import UserError


class ChequeNumberWizard(models.TransientModel):
    """Wizard to set cheque number before printing."""
    _name = 'payroll.cheque.number.wizard'
    _description = 'Cheque Number Wizard'

    cheque_id = fields.Many2one(
        'payroll.cheque',
        string='Cheque',
        required=True,
        readonly=True,
    )
    cheque_number = fields.Char(
        string='Cheque Number',
        required=True,
        help='Enter the cheque number to use for this cheque',
    )
    employee_name = fields.Char(
        string='Employee',
        related='cheque_id.employee_id.name',
        readonly=True,
    )
    amount = fields.Monetary(
        string='Amount',
        related='cheque_id.amount',
        readonly=True,
        currency_field='currency_id',
    )
    currency_id = fields.Many2one(
        'res.currency',
        related='cheque_id.currency_id',
        readonly=True,
    )

    @api.model
    def default_get(self, fields_list):
        """Load current cheque number or suggest next available number."""
        res = super().default_get(fields_list)
        cheque_id = self.env.context.get('default_cheque_id')
        if cheque_id:
            cheque = self.env['payroll.cheque'].browse(cheque_id)
            if cheque.exists():
                if cheque.cheque_number:
                    # Use existing cheque number
                    res['cheque_number'] = cheque.cheque_number
                else:
                    # Suggest next available number
                    res['cheque_number'] = self._get_next_cheque_number(cheque.company_id.id)
        return res
    
    def _get_next_cheque_number(self, company_id):
        """Get the next available cheque number by checking all sources."""
        max_num = 0
        
        # Check payroll cheques
        payroll_cheques = self.env['payroll.cheque'].search([
            ('cheque_number', '!=', False),
            ('cheque_number', '!=', ''),
            ('company_id', '=', company_id),
        ])
        for cheque in payroll_cheques:
            try:
                num = int(cheque.cheque_number)
                if num > max_num:
                    max_num = num
            except (ValueError, TypeError):
                pass
        
        # Check vendor payments (account.payment)
        if 'account.payment' in self.env:
            payments = self.env['account.payment'].search([
                ('check_number', '!=', False),
                ('check_number', '!=', ''),
                ('company_id', '=', company_id),
            ])
            for payment in payments:
                try:
                    num = int(payment.check_number)
                    if num > max_num:
                        max_num = num
                except (ValueError, TypeError):
                    pass
        
        next_num = max_num + 1
        return str(next_num).zfill(6)

    def action_confirm(self):
        """Save cheque number and print."""
        self.ensure_one()
        
        if not self.cheque_number:
            raise UserError(_('Please enter a cheque number.'))
        
        # Check if cheque number already exists
        existing = self.env['payroll.cheque'].search([
            ('cheque_number', '=', self.cheque_number),
            ('id', '!=', self.cheque_id.id),
            ('company_id', '=', self.cheque_id.company_id.id),
        ])
        if existing:
            raise UserError(_('Cheque number %s is already used by another cheque.') % self.cheque_number)
        
        # Check account.payment for vendor cheques
        payment_check = self.env['account.payment'].search([
            ('check_number', '=', self.cheque_number),
            ('company_id', '=', self.cheque_id.company_id.id),
        ], limit=1)
        if payment_check:
            raise UserError(_('Cheque number %s is already used by a vendor payment.') % self.cheque_number)
        
        # Update cheque number
        self.cheque_id.write({
            'cheque_number': self.cheque_number,
        })
        
        # Mark as printed and print
        self.cheque_id.write({
            'state': 'printed',
            'printed_date': fields.Datetime.now(),
        })
        
        return self.env.ref('fusion_payroll.action_report_payroll_cheque').report_action(self.cheque_id)
