<?php
// Start session
require_once 'session_config_emp.php';

// Check if employee is logged in
if (!isset($_SESSION['employee_id']) || !isset($_SESSION['cnic'])) {
    header('Location: login_emp.php');
    exit();
}

include 'connect.php';

// Get employee data from session
$employee_id = $_SESSION['employee_id'];
$cnic = $_SESSION['cnic'];

// First, get the personal_no from registrations_emp
$sql_reg = "SELECT emp_numb FROM registrations_emp WHERE id = ? AND cnic = ?";
$stmt_reg = $conn->prepare($sql_reg);
$stmt_reg->bind_param("is", $employee_id, $cnic);
$stmt_reg->execute();
$result_reg = $stmt_reg->get_result();

if ($result_reg->num_rows > 0) {
    $reg_data = $result_reg->fetch_assoc();
    $personal_no = $reg_data['emp_numb'];
    
    // Get employee_id from employees table
    $emp_sql = "SELECT employee_id FROM employees WHERE personal_no = ? LIMIT 1";
    $stmt_emp = $conn->prepare($emp_sql);
    $stmt_emp->bind_param("s", $personal_no);
    $stmt_emp->execute();
    $emp_result = $stmt_emp->get_result();
    
    if ($emp_result->num_rows > 0) {
        $employee_data = $emp_result->fetch_assoc();
        $db_employee_id = $employee_data['employee_id'];
        
        // Fetch professional qualifications with proper joins
        $professional_sql = "SELECT pq.*, 
                             CASE 
                                 WHEN pq.institution LIKE 'Board%' THEN b.b_name 
                                 WHEN pq.institution LIKE 'Uni%' THEN u.uni_name 
                                 ELSE pq.institution 
                             END as institution_name
                             FROM professional_qualifications pq
                             LEFT JOIN boards b ON pq.institution = CONCAT('Board', b.b_id)
                             LEFT JOIN universities u ON pq.institution = CONCAT('Uni', u.uni_id)
                             WHERE pq.employee_id = ? 
                             ORDER BY 
                             CASE 
                                 WHEN pq.passing_year != '0000-00-00' THEN pq.passing_year 
                                 ELSE '9999-12-31'
                             END DESC, 
                             pq.qualification_id DESC";
        
        $stmt_professional = $conn->prepare($professional_sql);
        $stmt_professional->bind_param("i", $db_employee_id);
        $stmt_professional->execute();
        $professional_result = $stmt_professional->get_result();
        
        $qualifications = [];
        while($row = $professional_result->fetch_assoc()) {
            $qualifications[] = $row;
        }
        
        // Calculate totals and statistics
        $total_qualifications = count($qualifications);
        
        // Function to format date properly
        function formatDateDisplay($date) {
            if (empty($date) || $date == '0000-00-00' || $date == '0000-00-00 00:00:00') {
                return 'N/A';
            }
            return date("d M Y", strtotime($date));
        }
        
        // Function to calculate percentage
        function calculatePercentage($obtained, $total) {
            if ($total == 0 || $obtained == 0) return 0;
            return ($obtained / $total) * 100;
        }
        
        // Function to get grade/division based on percentage
        function getDivisionGrade($percentage) {
            if ($percentage >= 80) {
                return 'A+ (Distinction)';
            } elseif ($percentage >= 70) {
                return 'A (Excellent)';
            } elseif ($percentage >= 60) {
                return 'B (Good)';
            } elseif ($percentage >= 50) {
                return 'C (Average)';
            } elseif ($percentage >= 40) {
                return 'D (Pass)';
            } else {
                return 'F (Fail)';
            }
        }
    }
}

// Close statements
if (isset($stmt_reg)) $stmt_reg->close();
if (isset($stmt_emp)) $stmt_emp->close();
if (isset($stmt_professional)) $stmt_professional->close();
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Professional Qualifications</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
<style>
    :root {
        --primary-info: #0dcaf0;
        --secondary-info: #31d2f2;
        --primary-blue: #0d6efd;
    }
    
    body {
        font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
        background-color: #f8f9fa;
        padding: 20px;
    }
    
    .professional-container {
        max-width: 1200px;
        margin: 0 auto;
    }
    
    .professional-card {
        border: none;
        border-radius: 15px;
        box-shadow: 0 5px 25px rgba(0,0,0,0.1);
        background: white;
        overflow: hidden;
    }
    
    .professional-header {
        background: linear-gradient(135deg, #0dcaf0 0%, #0d6efd 100%);
        color: white;
        padding: 25px 30px;
    }
    
    .qualification-card {
        border: 1px solid #dee2e6;
        border-radius: 10px;
        padding: 20px;
        margin-bottom: 20px;
        transition: all 0.3s ease;
        background: #f8fafc;
    }
    
    .professional-qualification-card {
        border-left: 4px solid #0dcaf0;
    }
    
    .qualification-card:hover {
        box-shadow: 0 5px 15px rgba(13, 202, 240, 0.2);
        transform: translateY(-2px);
    }
    
    .degree-badge {
        display: inline-block;
        padding: 5px 12px;
        border-radius: 20px;
        font-size: 0.85rem;
        font-weight: 500;
        color: white;
        margin-bottom: 10px;
    }
    
    .bg-info {
        background: #0dcaf0 !important;
    }
    
    .grade-badge {
        display: inline-block;
        padding: 5px 12px;
        border-radius: 20px;
        font-size: 0.85rem;
        font-weight: 500;
        color: white;
    }
    
    .badge-a {
        background: #198754;
    }
    
    .badge-b {
        background: #0dcaf0;
    }
    
    .badge-c {
        background: #ffc107;
        color: #000;
    }
    
    .badge-d {
        background: #fd7e14;
    }
    
    .badge-f {
        background: #dc3545;
    }
    
    .info-row {
        display: flex;
        align-items: center;
        margin-bottom: 8px;
        padding-bottom: 8px;
        border-bottom: 1px solid #e9ecef;
    }
    
    .info-label {
        font-weight: 500;
        color: #495057;
        min-width: 150px;
    }
    
    .info-value {
        font-weight: 500;
        color: #212529;
    }
    
    .empty-state {
        text-align: center;
        padding: 50px 20px;
        color: #6c757d;
    }
    
    .empty-state i {
        font-size: 64px;
        margin-bottom: 20px;
        color: #dee2e6;
    }
    
    .btn-add {
        background: var(--primary-info);
        color: white;
        border: none;
        padding: 10px 20px;
        border-radius: 5px;
        font-weight: 500;
        transition: all 0.3s ease;
    }
    
    .btn-add:hover {
        background: var(--secondary-info);
        color: white;
        transform: translateY(-2px);
    }
    
    .btn-edit {
        background: #0d6efd;
        color: white;
        border: none;
        padding: 5px 12px;
        border-radius: 5px;
        font-weight: 500;
        transition: all 0.3s ease;
        font-size: 0.85rem;
    }
    
    .btn-edit:hover {
        background: #0b5ed7;
        color: white;
        transform: translateY(-1px);
    }
    
    .btn-delete {
        background: #dc3545;
        color: white;
        border: none;
        padding: 5px 12px;
        border-radius: 5px;
        font-weight: 500;
        transition: all 0.3s ease;
        font-size: 0.85rem;
    }
    
    .btn-delete:hover {
        background: #bb2d3b;
        color: white;
        transform: translateY(-1px);
    }
    
    .btn-back {
        background: #6c757d;
        color: white;
        border: none;
        padding: 10px 20px;
        border-radius: 5px;
        font-weight: 500;
        transition: all 0.3s ease;
    }
    
    .btn-back:hover {
        background: #5a6268;
        color: white;
        transform: translateY(-2px);
    }
    
    .action-buttons {
        display: flex;
        gap: 10px;
        flex-wrap: wrap;
    }
    
    .summary-card {
        background: linear-gradient(135deg, #f8f9fa 0%, #e9ecef 100%);
        border-radius: 10px;
        padding: 20px;
        margin-bottom: 25px;
        border-left: 4px solid var(--primary-info);
        border: 1px solid #dee2e6;
    }
    
    .summary-title {
        font-weight: 600;
        color: var(--primary-info);
        margin-bottom: 15px;
        font-size: 1.1rem;
        display: flex;
        align-items: center;
        gap: 10px;
    }
    
    .summary-value {
        font-size: 2rem;
        font-weight: 700;
        color: var(--primary-blue);
        text-align: center;
    }
    
    .summary-label {
        text-align: center;
        color: #6c757d;
        font-size: 0.9rem;
    }
    
    .stats-card {
        background: white;
        border-radius: 10px;
        padding: 15px;
        text-align: center;
        box-shadow: 0 2px 5px rgba(0,0,0,0.05);
        border: 1px solid #e9ecef;
    }
    
    .stats-value {
        font-size: 1.5rem;
        font-weight: 700;
        color: var(--primary-info);
    }
    
    .stats-label {
        color: #6c757d;
        font-size: 0.85rem;
        margin-top: 5px;
    }
</style>
</head>
<body>
<div class="professional-container">
    <div class="professional-card">
        <div class="professional-header">
            <h2 class="mb-0">
                <i class="fas fa-certificate me-2"></i>Professional Qualifications
            </h2>
            <p class="mb-0 mt-2">View and manage your professional certifications and qualifications</p>
        </div>
        
        <div class="p-4">
            <?php if(isset($db_employee_id)): ?>
                <!-- STATISTICS SECTION -->
                <div class="summary-card">
                    <div class="row">
                        <div class="col-md-4">
                            <div class="stats-card">
                                <div class="stats-value"><?php echo $total_qualifications; ?></div>
                                <div class="stats-label">Total Qualifications</div>
                            </div>
                        </div>
                        <div class="col-md-8">
                            <h5 class="summary-title">
                                <i class="fas fa-chart-bar"></i>Professional Development Overview
                            </h5>
                            <p class="mb-0">Track your professional growth and certifications. Professional qualifications enhance your career prospects and demonstrate your commitment to continuous learning.</p>
                        </div>
                    </div>
                </div>
                
                <!-- ACTION BUTTONS -->
                <div class="d-flex justify-content-between align-items-center mb-4">
                    <div>
                        <h5 class="mb-0" style="color: var(--primary-info);">
                            <i class="fas fa-certificate me-2"></i>Professional Qualifications
                        </h5>
                        <p class="text-muted mb-0">All your professional certifications and qualifications</p>
                    </div>
                    <div class="action-buttons">
                        <a href="professional_qualification_edit.php" class="btn btn-add">
                            <i class="fas fa-plus me-2"></i>Add Qualification
                        </a>
                        <a href="employee_profile_view.php" class="btn btn-back">
                            <i class="fas fa-arrow-left me-2"></i>Back to Profile
                        </a>
                    </div>
                </div>
                
                <!-- QUALIFICATIONS LIST -->
                <?php if(isset($qualifications) && count($qualifications) > 0): ?>
                    <?php foreach($qualifications as $qual): 
                        $percentage = calculatePercentage($qual['obtained_marks'], $qual['total_marks']);
                        $division_grade = !empty($qual['division_grade']) ? $qual['division_grade'] : getDivisionGrade($percentage);
                        $badge_class = 'badge-' . strtolower(str_replace([' ', '/', '+', '(', ')'], ['-', '', '', '', ''], explode(' ', $division_grade)[0]));
                        $institution_display = $qual['institution_name'] ?? $qual['institution'] ?? 'N/A';
                        $passing_year_display = formatDateDisplay($qual['passing_year']);
                        $passing_year_only = ($qual['passing_year'] != '0000-00-00') ? date('Y', strtotime($qual['passing_year'])) : 'N/A';
                    ?>
                        <div class="qualification-card professional-qualification-card">
                            <div class="d-flex justify-content-between align-items-start mb-3">
                                <div>
                                    <span class="degree-badge bg-info">
                                        <i class="fas fa-certificate me-1"></i>
                                        Professional Certification
                                    </span>
                                    <h5 class="mb-1"><?php echo htmlspecialchars($qual['qualification_name']); ?></h5>
                                    <p class="text-muted mb-0">
                                        <i class="fas fa-university me-1"></i>
                                        <?php echo htmlspecialchars($institution_display); ?>
                                        |
                                        <i class="fas fa-calendar-alt me-1"></i>
                                        Year: <?php echo $passing_year_only; ?>
                                    </p>
                                </div>
                                <div>
                                    <?php if(!empty($qual['division_grade']) || $qual['total_marks'] > 0): ?>
                                    <span class="grade-badge <?php echo $badge_class; ?>">
                                        <?php echo htmlspecialchars($division_grade); ?>
                                    </span>
                                    <?php endif; ?>
                                </div>
                            </div>
                            
                            <div class="row">
                                <div class="col-md-6">
                                    <div class="info-row">
                                        <span class="info-label">Qualification:</span>
                                        <span class="info-value"><?php echo htmlspecialchars($qual['qualification_name']); ?></span>
                                    </div>
                                    <div class="info-row">
                                        <span class="info-label">Institution:</span>
                                        <span class="info-value"><?php echo htmlspecialchars($institution_display); ?></span>
                                    </div>
                                    <?php if(!empty($qual['passing_year']) && $qual['passing_year'] != '0000-00-00'): ?>
                                    <div class="info-row">
                                        <span class="info-label">Completion Date:</span>
                                        <span class="info-value"><?php echo $passing_year_display; ?></span>
                                    </div>
                                    <?php endif; ?>
                                </div>
                                <div class="col-md-6">
                                    <?php if($qual['total_marks'] > 0): ?>
                                    <div class="info-row">
                                        <span class="info-label">Marks Obtained:</span>
                                        <span class="info-value"><?php echo number_format($qual['obtained_marks'] ?? 0, 2); ?> / <?php echo number_format($qual['total_marks'], 2); ?></span>
                                    </div>
                                    <div class="info-row">
                                        <span class="info-label">Percentage:</span>
                                        <span class="info-value"><?php echo number_format($percentage, 2); ?>%</span>
                                    </div>
                                    <?php endif; ?>
                                    <div class="info-row">
                                        <span class="info-label">Grade/Division:</span>
                                        <span class="info-value"><?php echo htmlspecialchars($division_grade); ?></span>
                                    </div>
                                </div>
                            </div>
                            
                            <div class="d-flex justify-content-end gap-2 mt-3">
                                <a href="professional_qualification_edit.php?qualification_id=<?php echo $qual['qualification_id']; ?>" class="btn btn-edit">
                                    <i class="fas fa-edit me-1"></i>Edit
                                </a>
                                <button type="button" class="btn btn-delete" onclick="deleteProfessionalQualification(<?php echo $qual['qualification_id']; ?>)">
                                    <i class="fas fa-trash me-1"></i>Delete
                                </button>
                            </div>
                        </div>
                    <?php endforeach; ?>
                <?php else: ?>
                    <!-- EMPTY STATE -->
                    <div class="empty-state">
                        <i class="fas fa-certificate"></i>
                        <h4>No Professional Qualifications Found</h4>
                        <p class="mb-4">You haven't added any professional qualifications yet. Professional certifications enhance your career growth and demonstrate specialized skills.</p>
                        <a href="professional_qualification_edit.php" class="btn btn-add">
                            <i class="fas fa-plus me-2"></i>Add Your First Professional Qualification
                        </a>
                    </div>
                <?php endif; ?>
                
                <!-- BACK BUTTON -->
                <div class="text-center mt-4">
                    <a href="employee_profile_view.php" class="btn btn-back">
                        <i class="fas fa-arrow-left me-2"></i>Back to Profile
                    </a>
                </div>
            <?php else: ?>
                <div class="alert alert-warning">
                    <h4><i class="fas fa-exclamation-triangle me-2"></i>Profile Not Found</h4>
                    <p>Your employee profile is not linked to the main database.</p>
                    <p>Please contact the administrator to complete your profile setup.</p>
                </div>
            <?php endif; ?>
        </div>
    </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/js/bootstrap.bundle.min.js"></script>
<script>
    // AJAX Delete Function - FIXED VERSION
    function deleteProfessionalQualification(qualificationId, buttonElement) {
        if (confirm('Are you sure you want to delete this professional qualification? This action cannot be undone.')) {
            // Show loading
            const deleteBtn = buttonElement || event.target.closest('button') || event.target;
            const originalText = deleteBtn.innerHTML;
            deleteBtn.innerHTML = '<i class="fas fa-spinner fa-spin me-1"></i>Deleting...';
            deleteBtn.disabled = true;
            
            // Create FormData
            const formData = new FormData();
            formData.append('qualification_id', qualificationId);
            
            // Send AJAX request
            fetch('delete_professional_ajax.php', {
                method: 'POST',
                body: formData
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    // Show success message
                    showAlert('success', data.message);
                    
                    // Remove the qualification card from DOM
                    const qualificationCard = deleteBtn.closest('.qualification-card');
                    if (qualificationCard) {
                        qualificationCard.style.transition = 'all 0.3s ease';
                        qualificationCard.style.opacity = '0';
                        qualificationCard.style.transform = 'translateX(-100%)';
                        
                        setTimeout(() => {
                            qualificationCard.remove();
                            
                            // Update qualification count if exists
                            const countElement = document.querySelector('.summary-value');
                            if (countElement) {
                                const currentCount = parseInt(countElement.textContent);
                                countElement.textContent = currentCount - 1;
                            }
                            
                            // If no qualifications left, show empty state
                            const qualificationsContainer = document.querySelector('.qualification-card') ? 
                                document.querySelector('.qualification-card').parentElement : null;
                            if (qualificationsContainer && !qualificationsContainer.querySelector('.qualification-card')) {
                                qualificationsContainer.innerHTML = `
                                    <div class="empty-state">
                                        <i class="fas fa-certificate"></i>
                                        <h4>No Professional Qualifications Found</h4>
                                        <p class="mb-4">You haven't added any professional qualifications yet.</p>
                                        <a href="professional_qualification_edit.php" class="btn btn-add">
                                            <i class="fas fa-plus me-2"></i>Add Your First Professional Qualification
                                        </a>
                                    </div>
                                `;
                            }
                        }, 300);
                    }
                } else {
                    // Show error message
                    showAlert('danger', data.message);
                    deleteBtn.innerHTML = originalText;
                    deleteBtn.disabled = false;
                }
            })
            .catch(error => {
                console.error('Error:', error);
                showAlert('danger', 'An error occurred while deleting. Please try again.');
                deleteBtn.innerHTML = originalText;
                deleteBtn.disabled = false;
            });
        }
    }

    // Helper function to show alerts
    function showAlert(type, message) {
        // Remove any existing alerts first
        const existingAlerts = document.querySelectorAll('.alert');
        existingAlerts.forEach(alert => {
            const bsAlert = new bootstrap.Alert(alert);
            bsAlert.close();
        });
        
        const alertDiv = document.createElement('div');
        alertDiv.className = `alert alert-${type} alert-dismissible fade show`;
        alertDiv.innerHTML = `
            <i class="fas fa-${type === 'success' ? 'check-circle' : 'exclamation-circle'} me-2"></i>
            ${message}
            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
        `;
        
        // Add to page
        const container = document.querySelector('.professional-container') || document.querySelector('.edit-container') || document.body;
        container.insertBefore(alertDiv, container.firstChild);
        
        // Auto remove after 5 seconds
        setTimeout(() => {
            if (alertDiv.parentNode) {
                const bsAlert = new bootstrap.Alert(alertDiv);
                bsAlert.close();
            }
        }, 5000);
    }

    // Alternative: Event delegation approach (more reliable)
    document.addEventListener('DOMContentLoaded', function() {
        // Event delegation for delete buttons
        document.addEventListener('click', function(e) {
            if (e.target.classList.contains('btn-delete') || e.target.closest('.btn-delete')) {
                const deleteBtn = e.target.classList.contains('btn-delete') ? e.target : e.target.closest('.btn-delete');
                const qualificationId = deleteBtn.getAttribute('onclick')?.match(/\d+/)?.[0];
                
                if (qualificationId) {
                    e.preventDefault();
                    e.stopPropagation();
                    deleteProfessionalQualification(qualificationId, deleteBtn);
                }
            }
        });
    });
</script>
</body>
</html>