# -*- coding: utf-8 -*-
# Copyright 2024-2025 Nexa Systems Inc.
# License OPL-1 (Odoo Proprietary License v1.0)
# Part of the Fusion Claim Assistant product family.

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


class AccountPaymentRegister(models.TransientModel):
    _inherit = 'account.payment.register'

    x_fc_card_last_four = fields.Char(
        string='Card Last 4 Digits',
        size=4,
        help='Enter last 4 digits of the card used for payment (required for card payments)',
    )
    
    x_fc_payment_note = fields.Char(
        string='Payment Note',
        help='Additional note for this payment',
    )
    
    x_fc_is_card_payment = fields.Boolean(
        string='Is Card Payment',
        compute='_compute_is_card_payment',
        help='True if payment method is Credit Card or Debit Card',
    )

    @api.depends('payment_method_line_id', 'payment_method_line_id.x_fc_requires_card_digits')
    def _compute_is_card_payment(self):
        """Check if the selected payment method requires card digits.
        
        Uses the x_fc_requires_card_digits flag on payment method line.
        Falls back to keyword matching if field not set.
        """
        card_keywords = ['credit', 'debit', 'visa', 'mastercard', 'amex']
        for wizard in self:
            is_card = False
            if wizard.payment_method_line_id:
                # First check the explicit flag
                if hasattr(wizard.payment_method_line_id, 'x_fc_requires_card_digits'):
                    is_card = wizard.payment_method_line_id.x_fc_requires_card_digits
                # Fallback to keyword matching if flag not explicitly set
                if not is_card and wizard.payment_method_line_id.name:
                    method_name = wizard.payment_method_line_id.name.lower()
                    is_card = any(keyword in method_name for keyword in card_keywords)
            wizard.x_fc_is_card_payment = is_card

    def action_create_payments(self):
        """Override to validate card number is entered for card payments."""
        # Validate card number for card payments
        if self.x_fc_is_card_payment and not self.x_fc_card_last_four:
            raise UserError(
                "Card Last 4 Digits is required for Credit Card and Debit Card payments.\n\n"
                "Please enter the last 4 digits of the card used for this payment."
            )
        
        # Validate card number format (must be exactly 4 digits)
        if self.x_fc_card_last_four:
            if not self.x_fc_card_last_four.isdigit() or len(self.x_fc_card_last_four) != 4:
                raise UserError(
                    "Card Last 4 Digits must be exactly 4 numeric digits.\n\n"
                    "Example: 1234"
                )
        
        return super().action_create_payments()

    def _create_payment_vals_from_wizard(self, batch_result):
        """Override to add card info to payment values."""
        vals = super()._create_payment_vals_from_wizard(batch_result)
        
        # Add our custom fields
        if self.x_fc_card_last_four:
            vals['x_fc_card_last_four'] = self.x_fc_card_last_four
        if self.x_fc_payment_note:
            vals['x_fc_payment_note'] = self.x_fc_payment_note
            
        return vals
