
from odoo import models, fields, api
import re
from odoo.exceptions import ValidationError
from datetime import datetime, timedelta

class sos_inside_sales_leads(models.Model):
    _name = 'sos_inside_sales_leads'
    _description = 'Sosaley Customers Management'
    _rec_name="company_name"

    company_name = fields.Char(string="Company Name")
    lead_generated_by = fields.Many2one(
        'res.users', 
        string='Lead Generated By', 
        default=lambda self: self.env.user,
        readonly=True
    )
    entry_date = fields.Date(string="Date", default=fields.Date.today)
    moved_on = fields.Date(string="Moved On")
    location = fields.Char(string="Location")
    website_url = fields.Char(string="Website URL")
    vertical_domain = fields.Many2many('sos_vertical_domain',string="Domain / Industry", ondelete="cascade")
    line_ids_contacts = fields.One2many('sos_leads_contact_lines', 'ref_id', string="Contact Details",copy=True)
    # products = fields.Selection(
    #         [
    #             ('BHMS 1.2V', 'BHMS 1.2V'), 
    #             ('BHMS 2V', 'BHMS 2V'), 
    #             ('BHMS 12V', 'BHMS 12V'),  
    #             ('BMS-HV', 'BMS-HV'),
    #             ('BMS-LV 100A', 'BMS-LV 100A'), 
    #             ('BMS-LV 40A', 'BMS-LV 40A'),
    #             ('SBMS 55A', 'SBMS 55A'),              
    #             ('MC 250W', 'MC 250W'),                                
    #             ('HeartTarang', 'HeartTarang')                   
    #         ],
    #         string="Product Interested In")
    products_interested = fields.Many2many('sos_products',string="Product Interested In")
    service = fields.Selection(
            [
                ('Product', 'Products'), 
                ('Project', 'Projects')

            ],
            string="Service Type",default="Product")
    project_name= fields.Many2one('sos_projects',string="Project Name")
    status = fields.Selection(
            [
                ('Open', 'Open'), 
                ('Close', 'Close'), 
                ('New', 'New'),  
                ('In-Progress', 'In-Progress'),
                ('Qualified', 'Qualified'),
                ('Unqualified', 'Unqualified')

            ],
            string="Status",default="New")
    new_source = fields.Many2one('lead_source', string="Source")
    meeting_scheduled = fields.Selection(
            [
                ('Online', 'Online'), 
                ('Offline', 'Offline')             
            ],
            string="Meeting Schedule")
    expo_name = fields.Char(string="Expo Name")
    move_to_sales = fields.Many2many('res.users',string="Move Lead to", domain=lambda self: [('groups_id', 'in', self.env.ref('sos_inventory.sos_sales_user').ids + self.env.ref('sos_inventory.sos_ce_head').ids)])
    cc_mail = fields.Many2one('res.users',string="CC to", domain=lambda self: [('groups_id', 'in', self.env.ref('sos_inventory.sos_sales_user').ids + self.env.ref('sos_inventory.sos_ce_head').ids)])
    move_div_display = fields.Boolean(default=False,string="Moved to Sales")
    line_ids = fields.One2many('sos_inside_sales_activities_line', 'ref_id', string="Action")
    week = fields.Char(string="Week")
    reporting_to = fields.Many2one('res.users', string='Reporting To')
    sales_type = fields.Selection(
            [
                ('Domestic', 'Domestic'), 
                ('International', 'International')               
            ],
            string="Sales Type",default="Domestic")
    country = fields.Many2one(
    'res.country',
    string='Country',
    default=lambda self: self.env['res.country'].search([('code', '=', 'IN')], limit=1)
)

    @api.model
    def create(self, vals):
        create_uid = vals.get('create_uid', self.env.uid)
        create_user = self.env['res.users'].browse(create_uid)

        # Check if reporting_to exists before accessing .id
        vals['reporting_to'] = create_user.reporting_to.id if create_user.reporting_to else False

        record = super(sos_inside_sales_leads, self).create(vals)
        return record

    TARGET_PER_WEEK = 4
    def action_moveto_sales(self):
        if self.move_to_sales:
            #Target Starts
            entry_date = fields.Date.today()
            self.moved_on = entry_date
            start_of_week = entry_date - timedelta(days=entry_date.weekday())  # Monday
            end_of_week = start_of_week + timedelta(days=6)  # Sunday

            # Determine week number
            first_day_of_month = entry_date.replace(day=1)
            week_number = ((entry_date - first_day_of_month).days // 7) + 1
            
            # Exclude Saturdays for 2nd and 4th week
            if week_number in [2, 4]:
                end_of_week = start_of_week + timedelta(days=4)  # Friday

            self.week = f"{start_of_week.strftime('%d/%m/%Y')} to {end_of_week.strftime('%d/%m/%Y')}"
            sos_lines = self.env['sos_target_tracker'].search([
                ('week', '=', self.week),
                ('inside_sales_executive', '=', self.lead_generated_by.id)
            ])
            new_week_entry = sos_lines.weekly_entries_count + 1
            if new_week_entry < self.TARGET_PER_WEEK:
                remaining = self.TARGET_PER_WEEK - new_week_entry
                weekly_status = f"{remaining} more to achieve this week's target."
            elif new_week_entry == self.TARGET_PER_WEEK:
                weekly_status = "Target achieved for this week!"
            else:
                weekly_status = "Well performed! Exceeded weekly target!"
            if sos_lines:
                sos_lines.write({'weekly_entries_count': new_week_entry,'entry_date':self.entry_date,
                'weekly_status':weekly_status})
            else:
                self.env['sos_target_tracker'].create({
                    'entry_date': self.entry_date,
                    'inside_sales_executive': self.lead_generated_by.id,
                    'week': f"{start_of_week.strftime('%d/%m/%Y')} to {end_of_week.strftime('%d/%m/%Y')}",
                    'weekly_entries_count':1
                })
            #Target Ends
            for user in self.move_to_sales:
                body_html = f"""
                <p>Below <b>Lead</b> is moved to Sales</p>
                """
                subject = f"New Lead Received - {self.company_name}"
                send_email = self.env['sos_common_scripts']
                send_email.send_direct_email(self.env,"sos_inside_sales_leads",self.id,user.login,subject,body_html,self.cc_mail.login)
        new_record = self.env['sos_sales_leads'].create({
            'company_name': self.company_name,
            'transferred_on': fields.Date.today(),
            'location':self.location,
            'website_url':self.website_url,
            'vertical_domain': [(6, 0, self.vertical_domain.ids)],
            'products_interested':[(6, 0,self.products_interested.ids)],
            'source':'inside_sales',
            'expo_name':self.expo_name,
            'lead_generated_by':self.env.user.id,
            'sales_type':self.sales_type,
            'interested_in':self.service,
            'project_name':self.project_name.id
            })
        if new_record:
            if self.line_ids_contacts:
                for contact in self.line_ids_contacts:
                    self.env['sos_leads_customer_contact_lines'].create({
                    'ref_id': new_record.id,
                    'name': contact.name,
                    'dept': contact.dept,
                    'email': contact.email,
                    'mobile_number': contact.mobile_number,
                    'set_as_primary': contact.set_as_primary,
                    'linkedin_profile': contact.linkedin_profile,
                    'remarks': contact.remarks
                    })
            self.move_div_display = True
            return {
                    'type': 'ir.actions.client',
                    'tag': 'display_notification',
                    'params': {
                        'message': "Moved Successfully",
                        'type': 'success',
                        'sticky': False
                    }
                }
            
class SOS_Leads_Line(models.Model):
    _name = 'sos_leads_contact_lines'
    _description = 'Leads Contact Lines'

    ref_id = fields.Many2one('sos_inside_sales_leads', string="Customers", ondelete="cascade")
    name = fields.Char(string="Name")
    dept = fields.Char(string="Designation")
    email = fields.Char(string="Email Id")
    mobile_number = fields.Char(string="Contact Number")
    set_as_primary = fields.Boolean(string="Set Primary")
    linkedin_profile = fields.Char(string="LinkedIn Profile")
    remarks = fields.Text(string="Remarks")
    @api.model
    def create(self, vals):
        record = super(SOS_Leads_Line, self).create(vals)
        if not self.env['sos_leads_contact_lines'].search([
            ('ref_id', '=', record.ref_id.id),
            ('set_as_primary', '=', True)
        ]):
            # Set the created record as primary
            record.set_as_primary = True
        return record
    def write(self, vals):
        res = super(SOS_Leads_Line, self).write(vals)
        if 'set_as_primary' in vals and vals['set_as_primary']:
            for record in self:
                self.env['sos_leads_contact_lines'].search([
                    ('ref_id', '=', record.ref_id.id),
                    ('id', '!=', record.id)
                ]).write({'set_as_primary': False})
        return res
class sos_inside_sales_activities_lines(models.Model):
    _name = 'sos_inside_sales_activities_line'
    _description = 'Inside Sales executive activities log lines'

    ref_id = fields.Many2one('sos_inside_sales_leads', ondelete="cascade")
    action_date = fields.Date(string="Action Date")
    next_action_on = fields.Date(string="Next Action On")
    remarks = fields.Text(string="Remarks")

class LeadSource(models.Model):
    _name = 'lead_source'
    _description = 'Lead Source Master'

    name = fields.Char(string="Source Name", required=True)
