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

// Check if employee is logged in
if (!isset($_SESSION['employee_id']) || !isset($_SESSION['cnic'])) {
    header('HTTP/1.1 401 Unauthorized');
    echo 'Unauthorized access';
    exit();
}

include 'connect.php';

// Get employee ID from query parameter
$employee_id = isset($_GET['employee_id']) ? intval($_GET['employee_id']) : 0;

if ($employee_id <= 0) {
    echo '<div class="alert alert-warning">Invalid employee ID</div>';
    exit();
}

// Fetch professional qualifications with proper date formatting and institution names
$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", $employee_id);
$stmt_professional->execute();
$professional_result = $stmt_professional->get_result();

$qualifications = [];
while($row = $professional_result->fetch_assoc()) {
    $qualifications[] = $row;
}

// 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)';
    }
}

// Display qualifications
if (count($qualifications) > 0): 
    $total_qualifications = count($qualifications);
    // Sort by passing year to get the latest
    usort($qualifications, function($a, $b) {
        $dateA = ($a['passing_year'] == '0000-00-00') ? '1970-01-01' : $a['passing_year'];
        $dateB = ($b['passing_year'] == '0000-00-00') ? '1970-01-01' : $b['passing_year'];
        return strtotime($dateB) - strtotime($dateA);
    });
    $latest_qualification = $qualifications[0];
?>
    <!-- SUMMARY SECTION -->
    <div class="summary-card mb-4">
        <div class="row">
            <div class="col-md-3">
                <div class="summary-value"><?php echo $total_qualifications; ?></div>
                <div class="summary-label">Professional Qualifications</div>
            </div>
            <div class="col-md-9">
                <h5 class="summary-title">
                    <i class="fas fa-certificate"></i>Professional Profile Summary
                </h5>
                <p class="mb-0">Your professional certifications and qualifications are listed below.</p>
                <?php if(isset($latest_qualification) && !empty($latest_qualification['passing_year']) && $latest_qualification['passing_year'] != '0000-00-00'): ?>
                <p class="mb-0 mt-1">
                    <strong>Latest:</strong> <?php echo htmlspecialchars($latest_qualification['qualification_name']); ?> 
                    (<?php echo date('Y', strtotime($latest_qualification['passing_year'])); ?>)
                </p>
                <?php endif; ?>
            </div>
        </div>
    </div>
    
    <!-- QUALIFICATIONS LIST -->
    <?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([' ', '/', '+'], ['-', '', ''], $division_grade));
        // Get institution display name
        $institution_display = $qual['institution_name'] ?? $qual['institution'] ?? 'N/A';
        // Format passing year
        $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
                    </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-sm btn-primary">
                    <i class="fas fa-edit me-1"></i>Edit
                </a>
                <button type="button" class="btn btn-sm btn-danger" onclick="deleteProfessionalQualification(<?php echo $qual['qualification_id']; ?>)">
                    <i class="fas fa-trash me-1"></i>Delete
                </button>
            </div>
        </div>
    <?php endforeach; ?>
    
    <!-- VIEW FULL PAGE LINK -->
    <div class="text-center mt-4">
        <a href="professional_qualification_view.php" class="btn btn-info" target="_blank">
            <i class="fas fa-external-link-alt me-2"></i>View Full Professional Qualifications Page
        </a>
    </div>
<?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.</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; ?>

<?php
$stmt_professional->close();
$conn->close();
?>