# app/context_processors.py

from flask import current_app
from flask_login import current_user
from app.models import Notification
from app.public.forms import NewsletterForm
from datetime import datetime


def utility_processor():
    """Context processor اصلی برای تمام قالب‌ها"""
    
    def get_unread_notifications_count():
        if current_user.is_authenticated:
            try:
                return Notification.query.filter_by(
                    user_id=current_user.id, 
                    is_read=False
                ).count()
            except Exception as e:
                current_app.logger.error(f"Error getting unread count: {e}")
                return 0
        return 0
    
    def format_number(value):
        try:
            if value is None:
                return '۰'
            num = int(float(value))
            return f"{num:,}".replace(',', '٬')
        except (ValueError, TypeError):
            return str(value)
    
    # ایجاد فرم خبرنامه
    newsletter_form = NewsletterForm()
    
    return {
        'Notification': Notification,
        'get_unread_count': get_unread_notifications_count,
        'format_number': format_number,
        'current_year': datetime.now().year,
        'now': datetime.now(),
        'newsletter_form': newsletter_form  # اضافه کردن فرم به context
    }


def employer_context():
    """Context processor برای پنل کارفرما"""
    
    def get_employer_data():
        if not current_user.is_authenticated or current_user.role != 'employer':
            return {
                'pending_payment_requests_count': 0,
                'pending_releases_count': 0,
                'unread_notifications': 0,
                'total_projects': 0,
                'active_projects': 0
            }
        
        try:
            from app.models import Project, PaymentRequest, PaymentRelease, Contract
            
            projects = Project.query.filter_by(employer_id=current_user.id).all()
            project_ids = [p.id for p in projects]
            
            total_projects = len(projects)
            active_projects = sum(1 for p in projects if p.status == 'active')
            
            pending_payment_requests = 0
            pending_releases = 0
            
            if project_ids:
                pending_payment_requests = PaymentRequest.query.join(Contract).filter(
                    Contract.project_id.in_(project_ids),
                    PaymentRequest.employer_approved == False,
                    PaymentRequest.status == 'pending'
                ).count()
                
                pending_releases = PaymentRelease.query.filter(
                    PaymentRelease.contract_id.in_(
                        db.session.query(Contract.id).filter(Contract.project_id.in_(project_ids))
                    ),
                    PaymentRelease.employer_approved == False,
                    PaymentRelease.status == 'pending'
                ).count()
            
            unread_notifications = Notification.query.filter_by(
                user_id=current_user.id,
                is_read=False
            ).count()
            
            return {
                'pending_payment_requests_count': pending_payment_requests,
                'pending_releases_count': pending_releases,
                'unread_notifications': unread_notifications,
                'total_projects': total_projects,
                'active_projects': active_projects,
                'employer_projects': projects,
                'employer_project_ids': project_ids
            }
            
        except Exception as e:
            current_app.logger.error(f"Error in employer_context: {e}")
            return {
                'pending_payment_requests_count': 0,
                'pending_releases_count': 0,
                'unread_notifications': 0,
                'total_projects': 0,
                'active_projects': 0
            }
    
    return get_employer_data


def manager_context():
    """Context processor برای پنل مدیر پروژه"""
    
    def get_manager_data():
        if not current_user.is_authenticated or current_user.role != 'manager':
            return {
                'pending_payment_requests_count': 0,
                'pending_releases_count': 0,
                'unread_notifications': 0
            }
        
        try:
            from app.models import Project, PaymentRequest, PaymentRelease, Contract
            
            projects = Project.query.filter_by(manager_id=current_user.id).all()
            project_ids = [p.id for p in projects]
            
            pending_payment_requests = 0
            pending_releases = 0
            
            if project_ids:
                pending_payment_requests = PaymentRequest.query.join(Contract).filter(
                    Contract.project_id.in_(project_ids),
                    PaymentRequest.manager_approved == False,
                    PaymentRequest.status == 'pending'
                ).count()
                
                pending_releases = PaymentRelease.query.filter(
                    PaymentRelease.contract_id.in_(
                        db.session.query(Contract.id).filter(Contract.project_id.in_(project_ids))
                    ),
                    PaymentRelease.manager_approved == False,
                    PaymentRelease.status == 'pending'
                ).count()
            
            unread_notifications = Notification.query.filter_by(
                user_id=current_user.id,
                is_read=False
            ).count()
            
            return {
                'pending_payment_requests_count': pending_payment_requests,
                'pending_releases_count': pending_releases,
                'unread_notifications': unread_notifications
            }
            
        except Exception as e:
            current_app.logger.error(f"Error in manager_context: {e}")
            return {
                'pending_payment_requests_count': 0,
                'pending_releases_count': 0,
                'unread_notifications': 0
            }
    
    return get_manager_data


def employee_context():
    """Context processor برای پنل کارمند"""
    
    def get_employee_data():
        if not current_user.is_authenticated or current_user.role != 'employee':
            return {
                'unread_notifications': 0,
                'employee_has_project': False
            }
        
        try:
            from app.models import ProjectEmployee
            
            project_employee = ProjectEmployee.query.filter_by(
                employee_id=current_user.id,
                is_active=True
            ).first()
            
            unread_notifications = Notification.query.filter_by(
                user_id=current_user.id,
                is_read=False
            ).count()
            
            return {
                'unread_notifications': unread_notifications,
                'employee_has_project': project_employee is not None,
                'employee_project': project_employee.project if project_employee else None
            }
            
        except Exception as e:
            current_app.logger.error(f"Error in employee_context: {e}")
            return {
                'unread_notifications': 0,
                'employee_has_project': False
            }
    
    return get_employee_data