from django.shortcuts import render

# Create your views here.
from django.shortcuts import render, redirect
from django.contrib.auth.models import User
from django.contrib.auth import authenticate, login, logout
from django.contrib import messages
from django.http import HttpResponse
from django.template.loader import render_to_string
import pdfkit
import random


def register_view(request):
    if request.method == 'POST':
        username = request.POST.get('username')
        email= request.POST.get('email')
        password = request.POST.get('password')
        password1 = request.POST.get('password1')

         # ✅ Simple email validation (must contain '@')
        if '@' not in email:
            messages.error(request, "❌ Invalid email address. Please include '@'.")
            return redirect("register")

        # ✅ Check if passwords match
        if password == password1:
            # ✅ Check if username already exists
            if User.objects.filter(username=username).exists():
                messages.error(request, "❌ Username already exists. Please try again.")
                return redirect("register")

            # ✅ Check if email already exists
            elif User.objects.filter(email=email).exists():
                messages.error(request, "❌ Email already registered. Please try another.")
                return redirect("register")

            else:
                # ✅ Create user with email
                user = User.objects.create_user(username=username, email=email, password=password)
                user.save()
                messages.success(request, "✅ Account created successfully! Please login.")
                return redirect("login")

        else:
            messages.warning(request, "⚠️ Passwords do not match. Try again.")
            return redirect("register")

    return render(request, 'userapp/register.html')


def login_view(request):
    if request.method == 'POST':
        username = request.POST.get('username')
        password = request.POST.get('password')

        user = authenticate(request, username=username, password=password)

        if user is not None:
            login(request, user)
            messages.success(request, f"✅ Welcome back, {username}!")
            return redirect(demo_view)   # redirect to home page after login
        else:
            messages.error(request, "❌ Invalid username or password. Please try again.")
            return redirect("login")  # reload login page

    return render(request, 'userapp/login.html')

def logout_view(request):
    logout(request)
    return redirect("login")



def demo_view(request):
    return render(request, "userapp/demo.html")

# ------------------ CREATE RESUME ------------------


from django.shortcuts import render, redirect, get_object_or_404
from .models import Resume, PersonalInfo, Education, Experience, Project, Skill, Certification, Achievement, Extracurricular, Reference
from django.contrib.auth.decorators import login_required
from django.urls import reverse

@login_required
def resume_create(request):
    if request.method == "POST":
        # Debugging print
        print(request.POST)  # This will show the submitted form data in the console

        title = request.POST.get("title")
        summary = request.POST.get("summary")
        template_choice = request.POST.get("template_choice") or 'template1'

        print("Selected Template Choice:", template_choice)  # Debugging line

        resume = Resume.objects.create(
            user=request.user,
            title=title,
            summary=summary,
            template_choice=template_choice
        )

        # ---------------- Personal Info ----------------
        PersonalInfo.objects.create(
            resume=resume,
            full_name=request.POST.get("full_name"),
            email=request.POST.get("email"),
            phone=request.POST.get("phone"),
            address=request.POST.get("address"),
            linkedin=request.POST.get("linkedin"),
            github=request.POST.get("github"),
            portfolio=request.POST.get("portfolio"),
            dob=request.POST.get("dob") or None,
            nationality=request.POST.get("nationality"),
        )

        # ---------------- Education ----------------
        if request.POST.get("degree"):
            Education.objects.create(
                resume=resume,
                degree=request.POST.get("degree"),
                institution=request.POST.get("institution"),
                location=request.POST.get("location"),
                start_year=request.POST.get("start_year") or 0,
                end_year=request.POST.get("end_year") or None,
                grade=request.POST.get("grade")
            )

        # ---------------- Experience ----------------
        if request.POST.get("job_title"):
            Experience.objects.create(
                resume=resume,
                job_title=request.POST.get("job_title"),
                company=request.POST.get("company"),
                location=request.POST.get("location"),
                start_date=request.POST.get("start_date"),
                end_date=request.POST.get("end_date") or None,
                responsibilities=request.POST.get("responsibilities")
            )

        # ---------------- Projects ----------------
        if request.POST.get("title"):
            Project.objects.create(
                resume=resume,
                title=request.POST.get("title"),
                organization=request.POST.get("organization"),
                duration=request.POST.get("duration"),
                description=request.POST.get("description"),
                technologies=request.POST.get("technologies")
            )

        # ---------------- Skills ----------------
        skill_categories = request.POST.getlist("category[]")
        skill_names = request.POST.getlist("skill_name[]")
        for cat, name in zip(skill_categories, skill_names):
            if name.strip():
                Skill.objects.create(resume=resume, category=cat, name=name.strip())

        # ---------------- Certifications ----------------
        if request.POST.get("cert_name"):
            Certification.objects.create(
                resume=resume,
                name=request.POST.get("cert_name"),
                issued_by=request.POST.get("issued_by"),
                year=request.POST.get("year") or 0
            )

        # ---------------- Achievements ----------------
        if request.POST.get("ach_title"):
            Achievement.objects.create(
                resume=resume,
                title=request.POST.get("ach_title"),
                description=request.POST.get("ach_description")
            )

        # ---------------- Extracurricular ----------------
        if request.POST.get("activity"):
            Extracurricular.objects.create(
                resume=resume,
                activity=request.POST.get("activity"),
                description=request.POST.get("activity_desc")
            )

        # ---------------- References ----------------
        if request.POST.get("ref_name"):
            Reference.objects.create(
                resume=resume,
                name=request.POST.get("ref_name"),
                designation=request.POST.get("designation"),
                company=request.POST.get("company"),
                contact=request.POST.get("contact")
            )

        # ✅ After saving everything, redirect to resume list
        return redirect('resume_list')

    # ✅ Pass default template_choice to template for radio buttons
    return render(request, "userapp/resume_create.html", {"default_template": "template1"})


# ------------------ LIST RESUMES ------------------
@login_required
def resume_list(request):
    # Show only resumes of the logged-in user
    resumes = Resume.objects.filter(user=request.user).order_by("-created_at")
    return render(request, "userapp/resume_list.html", {"resumes": resumes})



# ------------------ RESUME DETAIL ------------------
from django.shortcuts import render, get_object_or_404
from .models import Resume

@login_required
def resume_detail(request, id):
    # Get the resume object for the logged-in user or return 404
    resume = get_object_or_404(Resume, id=id, user=request.user)

    # Try to fetch related models, handle the case if not found (for one-to-one relationship)
    try:
        personal_info = resume.personal_info
    except PersonalInfo.DoesNotExist:
        personal_info = None  # Handle the case where personal_info might not be set

    # Fetch the related many-to-one models
    education = resume.education.all()  # Fetch related education entries
    experience = resume.experience.all()  # Fetch related experience entries
    projects = resume.projects.all()  # Fetch related projects entries
    skills = resume.skills.all()  # Fetch related skills entries
    certifications = resume.certifications.all()  # Fetch related certifications entries
    achievements = resume.achievements.all()  # Fetch related achievements entries
    extracurricular = resume.extracurricular.all()  # Fetch related extracurricular activities entries
    references = resume.references.all()  # Fetch related references entries

    # Prepare the context dictionary to pass data to the template
    context = {
        "resume": resume,
        "personal_info": personal_info,
        "education": education,
        "experience": experience,
        "projects": projects,
        "skills": skills,
        "certifications": certifications,
        "achievements": achievements,
        "extracurricular": extracurricular,
        "references": references,
    }

    # Dynamically select the template based on the resume's template_choice
    template_choice = resume.template_choice
    # Validate that the template exists, otherwise fall back to a default template
    if template_choice in ['template1', 'template2', 'template3']:
        template_name = f"userapp/resume_{template_choice}.html"
    else:
        # Fallback to a default template if the template_choice is invalid
        template_name = "userapp/resume_template1.html"

    # Render the response with the appropriate template and context data
    return render(request, template_name, context)

# ------------------ EDIT RESUME ------------------
from django.shortcuts import render, get_object_or_404, redirect
from django.contrib.auth.decorators import login_required
from . import models, forms

from django.contrib.auth.decorators import login_required
from django.shortcuts import get_object_or_404, redirect, render

@login_required
def resume_edit(request, id):
    resume = get_object_or_404(Resume, id=id, user=request.user)
    personal_info = getattr(resume, "personal_info", None)

    # Define available templates
    templates = ['template1', 'template2', 'template3']

    if request.method == "POST":
        # Update main resume fields
        resume.title = request.POST.get("title", resume.title)
        resume.summary = request.POST.get("summary", resume.summary)
        resume.template_choice = request.POST.get("template_choice") or 'template1'
        resume.save()

        # Update or create personal info
        if personal_info:
            personal_info.full_name = request.POST.get("full_name", personal_info.full_name)
            personal_info.email = request.POST.get("email", personal_info.email)
            personal_info.phone = request.POST.get("phone", personal_info.phone)
            personal_info.address = request.POST.get("address", personal_info.address)
            personal_info.linkedin = request.POST.get("linkedin", personal_info.linkedin)
            personal_info.github = request.POST.get("github", personal_info.github)
            personal_info.portfolio = request.POST.get("portfolio", personal_info.portfolio)
            personal_info.dob = request.POST.get("dob") or None
            personal_info.nationality = request.POST.get("nationality", personal_info.nationality)
            personal_info.save()
        else:
            PersonalInfo.objects.create(
                resume=resume,
                full_name=request.POST.get("full_name"),
                email=request.POST.get("email"),
                phone=request.POST.get("phone"),
                address=request.POST.get("address"),
                linkedin=request.POST.get("linkedin"),
                github=request.POST.get("github"),
                portfolio=request.POST.get("portfolio"),
                dob=request.POST.get("dob") or None,
                nationality=request.POST.get("nationality"),
            )

        # Replace all related items safely
        # Education
        resume.education.all().delete()
        if request.POST.get("degree"):
            Education.objects.create(
                resume=resume,
                degree=request.POST.get("degree"),
                institution=request.POST.get("institution"),
                location=request.POST.get("location"),
                start_year=request.POST.get("start_year") or 0,
                end_year=request.POST.get("end_year") or None,
                grade=request.POST.get("grade")
            )

        # Experience
        resume.experience.all().delete()
        if request.POST.get("job_title"):
            Experience.objects.create(
                resume=resume,
                job_title=request.POST.get("job_title"),
                company=request.POST.get("company"),
                location=request.POST.get("location"),
                start_date=request.POST.get("start_date"),
                end_date=request.POST.get("end_date") or None,
                responsibilities=request.POST.get("responsibilities")
            )

        # Projects
        resume.projects.all().delete()
        if request.POST.get("project_title"):
            Project.objects.create(
                resume=resume,
                title=request.POST.get("project_title"),
                organization=request.POST.get("organization"),
                duration=request.POST.get("duration"),
                description=request.POST.get("description"),
                technologies=request.POST.get("technologies")
            )

        # Skills - multiple items
        resume.skills.all().delete()
        skill_categories = request.POST.getlist("category[]")
        skill_names = request.POST.getlist("skill_name[]")
        for cat, name in zip(skill_categories, skill_names):
            if name.strip():
                Skill.objects.create(resume=resume, category=cat, name=name.strip())

        # Certifications
        resume.certifications.all().delete()
        if request.POST.get("cert_name"):
            Certification.objects.create(
                resume=resume,
                name=request.POST.get("cert_name"),
                issued_by=request.POST.get("issued_by"),
                year=request.POST.get("year") or 0
            )

        # Achievements
        resume.achievements.all().delete()
        if request.POST.get("ach_title"):
            Achievement.objects.create(
                resume=resume,
                title=request.POST.get("ach_title"),
                description=request.POST.get("ach_description")
            )

        # Extracurricular activities
        resume.extracurricular.all().delete()
        if request.POST.get("activity"):
            Extracurricular.objects.create(
                resume=resume,
                activity=request.POST.get("activity"),
                description=request.POST.get("activity_desc")
            )

        # References
        resume.references.all().delete()
        if request.POST.get("ref_name"):
            Reference.objects.create(
                resume=resume,
                name=request.POST.get("ref_name"),
                designation=request.POST.get("designation"),
                company=request.POST.get("company"),
                contact=request.POST.get("contact")
            )

        return redirect('resume_list')

    # Prepare context for GET request to populate form
    context = {
        "resume": resume,
        "personal_info": personal_info,
        "education": resume.education.first(),
        "experience": resume.experience.first(),
        "project": resume.projects.first(),
        "skills": resume.skills.all(),
        "certification": resume.certifications.first(),
        "achievement": resume.achievements.first(),
        "extracurricular": resume.extracurricular.first(),
        "reference": resume.references.first(),
        "templates": templates,
    }

    return render(request, "userapp/resume_edit.html", context)


# ------------------ DELETE RESUME ------------------
def resume_delete(request, id):
    resume = get_object_or_404(Resume, id=id)
    if request.method == "POST":
        resume.delete()
        return redirect("resume_list")
    return render(request, "userapp/resume_delete_confirm.html", {"resume": resume})

from django.http import HttpResponse
from django.template.loader import get_template
from xhtml2pdf import pisa
from django.shortcuts import get_object_or_404
from .models import Resume
import io

def resume_download(request, id):
    resume = get_object_or_404(Resume, id=id)
    template = get_template('userapp/resume_detail_pdf.html')
    html = template.render({'resume': resume})

    # Create a PDF
    result = io.BytesIO()
    pdf = pisa.pisaDocument(io.BytesIO(html.encode("UTF-8")), result)

    if not pdf.err:
        response = HttpResponse(result.getvalue(), content_type='application/pdf')
        response['Content-Disposition'] = f'attachment; filename="{resume.title}.pdf"'
        return response
    return HttpResponse('Error generating PDF', status=500)
@login_required
def resume_preview(request, resume_id):
    resume = get_object_or_404(Resume, id=resume_id, user=request.user)
    context = {
        'resume': resume,
        'personal_info': getattr(resume, 'personal_info', None),
        'educations': resume.education.all(),
        'experiences': resume.experience.all(),
        'projects': resume.projects.all(),
        'skills': resume.skills.all(),
        'certifications': resume.certifications.all(),
        'achievements': resume.achievements.all(),
        'extracurriculars': resume.extracurricular.all(),
        'references': resume.references.all(),
    }

    # ✅ Dynamic template selection with default fallback to template1
    template_map = {
        'template1': 'userapp/resume_template1.html',
        'template2': 'userapp/resume_template2.html',
        'template3': 'userapp/resume_template3.html',
    }

    selected_template = template_map.get(resume.template_choice or 'template1', 'userapp/resume_template1.html')
    return render(request, selected_template, context)



# def form_view(request,id):
#     resume = models.Resume.objects.get(id=id)
#     PersonalInfo = models.PersonalInfo.objects.get(id=id)
#     Education = models.Education.objects.get(id=id)
#     Experience = models.Experience.objects.get(id=id)
#     Project = models.Project.objects.get(id=id)
#     Skill = models.Skill.objects.get(id=id)
#     Certification = models.Certification.objects.get(id=id)
#     Achievement = models.Achievement.objects.get(id=id)
#     Extracurricular = models.Extracurricular.objects.get(id=id)
#     Reference = models.Reference.objects.get(id=id)
#     if request.method == 'POST':
#         form = forms.PetForm(request.POST, instance=)  
#         if form.is_valid():
#             form.save()
#             return redirect(resume_list)
#         else:
#             print(form.errors)
#     context = {
#         'form': form,
#         'resume': resume,
#         'PersonalInfo': PersonalInfo,
#         'Education': Education,
#         'Experience': Experience,
#         'Project': Project,
#         'Skill': Skill,
#         'Certification': Certification,
#         'Achievement': Achievement,
#         'Extracurricular': Extracurricular,
#         'Reference': Reference,
#     }
#     return render(request, 'pet/edit_form.html', context)


# @login_required
# def resume_edit(request, id):
#     resume = get_object_or_404(Resume, id=id, user=request.user)

#     personal_info = getattr(resume, "personal_info", None)
#     education = resume.education.all()
#     experience = resume.experience.all()
#     projects = resume.projects.all()
#     skills = resume.skills.all()
#     certifications = resume.certifications.all()
#     achievements = resume.achievements.all()
#     extracurricular = resume.extracurricular.all()
#     references = resume.references.all()

#     if request.method == "POST":
#         # --- Resume Basic Info ---
#         resume.title = request.POST.get("title", "")
#         resume.summary = request.POST.get("summary", "")
#         resume.template_choice = request.POST.get("template_choice", "template1")
#         resume.save()

#         # --- Personal Info ---
#         if personal_info:
#             personal_info.full_name = request.POST.get("full_name", "")
#             personal_info.email = request.POST.get("email", "")
#             personal_info.phone = request.POST.get("phone", "")
#             personal_info.address = request.POST.get("address", "")
#             personal_info.linkedin = request.POST.get("linkedin", "")
#             personal_info.github = request.POST.get("github", "")
#             personal_info.portfolio = request.POST.get("portfolio", "")
#             personal_info.dob = request.POST.get("dob") or None
#             personal_info.nationality = request.POST.get("nationality", "")
#             personal_info.save()
#         else:
#             PersonalInfo.objects.create(
#                 resume=resume,
#                 full_name=request.POST.get("full_name", ""),
#                 email=request.POST.get("email", ""),
#                 phone=request.POST.get("phone", ""),
#                 address=request.POST.get("address", ""),
#                 linkedin=request.POST.get("linkedin", ""),
#                 github=request.POST.get("github", ""),
#                 portfolio=request.POST.get("portfolio", ""),
#                 dob=request.POST.get("dob") or None,
#                 nationality=request.POST.get("nationality", "")
#             )

#         # --- Education ---
#         resume.education.all().delete()
#         degrees = request.POST.getlist("degree")
#         institutions = request.POST.getlist("institution")
#         locations = request.POST.getlist("edu_location")
#         start_years = request.POST.getlist("start_year")
#         end_years = request.POST.getlist("end_year")
#         grades = request.POST.getlist("grade")
#         for i in range(len(degrees)):
#             if degrees[i]:
#                 Education.objects.create(
#                     resume=resume,
#                     degree=degrees[i],
#                     institution=institutions[i],
#                     location=locations[i],
#                     start_year=start_years[i] or 0,
#                     end_year=end_years[i] or None,
#                     grade=grades[i]
#                 )

#         # --- Experience ---
#         resume.experience.all().delete()
#         job_titles = request.POST.getlist("job_title")
#         companies = request.POST.getlist("company")
#         exp_locations = request.POST.getlist("exp_location")
#         start_dates = request.POST.getlist("start_date")
#         end_dates = request.POST.getlist("end_date")
#         responsibilities_list = request.POST.getlist("responsibilities")
#         for i in range(len(job_titles)):
#             if job_titles[i]:
#                 Experience.objects.create(
#                     resume=resume,
#                     job_title=job_titles[i],
#                     company=companies[i],
#                     location=exp_locations[i],
#                     start_date=start_dates[i] or None,
#                     end_date=end_dates[i] or None,
#                     responsibilities=responsibilities_list[i]
#                 )

#         # --- Projects ---
#         resume.projects.all().delete()
#         project_titles = request.POST.getlist("project_title")
#         organizations = request.POST.getlist("organization")
#         durations = request.POST.getlist("duration")
#         descriptions = request.POST.getlist("description")
#         technologies_list = request.POST.getlist("technologies")
#         for i in range(len(project_titles)):
#             if project_titles[i]:
#                 Project.objects.create(
#                     resume=resume,
#                     title=project_titles[i],
#                     organization=organizations[i],
#                     duration=durations[i],
#                     description=descriptions[i],
#                     technologies=technologies_list[i]
#                 )

#         # --- Skills ---
#         resume.skills.all().delete()
#         skill_categories = request.POST.getlist("category[]")
#         skill_names = request.POST.getlist("skill_name[]")
#         for category, name in zip(skill_categories, skill_names):
#             if name:
#                 Skill.objects.create(resume=resume, category=category, name=name)

#         # --- Certifications ---
#         resume.certifications.all().delete()
#         cert_names = request.POST.getlist("cert_name")
#         issued_bys = request.POST.getlist("issued_by")
#         years = request.POST.getlist("year")
#         for i in range(len(cert_names)):
#             if cert_names[i]:
#                 Certification.objects.create(
#                     resume=resume,
#                     name=cert_names[i],
#                     issued_by=issued_bys[i],
#                     year=years[i] or 0
#                 )

#         # --- Achievements ---
#         resume.achievements.all().delete()
#         ach_titles = request.POST.getlist("ach_title")
#         ach_descriptions = request.POST.getlist("ach_description")
#         for i in range(len(ach_titles)):
#             if ach_titles[i]:
#                 Achievement.objects.create(
#                     resume=resume,
#                     title=ach_titles[i],
#                     description=ach_descriptions[i]
#                 )

#         # --- Extracurricular ---
#         resume.extracurricular.all().delete()
#         activities = request.POST.getlist("activity")
#         activity_descs = request.POST.getlist("activity_desc")
#         for i in range(len(activities)):
#             if activities[i]:
#                 Extracurricular.objects.create(
#                     resume=resume,
#                     activity=activities[i],
#                     description=activity_descs[i]
#                 )

#         # --- References ---
#         resume.references.all().delete()
#         ref_names = request.POST.getlist("ref_name")
#         designations = request.POST.getlist("designation")
#         ref_companies = request.POST.getlist("ref_company")
#         contacts = request.POST.getlist("contact")
#         for i in range(len(ref_names)):
#             if ref_names[i]:
#                 Reference.objects.create(
#                     resume=resume,
#                     name=ref_names[i],
#                     designation=designations[i],
#                     company=ref_companies[i],
#                     contact=contacts[i]
#                 )

#         return redirect("resume_list")

#     context = {
#         "resume": resume,
#         "personal_info": personal_info,
#         "education": education,
#         "experience": experience,
#         "projects": projects,
#         "skills": skills,
#         "certifications": certifications,
#         "achievements": achievements,
#         "extracurricular": extracurricular,
#         "references": references,
#     }
#     return render(request, "userapp/resume_form.html", context)