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

$pageTitle = 'Evaluation Questions - Admin - PSAU GAD';
$db = getDB();

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

if (!$formId) {
    header('Location: evaluation-management.php');
    exit;
}

// Get form details
$stmt = $db->prepare("
    SELECT ef.*, a.title as activity_title 
    FROM evaluation_forms ef
    JOIN activities a ON ef.activity_id = a.activity_id
    WHERE ef.form_id = ?
");
$stmt->execute([$formId]);
$form = $stmt->fetch();

if (!$form) {
    header('Location: evaluation-management.php');
    exit;
}

// Handle form submission
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action'])) {
    $action = $_POST['action'];
    
    if ($action === 'add_question') {
        $questionText = trim($_POST['question_text']);
        $questionType = $_POST['question_type'];
        $isRequired = isset($_POST['is_required']) ? 1 : 0;
        
        try {
            // Get next order number
            $stmt = $db->prepare("SELECT COALESCE(MAX(order_num), 0) + 1 as next_order FROM evaluation_questions WHERE form_id = ?");
            $stmt->execute([$formId]);
            $orderNum = $stmt->fetchColumn();
            
            $stmt = $db->prepare("
                INSERT INTO evaluation_questions (form_id, question_text, question_type, is_required, order_num)
                VALUES (?, ?, ?, ?, ?)
            ");
            $stmt->execute([$formId, $questionText, $questionType, $isRequired, $orderNum]);
            $_SESSION['success'] = 'Question added successfully!';
        } catch (PDOException $e) {
            $_SESSION['error'] = 'Error adding question: ' . $e->getMessage();
        }
    } elseif ($action === 'delete_question') {
        $questionId = (int)$_POST['question_id'];
        
        try {
            $stmt = $db->prepare("DELETE FROM evaluation_questions WHERE question_id = ?");
            $stmt->execute([$questionId]);
            $_SESSION['success'] = 'Question deleted successfully!';
        } catch (PDOException $e) {
            $_SESSION['error'] = 'Error deleting question: ' . $e->getMessage();
        }
    }
    
    header("Location: evaluation-questions.php?form_id=$formId");
    exit;
}

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

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

<div class="min-h-screen bg-gray-50 py-8">
    <div class="container mx-auto px-4">
        <!-- Header -->
        <div class="mb-8">
            <div class="flex items-center mb-4">
                <a href="evaluation-management.php" class="text-admin hover:text-admin-dark 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-list text-admin mr-2"></i><?php echo htmlspecialchars($form['title']); ?>
                    </h1>
                    <p class="text-gray-600">
                        <i class="fas fa-calendar mr-2"></i><?php echo htmlspecialchars($form['activity_title']); ?>
                    </p>
                </div>
                <button onclick="document.getElementById('addModal').classList.remove('hidden')" 
                        class="bg-admin text-white px-6 py-3 rounded-lg hover:bg-admin-dark transition font-semibold">
                    <i class="fas fa-plus mr-2"></i>Add Question
                </button>
            </div>
        </div>

        <!-- Success/Error Messages -->
        <?php if (isset($_SESSION['success'])): ?>
            <div class="bg-green-100 border-l-4 border-green-500 text-green-700 p-4 mb-6 rounded">
                <i class="fas fa-check-circle mr-2"></i><?php echo $_SESSION['success']; unset($_SESSION['success']); ?>
            </div>
        <?php endif; ?>
        
        <?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; ?>

        <!-- Questions List -->
        <div class="bg-white rounded-xl shadow-lg p-6">
            <?php if (empty($questions)): ?>
                <div class="text-center py-12">
                    <i class="fas fa-question-circle text-gray-300 text-6xl mb-4"></i>
                    <h3 class="text-xl font-bold text-gray-900 mb-2">No Questions Yet</h3>
                    <p class="text-gray-600 mb-6">Add your first question to get started.</p>
                    <button onclick="document.getElementById('addModal').classList.remove('hidden')" 
                            class="bg-admin text-white px-6 py-3 rounded-lg hover:bg-admin-dark transition font-semibold">
                        <i class="fas fa-plus mr-2"></i>Add Question
                    </button>
                </div>
            <?php else: ?>
                <div class="space-y-4">
                    <?php foreach ($questions as $index => $question): ?>
                        <div class="border border-gray-200 rounded-lg p-4 hover:shadow-md transition">
                            <div class="flex items-start justify-between">
                                <div class="flex-1">
                                    <div class="flex items-center mb-2">
                                        <span class="bg-admin text-white rounded-full w-8 h-8 flex items-center justify-center font-bold mr-3">
                                            <?php echo $index + 1; ?>
                                        </span>
                                        <span class="text-sm font-semibold text-gray-600 uppercase">
                                            <?php 
                                            $typeLabels = [
                                                'rating' => '⭐ Rating (1-5)',
                                                'multiple_choice' => '☑️ Multiple Choice',
                                                'text' => '📝 Text',
                                                'yes_no' => '✓ Yes/No'
                                            ];
                                            echo $typeLabels[$question['question_type']] ?? $question['question_type'];
                                            ?>
                                        </span>
                                        <?php if ($question['is_required']): ?>
                                            <span class="ml-2 text-xs bg-red-100 text-red-800 px-2 py-1 rounded-full font-semibold">Required</span>
                                        <?php endif; ?>
                                    </div>
                                    <p class="text-gray-900 font-medium ml-11"><?php echo htmlspecialchars($question['question_text']); ?></p>
                                </div>
                                <form method="POST" class="ml-4" onsubmit="return confirm('Delete this question?')">
                                    <input type="hidden" name="action" value="delete_question">
                                    <input type="hidden" name="question_id" value="<?php echo $question['question_id']; ?>">
                                    <button type="submit" class="text-red-600 hover:text-red-700">
                                        <i class="fas fa-trash"></i>
                                    </button>
                                </form>
                            </div>
                        </div>
                    <?php endforeach; ?>
                </div>
                
                <div class="mt-6 pt-6 border-t border-gray-200 text-center">
                    <p class="text-gray-600 mb-4">
                        <strong><?php echo count($questions); ?></strong> question(s) in this evaluation form
                    </p>
                    <button onclick="document.getElementById('addModal').classList.remove('hidden')" 
                            class="bg-admin text-white px-6 py-2 rounded-lg hover:bg-admin-dark transition font-semibold">
                        <i class="fas fa-plus mr-2"></i>Add Another Question
                    </button>
                </div>
            <?php endif; ?>
        </div>
    </div>
</div>

<!-- Add Question Modal -->
<div id="addModal" class="hidden fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50">
    <div class="bg-white rounded-xl shadow-2xl max-w-2xl w-full mx-4">
        <div class="bg-admin text-white px-6 py-4 flex items-center justify-between rounded-t-xl">
            <h3 class="text-xl font-bold"><i class="fas fa-plus mr-2"></i>Add Question</h3>
            <button onclick="document.getElementById('addModal').classList.add('hidden')" class="text-white hover:text-gray-200">
                <i class="fas fa-times text-2xl"></i>
            </button>
        </div>
        
        <form method="POST" class="p-6">
            <input type="hidden" name="action" value="add_question">
            
            <div class="space-y-4">
                <div>
                    <label class="block text-sm font-semibold text-gray-700 mb-2">Question Type *</label>
                    <select name="question_type" id="questionType" required 
                            class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-admin focus:border-transparent">
                        <option value="rating">⭐ Rating (1-5 stars)</option>
                        <option value="multiple_choice">☑️ Multiple Choice</option>
                        <option value="text">📝 Text Response</option>
                        <option value="yes_no">✓ Yes/No</option>
                    </select>
                </div>
                
                <div>
                    <label class="block text-sm font-semibold text-gray-700 mb-2">Question Text *</label>
                    <textarea name="question_text" required rows="3"
                              placeholder="Enter your question here..."
                              class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-admin focus:border-transparent"></textarea>
                </div>
                
                <div>
                    <label class="flex items-center">
                        <input type="checkbox" name="is_required" value="1" checked
                               class="w-4 h-4 text-admin border-gray-300 rounded focus:ring-admin">
                        <span class="ml-2 text-sm font-semibold text-gray-700">Required Question</span>
                    </label>
                </div>
            </div>
            
            <div class="flex justify-end space-x-3 mt-6 pt-6 border-t border-gray-200">
                <button type="button" onclick="document.getElementById('addModal').classList.add('hidden')"
                        class="px-6 py-2 border border-gray-300 rounded-lg hover:bg-gray-50 transition font-semibold">
                    Cancel
                </button>
                <button type="submit" class="bg-admin text-white px-6 py-2 rounded-lg hover:bg-admin-dark transition font-semibold">
                    <i class="fas fa-save mr-2"></i>Add Question
                </button>
            </div>
        </form>
    </div>
</div>

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

