# -*- coding: utf-8 -*-

from odoo import models, fields, api



class sos_travel_plan(models.Model):
    _name = 'sos_travel_plan'
    _description = 'Travel Plan'
    _rec_name = 'plan_id'
    _order = 'id desc'

    plan_id = fields.Char(string="Plan Id",readonly= True, required= True,default=lambda self: self._generate_id())
    travel_type =  fields.Selection([('installation','Installation & Commissioning'),('service','Service'),('demo','Demo'),('validation','Validation'),('warranty','Warranty Call'),('amc','AMC/Cloud Service')],string='Type')
    customer_name = fields.Many2one('sos_inventory_customers',string="Customer Name")
    customer_location = fields.Char(string="Customer Location")
    dock_audit_no = fields.Many2one('sos_dock_audit',string="Dock Audit Reference No")
    date_of_travel =  fields.Date(string="Date of Travel")
    duration = fields.Integer(string="Duration(In Days)")
    mode_of_travel = fields.Selection([('car','🚗 Car'),('bus','🚌 Bus'),('train','🚂 Train'),('flight','🛩️ Flight')],string='Mode of Travel')
    activity_planned = fields.Html(string="Activities Planned")
    return_date = fields.Date(string="Date of return travel")
    return_mode_of_travel = fields.Selection([('car','🚗 Car'),('bus','🚌 Bus'),('train','🚂 Train'),('flight','🛩️ Flight')],string='Mode of Travel')
    project_coordinators = fields.Many2one(
    'res.users',
    string='Project Coordinator',
    domain=lambda self: [
        '|', '|', '|',
        ('groups_id', 'in', self.env.ref('sos_inventory.sos_ce_user').ids),
        ('groups_id', 'in', self.env.ref('sos_inventory.sos_sales_user').ids),
        ('groups_id', 'in', self.env.ref('sos_inventory.sos_ce_head').ids),
        ('groups_id', 'in', self.env.ref('sos_inventory.sos_qc_user').ids),
            ]
        )
    persons = fields.Many2many(
    'res.users',
    string='Number of Persons Travelling',
    domain=lambda self: [
        '|', '|', '|',
        ('groups_id', 'in', self.env.ref('sos_inventory.sos_ce_user').ids),
        ('groups_id', 'in', self.env.ref('sos_inventory.sos_sales_user').ids),
        ('groups_id', 'in', self.env.ref('sos_inventory.sos_ce_head').ids),
        ('groups_id', 'in', self.env.ref('sos_inventory.sos_qc_user').ids),
            ]
        )
    prepared_by_name = fields.Many2one('res.users', string='Prepared by')
    reporting_to = fields.Many2one('res.users',related="prepared_by_name.reporting_to", string='Prepared by')
    prepared_by_image = fields.Image(related="prepared_by_name.signature_image",string='Prepared by Sign',readonly=True)
    prepared_on = fields.Datetime(string="Approved On")
    dept_in_charge_name = fields.Many2one('res.users', string='Department In-Charge')
    dept_in_charge_image = fields.Image(related="dept_in_charge_name.signature_image",string='Department In-Charge Sign',readonly=True)
    dept_in_charge_approved_on = fields.Datetime(string="Approved On")
    top_management_name = fields.Many2one('res.users', string='Top Management Approver')
    top_management_approval_image = fields.Image(related="top_management_name.signature_image",string='Top Management Approval',readonly=True)
    top_management_approved_on = fields.Datetime(string="Approved On")
    hr_in_charge_name = fields.Many2one('res.users', string='HR In-Charge')
    hr_in_charge_image = fields.Image(related="hr_in_charge_name.signature_image",string='HR In-Charge Sign',readonly=True)
    hr_in_charge_approved_on = fields.Datetime(string="Approved On")
    hr_remarks=fields.Text(string="Remarks")
    advance_req = fields.Selection([('yes','Yes'),('no','No')],string='Advance Required')
    ticket = fields.Binary(string="Tickets")
    ticket_filename=fields.Char(string="File Name")
    return_ticket = fields.Binary(string="Return Tickets")
    return_ticket_filename=fields.Char(string="Return File Name")
    def action_view_ticket(self):
        if not self.ticket:
            raise UserError("No ticket available.")
        
        # Use `ir.actions.act_url` to open the binary file as a PDF
        return {
        'type': 'ir.actions.act_url',
        'url': '/web/content/{}/{}/{}?download=false'.format(
            self._name, self.id, 'ticket'),
        'target': 'new',  # This opens the PDF in a new tab
        }
    def action_view_returnticket(self):
        if not self.return_ticket:
            raise UserError("No ticket available.")
        
        # Use `ir.actions.act_url` to open the binary file as a PDF
        return {
        'type': 'ir.actions.act_url',
        'url': '/web/content/{}/{}/{}?download=false'.format(
            self._name, self.id, 'return_ticket'),
        'target': 'new',  # This opens the PDF in a new tab
        }
    def _generate_id(self):
        sequence_util = self.env['sos_common_scripts']
        return sequence_util.generate_sequence('sos_travel_plan','PLAN', 'plan_id')
    def action_report_travel_plan(self):
        try:
            action = self.env.ref("sos_installation_commision.action_report_travel_plan").report_action(self)
            return action
        except ValueError as e:
            print(f"Failed to find report action: {e}")
    def action_report_esign_btn(self):
        # Email part
        body_html = f"""
        <p>Below <b>Travel Plan</b> is waiting for your Approval</p>
        """
        sequence_util = self.env['sos_common_scripts']
        sequence_util.send_group_email(self.env,'sos_travel_plan',self.id,"deenalaura.m@sosaley.in","Travel Plan Approval Request",body_html,'sos_inventory.sos_ce_head')
        # Email part ends
        return sequence_util.action_assign_signature(
        self, 
        'prepared_by_name',
        'prepared_on'
    )
    def action_deptincharge_esign_btn(self):
        # Email part
        body_html = f"""
        <p>Below <b>Travel Plan</b> is waiting for your Approval</p>
        """
        sequence_util = self.env['sos_common_scripts']
        sequence_util.send_direct_email(self.env,"sos_travel_plan",self.id,"ramachandran.r@sosaley.in","Travel Plan Approval Request",body_html)
        # Email part ends
        return sequence_util.action_assign_signature(
        self, 
        'dept_in_charge_name',
        'dept_in_charge_approved_on'
    )
    def action_topmanagement_esign_btn(self):
        sequence_util = self.env['sos_common_scripts']
        acc_body_html = f"""
        <p>Below <b>Travel Plan</b> got Approved</p>
        """
        
        sequence_util.send_group_email(self.env,'sos_travel_plan',self.id,"deenalaura.m@sosaley.in","Travel Plan Approved",acc_body_html,'sos_inventory.sos_finance_user')
        
        hr_body_html = f"""
        <p>Below <b>Travel Plan</b> is waiting for your Acknowledgement</p>
        """
        sequence_util.send_group_email(self.env,'sos_travel_plan',self.id,"deenalaura.m@sosaley.in","Travel Plan Acknowledgement",hr_body_html,'sos_inventory.sos_hr_user')

        return sequence_util.action_assign_signature(
        self, 
        'top_management_name',
        'top_management_approved_on'
    )
    def action_hr_esign_btn(self):
        sequence_util = self.env['sos_common_scripts']
        ce_body_html = f"""
        <p>Below <b>Travel Plan</b> got Approved</p>
        """
        if self.ticket:
            ce_body_html += "<p><b>Ticket attached</b></p>"
        sequence_util.send_group_email(self.env,'sos_travel_plan',self.id,"deenalaura.m@sosaley.in","Travel Plan Approved",ce_body_html,'sos_inventory.sos_ce_user')
        
        return sequence_util.action_assign_signature(
        self, 
        'hr_in_charge_name',
        'hr_in_charge_approved_on'
    )
    