# -*- coding: utf-8 -*-
from odoo import http,_
from odoo.http import request
from odoo import models, fields, api
import werkzeug
from datetime import datetime
from odoo.tools import format_datetime, format_date, is_html_empty
from dateutil.relativedelta import relativedelta
from odoo.exceptions import UserError
from odoo.addons.website_event.controllers.main import WebsiteEventController
from odoo.addons.payment.controllers.portal import PaymentProcessing
from odoo.addons.sale.controllers.portal import CustomerPortal
from odoo.addons.portal.controllers.portal import pager as portal_pager, get_records_pager
import json

class kalachakra_event(WebsiteEventController,PaymentProcessing):

    def _extract_searched_event_tags(self, searches):
        tags = request.env['event.tag']
        
        if searches.get('tags'):
          
            tags = request.env['event.tag'].search([('name', '=', searches['tags'])])
        return tags
    
    @http.route(['/event/calendar'], type='http', auth='public', website=True, sitemap=False,csrf=False)
    def eventCalendar(self,**post):
        url='https://calendar.google.com/calendar/embed?height=600&wkst=2&bgcolor=%23ffffff&ctz=Europe%2FParis&mode=WEEK&src=aXRrYWxhY2hha3JhQGdtYWlsLmNvbQ&src=bjYxODA1OXQ2dmRwNmp0Y3Foa3FjMTMwdWtAZ3JvdXAuY2FsZW5kYXIuZ29vZ2xlLmNvbQ&src=MnJzc2VvY3MzcGNiaDliaGFvNXZ1a3JpM3NAZ3JvdXAuY2FsZW5kYXIuZ29vZ2xlLmNvbQ&src=cGJ0YjBtbTBja2NsMDZmdTNvb2ViMDJpOXNAZ3JvdXAuY2FsZW5kYXIuZ29vZ2xlLmNvbQ&src=ZnIuZnJlbmNoI2hvbGlkYXlAZ3JvdXAudi5jYWxlbmRhci5nb29nbGUuY29t&color=%23039BE5&color=%238E24AA&color=%23E4C441&color=%237CB342&color=%230B8043" style="border:solid 1px #777" width="800" height="600" frameborder="0" scrolling="no"'
        #url='https://calendar.google.com/calendar/embed?height=600&wkst=1&bgcolor=%23ffffff&ctz=Europe%2FParis&src=cmF5bmFsZC5jYW5kZWxpZXJAZ21haWwuY29t&src=Z3I4aGdpbm5hYjNwZ2ExY3M4MTAxczVlcjhAZ3JvdXAuY2FsZW5kYXIuZ29vZ2xlLmNvbQ&src=ZnIuZnJlbmNoI2hvbGlkYXlAZ3JvdXAudi5jYWxlbmRhci5nb29nbGUuY29t&color=%23039BE5&color=%23D50000&color=%237986CB'
        return http.request.render('kalachakra.event_calendar',{'url':url})
    
    @http.route(['/event/calendartui'], type='http', auth='public', website=True, sitemap=False,csrf=False)
    def eventCalendartui(self,**post):
        
        return http.request.render('kalachakra.event_calendartui')
    
    @http.route(['/kalachakra/contactus'], type='http', auth='public', website=True, sitemap=False,csrf=False)
    def kalachakracontactus(self,**post):
        
        return http.request.render('kalachakra.contactus')
    
    @http.route(['/kalachakra/thankyou'], type='http', auth='public', website=True, sitemap=False,csrf=False)
    def kalachakrathankyou(self,**post):
        
        return http.request.render('kalachakra.thankyou')
    
    @http.route(['/kalachakra/programme'], type='http', auth='public', website=True, sitemap=False,csrf=False)
    def kalachakracontactus(self,**post):
        
        return http.request.redirect('https://www.dropbox.com/s/ijsd6n82oyp0gw8/programme_Paris.pdf?dl=0')
        
    
    @http.route(['/kalachakra/object'], type='http', auth='public', website=True, sitemap=False,csrf=False)
    def object(self,model,id,*args,**kw):
        
        field_list=request.env[model].sudo().fields_get()
        objet=request.env[model].search([('id','=',int(id))])
        
        # result=[]
        # for key in field_list:

            
        #      result.append((key,str(objet[key])))
        # result.sort()
        # return json.dumps(result)
        result=""
        for key in field_list:
            result=result+str(key)+':'+str(objet[key])+'<br>'
        return result
        return model_id+ record_id
    
    @http.route(['/kalachakra/inv'], type='http', auth='public', website=True, sitemap=False,csrf=False)
    def object3(self,id,*args,**kw):
        
       move=request.env['account.move'].search([('id','=',int(id))])
       if move.state != 'posted' \
                    or move.payment_state not in ('not_paid', 'partial') \
                    or not move.is_invoice(include_receipts=True):
                return "KO"

       pay_term_lines = move.line_ids\
                .filtered(lambda line: line.account_id.user_type_id.type in ('receivable', 'payable'))

       domain = [
                ('account_id', 'in', pay_term_lines.account_id.ids),
                ('move_id.state', '=', 'posted'),
                ('partner_id', '=', move.commercial_partner_id.id),
                ('reconciled', '=', False),
                '|', ('amount_residual', '!=', 0.0), ('amount_residual_currency', '!=', 0.0),
            ]

       payments_widget_vals = {'outstanding': True, 'content': [], 'move_id': move.id}

       if move.is_inbound():
                domain.append(('balance', '<', 0.0))
                payments_widget_vals['title'] = _('Outstanding credits')
       else:
                domain.append(('balance', '>', 0.0))
                payments_widget_vals['title'] = _('Outstanding debits')

       
       result="currency_id="+str(move.currency_id)+'<br>'
       result=result+"is_invoice="+str(move.is_invoice())+'<br>'
       result=result+"state="+str(move.state)+'<br>'
       result=result+"currency.is_zero(invoice.amount_residual)="+str(move.amount_residual)+'<br>'

       for line in move.line_ids:

            amount = move.company_currency_id._convert(
                            abs(line.amount_residual),
                            move.currency_id,
                            move.company_id,
                            line.date,
                        )
            
            
            

            amount = abs(line.amount_residual_currency)
            result=result+"id="+str(line.id)+'<br>'
            result=result+"account_id="+str(line.account_id)+'<br>'
            result=result+"domain="+json.dumps(domain)+'<br>'
            result=result+"move_id.state="+str(line.move_id.state)+'<br>'
            result=result+"partner_id="+str(line.partner_id)+'<br>'
            result=result+"reconciled="+str(line.reconciled)+'<br>'
            result=result+"amount_residual="+str(line.amount_residual)+'<br>'
            result=result+"amount_residual_currency="+str(line.amount_residual_currency)+'<br>'
            

            
            result=result+"domain="+str(domain)+'<br>'
            result=result+"amount="+str(amount)+'<br>'
            result=result+"move.currency_id.is_zero(amount)="+str(move.currency_id.is_zero(amount))+'<br>'
            result=result+"currency_id="+str(line.currency_id)+'<br>'
            result=result+"line.account_id.reconcile="+str(line.account_id.reconcile)+'<br>'
            result=result+"line.account_id.user_type_id.type="+str(line.account_id.user_type_id.type)+'<br>'
            result=result+"line.amount_residual"+str(line.amount_residual)+'<br>'
            result=result+"balance="+str(line.balance)+'<br>'
            #if line.id and (line.account_id.reconcile or line.account_id.internal_type == 'liquidity'):
            result=result+"OK<br>"
            reconciled_balance = sum(line.matched_credit_ids.mapped('amount')) \
                                     - sum(line.matched_debit_ids.mapped('amount'))
            reconciled_amount_currency = sum(line.matched_credit_ids.mapped('debit_amount_currency'))\
                                             - sum(line.matched_debit_ids.mapped('credit_amount_currency'))

            result=result+str(reconciled_balance)+'<br>'
            result=result+str(reconciled_amount_currency)+'<br>'
            result=result+'<br></br>'
                

       return result

    @http.route(['/kalachakra/update'], type='http', auth='public', website=True, sitemap=False,csrf=False)
    def object2(self,*args,**kw):
        
        
        objet=request.env['account.move'].search([('id','=',108)])
        #objet.payment_reference='REC108'
        objet.posted_before=True
        
        return "ok"

        
        return http.request.redirect('https://www.dropbox.com/s/ijsd6n82oyp0gw8/programme_Paris.pdf?dl=0')

    @http.route(['/event/registration/step1'], type='http', auth='user', website=True, sitemap=False,csrf=False)
    def event_registration_step1(self,event_id,*args,**kw):
        data={}
        #contact lié à l'utilisateur
        userid=request.env.context.get('uid')
        user=request.env['res.users'].search([('id','=',int(userid))])
        partner=request.env['res.partner'].sudo().search([('id','=',int(user.partner_id))])
        data['partner']=partner
        #évenement
        event=request.env['event.event'].sudo().search([('id','=',int(event_id))])
        request.session['event_id']=int(event_id)
        data['event']=event

        #si le pays n'est pas renseigné, on le renseigne avec France
        if not partner.country_id:
            country=request.env['res.country'].search([('name','=','France')])
            partner.country_id=country.id

        
        
       
    
        data['status']=partner.member_status
        if data['status']=='not member':data['status']='non adhérent'
        if data['status']=='member':data['status']='adhérent'
        if data['status']=='super member':data['status']='adhérent de soutien'
        
        
        request.session['status']=partner.member_status
        return http.request.render('kalachakra.registration_step1',data)
        

    @http.route(['/event/registration/step2'], type='http', auth='user', website=True, sitemap=False,csrf=False)
    def event_registration_step2(self,event_id,**post):
        data={}
        #contact lié à l'utilisateur
        userid=request.env.context.get('uid')
        user=request.env['res.users'].search([('id','=',int(userid))])
        partner=request.env['res.partner'].sudo().search([('id','=',int(user.partner_id))])
        request.session['partner_id']=int(partner.id)
        data['partner']=partner
        
        #évenement
        event=request.env['event.event'].sudo().search([('id','=',int(event_id))])
        request.session['event_id']=int(event_id)
        data['event']=event
        
        data['online']=False
        
        if event.online_event:
            if post.get('online')=='yes':data['online']=True
        
        
        data['status']=request.session['status']
        
        data['price']=''
        if partner.member_status=='not member':data['participation_amount']=int(event.participation_standard_price)
        if partner.member_status=='member':data['participation_amount']=int(event.participation_member_price)
        if partner.member_status=='super member':data['participation_amount']=int(event.participation_super_member_price)
        
        membership_product=request.env['product.product'].sudo().search([('membership_product','=',True)],limit=1)
        if not membership_product: raise UserError(_('No membership product, please add one'))
        data['membership_amount']=membership_product.list_price
        data['membership_and_participation_amount']=data['membership_amount']+data['participation_amount']
        
        #enregistrement de l'inscription si pas déjà inscrit :
        res=request.env['event.registration'].sudo().search([('event_id','=',int(request.session['event_id'])),('partner_id','=',int(request.session['partner_id']))],limit=1)
        data['already_registered']=True
        data['payment_status']=res.payment_status

        

        if not res:
            data['already_registered']=False
            vals={}
            vals['event_id']=request.session['event_id']
            vals['partner_id']=request.session['partner_id']
            if event.online_event:
                vals['online']=post.get('online')
            else:
                vals['online']=False
            vals['state']='open'

            res=request.env['event.registration'].sudo().create(vals)
            #création de la facture à régler
            membership=False
            invoice_id=request.env['event.registration'].sudo().action_generate_participation_invoice(int(res.id),'CB',membership)

        request.session['res_id']=res.id

        
        return http.request.render('kalachakra.registration_step2',data)

    @http.route(['/kalachakra/onthespotpayment'], type='http', auth='public', website=True, sitemap=False,csrf=False)
    def onthespotparticipation(self,type=None,**post):
        res=request.env['event.registration'].sudo().search([('id','=',request.session['res_id'])])
        
        res.onthespot_payment=True

        return http.request.render('kalachakra.onthespotpayment')

    @http.route(['/kalachakra/participation'], type='http', auth='public', website=True, sitemap=False,csrf=False)
    def participation(self,type=None,**post):
        data={}
        request.session['kalachakra_transaction']=''

        if type=='participation':
            res=request.env['event.registration'].sudo().search([('id','=',request.session['res_id'])])
            invoice_id=res.invoice_id
            invoice=request.env['account.move'].sudo().search([('id','=',int(invoice_id))])
            invoice.state='posted'
            #redirection sur la page de paiement de la facture :
            url="/my/invoices/"+str(int(res.invoice_id))
            return request.redirect(url)

        if type=='membership_and_participation':
            res=request.env['event.registration'].sudo().search([('id','=',request.session['res_id'])])
            #suppression de la facture sans adhésion
            invoice_id=res.invoice_id
            res.invoice_id=False
            request.env['account.move'].sudo().search([('id','=',int(invoice_id))]).unlink()
            
            #creation de la facture avec adhésion
            membership=True
            invoice_id=request.env['event.registration'].sudo().action_generate_participation_invoice(int(res.id),'CB',membership)
            invoice=request.env['account.move'].sudo().search([('id','=',int(invoice_id))])
            res.invoice_id=invoice.id
            res.with_membership=True
            invoice.state='posted'

            #création de l'adhésion à régler
            #ajout de l'adhésion
            membership_product=request.env['product.product'].sudo().search([('membership_product','=',True)],limit=1)
            if not membership_product: raise UserError(_('No membership product, please add one'))
            vals={}
            vals['invoice_id']=int(invoice.id)
            vals['partner_id']=int(res.partner_id)
            vals['product_id']=int(membership_product.id)
            vals['start_date']=datetime.now()
            vals['end_date']=datetime.now()+relativedelta(years=1)
            vals['amount']=membership_product.list_price
            membership=request.env['kalachakra.membership'].sudo().create(vals)

            #redirection sur la page de paiement de la facture :
            url="/my/invoices/"+str(int(res.invoice_id))
            return request.redirect(url)


            

        if type=='donation':
            request.session['kalachakra_transaction']='donation'
            data['kalachakra_transaction']='donation'
            data['title']='make donation'
            data['amount']=10
            #donation product
            data['products']=request.env['product.product'].sudo().search([('donation','=',True)])


        if type=='membership':
            request.session['kalachakra_transaction']='membership'
            data['kalachakra_transaction']='membership'
            data['title']='Become a member'
            p=request.env['product.product'].sudo().search([('membership_product','=',True)],limit=1)
            if not p: raise UserError(_('No membership product, please add one'))
            data['amount']=p.list_price
            
            #membership product
            data['products']=p
        
        if type=='super_membership':
            request.session['kalachakra_transaction']='super_membership'
            data['kalachakra_transaction']='super_membership'
            data['title']='Become a super member'
            p=request.env['product.product'].sudo().search([('super_membership_product','=',True)],limit=1)
            if not p: raise UserError(_('No membership product, please add one'))
            data['amount']=p.list_price
            
            #super membership product
            data['products']=p
            
        
        userid=request.env.context.get('uid')
        #title options
        title=request.env['res.partner.title'].sudo().search([])
        data['titles']=title
        
        
        
        
        if userid:
            user=request.env['res.users'].sudo().search([('id','=',int(userid))])
            partner=request.env['res.partner'].sudo().search([('id','=',int(user.partner_id))])
            request.session['partner_id']=int(partner.id)
            data['partner']=partner
            data['registred']=True
            country=request.env['res.country'].sudo().search([])
            data['countries']=country
          
        # si pas connecté
        else:
            data['registred']=False
            title_male=request.env['res.partner.title'].sudo().search([('name','=','Monsieur')])
            #country options
            country=request.env['res.country'].sudo().search([])
            data['countries']=country
            country_france=request.env['res.country'].sudo().search([('name','=','France')])
            
            
            partner=request.env['res.partner']
            partner.email=''
            partner.title=title_male.id
            partner.country_id=country_france.id

            partner.firstname=''
            partner.name=''
            partner.street=''
            partner.street2=''
            partner.zip=''
            
            data['partner']=partner

            
        return http.request.render('kalachakra.participation_form',data)

    @http.route(['/kalachakra/payment_choice'], type='http', auth='public', website=True, sitemap=False,csrf=False)
    def payment_choice(self,**post):
        
       
        #gestion du retour page précédente depuis page de paiement : on supprime les éléments générés ( don , adhésion)
        if not post.get('product_id'):
            if request.session['kalachakra_transaction']=='donation':
                request.env['donation.donation'].sudo().search([('id','=',int(request.session['donation_id']))]).unlink()
            if request.session['kalachakra_transaction']=='membership':
                request.env['kalachakra.membership'].sudo().search([('id','=',int(request.session['membership_id']))]).unlink()

            return request.redirect('/kalachakra/participation?type='+request.session['kalachakra_transaction'])
              
        


        userid=request.env.context.get('uid')
        if userid:
            user=request.env['res.users'].search([('id','=',int(userid))])
            partner=request.env['res.partner'].sudo().search([('id','=',int(user.partner_id))])
            request.session['partner_id']=int(partner.id)
            #mise à jour des informations du contact lié à l'utilisateur
            vals={}    
            vals['name']=post.get('name')
            vals['firstname']=post.get('firstname')
            vals['title']=int(post.get('title_id'))
            vals['street']=post.get('street')
            vals['street2']=post.get('street2')
            vals['zip']=post.get('zip')
            vals['country_id']=int(post.get('country_id'))
            vals['phone']=post.get('phone')
            partner.sudo().write(vals)

        else:
            
            #si pas connecté on cherche le contact indiqué par l'email
            partner=request.env['res.partner'].sudo().search([('email','=',post.get('email'))],limit=1)
            #si pas de contact on le créé dans la base
            if not partner:
                vals={}
                vals['email']=post.get('email')
                vals['name']=post.get('name')
                vals['firstname']=post.get('firstname')
                vals['title']=int(post.get('title_id'))
                vals['street']=post.get('street')
                vals['street2']=post.get('street2')
                vals['zip']=post.get('zip')
                vals['country_id']=int(post.get('country_id'))
                vals['phone']=post.get('phone')
                partner=request.env['res.partner'].sudo().create(vals)
                #création du compte  utilisateur
                user=request.env['res.users'].sudo().search([('email','=',partner.email)])
                group_portal=request.env.ref('base.group_portal')
                if not user:
                    request.env['res.users'].sudo().create({
                        'name': partner.name,
                        'login': partner.email,
                        'email': partner.email,
                        'partner_id':partner.id,
                        'groups_id': [(4, group_portal.id)]
                    })
                    user.sudo().action_reset_password()

            #si le contact existe :
            #on met à jour ses informations
            else:
                
                vals={}
                
                vals['name']=post.get('name')
                vals['firstname']=post.get('firstname')
                vals['title']=int(post.get('title_id'))
                vals['street']=post.get('street')
                vals['street2']=post.get('street2')
                vals['zip']=post.get('zip')
                vals['country_id']=int(post.get('country_id'))
                vals['phone']=post.get('phone')
                partner.sudo().write(vals)
                user=request.env['res.users'].sudo().search([('email','=',partner.email)])
                group_portal=request.env.ref('base.group_portal')
                #création du compte  utilisateur
                if not user:
                    request.env['res.users'].sudo().create({
                        'name': partner.name,
                        'login': partner.email,
                        'email': partner.email,
                        'partner_id':partner.id,
                        'groups_id': [(4, group_portal.id)]
                    })
                    user.sudo().action_reset_password()

                #on vérifie qu'il n'est pas déjà adhérent si demande d'adhésion
                if partner.member_status in ('member','super member') and request.session['kalachakra_transaction']=='membership':
                    data={}
                    data['email']==post.get('email')
                    return http.request.render('kalachakra.already_member',data)  




        data={}
        if request.session['kalachakra_transaction']=='donation':
            data['submit_txt']='Donate now'
        if request.session['kalachakra_transaction']=='membership':
            data['submit_txt']='Pay now'

        data['success_url']='/kalachakra/payment/success'
        data['error_url']='/kalachakra/payment/error'

        if request.session['kalachakra_transaction'] in ['donation','membership']:
            data['acquirers'] = list(request.env['payment.acquirer'].sudo().search([
                ('state', 'in', ['enabled', 'test']),
                ('company_id', '=', request.env.company.id),
                ('provider', '!=', 'transfer')

            ]))
        else:
            data['acquirers'] = list(request.env['payment.acquirer'].sudo().search([
                ('state', 'in', ['enabled', 'test']),
                ('company_id', '=', request.env.company.id)
            ]))

        
       
        payment_tokens = partner.payment_token_ids
        payment_tokens |= partner.commercial_partner_id.sudo().payment_token_ids
        
        data['payment_tokens']=payment_tokens
        
        #create donation
        if request.session['kalachakra_transaction'] in ['donation']:
            vals={}
            vals['partner_id']=partner.id
            vals['donation_date']=datetime.now()
            vals['tax_receipt_option']='annual'
            #mode de paiement CB
            electronic_method=request.env['account.payment.method'].sudo().search([('code','=','electronic')],limit=1)
            if electronic_method:
                    cb_mode=request.env['account.payment.mode'].sudo().search([('payment_method_id','=',int(electronic_method.id))],limit=1)
                    if cb_mode:
                        vals['payment_mode_id']=cb_mode.id
                    else:
                        raise Warning('please configure credit card mode')
            vals['state']='draft'
            vals['payment_ref']='internet'
            donation_draft=request.env['donation.donation'].sudo().create(vals)
            vals={}
            #create line donation
            vals['donation_id']=donation_draft.id
            product=request.env['product.template'].sudo().search([('id','=',int(post.get('product_id')))])
            vals['product_id']=int(post.get('product_id'))
            vals['display_name']=product.name
            vals['quantity']=1
            vals['unit_price']=post.get('amount')
            vals['tax_receipt_ok']=product.tax_receipt_ok
            
            
            donation_line=request.env['donation.line'].sudo().create(vals)
            
            data['order_id']=donation_draft.id
            request.session['donation_id'] = donation_draft.id
        
        #create membership
        if request.session['kalachakra_transaction'] in ['membership']:
            vals={}
            
            vals['partner_id']=partner.id
            vals['product_id']=int(post.get('product_id'))
            vals['start_date']=datetime.now()
            vals['end_date']=datetime.now()+relativedelta(years=1)
            vals['amount']=post.get('amount')
            membership=request.env['kalachakra.membership'].sudo().create(vals)
            data['order_id']=membership.id
            request.session['membership_id'] = membership.id

        return http.request.render('kalachakra.kalachakra_payment_choice_form',data)        


    @http.route(['/kalachakra/payment/transaction/',
        '/kalachakra/payment/transaction/<int:so_id>',
        '/kalachakra/payment/transaction/<int:so_id>/<string:access_token>'], type='json', auth="public", website=True)
    def kalachakra_payment_transaction(self, acquirer_id,order_id, save_token=False, so_id=None, access_token=None, token=None, **kwargs):
        """ Json method that creates a payment.transaction, used to create a
        transaction when the user clicks on 'pay now' button. After having
        created the transaction, the event continues and the user is redirected
        to the acquirer website.

        :param int acquirer_id: id of a payment.acquirer record. If not set the
                                user is redirected to the checkout page
        """
        # Ensure a payment acquirer is selected
        
        
        if not acquirer_id:
            return False

        try:
            acquirer_id = int(acquirer_id)
        except:
            return False
        
        if request.session['kalachakra_transaction'] in ['donation']:
            # Retrieve the donation
            donation_id=order_id
            donation=request.env['donation.donation'].sudo().search([('id','=',int(donation_id))], limit=1)
            

            # Ensure there is something to proceed
            if not donation or (donation and not donation.line_ids):
                return False
        
            assert donation.partner_id.id != request.website.partner_id.id
            
            # Create transaction
            vals = {'acquirer_id': acquirer_id,
                    'return_url': '/kalachakra/payment/validate'}

            if save_token:
                vals['type'] = 'form_save'
            if token:
                vals['payment_token_id'] = int(token)

            transaction = donation.sudo()._create_payment_transaction(vals)
            
            # store the new transaction into the transaction list and if there's an old one, we remove it
            # until the day the ecommerce supports multiple orders at the same time
            last_tx_id = request.session.get('__website_sale_last_tx_id')
            last_tx = request.env['payment.transaction'].browse(last_tx_id).sudo().exists()
            if last_tx:
                PaymentProcessing.remove_payment_transaction(last_tx)
            PaymentProcessing.add_payment_transaction(transaction)
            request.session['__website_sale_last_tx_id'] = transaction.id
            return transaction.render_donation_button(donation)

        if request.session['kalachakra_transaction'] in ['membership']:
            
            # Retrieve the membeship
            membership_id=order_id
            membership=request.env['kalachakra.membership'].sudo().search([('id','=',int(membership_id))], limit=1)
        

            # Ensure there is something to proceed
            if not membership :
                return False
        
            assert membership.partner_id.id != request.website.partner_id.id

            # Create transaction
            vals = {'acquirer_id': acquirer_id,
                    'return_url': '/kalachakra/payment/validate'}

            if save_token:
                vals['type'] = 'form_save'
            if token:
                vals['payment_token_id'] = int(token)

            transaction = membership.sudo()._create_payment_transaction(vals)

            # store the new transaction into the transaction list and if there's an old one, we remove it
            # until the day the ecommerce supports multiple orders at the same time
            last_tx_id = request.session.get('__website_sale_last_tx_id')
            last_tx = request.env['payment.transaction'].browse(last_tx_id).sudo().exists()
            if last_tx:
                PaymentProcessing.remove_payment_transaction(last_tx)
            PaymentProcessing.add_payment_transaction(transaction)
            request.session['__website_sale_last_tx_id'] = transaction.id
            return transaction.sudo().render_membership_button(membership)

    http.route('/kalachakra/payment/token', type='http', auth='public', website=True, sitemap=False)
    def kalachakra_payment_token(self, pm_id=None, **kwargs):
        """ Method that handles payment using saved tokens

        :param int pm_id: id of the payment.token that we want to use to pay.
        """
        
        try:
            pm_id = int(pm_id)
        except ValueError:
            return request.redirect('/shop/?error=invalid_token_id')

        # We retrieve the token the user want to use to pay
        if not request.env['payment.token'].sudo().search_count([('id', '=', pm_id)]):
            return request.redirect('/shop/?error=token_not_found')

        # Create transaction
        vals = {'payment_token_id': pm_id, 'return_url': '/kalachakra/payment/validate'}

        if request.session['kalachakra_transaction'] in ['donation']:
            tx = donation.sudo()._create_payment_transaction(vals)
        
        if request.session['kalachakra_transaction'] in ['membership']:
            tx = membership.sudo()._create_payment_transaction(vals)

        request.session['transaction_id']=tx.id
        PaymentProcessing.add_payment_transaction(tx)
        return request.redirect('kalachakra/payment/process')

    @http.route(['/kalachakra/payment/process'], type="http", auth="public", website=True, sitemap=False)
    def kalachakra_payment_status_page(self, **kwargs):
        # When the customer is redirect to this website page,
        # we retrieve the payment transaction list from his session
        tx_ids_list = self.get_payment_transaction_ids()
        payment_transaction_ids = request.env['payment.transaction'].sudo().browse(tx_ids_list).exists()

        render_ctx = {
            'payment_tx_ids': payment_transaction_ids.ids,
        }
        return request.render("payment.payment_process_page", render_ctx)
    
    @http.route('/kalachakra/payment/validate', type='http', auth="public", website=True, sitemap=False)
    def kalachakra_payment_validate(self, transaction_id=None, sale_order_id=None, **post):
        """ Method that should be called by the server when receiving an update
        for a transaction. State at this point :

         - UDPATE ME
        """
        if request.session['kalachakra_transaction'] in ['donation']:
        
            donation_id=int(request.session['donation_id'])
            #validation du don car la tranasction est ok
            donation=request.env['donation.donation'].sudo().search([('id','=',donation_id)])
            donation.state='done'
            request.session['donation_id']=None

        if request.session['kalachakra_transaction'] in ['membership']:
            membership_id=int(request.session['membership_id'])
            #validation du don car la tranasction est ok
            membership=request.env['kalachakra.membership'].sudo().search([('id','=',membership_id)])
            membership.state='done'
            request.session['membership_id']=None

        transaction_id=int(request.session['__website_sale_last_tx_id'] )
        tx = request.env['payment.transaction'].sudo().browse(transaction_id)
       

        

        PaymentProcessing.remove_payment_transaction(tx)
        return request.redirect('/kalachakra/payment/confirmation') 

    
    @http.route(['/kalachakra/payment/confirmation'], type='http', auth="public", website=True, sitemap=False)
    def kalachakra_payment_confirmation(self, **post):
        
        return request.render("kalachakra.thankyou")
        
        