<?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 trainings with proper joins
        $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", $db_employee_id);
        $stmt_training->execute();
        $training_result = $stmt_training->get_result();
        
        $trainings = [];
        while($row = $training_result->fetch_assoc()) {
            $trainings[] = $row;
        }
        
        // Calculate totals and statistics
        $total_trainings = count($trainings);
        $total_days = array_sum(array_column($trainings, 'duration_days'));
        
        // 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));
        }
    }
}

// Close statements
if (isset($stmt_reg)) $stmt_reg->close();
if (isset($stmt_emp)) $stmt_emp->close();
if (isset($stmt_training)) $stmt_training->close();
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Trainings</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-warning: #ffc107;
        --secondary-warning: #ffca2c;
        --primary-blue: #0d6efd;
    }
    
    body {
        font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
        background-color: #f8f9fa;
        padding: 20px;
    }
    
    .training-container {
        max-width: 1200px;
        margin: 0 auto;
    }
    
    .training-card-container {
        border: none;
        border-radius: 15px;
        box-shadow: 0 5px 25px rgba(0,0,0,0.1);
        background: white;
        overflow: hidden;
    }
    
    .training-header {
        background: linear-gradient(135deg, #ffc107 0%, #fd7e14 100%);
        color: white;
        padding: 25px 30px;
    }
    
    .training-card {
        border: 1px solid #dee2e6;
        border-radius: 10px;
        padding: 20px;
        margin-bottom: 20px;
        transition: all 0.3s ease;
        background: #fffbf0;
        border-left: 4px solid #ffc107;
    }
    
    .training-card:hover {
        box-shadow: 0 5px 15px rgba(255, 193, 7, 0.2);
        transform: translateY(-2px);
    }
    
    .training-badge {
        display: inline-block;
        padding: 5px 12px;
        border-radius: 20px;
        font-size: 0.85rem;
        font-weight: 500;
        color: #000;
        margin-bottom: 10px;
    }
    
    .bg-warning {
        background: #ffc107 !important;
    }
    
    .duration-badge {
        display: inline-block;
        padding: 5px 12px;
        border-radius: 20px;
        font-size: 0.85rem;
        font-weight: 500;
        background: #0dcaf0;
        color: white;
    }
    
    .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-training {
        background: var(--primary-warning);
        color: #000;
        border: none;
        padding: 10px 20px;
        border-radius: 5px;
        font-weight: 500;
        transition: all 0.3s ease;
    }
    
    .btn-add-training:hover {
        background: var(--secondary-warning);
        color: #000;
        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, #fff9db 0%, #fff3bf 100%);
        border-radius: 10px;
        padding: 20px;
        margin-bottom: 25px;
        border-left: 4px solid var(--primary-warning);
        border: 1px solid #ffe066;
    }
    
    .summary-title {
        font-weight: 600;
        color: #e67700;
        margin-bottom: 15px;
        font-size: 1.1rem;
        display: flex;
        align-items: center;
        gap: 10px;
    }
    
    .summary-value {
        font-size: 2rem;
        font-weight: 700;
        color: #e67700;
        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: #e67700;
    }
    
    .stats-label {
        color: #6c757d;
        font-size: 0.85rem;
        margin-top: 5px;
    }
</style>
</head>
<body>
<div class="training-container">
    <div class="training-card-container">
        <div class="training-header">
            <h2 class="mb-0">
                <i class="fas fa-chalkboard-teacher me-2"></i>Trainings
            </h2>
            <p class="mb-0 mt-2">View and manage your professional development trainings</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_trainings; ?></div>
                                <div class="stats-label">Total Trainings</div>
                            </div>
                        </div>
                        <div class="col-md-8">
                            <h5 class="summary-title">
                                <i class="fas fa-chart-line"></i>Training & Development Overview
                            </h5>
                            <p class="mb-0">Track your professional development through various training programs. Continuous learning enhances your skills and career growth.</p>
                            <?php if($total_days > 0): ?>
                            <p class="mb-0 mt-2">
                                <i class="fas fa-clock text-warning me-1"></i>
                                <strong>Total Training Duration:</strong> <?php echo $total_days; ?> days
                            </p>
                            <?php endif; ?>
                        </div>
                    </div>
                </div>
                
                <!-- ACTION BUTTONS -->
                <div class="d-flex justify-content-between align-items-center mb-4">
                    <div>
                        <h5 class="mb-0" style="color: #e67700;">
                            <i class="fas fa-chalkboard-teacher me-2"></i>Training Records
                        </h5>
                        <p class="text-muted mb-0">All your professional development trainings</p>
                    </div>
                    <div class="action-buttons">
                        <a href="training_edit.php" class="btn btn-add-training">
                            <i class="fas fa-plus me-2"></i>Add Training
                        </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>
                
                <!-- TRAININGS LIST -->
                <?php if(isset($trainings) && count($trainings) > 0): ?>
                    <?php foreach($trainings as $training): 
                        $institution_display = $training['institution_name'] ?? $training['institution'] ?? 'N/A';
                        $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>
                                        Professional 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-edit">
                                    <i class="fas fa-edit me-1"></i>Edit
                                </a>
                                <button type="button" class="btn btn-delete" onclick="deleteTraining(<?php echo $training['training_id']; ?>, this)">
                                    <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-chalkboard-teacher"></i>
                        <h4>No Trainings Found</h4>
                        <p class="mb-4">You haven't added any training records yet. Professional trainings enhance your skills and career development.</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; ?>
                
                <!-- 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>
    // Simple Delete Function for Trainings
    function deleteTraining(trainingId, buttonElement) {
        if (confirm('Are you sure you want to delete this training record? This action cannot be undone.')) {
            // Create a form and submit it
            const form = document.createElement('form');
            form.method = 'POST';
            form.action = 'delete_training.php';
            
            const input = document.createElement('input');
            input.type = 'hidden';
            input.name = 'training_id';
            input.value = trainingId;
            
            form.appendChild(input);
            document.body.appendChild(form);
            form.submit();
        }
    }
    
    // Auto-hide alerts after 5 seconds
    setTimeout(function() {
        const alerts = document.querySelectorAll('.alert');
        alerts.forEach(alert => {
            const bsAlert = new bootstrap.Alert(alert);
            bsAlert.close();
        });
    }, 5000);
</script>
</body>
</html>