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

$pageTitle = 'Post-Test Management - Secretariat - PSAU GAD';
$db = getDB();

// Handle form submission
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action'])) {
    $action = $_POST['action'];
    
    if ($action === 'create_test') {
        $activityId = (int)$_POST['activity_id'];
        $title = trim($_POST['title']);
        $instructions = trim($_POST['instructions']);
        $passingScore = (int)$_POST['passing_score'];
        $timeLimit = (int)$_POST['time_limit'];
        
        try {
            $stmt = $db->prepare("
                INSERT INTO post_tests (activity_id, title, instructions, passing_score, time_limit, created_by)
                VALUES (?, ?, ?, ?, ?, ?)
            ");
            $stmt->execute([$activityId, $title, $instructions, $passingScore, $timeLimit, getCurrentUserId()]);
            $_SESSION['success'] = 'Pre-test created successfully!';
            header('Location: post-test-management.php');
            exit;
        } catch (PDOException $e) {
            $_SESSION['error'] = 'Error creating post-test: ' . $e->getMessage();
        }
    } elseif ($action === 'delete_test') {
        $testId = (int)$_POST['test_id'];
        
        try {
            $stmt = $db->prepare("DELETE FROM post_tests WHERE test_id = ?");
            $stmt->execute([$testId]);
            $_SESSION['success'] = 'Pre-test deleted successfully!';
        } catch (PDOException $e) {
            $_SESSION['error'] = 'Error deleting post-test: ' . $e->getMessage();
        }
    } elseif ($action === 'toggle_status') {
        $testId = (int)$_POST['test_id'];
        
        try {
            $stmt = $db->prepare("UPDATE post_tests SET is_active = NOT is_active WHERE test_id = ?");
            $stmt->execute([$testId]);
            $_SESSION['success'] = 'Pre-test status updated!';
        } catch (PDOException $e) {
            $_SESSION['error'] = 'Error updating status: ' . $e->getMessage();
        }
    }
}

// Get all post-tests with activity info
$stmt = $db->query("
    SELECT 
        pt.*,
        a.title as activity_title,
        a.activity_date,
        COUNT(DISTINCT q.question_id) as question_count,
        COUNT(DISTINCT r.response_id) as response_count
    FROM post_tests pt
    JOIN activities a ON pt.activity_id = a.activity_id
    LEFT JOIN test_questions q ON pt.test_id = q.test_id AND q.test_type = 'post_test'
    LEFT JOIN post_test_responses r ON pt.test_id = r.test_id
    GROUP BY pt.test_id
    ORDER BY a.activity_date DESC, pt.created_at DESC
");
$tests = $stmt->fetchAll();

// Get activities for dropdown
$stmt = $db->query("
    SELECT activity_id, title, activity_date 
    FROM activities 
    WHERE is_active = 1 
    ORDER BY activity_date DESC
");
$activities = $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 justify-between">
                <div>
                    <h1 class="text-3xl font-bold text-gray-900 mb-2">
                        <i class="fas fa-file-alt text-secretariat mr-2"></i>Post-Test Management
                    </h1>
                    <p class="text-gray-600">Create and manage post-tests for activities</p>
                </div>
                <button onclick="document.getElementById('createModal').classList.remove('hidden')" 
                        class="bg-secretariat text-white px-6 py-3 rounded-lg hover:bg-secretariat-dark transition font-semibold">
                    <i class="fas fa-plus mr-2"></i>Create Post-Test
                </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; ?>

        <!-- Tests List -->
        <div class="bg-white rounded-xl shadow-lg overflow-hidden">
            <?php if (empty($tests)): ?>
                <div class="p-12 text-center">
                    <i class="fas fa-file-alt text-gray-300 text-6xl mb-4"></i>
                    <h3 class="text-xl font-bold text-gray-900 mb-2">No Post-Tests Yet</h3>
                    <p class="text-gray-600 mb-6">Create your first post-test to get started.</p>
                    <button onclick="document.getElementById('createModal').classList.remove('hidden')" 
                            class="bg-secretariat text-white px-6 py-3 rounded-lg hover:bg-secretariat-dark transition font-semibold">
                        <i class="fas fa-plus mr-2"></i>Create Post-Test
                    </button>
                </div>
            <?php else: ?>
                <div class="overflow-x-auto">
                    <table class="w-full">
                        <thead class="bg-secretariat text-white">
                            <tr>
                                <th class="px-6 py-4 text-left text-sm font-semibold">Test Title</th>
                                <th class="px-6 py-4 text-left text-sm font-semibold">Activity</th>
                                <th class="px-6 py-4 text-left text-sm font-semibold">Questions</th>
                                <th class="px-6 py-4 text-left text-sm font-semibold">Responses</th>
                                <th class="px-6 py-4 text-left text-sm font-semibold">Passing Score</th>
                                <th class="px-6 py-4 text-left text-sm font-semibold">Time Limit</th>
                                <th class="px-6 py-4 text-left text-sm font-semibold">Status</th>
                                <th class="px-6 py-4 text-left text-sm font-semibold">Actions</th>
                            </tr>
                        </thead>
                        <tbody class="divide-y divide-gray-200">
                            <?php foreach ($tests as $test): ?>
                                <tr class="hover:bg-gray-50">
                                    <td class="px-6 py-4">
                                        <div class="font-semibold text-gray-900"><?php echo htmlspecialchars($test['title']); ?></div>
                                        <div class="text-xs text-gray-500">Created <?php echo date('M j, Y', strtotime($test['created_at'])); ?></div>
                                    </td>
                                    <td class="px-6 py-4">
                                        <div class="text-sm text-gray-900"><?php echo htmlspecialchars($test['activity_title']); ?></div>
                                        <div class="text-xs text-gray-500"><?php echo formatDate($test['activity_date']); ?></div>
                                    </td>
                                    <td class="px-6 py-4">
                                        <span class="text-lg font-bold text-secretariat"><?php echo $test['question_count']; ?></span>
                                    </td>
                                    <td class="px-6 py-4">
                                        <span class="text-lg font-bold text-green-600"><?php echo $test['response_count']; ?></span>
                                    </td>
                                    <td class="px-6 py-4 text-sm text-gray-900"><?php echo $test['passing_score']; ?>%</td>
                                    <td class="px-6 py-4 text-sm text-gray-900"><?php echo $test['time_limit']; ?> min</td>
                                    <td class="px-6 py-4">
                                        <form method="POST" class="inline">
                                            <input type="hidden" name="action" value="toggle_status">
                                            <input type="hidden" name="test_id" value="<?php echo $test['test_id']; ?>">
                                            <button type="submit" class="text-sm">
                                                <?php if ($test['is_active']): ?>
                                                    <span class="px-2 py-1 rounded-full bg-green-100 text-green-800 font-semibold">Active</span>
                                                <?php else: ?>
                                                    <span class="px-2 py-1 rounded-full bg-gray-100 text-gray-800 font-semibold">Inactive</span>
                                                <?php endif; ?>
                                            </button>
                                        </form>
                                    </td>
                                    <td class="px-6 py-4">
                                        <div class="flex items-center space-x-2">
                                            <a href="post-test-questions.php?test_id=<?php echo $test['test_id']; ?>" 
                                               class="text-secretariat hover:text-secretariat-dark" title="Manage Questions">
                                                <i class="fas fa-list"></i>
                                            </a>
                                            <a href="post-test-results.php?test_id=<?php echo $test['test_id']; ?>" 
                                               class="text-green-600 hover:text-green-700" title="View Results">
                                                <i class="fas fa-chart-bar"></i>
                                            </a>
                                            <form method="POST" class="inline" onsubmit="return confirm('Delete this post-test?')">
                                                <input type="hidden" name="action" value="delete_test">
                                                <input type="hidden" name="test_id" value="<?php echo $test['test_id']; ?>">
                                                <button type="submit" class="text-red-600 hover:text-red-700" title="Delete">
                                                    <i class="fas fa-trash"></i>
                                                </button>
                                            </form>
                                        </div>
                                    </td>
                                </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
            <?php endif; ?>
        </div>
    </div>
</div>

<!-- Create Modal -->
<div id="createModal" 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 max-h-[90vh] overflow-y-auto">
        <div class="bg-secretariat 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>Create Post-Test</h3>
            <button onclick="document.getElementById('createModal').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="create_test">
            
            <div class="space-y-4">
                <div>
                    <label class="block text-sm font-semibold text-gray-700 mb-2">Activity *</label>
                    <select name="activity_id" required class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-secretariat focus:border-transparent">
                        <option value="">Select Activity</option>
                        <?php foreach ($activities as $activity): ?>
                            <option value="<?php echo $activity['activity_id']; ?>">
                                <?php echo htmlspecialchars($activity['title']); ?> - <?php echo formatDate($activity['activity_date']); ?>
                            </option>
                        <?php endforeach; ?>
                    </select>
                </div>
                
                <div>
                    <label class="block text-sm font-semibold text-gray-700 mb-2">Test Title *</label>
                    <input type="text" name="title" required 
                           placeholder="e.g., Gender Sensitivity Post-Test"
                           class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-secretariat focus:border-transparent">
                </div>
                
                <div>
                    <label class="block text-sm font-semibold text-gray-700 mb-2">Instructions</label>
                    <textarea name="instructions" rows="3" 
                              placeholder="Enter test instructions..."
                              class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-secretariat focus:border-transparent"></textarea>
                </div>
                
                <div class="grid grid-cols-2 gap-4">
                    <div>
                        <label class="block text-sm font-semibold text-gray-700 mb-2">Passing Score (%) *</label>
                        <input type="number" name="passing_score" value="60" min="0" max="100" required
                               class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-secretariat focus:border-transparent">
                    </div>
                    
                    <div>
                        <label class="block text-sm font-semibold text-gray-700 mb-2">Time Limit (minutes) *</label>
                        <input type="number" name="time_limit" value="30" min="5" max="180" required
                               class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-secretariat focus:border-transparent">
                    </div>
                </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('createModal').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-secretariat text-white px-6 py-2 rounded-lg hover:bg-secretariat-dark transition font-semibold">
                    <i class="fas fa-save mr-2"></i>Create Test
                </button>
            </div>
        </form>
    </div>
</div>

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

