<?php
require_once 'includes/config.php';
redirectIfNotLoggedIn();

$userData = getMemberData($pdo, $_SESSION['user_id']);
$status = getMembershipStatus($userData['expiry_date']);

// Get membership type details
$stmt = $pdo->prepare("SELECT mt.type, mt.amount FROM membership_types mt WHERE mt.id = ?");
$stmt->execute([$userData['membership_type_id']]);
$membershipType = $stmt->fetch();

// Handle image paths
$photo_path = 'uploads/' . $userData['profile_photo'];
if (!file_exists($photo_path) || $userData['profile_photo'] == 'default.jpg' || empty($userData['profile_photo'])) {
    $photo_path = 'assets/images/default-avatar.png';
}

// Get authorized signatory from settings or use default
$authorized_signatory = getSystemSetting($pdo, 'authorized_signatory');
$signatory_designation = getSystemSetting($pdo, 'signatory_designation');
if (empty($authorized_signatory)) {
    $authorized_signatory = 'Authorized Signatory';
}
if (empty($signatory_designation)) {
    $signatory_designation = 'PRESIDENT OF BMYA';
}

// Get organization name in uppercase
$organization_name = strtoupper(SITE_NAME);
$association_reg_no = "U88100AS2026NPL030264,LIC NO.183299,";
$reg_additional_text = "(Central Registration Centre- Act, 2013)";

// Change membership number prefix from BMYO to BMYA
$membership_id_prefix = "BMYA"; // Changed from BMYO to BMYA
$original_membership_number = $userData['membership_number'];
// Check if membership number already has prefix and replace it
if (strpos($original_membership_number, 'BMYO/') === 0) {
    $membership_number_display = $membership_id_prefix . substr($original_membership_number, 4);
} elseif (strpos($original_membership_number, 'BMYA/') === 0) {
    $membership_number_display = $original_membership_number;
} else {
    $membership_number_display = $membership_id_prefix . '/' . $original_membership_number;
}

// Watermark image path with BMYA instead of BMYO
$watermark_path = 'assets/images/watermark.png';
if (!file_exists($watermark_path)) {
    $watermark_path = 'data:image/svg+xml;base64,' . base64_encode('<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 200 200"><circle cx="100" cy="100" r="90" fill="none" stroke="rgba(255,255,255,0.25)" stroke-width="3"/><text x="100" y="110" text-anchor="middle" fill="rgba(255,255,255,0.25)" font-size="16" font-weight="bold" font-family="Arial">BMYA</text><line x1="25" y1="25" x2="175" y2="175" stroke="rgba(255,255,255,0.15)" stroke-width="2"/><line x1="175" y1="25" x2="25" y2="175" stroke="rgba(255,255,255,0.15)" stroke-width="2"/><text x="100" y="140" text-anchor="middle" fill="rgba(255,255,255,0.2)" font-size="10" font-family="Arial">MEMBER</text></svg>');
}
?>

<?php include 'header.php'; ?>

<div class="row justify-content-center">
    <div class="col-md-8">
        <div class="card">
            <div class="card-header bg-success text-white text-center">
                <h3 class="mb-0"><i class="fas fa-id-card me-2"></i>Membership ID Card</h3>
            </div>
            <div class="card-body text-center">
                <!-- ID Card Container - PAN Card Style -->
                <div class="id-card-pan-style" id="idCard">
                    <div class="id-card-watermark"></div>
                    <div class="id-card-watermark second"></div>
                    <div class="id-card-watermark third"></div>
                    
                    <div class="id-card-header-pan">
                        <div class="organization-info-pan">
                            <div class="organization-logo-pan">
                                <img src="<?php echo UPLOAD_URL . getSystemSetting($pdo, 'logo'); ?>" 
                                     alt="Organization Logo"
                                     id="orgLogo"
                                     crossorigin="anonymous"
                                     onerror="this.src='assets/images/logo.png'">
                            </div>
                            <h3><?php echo $organization_name; ?></h3>
                            <p class="organization-subtitle-pan">OFFICIAL MEMBERSHIP CARD</p>
                            <p class="association-reg-no-pan">Reg. No: <?php echo $association_reg_no; ?> <?php echo $reg_additional_text; ?></p>
                        </div>
                    </div>
                    
                    <div class="id-card-body-pan">
                        <div class="member-photo-section-pan">
                            <div class="photo-container-pan">
                                <img src="<?php echo $photo_path; ?>" 
                                     class="member-photo-pan" 
                                     alt="Member Photo"
                                     id="memberPhotoElement"
                                     crossorigin="anonymous"
                                     onerror="this.src='assets/images/default-avatar.png'">
                            </div>
                            <div class="photo-label-pan">ID PHOTO</div>
                            <div class="member-id-pan">ID: <?php echo $membership_number_display; ?></div>
                        </div>
                        
                        <div class="member-details-pan">
                            <div class="detail-row-pan">
                                <div class="detail-label-pan">MEMBERSHIP NO:</div>
                                <div class="detail-value-pan"><?php echo $membership_number_display; ?></div>
                            </div>
                            
                            <div class="detail-row-pan">
                                <div class="detail-label-pan">FULL NAME:</div>
                                <div class="detail-value-pan name-pan"><?php echo strtoupper(htmlspecialchars($userData['fullname'])); ?></div>
                            </div>
                            
                            <div class="detail-row-pan">
                                <div class="detail-label-pan">MEMBERSHIP TYPE:</div>
                                <div class="detail-value-pan type-pan"><?php echo htmlspecialchars($membershipType['type']); ?></div>
                            </div>
                            
                            <div class="detail-row-pan">
                                <div class="detail-label-pan">VALID THROUGH:</div>
                                <div class="detail-value-pan">
                                    <?php echo $userData['expiry_date'] ? date('d/m/Y', strtotime($userData['expiry_date'])) : 'LIFETIME'; ?>
                                </div>
                            </div>
                            
                            <div class="detail-row-pan">
                                <div class="detail-label-pan">ADDRESS:</div>
                                <div class="detail-value-pan address-pan"><?php echo htmlspecialchars($userData['address'] ?: 'Not specified'); ?></div>
                            </div>
                        </div>
                    </div>
                    
                    <div class="id-card-footer-pan">
                        <div class="signature-section-pan">
                            <div class="authority-signature-pan" id="signatureContainer">
                                <img src="assets/images/signature.png" 
                                     id="signatureImage"
                                     alt="Signature"
                                     style="width: 70px; height: 30px; object-fit: contain;"
                                     onerror="this.style.display='none'; document.getElementById('fallbackSignature').style.display='block';">
                                <canvas id="fallbackSignature" width="70" height="30" style="display: none;"></canvas>
                            </div>
                            <div class="signature-line-pan"></div>
                            <div class="signature-label-pan">
                                <div class="authority-name-pan" id="authorityName"><?php echo htmlspecialchars($authorized_signatory); ?></div>
                                <div class="authority-designation-pan" id="authorityDesignation"><?php echo htmlspecialchars($signatory_designation); ?></div>
                            </div>
                        </div>
                        <div class="issued-date-pan">
                            ISSUED: <?php echo date('d/m/Y', strtotime($userData['join_date'] ?: 'now')); ?>
                        </div>
                    </div>
                    
                    <div class="security-features-pan">
                        <div class="microprint-pan"><?php echo $organization_name; ?></div>
                    </div>
                </div>
                
                <div class="mt-4">
                    <button onclick="downloadIDCard()" id="downloadBtn" class="btn btn-primary">
                        <i class="fas fa-download"></i> Download as PNG
                    </button>
                    <button onclick="printIDCard()" class="btn btn-secondary">
                        <i class="fas fa-print"></i> Print Card
                    </button>
                </div>
                
                <div class="alert alert-info mt-3 small">
                    <i class="fas fa-info-circle"></i> 
                    This is your official membership ID card. Keep it safe and present when required.
                </div>
            </div>
        </div>
    </div>
</div>

<style>
/* Your existing CSS remains the same */
.id-card-pan-style {
    width: 336px;
    height: 210px;
    background: linear-gradient(135deg, #1e3c72 0%, #2a5298 100%);
    border: 2px solid #1e3c72;
    border-radius: 8px;
    color: white;
    position: relative;
    overflow: hidden;
    font-family: 'Arial', 'Segoe UI', sans-serif;
    box-shadow: 0 8px 25px rgba(0,0,0,0.3);
    margin: 0 auto;
}

.id-card-watermark {
    position: absolute;
    width: 120px;
    height: 120px;
    background-image: url('<?php echo $watermark_path; ?>');
    background-size: contain;
    background-position: center;
    background-repeat: no-repeat;
    opacity: 0.15;
    z-index: 1;
    pointer-events: none;
}

.id-card-watermark {
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%) rotate(-25deg);
}

.id-card-watermark.second {
    top: 15%;
    right: -30px;
    left: auto;
    transform: rotate(15deg) scale(0.7);
    opacity: 0.1;
}

.id-card-watermark.third {
    bottom: 10%;
    left: -30px;
    top: auto;
    transform: rotate(-40deg) scale(0.6);
    opacity: 0.1;
}

.id-card-header-pan {
    background: rgba(255,255,255,0.1);
    padding: 8px 12px;
    border-bottom: 2px solid rgba(255,255,255,0.3);
    position: relative;
    z-index: 2;
}

.organization-info-pan {
    position: relative;
    min-height: 45px;
}

.organization-logo-pan {
    position: absolute;
    left: 0;
    top: 50%;
    transform: translateY(-50%);
    width: 40px;
    height: 40px;
}

.organization-logo-pan img {
    width: 100%;
    height: 100%;
    object-fit: contain;
}

.organization-info-pan h3 {
    font-size: 11px;
    font-weight: bold;
    margin: 0;
    text-align: center;
    margin-left: 45px;
    line-height: 1.2;
}

.organization-subtitle-pan {
    font-size: 7px;
    margin: 2px 0 0;
    text-align: center;
    opacity: 0.85;
    margin-left: 45px;
}

.association-reg-no-pan {
    font-size: 5px;
    margin: 2px 0 0;
    text-align: center;
    opacity: 0.8;
    margin-left: 45px;
    font-weight: normal;
    letter-spacing: 0.3px;
    line-height: 1.2;
    word-break: break-word;
}

.id-card-body-pan {
    padding: 8px 12px;
    display: flex;
    height: 115px;
    position: relative;
    z-index: 2;
}

.member-photo-section-pan {
    flex: 0 0 75px;
    text-align: center;
    margin-right: 10px;
}

.photo-container-pan {
    width: 65px;
    height: 65px;
    border: 2px solid rgba(255,255,255,0.8);
    overflow: hidden;
    margin-bottom: 3px;
    background: rgba(255,255,255,0.1);
}

.member-photo-pan {
    width: 100%;
    height: 100%;
    object-fit: cover;
}

.photo-label-pan {
    font-size: 6px;
    font-weight: bold;
    opacity: 0.8;
}

.member-id-pan {
    font-size: 6px;
    opacity: 0.7;
    margin-top: 2px;
}

.member-details-pan {
    flex: 1;
    text-align: left;
}

.detail-row-pan {
    display: flex;
    margin-bottom: 3px;
    align-items: baseline;
}

.detail-label-pan {
    font-size: 7px;
    font-weight: bold;
    width: 75px;
    flex-shrink: 0;
    opacity: 0.85;
}

.detail-value-pan {
    font-size: 8px;
    font-weight: normal;
    flex: 1;
    word-break: break-word;
}

.detail-value-pan.name-pan {
    font-size: 9px;
    font-weight: bold;
    text-transform: uppercase;
}

.detail-value-pan.type-pan {
    font-size: 9px;
    font-weight: bold;
    color: #FFD700;
}

.detail-value-pan.address-pan {
    font-size: 7px;
    line-height: 1.2;
}

.id-card-footer-pan {
    position: absolute;
    bottom: 0;
    left: 0;
    right: 0;
    padding: 5px 12px;
    background: rgba(0,0,0,0.25);
    display: flex;
    justify-content: space-between;
    align-items: center;
    border-top: 1px solid rgba(255,255,255,0.2);
    z-index: 2;
}

.signature-section-pan {
    text-align: center;
    position: relative;
}

.authority-signature-pan {
    position: absolute;
    bottom: 12px;
    left: 50%;
    transform: translateX(-50%);
    width: 70px;
    height: 30px;
    z-index: 3;
}

.authority-signature-pan img {
    width: 100%;
    height: 100%;
    object-fit: contain;
}

.signature-line-pan {
    width: 80px;
    height: 1px;
    background: rgba(255,255,255,0.8);
    margin-bottom: 2px;
    margin-top: 20px;
}

.signature-label-pan {
    font-size: 5px;
    opacity: 0.7;
}

.authority-name-pan {
    font-weight: bold;
    font-size: 6px;
}

.authority-designation-pan {
    font-size: 5px;
    opacity: 0.8;
}

.issued-date-pan {
    font-size: 6px;
    opacity: 0.8;
}

.security-features-pan {
    position: absolute;
    top: 8px;
    right: 8px;
    z-index: 2;
}

.microprint-pan {
    font-size: 4px;
    transform: rotate(-45deg);
    opacity: 0.25;
    white-space: nowrap;
}

@media (max-width: 480px) {
    .id-card-pan-style {
        transform: scale(0.9);
        margin: 0 auto;
    }
    .id-card-watermark {
        width: 100px;
        height: 100px;
    }
}

@media print {
    .btn, .alert, .card-header {
        display: none !important;
    }
    .id-card-pan-style {
        box-shadow: none;
        margin: 0;
        -webkit-print-color-adjust: exact;
        print-color-adjust: exact;
    }
    .id-card-watermark {
        opacity: 0.1;
    }
}
</style>

<script src="https://cdnjs.cloudflare.com/ajax/libs/html2canvas/1.4.1/html2canvas.min.js"></script>
<script>
// Your existing JavaScript remains the same
function drawFallbackSignature() {
    const canvas = document.getElementById('fallbackSignature');
    if (canvas && canvas.style.display !== 'none') {
        const ctx = canvas.getContext('2d');
        ctx.strokeStyle = '#ffffff';
        ctx.lineWidth = 1.5;
        
        ctx.beginPath();
        ctx.moveTo(5, 15);
        ctx.quadraticCurveTo(15, 5, 25, 15);
        ctx.quadraticCurveTo(35, 25, 45, 15);
        ctx.quadraticCurveTo(55, 5, 65, 15);
        ctx.stroke();
        
        ctx.beginPath();
        ctx.moveTo(10, 22);
        ctx.quadraticCurveTo(20, 12, 30, 22);
        ctx.quadraticCurveTo(40, 32, 50, 22);
        ctx.quadraticCurveTo(60, 12, 68, 22);
        ctx.stroke();
    }
}

function downloadIDCard() {
    const element = document.getElementById('idCard');
    const filename = 'membership_id_card_<?php echo $membership_number_display; ?>.png';
    
    const btn = document.getElementById('downloadBtn');
    const originalHtml = btn.innerHTML;
    btn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Generating...';
    btn.disabled = true;
    
    const images = element.querySelectorAll('img');
    let imagesLoaded = 0;
    const totalImages = images.length;
    
    if (totalImages === 0) {
        captureCard();
    } else {
        images.forEach(img => {
            if (img.complete) {
                imagesLoaded++;
                if (imagesLoaded === totalImages) captureCard();
            } else {
                img.addEventListener('load', () => {
                    imagesLoaded++;
                    if (imagesLoaded === totalImages) captureCard();
                });
                img.addEventListener('error', () => {
                    imagesLoaded++;
                    if (imagesLoaded === totalImages) captureCard();
                });
            }
        });
    }
    
    function captureCard() {
        html2canvas(element, {
            scale: 3,
            backgroundColor: null,
            useCORS: true,
            logging: false,
            allowTaint: false
        }).then(canvas => {
            const link = document.createElement('a');
            link.download = filename;
            link.href = canvas.toDataURL('image/png');
            link.click();
            
            btn.innerHTML = originalHtml;
            btn.disabled = false;
            showNotification('ID Card downloaded successfully!', 'success');
        }).catch(error => {
            console.error('Error:', error);
            btn.innerHTML = originalHtml;
            btn.disabled = false;
            showNotification('Error generating ID card. Please try again.', 'error');
        });
    }
}

function printIDCard() {
    const element = document.getElementById('idCard');
    const printWindow = window.open('', '_blank');
    
    printWindow.document.write('<!DOCTYPE html><html><head><title>Membership ID Card</title>');
    printWindow.document.write('<style>');
    printWindow.document.write(`
        * { margin: 0; padding: 0; box-sizing: border-box; }
        body {
            display: flex;
            justify-content: center;
            align-items: center;
            min-height: 100vh;
            background: #f0f0f0;
            font-family: 'Arial', sans-serif;
        }
        .id-card-pan-style {
            width: 336px;
            height: 210px;
            background: linear-gradient(135deg, #1e3c72 0%, #2a5298 100%);
            border: 2px solid #1e3c72;
            border-radius: 8px;
            color: white;
            position: relative;
            overflow: hidden;
            box-shadow: none;
            margin: 0 auto;
        }
        .id-card-watermark {
            position: absolute;
            width: 120px;
            height: 120px;
            background-image: url('<?php echo $watermark_path; ?>');
            background-size: contain;
            background-position: center;
            background-repeat: no-repeat;
            opacity: 0.15;
            z-index: 1;
            pointer-events: none;
        }
        .id-card-watermark { top: 50%; left: 50%; transform: translate(-50%, -50%) rotate(-25deg); }
        .id-card-watermark.second { top: 15%; right: -30px; left: auto; transform: rotate(15deg) scale(0.7); opacity: 0.1; }
        .id-card-watermark.third { bottom: 10%; left: -30px; top: auto; transform: rotate(-40deg) scale(0.6); opacity: 0.1; }
        .id-card-header-pan { background: rgba(255,255,255,0.1); padding: 8px 12px; border-bottom: 2px solid rgba(255,255,255,0.3); position: relative; z-index: 2; }
        .organization-info-pan { position: relative; min-height: 45px; }
        .organization-logo-pan { position: absolute; left: 0; top: 50%; transform: translateY(-50%); width: 40px; height: 40px; }
        .organization-logo-pan img { width: 100%; height: 100%; object-fit: contain; }
        .organization-info-pan h3 { font-size: 11px; font-weight: bold; margin: 0; text-align: center; margin-left: 45px; }
        .organization-subtitle-pan { font-size: 7px; margin: 2px 0 0; text-align: center; margin-left: 45px; }
        .association-reg-no-pan { font-size: 5px; margin: 2px 0 0; text-align: center; margin-left: 45px; line-height: 1.2; }
        .id-card-body-pan { padding: 8px 12px; display: flex; height: 115px; position: relative; z-index: 2; }
        .member-photo-section-pan { flex: 0 0 75px; text-align: center; margin-right: 10px; }
        .photo-container-pan { width: 65px; height: 65px; border: 2px solid rgba(255,255,255,0.8); overflow: hidden; margin-bottom: 3px; }
        .member-photo-pan { width: 100%; height: 100%; object-fit: cover; }
        .photo-label-pan { font-size: 6px; font-weight: bold; }
        .member-id-pan { font-size: 6px; margin-top: 2px; }
        .member-details-pan { flex: 1; }
        .detail-row-pan { display: flex; margin-bottom: 3px; }
        .detail-label-pan { font-size: 7px; font-weight: bold; width: 75px; }
        .detail-value-pan { font-size: 8px; }
        .detail-value-pan.name-pan { font-size: 9px; font-weight: bold; text-transform: uppercase; }
        .detail-value-pan.type-pan { font-size: 9px; font-weight: bold; color: #FFD700; }
        .detail-value-pan.address-pan { font-size: 7px; }
        .id-card-footer-pan { position: absolute; bottom: 0; left: 0; right: 0; padding: 5px 12px; background: rgba(0,0,0,0.25); display: flex; justify-content: space-between; align-items: center; border-top: 1px solid rgba(255,255,255,0.2); z-index: 2; }
        .signature-section-pan { text-align: center; position: relative; }
        .authority-signature-pan { position: absolute; bottom: 12px; left: 50%; transform: translateX(-50%); width: 70px; height: 30px; }
        .signature-line-pan { width: 80px; height: 1px; background: rgba(255,255,255,0.8); margin-bottom: 2px; margin-top: 20px; }
        .signature-label-pan { font-size: 5px; }
        .authority-name-pan { font-weight: bold; font-size: 6px; }
        .authority-designation-pan { font-size: 5px; }
        .issued-date-pan { font-size: 6px; }
        .security-features-pan { position: absolute; top: 8px; right: 8px; z-index: 2; }
        .microprint-pan { font-size: 4px; transform: rotate(-45deg); opacity: 0.25; white-space: nowrap; }
        @media print {
            body { background: white; }
            .id-card-pan-style { -webkit-print-color-adjust: exact; print-color-adjust: exact; }
            .id-card-watermark { opacity: 0.1; }
        }
    `);
    printWindow.document.write('</style></head><body>');
    printWindow.document.write(element.outerHTML);
    printWindow.document.write('<script>window.onload = function() { window.print(); setTimeout(() => window.close(), 1000); };<\/script>');
    printWindow.document.write('</body></html>');
    printWindow.document.close();
}

function showNotification(message, type) {
    const alertDiv = document.createElement('div');
    alertDiv.className = `alert alert-${type === 'success' ? 'success' : 'danger'} alert-dismissible fade show`;
    alertDiv.style.position = 'fixed';
    alertDiv.style.top = '20px';
    alertDiv.style.right = '20px';
    alertDiv.style.zIndex = '9999';
    alertDiv.style.minWidth = '300px';
    alertDiv.innerHTML = `
        <i class="fas fa-${type === 'success' ? 'check-circle' : 'exclamation-triangle'} me-2"></i>
        ${message}
        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
    `;
    document.body.appendChild(alertDiv);
    
    setTimeout(() => {
        alertDiv.remove();
    }, 5000);
}

document.addEventListener('DOMContentLoaded', function() {
    drawFallbackSignature();
    
    const signatureImg = document.getElementById('signatureImage');
    if (signatureImg) {
        signatureImg.addEventListener('error', function() {
            this.style.display = 'none';
            const fallbackCanvas = document.getElementById('fallbackSignature');
            if (fallbackCanvas) {
                fallbackCanvas.style.display = 'block';
                drawFallbackSignature();
            }
        });
    }
});
</script>

<?php include 'footer.php'; ?>