from flask import render_template, redirect, url_for
from flask_login import login_required, current_user
from app.dashboard import dashboard_bp
from app.extensions import db
from app.models import User, Project, Attendance,AdvertisementRequest
from datetime import datetime, date



@dashboard_bp.route('/')
def index():
    """صفحه اصلی سایت"""
    # تبلیغات تایید شده و فعال
    approved_ads = AdvertisementRequest.query.filter(
        AdvertisementRequest.status == 'approved',
        AdvertisementRequest.start_date <= datetime.utcnow(),
        AdvertisementRequest.end_date >= datetime.utcnow()
    ).order_by(AdvertisementRequest.created_at.desc()).all()
    
    # پروژه‌های فعال برای نمایش
    active_projects = Project.query.filter_by(status='active').limit(6).all()
    
    # آمار کلی برای نمایش در صفحه اصلی
    stats = {
        'total_managers': User.query.filter_by(role='manager', is_active=True).count(),
        'total_projects': Project.query.filter_by(status='active').count(),
        'total_employees': User.query.filter_by(role='employee', is_active=True).count(),
        'total_employers': User.query.filter_by(role='employer', is_active=True).count(),
        'total_advertisements': len(approved_ads)
    }
    
    return render_template('public/index.html', 
                         advertisements=approved_ads,
                         projects=active_projects,
                         stats=stats)




@dashboard_bp.route('/advertisement/click/<int:ad_id>')
def advertisement_click(ad_id):
    """ثبت کلیک روی تبلیغ"""
    ad = AdvertisementRequest.query.get_or_404(ad_id)
    ad.click_count += 1
    db.session.commit()
    
    # ریدایرکت به لینک تبلیغ
    if ad.target_url:
        return redirect(ad.target_url)
    return redirect(url_for('dashboard.index'))


@dashboard_bp.route('/admin')
@login_required
def admin():
    if current_user.role != 'admin':
        return redirect(url_for('auth.dashboard'))
    
    total_users = User.query.count()
    total_projects = Project.query.count()
    today_attendance = Attendance.query.filter(
        Attendance.check_in_time >= date.today()
    ).count()
    
    return render_template('admin/index.html',
                         total_users=total_users,
                         total_projects=total_projects,
                         today_attendance=today_attendance,
                         on_time_count=50,
                         users=User.query.all(),
                         recent_activities=[],
                         weekly_attendance=[45, 52, 48, 60, 55, 42],
                         project_status=[15, 8, 3])

@dashboard_bp.route('/manager')
@login_required
def manager():
    if current_user.role != 'manager':
        return redirect(url_for('auth.dashboard'))
    
    projects = Project.query.filter_by(manager_id=current_user.id).all()
    return render_template('manager/index.html', projects=projects)

@dashboard_bp.route('/employer')
@login_required
def employer():
    if current_user.role != 'employer':
        return redirect(url_for('auth.dashboard'))
    
    projects = Project.query.filter_by(employer_id=current_user.id).all()
    return render_template('employer/index.html', 
                         projects=projects,
                         active_projects=projects,
                         total_employees=25,
                         total_work_hours=180,
                         managers=User.query.filter_by(role='manager').all())

@dashboard_bp.route('/employee')
@login_required
def employee():
    if current_user.role != 'employee':
        return redirect(url_for('auth.dashboard'))
    
    today_attendance = Attendance.query.filter(
        Attendance.employee_id == current_user.id,
        Attendance.check_in_time >= date.today()
    ).first()
    
    return render_template('employee/index.html',
                         has_checked_in=today_attendance is not None,
                         attendance_history=[],
                         current_project=None)