from odoo import models, fields, api


class SaleOrder(models.Model):
    _inherit = 'sale.order'


    def write(self,vals):
    
        res = super(SaleOrder, self).write(vals)
        
        if self.state=='sale':
            
            #on recherche si le devis est lié à une booking inscription
            event_registration=self.env['event.registration'].search(['|','|',('order_id','=',int(self.id)),('down_payment_order_id','=',int(self.id)),('balance_order_id','=',int(self.id))])
            #event_registration=self.env['event.registration'].search([('order_id','=',int(self.id))])
            
            if event_registration:
                
                if event_registration.payment_status=='paid':
                    amount=0
                    for option in event_registration.option_ids:
                        prd=self.env['product.product'].search([('id','=',int(option.booking_option_id)),('donation','=',True)])
                        if prd:
                            #au niveau de l'événement,on recherche le montant du don en fonction du statut:
                            booking_option=self.env['booking.option'].search([('event_id','=',int(event_registration.event_id)),('booking_option_id','=',int(option.booking_option_id))])
                            if booking_option:
                                if event_registration.partner_id.member_status=='not member' : amount=booking_option.booking_option_price
                                if event_registration.partner_id.member_status=='member': amount=booking_option.booking_option_member_price
                                if event_registration.partner_id.member_status=='super member': amount=booking_option.booking_option_super_member_price


                            self.env['event.registration'].create_donation(event_registration.id,event_registration.partner_id,option.booking_option_id,amount)
                    
                        



        