<?php
require_once('../includes/functions.php');

if (!isset($_SESSION['user_id']) || $_SESSION['role'] != 'admin') {
    header("Location: ../login.php");
    exit();
}

$message = '';
$step = $_GET['step'] ?? 1;
$quizId = $_GET['quiz_id'] ?? 0;

// Step 1: Create Quiz
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['create_quiz'])) {
    $quizzes = readJson('quizzes');
    $newId = getNextId('quizzes');
    
    $quizzes[] = [
        'id' => $newId,
        'title' => $_POST['title'],
        'description' => $_POST['description'],
        'passing_score' => $_POST['passing_score'],
        'assigned_to' => $_POST['user_ids'],
        'created_by' => $_SESSION['user_id'],
        'created_at' => date('Y-m-d H:i:s')
    ];
    writeJson('quizzes', $quizzes);
    
    // Send email notifications
    $employees = getAllEmployees();
    foreach ($employees as $emp) {
        if (in_array($emp['id'], $_POST['user_ids'])) {
            $subject = "📚 New Quiz Assigned: " . $_POST['title'];
            $emailMsg = "<h3>New Quiz Assigned</h3>
                        <p><strong>Quiz:</strong> " . htmlspecialchars($_POST['title']) . "</p>
                        <p><strong>Description:</strong> " . htmlspecialchars($_POST['description']) . "</p>
                        <p><strong>Passing Score:</strong> " . $_POST['passing_score'] . "%</p>
                        <p>Please login to the portal to take this quiz.</p>
                        <hr>
                        <p><small>This is an automated notification from Employee Portal.</small></p>";
            sendEmailNotification($emp['email'], $subject, $emailMsg);
        }
    }
    
    header("Location: add_quiz.php?step=2&quiz_id=" . $newId);
    exit();
}

// Step 2: Add Questions
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['add_question'])) {
    $questions = readJson('questions');
    $questions[] = [
        'id' => getNextId('questions'),
        'quiz_id' => $_POST['quiz_id'],
        'question' => $_POST['question'],
        'option_a' => $_POST['option_a'],
        'option_b' => $_POST['option_b'],
        'option_c' => $_POST['option_c'],
        'option_d' => $_POST['option_d'],
        'correct_answer' => $_POST['correct_answer']
    ];
    writeJson('questions', $questions);
    $message = "✅ Question added successfully!";
}

// Step 3: Finish quiz
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['finish_quiz'])) {
    header("Location: dashboard.php");
    exit();
}

$employees = getAllEmployees();
$currentQuiz = null;
if ($quizId > 0) {
    $quizzes = readJson('quizzes');
    foreach ($quizzes as $quiz) {
        if ($quiz['id'] == $quizId) {
            $currentQuiz = $quiz;
            break;
        }
    }
}

$questions = readJson('questions');
$quizQuestions = array_filter($questions, function($q) use ($quizId) {
    return $q['quiz_id'] == $quizId;
});
?>
<?php include('../includes/header.php'); ?>
<div class="sidebar">
    <h3>📋 Admin Menu</h3>
    <a href="dashboard.php" class="btn" style="display: block;">📊 Dashboard</a>
    <a href="add_user.php" class="btn" style="display: block;">👤 Add Employee</a>
    <a href="manage_users.php" class="btn" style="display: block;">📋 Manage Users</a>
    <a href="add_memo.php" class="btn" style="display: block;">📝 Add Memo</a>
    <a href="add_quiz.php" class="btn" style="display: block; background: #667eea;">📚 Add Quiz</a>
    <a href="inbox.php" class="btn" style="display: block;">📥 Safety Reports</a>
</div>
<div class="content">
    <?php if($step == 1): ?>
        <h2>Create New Quiz</h2>
        <form method="POST">
            <label>Quiz Title *</label>
            <input type="text" name="title" required placeholder="Enter quiz title">
            
            <label>Description</label>
            <textarea name="description" rows="3" placeholder="Describe what this quiz covers..."></textarea>
            
            <label>Passing Score (%) *</label>
            <input type="number" name="passing_score" value="70" min="0" max="100" required>
            
            <label>Assign to Employees (Hold Ctrl/Cmd to select multiple) *</label>
            <select name="user_ids[]" multiple size="8" required style="width: 100%; padding: 10px;">
                <?php foreach($employees as $emp): ?>
                    <option value="<?php echo $emp['id']; ?>">
                        <?php echo htmlspecialchars($emp['full_name'] . " - " . $emp['email']); ?>
                    </option>
                <?php endforeach; ?>
            </select>
            <small style="color: #666;">💡 Tip: Hold Ctrl (Windows) or Cmd (Mac) to select multiple employees</small>
            
            <button type="submit" name="create_quiz" class="btn btn-success" style="margin-top: 20px;">Create Quiz & Add Questions</button>
        </form>
    
    <?php elseif($step == 2 && $currentQuiz): ?>
        <h2>Add Questions to: <?php echo htmlspecialchars($currentQuiz['title']); ?></h2>
        
        <?php if($message): ?>
            <div class="alert alert-info"><?php echo $message; ?></div>
        <?php endif; ?>
        
        <div class="card">
            <h3>Add New Question</h3>
            <form method="POST">
                <input type="hidden" name="quiz_id" value="<?php echo $quizId; ?>">
                
                <label>Question *</label>
                <textarea name="question" rows="3" required placeholder="Enter the question here..."></textarea>
                
                <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 15px;">
                    <div>
                        <label>Option A *</label>
                        <input type="text" name="option_a" required placeholder="Option A">
                    </div>
                    <div>
                        <label>Option B *</label>
                        <input type="text" name="option_b" required placeholder="Option B">
                    </div>
                    <div>
                        <label>Option C *</label>
                        <input type="text" name="option_c" required placeholder="Option C">
                    </div>
                    <div>
                        <label>Option D *</label>
                        <input type="text" name="option_d" required placeholder="Option D">
                    </div>
                </div>
                
                <label>Correct Answer *</label>
                <select name="correct_answer" required>
                    <option value="">Select correct answer</option>
                    <option value="A">A</option>
                    <option value="B">B</option>
                    <option value="C">C</option>
                    <option value="D">D</option>
                </select>
                
                <button type="submit" name="add_question" class="btn btn-success" style="margin-top: 10px;">+ Add Question</button>
            </form>
        </div>
        
        <?php if(count($quizQuestions) > 0): ?>
            <div class="card">
                <h3>Added Questions (<?php echo count($quizQuestions); ?>)</h3>
                <div class="table-responsive">
                    <table style="width: 100%;">
                        <thead>
                            <tr style="background: #f8f9fa;">
                                <th>#</th>
                                <th>Question</th>
                                <th>Correct Answer</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php $i = 1; foreach($quizQuestions as $q): ?>
                            <tr>
                                <td><?php echo $i++; ?></td>
                                <td><?php echo htmlspecialchars(substr($q['question'], 0, 50)) . (strlen($q['question']) > 50 ? '...' : ''); ?></td>
                                <td><strong><?php echo $q['correct_answer']; ?></strong> - <?php echo htmlspecialchars($q['option_' . strtolower($q['correct_answer'])]); ?></td>
                            </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
                <form method="POST" style="margin-top: 20px; text-align: center;">
                    <button type="submit" name="finish_quiz" class="btn btn-success">✓ Finish Quiz Creation</button>
                    <a href="add_quiz.php?step=2&quiz_id=<?php echo $quizId; ?>" class="btn">+ Add More Questions</a>
                </form>
            </div>
        <?php else: ?>
            <div class="alert alert-warning" style="text-align: center; padding: 20px;">
                <p>No questions added yet. Add at least one question to complete the quiz.</p>
            </div>
        <?php endif; ?>
        
    <?php endif; ?>
</div>
<div class="clearfix"></div>
<?php include('../includes/footer.php'); ?>