from odoo import models, fields, api
import base64

class SupplierQuotationWizard(models.TransientModel):
    _name = 'supplier_quotation_wizard'
    _description = 'Supplier Quotation Wizard'


    supplier_id = fields.Many2one('sos_suppliers', string="Supplier", required=True)
    plan_id = fields.Many2one('sos_quote_generation', string='Indent No')
    line_ids = fields.One2many('supplier_quotation_wizard_line', 'wizard_id', string="Lines")

    def action_view_quote(self):
        materials = [{'material_name': line.material_name.part_no, 'required_qty': line.required_qty} for line in self.line_ids]
        doc_data = {
            'supplier': self.supplier_id.supplier_name,
            'supplier_address': self.supplier_id.address,
            'materials': materials
        }
        return self.env.ref('sos_inventory.action_report_supplier_materials').report_action(self, data=doc_data)

    def action_send_quote(self):
        materials = [{'material_name': line.material_name.part_no, 'required_qty': line.required_qty} for line in self.line_ids]
        doc_data = {
            'supplier': self.supplier_id.supplier_name,
            'supplier_address': self.supplier_id.address,
            'materials': materials
        }
        # Generate the PDF
        report_action = self.env.ref('sos_inventory.action_email_supplier_materials')

        pdf_base64 = base64.b64encode(
            self.env['ir.actions.report'].sudo()._render_qweb_pdf(
                report_action, [self.id], data=doc_data)[0])
        attachment = self.env['ir.attachment'].create({
            'name': 'Supplier_Quote.pdf',
            'type': 'binary',
            'datas': pdf_base64,
            'res_model': self._name,
            'res_id': self.id,
            'mimetype': 'application/x-pdf'
        })

        # Send email
        mail_template = self.env.ref('sos_inventory.email_template_supplier_quote')
        mail_template.attachment_ids = [(6, 0, [attachment.id])]
        mail_template.send_mail(self.id, force_send=True)
        return {
            'type': 'ir.actions.client',
            'tag': 'display_notification',
            'params': {
                'title': 'Success!',
                'message': f"Quote sent to {self.supplier_id.supplier_name} successfully.",
                'type': 'success', 
                'sticky': False,
            }
            
        }

class SupplierQuotationWizardLine(models.TransientModel):
    _name = 'supplier_quotation_wizard_line'
    _description = 'Supplier Quotation Wizard Line'

    wizard_id = fields.Many2one('supplier_quotation_wizard', string="Wizard")
    material_name = fields.Many2one('sos_material',string="Material Name")
    required_qty = fields.Integer(string="Required Quantity")

