<?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 trainings with proper joins for institution
$training_sql = "SELECT t.*, 
                 CASE 
                     WHEN t.institution LIKE 'Board%' THEN b.b_name 
                     WHEN t.institution LIKE 'Uni%' THEN u.uni_name 
                     ELSE t.institution 
                 END as institution_name
                 FROM trainings t
                 LEFT JOIN boards b ON t.institution = CONCAT('Board', b.b_id)
                 LEFT JOIN universities u ON t.institution = CONCAT('Uni', u.uni_id)
                 WHERE t.employee_id = ? 
                 ORDER BY 
                 CASE 
                     WHEN t.training_date != '0000-00-00' THEN t.training_date 
                     ELSE '9999-12-31'
                 END DESC, 
                 t.training_id DESC";

$stmt_training = $conn->prepare($training_sql);
$stmt_training->bind_param("i", $employee_id);
$stmt_training->execute();
$training_result = $stmt_training->get_result();

$trainings = [];
while($row = $training_result->fetch_assoc()) {
    $trainings[] = $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));
}

// Display trainings
if (count($trainings) > 0): 
    $total_trainings = count($trainings);
    // Sort by training date to get the latest
    usort($trainings, function($a, $b) {
        $dateA = ($a['training_date'] == '0000-00-00') ? '1970-01-01' : $a['training_date'];
        $dateB = ($b['training_date'] == '0000-00-00') ? '1970-01-01' : $b['training_date'];
        return strtotime($dateB) - strtotime($dateA);
    });
    $latest_training = $trainings[0];
    
    // Calculate total training days
    $total_days = array_sum(array_column($trainings, 'duration_days'));
?>
    <!-- SUMMARY SECTION -->
    <div class="summary-card mb-4">
        <div class="row">
            <div class="col-md-3">
                <div class="summary-value"><?php echo $total_trainings; ?></div>
                <div class="summary-label">Total Trainings</div>
            </div>
            <div class="col-md-9">
                <h5 class="summary-title">
                    <i class="fas fa-chalkboard-teacher"></i>Training Summary
                </h5>
                <p class="mb-0">Your professional development trainings are listed below.</p>
                <?php if(isset($latest_training) && !empty($latest_training['training_date']) && $latest_training['training_date'] != '0000-00-00'): ?>
                <p class="mb-0 mt-1">
                    <strong>Latest:</strong> <?php echo htmlspecialchars($latest_training['training_name']); ?> 
                    (<?php echo date('Y', strtotime($latest_training['training_date'])); ?>)
                </p>
                <?php endif; ?>
                <?php if($total_days > 0): ?>
                <p class="mb-0 mt-1">
                    <strong>Total Training Days:</strong> <?php echo $total_days; ?> days
                </p>
                <?php endif; ?>
            </div>
        </div>
    </div>
    
    <!-- TRAININGS LIST -->
    <?php foreach($trainings as $training): 
        // Get institution display name
        $institution_display = $training['institution_name'] ?? $training['institution'] ?? 'N/A';
        // Format training date
        $training_date_display = formatDateDisplay($training['training_date']);
        $training_year_only = ($training['training_date'] != '0000-00-00') ? date('Y', strtotime($training['training_date'])) : 'N/A';
    ?>
        <div class="training-card">
            <div class="d-flex justify-content-between align-items-start mb-3">
                <div>
                    <span class="training-badge bg-warning">
                        <i class="fas fa-chalkboard-teacher me-1"></i>
                        Training
                    </span>
                    <h5 class="mb-1"><?php echo htmlspecialchars($training['training_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 $training_year_only; ?>
                    </p>
                </div>
                <div>
                    <span class="duration-badge">
                        <i class="fas fa-clock me-1"></i>
                        <?php echo $training['duration_days']; ?> days
                    </span>
                </div>
            </div>
            
            <div class="row">
                <div class="col-md-6">
                    <div class="info-row">
                        <span class="info-label">Training Name:</span>
                        <span class="info-value"><?php echo htmlspecialchars($training['training_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($training['training_date']) && $training['training_date'] != '0000-00-00'): ?>
                    <div class="info-row">
                        <span class="info-label">Training Date:</span>
                        <span class="info-value"><?php echo $training_date_display; ?></span>
                    </div>
                    <?php endif; ?>
                </div>
                <div class="col-md-6">
                    <div class="info-row">
                        <span class="info-label">Place/Venue:</span>
                        <span class="info-value"><?php echo htmlspecialchars($training['place']); ?></span>
                    </div>
                    <div class="info-row">
                        <span class="info-label">Duration:</span>
                        <span class="info-value"><?php echo $training['duration_days']; ?> days</span>
                    </div>
                </div>
            </div>
            
            <div class="d-flex justify-content-end gap-2 mt-3">
                <a href="training_edit.php?training_id=<?php echo $training['training_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="deleteTraining(<?php echo $training['training_id']; ?>, this)">
                    <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="training_view.php" class="btn btn-warning" target="_blank">
            <i class="fas fa-external-link-alt me-2"></i>View Full Trainings Page
        </a>
    </div>
<?php else: ?>
    <!-- EMPTY STATE -->
    <div class="empty-state">
        <i class="fas fa-chalkboard-teacher"></i>
        <h4>No Trainings Found</h4>
        <p class="mb-4">You haven't added any training records yet.</p>
        <a href="training_edit.php" class="btn btn-add-training">
            <i class="fas fa-plus me-2"></i>Add Your First Training
        </a>
    </div>
<?php endif; ?>

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