# app/employer/routes.py

from flask import render_template, redirect, url_for, flash, request, jsonify
from flask_login import login_required, current_user
from app.employer import employer_bp
from app.extensions import db
from app.models import (
    Project, Contract, ContractInstallment, Deposit,Payment, 
    PaymentRequest, PaymentRelease, Attendance, 
    PhotoReport, Report, Notification, User,
    ProjectEmployee, SmartReport, PaymentIdentifier,
    Installment, SystemCommission,PaymentControl, InstallmentPayment,
    CheckIssuance
)
from .forms import (
    WorkPlanForm, ProfileForm
)
from datetime import datetime, timedelta
from sqlalchemy import func, and_, or_
import json
import hashlib
import random
import string


# ==================== 1. داشبورد اصلی کارفرما ====================
@employer_bp.route('/')
@employer_bp.route('/index')
@login_required
def index():
    """داشبورد اصلی کارفرما"""
    if current_user.role != 'employer':
        flash('دسترسی غیرمجاز', 'danger')
        return redirect(url_for('auth.dashboard'))
    
    # دریافت تمام پروژه‌های کارفرما
    projects = Project.query.filter_by(employer_id=current_user.id).all()
    
    # آمار کلی
    total_projects = len(projects)
    active_projects = sum(1 for p in projects if p.status == 'active')
    completed_projects = sum(1 for p in projects if p.status == 'completed')
    
    # تعداد کل کارکنان در پروژه‌ها
    total_employees = 0
    total_contracts = 0
    for project in projects:
        total_employees += project.get_employee_count()
        total_contracts += len(project.contracts)
    
    # درخواست‌های پرداخت نیازمند تایید
    pending_payment_requests = PaymentRequest.query.join(Contract).filter(
        Contract.project_id.in_([p.id for p in projects]),
        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_([p.id for p in projects]))
        ),
        PaymentRelease.employer_approved == False,
        PaymentRelease.status == 'pending'
    ).count()
    
    # گزارشات نیازمند بررسی
    pending_reports = Report.query.filter(
        Report.project_id.in_([p.id for p in projects]),
        Report.status == 'pending'
    ).count()
    
    # اقساط معوق
    overdue_installments = ContractInstallment.query.join(Contract).filter(
        Contract.project_id.in_([p.id for p in projects]),
        ContractInstallment.status == 'pending',
        ContractInstallment.due_date < datetime.now().date()
    ).count()
    
    # آخرین فعالیت‌ها
    recent_attendances = Attendance.query.join(Project).filter(
        Project.employer_id == current_user.id
    ).order_by(Attendance.created_at.desc()).limit(10).all()
    
    recent_payments = PaymentRequest.query.join(Contract).filter(
        Contract.project_id.in_([p.id for p in projects])
    ).order_by(PaymentRequest.created_at.desc()).limit(10).all()
    
    # تعداد نوتیفیکیشن‌های خوانده نشده
    unread_notifications = Notification.query.filter_by(
        user_id=current_user.id,
        is_read=False
    ).count()
    
    return render_template(
        'employer/index.html',
        projects=projects,
        total_projects=total_projects,
        active_projects=active_projects,
        completed_projects=completed_projects,
        total_employees=total_employees,
        total_contracts=total_contracts,
        pending_payment_requests=pending_payment_requests,
        pending_releases=pending_releases,
        pending_reports=pending_reports,
        overdue_installments=overdue_installments,
        recent_attendances=recent_attendances,
        recent_payments=recent_payments,
        unread_notifications=unread_notifications,
        pending_payment_requests_count=pending_payment_requests,  # اضافه شد
        pending_releases_count=pending_releases,  # اضافه شد
        now=datetime.now()
    )




# ==================== 2. مدیریت پروژه‌ها ====================

@employer_bp.route('/projects')
@login_required
def projects_list():
    """لیست پروژه‌های کارفرما"""
    if current_user.role != 'employer':
        flash('دسترسی غیرمجاز', 'danger')
        return redirect(url_for('auth.dashboard'))
    
    projects = Project.query.filter_by(employer_id=current_user.id).all()
    
    return render_template('employer/projects.html', projects=projects)


@employer_bp.route('/project/<int:project_id>')
@login_required
def project_dashboard(project_id):
    """داشبورد پروژه کارفرما"""
    if current_user.role != 'employer':
        flash('دسترسی غیرمجاز', 'danger')
        return redirect(url_for('auth.dashboard'))
    
    project = Project.query.get_or_404(project_id)
    
    # بررسی دسترسی کارفرما
    if project.employer_id != current_user.id:
        flash('شما به این پروژه دسترسی ندارید', 'danger')
        return redirect(url_for('employer.index'))
    
    today = datetime.now().date()
    
    # آمار حضور امروز
    today_attendances = Attendance.query.filter(
        Attendance.project_id == project.id,
        func.date(Attendance.check_in_time) == today
    ).all()
    
    # آمار حضور هفته جاری
    week_start = today - timedelta(days=today.weekday())
    weekly_attendances = Attendance.query.filter(
        Attendance.project_id == project.id,
        func.date(Attendance.check_in_time) >= week_start
    ).all()
    
    # لیست قراردادهای پروژه
    contracts = Contract.query.filter_by(
        project_id=project.id,
        is_active=True
    ).all()
    
    # اقساط معوق
    overdue_installments = ContractInstallment.query.join(Contract).filter(
        Contract.project_id == project.id,
        ContractInstallment.status == 'pending',
        ContractInstallment.due_date < today
    ).all()
    
    # گزارشات پروژه
    reports = Report.query.filter_by(
        project_id=project.id
    ).order_by(Report.created_at.desc()).limit(10).all()
    
    # درخواست‌های پرداخت
    payment_requests = PaymentRequest.query.join(Contract).filter(
        Contract.project_id == project.id
    ).order_by(PaymentRequest.created_at.desc()).limit(20).all()
    
    return render_template(
        'employer/project_dashboard.html',
        project=project,
        today_attendances=today_attendances,
        weekly_attendances=weekly_attendances,
        contracts=contracts,
        overdue_installments=overdue_installments,
        reports=reports,
        payment_requests=payment_requests,
        today=today,
        week_start=week_start
    )


# ==================== 3. مدیریت قراردادها و اقساط ====================

@employer_bp.route('/project/<int:project_id>/contracts')
@login_required
def project_contracts(project_id):
    """لیست قراردادهای پروژه"""
    if current_user.role != 'employer':
        flash('دسترسی غیرمجاز', 'danger')
        return redirect(url_for('auth.dashboard'))
    
    project = Project.query.get_or_404(project_id)
    
    if project.employer_id != current_user.id:
        flash('شما به این پروژه دسترسی ندارید', 'danger')
        return redirect(url_for('employer.index'))
    
    contracts = Contract.query.filter_by(project_id=project.id).all()
    
    return render_template('employer/contracts.html', project=project, contracts=contracts)


@employer_bp.route('/contract/<int:contract_id>/installments')
@login_required
def contract_installments(contract_id):
    """مشاهده جزئیات کامل اقساط یک قرارداد با کدهای شناسه پرداخت"""
    if current_user.role != 'employer':
        flash('دسترسی غیرمجاز', 'danger')
        return redirect(url_for('auth.dashboard'))
    
    contract = Contract.query.get_or_404(contract_id)
    
    # بررسی دسترسی کارفرما
    project = Project.query.get(contract.project_id)
    if project.employer_id != current_user.id:
        flash('شما به این قرارداد دسترسی ندارید', 'danger')
        return redirect(url_for('employer.index'))
    
    # دریافت اطلاعات کارمند
    employee = User.query.get(contract.employee_id)
    project_employee = ProjectEmployee.query.filter_by(
        project_id=project.id,
        employee_id=employee.id if employee else None
    ).first()
    
    # ============================================
    # دریافت اقساط با جزئیات کامل (مشابه کد مدیر)
    # ============================================
    
    # دریافت تمام اقساط قرارداد
    installments = Installment.query.filter_by(
        contract_id=contract_id
    ).order_by(Installment.installment_number).all()
    
    # دریافت جزئیات کامل هر قسط
    installment_details = []
    
    for installment in installments:
        # دریافت کد شناسایی پرداخت برای این قسط
        payment_identifier = PaymentIdentifier.query.filter_by(
            installment_id=installment.id,
            is_active=True
        ).first()
        
        # دریافت وضعیت کنترل‌ها
        controls = []
        if payment_identifier:
            try:
                controls = PaymentControl.query.filter_by(
                    payment_identifier_id=payment_identifier.id
                ).order_by(PaymentControl.created_at).all()
            except Exception as e:
                pass
        
        # دریافت پرداخت‌های انجام شده برای این قسط
        payments = InstallmentPayment.query.filter_by(
            installment_id=installment.id
        ).all()
        
        # دریافت درخواست‌های پرداخت مربوط به این قسط
        payment_requests = PaymentRequest.query.filter_by(
            installment_id=installment.id
        ).all()
        
        installment_details.append({
            'installment': installment,
            'payment_identifier': payment_identifier,
            'controls': controls,
            'payments': payments,
            'payment_requests': payment_requests,
            'is_paid': installment.is_paid,
            'status': installment.status,
            'contract': contract,
            'employee': employee,
            'project_employee': project_employee
        })
    
    # محاسبه آمار
    total_installments = len(installments)
    paid_installments = sum(1 for i in installments if i.is_paid)
    pending_installments = sum(1 for i in installments if i.status == 'pending')
    overdue_installments = sum(1 for i in installments if i.status == 'overdue')
    cancelled_installments = sum(1 for i in installments if i.status == 'cancelled')
    
    # محاسبه مجموع مبالغ
    total_amount = sum(i.amount for i in installments)
    paid_amount = sum(i.amount for i in installments if i.is_paid)
    pending_amount = sum(i.amount for i in installments if i.status == 'pending')
    overdue_amount = sum(i.amount for i in installments if i.status == 'overdue')
    
    # دریافت کدهای شناسایی پرداخت برای کل قرارداد (بدون قسط)
    full_payment_identifiers = []
    try:
        full_payment_identifiers = PaymentIdentifier.query.filter(
            PaymentIdentifier.contract_id == contract_id,
            PaymentIdentifier.installment_id.is_(None),
            PaymentIdentifier.is_active == True
        ).all()
    except Exception as e:
        pass
    
    return render_template(
        'employer/contract_installments.html',
        contract=contract,
        project=project,
        employee=employee,
        project_employee=project_employee,
        installments=installments,
        installment_details=installment_details,
        total_installments=total_installments,
        paid_installments=paid_installments,
        pending_installments=pending_installments,
        overdue_installments=overdue_installments,
        cancelled_installments=cancelled_installments,
        total_amount=total_amount,
        paid_amount=paid_amount,
        pending_amount=pending_amount,
        overdue_amount=overdue_amount,
        full_payment_identifiers=full_payment_identifiers,
        now=datetime.now()
    )


# ==================== 4. پرداخت اقساط با شناسه پرداخت ====================
@employer_bp.route('/installment/<int:installment_id>/pay', methods=['GET', 'POST'])
@login_required
def pay_installment(installment_id):
    """پرداخت قسط توسط کارفرما"""
    if current_user.role != 'employer':
        flash('دسترسی غیرمجاز', 'danger')
        return redirect(url_for('auth.dashboard'))
    
    installment = Installment.query.get_or_404(installment_id)
    contract = Contract.query.get(installment.contract_id)
    project = Project.query.get(contract.project_id)
    
    # بررسی دسترسی کارفرما
    if project.employer_id != current_user.id:
        flash('شما به این قسط دسترسی ندارید', 'danger')
        return redirect(url_for('employer.index'))
    
    if installment.is_paid:
        flash('این قسط قبلاً پرداخت شده است', 'warning')
        return redirect(url_for('employer.contract_installments', contract_id=contract.id))
    
    # دریافت کد شناسه پرداخت موجود (از زمان ایجاد قسط)
    payment_identifier = PaymentIdentifier.query.filter_by(
        installment_id=installment.id,
        is_active=True
    ).first()
    
    # اگر کد شناسه وجود نداشت، خطا بدهید
    if not payment_identifier:
        flash('کد شناسه پرداخت برای این قسط یافت نشد. لطفاً با مدیر سیستم تماس بگیرید.', 'danger')
        return redirect(url_for('employer.contract_installments', contract_id=contract.id))
    
    # دریافت اطلاعات صندوق امانی پروژه
    escrow_account = project.escrow_account
    system_account = escrow_account.system_account if escrow_account else None
    
    if request.method == 'POST':
        try:
            # دریافت اطلاعات پرداخت از فرم
            tracking_code = request.form.get('tracking_code')
            payment_date = datetime.strptime(request.form.get('payment_date'), '%Y-%m-%d').date()
            receipt_image = request.files.get('receipt_image')
            description = request.form.get('description', '')
            
            # ذخیره تصویر رسید
            receipt_path = None
            if receipt_image and receipt_image.filename:
                from app.employee.routes import save_image
                receipt_path = save_image(receipt_image, 'receipts')
            
            # ثبت پرداخت با استفاده از کد شناسه موجود
            payment = Payment(
                project_id=project.id,
                employee_id=contract.employee_id,
                employer_id=current_user.id,
                payment_identifier_id=payment_identifier.id,
                amount=installment.amount,
                installment_number=installment.installment_number,
                payment_method='bank_transfer',
                tracking_code=tracking_code,
                payment_date=payment_date,
                status='pending',
                recorded_by=current_user.id
            )
            db.session.add(payment)
            db.session.flush()
            
            # ایجاد درخواست پرداخت برای تایید
            payment_request = PaymentRequest(
                contract_id=contract.id,
                installment_id=installment.id,
                amount=installment.amount,
                request_date=payment_date,
                due_date=installment.due_date,
                employer_approved=True,
                employer_approved_at=datetime.utcnow(),
                employer_approved_by=current_user.id,
                status='pending',
                description=f'پرداخت قسط شماره {installment.installment_number} با شناسه پرداخت {payment_identifier.identifier_code}',
                created_by=current_user.id,
                project_id=project.id
            )
            db.session.add(payment_request)
            db.session.flush()
            
            # ثبت واریز به صندوق امانی
            if escrow_account:
                deposit = Deposit(
                    escrow_id=escrow_account.id,
                    project_id=project.id,
                    employer_id=current_user.id,
                    contract_id=contract.id,
                    amount=installment.amount,
                    installment_number=installment.installment_number,
                    tracking_code=tracking_code or f"DEP-{datetime.now().strftime('%Y%m%d%H%M%S')}",
                    payment_date=payment_date,
                    receipt_image=receipt_path,
                    source_bank=None,  # حذف شد
                    source_account=None,  # حذف شد
                    status='pending',
                    admin_verified=False,
                    description=f'واریز قسط شماره {installment.installment_number} - شناسه پرداخت {payment_identifier.identifier_code}'
                )
                db.session.add(deposit)
                
                # ثبت تراکنش صندوق امانی
                escrow_transaction = escrow_account.deposit(
                    amount=installment.amount,
                    tracking_code=tracking_code,
                    employer_id=current_user.id,
                    source_bank=None,  # حذف شد
                    source_account=None,  # حذف شد
                    description=f'واریز قسط شماره {installment.installment_number} - شناسه پرداخت {payment_identifier.identifier_code}'
                )
                if escrow_transaction:
                    db.session.add(escrow_transaction)
            
            # علامت زدن قسط به عنوان پرداخت شده
            installment.is_paid = True
            installment.status = 'paid'
            installment.paid_at = datetime.utcnow()
            installment.payment_date = payment_date
            
            db.session.commit()
            
            # ارسال نوتیفیکیشن به مدیر، ادمین و کارمند
            _send_payment_notifications(
                contract=contract,
                installment=installment,
                identifier_code=payment_identifier.identifier_code,
                tracking_code=tracking_code,
                amount=installment.amount,
                project=project
            )
            
            flash(f'✅ پرداخت قسط با موفقیت انجام شد. شناسه پرداخت: {payment_identifier.identifier_code}', 'success')
            return redirect(url_for('employer.contract_installments', contract_id=contract.id))
            
        except Exception as e:
            db.session.rollback()
            flash(f'❌ خطا در پرداخت: {str(e)}', 'danger')
            import traceback
            traceback.print_exc()
    
    return render_template(
        'employer/pay_installment.html',
        installment=installment,
        contract=contract,
        project=project,
        payment_identifier=payment_identifier,
        escrow_account=escrow_account,
        system_account=system_account
    )


def _send_payment_notifications(contract, installment, identifier_code, tracking_code, amount, project):
    """ارسال نوتیفیکیشن‌های پرداخت"""
    try:
        manager_id = project.manager_id
        employee_id = contract.employee_id
        
        admins = User.query.filter_by(role='admin').all()
        admin_ids = [admin.id for admin in admins]
        
        title = f'پرداخت قسط شماره {installment.installment_number}'
        message = f'قسط شماره {installment.installment_number} به مبلغ {amount:,.0f} ریال توسط کارفرما پرداخت شد. شناسه پرداخت: {identifier_code} - کد پیگیری: {tracking_code}'
        
        # ارسال به مدیر
        if manager_id:
            Notification.create(
                user_id=manager_id,
                title=title,
                message=message,
                type='success',
                link=f'/manager/payment-requests',
                data={'installment_id': installment.id, 'identifier_code': identifier_code}
            )
        
        # ارسال به کارمند
        if employee_id:
            Notification.create(
                user_id=employee_id,
                title=title,
                message=f'قسط شماره {installment.installment_number} به مبلغ {amount:,.0f} ریال پرداخت شد. شناسه پرداخت: {identifier_code}',
                type='success',
                link=f'/employee/contracts',
                data={'installment_id': installment.id, 'identifier_code': identifier_code}
            )
        
        # ارسال به ادمین‌ها
        for admin_id in admin_ids:
            Notification.create(
                user_id=admin_id,
                title=f'پرداخت جدید - {identifier_code}',
                message=f'قسط شماره {installment.installment_number} به مبلغ {amount:,.0f} ریال توسط کارفرما پرداخت شد. شناسه پرداخت: {identifier_code}',
                type='info',
                link=f'/admin/payment-requests',
                data={'installment_id': installment.id, 'identifier_code': identifier_code}
            )
            
    except Exception as e:
        print(f"خطا در ارسال نوتیفیکیشن: {str(e)}")


# ==================== 5. مدیریت گزارشات حضور و روزانه ====================

@employer_bp.route('/project/<int:project_id>/attendances')
@login_required
def project_attendances(project_id):
    """مشاهده گزارشات حضور کارکنان پروژه"""
    if current_user.role != 'employer':
        flash('دسترسی غیرمجاز', 'danger')
        return redirect(url_for('auth.dashboard'))
    
    project = Project.query.get_or_404(project_id)
    
    if project.employer_id != current_user.id:
        flash('شما به این پروژه دسترسی ندارید', 'danger')
        return redirect(url_for('employer.index'))
    
    # فیلترهای تاریخ
    from_date = request.args.get('from_date')
    to_date = request.args.get('to_date')
    employee_id = request.args.get('employee_id')
    
    query = Attendance.query.filter_by(project_id=project.id)
    
    if from_date:
        query = query.filter(func.date(Attendance.check_in_time) >= from_date)
    if to_date:
        query = query.filter(func.date(Attendance.check_in_time) <= to_date)
    if employee_id:
        query = query.filter_by(employee_id=employee_id)
    
    attendances = query.order_by(Attendance.check_in_time.desc()).all()
    
    # لیست کارکنان پروژه
    employees = ProjectEmployee.query.filter_by(
        project_id=project.id,
        is_active=True
    ).all()
    
    # محاسبه آمار حضور
    today = datetime.now().date()
    today_attendances = Attendance.query.filter(
        Attendance.project_id == project.id,
        func.date(Attendance.check_in_time) == today
    ).count()
    
    # آمار حضور ماه جاری
    month_start = today.replace(day=1)
    month_attendances = Attendance.query.filter(
        Attendance.project_id == project.id,
        func.date(Attendance.check_in_time) >= month_start
    ).count()
    
    return render_template(
        'employer/attendances.html',
        project=project,
        attendances=attendances,
        employees=employees,
        today_attendances=today_attendances,
        month_attendances=month_attendances,
        from_date=from_date,
        to_date=to_date,
        selected_employee=employee_id
    )


@employer_bp.route('/attendance/<int:attendance_id>/review', methods=['POST'])
@login_required
def review_attendance(attendance_id):
    """تایید یا رد گزارش حضور (اظهار نظر)"""
    if current_user.role != 'employer':
        return jsonify({'error': 'دسترسی غیرمجاز'}), 403
    
    attendance = Attendance.query.get_or_404(attendance_id)
    project = Project.query.get(attendance.project_id)
    
    if project.employer_id != current_user.id:
        return jsonify({'error': 'شما به این گزارش دسترسی ندارید'}), 403
    
    data = request.get_json()
    status = data.get('status')  # approved, rejected
    comment = data.get('comment', '')
    
    if status not in ['approved', 'rejected']:
        return jsonify({'error': 'وضعیت نامعتبر'}), 400
    
    # بروزرسانی وضعیت گزارش حضور
    attendance.employer_reviewed = True
    attendance.employer_reviewed_at = datetime.utcnow()
    attendance.employer_comment = comment
    
    if status == 'approved':
        attendance.employer_approved = True
        flash_message = 'گزارش حضور تایید شد'
    else:
        attendance.employer_approved = False
        flash_message = 'گزارش حضور رد شد'
    
    db.session.commit()
    
    # ارسال نوتیفیکیشن به کارمند
    Notification.create(
        user_id=attendance.employee_id,
        title='نتیجه بررسی گزارش حضور',
        message=f'گزارش حضور شما در تاریخ {attendance.check_in_time.strftime("%Y-%m-%d")} توسط کارفرما {status} شد. نظر: {comment}',
        type='success' if status == 'approved' else 'danger',
        link=f'/employee/attendances'
    )
    
    return jsonify({'success': True, 'message': flash_message})


@employer_bp.route('/project/<int:project_id>/smart-reports')
@login_required
def project_smart_reports(project_id):
    """مشاهده گزارشات هوشمند حضور پروژه"""
    if current_user.role != 'employer':
        flash('دسترسی غیرمجاز', 'danger')
        return redirect(url_for('auth.dashboard'))
    
    project = Project.query.get_or_404(project_id)
    
    if project.employer_id != current_user.id:
        flash('شما به این پروژه دسترسی ندارید', 'danger')
        return redirect(url_for('employer.index'))
    
    smart_reports = SmartReport.query.filter_by(
        project_id=project.id
    ).order_by(SmartReport.report_date.desc()).all()
    
    return render_template(
        'employer/smart_reports.html',
        project=project,
        smart_reports=smart_reports
    )


@employer_bp.route('/smart-report/<int:report_id>/employer-approve', methods=['POST'])
@login_required
def employer_approve_smart_report(report_id):
    """تایید گزارش هوشمند توسط کارفرما"""
    if current_user.role != 'employer':
        return jsonify({'error': 'دسترسی غیرمجاز'}), 403
    
    report = SmartReport.query.get_or_404(report_id)
    project = Project.query.get(report.project_id)
    
    if project.employer_id != current_user.id:
        return jsonify({'error': 'شما به این گزارش دسترسی ندارید'}), 403
    
    data = request.get_json()
    status = data.get('status')
    comment = data.get('comment', '')
    
    report.employer_approved = True
    report.employer_approved_at = datetime.utcnow()
    report.employer_comment = comment
    
    db.session.commit()
    
    # ارسال نوتیفیکیشن
    Notification.create(
        user_id=report.employee_id,
        title='تایید گزارش هوشمند',
        message=f'گزارش هوشمند حضور شما در تاریخ {report.report_date.strftime("%Y-%m-%d")} توسط کارفرما تایید شد.',
        type='success',
        link=f'/employee/smart-reports'
    )
    
    return jsonify({'success': True, 'message': 'گزارش هوشمند تایید شد'})


# ==================== 6. گزارشات کارکنان (Photo Reports) ====================

@employer_bp.route('/project/<int:project_id>/photo-reports')
@login_required
def project_photo_reports(project_id):
    """مشاهده گزارشات تصویری کارکنان"""
    if current_user.role != 'employer':
        flash('دسترسی غیرمجاز', 'danger')
        return redirect(url_for('auth.dashboard'))
    
    project = Project.query.get_or_404(project_id)
    
    if project.employer_id != current_user.id:
        flash('شما به این پروژه دسترسی ندارید', 'danger')
        return redirect(url_for('employer.index'))
    
    photo_reports = PhotoReport.query.filter_by(
        project_id=project.id
    ).order_by(PhotoReport.report_time.desc()).all()
    
    return render_template(
        'employer/photo_reports.html',
        project=project,
        photo_reports=photo_reports
    )


@employer_bp.route('/photo-report/<int:report_id>/review', methods=['POST'])
@login_required
def review_photo_report(report_id):
    """بررسی و اظهار نظر روی گزارش تصویری"""
    if current_user.role != 'employer':
        return jsonify({'error': 'دسترسی غیرمجاز'}), 403
    
    photo_report = PhotoReport.query.get_or_404(report_id)
    project = Project.query.get(photo_report.project_id)
    
    if project.employer_id != current_user.id:
        return jsonify({'error': 'شما به این گزارش دسترسی ندارید'}), 403
    
    data = request.get_json()
    comment = data.get('comment', '')
    verified = data.get('verified', False)
    
    photo_report.employer_reviewed = True
    photo_report.employer_reviewed_at = datetime.utcnow()
    photo_report.employer_comment = comment
    photo_report.employer_verified = verified
    
    db.session.commit()
    
    return jsonify({
        'success': True,
        'message': 'نظر شما با موفقیت ثبت شد'
    })


# ==================== 7. تهیه و ابلاغ برنامه کارگاهی ====================
@employer_bp.route('/project/<int:project_id>/work-plan/create', methods=['GET', 'POST'])
@login_required
def create_work_plan(project_id):
    """ایجاد برنامه کارگاهی جدید"""
    if current_user.role != 'employer':
        flash('دسترسی غیرمجاز', 'danger')
        return redirect(url_for('auth.dashboard'))
    
    project = Project.query.get_or_404(project_id)
    
    if project.employer_id != current_user.id:
        flash('شما به این پروژه دسترسی ندارید', 'danger')
        return redirect(url_for('employer.index'))
    
    # ایجاد فرم
    from app.employer.forms import WorkPlanForm
    form = WorkPlanForm()
    
    if request.method == 'POST':
        try:
            plan_type = request.form.get('plan_type')
            title = request.form.get('title')
            content = request.form.get('content')
            start_date = datetime.strptime(request.form.get('start_date'), '%Y-%m-%d').date()
            end_date = request.form.get('end_date')
            if end_date:
                end_date = datetime.strptime(end_date, '%Y-%m-%d').date()
            
            # دریافت لیست کارکنان برای ابلاغ
            employee_ids = request.form.getlist('employee_ids')
            
            # ایجاد گزارش برنامه کارگاهی
            report = Report(
                project_id=project.id,
                employer_id=current_user.id,
                report_type=plan_type,
                title=title,
                content=content,
                status='pending',
                created_by=current_user.id,
                start_date=start_date,
                end_date=end_date
            )
            db.session.add(report)
            db.session.flush()
            
            # ابلاغ به کارکنان
            if employee_ids:
                for emp_id in employee_ids:
                    Notification.create(
                        user_id=int(emp_id),
                        title=f'برنامه کارگاهی جدید - {title}',
                        message=f'برنامه کارگاهی {plan_type} با عنوان "{title}" برای پروژه {project.name} تهیه شده است. لطفاً مشاهده کنید.',
                        type='primary',
                        link=f'/employee/work-plans/{report.id}',
                        data={'report_id': report.id, 'project_id': project.id}
                    )
            
            # ارسال به مدیر پروژه
            if project.manager_id:
                Notification.create(
                    user_id=project.manager_id,
                    title=f'برنامه کارگاهی جدید - {title}',
                    message=f'برنامه کارگاهی {plan_type} با عنوان "{title}" برای پروژه {project.name} تهیه شده است.',
                    type='primary',
                    link=f'/manager/work-plans/{report.id}',
                    data={'report_id': report.id, 'project_id': project.id}
                )
            
            # ارسال به ادمین در صورت نیاز
            if request.form.get('send_to_admin'):
                admins = User.query.filter_by(role='admin', is_active=True).all()
                for admin in admins:
                    Notification.create(
                        user_id=admin.id,
                        title=f'برنامه کارگاهی جدید - {title}',
                        message=f'برنامه کارگاهی {plan_type} با عنوان "{title}" برای پروژه {project.name} تهیه شده است.',
                        type='primary',
                        link=f'/admin/work-plans/{report.id}',
                        data={'report_id': report.id, 'project_id': project.id}
                    )
            
            db.session.commit()
            flash(f'برنامه کارگاهی با موفقیت ایجاد و به {len(employee_ids)} نفر ابلاغ شد', 'success')
            return redirect(url_for('employer.work_plan', project_id=project.id))
            
        except Exception as e:
            db.session.rollback()
            flash(f'خطا در ایجاد برنامه: {str(e)}', 'danger')
            import traceback
            traceback.print_exc()
    
    # دریافت لیست کارکنان پروژه
    employees = ProjectEmployee.query.filter_by(
        project_id=project.id,
        is_active=True
    ).all()
    
    return render_template(
        'employer/create_work_plan.html',
        project=project,
        employees=employees,
        form=form,
        now=datetime.now()
    )


#=====
@employer_bp.route('/project/<int:project_id>/work-plan')
@login_required
def work_plan(project_id):
    """مشاهده و تهیه برنامه کارگاهی"""
    if current_user.role != 'employer':
        flash('دسترسی غیرمجاز', 'danger')
        return redirect(url_for('auth.dashboard'))
    
    project = Project.query.get_or_404(project_id)
    
    if project.employer_id != current_user.id:
        flash('شما به این پروژه دسترسی ندارید', 'danger')
        return redirect(url_for('employer.index'))
    
    # دریافت برنامه‌های موجود
    work_plans = Report.query.filter_by(
        project_id=project.id,
        report_type='weekly'  # یا daily, monthly
    ).order_by(Report.created_at.desc()).all()
    
    return render_template(
        'employer/work_plan.html',
        project=project,
        work_plans=work_plans
    )



@employer_bp.route('/work-plan/<int:plan_id>/edit', methods=['GET', 'POST'])
@login_required
def edit_work_plan(plan_id):
    """ویرایش برنامه کارگاهی"""
    if current_user.role != 'employer':
        flash('دسترسی غیرمجاز', 'danger')
        return redirect(url_for('auth.dashboard'))
    
    plan = Report.query.get_or_404(plan_id)
    project = Project.query.get(plan.project_id)
    
    if project.employer_id != current_user.id:
        flash('شما به این برنامه دسترسی ندارید', 'danger')
        return redirect(url_for('employer.index'))
    
    if request.method == 'POST':
        try:
            plan.title = request.form.get('title')
            plan.content = request.form.get('content')
            plan.updated_at = datetime.utcnow()
            
            db.session.commit()
            flash('برنامه با موفقیت ویرایش شد', 'success')
            return redirect(url_for('employer.work_plan', project_id=project.id))
            
        except Exception as e:
            db.session.rollback()
            flash(f'خطا در ویرایش: {str(e)}', 'danger')
    
    return render_template(
        'employer/edit_work_plan.html',
        plan=plan,
        project=project
    )


# ==================== 8. مدیریت درخواست‌های پرداخت ====================

@employer_bp.route('/payment-requests')
@login_required
def payment_requests_list():
    """لیست درخواست‌های پرداخت برای تایید"""
    if current_user.role != 'employer':
        flash('دسترسی غیرمجاز', 'danger')
        return redirect(url_for('auth.dashboard'))
    
    # دریافت پروژه‌های کارفرما
    projects = Project.query.filter_by(employer_id=current_user.id).all()
    project_ids = [p.id for p in projects]
    
    # درخواست‌های در انتظار تایید کارفرما
    pending_requests = PaymentRequest.query.join(Contract).filter(
        Contract.project_id.in_(project_ids),
        PaymentRequest.employer_approved == False,
        PaymentRequest.status == 'pending'
    ).order_by(PaymentRequest.created_at.desc()).all()
    
    # درخواست‌های تایید شده توسط کارفرما
    approved_requests = PaymentRequest.query.join(Contract).filter(
        Contract.project_id.in_(project_ids),
        PaymentRequest.employer_approved == True
    ).order_by(PaymentRequest.created_at.desc()).all()
    
    return render_template(
        'employer/payment_requests.html',
        pending_requests=pending_requests,
        approved_requests=approved_requests
    )


@employer_bp.route('/payment-request/<int:request_id>/approve', methods=['POST'])
@login_required
def approve_payment_request(request_id):
    """تایید درخواست پرداخت توسط کارفرما"""
    if current_user.role != 'employer':
        return jsonify({'error': 'دسترسی غیرمجاز'}), 403
    
    payment_request = PaymentRequest.query.get_or_404(request_id)
    contract = Contract.query.get(payment_request.contract_id)
    project = Project.query.get(contract.project_id)
    
    if project.employer_id != current_user.id:
        return jsonify({'error': 'شما به این درخواست دسترسی ندارید'}), 403
    
    data = request.get_json()
    status = data.get('status')
    comment = data.get('comment', '')
    
    if status == 'approved':
        payment_request.employer_approved = True
        payment_request.employer_approved_at = datetime.utcnow()
        payment_request.employer_approved_by = current_user.id
        payment_request._check_approvals()
        
        # ارسال نوتیفیکیشن
        Notification.create(
            user_id=contract.employee_id,
            title='تایید درخواست پرداخت',
            message=f'درخواست پرداخت شما به مبلغ {payment_request.amount:,.0f} تومان توسط کارفرما تایید شد.',
            type='success',
            link=f'/employee/payment-requests'
        )
        
        db.session.commit()
        return jsonify({'success': True, 'message': 'درخواست پرداخت تایید شد'})
    
    else:
        payment_request.reject(current_user.id, comment)
        db.session.commit()
        
        # ارسال نوتیفیکیشن رد
        Notification.create(
            user_id=contract.employee_id,
            title='رد درخواست پرداخت',
            message=f'درخواست پرداخت شما به مبلغ {payment_request.amount:,.0f} تومان توسط کارفرما رد شد. دلیل: {comment}',
            type='danger',
            link=f'/employee/payment-requests'
        )
        
        return jsonify({'success': True, 'message': 'درخواست پرداخت رد شد'})


# ==================== 9. مدیریت درخواست‌های آزادسازی ====================

@employer_bp.route('/payment-releases')
@login_required
def payment_releases_list():
    """لیست درخواست‌های آزادسازی برای تایید"""
    if current_user.role != 'employer':
        flash('دسترسی غیرمجاز', 'danger')
        return redirect(url_for('auth.dashboard'))
    
    projects = Project.query.filter_by(employer_id=current_user.id).all()
    project_ids = [p.id for p in projects]
    
    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'
    ).order_by(PaymentRelease.created_at.desc()).all()
    
    approved_releases = PaymentRelease.query.filter(
        PaymentRelease.contract_id.in_(
            db.session.query(Contract.id).filter(Contract.project_id.in_(project_ids))
        ),
        PaymentRelease.employer_approved == True
    ).order_by(PaymentRelease.created_at.desc()).all()
    
    return render_template(
        'employer/payment_releases.html',
        pending_releases=pending_releases,
        approved_releases=approved_releases
    )


@employer_bp.route('/payment-release/<int:release_id>/approve', methods=['POST'])
@login_required
def approve_payment_release(release_id):
    """تایید درخواست آزادسازی توسط کارفرما"""
    if current_user.role != 'employer':
        return jsonify({'error': 'دسترسی غیرمجاز'}), 403
    
    payment_release = PaymentRelease.query.get_or_404(release_id)
    contract = Contract.query.get(payment_release.contract_id)
    project = Project.query.get(contract.project_id)
    
    if project.employer_id != current_user.id:
        return jsonify({'error': 'شما به این درخواست دسترسی ندارید'}), 403
    
    data = request.get_json()
    status = data.get('status')
    comment = data.get('comment', '')
    
    if status == 'approved':
        payment_release.employer_approved = True
        payment_release.employer_approved_at = datetime.utcnow()
        payment_release._check_approvals()
        
        db.session.commit()
        return jsonify({'success': True, 'message': 'درخواست آزادسازی تایید شد'})
    
    else:
        payment_release.reject(comment)
        db.session.commit()
        return jsonify({'success': True, 'message': 'درخواست آزادسازی رد شد'})


# ==================== 10. گزارشات مالی ====================

@employer_bp.route('/financial-reports')
@login_required
def financial_reports():
    """گزارشات مالی کارفرما"""
    if current_user.role != 'employer':
        flash('دسترسی غیرمجاز', 'danger')
        return redirect(url_for('auth.dashboard'))
    
    projects = Project.query.filter_by(employer_id=current_user.id).all()
    project_ids = [p.id for p in projects]
    
    # جمع کل پرداختی‌ها
    total_payments = db.session.query(func.sum(Payment.amount)).filter(
        Payment.project_id.in_(project_ids),
        Payment.status == 'paid'
    ).scalar() or 0
    
    # جمع کل واریزی‌ها
    total_deposits = db.session.query(func.sum(Deposit.amount)).filter(
        Deposit.project_id.in_(project_ids),
        Deposit.status == 'verified'
    ).scalar() or 0
    
    # مبلغ باقیمانده
    total_remaining = db.session.query(func.sum(Contract.remaining_amount)).filter(
        Contract.project_id.in_(project_ids)
    ).scalar() or 0
    
    # گزارش ماهانه
    today = datetime.now().date()
    month_start = today.replace(day=1)
    
    monthly_payments = db.session.query(func.sum(Payment.amount)).filter(
        Payment.project_id.in_(project_ids),
        Payment.payment_date >= month_start,
        Payment.status == 'paid'
    ).scalar() or 0
    
    return render_template(
        'employer/financial_reports.html',
        projects=projects,
        total_payments=total_payments,
        total_deposits=total_deposits,
        total_remaining=total_remaining,
        monthly_payments=monthly_payments,
        month_start=month_start,
        today=today
    )


# ==================== 11. API endpoints ====================

@employer_bp.route('/api/my-projects')
@login_required
def my_projects_api():
    """API دریافت پروژه‌های کارفرما"""
    if current_user.role != 'employer':
        return jsonify({'error': 'دسترسی غیرمجاز'}), 403
    
    projects = Project.query.filter_by(employer_id=current_user.id).all()
    
    return jsonify([{
        'id': p.id,
        'name': p.name,
        'project_code': p.project_code,
        'status': p.status,
        'status_display': p.get_status_display(),
        'employee_count': p.get_employee_count(),
        'today_attendance': p.get_today_attendance_count(),
        'escrow_balance': p.get_escrow_balance(),
        'total_contracts_value': p.get_total_contracts_value()
    } for p in projects])


@employer_bp.route('/api/project/<int:project_id>/stats')
@login_required
def project_stats_api(project_id):
    """API دریافت آمار پروژه"""
    if current_user.role != 'employer':
        return jsonify({'error': 'دسترسی غیرمجاز'}), 403
    
    project = Project.query.get_or_404(project_id)
    
    if project.employer_id != current_user.id:
        return jsonify({'error': 'دسترسی غیرمجاز'}), 403
    
    today = datetime.now().date()
    week_start = today - timedelta(days=today.weekday())
    month_start = today.replace(day=1)
    
    stats = {
        'total_employees': project.get_employee_count(),
        'today_attendance': project.get_today_attendance_count(),
        'weekly_attendance': Attendance.query.filter(
            Attendance.project_id == project.id,
            func.date(Attendance.check_in_time) >= week_start
        ).count(),
        'monthly_attendance': Attendance.query.filter(
            Attendance.project_id == project.id,
            func.date(Attendance.check_in_time) >= month_start
        ).count(),
        'total_contracts': len(project.contracts),
        'total_contracts_value': project.get_total_contracts_value(),
        'total_deposits': project.get_total_deposits(),
        'escrow_balance': project.get_escrow_balance(),
        'pending_payment_requests': len(project.project_pending_payment_requests),
        'overdue_installments': ContractInstallment.query.join(Contract).filter(
            Contract.project_id == project.id,
            ContractInstallment.status == 'pending',
            ContractInstallment.due_date < today
        ).count()
    }
    
    return jsonify(stats)

# ==================== 12. مشاهده جزئیات اقساط پروژه با کد شناسه پرداخت ====================

@employer_bp.route('/project/<int:project_id>/installments-detail')
@login_required
def project_installments_detail(project_id):
    """مشاهده جزئیات کامل اقساط پروژه با کدهای شناسه پرداخت"""
    if current_user.role != 'employer':
        flash('دسترسی غیرمجاز', 'danger')
        return redirect(url_for('auth.dashboard'))
    
    project = Project.query.get_or_404(project_id)
    
    # بررسی دسترسی کارفرما
    if project.employer_id != current_user.id:
        flash('شما به این پروژه دسترسی ندارید', 'danger')
        return redirect(url_for('employer.index'))
    
    # دریافت تمام قراردادهای فعال پروژه
    contracts = Contract.query.filter_by(
        project_id=project.id,
        is_active=True
    ).all()
    contract_ids = [c.id for c in contracts]
    
    # دریافت تمام اقساط مربوط به قراردادهای پروژه
    installments = []
    installment_details = []
    
    if contract_ids:
        # دریافت اقساط
        installments = Installment.query.filter(
            Installment.contract_id.in_(contract_ids)
        ).order_by(Installment.due_date).all()
        
        # دریافت کدهای شناسایی پرداخت برای هر قسط
        for installment in installments:
            # دریافت کد شناسایی پرداخت برای این قسط
            payment_identifier = PaymentIdentifier.query.filter_by(
                installment_id=installment.id,
                is_active=True
            ).first()
            
            # دریافت وضعیت کنترل‌ها
            controls = []
            if payment_identifier:
                controls = PaymentControl.query.filter_by(
                    payment_identifier_id=payment_identifier.id
                ).order_by(PaymentControl.created_at).all()
            
            # دریافت پرداخت‌های انجام شده برای این قسط
            payments = InstallmentPayment.query.filter_by(
                installment_id=installment.id
            ).all()
            
            # دریافت درخواست‌های پرداخت مربوط به این قسط
            payment_requests = PaymentRequest.query.filter_by(
                installment_id=installment.id
            ).all()
            
            # دریافت اطلاعات کارمند مربوط به قرارداد
            contract = Contract.query.get(installment.contract_id)
            employee = User.query.get(contract.employee_id) if contract else None
            project_employee = ProjectEmployee.query.filter_by(
                project_id=project.id,
                employee_id=employee.id if employee else None
            ).first()
            
            installment_details.append({
                'installment': installment,
                'payment_identifier': payment_identifier,
                'controls': controls,
                'payments': payments,
                'payment_requests': payment_requests,
                'is_paid': installment.is_paid,
                'status': installment.status,
                'contract': contract,
                'employee': employee,
                'project_employee': project_employee,
                'role_type': project_employee.role_type if project_employee else None,
                'job_title': project_employee.job_title if project_employee else None
            })
    
    # آمار اقساط
    total_installments = len(installments)
    paid_installments = sum(1 for i in installments if i.is_paid)
    pending_installments = sum(1 for i in installments if i.status == 'pending')
    overdue_installments = sum(1 for i in installments if i.status == 'overdue')
    cancelled_installments = sum(1 for i in installments if i.status == 'cancelled')
    
    # محاسبه مجموع مبالغ
    total_amount = sum(i.amount for i in installments)
    paid_amount = sum(i.amount for i in installments if i.is_paid)
    pending_amount = sum(i.amount for i in installments if i.status == 'pending')
    overdue_amount = sum(i.amount for i in installments if i.status == 'overdue')
    
    # دریافت کدهای شناسایی پرداخت برای کل قراردادها (بدون قسط)
    full_payment_identifiers = PaymentIdentifier.query.filter(
        PaymentIdentifier.contract_id.in_(contract_ids),
        PaymentIdentifier.installment_id.is_(None),
        PaymentIdentifier.is_active == True
    ).all()
    
    return render_template(
        'employer/project_installments_detail.html',
        project=project,
        contracts=contracts,
        installments=installments,
        installment_details=installment_details,
        total_installments=total_installments,
        paid_installments=paid_installments,
        pending_installments=pending_installments,
        overdue_installments=overdue_installments,
        cancelled_installments=cancelled_installments,
        total_amount=total_amount,
        paid_amount=paid_amount,
        pending_amount=pending_amount,
        overdue_amount=overdue_amount,
        full_payment_identifiers=full_payment_identifiers,
        now=datetime.now()
    )


@employer_bp.route('/payment-identifier/<int:identifier_id>/detail')
@login_required
def employer_payment_identifier_detail(identifier_id):
    """مشاهده جزئیات کد شناسه پرداخت توسط کارفرما"""
    if current_user.role != 'employer':
        flash('دسترسی غیرمجاز', 'danger')
        return redirect(url_for('auth.dashboard'))
    
    payment_identifier = PaymentIdentifier.query.get_or_404(identifier_id)
    contract = payment_identifier.contract
    project = contract.project
    
    # بررسی دسترسی کارفرما
    if project.employer_id != current_user.id:
        flash('شما به این کد شناسه دسترسی ندارید', 'danger')
        return redirect(url_for('employer.index'))
    
    # دریافت کنترل‌ها
    controls = PaymentControl.query.filter_by(
        payment_identifier_id=identifier_id
    ).order_by(PaymentControl.created_at).all()
    
    # دریافت چک‌ها
    checks = CheckIssuance.query.filter_by(
        payment_identifier_id=identifier_id
    ).all()
    
    # دریافت پرداخت‌ها
    payments = Payment.query.filter_by(
        payment_identifier_id=identifier_id
    ).all()
    
    # دریافت درخواست‌های پرداخت
    payment_requests = PaymentRequest.query.filter_by(
        contract_id=contract.id
    ).all()
    
    # دریافت اطلاعات قسط
    installment = None
    if payment_identifier.installment_id:
        installment = Installment.query.get(payment_identifier.installment_id)
    
    return render_template(
        'employer/payment_identifier_detail.html',
        payment_identifier=payment_identifier,
        contract=contract,
        project=project,
        controls=controls,
        checks=checks,
        payments=payments,
        payment_requests=payment_requests,
        installment=installment
    )

#==========

@employer_bp.route('/api/installment/<int:installment_id>/payment-status')
@login_required
def installment_payment_status_api(installment_id):
    """API بررسی وضعیت پرداخت قسط"""
    if current_user.role != 'employer':
        return jsonify({'error': 'دسترسی غیرمجاز'}), 403
    
    installment = ContractInstallment.query.get_or_404(installment_id)
    contract = Contract.query.get(installment.contract_id)
    project = Project.query.get(contract.project_id)
    
    if project.employer_id != current_user.id:
        return jsonify({'error': 'دسترسی غیرمجاز'}), 403
    
    return jsonify({
        'id': installment.id,
        'status': installment.status,
        'status_display': installment.get_status_display(),
        'is_overdue': installment.is_overdue(),
        'amount': installment.amount,
        'amount_formatted': f"{installment.amount:,.0f}",
        'due_date': installment.due_date.strftime('%Y-%m-%d'),
        'paid_at': installment.paid_at.strftime('%Y-%m-%d %H:%M:%S') if installment.paid_at else None
    })

# app/employer/routes.py

@employer_bp.route('/profile', methods=['GET', 'POST'])
@login_required
def profile():
    """مشاهده و ویرایش پروفایل کارفرما"""
    if current_user.role != 'employer':
        flash('دسترسی غیرمجاز', 'danger')
        return redirect(url_for('auth.dashboard'))
    
    from app.employer.forms import ProfileForm
    
    form = ProfileForm(obj=current_user)
    
    if form.validate_on_submit():
        try:
            current_user.fullname = form.fullname.data
            current_user.phone = form.phone.data
            current_user.email = form.email.data
            current_user.address = form.address.data
            
            db.session.commit()
            flash('✅ اطلاعات شما با موفقیت به‌روزرسانی شد', 'success')
            return redirect(url_for('employer.profile'))
        except Exception as e:
            db.session.rollback()
            flash(f'❌ خطا در به‌روزرسانی: {str(e)}', 'danger')
    
    return render_template('employer/profile.html', form=form)