"""
Django settings for hrnexus project.

Generated by 'django-admin startproject' using Django 5.0.7.

For more information on this file, see
https://docs.djangoproject.com/en/5.0/topics/settings/

For the full list of settings and their values, see
https://docs.djangoproject.com/en/5.0/ref/settings/
"""
import os
from pathlib import Path

# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent


# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/5.0/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'django-insecure-pkpc=z4t*!zcyu&qq$1n%xl45%!b+raf91!y669l$3lkovpr8x'

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

ALLOWED_HOSTS = ['backend.emeraldtownship.com','www.backend.emeraldtownship.com','localhost', '127.0.0.1']


# Application definition

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'Company',
    'Employee',
    'SuperAdmin',
    "corsheaders",
    "rest_framework",
    "Recruitment",
    "People",
    "Training",
    "Timesheet",
    "AdminCenter",
    "Insurance",
    "EmployeeRelations",
    "Communication",
    "PayrollHub",
    "ProjectHub",
] 


CORS_ALLOWED_ORIGINS = [
    "http://peoplesuite.in",
    "https://peoplesuite.in",
    "https://www.peoplesuite.in",
    "https://peoplesuite.edunexusone.com",
    "http://peoplesuite.edunexusone.com",
    "https://www.peoplesuite.edunexusone.com",
]

CANDIDATE_PORTAL_BASE_URLS = [
    "https://peoplesuite.edunexusone.com",
    "https://peoplesuite.in",
]

CSRF_TRUSTED_ORIGINS = [
    "http://peoplesuite.in",
    "https://peoplesuite.in",
    "https://www.peoplesuite.in",
    "https://peoplesuite.edunexusone.com",
    "http://peoplesuite.edunexusone.com",
    "https://www.peoplesuite.edunexusone.com",
]
from corsheaders.defaults import default_headers

CORS_ALLOW_HEADERS = [
    *default_headers,
    "x-user-role",
]



MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',

    # CORS must run before CommonMiddleware
    'corsheaders.middleware.CorsMiddleware',

    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
    
    # ADDITIVE: platform staff role/permission enforcement (SuperAdmin portal)
    'SuperAdmin.middleware.SuperAdminPermissionMiddleware',
]


# MIDDLEWARE = [
#     'django.middleware.security.SecurityMiddleware',
#     'django.contrib.sessions.middleware.SessionMiddleware',
#     'django.middleware.common.CommonMiddleware',
#     'django.middleware.csrf.CsrfViewMiddleware',
#     'django.contrib.auth.middleware.AuthenticationMiddleware',
#     'django.contrib.messages.middleware.MessageMiddleware',
#     'django.middleware.clickjacking.XFrameOptionsMiddleware',
#     'corsheaders.middleware.CorsMiddleware',
# ]

ROOT_URLCONF = 'hrnexus.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [os.path.join(BASE_DIR, 'templates')],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

WSGI_APPLICATION = 'hrnexus.wsgi.application'


# Database
# https://docs.djangoproject.com/en/5.0/ref/settings/#databases

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': BASE_DIR / 'db.sqlite3',
    },

    'mysql': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'peoplesuite',
        'USER': 'peoplesuite_user',
        'PASSWORD': 'peoplesuite@123',
        'HOST': 'localhost',
        'PORT': '3306',
        'OPTIONS': {
            'charset': 'utf8mb4',
        },
    }
}

# DATABASES = {
#     'default': {
#         'ENGINE': 'django.db.backends.sqlite3',
#         'NAME': BASE_DIR / 'db.sqlite3',
#     }
# }


# Password validation
# https://docs.djangoproject.com/en/5.0/ref/settings/#auth-password-validators

AUTH_PASSWORD_VALIDATORS = [
    {
        'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
    },
]



# Internationalization
# https://docs.djangoproject.com/en/4.2/topics/i18n/

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'Asia/Kolkata'

USE_I18N = True

USE_TZ = True


# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/4.2/howto/static-files/

import os


STATIC_URL = '/static/'
STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static')]
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')

MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')

# WhiteNoise storage adds compression + cache-busting hashes
STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage'

# Default primary key field type
# https://docs.djangoproject.com/en/4.2/ref/settings/#default-auto-field

DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'

# Authentication
# AUTH_USER_MODEL = 'Employee.EmployeeDT'
# LOGIN_URL = '/login/'
# LOGIN_REDIRECT_URL = '/chat/'

# Channels: Redis in production, in-memory fallback for dev
REDIS_URL = os.getenv('REDIS_URL')
if REDIS_URL:
    CHANNEL_LAYERS = {
        'default': {
            'BACKEND': 'channels_redis.core.RedisChannelLayer',
            'CONFIG': {
                'hosts': [REDIS_URL],
            },
        },
    }
else:
    CHANNEL_LAYERS = {
        'default': {
            'BACKEND': 'channels.layers.InMemoryChannelLayer',
        }
    }


from datetime import timedelta

REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': (
        'rest_framework_simplejwt.authentication.JWTAuthentication',
    ),
}

SIMPLE_JWT = {
    'ACCESS_TOKEN_LIFETIME': timedelta(days=1),
    'REFRESH_TOKEN_LIFETIME': timedelta(days=7),
    'AUTH_HEADER_TYPES': ('Bearer',),
}


# ============================================================
# ADDITIVE: outgoing email (SMTP) - Titan / BigRock
# Credentials are NOT stored here. Provide them either as
# environment variables (EMAIL_HOST_USER / EMAIL_HOST_PASSWORD)
# or in hrnexus/email_local.py (see email_local.example.py).
# ============================================================

EMAIL_BACKEND = os.getenv(
    "EMAIL_BACKEND",
    "django.core.mail.backends.smtp.EmailBackend"
)
EMAIL_HOST = "smtp.titan.email"
EMAIL_PORT = 465
EMAIL_USE_SSL = True
EMAIL_USE_TLS = False
EMAIL_HOST_USER = "Akshay.Kedar@impetechglobal.com"
EMAIL_HOST_PASSWORD = "Akshay.Kedar"
DEFAULT_FROM_EMAIL = "Akshay.Kedar@impetechglobal.com"
# Shown as "Login URL" in the welcome email (leave "" to hide)
SITE_BASE_URL = os.getenv("SITE_BASE_URL", "https://hrms.edunexusone.com")

try:
    from .email_local import *  # noqa: F401,F403
except ImportError:
    pass


CALENDARIFIC_API_KEY = "4JfojaBzUBD7PXN9jSqsWCxSX4DTQKTe"


# ============================================================
# ADDITIVE: Hiring Plus settings (all optional - these are the defaults)
# ============================================================
HIRING_HIKE_LIMIT_PERCENT = 10                 # offer above this % hike over last CTC needs management approval
HIRING_NOTICE_PERIOD_OPTIONS = (30, 60, 90)    # allowed notice period days on the candidate form
HIRING_REQUIRE_CANDIDATE_APPROVAL = True       # new candidates need an M-level checker before Interview
HIRING_ALLOW_SELF_APPROVAL = False             # maker and checker must be different people
HIRING_REQUIRE_ID_VERIFICATION = False         # True = block Ready-To-Join / conversion until PAN, Aadhaar, Education, Experience are verified
HIRING_M_LEVEL_ROLE_CODES = ("m_level", "manager", "hr_manager", "hiring_manager", "hr_head", "chro", "hcm", "director", "ceo")
# Only these roles can be picked as Hiring Manager on a requisition
HIRING_MANAGER_ROLE_CODES = ("hiring_manager",)
HIRING_MANAGER_ROLE_NAMES = ("hiring manager",)
# Aadhaar verification: "manual" (checksum + document check), "http" (OTP via your KYC vendor) or "mock" (dev only, OTP 123456)
HIRING_AADHAAR_PROVIDER = os.getenv("HIRING_AADHAAR_PROVIDER", "manual")
HIRING_AADHAAR_HTTP = {
    "generate_url": os.getenv("AADHAAR_GENERATE_OTP_URL", ""),
    "submit_url": os.getenv("AADHAAR_SUBMIT_OTP_URL", ""),
    "token": os.getenv("AADHAAR_API_TOKEN", ""),
    "id_field": "id_number", "ref_field": "client_id", "otp_field": "otp", "timeout": 20,
}






# ============================================================
# ADDITIVE: per-company SMTP (see People/mail_backend.py, People/views_mail.py)
# Every company can store its own SMTP account(s) for mails to ITS employees and candidates.
# The backend below picks the recipient's company SMTP automatically; everything else keeps using the
# previous (global) backend, which stays available as the fallback.
# ============================================================
COMPANY_MAIL_FALLBACK_BACKEND = EMAIL_BACKEND            # whatever was configured above (SMTP / console ...)
EMAIL_BACKEND = "People.mail_backend.CompanyAwareEmailBackend"
# Fernet key used to encrypt stored SMTP passwords. Generate once:  python -c "from cryptography.fernet import Fernet; print(Fernet.generate_key().decode())"
# and put it in the environment. If unset, a key derived from SECRET_KEY is used.
COMPANY_SMTP_ENCRYPTION_KEY = os.getenv("COMPANY_SMTP_ENCRYPTION_KEY") or None
COMPANY_SMTP_ALLOWED_PORTS = (25, 465, 587, 2525)         # None = any port
COMPANY_SMTP_ALLOW_PRIVATE_HOSTS = False                 # True only for an internal mail relay (blocks SSRF otherwise)
COMPANY_SMTP_VERIFY_DNS = True                           # host name must resolve (and must not point to a private address)
COMPANY_SMTP_ALLOW_SHARED_MAILBOX = False                # False = one mailbox cannot be registered by two companies
COMPANY_MAIL_ALLOW_PLATFORM_FALLBACK = False              # False = mail to a company's employees/candidates is NEVER sent through the
                                                         # SuperAdmin mailbox above; a company without its own SMTP simply cannot send
MIDDLEWARE = list(MIDDLEWARE) + ["People.mail_context.CompanyMailContextMiddleware"]   # knows which company is calling



# ============================================================
# MYSQL DATABASE CONFIGURATION
# ============================================================

try:
    import MySQLdb
except ImportError:
    import pymysql
    pymysql.version_info = (2, 2, 7, "final", 0)
    pymysql.install_as_MySQLdb()

if os.environ.get("USE_SQLITE") != "1":

    DATABASES['mysql']['NAME'] = os.environ.get(
        "DB_NAME", DATABASES['mysql']['NAME']
    )

    DATABASES['mysql']['USER'] = os.environ.get(
        "DB_USER", DATABASES['mysql']['USER']
    )

    DATABASES['mysql']['PASSWORD'] = os.environ.get(
        "DB_PASSWORD", DATABASES['mysql']['PASSWORD']
    )

    DATABASES['mysql']['HOST'] = os.environ.get(
        "DB_HOST", DATABASES['mysql']['HOST']
    )

    DATABASES['default'] = DATABASES['mysql']
    

