"""
Django settings for config project.

Generated by 'django-admin startproject' using Django 4.2.30.

For more information on this file, see
https://docs.djangoproject.com/en/4.2/topics/settings/

For the full list of settings and their values, see
https://docs.djangoproject.com/en/4.2/ref/settings/
"""

from pathlib import Path
import os
from dotenv import load_dotenv
import dj_database_url

# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent

# Load environment variables
load_dotenv(BASE_DIR / '.env')


# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/4.2/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = os.getenv('SECRET_KEY', 'django-insecure-dev-key-change-in-production')

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = False
# DEBUG = os.getenv('DEBUG', 'False') == 'True'

ALLOWED_HOSTS = ['site.loftycreekchristianschool.org', '127.0.0.1', 'localhost']

# Render uses a proxy that handles SSL termination.
# This setting tells Django to trust the HTTP_X_FORWARDED_PROTO header.
SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https')

CSRF_TRUSTED_ORIGINS = [
    'https://site.loftycreekchristianschool.org',
    'http://127.0.0.1:8000',
]

# Add any additional origins from environment variables
env_trusted_origins = os.getenv('CSRF_TRUSTED_ORIGINS')
if env_trusted_origins:
    CSRF_TRUSTED_ORIGINS.extend(env_trusted_origins.split(','))
else:
    # Default Render URL if not explicitly provided
    CSRF_TRUSTED_ORIGINS.append('https://site.loftycreekchristianschool.org')


# Application definition

INSTALLED_APPS = [
    'jazzmin',
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'django_summernote',
    'public',
    'core',
    'sms',
]

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'whitenoise.middleware.WhiteNoiseMiddleware',
    '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',
]

ROOT_URLCONF = 'config.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [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',
                'sms.context_processors.balance_processor',
            ],
        },
    },
]

WSGI_APPLICATION = 'config.wsgi.application'


# Database
# https://docs.djangoproject.com/en/4.2/ref/settings/#databases

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'loftycre_new',
        'USER': 'loftycre_LoftyCreek',
        'PASSWORD': 'Lccs@2026!',  
        'HOST': '127.0.0.1',
        'PORT': '3306',
        'OPTIONS': {
            'init_command': "SET sql_mode='STRICT_TRANS_TABLES'",
        },
    }
}


# Password validation
# https://docs.djangoproject.com/en/4.2/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 = 'UTC'

USE_I18N = True

USE_TZ = True


# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/4.2/howto/static-files/

STATIC_URL = '/static/'
STATICFILES_DIRS = [BASE_DIR / 'static']
STATIC_ROOT = BASE_DIR / 'staticfiles'

STORAGES = {
    "default": {
        "BACKEND": "django.core.files.storage.FileSystemStorage",
    },
    "staticfiles": {
        "BACKEND": "whitenoise.storage.CompressedStaticFilesStorage",
    },
}

MEDIA_URL = '/media/'
MEDIA_ROOT = BASE_DIR / 'media'

# Default primary key field type
# https://docs.djangoproject.com/en/4.2/ref/settings/#default-auto-field

DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'

SESSION_COOKIE_AGE = 300
SESSION_SAVE_EVERY_REQUEST = True
SESSION_COOKIE_SECURE = not DEBUG
SESSION_COOKIE_SAMESITE = 'Lax'
CSRF_COOKIE_SECURE = not DEBUG
CSRF_COOKIE_HTTPONLY = False
CSRF_USE_SESSIONS = False

LOGIN_URL = '/admin/login/'
LOGIN_REDIRECT_URL = '/admin/'
LOGOUT_REDIRECT_URL = '/'

if not DEBUG:
    SECURE_SSL_REDIRECT = True
    SECURE_HSTS_SECONDS = 31536000
    SECURE_HSTS_INCLUDE_SUBDOMAINS = True
    SECURE_HSTS_PRELOAD = True

# Africa's Talking API Credentials
AFRICASTALKING_USERNAME = os.getenv('AFRICASTALKING_USERNAME', 'sandbox')
AFRICASTALKING_API_KEY = os.getenv('AFRICASTALKING_API_KEY', '')
AFRICASTALKING_SENDER_ID = os.getenv('AFRICASTALKING_SENDER_ID', None)


# ---------------------------------------------------------------------------
# Jazzmin Admin Dashboard – Lofty Creek Christian School
# ---------------------------------------------------------------------------
JAZZMIN_SETTINGS = {
    # ── Branding ──────────────────────────────────────────────────────────
    "site_title": "LCCS Admin",
    "site_header": "Lofty Creek Christian School",
    "site_brand": "LCCS",
    "site_logo": "img/logo_2.png",
    "login_logo": "img/logo_2.png",
    "site_icon": None,
    "welcome_sign": "Welcome to the LCCS Administration Portal",
    "copyright": "Lofty Creek Christian School",

    # ── Top links (quick nav shortcuts) ───────────────────────────────────
    "topmenu_links": [
        {"name": "Home", "url": "admin:index", "permissions": ["auth.view_user"]},
        {"name": "📡 SMS Dashboard", "url": "/sms/", "new_window": False},
        {"name": "🌐 School Website", "url": "/", "new_window": True},
    ],

    # ── User menu (top-right avatar dropdown) ─────────────────────────────
    "usermenu_links": [
        {"name": "📡 SMS Dashboard", "url": "/sms/", "icon": "fas fa-satellite-dish"},
        {"model": "auth.user"},
    ],

    # ── Sidebar ───────────────────────────────────────────────────────────
    "show_sidebar": True,
    "navigation_expanded": True,
    "hide_apps": [],
    "hide_models": [],

    # Order the sidebar apps and models explicitly
    "order_with_respect_to": [
        "auth",
        "public",
        "public.BlogPost",
        "public.GalleryPhoto",
        "public.ContactMessage",
        "core",
        "core.Contact",
        "core.ContactGroup",
        "core.SMSTemplate",
        "sms",
        "sms.SMSCampaign",
        "sms.SMSMessage",
        "sms.SMSTemplate",
    ],

    # Custom sidebar links per app
    "custom_links": {
        "sms": [
            {
                "name": "📡 SMS Dashboard",
                "url": "/sms/",
                "icon": "fas fa-tachometer-alt",
            },
            {
                "name": "✍️ Broadcast Hub",
                "url": "/sms/compose/",
                "icon": "fas fa-paper-plane",
            },
            {
                "name": "👥 Contact Manager",
                "url": "/sms/contacts/",
                "icon": "fas fa-address-book",
            },
            {
                "name": "📋 Message Templates",
                "url": "/sms/templates/",
                "icon": "fas fa-file-alt",
            },
        ],
    },

    # ── Icons ─────────────────────────────────────────────────────────────
    "icons": {
        "auth":                        "fas fa-users-cog",
        "auth.user":                   "fas fa-user",
        "auth.Group":                  "fas fa-layer-group",
        "public.BlogPost":             "fas fa-blog",
        "public.GalleryPhoto":         "fas fa-images",
        "public.ContactMessage":       "fas fa-envelope-open-text",
        "core.Contact":                "fas fa-address-card",
        "core.ContactGroup":           "fas fa-users",
        "core.SMSTemplate":            "fas fa-file-alt",
        "sms.SMSCampaign":             "fas fa-broadcast-tower",
        "sms.SMSMessage":              "fas fa-envelope",
        "sms.SMSTemplate":             "fas fa-scroll",
    },
    "default_icon_parents": "fas fa-folder",
    "default_icon_children": "fas fa-circle",

    # ── UI options ────────────────────────────────────────────────────────
    "related_modal_active": True,
    "use_google_fonts_cdn": True,
    "show_ui_builder": False,
    "custom_css": "css/admin.css",

    # ── Search ────────────────────────────────────────────────────────────
    "search_model": ["auth.user", "core.Contact"],

    # ── Change-view actions ───────────────────────────────────────────────
    "changeform_format": "horizontal_tabs",
    "changeform_format_overrides": {
        "auth.user":  "collapsible",
        "auth.group": "vertical_tabs",
    },
}

JAZZMIN_UI_TWEAKS = {
    "navbar_small_text": False,
    "footer_small_text": False,
    "body_small_text": False,
    "brand_small_text": False,
    "brand_colour": "navbar-primary",
    "accent": "accent-primary",
    "navbar": "navbar-dark",
    "no_navbar_border": True,
    "navbar_fixed": True,
    "layout_boxed": False,
    "footer_fixed": False,
    "sidebar_fixed": True,
    "sidebar": "sidebar-dark-primary",
    "sidebar_nav_small_text": False,
    "sidebar_disable_expand": False,
    "sidebar_nav_child_indent": True,
    "sidebar_nav_compact_style": False,
    "sidebar_nav_legacy_style": False,
    "sidebar_nav_flat_style": False,
    "theme": "default",
    "dark_mode_theme": None,
    "button_classes": {
        "primary":   "btn-primary",
        "secondary": "btn-secondary",
        "info":      "btn-info",
        "warning":   "btn-warning",
        "danger":    "btn-danger",
        "success":   "btn-success",
    },
}

# ---------------------------------------------------------------------------
# Logging Configuration
# ---------------------------------------------------------------------------
LOGS_DIR = BASE_DIR / 'logs'
os.makedirs(LOGS_DIR, exist_ok=True)

LOGGING = {
    'version': 1,
    'disable_existing_loggers': False,
    'formatters': {
        'simple': {
            'format': '{levelname} {asctime} [{module}] {message}',
            'style': '{',
        },
        'sms_format': {
            'format': '%(asctime)s [%(levelname)s] %(message)s',
            'datefmt': '%Y-%m-%d %H:%M:%S',
        },
    },
    'handlers': {
        'console': {
            'level': 'INFO',
            'class': 'logging.StreamHandler',
            'formatter': 'simple',
        },
        'sms_file': {
            'level': 'INFO',
            'class': 'logging.handlers.RotatingFileHandler',
            'filename': os.path.join(LOGS_DIR, 'sms_campaigns.log'),
            'maxBytes': 1024 * 1024 * 5,  # 5 MB
            'backupCount': 5,
            'formatter': 'sms_format',
        },
    },
    'loggers': {
        'sms': {
            'handlers': ['console', 'sms_file'],
            'level': 'INFO',
            'propagate': False,
        },
    },
}

