<?php
// Show all errors and warnings
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
?>
<?php
session_start();
include 'config.php';

// ✅ Redirect if not logged in
if (!isset($_SESSION['user'])) {
    header("Location: index.php");
    exit;
}

// Create module
if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['create_module'])) {
    $title = $_POST['title'];
    $duration = $_POST['duration_minutes'];
    $is_active = isset($_POST['is_active']) ? 1 : 0;

    $sql = "INSERT INTO exams (title, duration_minutes, is_active, created_at) 
            VALUES (?, ?, ?, NOW())";
    $stmt = $conn->prepare($sql);
    $stmt->bind_param("sii", $title, $duration, $is_active);
    $stmt->execute();
    $stmt->close();
}

if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['save_questions'])) {
    $exam_id = $_POST['exam_id'];
    $questions = $_POST['questions'] ?? [];

    // Clear old entries
    $conn->query("DELETE FROM exam_questions WHERE exam_id = $exam_id");

    foreach ($questions as $qid) {
        $stmt = $conn->prepare("INSERT INTO exam_questions (exam_id, question_id) VALUES (?, ?)");
        $stmt->bind_param("ii", $exam_id, $qid);
        $stmt->execute();
        $stmt->close();
    }
}

// ✅ Toggle active status BEFORE output
if (isset($_GET['toggle_id'])) {
    $exam_id = intval($_GET['toggle_id']);
    $current_status = intval($_GET['status']); // 0 or 1

    $new_status = $current_status ? 0 : 1;

    $stmt = $conn->prepare("UPDATE exams SET is_active = ? WHERE id = ?");
    $stmt->bind_param("ii", $new_status, $exam_id);
    $stmt->execute();
    $stmt->close();

    header("Location: ".$_SERVER['PHP_SELF']); // Safe now
    exit;
}

// Fetch modules
$modules = $conn->query("SELECT * FROM exams ORDER BY id DESC");

// ✅ Only include header after all redirect logic
$page_title = "Module Page"; 
// ✅ Delete module
if (isset($_GET['delete_id'])) {
    $delete_id = intval($_GET['delete_id']);

    // Delete related exam_questions first
    $conn->query("DELETE FROM questions WHERE exam_id = $delete_id");

    // Delete module
    $stmt = $conn->prepare("DELETE FROM exams WHERE id = ?");
    $stmt->bind_param("i", $delete_id);
    $stmt->execute();
    $stmt->close();

    header("Location: ".$_SERVER['PHP_SELF']); 
    exit;
}

include 'common/header.php';
?>
<style>
body {
    font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
    background: #eef1f6;
    margin: 0;
    padding: 0;
}

.main-wrapper {
    flex: 1;
    padding: 30px;
    display: flex;          
    flex-direction: column; 
}

.content {
    background: #fff;
    padding: 25px;
    border-radius: 12px;
    box-shadow: 0 4px 10px rgba(0,0,0,0.08);
    transition: 0.3s ease-in-out;
}

.content:hover {
    box-shadow: 0 6px 16px rgba(0,0,0,0.12);
}

h2 {
    margin-bottom: 20px;
    color: #2d3748;
    font-size: 26px;
    
    padding-left: 12px;
}

h3 {
    margin-bottom: 15px;
    color: #444;
    font-size: 20px;
}

.form {
    display: flex;
    flex-direction: column;
    gap: 14px;
    margin-bottom: 25px;
    padding: 15px;
    border: 1px solid #ddd;
    border-radius: 10px;
    background: #fafafa;
}

.form label {
    font-weight: 500;
    color: #555;
}

.form input[type="text"],
.form input[type="number"] {
    padding: 10px;
    border: 1px solid #ccc;
    border-radius: 8px;
    font-size: 14px;
    outline: none;
    transition: 0.3s;
}

.form input[type="text"]:focus,
.form input[type="number"]:focus {
    border-color: #007bff;
    box-shadow: 0 0 4px rgba(0,123,255,0.3);
}

.form input[type="checkbox"] {
    margin-right: 6px;
    transform: scale(1.2);
}

.form button {
    padding: 12px;
    background: linear-gradient(135deg, #007bff, #0056b3);
    color: #fff;
    font-size: 15px;
    font-weight: 500;
    border: none;
    border-radius: 8px;
    cursor: pointer;
    transition: all 0.3s;
}

.form button:hover {
    background: linear-gradient(135deg, #0056b3, #004494);
    transform: translateY(-2px);
    box-shadow: 0 4px 10px rgba(0,0,0,0.15);
}

/* Table styling */
table {
    width: 100%;
    border-collapse: collapse;
    margin-top: 15px;
    border-radius: 10px;
    overflow: hidden;
    box-shadow: 0 2px 8px rgba(0,0,0,0.1);
}

table th, table td {
    padding: 12px 15px;
    border: 1px solid #eee;
    text-align: center;
    font-size: 14px;
}

table th {
    background: #007bff;
    color: #fff;
    text-transform: uppercase;
    font-size: 13px;
}

table tr:nth-child(even) {
    background: #f9fbfd;
}

table tr:hover {
    background: #f1f7ff;
}

table a {
    text-decoration: none;
    font-weight: 500;
    transition: 0.2s;
}

/* Responsive */
@media (max-width: 768px) {
    .content {
        padding: 15px;
    }

    table th, table td {
        padding: 8px;
        font-size: 12px;
    }
}
</style>

<div class="main-wrapper">
    <div class="content">
        <!-- Create Module -->
        <form method="post" class="form">
            <h3>Create New Module</h3>
            <label>Title:</label>
            <input type="text" name="title" required>

            <label>Duration (minutes):</label>
            <input type="number" name="duration_minutes" required>

            <label>
                <input type="checkbox" name="is_active" value="1"> Active
            </label>

            <button type="submit" name="create_module">Create Module</button>
        </form>

        <hr>

        <!-- List Modules -->
        <h3>Existing Modules</h3>
        <table>
            <tr>
                <th>ID</th>
                <th>Title</th>
                <th>Duration</th>
                <th>Active</th>
                <th>Actions</th>
            </tr>
            <?php while($row = $modules->fetch_assoc()): ?>
            <tr>
                <td><?= $row['id'] ?></td>
                <td><?= $row['title'] ?></td>
                <td><?= $row['duration_minutes'] ?></td>
                <td>
                    <a href="?toggle_id=<?= $row['id'] ?>&status=<?= $row['is_active'] ?>"
                       style="padding:6px 12px; border-radius:6px; 
                              color:#fff; 
                              background:<?= $row['is_active'] ? '#28a745' : '#dc3545' ?>;">
                       <?= $row['is_active'] ? 'Active' : 'Inactive' ?>
                    </a>
                </td>
                <td>
    <a href="question1.php?exam_id=<?= $row['id'] ?>">Add Questions</a> | 
    <a href="edit_module.php?id=<?= $row['id'] ?>" style="color:orange;">Edit</a> | 
    <a href="?delete_id=<?= $row['id'] ?>" 
       onclick="return confirm('Are you sure you want to delete this module?');" 
       style="color:red;">Delete</a>
</td>

            </tr>
            <?php endwhile; ?>
        </table>

        <?php
        // If exam selected, show questions to assign
        if (isset($_GET['exam_id'])) {
            $exam_id = intval($_GET['exam_id']);

            // Fetch all questions
            $questions = $conn->query("SELECT * FROM questions");

            // Fetch already selected questions
            $selected = [];
            $res = $conn->query("SELECT question_id FROM exam_questions WHERE exam_id = $exam_id");
            while ($r = $res->fetch_assoc()) {
                $selected[] = $r['question_id'];
            }
        ?>
        <hr>
        
        <form method="post" class="form">
            <input type="hidden" name="exam_id" value="<?= $exam_id ?>">
            <?php while($q = $questions->fetch_assoc()): ?>
                <label>
                    <input type="checkbox" name="questions[]" value="<?= $q['id'] ?>"
                        <?= in_array($q['id'], $selected) ? 'checked' : '' ?>>
                    <?= htmlspecialchars($q['question_text']) ?>
                </label>
            <?php endwhile; ?>
            <button type="submit" name="save_questions">Save Questions</button>
        </form>
        <?php } ?>
    </div>
</div>
