????????????????????
??????????????????
ÿØÿà
 JFIF      ÿÛ C      


!"$"$ÿÛ C    
ÿÂ p 
" ÿÄ     
         ÿÄ             ÿÚ 
   ÕÔË®

(%	aA*‚XYD¡(J„¡E¢RE,P€XYae )(E¤²€B¤R¥	BQ¤¢ X«)X…€¤   @  

adadasdasdasasdasdas


.....................................................................................................................................????????????????????
??????????????????
ÿØÿà
 JFIF      ÿÛ C      


!"$"$ÿÛ C    
ÿÂ p 
" ÿÄ     
         ÿÄ             ÿÚ 
   ÕÔË®

(%	aA*‚XYD¡(J„¡E¢RE,P€XYae )(E¤²€B¤R¥	BQ¤¢ X«)X…€¤   @  

adadasdasdasasdasdas


.....................................................................................................................................<?php
    
session_start();
require_once "session.php"; // Update path if needed
require_once "connection.php"; // For login check + session validation

// CSRF
if (empty($_SESSION['csrf_token'])) $_SESSION['csrf_token'] = bin2hex(random_bytes(32));
$csrf = $_SESSION['csrf_token'];

if (!isset($_GET['question_id']) || !is_numeric($_GET['question_id'])) {
    die("Invalid question id.");
}
$question_id = intval($_GET['question_id']);

// Fetch question + assignment id
$q = $pdo->prepare("SELECT * FROM questions WHERE id = ?");
$q->execute([$question_id]);
$question = $q->fetch(PDO::FETCH_ASSOC);
if (!$question) die("Question not found.");

$assignment_id = $question['assignment_id'];

// Fetch options
$optStmt = $pdo->prepare("SELECT * FROM options WHERE question_id = ? ORDER BY id ASC");
$optStmt->execute([$question_id]);
$options = $optStmt->fetchAll(PDO::FETCH_ASSOC);

// Handle POST update
$error = null;
$success = null;
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (!isset($_POST['csrf_token']) || $_POST['csrf_token'] !== $_SESSION['csrf_token']) {
        die("Invalid CSRF token");
    }

    $question_text = trim($_POST['question_text'] ?? '');
    $weight = floatval($_POST['weight'] ?? 0);
    $order = isset($_POST['question_order']) && $_POST['question_order'] !== '' ? intval($_POST['question_order']) : null;

    $opt_texts = [
        trim($_POST['option1'] ?? ''),
        trim($_POST['option2'] ?? ''),
        trim($_POST['option3'] ?? ''),
        trim($_POST['option4'] ?? '')
    ];
    $correct_option = isset($_POST['correct_option']) ? intval($_POST['correct_option']) : 0;

    if ($question_text === '' || $weight <= 0) {
        $error = "Question text and weight required.";
    } elseif ($correct_option < 1 || $correct_option > 4) {
        $error = "Choose correct option.";
    } elseif (count(array_unique($opt_texts)) < 4) {
        $error = "Options must be unique.";
    } else {
        try {
    $pdo->beginTransaction();

    // Handle new image upload (optional)
    $newImageName = $question['question_image']; // Default: old image stays

    if (!empty($_FILES['question_image']['name'])) {
        $ext = strtolower(pathinfo($_FILES['question_image']['name'], PATHINFO_EXTENSION));
        $allowed = ['jpg','jpeg','png','webp'];

        if (!in_array($ext, $allowed)) {
            throw new Exception("Invalid image type");
        }

        $newImageName = "question_" . time() . "_" . rand(1000,9999) . "." . $ext;
        $uploadPath = "uploads/questions/" . $newImageName;

        // delete old file
        if (!empty($question['question_image'])) {
            $oldPath = "uploads/questions/" . $question['question_image'];
            if (file_exists($oldPath)) unlink($oldPath);
        }

        move_uploaded_file($_FILES['question_image']['tmp_name'], $uploadPath);
    }

    // Update question (with new or old image name)
    $updQ = $pdo->prepare("UPDATE questions 
        SET question_text=?, weight=?, question_order=?, question_image=? 
        WHERE id=?");
    $updQ->execute([$question_text, $weight, $order, $newImageName, $question_id]);

            // Update options: assume 4 options, keep their ids order as fetched
            $optIds = array_column($options, 'id');
            $optUpd = $pdo->prepare("UPDATE options SET option_text=?, is_correct=? WHERE id=?");
            foreach ($optIds as $i => $oid) {
                $is_correct = (($i + 1) === $correct_option) ? 1 : 0;
                $optUpd->execute([$opt_texts[$i], $is_correct, $oid]);
            }

            // Recalc total marks
            $pdo->prepare("UPDATE assignments SET total_marks = (SELECT IFNULL(SUM(weight),0) FROM questions WHERE assignment_id = ?) WHERE id = ?")
                ->execute([$assignment_id, $assignment_id]);

            $pdo->commit();
            $success = "Question updated successfully.";
            // Refresh fetch
            $q->execute([$question_id]); $question = $q->fetch(PDO::FETCH_ASSOC);
            $optStmt->execute([$question_id]); $options = $optStmt->fetchAll(PDO::FETCH_ASSOC);
        } catch (Exception $e) {
            $pdo->rollBack();
            $error = "Error: " . $e->getMessage();
        }
    }
}
 
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Add Customers | Xcel Training Institute</title>
    <!-- Favicon icon -->
    <link rel="icon" type="image/png" href="../images/logo-wide.png">
    <!-- Base Styling  -->
    <link rel="stylesheet" href="assets/main/css/fonts.css">
    <link rel="stylesheet" href="assets/main/css/style.css">
<script src="https://cdn.jsdelivr.net/npm/alpinejs@3.x.x/dist/cdn.min.js" defer></script>
<script src="https://code.jquery.com/jquery-3.6.4.min.js"></script>
<script src="https://cdn.tailwindcss.com"></script>  
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet">  

<style>
    .btn{
            background-color: red;
            border: none;
            color: white;
            padding: 5px 5px;
            text-align: center;
            text-decoration: none;
            display: inline-block;
            font-size: 20px;
            margin: 4px 2px;
            cursor: pointer;
            border-radius: 20px;
        }
        .green{
            background-color: #199319;
        }
        .red{
            background-color: red;
        }
        </style>
</head>

<body>
    <div id="main-wrapper" class="show">


      <?php
         include "sidebar.php";
         ?>


         <?php
         include "header.php";
         ?>


          <div class="content-body">
            <div class="warper container-fluid">
                <div class="new-patients main_container">
                    
       <div class="row">
                        <div class="col-lg-12">
                            <div class="card">

                           <div class="container">
    <h3>Edit Question (ID: <?= $question_id ?>)</h3>
    <?php if ($error): ?><div class="alert alert-danger"><?= htmlspecialchars($error) ?></div><?php endif; ?>
    <?php if ($success): ?><div class="alert alert-success"><?= htmlspecialchars($success) ?></div><?php endif; ?>

    <form method="post" enctype="multipart/form-data">

        <input type="hidden" name="csrf_token" value="<?= $csrf ?>">
        <div class="mb-3">
            <label class="form-label">Question Text</label>
            <textarea name="question_text" class="form-control" required><?= htmlspecialchars($question['question_text']) ?></textarea>
        </div>


<?php if (!empty($question['question_image'])): ?>
    <div class="mb-3">
        <label class="fw-bold">Current Image</label><br>
        <img src="uploads/questions/<?= htmlspecialchars($question['question_image']) ?>" 
             alt="Question Image" style="max-width:200px;border:1px solid #ccc;">
    </div>
<?php endif; ?>

<div class="mb-3">
    <label class="fw-bold">Upload New Image (optional)</label>
    <input type="file" name="question_image" class="form-control">
    <small class="text-muted">Only upload if you want to replace the existing image.</small>
</div>


        <div class="row mb-3">
            <div class="col">
                <label>Weight (marks)</label>
                <input type="number" name="weight" min="1" class="form-control" value="<?= htmlspecialchars($question['weight']) ?>" required>
            </div>
            <div class="col">
                <label>Order</label>
                <input type="number" name="question_order" class="form-control" value="<?= htmlspecialchars($question['question_order']) ?>">
            </div>
        </div>

        <label class="fw-bold">Options</label>
        <?php foreach ($options as $i => $op): $index = $i + 1; ?>
            <div class="input-group mb-2">
                <span class="input-group-text"><?= $index ?></span>
                <input type="text" name="option<?= $index ?>" class="form-control" value="<?= htmlspecialchars($op['option_text']) ?>" required>
                <span class="input-group-text">
                    <input type="radio" name="correct_option" value="<?= $index ?>" <?= $op['is_correct'] ? 'checked' : '' ?>>
                    Correct
                </span>
            </div>
        <?php endforeach; ?>

        <button class="btn btn-primary">Save</button>
        <a href="upload_questions_tailwind.php?assignment_id=<?= $assignment_id ?>" class="btn btn-secondary">Back</a>
    </form>
</div>
                        </div>
 
                          



                    </div>
                    
                </div>
            </div>
        </div>
        <!-- End section content -->

        <?php
//    include('footer.php');
?>


    </div>
  

    
    <!-- popper js -->
    <script src="assets/plugins/popper/popper.min.js"></script>

    <!-- Bootstrap -->
    <script src="assets/plugins/bootstrap/js/bootstrap.js"></script>

    <!-- Moment -->
    <script src="assets/plugins/moment/moment.min.js"></script>

    <!-- Date Range Picker -->
    <script src="assets/plugins/daterangepicker/daterangepicker.min.js"></script>

    <!-- Datatable -->
    <script src="assets/plugins/datatables/jquery.dataTables.min.js"></script>
    <script src="assets/js/init-tdatatable.js"></script>

    <!-- Chart js -->
    <script src="assets/plugins/chart/chart/Chart.min.js"></script>
    <script src="assets/js/charts-custom.js"></script>

    <!-- Main Custom JQuery -->
    <script src="assets/js/toggleFullScreen.js"></script>
    <script src="assets/js/main.js"></script>

</body>
</html>