import json
from django.contrib.auth import get_user_model
User = get_user_model()
from django.conf import settings
from blog.models import BlogPost
from django.core.paginator import Paginator
from django.shortcuts import render, redirect, get_object_or_404, reverse
from django.contrib import messages
from .models import Job, Application, Profile, ContactMessage, RecruiterProfile, ReferralWallet, Transaction, WithdrawalRequest, CandidateWallet, NewsPost, CoinTransaction, LuckyWheelActivity, AIResumeSnapshot, SiteHit, TradePosition, COUNTRY_CHOICES, CountryGuide, FormOTP, EmployerRequirement
from .utils import add_v_coins, deduct_v_coins
from django.core.mail import send_mail
from django.contrib.sitemaps import Sitemap
import requests # Library ki zaroorat nahi, seedha HTTP call
import traceback
from datetime import datetime, time
from django.core.exceptions import ValidationError
from django.utils import timezone
import random
from django.db.models import Q
from travels.models import Trip, TravelBlog
from study.models import StudyDestination, Program, StudyBlog
from django.urls import reverse
from django.utils.text import slugify
from .utils_ai import generate_country_guide_ai
import re
import base64
from datetime import timedelta
from django.views.decorators.csrf import csrf_exempt
import openpyxl
from decimal import Decimal # ✅ Zaroori import calculations ke liye
from django.contrib.auth.decorators import login_required, user_passes_test
from django.contrib.auth import authenticate, login, logout
from django.db.models import Count
from .forms import CandidateProfileForm, JobPostForm, RecruiterProfileForm, RecruiterBrandingForm
from django.http import JsonResponse, HttpResponse
from .decorators import recruiter_required, candidate_required
from blog.models import BlogPost

def home(request):
    """
    NEW HOMEPAGE VIEW (Design 3 - Authority Hub) 🚀
    Template: jobs/home.html
    """
    # 1. Top Bar & Sidebar News
    breaking_news = NewsPost.objects.filter(status='published', is_breaking=True)[:6]
    latest_news = NewsPost.objects.filter(status='published').order_by('-created_at')[:12]
    
    # 2. Expert Guides (Gyan Kendra)
    latest_guides = BlogPost.objects.filter(is_published=True).order_by('-created_at')[:6]
    
    # 3. Hierarchy based Jobs for the Hub (No Pagination needed here)
    # Pehle 12 jobs fetch kar rahe hain, template handle karega 1 Big, 2 Mid, rest Slider.
    featured_jobs = Job.objects.filter(is_approved=True).order_by('-is_featured', '-is_hot', '-id')[:12]
    active_country_codes = Job.objects.filter(is_approved=True).values_list('country', flat=True).distinct()

    context = {
        'jobs': featured_jobs,
        'countries': COUNTRY_CHOICES,
        'active_codes': active_country_codes,
        'breaking_news': breaking_news,
        'latest_news': latest_news,
        'latest_guides': latest_guides,
    }
    return render(request, 'jobs/home.html', context)
    
def job_list(request):
    """
    DEDICATED JOB LISTING PAGE 📋
    URL: /jobs/find-overseas-jobs/
    Template: jobs/job_list.html (Purana home.html)
    """
    query = request.GET.get('search') 
    country_filter = request.GET.get('country') 
    
    # --- Role Based Filtering ---
    if request.user.is_authenticated:
        if request.user.is_staff or request.user.is_superuser:
            jobs_base = Job.objects.all()
        elif request.user.is_recruiter:
            jobs_base = Job.objects.filter(posted_by=request.user)
        else:
            jobs_base = Job.objects.filter(is_approved=True)
    else:
        jobs_base = Job.objects.filter(is_approved=True)
        
    # --- Filter & Sort ---
    jobs_base = jobs_base.order_by('-is_featured', '-is_hot', '-id', 'sequence')
    
    if query:
        jobs_base = jobs_base.filter(
            Q(title__icontains=query) | 
            Q(industry_old__icontains=query) |
            Q(industry_master__name__icontains=query)
        ).distinct()
    
    if country_filter:
        jobs_base = jobs_base.filter(country__icontains=country_filter)

    # --- Applied Tracking ---
    applied_job_ids = []
    if request.user.is_authenticated:
        from .models import Application
        applied_job_ids = Application.objects.filter(user=request.user).values_list('job_id', flat=True)

    # --- Pagination (8 per page) ---
    paginator = Paginator(jobs_base, 8) 
    page_number = request.GET.get('page')
    jobs_paginated = paginator.get_page(page_number)

    return render(request, 'jobs/job_list.html', {
        'jobs': jobs_paginated,
        'countries': COUNTRY_CHOICES,
        'applied_job_ids': applied_job_ids,
        'total_jobs': jobs_base.count(),
    })    
    

@csrf_exempt
def user_signup(request):
    """VERSION 45.0: PROTECTED SIGNUP (Manual HTML Form Guard)"""
    if request.method == "POST":
        # 1. 🛡️ HONEYPOT
        if request.POST.get('website_url'):
            return HttpResponse("Bot detected!", status=403)
            
        # 2. 🛡️ TURNSTILE CHECK
        token = request.POST.get('cf-turnstile-response')
        if not verify_turnstile(token):
            messages.error(request, "Captcha verification failed!")
            return render(request, 'account/signup.html')

        # DATA GATHERING
        u_name = request.POST.get('username')
        f_name = request.POST.get('full_name')
        email = request.POST.get('email')
        p_word = request.POST.get('password1')
        
        # 3. 🛡️ EMAIL GUARD (Manual Validation)
        try:
            validate_videsh_email(email)
        except ValidationError as e:
            messages.error(request, str(e.message))
            return render(request, 'account/signup.html')

        # 4. DUPLICATE CHECK
        if User.objects.filter(username=u_name).exists():
            messages.error(request, "Bhai, ye username booked hai!")
            return render(request, 'account/signup.html')

        # SAVE NEW USER
        try:
            user = User.objects.create_user(username=u_name, email=email, password=p_word)
            user.first_name = f_name
            user.save()
            messages.info(request, "Account ban gaya! Ab login karein.")
            return redirect('account_login')
        except Exception as e:
            messages.error(request, f"Error: {e}")
            return render(request, 'account/signup.html')
            
    return render(request, 'account/signup.html')



def user_login(request):
    if request.method == "POST":
        u_name = request.POST.get('username')
        p_word = request.POST.get('password')
        
        user = authenticate(request, username=u_name, password=p_word)
        
        if user is not None:
            login(request, user)
            messages.info(request, f"Welcome back, {user.username}!")
            return redirect('home')
        else:
            messages.error(request, "Invalid username or password!")
            
    return render(request, 'account/login.html')

def user_logout(request):
    logout(request)
    messages.info(request, "Come back again.")
    return redirect('home')
    
# ️ CLOUDFLARE TURNSTILE BACKEND VERIFICATION
def verify_turnstile(token):
    """
    Cloudflare API se verify karta hai ki token valid hai ya nahi.
    """
    # ⚠️ Bhai, yahan apni 'Secret Key' Cloudflare Dashboard se copy karke dalo
    # Behtar hoga agar aap ise Environment Variable (os.environ.get) mein rakhein
    secret_key = "0x4AAAAAACkBDJY3z5jnDqrqaaNixRpxCU4" 
    
    verify_url = "https://challenges.cloudflare.com/turnstile/v0/siteverify"
    
    payload = {
        'secret': secret_key,
        'response': token,
    }
    
    try:
        response = requests.post(verify_url, data=payload, timeout=10)
        result = response.json()
        return result.get('success', False)
    except Exception as e:
        print(f"Turnstile Error: {e}")
        return False

# --- NAYA FUNCTION: Withdraw Application ---
@candidate_required
def withdraw_application(request, job_id):
    if request.method == "POST":
        job = get_object_or_404(Job, id=job_id)
        # 🚀 FIX: HTML se 'next' uthao, agar nahi hai toh 'home' par bhejo
        next_url = request.POST.get('next', 'home')
        
        application = Application.objects.filter(user=request.user, job=job).first()
        if application:
            application.delete()
            messages.warning(request, f"Aapne {job.title} ke liye application withdraw kar li hai.")
            
        return redirect(next_url)
    return redirect('home')

@csrf_exempt
def apply_job(request, job_id):
    """
    VERSION 43.0: FULL PROTECTION (Time + Turnstile + Registered Logic)
    Integrates Speed check and Turnstile without affecting existing features.
    """
    if request.method == "POST":
        # ️ 1. HONEYPOT CHECK (Existing)
        # Check if website_url is filled (Bot trap)
        if request.POST.get('website_url'):
            return HttpResponse("Bot detected! Application rejected.", status=400)
            
        job = get_object_or_404(Job, id=job_id)

            # B. Turnstile Verification: Validate Cloudflare token
        if not request.user.is_authenticated:
            turnstile_token = request.POST.get('cf-turnstile-response')
            if not verify_turnstile(turnstile_token):
                messages.error(request, "Bhai, Captcha verify nahi hua! Dobara koshish karein.")
                return redirect(next_url)

        # --- 🛡️ 3. DUPLICATE CHECK (Existing) ---
        if request.user.is_authenticated:
            already_applied = Application.objects.filter(user=request.user, job=job).exists()
            if already_applied:
                messages.info(request, f"Bhai, aap '{job.title}' ke liye pehle hi apply kar chuke hain!")
                return redirect(request.POST.get('next', 'home'))

        # --- 4. DATA GATHERING & SAVING (Existing Logic) ---
        full_name = request.POST.get('full_name')
        email = request.POST.get('email')
        phone = request.POST.get('phone')
        resume = request.FILES.get('resume')

        app = Application.objects.create(
            job=job, 
            full_name=full_name, 
            email=email, 
            phone=phone, 
            resume=resume
        )

        next_url = request.POST.get('next', 'home')

        if request.user.is_authenticated:
            app.user = request.user
            app.save()

        # --- 5. EMAIL NOTIFICATION (Existing) ---
        try:
            subject = f"Application Received: {job.title}"
            message = f"Hello {full_name},\n\nHumne aapka application receive kar liya hai. Humari team aapse jald sampark karegi.\n\nRegards,\nTeam Videsh Chalo"
            send_mail(subject, message, 'support@videshchalo.com', [email], fail_silently=True)
        except Exception:
            pass # Email fail hone par user ko na rokein

        messages.success(request, f"Jabardast! {job.title} ke liye aapka application jama ho gaya hai.")
        return redirect(next_url)
    
    return HttpResponse("Method not allowed", status=405)
    

@candidate_required
def profile_dashboard(request):
    # 1. Basic Stats
    my_apps = Application.objects.filter(user=request.user).order_by('-id')
    applied_job_ids = Application.objects.filter(user=request.user).values_list('job_id', flat=True)
    wallet, created = ReferralWallet.objects.get_or_create(user=request.user)
    
    # --- 🔥 NAYA: V-COIN LOGIC START (Daily Login Reward Middleware samhal raha hain) ---
    coin_wallet, _ = CandidateWallet.objects.get_or_create(user=request.user)

    # 2. Successful Hires Logic (Updated based on STATUS_CHOICES)
    # ✅ FIX: Ab ye 'Deployed' aur 'Paid' dono ko count karega
    hired_statuses = ['Deployed', 'Paid']
    successful_hires = Application.objects.filter(
        user__profile__referred_by=request.user, 
        status__in=hired_statuses
    ).values('user').distinct().count()

    # 4. Slab-based Calculation
    # ✅ FIX: Variable ko default 0 par set kiya taaki NameError na aaye
    calculated_total = 0
    
    if successful_hires > 0:
        if successful_hires <= 9:
            calculated_total = successful_hires * 1000
        elif successful_hires <= 20:
            calculated_total = (9 * 1000) + ((successful_hires - 9) * 1500)
        else:
            calculated_total = (9 * 1000) + (11 * 1500) + ((successful_hires - 20) * 2000)

    # 4. Wallet Sync
    # ✅ SAFE CONVERSION: float aur decimal ke jhamela khatam karne ke liye str() use kiya hai
    dec_total_earned = Decimal(str(wallet.total_earned))
    dec_calculated_total = Decimal(str(calculated_total))

    if dec_calculated_total > dec_total_earned:
        difference = dec_calculated_total - dec_total_earned
        wallet.balance += difference
        wallet.total_earned = dec_calculated_total
        wallet.save()

        # Bahi-khata Entry (Transaction)
        Transaction.objects.create(
            wallet=wallet,
            amount=difference,
            transaction_type='Credit',
            description=f"Referral bonus credited for deployment #{successful_hires}"
        )

    # 5. Referrals Tracking Data
    referrals_data = Profile.objects.filter(referred_by=request.user).select_related('user')
    for ref in referrals_data:
        latest_app = ref.user.my_applications.last() if hasattr(ref.user, 'my_applications') else None
        ref.current_status = latest_app.status if latest_app else "Registered"

    # 6. Recent Transactions
    recent_transactions = wallet.transactions.all().order_by('-timestamp')[:5]
    coin_transactions = coin_wallet.transactions.all().order_by('-timestamp')[:10]
    withdrawal_history = WithdrawalRequest.objects.filter(user=request.user).order_by('-request_date')

    # Stats for UI
    total_referrals = referrals_data.count()

    context = {
        'my_apps': my_apps,
        'total_applied': my_apps.count(),
        'applied_job_ids': applied_job_ids,
        'wallet': wallet,
        'coin_wallet': coin_wallet,
        'successful_hires': successful_hires,
        'total_referrals': total_referrals,
        'recent_transactions': recent_transactions,
        'coin_transactions': coin_transactions,
        'referrals_data': referrals_data,
        'withdrawal_history': withdrawal_history
    }
    return render(request, 'jobs/profile.html', context)

@login_required
def withdraw_money(request):
    if request.method == "POST":
        try:
            amount_val = request.POST.get('amount', 0)
            amount = Decimal(amount_val) if amount_val else Decimal('0')
            upi_id = request.POST.get('upi_id')
            wallet = request.user.wallet

            if amount < Decimal('500'):
                messages.error(request, "Bhai, kam se kam ₹500 hone chahiye.")
            elif amount > wallet.balance:
                messages.error(request, "Itna paisa wallet mein nahi hai!")
            elif not upi_id:
                messages.error(request, "UPI ID dena zaroori hai.")
            else:
                # Create Request
                WithdrawalRequest.objects.create(
                    user=request.user,
                    amount=amount,
                    upi_id=upi_id,
                    status='Pending'
                )
                
                # Deduct from Balance
                wallet.balance -= amount
                wallet.save()

                # Record Transaction
                Transaction.objects.create(
                    wallet=wallet,
                    amount=amount,
                    transaction_type='Debit',
                    description=f"Withdrawal request for ₹{amount} ({upi_id})"
                )
                messages.success(request, f"₹{amount} ki request bhej di gayi hai! 🚀")
        except Exception as e:
            messages.error(request, "Kuch gadbad ho gayi, fir se try karein.")
            
    return redirect('profile_dashboard')
    
def toggle_favorite(request, job_id):
    # 1. Check karo user login hai ya nahi
    if not request.user.is_authenticated:
        # Ab usey login page par bhej do 'next' parameter ke saath
        login_url = f"{settings.LOGIN_URL}?next={request.path}"
        return redirect(login_url)

    # 2. Agar user login hai, toh purana makkhan logic
    job = get_object_or_404(Job, id=job_id)
    referer = request.META.get('HTTP_REFERER', '')
    if 'accounts/login' in referer:
        # User login karke aaya hai, Signal ne kaam kar diya hoga
        # Chaho toh yahan ek print laga lo check karne ke liye
        print(f"DEBUG: {request.user} login se aaya hai, toggle skip kar raha hu.")
        return redirect('home')

    # Normal toggle logic (jab user pehle se login ho aur heart dabaye)
    if job.favorites.filter(id=request.user.id).exists():
        job.favorites.remove(request.user)
    else:
        job.favorites.add(request.user)
        
    return redirect('home')


@user_passes_test(lambda u: u.is_staff, login_url='home')
def admin_dashboard(request):
    """
    VERSION 2.1: BULLETPROOF ADMIN DASHBOARD
    - Candidate Stats (Fixed Range)
    - Recruiter Stats (Fixed Range)
    - Application Stats
    - LIVE TRAFFIC HITS (Fixed Range)
    """
    now = timezone.now()
    today = timezone.localdate()
    
    # 🛡️ BULLETPROOF DATE RANGE: Timezone ki kisi bhi gadbad se bachne ke liye
    today_start = timezone.make_aware(datetime.combine(today, time.min))
    today_end = timezone.make_aware(datetime.combine(today, time.max))
    last_7_start = now - timedelta(days=7)
    last_30_start = now - timedelta(days=30)

    # --- 1. CANDIDATE STATS (Range Logic Applied) ---
    candidates = User.objects.filter(is_candidate=True)
    candidate_stats = {
        'total': candidates.count(),
        'today': candidates.filter(date_joined__range=(today_start, today_end)).count(),
        'last_7': candidates.filter(date_joined__gte=last_7_start).count(),
        'last_30': candidates.filter(date_joined__gte=last_30_start).count(),
    }

    # --- 2. RECRUITER STATS (Range Logic Applied) ---
    recruiters = User.objects.filter(is_recruiter=True)
    recruiter_stats = {
        'total': recruiters.count(),
        'today': recruiters.filter(date_joined__range=(today_start, today_end)).count(),
        'last_7': recruiters.filter(date_joined__gte=last_7_start).count(),
        'last_30': recruiters.filter(date_joined__gte=last_30_start).count(),
    }

    # --- 3. APPLICATION STATS (Existing - Stable) ---
    apps = Application.objects.all()
    app_stats = {
        'total': apps.count(),
        'today': apps.filter(applied_at__range=(today_start, today_end)).count(),
        'last_7': apps.filter(applied_at__gte=last_7_start).count(),
        'last_30': apps.filter(applied_at__gte=last_30_start).count(),
    }

    # --- 🚀 4. TRAFFIC HITS STATS (Range Logic Applied) ---
    traffic_stats = {
        'today': SiteHit.objects.filter(timestamp__range=(today_start, today_end), is_unique=True).count(),
        'last_7': SiteHit.objects.filter(timestamp__gte=last_7_start, is_unique=True).count(),
        'last_30': SiteHit.objects.filter(timestamp__gte=last_30_start, is_unique=True).count(),
        'total_hits': SiteHit.objects.filter(is_unique=True).count(), # 'Unique' visitors only
        'raw_hits_today': SiteHit.objects.filter(timestamp__range=(today_start, today_end)).count(), # Debug Info
    }

    # Data 1: Country-wise stats
    country_stats = Application.objects.values('job__country').annotate(total=Count('id'))
    
    # Data 2: Job-wise stats
    job_stats = Application.objects.values('job__title').annotate(total=Count('id'))
    
    context = {
        'c_stats': candidate_stats,
        'r_stats': recruiter_stats,
        'app_stats': app_stats,
        'traffic': traffic_stats, 
        'labels': [item['job__country'] for item in country_stats],
        'counts': [item['total'] for item in country_stats],
        'job_labels': [item['job__title'] for item in job_stats],
        'job_counts': [item['total'] for item in job_stats],
    }
    
    return render(request, 'jobs/admin_dashboard.html', context)


@user_passes_test(lambda u: u.is_staff)
def detailed_stats(request):
    stat_type = request.GET.get('type', 'Total Candidates')
    now = timezone.now()
    today = timezone.localdate()
    
    # 🛡️ BULLETPROOF DATE RANGE: Timezone safety ke liye
    today_start = timezone.make_aware(datetime.combine(today, time.min))
    today_end = timezone.make_aware(datetime.combine(today, time.max))
    
    
    # 1. Data Fetching & Initial Filtering
    if 'Candidate' in stat_type:
        queryset = User.objects.filter(is_candidate=True)
        # ✅ Filter updated to use Range instead of __date
        if 'Today' in stat_type: 
            queryset = queryset.filter(date_joined__range=(today_start, today_end))
        elif '7 Days' in stat_type: 
            queryset = queryset.filter(date_joined__gte=now-timedelta(days=7))
        elif '30 Days' in stat_type: 
            queryset = queryset.filter(date_joined__gte=now-timedelta(days=30))
        data_list = list(queryset.order_by('-date_joined'))
        
    elif 'Recruiter' in stat_type:
        queryset = User.objects.filter(is_recruiter=True)
        # ✅ Filter updated to use Range instead of __date
        if 'Today' in stat_type: 
            queryset = queryset.filter(date_joined__range=(today_start, today_end))
        elif '7 Days' in stat_type: 
            queryset = queryset.filter(date_joined__gte=now-timedelta(days=7))
        elif '30 Days' in stat_type: 
            queryset = queryset.filter(date_joined__gte=now-timedelta(days=30))
        data_list = list(queryset.order_by('-date_joined'))

    elif 'Application' in stat_type:
        queryset = Application.objects.all().select_related('user')
        # ✅ Filter updated to use Range instead of __date
        if 'Today' in stat_type: 
            queryset = queryset.filter(applied_at__range=(today_start, today_end))
        elif '7 Days' in stat_type: 
            queryset = queryset.filter(applied_at__gte=now-timedelta(days=7))
        elif '30 Days' in stat_type: 
            queryset = queryset.filter(applied_at__gte=now-timedelta(days=30))
        data_list = list(queryset.order_by('-applied_at'))
    else:
        data_list = []

    # 2. ✅ Force Attach Display Names (Old logic preserved)
    for item in data_list:
        if hasattr(item, 'applied_at'):  # Application Model
            item.display_name = item.full_name or (item.user.first_name if item.user else "") or (item.user.username if item.user else "Anonymous")
        else:  # User Model
            full = f"{item.first_name} {item.last_name}".strip()
            item.display_name = full or item.username

    # 3. Excel Export Logic (Old logic preserved)
    if request.GET.get('export') == 'excel':
        response = HttpResponse(content_type='application/ms-excel')
        response['Content-Disposition'] = f'attachment; filename="{stat_type}_Report.xlsx"'
        wb = openpyxl.Workbook()
        ws = wb.active
        ws.append(['ID', 'Full Name', 'Username', 'Email', 'Contact', 'Role', 'Date'])

        for item in data_list:
            d_user = item.user.username if hasattr(item, 'user') and item.user else item.username
            d_date = item.applied_at if hasattr(item, 'applied_at') else item.date_joined
            
            if hasattr(item, 'phone') and item.phone: d_contact = item.phone
            elif hasattr(item, 'profile') and item.profile.whatsapp_number: d_contact = item.profile.whatsapp_number
            else: d_contact = "N/A"

            ws.append([
                item.id, item.display_name, d_user,
                item.email if hasattr(item, 'email') else (item.user.email if item.user else "N/A"),
                d_contact,
                "Application" if hasattr(item, 'applied_at') else ("Recruiter" if item.is_recruiter else "Candidate"),
                d_date.strftime("%d-%m-%Y %H:%M") if d_date else ""
            ])
        wb.save(response)
        return response

    # 4. Normal Page Render
    return render(request, 'jobs/detailed_stats.html', {
        'data_list': data_list,
        'title': stat_type,
    })

def contact_view(request):
    if request.method == "POST":
        # ️ HONEYPOT CHECK
        if is_bot(request):
            return HttpResponse("Bot detected! Access Denied.", status=400)
        name = request.POST.get('name')
        phone = request.POST.get('phone')
        message = request.POST.get('message')
        
        # Database mein save karo
        ContactMessage.objects.create(name=name, phone=phone, message=message)
        
        # Success signal bhejo taaki SweetAlert chale
        return render(request, 'pages/contact.html', {'success': True})
    
    return render(request, 'pages/contact.html')

# NAYA FUNCTION: AJAX ke through avatar update karne ke liye
@login_required
def update_avatar(request):
    if request.method == "POST" and request.FILES.get('avatar'):
        try:
            # request.user tabhi kaam karega jab login hoga
            user_profile = request.user.profile 
            user_profile.avatar = request.FILES['avatar']
            user_profile.save()
            
            return JsonResponse({
                'success': True,
                'new_url': user_profile.avatar.url
            })
        except Exception as e:
            return JsonResponse({'success': False, 'error': str(e)})
            
    return JsonResponse({'success': False, 'error': 'Invalid request'})

# NAYA FUNCTION: Recruiter Dashboard (sirf unke liye jo staff hain)

@recruiter_required
def recruiter_dashboard(request):
    # 1. Pehle check karo ki user ne role select kiya hai ya nahi
    if not request.user.is_recruiter:
        messages.error(request, "Na kare janaab aisa na karein, ye dashboard sirf Recruiters ke liye hai!")
        return redirect('home')

    # 2. STRICT FIX: Seedha RecruiterProfile table se data uthao
    from .models import RecruiterProfile
    recruiter_info = RecruiterProfile.objects.filter(user=request.user).first()

    # 3. Agar table mein entry hi nahi hai toh register pe bhejo
    if not recruiter_info:
        return redirect('recruiter_register')

    # 4. Jobs ka data
    my_jobs = Job.objects.filter(posted_by=request.user).order_by('-created_at')
    
    context = {
        'my_jobs': my_jobs,
        'total_jobs': my_jobs.count(),
        'approved_jobs': my_jobs.filter(is_approved=True).count(),
        'pending_jobs': my_jobs.filter(is_approved=False).count(),
        'recruiter': recruiter_info, # Ab hamesha 'Dynamic Staffing' hi aayega
    }
    
    # TERMINAL CHECK: Is baar pakka print hoga
    print("\n" + "="*30)
    print(f"LOGIN USER: {request.user.username}")
    print(f"FETCHED COMPANY: {recruiter_info.company_name}")
    print("="*30 + "\n")

    return render(request, 'jobs/recruiter_dashboard.html', context)

    # jobs/views.py
from .forms import JobPostForm

# NAYA FUNCTION: Recruiter ke liye job post karne ka form

@recruiter_required
def post_job(request):
    if request.method == "POST":
        form = JobPostForm(request.POST, request.FILES)
        if form.is_valid():
            job = form.save(commit=False)
            job.posted_by = request.user
            job.is_approved = False # Default Pending
            job.save()

            # --- MasterBlaster Email Alert ---
            subject = f"Nayi Job Alert: {job.title} 🚀"
            message = f"Admin bhai,\n\n{request.user.username} ne ek nayi job '{job.title}' post ki hai.\n\nIse approve karne ke liye Admin Stats page par jayein.\n\nVidesh Chalo Team."
            
            # Aapka email yahan dalo
            admin_email = "support@videshchalo.com" 
            
            send_mail(subject, message, settings.EMAIL_HOST_USER, [admin_email], fail_silently=True)
            # ---------------------------------

            messages.success(request, "Wow! job submit ho gayi hai! Admin approval ke baad live ho jayegi.")
            return redirect('recruiter_dashboard')
    else:
        form = JobPostForm()
    
    return render(request, 'jobs/post_job.html', {'form': form})

# NAYA FUNCTION: Job edit karne ke liye (sirf apni jobs)

@recruiter_required
def edit_job(request, job_id):
    job = get_object_or_404(Job, id=job_id, posted_by=request.user) # Security check
    if request.method == "POST":
        form = JobPostForm(request.POST, request.FILES, instance=job)
        if form.is_valid():
            job = form.save(commit=False)
            job.is_approved = False  # Reset approval status on edit
            job.save()
            messages.success(request, "Success! job update ho gayi aur Approval ke liye Admin ke paas bhej di gayi hai! ⏳!")
            return redirect('recruiter_dashboard')
    else:
        form = JobPostForm(instance=job)
    return render(request, 'jobs/post_job.html', {'form': form, 'edit_mode': True})

@recruiter_required
def delete_job(request, job_id):
    job = get_object_or_404(Job, id=job_id, posted_by=request.user)
    if request.method == "POST":
        job.delete()
        messages.error(request, "Job delete kar di gayi hai.")
        return redirect('recruiter_dashboard')
    return render(request, 'jobs/confirm_delete.html', {'job': job})


@recruiter_required
def update_recruiter_branding(request):
    # Recruiter ki profile uthao ya nayi banao
    profile, created = RecruiterProfile.objects.get_or_create(user=request.user)
    
    if request.method == "POST":
        form = RecruiterBrandingForm(request.POST, request.FILES, instance=profile)
        if form.is_valid():
            form.save()
            messages.success(request, "Bhai, Company Branding update ho gayi hai! ✨")
            return redirect('recruiter_dashboard')
    else:
        form = RecruiterBrandingForm(instance=profile)
    
    return render(request, 'jobs/update_branding.html', {'form': form, 'profile': profile})

@login_required
def set_user_role(request):
    if request.method == 'POST':
        role = request.POST.get('role')
        user = request.user # Ye naya AbstractUser hai
        
        if role == 'candidate':
            if not user.role_selected:
                add_v_coins(user, 100, "Signup Welcome Bonus")
            user.is_candidate = True
            user.is_recruiter = False
        elif role == 'recruiter':
            user.is_recruiter = True
            user.is_candidate = False
        
        user.role_selected = True # User model wala field
        user.save() # Ab Middleware ko pata chal jayega ki role set hai!
        return JsonResponse({'status': 'success'})
    return JsonResponse({'status': 'error'}, status=400)

@candidate_required
def candidate_register(request):
    """
    VERSION 48.0: THE CELEBRATION GUARDIAN 🛡️
    - Ensures Welcome Bonus UI only triggers ONCE in a lifetime.
    - Differentiates between 'New Registration' and 'Profile Edit'.
    """
    profile, created = Profile.objects.get_or_create(user=request.user)
    user = request.user
    
    if request.method == 'POST':
        form = CandidateProfileForm(request.POST, request.FILES, instance=profile)
        if form.is_valid():
            # 🕵️ Check: Kya ye banda pehli baar role select kar raha hai?
            # Agar role_selected pehle se True hai, toh ye sirf EDIT kar raha hai.
            check_profile = Profile.objects.get(user=user)
            is_new_registration = not bool(check_profile.whatsapp_number)

            # ✅ User model sync: Name aur Email update
            full_name = form.cleaned_data.get('full_name')
            new_email = form.cleaned_data.get('email')
            
            user.full_name = full_name
            user.first_name = full_name
            user.last_name = ""
            user.email = new_email
            user.is_candidate = True
            user.role_selected = True # Ab ye hamesha ke liye True ho jayega
            user.save() 
            
            # 🎊 Celebration Logic (Strictly for NEW users only)
            if is_new_registration:
                if not request.session.get('welcome_celebrated'):
                    request.session['show_welcome_bonus'] = True
                    request.session['welcome_celebrated'] = True
                    # Note: Yahan hum man kar chal rahe hain ki Signup bonus 
                    # wallet mein registration ke waqt hi add ho chuka hai.

            # --- 🚀 REFERRAL LOGIC ---
            referrer_id = request.session.get('referrer_id')
            if referrer_id and not profile.referred_by:
                try:
                    from django.contrib.auth.models import User as AuthUser
                    referrer = AuthUser.objects.get(id=referrer_id)
                    if referrer != user:
                        profile.referred_by = referrer
                except:
                    pass

            # Profile fields save karein
            form.save() 
            
            if 'referrer_id' in request.session:
                del request.session['referrer_id']

            # Alag messages taaki user ko pata chale kaam ho gaya
            if is_new_registration:
                messages.success(request, "Mubarak Ho! Aapka account taiyar hai. 100 V-Coins Welcome Bonus mil gaye hain! ✨")
            else:
                messages.info(request, "Success ✅! Your Profle has been updated. ")
                
            return redirect('profile_dashboard')
    else:
        # Form load hote waqt data pre-fill karein
        form = CandidateProfileForm(
            instance=profile, 
            initial={
                'full_name': getattr(user, 'full_name', user.get_full_name()) or user.username,
                'email': user.email
            }
        )
        
    return render(request, 'jobs/candidate_register.html', {'form': form})

def clear_welcome_flag(request):
    """Animation dikhne ke baad flag saaf karne ke liye"""
    if 'show_welcome_bonus' in request.session:
        del request.session['show_welcome_bonus']
    return JsonResponse({'status': 'ok'})

@recruiter_required
def recruiter_register(request):
    # Recruiter Profile fetch ya create karo
    profile, created = RecruiterProfile.objects.get_or_create(user=request.user)
    
    if request.method == 'POST':
        form = RecruiterProfileForm(request.POST, request.FILES, instance=profile)
        if form.is_valid():
            # ✅ Sabse Zaruri: User table ka status change karo
            user = request.user
            user.is_recruiter = True
            user.role_selected = True # Ye field bhi update karna hai taaki Middleware samajh jaye ki role select ho chuka hai
            user.save() # Malik ke darbaar mein status update
            
            form.save()
            messages.success(request, "Recruiter profile complete! ✅ Ab aap apni jobs post kar sakte hain.")
            return redirect('home')
    else:
        form = RecruiterProfileForm(instance=profile)
    return render(request, 'jobs/recruiter_register.html', {'form': form})

# NAYA FUNCTION: Recruiter ke liye apne job ke applicants dekhne ka page (sirf unki jobs ke liye)
@recruiter_required
def view_applicants(request, job_id):
    # Sirf wahi recruiter ye dekh sake jiski ye job hai
    job = get_object_or_404(Job, id=job_id, posted_by=request.user)
    
    # Is job ke liye saare applications fetch karo
    applicants = Application.objects.filter(job=job).order_by('-id')
    
    return render(request, 'jobs/view_applicants.html', {
        'job': job,
        'applicants': applicants
    })

@recruiter_required
def unlock_applicant(request, application_id):
    # Application fetch karo
    application = get_object_or_404(Application, id=application_id)
    recruiter_profile = request.user.recruiter_profile

    # Check karo ki kahin ye pehle se unlock toh nahi hai?
    if request.user in application.unlocked_by.all():
        messages.info(request, "Arrrre.., ye toh pehle se unlocked hai, Dekho Jara!")
        return redirect('view_applicants', job_id=application.job.id)

    # 💰 Toll Check
    if recruiter_profile.credits >= 1:
        recruiter_profile.credits -= 1
        recruiter_profile.save()
        
        # Application ko is recruiter ke liye unlock kar do
        application.unlocked_by.add(request.user)
        
        messages.success(request, f"Badhaai! {application.full_name} ki details unlock ho gayi hain. 1 Credit deducted.")
    else:
        # Agar paise nahi hain toh payment page par bhejo
        messages.error(request, "Bhai, galla khali hai! Credits recharge karo pehle.")
        return redirect('buy_credits')

    return redirect('view_applicants', job_id=application.job.id)

# NAYA FUNCTION: Recruiter ke liye credits kharidne ka page (sirf unke liye)
@recruiter_required
def buy_credits(request):
    # Recruiter ki profile fetch karo taaki uska current balance dikha sakein
    profile = get_object_or_404(RecruiterProfile, user=request.user)
    
    return render(request, 'jobs/buy_credits.html', {
        'profile': profile
    })


# NAYA FUNCTION: Recruiter ke liye apni job ko featured karne ka option (sirf unki jobs ke liye)
@recruiter_required
def make_job_featured(request, job_id):
    # Sirf wahi recruiter feature kar sake jiski ye job hai
    job = get_object_or_404(Job, id=job_id, posted_by=request.user)
    recruiter_profile = request.user.recruiter_profile

    # Agar pehle se featured hai toh mana kar do
    if job.is_featured:
        messages.info(request, "Bhai, ye job toh pehle se hi TOP par chamak rahi hai!")
        return redirect('recruiter_dashboard')

    # 💰 Featured Hone ka "Toll" (Maano 20 Credits)
    FEATURED_COST = 20 

    if recruiter_profile.credits >= FEATURED_COST:
        recruiter_profile.credits -= FEATURED_COST
        recruiter_profile.save()
        
        job.is_featured = True
        job.save()
        messages.success(request, f"Congratolations! 🎊 Aapki job ab Featured hai. {FEATURED_COST} Credits deducted.")
    else:
        messages.error(request, f"Bhai, Featured karne ke liye kam se kam {FEATURED_COST} Credits chahiye. Recharge kar lo!")
        return redirect('buy_credits')

    return redirect('recruiter_dashboard')
    
def get_trade_positions(request):
    """Industry ID ke basis par Trades (Positions) ki list dena"""
    industry_id = request.GET.get('industry_id')
    
    # Database se us industry ke trades uthao
    # Hum 'is_verified=True' wale trades dikhayenge
    positions = TradePosition.objects.filter(
        industry_id=industry_id, 
        is_verified=True
    ).values('id', 'title')
    
    return JsonResponse(list(positions), safe=False)
    
def referral_program(request):
    # Ab hum 'pages/' prefix laga rahe hain kyunki file folder ke andar hai
    return render(request, 'pages/referral_program.html')
    
def job_detail(request, slug):
    # 1. Slug ke aadhar par job dhoondo
    job = get_object_or_404(Job, slug=slug)
    valid_through = job.created_at + timedelta(days=30)
    
    # 2. Related jobs fetch karo
    related_jobs = Job.objects.filter(country=job.country).exclude(id=job.id)[:3]

    # --- 🚀 FIX: Yahan se applied_job_ids bhejna zaroori hai ---
    applied_job_ids = []
    has_applied = False
    
    if request.user.is_authenticated:
        # Saari IDs nikal lo (jaise home view mein kiya tha)
        applied_job_ids = Application.objects.filter(user=request.user).values_list('job_id', flat=True)
        # Extra safety ke liye check karo ki kya Shalini ne is specific job par apply kiya hai
        has_applied = Application.objects.filter(user=request.user, job=job).exists()

    context = {
        'job': job,
        'related_jobs': related_jobs,
        'applied_job_ids': applied_job_ids, # Ye list HTML ko chahiye
        'has_applied': has_applied,         # Ye boolean bhi kaam aayega
        'valid_through': valid_through,
        'SITE_URL': settings.SITE_URL,
    }
    return render(request, 'jobs/job_detail.html', context)
    
# --- BOT PROTECTION LOGIC (HONEYPOT) ---
def is_bot(request):
    """
    Agar 'website_url' field bhara hua hai, toh wo bot hai.
    Insaano ko ye field dikhta hi nahi hai.
    """
    if request.POST.get('website_url'):
        return True
    return False
    
@login_required
@candidate_required
def heartbeat_timer(request):
    wallet, _ = CandidateWallet.objects.get_or_create(user=request.user)
    
    # ️ ELIGIBILITY CHECK: Agar user ban ho chuka hai
    if not wallet.is_eligible_for_time_reward:
        return JsonResponse({'status': 'banned', 'message': 'Disqualified from time rewards.'})

    now = timezone.now()
    
    # ️ CONTINUITY CHECK: Agar pichla signal 90s se purana hai, toh counter reset
    if wallet.last_heartbeat and (now - wallet.last_heartbeat) > timedelta(seconds=90):
        wallet.total_time_spent = 0
    
    # 1 Minute jodein
    wallet.total_time_spent += 1
    wallet.last_heartbeat = now
    
    reward_amount = 0
    reason = ""

    # 💰 PAYOUT LOGIC
    if wallet.total_time_spent == 10:
        reward_amount = 10
        reason = "Continuous Browsing Reward (10 Mins)"
    elif wallet.total_time_spent > 10:
        reward_amount = 1;
        reason = "Active Browsing Bonus (+1 Min)"
        
    if reward_amount > 0:
        from .utils import add_v_coins
        add_v_coins(request.user, reward_amount, reason)
        
    wallet.save()
    
    return JsonResponse({
        'status': 'success', 
        'reward_given': reward_amount > 0,
        'amount': reward_amount,
        'session_minutes': wallet.total_time_spent
    })

@login_required
@candidate_required
def report_fraud(request):
    """
    Jab frontend abnormal clicks detect karega, toh ye view user ko ban kar dega.
    """
    wallet, _ = CandidateWallet.objects.get_or_create(user=request.user)
    wallet.is_eligible_for_time_reward = False
    wallet.save()
    
    # Transaction log for admin info
    from .models import CoinTransaction
    CoinTransaction.objects.create(
        wallet=wallet,
        amount=0,
        transaction_type='Debit',
        reason="Banned: Auto-clicker/Bot activity detected"
    )
    
    return JsonResponse({'status': 'banned'})
    
def sitemap_view(request):
    """
    Final Sitemap logic (v4.0):
    - Static Pages (Home, Contact, AI Resume, Travels Home, etc.)
    - Dynamic Jobs (Approved only)
    - Dynamic News (Published only)
    - Dynamic Blog/Guides (Published only)
    - Dynamic Country Pages 
    - Dynamic Travel Trips and Blogs ✅ Added
    """
    try:
        protocol = 'https' if request.is_secure() else 'http'
        domain = request.get_host()
        base_url = f"{protocol}://{domain}"
        
        xml = '<?xml version="1.0" encoding="UTF-8"?>'
        xml += '\n<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">'
        
        # --- 1. Static Pages ---
        # ✅ 'travels_home' ko static_names mein jodh diya
        static_names = [
            'home', 'contact', 'about', 'services', 'privacy', 'terms',
            'referral_program', 'job_list', 'jobs_by_location', 'news_list', 'blog_list', 'ai_resume_builder',
            'travels_home', 'travel_blog_list', 'study_home', 'study_blog_list'
        ]

        for name in static_names:
            try:
                path = reverse(name)
                xml += f'\n  <url>'
                xml += f'\n    <loc>{base_url}{path}</loc>'
                xml += f'\n    <changefreq>daily</changefreq>'
                xml += f'\n    <priority>1.0</priority>'
                xml += f'\n  </url>'
            except:
                continue

        # --- 2. Dynamic Job Pages ---
        active_jobs = Job.objects.filter(is_approved=True).only('slug', 'updated_at')
        for job in active_jobs:
            if job.slug:
                try:
                    job_path = reverse('job_detail', kwargs={'slug': job.slug})
                    lastmod = job.updated_at.strftime('%Y-%m-%d')
                    xml += f'\n  <url>'
                    xml += f'\n    <loc>{base_url}{job_path}</loc>'
                    xml += f'\n    <lastmod>{lastmod}</lastmod>'
                    xml += f'\n    <changefreq>weekly</changefreq>'
                    xml += f'\n    <priority>0.8</priority>'
                    xml += f'\n  </url>'
                except:
                    continue

        # --- 3. Dynamic News Pages (Rojgar Samachar) ---
        published_news = NewsPost.objects.filter(status='published').only('slug', 'updated_at', 'category')
        for post in published_news:
            if post.slug:
                try:
                    news_path = reverse('news_detail', kwargs={
                        'category_slug': post.category_slug, 
                        'slug': post.slug
                    })
                    lastmod = post.updated_at.strftime('%Y-%m-%d')
                    xml += f'\n  <url>'
                    xml += f'\n    <loc>{base_url}{news_path}</loc>'
                    xml += f'\n    <lastmod>{lastmod}</lastmod>'
                    xml += f'\n    <changefreq>weekly</changefreq>'
                    xml += f'\n    <priority>0.7</priority>'
                    xml += f'\n  </url>'
                except:
                    continue

        # --- 4. Dynamic Blog Guides (Gyan Kendra) 📚 ---
        published_guides = BlogPost.objects.filter(is_published=True).only('slug', 'updated_at', 'category')
        for guide in published_guides:
            if guide.slug:
                try:
                    blog_path = reverse('blog_detail', kwargs={
                        'category': guide.category, 
                        'slug': guide.slug
                    })
                    lastmod = guide.updated_at.strftime('%Y-%m-%d')
                    xml += f'\n  <url>'
                    xml += f'\n    <loc>{base_url}{blog_path}</loc>'
                    xml += f'\n    <lastmod>{lastmod}</lastmod>'
                    xml += f'\n    <changefreq>monthly</changefreq>'
                    xml += f'\n    <priority>0.7</priority>'
                    xml += f'\n  </url>'
                except:
                    continue
                    
        # --- 5. Dynamic Country Pages 🌍 ---
        distinct_countries = Job.objects.filter(is_approved=True).values_list('country', flat=True).distinct()
        processed_country_slugs = set()

        for country in distinct_countries:
            if country:
                country_slug = slugify(country.strip())
                # Suffix/Duplicate check
                if country_slug in processed_country_slugs:
                    continue
                processed_country_slugs.add(country_slug)

                try:
                    # Aapka URLs.py: jobs-in-<path:country_name>
                    country_path = reverse('country_jobs', kwargs={'country_name': country_slug})
                    xml += f'\n  <url>'
                    xml += f'\n    <loc>{base_url}{country_path}</loc>'
                    xml += f'\n    <changefreq>daily</changefreq>'
                    xml += f'\n    <priority>0.9</priority>'
                    xml += f'\n  </url>'
                except:
                    continue

        # --- 6. Dynamic Travel Trips ✈️ (NEW) ---
        active_trips = Trip.objects.filter(is_active=True).only('slug', 'created_at')
        for trip in active_trips:
            if trip.slug:
                try:
                    # Aapke travels/urls.py mein 'name="trip_detail"' hai, aur namespace use nahi hua hai
                    # isliye reverse('trip_detail') perfectly kaam karna chahiye.
                    trip_path = reverse('trip_detail', kwargs={'slug': trip.slug})
                    
                    # Since created_at contains time as well, use .date() or .strftime to format it
                    lastmod = trip.created_at.strftime('%Y-%m-%d')
                    
                    xml += f'\n  <url>'
                    xml += f'\n    <loc>{base_url}{trip_path}</loc>'
                    xml += f'\n    <lastmod>{lastmod}</lastmod>'
                    xml += f'\n    <changefreq>weekly</changefreq>'
                    xml += f'\n    <priority>0.8</priority>'
                    xml += f'\n  </url>'
                except Exception as e:
                    print(f"Error reversing trip_detail for {trip.slug}: {e}")
                    continue
                
         # --- 7. Dynamic Travel Blogs ✈️📖 (NEW) ---
        published_travel_blogs = TravelBlog.objects.filter(is_published=True).only('slug', 'updated_at')
        for t_blog in published_travel_blogs:
            if t_blog.slug:
                try:
                    t_blog_path = reverse('travel_blog_detail', kwargs={'slug': t_blog.slug})
                    lastmod = t_blog.updated_at.strftime('%Y-%m-%d')
                    
                    xml += f'\n  <url>'
                    xml += f'\n    <loc>{base_url}{t_blog_path}</loc>'
                    xml += f'\n    <lastmod>{lastmod}</lastmod>'
                    xml += f'\n    <changefreq>monthly</changefreq>'
                    xml += f'\n    <priority>0.7</priority>'
                    xml += f'\n  </url>'
                except Exception as e:
                    print(f"Error reversing travel_blog_detail for {t_blog.slug}: {e}")
                    continue
        
        # --- 8. Dynamic Study Destinations 🌍 ---
        try:
            destinations = StudyDestination.objects.all().only('slug')
            for dest in destinations:
                if dest.slug:
                    try:
                        dest_path = reverse('destination_detail', kwargs={'slug': dest.slug})
                        xml += f'\n  <url>'
                        xml += f'\n    <loc>{base_url}{dest_path}</loc>'
                        xml += f'\n    <changefreq>weekly</changefreq>'
                        xml += f'\n    <priority>0.8</priority>'
                        xml += f'\n  </url>'
                    except:
                        continue
        except:
            pass

        # --- 9. Dynamic Study Programs 🎓 ---
        try:
            programs = Program.objects.all().only('slug')
            for prog in programs:
                if prog.slug:
                    try:
                        prog_path = reverse('program_detail', kwargs={'slug': prog.slug})
                        xml += f'\n  <url>'
                        xml += f'\n    <loc>{base_url}{prog_path}</loc>'
                        xml += f'\n    <changefreq>daily</changefreq>'
                        xml += f'\n    <priority>0.9</priority>'
                        xml += f'\n  </url>'
                    except:
                        continue
        except:
            pass
        
         # --- 10. Dynamic Study Blogs ✈️📖 (NEW) ---
        published_study_blogs = StudyBlog.objects.filter(is_published=True).only('slug', 'updated_at')
        for t_blog in published_study_blogs:
            if t_blog.slug:
                try:
                    t_blog_path = reverse('study_blog_detail', kwargs={'slug': t_blog.slug})
                    lastmod = t_blog.updated_at.strftime('%Y-%m-%d')
                    
                    xml += f'\n  <url>'
                    xml += f'\n    <loc>{base_url}{t_blog_path}</loc>'
                    xml += f'\n    <lastmod>{lastmod}</lastmod>'
                    xml += f'\n    <changefreq>monthly</changefreq>'
                    xml += f'\n    <priority>0.7</priority>'
                    xml += f'\n  </url>'
                except Exception as e:
                    print(f"Error reversing travel_blog_detail for {t_blog.slug}: {e}")
                    continue
        
        xml += '\n</urlset>'
        return HttpResponse(xml, content_type="application/xml")
    
    except Exception as e:
        return HttpResponse(f"Error generating sitemap: {e}", status=500)

def robots_txt(request):
    protocol = 'https' if request.is_secure() else 'http'
    domain = request.get_host()
    content = f"User-agent: *\nDisallow: /admin/\nDisallow: /vcoin/\nDisallow: /profile/\n\nSitemap: {protocol}://{domain}/sitemap.xml"
    return HttpResponse(content, content_type="text/plain")    


# ---    LUCKY WHEEL SPIN VIEW ---
@login_required
@candidate_required
def spin_lucky_wheel(request):
    today = timezone.localdate()
    
    # Check eligibility
    already_spun = LuckyWheelActivity.objects.filter(user=request.user, spin_date=today).exists()
    if already_spun:
        return JsonResponse({'status': 'error', 'message': 'Bhai, aaj ka spin ho gaya! Kal fir koshish karein.'}, status=400)

    # Reward Logic
    options = [0, 1, 2, 3, 5, 10, 15, 20]
    win_amount = random.choice(options)

    # Save activity
    LuckyWheelActivity.objects.create(user=request.user, spin_date=today, win_amount=win_amount)

    if win_amount > 0:
        from .utils import add_v_coins
        add_v_coins(request.user, win_amount, "Lucky Wheel Win!   ")

    return JsonResponse({
        'status': 'success',
        'win_amount': win_amount,
        'message': f'Badhai ho! Aapne {win_amount} V-Coins jeete hain.' if win_amount > 0 else 'Arre re! Aaj kismat ne saath nahi diya. Kal koshish karein!'
    })

def ai_resume_builder(request):
    """
    AI Resume Builder page ko render karne ke liye view.
    """
    context = {
        'title': 'AI Resume Builder - Videsh Chalo',
    }
    return render(request, 'jobs/ai_resume_builder.html', context)
    
    
@login_required
@csrf_exempt
def deduct_resume_coins(request):
    """
    Deduction triggered only on real PDF Download.
    """
    if request.method != 'POST':
        return JsonResponse({'error': 'POST required'}, status=405)
    
    if deduct_v_coins(request.user, 50, "AI Premium Resume Download"):
        wallet = CandidateWallet.objects.get(user=request.user)
        return JsonResponse({'status': 'success', 'new_balance': wallet.coins})
    else:
        return JsonResponse({'error': 'Bhai, wallet mein balance kam hai.'}, status=403)
        
        
@login_required
def vcoin_dashboard(request):
    """
    User ka personal V-Coin khata.
    """
    wallet, created = CandidateWallet.objects.get_or_create(user=request.user)
    # Latest 50 transactions dikhayenge
    transactions = CoinTransaction.objects.filter(wallet=wallet).order_by('-timestamp')[:50]
    
    # 🔟 7 transactions per page ka logic
    paginator = Paginator(transactions, 7)
    page_number = request.GET.get('page')
    transactions = paginator.get_page(page_number)
    
    context = {
        'wallet': wallet,
        'transactions': transactions,
        'active_tab': 'vcoin'
    }
    return render(request, 'jobs/vcoin_dashboard.html', context)

    
def public_cv_verify(request, uuid_id):
    """
    RECIEVER POINT: Recruiter scans QR -> This view fetches FREEZED data.
    """
    snapshot = get_object_or_404(AIResumeSnapshot, id=uuid_id)
    cv = snapshot.cv_data
    
    return render(request, 'jobs/public_cv_view.html', {
        'cv': cv,
        'snapshot': snapshot,
        'is_public_view': True
    })



@login_required
@csrf_exempt
def process_ai_resume(request):
    """
    VERSION 40.0: THE ULTIMATE INTEGRITY SNAPSHOT (Final Standard ✨).
    - Data Priority: Form > Profile > Latest App > User Model.
    - Snapshot: Freezes data into AIResumeSnapshot for permanent QR verification.
    - Protection: Ensures dates and company names are never lost or undefined.
    """
    if request.method != 'POST':
        return JsonResponse({'error': 'Only POST allowed'}, status=405)

    user = request.user
    
    # 💰 1. V-COIN PRE-CHECK (Preview is free, but check if they CAN afford it)
    try:
        wallet, _ = CandidateWallet.objects.get_or_create(user=user)
        if wallet.coins < 50:
            return JsonResponse({
                'error': 'Insufficient Coins',
                'message': 'Bhai, Premium Resume banane ke liye 50 V-Coins chahiye.'
            }, status=403)
    except Exception:
        return JsonResponse({'error': 'Wallet Error'}, status=403)

    def to_safe_str(val, default=""):
        if val is None or str(val).strip().lower() == "none" or str(val).strip() == "":
            return default
        return str(val).strip()

    # Data Source Pointers
    profile = getattr(user, 'profile', None)
    latest_app = Application.objects.filter(user=user).order_by('-applied_at').first()

    try:
        data = json.loads(request.body)
        user_input = data.get('prompt_data', {})

        # 👤 2. ROBUST DATA GATHERING (Restored V36 Logic)
        res_data = {
            "full_name": to_safe_str(user_input.get('fullName') or user.get_full_name() or getattr(latest_app, 'full_name', user.username)),
            "phone": to_safe_str(user_input.get('phone') or getattr(profile, 'whatsapp_number', getattr(latest_app, 'phone', "")), "Not Provided"),
            "email": to_safe_str(user_input.get('email') or user.email or getattr(profile, 'email', ""), "Not Provided"),
            "dob": to_safe_str(user_input.get('dob') or getattr(profile, 'dob', ""), "Not Provided"),
            "location": to_safe_str(user_input.get('address') or (f"{getattr(profile, 'city','')}, {getattr(profile, 'state','')}".strip(", ") if profile else ""), "International"),
            "target_role": to_safe_str(user_input.get('jobTitle') or "Professional Candidate"),
            "education": user_input.get('education', []),
            "experience": user_input.get('experience', []),
            "languages": user_input.get('languages', []),
            "photo": to_safe_str(user_input.get('uploadedPhoto')) 
        }

        # Photo Fallback from DB
        if not res_data["photo"] and profile and profile.avatar:
            try:
                res_data["photo"] = request.build_absolute_uri(profile.avatar.url)
            except: pass

        # 🤖 3. AI MAGIC (Groq Refinement)
        groq_key = "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"
        v_segment = chr(118) + chr(49) 
        api_url = f"https://api.groq.com/openai/{v_segment}/chat/completions"

        prompt_text = (
            f"You are an Elite International Recruiter. Refine this worker's CV JSON:\n"
            f"Role: {res_data['target_role']}\n"
            f"Context: {user_input.get('aboutMe')}\n"
            f"Experience: {res_data['experience']}\n"
            f"Skills Input: {user_input.get('skills')}\n\n"
            f"MANDATORY RULES:\n"
            f"1. Refine every 'tasks' field into professional bullet points (start with '•').\n"
            f"2. If input is generic (like 'create suitable'), YOU MUST invent 4 expert bullet points.\n"
            f"3. Write a 4-line sophisticated summary in elite English.\n"
            f"4. DO NOT change 'company', 'from', or 'to' fields.\n"
            f"RETURN ONLY RAW JSON: {{'sophisticated_summary': '', 'refined_skills': [], 'refined_experience': [{{'company': '', 'tasks': ''}}]}}"
        )

        headers = {"Authorization": f"Bearer {groq_key}", "Content-Type": "application/json"}
        payload = {"model": "llama-3.3-70b-versatile", "messages": [{"role": "user", "content": prompt_text}], "temperature": 0.1}

        response = requests.post(api_url, json=payload, headers=headers, timeout=25)
        ai_refined = {"sophisticated_summary": "", "refined_skills": [], "refined_experience": []}
        
        if response.status_code == 200:
            content = response.json()['choices'][0]['message']['content']
            match = re.search(r'\{.*\}', content, re.DOTALL)
            if match:
                raw_json = match.group(0).replace("'", '"')
                try: ai_refined = json.loads(raw_json)
                except: pass

        # 🛡️ 4. MERGE WHILE PROTECTING DATES (The 'undefined' prevention)
        final_exp = []
        ai_exp_list = ai_refined.get('refined_experience', [])
        
        for i, original in enumerate(res_data['experience']):
            refined_tasks = original.get('tasks', '')
            if i < len(ai_exp_list):
                refined_tasks = ai_exp_list[i].get('tasks') or refined_tasks
            
            final_exp.append({
                "from": to_safe_str(original.get('from')),
                "to": to_safe_str(original.get('to')),
                "company": to_safe_str(original.get('company')),
                "city": to_safe_str(original.get('city')),
                "tasks": to_safe_str(refined_tasks)
            })

        # Skills normalization
        raw_skills = user_input.get('skills', [])
        skills_list = [s.strip() for s in raw_skills.split(',') if s.strip()] if isinstance(raw_skills, str) else []
        
        # Consolidate Full Data for Snapshot
        full_cv_json = {
            **res_data,
            "experience": final_exp,
            "summary": to_safe_str(ai_refined.get('sophisticated_summary') or f"Highly dedicated {res_data['target_role']} professional."),
            "technical_skills": ai_refined.get('refined_skills') or skills_list,
            "is_ai": True
        }

        # 📸 5. CREATE PERMANENT SNAPSHOT (The Digital Freeze)
        snapshot = AIResumeSnapshot.objects.create(user=user, cv_data=full_cv_json)

        return JsonResponse({
            **full_cv_json,
            "qr_link": f"https://videshchalo.com/cv/verify/{snapshot.id}/"
        })

    except Exception as e:
        return JsonResponse({"error": str(e)}, status=500)
        
# ==========================================
# 📊 NEWSPOST Views
# ==========================================

def news_list(request):
    # 1. Sabse pehle top 3 most viewed posts uthao
    top_3_posts = NewsPost.objects.filter(status='published').order_by('-views_count')[:3]
    top_3_ids = [p.id for p in top_3_posts]
    
    # 2. Baaki posts uthao (Recent order mein) aur unhe exclude karo jo top 3 mein hain
    remaining_posts = NewsPost.objects.filter(status='published').exclude(id__in=top_3_ids).order_by('-created_at')
    
    # 3. Dono ko combine karke list banayein
    full_list = list(top_3_posts) + list(remaining_posts)
    
    # 4. Pagination (Ek page par 9 news)
    paginator = Paginator(full_list, 9)
    page_number = request.GET.get('page')
    page_obj = paginator.get_page(page_number)
    
    return render(request, 'jobs/news_list.html', {'page_obj': page_obj})

def news_detail(request, category_slug, slug):
    """
    Single news page jahan user poori khabar padhega
    """
    post = get_object_or_404(NewsPost, slug=slug, status='published')
    
    # ✅ 1. Related News (Article ke beech ke liye - Same Category)
    related_news = NewsPost.objects.filter(
        category=post.category, 
        status='published'
    ).exclude(id=post.id)[:6]
    
    # ✅ 2. Recent News (Sidebar ke liye - Global Latest)
    recent_news = NewsPost.objects.filter(
        status='published'
    ).exclude(id=post.id).order_by('-created_at')[:5]
    
    # URL validation (Optional): Agar koi galat category slug likhe toh redirect kar sakte hain
    if post.category_slug != category_slug:
        return redirect('news_detail', category_slug=post.category_slug, slug=post.slug)
    
    # Views count badhayein jab koi khabar padhe
    post.views_count += 1
    post.save()
    
    return render(request, 'jobs/news_detail.html', {
        'post': post,
        'related_news': related_news,
        'recent_news': recent_news
    })
    

# jobs/views.py
def country_jobs(request, country_name):
    """
    URL: /jobs/country/jobs-in-<country_name>/
    Logic: 0 jobs ho ya multiple, AI Guide hamesha safe rahega.
    """
    # 1. URL se clean naam nikalein (e.g. 'bangladesh' -> 'Bangladesh')
    url_country_clean = country_name.replace('-', ' ').title()
    if 'uae' in country_name.lower(): url_country_clean = 'United Arab Emirates'

    # 2. Saari approved jobs ke unique country names uthao
    distinct_countries = Job.objects.filter(is_approved=True).values_list('country', flat=True).distinct()
    
    # 3. DB mein check karo kya ye desh hamare jobs mein exist karta hai?
    matched_country = next((c for c in distinct_countries if slugify(c) == country_name), None)
    
    # 🎯 FIX: guide_search_key determine karein (Isse IntegrityError kabhi nahi aayega)
    # Agar DB mein matching job hai toh DB ka value (e.g. 'Russia'), warna URL ka clean value
    guide_search_key = matched_country if matched_country else url_country_clean
    display_name = guide_search_key

    # Queryset logic set karein
    if matched_country:
        # Full label lookup for display (e.g. 'AE' -> 'United Arab Emirates')
        full_label = next((label for val, label in COUNTRY_CHOICES if val == matched_country), matched_country)
        display_name = full_label
        jobs_queryset = Job.objects.filter(country=matched_country, is_approved=True).order_by('-created_at')
    else:
        # 0 Jobs Case: Empty queryset
        jobs_queryset = Job.objects.none()

    # --- 🔍 TRADE SEARCH (User logic integrated) ---
    search_query = request.GET.get('q', '')
    if search_query:
        jobs_queryset = jobs_queryset.filter(
            Q(title__icontains=search_query) | 
            Q(position__title__icontains=search_query) | 
            Q(industry_master__name__icontains=search_query) |
            Q(industry_old__icontains=search_query)
        )

    # --- 💰 SMART SALARY FILTER (User fixed logic) ---
    min_salary = request.GET.get('min_salary')
    
    # Queryset ko list mein badalna zaroori hai memory filtering ke liye
    jobs = list(jobs_queryset)

    if min_salary:
        try:
            min_val = int(min_salary)
            filtered_jobs = []
            
            for j in jobs:
                # Salary string se sirf numbers nikalne ka logic (e.g. "₹60,000/-" -> 60000)
                salary_digits = re.sub(r'\D', '', str(j.salary))
                
                if salary_digits:
                    actual_salary = int(salary_digits)
                    # ✅ CHECK: Agar asli salary min_salary se badi ya barabar hai
                    if actual_salary >= min_val:
                        filtered_jobs.append(j)
                else:
                    # Agar salary field khali nahi hai par number nahi mila, toh safety ke liye dikha do
                    if not min_val: filtered_jobs.append(j)
            
            jobs = filtered_jobs
        except ValueError:
            pass

    # ✅ HIGH-TO-LOW SORTING LOGIC
    jobs.sort(key=lambda j: int(re.sub(r'\D', '', str(j.salary)) or 0), reverse=True)

    # --- 🤖 SMART AI CACHING (The Fix: Using guide_search_key instead of matched_country) ---
    guide_obj = None
    if guide_search_key:
        # Pehle DB mein dhoondo using SAFE KEY
        guide_obj = CountryGuide.objects.filter(country_name=guide_search_key).first()
        
        if not guide_obj:
            # AI se guide banwayein using SAFE KEY
            ai_content = generate_country_guide_ai(guide_search_key)
            if ai_content:
                # Creation using SAFE KEY (matched_country None ho sakta hai, ye nahi hoga)
                guide_obj = CountryGuide.objects.create(
                    country_name=guide_search_key,
                    content_html=ai_content,
                    meta_description=f"Official Videsh Chalo Guide to Working in {guide_search_key}. Get visa and job tips."
                )

    context = {
        'jobs': jobs,
        'country_name': display_name, 
        'country_slug': country_name,
        'search_query': search_query,
        'min_salary': min_salary,
        'country_article': guide_obj.content_html if guide_obj else None,
        'country_article_snippet': guide_obj.meta_description if guide_obj else None,
        'countries': COUNTRY_CHOICES,
    }
    return render(request, 'jobs/country_jobs.html', context)
    
def jobs_by_location(request):
    """
    Landing page that lists all available countries for jobs.
    Excellent for SEO and User Navigation.
    """
    # Filter only those countries that actually have active jobs
    from .models import Job
    active_country_codes = Job.objects.filter(is_approved=True).values_list('country', flat=True).distinct()
    
    # We will pass the full choice list but can highlight those with active jobs
    context = {
        'countries': COUNTRY_CHOICES,
        'active_codes': active_country_codes,
        'meta_title': "Jobs by Country & Location | Videsh Chalo International Career",
        'meta_description': "Find your dream job abroad by location. Explore latest vacancies in Dubai, Russia, Saudi Arabia, Mauritius and more."
    }
    return render(request, 'jobs/jobs_by_location.html', context)
    

def employer_faq_form(request):
    """
    Yash Babu's Special Recruiter Internal Form 🛡️
    - Process: OTP Validation -> Session Check -> Data Submission -> OTP Burn
    """
    
    # 🕵️ SESSION CHECK: Dekho kya recruiter ne pehle se OTP verify kiya hai?
    active_otp = request.session.get('verified_recruiter_otp')
    
    if request.method == "POST":
        
        # --- CASE 1: OTP VERIFICATION ---
        if 'verify_otp' in request.POST:
            otp_input = request.POST.get('otp_code', '').strip()
            
            # Database mein Active OTP dhundo
            otp_obj = FormOTP.objects.filter(code=otp_input, is_used=False).first()
            
            if otp_obj:
                # Session mein save karo taaki form khul sake
                request.session['verified_recruiter_otp'] = otp_input
                # Professional message for recruiter
                messages.success(request, "Access Granted. Please fill out the requirement details below.")
                return redirect('employer_faq_form')
            else:
                # Galat ya used OTP ka message
                messages.error(request, "Invalid or Expired Access Code. Please contact our coordinator.")
                return render(request, 'jobs/otp_entry.html')

        # --- CASE 2: FORM SUBMISSION ---
        elif 'submit_form' in request.POST:
            if not active_otp:
                return redirect('employer_faq_form')

            try:
                # 💾 SAVE DATA: EmployerRequirement model mein data bharein
                EmployerRequirement.objects.create(
                    company_name=request.POST.get('company_name'),
                    contact_person=request.POST.get('contact_person'),
                    positions=request.POST.get('positions'),
                    total_vacancies=request.POST.get('total_vacancies'),
                    responsibilities=request.POST.get('responsibilities'),
                    skills_required=request.POST.get('skills_required'),
                    english_level=request.POST.get('english_level'),
                    working_schedule=request.POST.get('working_schedule'),
                    salary_range=request.POST.get('salary_range'),
                    overtime_details=request.POST.get('overtime_details'),
                    bonuses=request.POST.get('bonuses'),
                    accommodation=request.POST.get('accommodation'),
                    food_allowance=request.POST.get('food_allowance'),
                    transportation=request.POST.get('transportation'),
                    airfare_bearer=request.POST.get('airfare_bearer'),
                    visa_permit_provided=request.POST.get('visa_permit_provided'),
                    visa_processing_handler=request.POST.get('visa_processing_handler'),
                    medical_insurance=request.POST.get('medical_insurance'),
                    contract_duration=request.POST.get('contract_duration'),
                    probation_period=request.POST.get('probation_period'),
                    termination_conditions=request.POST.get('termination_conditions'),
                    paid_leave=request.POST.get('paid_leave'),
                    room_type=request.POST.get('room_type'),
                    people_per_room=request.POST.get('people_per_room'),
                    utilities_included=request.POST.get('utilities_included'),
                    annual_leave_tickets=request.POST.get('annual_leave_tickets'),
                    salary_deductions=request.POST.get('salary_deductions'),
                    arrival_support=request.POST.get('arrival_support'),
                    restrictions=request.POST.get('restrictions'),
                )

                # 🔥 OTP BURN: Is code ko ab dobara use nahi kiya ja sakega
                FormOTP.objects.filter(code=active_otp).update(
                    is_used=True, 
                    used_at=timezone.now()
                )

                # Session clear karein
                del request.session['verified_recruiter_otp']

                return render(request, 'jobs/form_success.html')

            except Exception as e:
                messages.error(request, f"An error occurred while saving: {str(e)}")
                return render(request, 'jobs/requirement_form.html')

    # --- GET REQUEST HANDLING ---
    
    # Agar OTP verified hai toh asli form dikhao
    if active_otp:
        return render(request, 'jobs/requirement_form.html')
    
    # Warna OTP entry screen dikhao
    return render(request, 'jobs/otp_entry.html')