"use client" import { useEffect, useState } from "react" import { useParams, useRouter } from "next/navigation" import { Calendar, User, BookOpen, Wallet, Award, Share2, Download, CheckCircle, AlertCircle } from "lucide-react" import { toast } from "react-hot-toast" interface Certificate { certificate_id: string share_code: string user_name: string student_name: string studentName?: string // camelCase variant userName?: string // camelCase variant course_title: string courseTitle?: string // camelCase variant mentor_name: string instructor_name: string instructorName?: string // camelCase variant mentorName?: string // camelCase variant completion_date: string completionDate?: string // camelCase variant wallet_address?: string walletAddress?: string // camelCase variant issued_by: string issuedBy?: string // camelCase variant view_count: number viewCount?: number // camelCase variant blockchain_hash?: string blockchainHash?: string // camelCase variant public_url?: string publicUrl?: string // camelCase variant verification_url?: string is_verified: boolean isVerified?: boolean // camelCase variant is_revoked: boolean isRevoked?: boolean // camelCase variant } export default function CertificatePage() { const params = useParams() const router = useRouter() const [certificate, setCertificate] = useState(null) const [loading, setLoading] = useState(true) const [error, setError] = useState(null) const certificateId = params?.id as string useEffect(() => { if (certificateId) { fetchCertificate(certificateId) } }, [certificateId]) const fetchCertificate = async (id: string) => { try { setLoading(true) setError(null) console.log(`🔍 Fetching certificate with ID: ${id}`) let response = null // Try verify endpoint first try { console.log(`🔍 Trying verify endpoint: /api/certificate/verify/${id}`) response = await fetch(`http://127.0.0.1:5000/api/certificate/verify/${id}`) if (response.ok) { const data = await response.json() console.log('🔍 Verify endpoint response:', data) if (data.success && data.verified) { console.log('✅ Found certificate by verify endpoint') console.log('🎓 Student name fields:', { student_name: data.certificate?.student_name, user_name: data.certificate?.user_name, studentName: data.certificate?.studentName, userName: data.certificate?.userName }) console.log('👨‍🏫 Instructor name fields:', { instructor_name: data.certificate?.instructor_name, mentor_name: data.certificate?.mentor_name, instructorName: data.certificate?.instructorName, mentorName: data.certificate?.mentorName }) setCertificate(data.certificate) setLoading(false) return } } } catch (error) { console.log('Verify endpoint failed, trying next...') } // Try direct ID endpoint try { console.log(`🔍 Trying direct endpoint: /api/certificate/${id}`) response = await fetch(`http://127.0.0.1:5000/api/certificate/${id}`) if (response.ok) { const data = await response.json() console.log('🔍 Direct endpoint response:', data) if (data.success) { console.log('✅ Found certificate by direct endpoint') console.log('🎓 Student name fields:', { student_name: data.certificate?.student_name, user_name: data.certificate?.user_name, studentName: data.certificate?.studentName, userName: data.certificate?.userName }) console.log('👨‍🏫 Instructor name fields:', { instructor_name: data.certificate?.instructor_name, mentor_name: data.certificate?.mentor_name, instructorName: data.certificate?.instructorName, mentorName: data.certificate?.mentorName }) setCertificate(data.certificate) setLoading(false) return } } } catch (error) { console.log('Direct endpoint failed') } console.error('❌ Certificate not found in any endpoint') setError("Certificate not found") setLoading(false) } catch (error) { console.error('❌ Error fetching certificate:', error) setError("Failed to load certificate") setLoading(false) } } // ✅ FIXED: Helper functions to get names with multiple fallbacks const getStudentName = () => { if (!certificate) return 'Student Name Missing' const name = certificate.student_name || certificate.user_name || certificate.studentName || certificate.userName || 'Student Name Missing' console.log('🎓 Final student name:', name) return name } const getInstructorName = () => { if (!certificate) return 'OpenLearnX Instructor' const name = certificate.instructor_name || certificate.mentor_name || certificate.instructorName || certificate.mentorName || 'OpenLearnX Instructor' console.log('👨‍🏫 Final instructor name:', name) return name } const getCourseTitle = () => { if (!certificate) return 'Course Title Missing' return certificate.course_title || certificate.courseTitle || 'Course Title Missing' } const getCompletionDate = () => { if (!certificate) return new Date() const dateStr = certificate.completion_date || certificate.completionDate || new Date().toISOString() return new Date(dateStr) } const handleDownloadPDF = () => { if (!certificate) return try { const studentName = getStudentName() const instructorName = getInstructorName() const courseTitle = getCourseTitle() const completionDate = getCompletionDate() const certificateHTML = ` Certificate - ${studentName}
🏆

CERTIFICATE OF COMPLETION

This is to certify that
${studentName}
has successfully completed the course
"${courseTitle}"
✅ Completed on: ${completionDate.toLocaleDateString('en-US', { year: 'numeric', month: 'long', day: 'numeric' })}
${instructorName}
Course Instructor
Certificate ID: ${certificate.certificate_id}
OpenLearnX Learning Platform
🔒 Blockchain Verified Completion
` const printWindow = window.open('', '_blank') if (printWindow) { printWindow.document.write(certificateHTML) printWindow.document.close() printWindow.onload = () => { setTimeout(() => { printWindow.print() printWindow.close() }, 500) } toast.success("Certificate PDF download initiated!") } else { toast.error("Popup blocked. Please allow popups and try again.") } } catch (error) { console.error('PDF generation error:', error) toast.error("Failed to generate PDF") } } const handleShare = async () => { if (!certificate) return const studentName = getStudentName() const courseTitle = getCourseTitle() const shareText = `🎓 Check out my certificate of completion for "${courseTitle}" from OpenLearnX!\n\nStudent: ${studentName}\nCertificate ID: ${certificate.certificate_id}\n\n#OpenLearnX #Certificate #Learning` const shareUrl = window.location.href if (navigator.share) { try { await navigator.share({ title: `Certificate - ${courseTitle}`, text: shareText, url: shareUrl }) // Track share try { await fetch(`http://127.0.0.1:5000/api/certificate/share/${certificate.certificate_id}`, { method: 'POST' }) } catch (e) { console.log('Share tracking failed:', e) } } catch (error) { console.log('Share cancelled') } } else { try { await navigator.clipboard.writeText(`${shareText}\n\n${shareUrl}`) toast.success("Certificate link copied to clipboard!") // Track share try { await fetch(`http://127.0.0.1:5000/api/certificate/share/${certificate.certificate_id}`, { method: 'POST' }) } catch (e) { console.log('Share tracking failed:', e) } } catch (error) { toast.error("Failed to copy link") } } } if (loading) { return (

Loading certificate...

Certificate ID: {certificateId}

) } if (error) { return (

Certificate Not Found

{error}

Certificate ID: {certificateId}

) } if (!certificate) { return (

No certificate data available

) } // ✅ Get the final names to display const studentName = getStudentName() const instructorName = getInstructorName() const courseTitle = getCourseTitle() const completionDate = getCompletionDate() return (

Verified Certificate

This certificate has been verified on the blockchain

Verified
🏆

CERTIFICATE OF COMPLETION

This is to certify that

{/* ✅ FIXED: Using helper function for guaranteed name display */}
{studentName}

Student

has successfully completed the course

{/* ✅ FIXED: Using helper function for course title */}

"{courseTitle}"

Completion Date

{completionDate.toLocaleDateString('en-US', { year: 'numeric', month: 'long', day: 'numeric' })}

Certificate ID

{certificate.certificate_id}

Views

{certificate.view_count || certificate.viewCount || 0}

{/* ✅ FIXED: Using helper function for instructor name */}

{instructorName}

Course Instructor

{certificate.issued_by || certificate.issuedBy || 'OpenLearnX'}
Digital Certificate of Achievement
🔒 Blockchain Verified

{(certificate.blockchain_hash || certificate.blockchainHash) && (

Blockchain Hash: {certificate.blockchain_hash || certificate.blockchainHash}

)}

This certificate can be verified at any time using the certificate ID above.

Powered by OpenLearnX • Secured by Blockchain Technology

{/* ✅ DEBUG: Show raw certificate data in development */} {process.env.NODE_ENV === 'development' && (
Debug: Raw Certificate Data
                {JSON.stringify(certificate, null, 2)}
              
)}
) }