from django.http import HttpResponse
from django.template.loader import get_template
from xhtml2pdf import pisa
from io import BytesIO
import os
from django.conf import settings

def generate_certificate_pdf(certificate):
    """Generate PDF certificate"""
    try:
        context = {
            'certificate': certificate,
            'student_name': certificate.student.profile.name,
            'course_name': certificate.course.name,
            'certificate_number': certificate.certificate_number,
            'certificate_date': certificate.certificate_date,
            'exam_score': certificate.exam_score,
        }
        
        # Use the HTML template directly since template file might not exist
        html = CERTIFICATE_HTML_TEMPLATE.format(**context)
        
        # Create a Django response object, and specify content_type as pdf
        response = HttpResponse(content_type='application/pdf')
        response['Content-Disposition'] = f'attachment; filename="certificate_{certificate.certificate_number}.pdf"'
        
        # Create a PDF
        pisa_status = pisa.CreatePDF(html, dest=response)
        
        if pisa_status.err:
            return HttpResponse(f'PDF generation error: {pisa_status.err}', status=500)
        return response
    except Exception as e:
        return HttpResponse(f'Certificate generation failed: {str(e)}', status=500)

# Certificate HTML template (minimal design)
CERTIFICATE_HTML_TEMPLATE = """
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>Certificate</title>
    <style>
        body {{ font-family: Arial, sans-serif; text-align: center; padding: 50px; }}
        .certificate {{ border: 5px solid #0066cc; padding: 50px; margin: 20px; }}
        .title {{ font-size: 36px; color: #0066cc; margin-bottom: 30px; }}
        .content {{ font-size: 18px; line-height: 1.6; }}
        .student-name {{ font-size: 24px; font-weight: bold; color: #333; margin: 20px 0; }}
        .course-name {{ font-size: 20px; color: #666; margin: 15px 0; }}
        .score {{ font-size: 16px; color: #0066cc; margin: 10px 0; }}
        .cert-number {{ font-size: 14px; color: #999; margin-top: 30px; }}
    </style>
</head>
<body>
    <div class="certificate">
        <h1 class="title">CERTIFICATE OF COMPLETION</h1>
        <div class="content">
            <p>This is to certify that</p>
            <div class="student-name">{student_name}</div>
            <p>has successfully completed the course</p>
            <div class="course-name">{course_name}</div>
            <div class="score">with a score of {exam_score}%</div>
            <p>Date: {certificate_date}</p>
            <div class="cert-number">Certificate Number: {certificate_number}</div>
        </div>
    </div>
</body>
</html>
"""