<?php
require_once '../config/config.php';
requireRole('employee');

$pageTitle = 'Activity Evaluation - Employee - PSAU GAD';
$db = getDB();
$userId = getCurrentUserId();

// Get activity_id from URL
$activityId = isset($_GET['activity_id']) ? (int)$_GET['activity_id'] : 0;

if (!$activityId) {
    header('Location: my-activities.php');
    exit;
}

// Get evaluation form for this activity
$stmt = $db->prepare("
    SELECT ef.*, a.title as activity_title, a.activity_date
    FROM evaluation_forms ef
    JOIN activities a ON ef.activity_id = a.activity_id
    WHERE ef.activity_id = ? AND ef.is_active = 1
");
$stmt->execute([$activityId]);
$form = $stmt->fetch();

if (!$form) {
    $_SESSION['error'] = 'No evaluation form found for this activity.';
    header('Location: my-activities.php');
    exit;
}

// Check if user attended this activity
$stmt = $db->prepare("
    SELECT aa.* 
    FROM activity_attendance aa
    JOIN activity_registrations ar ON aa.registration_id = ar.registration_id
    WHERE ar.activity_id = ? AND ar.user_id = ? AND aa.status IN ('present', 'late')
");
$stmt->execute([$activityId, $userId]);
$attendance = $stmt->fetch();

if (!$attendance) {
    $_SESSION['error'] = 'You must attend the activity before submitting an evaluation.';
    header('Location: my-activities.php');
    exit;
}

// Check if already submitted
$stmt = $db->prepare("SELECT * FROM evaluation_responses WHERE form_id = ? AND user_id = ?");
$stmt->execute([$form['form_id'], $userId]);
$existingResponse = $stmt->fetch();

if ($existingResponse) {
    $_SESSION['error'] = 'You have already submitted an evaluation for this activity.';
    header('Location: my-activities.php');
    exit;
}

// Handle form submission
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    try {
        $db->beginTransaction();
        
        // Create evaluation response
        $stmt = $db->prepare("
            INSERT INTO evaluation_responses (form_id, user_id, submitted_at)
            VALUES (?, ?, NOW())
        ");
        $stmt->execute([$form['form_id'], $userId]);
        $responseId = $db->lastInsertId();
        
        // Get all questions
        $stmt = $db->prepare("SELECT * FROM evaluation_questions WHERE form_id = ? ORDER BY order_num");
        $stmt->execute([$form['form_id']]);
        $questions = $stmt->fetchAll();
        
        // Save answers
        foreach ($questions as $question) {
            $questionId = $question['question_id'];
            $answer = isset($_POST['answer_' . $questionId]) ? trim($_POST['answer_' . $questionId]) : '';
            
            if ($question['is_required'] && empty($answer)) {
                throw new Exception('Please answer all required questions.');
            }
            
            if (!empty($answer)) {
                $stmt = $db->prepare("
                    INSERT INTO evaluation_answers (response_id, question_id, answer_text)
                    VALUES (?, ?, ?)
                ");
                $stmt->execute([$responseId, $questionId, $answer]);
            }
        }
        
        $db->commit();
        $_SESSION['success'] = 'Thank you! Your evaluation has been submitted successfully.';
        header('Location: my-activities.php');
        exit;
        
    } catch (Exception $e) {
        $db->rollBack();
        $_SESSION['error'] = 'Error submitting evaluation: ' . $e->getMessage();
    }
}

// Get questions
$stmt = $db->prepare("SELECT * FROM evaluation_questions WHERE form_id = ? ORDER BY order_num");
$stmt->execute([$form['form_id']]);
$questions = $stmt->fetchAll();

include '../includes/header.php';
include '../includes/navbar.php';
?>

<div class="min-h-screen bg-gradient-to-br from-green-50 to-blue-50 py-8">
    <div class="container mx-auto px-4 max-w-4xl">
        <!-- Header -->
        <div class="bg-white rounded-xl shadow-lg p-6 mb-6">
            <div class="flex items-center mb-4">
                <a href="my-activities.php" class="text-employee hover:text-green-700 mr-4">
                    <i class="fas fa-arrow-left text-xl"></i>
                </a>
                <div class="flex-1">
                    <h1 class="text-3xl font-bold text-gray-900 mb-2">
                        <i class="fas fa-clipboard-check text-employee mr-2"></i>Activity Evaluation
                    </h1>
                    <p class="text-gray-600">
                        <i class="fas fa-calendar mr-2"></i><?php echo htmlspecialchars($form['activity_title']); ?>
                        <span class="mx-2">•</span>
                        <?php echo formatDate($form['activity_date']); ?>
                    </p>
                </div>
            </div>
            
            <?php if ($form['instructions']): ?>
                <div class="bg-blue-50 border-l-4 border-blue-500 p-4 rounded">
                    <p class="text-gray-700"><?php echo nl2br(htmlspecialchars($form['instructions'])); ?></p>
                </div>
            <?php endif; ?>
        </div>

        <!-- Error Messages -->
        <?php if (isset($_SESSION['error'])): ?>
            <div class="bg-red-100 border-l-4 border-red-500 text-red-700 p-4 mb-6 rounded">
                <i class="fas fa-exclamation-circle mr-2"></i><?php echo $_SESSION['error']; unset($_SESSION['error']); ?>
            </div>
        <?php endif; ?>

        <!-- Evaluation Form -->
        <form method="POST" id="evaluationForm" class="bg-white rounded-xl shadow-lg p-8">
            <div class="space-y-6">
                <?php foreach ($questions as $index => $question): ?>
                    <div class="border-b border-gray-200 pb-6 last:border-0">
                        <label class="block mb-3">
                            <span class="text-gray-900 font-semibold text-lg">
                                <?php echo $index + 1; ?>. <?php echo htmlspecialchars($question['question_text']); ?>
                                <?php if ($question['is_required']): ?>
                                    <span class="text-red-500">*</span>
                                <?php endif; ?>
                            </span>
                        </label>
                        
                        <?php if ($question['question_type'] === 'rating'): ?>
                            <!-- Star Rating -->
                            <div class="flex items-center space-x-2">
                                <?php for ($i = 1; $i <= 5; $i++): ?>
                                    <label class="cursor-pointer">
                                        <input type="radio" name="answer_<?php echo $question['question_id']; ?>" 
                                               value="<?php echo $i; ?>" <?php echo $question['is_required'] ? 'required' : ''; ?>
                                               class="hidden star-radio">
                                        <i class="fas fa-star text-3xl text-gray-300 hover:text-yellow-400 transition star-icon"></i>
                                    </label>
                                <?php endfor; ?>
                                <span class="ml-4 text-gray-600 font-semibold rating-text"></span>
                            </div>
                            
                        <?php elseif ($question['question_type'] === 'yes_no'): ?>
                            <!-- Yes/No -->
                            <div class="flex space-x-4">
                                <label class="flex items-center cursor-pointer">
                                    <input type="radio" name="answer_<?php echo $question['question_id']; ?>" 
                                           value="Yes" <?php echo $question['is_required'] ? 'required' : ''; ?>
                                           class="w-4 h-4 text-employee border-gray-300 focus:ring-employee">
                                    <span class="ml-2 text-gray-700">Yes</span>
                                </label>
                                <label class="flex items-center cursor-pointer">
                                    <input type="radio" name="answer_<?php echo $question['question_id']; ?>" 
                                           value="No" <?php echo $question['is_required'] ? 'required' : ''; ?>
                                           class="w-4 h-4 text-employee border-gray-300 focus:ring-employee">
                                    <span class="ml-2 text-gray-700">No</span>
                                </label>
                            </div>
                            
                        <?php elseif ($question['question_type'] === 'text'): ?>
                            <!-- Text Response -->
                            <textarea name="answer_<?php echo $question['question_id']; ?>" 
                                      rows="4" <?php echo $question['is_required'] ? 'required' : ''; ?>
                                      placeholder="Enter your response here..."
                                      class="w-full px-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-employee focus:border-transparent"></textarea>
                        <?php endif; ?>
                    </div>
                <?php endforeach; ?>
            </div>
            
            <div class="flex justify-end space-x-4 mt-8 pt-6 border-t border-gray-200">
                <a href="my-activities.php" 
                   class="px-6 py-3 border border-gray-300 rounded-lg hover:bg-gray-50 transition font-semibold">
                    Cancel
                </a>
                <button type="submit" 
                        class="bg-employee text-white px-8 py-3 rounded-lg hover:bg-green-700 transition font-semibold">
                    <i class="fas fa-paper-plane mr-2"></i>Submit Evaluation
                </button>
            </div>
        </form>
    </div>
</div>

<script>
// Star rating functionality
document.querySelectorAll('.star-radio').forEach(radio => {
    radio.addEventListener('change', function() {
        const container = this.closest('div');
        const stars = container.querySelectorAll('.star-icon');
        const ratingText = container.querySelector('.rating-text');
        const value = parseInt(this.value);
        
        stars.forEach((star, index) => {
            if (index < value) {
                star.classList.remove('text-gray-300');
                star.classList.add('text-yellow-400');
            } else {
                star.classList.remove('text-yellow-400');
                star.classList.add('text-gray-300');
            }
        });
        
        const labels = ['Poor', 'Fair', 'Good', 'Very Good', 'Excellent'];
        ratingText.textContent = labels[value - 1];
    });
});

// Form validation
document.getElementById('evaluationForm').addEventListener('submit', function(e) {
    const requiredFields = this.querySelectorAll('[required]');
    let allFilled = true;
    
    requiredFields.forEach(field => {
        if (!field.value && field.type !== 'radio') {
            allFilled = false;
        }
    });
    
    if (!allFilled) {
        e.preventDefault();
        alert('Please answer all required questions.');
    }
});
</script>

<?php include '../includes/footer.php'; ?>

