<?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'];
$error = '';
$success = '';

// Initialize variables
$db_employee_id = null;
$boards = [];
$universities = [];
$is_edit = false;
$training_data = null;
$training_id = 0;

// Check if editing existing training
if (isset($_GET['training_id'])) {
    $training_id = intval($_GET['training_id']);
    $is_edit = ($training_id > 0);
}

// Get employee_id from database
$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'];
        
        // If editing, fetch training data
        if ($is_edit) {
            $training_sql = "SELECT * FROM trainings WHERE training_id = ? AND employee_id = ?";
            $stmt_training = $conn->prepare($training_sql);
            $stmt_training->bind_param("ii", $training_id, $db_employee_id);
            $stmt_training->execute();
            $training_result = $stmt_training->get_result();
            
            if ($training_result->num_rows > 0) {
                $training_data = $training_result->fetch_assoc();
            } else {
                $error = "Training not found or you don't have permission to edit it.";
                $is_edit = false;
            }
            $stmt_training->close();
        }
        
        // Fetch boards and universities for dropdown
        $boards_sql = "SELECT b_id, b_name FROM boards ORDER BY b_name";
        $boards_result = $conn->query($boards_sql);
        if ($boards_result) {
            while($row = $boards_result->fetch_assoc()) {
                $boards[] = $row;
            }
        }
        
        $unis_sql = "SELECT uni_id, uni_name FROM universities ORDER BY uni_name";
        $unis_result = $conn->query($unis_sql);
        if ($unis_result) {
            while($row = $unis_result->fetch_assoc()) {
                $universities[] = $row;
            }
        }
        
        $stmt_emp->close();
    } else {
        $error = "Employee profile not found in main database.";
    }
} else {
    $error = "Registration record not found.";
}

$stmt_reg->close();

// Handle form submission
if ($_SERVER['REQUEST_METHOD'] == 'POST' && $db_employee_id) {
    $training_name = trim($_POST['training_name'] ?? '');
    $institution = trim($_POST['institution'] ?? '');
    $custom_institution = trim($_POST['custom_institution'] ?? '');
    $training_date = $_POST['training_date'] ?? '';
    $place = trim($_POST['place'] ?? '');
    $duration_days = intval($_POST['duration_days'] ?? 0);
    
    // Use custom institution if provided, otherwise use selected institution
    $final_institution = !empty($custom_institution) ? $custom_institution : $institution;
    
    // Validation
    if (empty($training_name)) {
        $error = "Training name is required.";
    } elseif (empty($final_institution)) {
        $error = "Institution is required.";
    } elseif (empty($training_date)) {
        $error = "Training date is required.";
    } elseif (empty($place)) {
        $error = "Place/venue is required.";
    } elseif ($duration_days <= 0) {
        $error = "Duration must be at least 1 day.";
    } elseif ($duration_days > 365) {
        $error = "Duration cannot exceed 365 days.";
    } else {
        if ($is_edit && $training_data) {
            // Update existing training
            $update_sql = "UPDATE trainings SET 
                          training_name = ?,
                          institution = ?,
                          training_date = ?,
                          place = ?,
                          duration_days = ?
                          WHERE training_id = ? AND employee_id = ?";
            
            $stmt = $conn->prepare($update_sql);
            $stmt->bind_param("ssssiii", 
                $training_name,
                $final_institution,
                $training_date,
                $place,
                $duration_days,
                $training_id,
                $db_employee_id
            );
        } else {
            // Insert new training
            $insert_sql = "INSERT INTO trainings 
                          (employee_id, training_name, institution, training_date, place, duration_days)
                          VALUES (?, ?, ?, ?, ?, ?)";
            
            $stmt = $conn->prepare($insert_sql);
            $stmt->bind_param("issssi",
                $db_employee_id,
                $training_name,
                $final_institution,
                $training_date,
                $place,
                $duration_days
            );
        }
        
        if ($stmt->execute()) {
            $success = $is_edit ? 
                "Training record updated successfully!" : 
                "Training record added successfully!";
            
            // Redirect after success
            $_SESSION['success_message'] = $success;
            header("Location: training_view.php");
            exit();
        } else {
            $error = "Failed to save training: " . $conn->error;
        }
        $stmt->close();
    }
}

$conn->close();
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title><?php echo $is_edit ? 'Edit' : 'Add'; ?> Training</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;
    }
    
    body {
        font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
        background-color: #f8f9fa;
        padding: 20px;
    }
    
    .edit-container {
        max-width: 800px;
        margin: 0 auto;
    }
    
    .edit-card {
        border: none;
        border-radius: 15px;
        box-shadow: 0 5px 25px rgba(0,0,0,0.1);
        background: white;
        overflow: hidden;
    }
    
    .edit-header {
        background: linear-gradient(135deg, #ffc107 0%, #fd7e14 100%);
        color: white;
        padding: 25px 30px;
    }
    
    .form-card {
        background: #fffbf0;
        border-radius: 10px;
        padding: 25px;
        margin-bottom: 20px;
        border: 1px solid #ffe8a1;
    }
    
    .form-section-title {
        font-weight: 600;
        color: #e67700;
        margin-bottom: 20px;
        font-size: 1.1rem;
        display: flex;
        align-items: center;
        gap: 10px;
        padding-bottom: 10px;
        border-bottom: 2px solid #ffd8a8;
    }
    
    .btn-submit {
        background: var(--primary-warning);
        color: #000;
        border: none;
        padding: 12px 30px;
        border-radius: 5px;
        font-weight: 500;
        transition: all 0.3s ease;
        font-size: 1rem;
    }
    
    .btn-submit:hover {
        background: var(--secondary-warning);
        color: #000;
        transform: translateY(-2px);
        box-shadow: 0 5px 15px rgba(255, 193, 7, 0.3);
    }
    
    .btn-cancel {
        background: #6c757d;
        color: white;
        border: none;
        padding: 12px 30px;
        border-radius: 5px;
        font-weight: 500;
        transition: all 0.3s ease;
        font-size: 1rem;
    }
    
    .btn-cancel:hover {
        background: #5a6268;
        color: white;
        transform: translateY(-2px);
    }
    
    .required-label::after {
        content: " *";
        color: #dc3545;
    }
    
    .form-label {
        font-weight: 500;
        color: #495057;
    }
    
    .form-control:focus, .form-select:focus {
        border-color: #ffc107;
        box-shadow: 0 0 0 0.25rem rgba(255, 193, 7, 0.25);
    }
    
    .institution-section {
        background: #f8f9fa;
        border-radius: 8px;
        padding: 15px;
        margin-bottom: 20px;
        border: 1px solid #dee2e6;
    }
    
    .duration-info {
        background: #e7f5ff;
        border: 1px solid #a5d8ff;
        border-radius: 5px;
        padding: 10px 15px;
        margin-top: 10px;
        font-weight: 500;
    }
</style>
</head>
<body>
<div class="edit-container">
    <div class="edit-card">
        <div class="edit-header">
            <h2 class="mb-0">
                <i class="fas fa-chalkboard-teacher me-2"></i>
                <?php echo $is_edit ? 'Edit Training' : 'Add Training'; ?>
            </h2>
            <p class="mb-0 mt-2">
                <?php echo $is_edit ? 
                    'Update your training details' : 
                    'Add new professional development training record'; ?>
            </p>
        </div>
        
        <div class="p-4">
            <?php if(!empty($error)): ?>
                <div class="alert alert-danger alert-dismissible fade show" role="alert">
                    <i class="fas fa-exclamation-circle me-2"></i><?php echo htmlspecialchars($error); ?>
                    <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                </div>
            <?php endif; ?>
            
            <?php if($db_employee_id): ?>
                <form method="POST" action="" id="trainingForm">
                    <div class="form-card">
                        <h5 class="form-section-title">
                            <i class="fas fa-info-circle"></i>Training Details
                        </h5>
                        
                        <div class="row mb-3">
                            <div class="col-md-12">
                                <label for="training_name" class="form-label required-label">Training Name</label>
                                <input type="text" class="form-control" id="training_name" name="training_name" 
                                       value="<?php echo htmlspecialchars($training_data['training_name'] ?? ''); ?>" 
                                       required placeholder="e.g., Leadership Development Program, Technical Skills Training">
                                <div class="form-text">Enter the full name of the training program</div>
                            </div>
                        </div>
                        
                        <!-- INSTITUTION SELECTION -->
                        <div class="institution-section">
                            <label class="form-label required-label mb-3">Institution/Organization</label>
                            
                            <!-- Boards Dropdown -->
                            <div class="mb-3">
                                <label class="form-label">Select from Boards:</label>
                                <select class="form-select" id="board_select" onchange="updateInstitution()">
                                    <option value="">Select Board</option>
                                    <?php foreach($boards as $board): 
                                        $selected = (isset($training_data['institution']) && $training_data['institution'] == 'Board' . $board['b_id']) ? 'selected' : '';
                                    ?>
                                        <option value="Board<?php echo $board['b_id']; ?>" <?php echo $selected; ?>>
                                            <?php echo htmlspecialchars($board['b_name']); ?>
                                        </option>
                                    <?php endforeach; ?>
                                </select>
                            </div>
                            
                            <!-- Universities Dropdown -->
                            <div class="mb-3">
                                <label class="form-label">Select from Universities:</label>
                                <select class="form-select" id="uni_select" onchange="updateInstitution()">
                                    <option value="">Select University</option>
                                    <?php foreach($universities as $uni): 
                                        $selected = (isset($training_data['institution']) && $training_data['institution'] == 'Uni' . $uni['uni_id']) ? 'selected' : '';
                                    ?>
                                        <option value="Uni<?php echo $uni['uni_id']; ?>" <?php echo $selected; ?>>
                                            <?php echo htmlspecialchars($uni['uni_name']); ?>
                                        </option>
                                    <?php endforeach; ?>
                                </select>
                            </div>
                            
                            <!-- Custom Institution -->
                            <div class="mb-3">
                                <label class="form-label">Or enter custom institution/organization:</label>
                                <input type="text" class="form-control" id="custom_institution" name="custom_institution" 
                                       value="<?php echo (isset($training_data['institution']) && 
                                               !str_starts_with($training_data['institution'], 'Board') && 
                                               !str_starts_with($training_data['institution'], 'Uni')) ? 
                                               htmlspecialchars($training_data['institution']) : ''; ?>" 
                                       placeholder="e.g., Training Institute, Professional Organization">
                            </div>
                            
                            <!-- Hidden field for the actual institution value -->
                            <input type="hidden" id="institution" name="institution" value="<?php echo htmlspecialchars($training_data['institution'] ?? ''); ?>">
                        </div>
                        
                        <div class="row mb-3">
                            <div class="col-md-6">
                                <label for="training_date" class="form-label required-label">Training Date</label>
                                <input type="date" class="form-control" id="training_date" name="training_date" 
                                       value="<?php echo !empty($training_data['training_date']) && $training_data['training_date'] != '0000-00-00' ? 
                                               date('Y-m-d', strtotime($training_data['training_date'])) : ''; ?>" 
                                       required>
                                <div class="form-text">Select the date when training was conducted</div>
                            </div>
                            <div class="col-md-6">
                                <label for="duration_days" class="form-label required-label">Duration (Days)</label>
                                <input type="number" class="form-control" id="duration_days" name="duration_days" 
                                       value="<?php echo $training_data['duration_days'] ?? '1'; ?>" 
                                       required min="1" max="365" step="1">
                                <div class="form-text">Enter duration in days (1-365)</div>
                            </div>
                        </div>
                        
                        <div class="row mb-3">
                            <div class="col-md-12">
                                <label for="place" class="form-label required-label">Place/Venue</label>
                                <input type="text" class="form-control" id="place" name="place" 
                                       value="<?php echo htmlspecialchars($training_data['place'] ?? ''); ?>" 
                                       required placeholder="e.g., Islamabad, Lahore, Karachi, or specific venue name">
                                <div class="form-text">Enter the city or specific venue where training was conducted</div>
                            </div>
                        </div>
                    </div>
                    
                    <div class="d-flex justify-content-between align-items-center mt-4">
                        <a href="training_view.php" class="btn btn-cancel">
                            <i class="fas fa-times me-2"></i>Cancel
                        </a>
                        <button type="submit" class="btn btn-submit">
                            <i class="fas fa-save me-2"></i>
                            <?php echo $is_edit ? 'Update Training' : 'Add Training'; ?>
                        </button>
                    </div>
                </form>
            <?php elseif(!empty($error)): ?>
                <div class="alert alert-warning">
                    <h4><i class="fas fa-exclamation-triangle me-2"></i>Profile Not Found</h4>
                    <p><?php echo htmlspecialchars($error); ?></p>
                    <p>Please contact the administrator to complete your profile setup.</p>
                    <div class="mt-3">
                        <a href="employee_profile_view.php" class="btn btn-primary">
                            <i class="fas fa-arrow-left me-2"></i>Back to Profile
                        </a>
                    </div>
                </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>
    // Update institution value based on selection
    function updateInstitution() {
        const boardSelect = document.getElementById('board_select');
        const uniSelect = document.getElementById('uni_select');
        const customInstitution = document.getElementById('custom_institution');
        const institutionField = document.getElementById('institution');
        
        // Clear custom institution if board or uni is selected
        if (boardSelect.value || uniSelect.value) {
            customInstitution.value = '';
        }
        
        // Set institution value
        if (boardSelect.value) {
            institutionField.value = boardSelect.value;
        } else if (uniSelect.value) {
            institutionField.value = uniSelect.value;
        } else if (customInstitution.value) {
            institutionField.value = customInstitution.value;
        } else {
            institutionField.value = '';
        }
    }
    
    // Initialize institution selection
    function initializeInstitution() {
        const currentInstitution = document.getElementById('institution').value;
        
        if (currentInstitution.startsWith('Board')) {
            document.getElementById('board_select').value = currentInstitution;
        } else if (currentInstitution.startsWith('Uni')) {
            document.getElementById('uni_select').value = currentInstitution;
        } else if (currentInstitution) {
            document.getElementById('custom_institution').value = currentInstitution;
        }
    }
    
    // Form validation
    document.getElementById('trainingForm').addEventListener('submit', function(e) {
        const institution = document.getElementById('institution').value;
        const durationDays = parseInt(document.getElementById('duration_days').value);
        const trainingDate = document.getElementById('training_date').value;
        
        if (!institution) {
            e.preventDefault();
            alert('Please select or enter an institution.');
            return false;
        }
        
        if (durationDays < 1 || durationDays > 365) {
            e.preventDefault();
            alert('Duration must be between 1 and 365 days.');
            document.getElementById('duration_days').focus();
            return false;
        }
        
        if (!trainingDate) {
            e.preventDefault();
            alert('Please select a training date.');
            return false;
        }
        
        // Check if training date is in future
        const selectedDate = new Date(trainingDate);
        const today = new Date();
        today.setHours(0, 0, 0, 0);
        
        if (selectedDate > today) {
            const confirmFuture = confirm('Training date is in the future. Is this correct?');
            if (!confirmFuture) {
                e.preventDefault();
                document.getElementById('training_date').focus();
                return false;
            }
        }
    });
    
    // Initialize on page load
    document.addEventListener('DOMContentLoaded', function() {
        initializeInstitution();
    });
</script>
</body>
</html>