<?php
require_once "auth/auth_check.php";
require_once "auth/config.php";

/* ================= FETCH ACTIVE TERM & SESSION ================= */

$active_term_row    = $conn->query("SELECT name FROM terms    WHERE is_active = 1 LIMIT 1")->fetch_assoc();
$active_session_row = $conn->query("SELECT name FROM sessions WHERE is_active = 1 LIMIT 1")->fetch_assoc();
$activeTerm    = $active_term_row    ? $active_term_row['name']    : '';
$activeSession = $active_session_row ? $active_session_row['name'] : '';

/* ================= UPDATE ================= */

if(isset($_POST['update_question'])){

    $id         = (int)$_POST['id'];
    $class_id   = (int)$_POST['class_id'];
    $subject_id = (int)$_POST['subject_id'];
    $term       = $activeTerm;
    $session    = $activeSession;

    $question      = trim($_POST['question']);
    $a             = trim($_POST['option_a']      ?? '');
    $b             = trim($_POST['option_b']      ?? '');
    $c             = trim($_POST['option_c']      ?? '');
    $correct       = trim($_POST['correct_option']?? '');
    $type          = trim($_POST['question_type'] ?? 'objective');
    $instruction   = trim($_POST['instruction']   ?? '');
    $sample_answer = trim($_POST['sample_answer'] ?? '');

    $stmt = $conn->prepare("
        UPDATE questions SET
            question=?,
            option_a=?,
            option_b=?,
            option_c=?,
            correct_option=?,
            question_type=?,
            instruction=?,
            sample_answer=?
        WHERE id=?
    ");
    $stmt->bind_param("ssssssssi",
        $question, $a, $b, $c, $correct, $type, $instruction, $sample_answer, $id
    );
    $stmt->execute();

    /* ── cropped image ── */
    if(!empty($_POST['cropped_image'])){

        $imageData = $_POST['cropped_image'];
        $imageData = str_replace('data:image/jpeg;base64,', '', $imageData);
        $imageData = str_replace(' ', '+', $imageData);
        $imageBinary = base64_decode($imageData);

        if(!is_dir('uploads/questions')){ mkdir('uploads/questions', 0777, true); }

        $imgName = 'edit_' . $id . '_' . time() . '.jpg';
        $fullPath = 'uploads/questions/' . $imgName;
        file_put_contents($fullPath, $imageBinary);

        $check = $conn->prepare("SELECT id FROM question_images WHERE question_id=?");
        $check->bind_param("i", $id);
        $check->execute();

        if(stmt_get_result($check)->num_rows > 0){
            $up = $conn->prepare("UPDATE question_images SET image_name=? WHERE question_id=?");
            $up->bind_param("si", $imgName, $id);
            $up->execute();
        } else {
            $ins = $conn->prepare("INSERT INTO question_images(question_id,image_name) VALUES(?,?)");
            $ins->bind_param("is", $id, $imgName);
            $ins->execute();
        }

        /* also update questions.question_image column if it exists */
        $conn->query("UPDATE questions SET question_image='$imgName' WHERE id=$id");
    }

    header("Location: edit_questions.php?class_id=$class_id&subject_id=$subject_id&updated=1");
    exit;
}

/* ================= DELETE ================= */

if(isset($_POST['delete_question'])){

    $id         = (int)$_POST['id'];
    $class_id   = (int)$_POST['class_id'];
    $subject_id = (int)$_POST['subject_id'];

    $d = $conn->prepare("DELETE FROM questions WHERE id=?");
    $d->bind_param("i",$id);
    $d->execute();

    header("Location: edit_questions.php?class_id=$class_id&subject_id=$subject_id&deleted=1");
    exit;
}

/* ================= DELETE IMAGE ================= */

if(isset($_POST['action']) && $_POST['action'] === 'delete_img'){
    $id         = (int)$_POST['id'];
    $class_id   = (int)$_POST['class_id'];
    $subject_id = (int)$_POST['subject_id'];

    // get image name
    $r = $conn->prepare("SELECT image_name FROM question_images WHERE question_id=? LIMIT 1");
    $r->bind_param("i", $id);
    $r->execute();
    $imgRow = stmt_get_result($r)->fetch_assoc();

    if($imgRow && !empty($imgRow['image_name'])){
        $filePath = 'uploads/questions/' . $imgRow['image_name'];
        if(file_exists($filePath)) unlink($filePath);
    }

    $di = $conn->prepare("DELETE FROM question_images WHERE question_id=?");
    $di->bind_param("i",$id);
    $di->execute();

    $conn->query("UPDATE questions SET question_image='' WHERE id=$id");

    header("Location: edit_questions.php?class_id=$class_id&subject_id=$subject_id&img_deleted=1");
    exit;
}

include "header.php";

/* ================= LISTS ================= */

$classes  = $conn->query("SELECT * FROM classes  ORDER BY class_name  ASC");
$subjects = $conn->query("SELECT * FROM subjects ORDER BY subject_name ASC");

/* ================= FILTER ================= */

$class_id   = $_GET['class_id']   ?? '';
$subject_id = $_GET['subject_id'] ?? '';

$viewMode = !empty($class_id) && !empty($subject_id) && !empty($activeTerm) && !empty($activeSession);

/* ================= QUESTIONS ================= */

$questions = [];

if($viewMode){

    $stmt = $conn->prepare("
        SELECT
            q.*,
            c.class_name,
            s.subject_name,
            qi.image_name
        FROM questions q
        LEFT JOIN classes  c  ON q.class_id   = c.id
        LEFT JOIN subjects s  ON q.subject_id = s.id
        LEFT JOIN question_images qi
            ON qi.question_id = q.id
            AND qi.id = (SELECT MAX(id) FROM question_images WHERE question_id = q.id)
        WHERE q.class_id=?
        AND   q.subject_id=?
        AND   q.term=?
        AND   q.session=?
        ORDER BY q.id ASC
    ");
    $stmt->bind_param("iiss", $class_id, $subject_id, $activeTerm, $activeSession);
    $stmt->execute();
    $res = stmt_get_result($stmt);
    while($row = $res->fetch_assoc()){ $questions[] = $row; }
}
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Edit Questions</title>

<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
<link  rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/cropperjs/1.6.2/cropper.min.css"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/cropperjs/1.6.2/cropper.min.js"></script>

<style>

*{ margin:0; padding:0; box-sizing:border-box; }

body{
    background:#f4f6f9;
    font-family:Arial,sans-serif;
    overflow-x:hidden;
    padding-bottom:120px;
}

.wrapper{
    min-height:calc(100vh - 160px);
    display:flex;
    justify-content:center;
    align-items:flex-start;
    padding:90px 20px 140px;
    width:100%;
}

.card{
    width:100%;
    max-width:700px;
    background:#fff;
    padding:20px;
    border-radius:18px;
    border:1px solid #e6e6e6;
    box-shadow:0 10px 30px rgba(0,0,0,.06);
    margin:0 auto;
}

.title{ text-align:center; margin-bottom:20px; }
.title h2{ font-size:18px; color:#222; }
.title p { font-size:11px; color:#777; }

/* ── form elements ── */
.form-group{ margin-bottom:12px; }
.form-group label{ display:block; margin-bottom:6px; font-size:12px; font-weight:600; }

.form-group input,
.form-group select,
.form-group textarea{
    width:100%;
    padding:12px;
    border:1px solid #dcdcdc;
    border-radius:10px;
    font-size:12px;
    transition:.3s;
}

.form-group input:focus,
.form-group select:focus,
.form-group textarea:focus{
    border-color:#198754;
    outline:none;
    box-shadow:0 0 0 3px rgba(25,135,84,.1);
}

.form-group textarea{ min-height:100px; resize:vertical; }

.row{ display:flex; gap:12px; }

/* ── buttons ── */
.btn{
    border:none;
    padding:12px;
    border-radius:10px;
    color:#fff;
    font-size:12px;
    font-weight:bold;
    cursor:pointer;
    position:relative;
    overflow:hidden;
    transition:.3s;
    width:100%;
}
.btn:hover{ transform:translateY(-1px); }
.btn-purple{ background:#198754; }
.btn-blue  { background:#0d6efd; }
.btn-green { background:#198754; }
.btn-red   { background:#dc3545; }
.half-btn  { width:50%; }

.spinner{
    width:14px; height:14px;
    border:2px solid rgba(255,255,255,.3);
    border-top:2px solid #fff;
    border-radius:50%;
    display:none;
    position:absolute;
    left:8px; top:50%;
    transform:translateY(-50%);
    animation:spin .6s linear infinite;
}
@keyframes spin{ to{ transform:translateY(-50%) rotate(360deg); } }

/* ── term/session bar ── */
.ts-bar{
    background:#eaffea;
    border-left:4px solid #198754;
    border-radius:10px;
    padding:10px 14px;
    margin-bottom:14px;
    font-size:12px;
    color:#14532d;
    white-space:nowrap;
    overflow:hidden;
    text-overflow:ellipsis;
}
.ts-warn{
    background:#fff3cd;
    border-left:4px solid #d97706;
    border-radius:10px;
    padding:10px 14px;
    margin-bottom:14px;
    font-size:12px;
    color:#92400e;
}

/* ── question list ── */
.q-list{ margin-top:4px; }

.q-card{
    border:1px solid #e6e6e6;
    padding:14px;
    margin-bottom:10px;
    border-radius:12px;
    cursor:pointer;
    transition:.2s;
    background:#fafafa;
}
.q-card:hover{ border-color:#198754; background:#f0fdf4; }

.q-num{ font-size:11px; color:#198754; font-weight:700; margin-bottom:4px; }
.q-text{ font-size:13px; font-weight:bold; color:#222; line-height:1.5; }
.q-opts{ font-size:11px; color:#555; margin-top:6px; display:flex; flex-wrap:wrap; gap:8px; }
.q-opt{ background:#14532d; color:#fff; padding:2px 8px; border-radius:6px; font-weight:600; }
.q-type{ font-size:10px; color:#999; margin-top:6px; }
.edit-hint{ font-size:11px; color:#198754; opacity:.6; margin-top:6px; }

.q-img{
    width:100%; max-height:160px; object-fit:cover;
    border-radius:8px; margin-top:8px; border:1px solid #ddd;
}

.hidden{ display:none; }

.no-q{
    text-align:center; padding:30px 0;
    color:#999; font-size:13px;
}

/* ── modal ── */
.modal{
    display:none;
    position:fixed; inset:0;
    background:rgba(0,0,0,.55);
    justify-content:center; align-items:center;
    z-index:9999; padding:12px;
}
.modal.open{ display:flex; }

.modal-box{
    background:#fff;
    width:100%; max-width:660px;
    padding:20px;
    border-radius:16px;
    border:1px solid #e6e6e6;
    max-height:92vh; overflow-y:auto;
    box-shadow:0 20px 60px rgba(0,0,0,.2);
}
.modal-box h3{
    font-size:14px; font-weight:700;
    color:#198754; margin-bottom:14px;
    padding-bottom:10px;
    border-bottom:1px solid #dcfce7;
}

/* ── cropper in modal ── */
.custom-file-upload{
    width:100%; display:block;
    border:2px dashed #198754;
    border-radius:14px;
    background:#f0fdf4;
    padding:14px; cursor:pointer; transition:.3s;
}
.custom-file-upload:hover{ background:#dcfce7; }
.custom-file-upload input{ display:none; }

.upload-inner{ display:flex; align-items:center; gap:14px; }
.upload-icon{
    width:46px; height:46px; border-radius:10px;
    background:#198754; color:#fff;
    display:flex; justify-content:center; align-items:center;
    font-size:20px; flex-shrink:0;
}
.upload-text span{ display:block; font-size:12px; font-weight:bold; }
.upload-text small{ color:#777; font-size:11px; }

.crop-box{
    width:100%; max-height:340px; overflow:hidden;
    background:#000; border-radius:12px; margin-top:12px;
}
#editCropImage{ width:100%; display:block; }

.crop-buttons{ margin-top:10px; display:flex; justify-content:center; }

.preview-image{
    width:100%; max-height:220px; object-fit:contain;
    margin-top:10px; border-radius:10px; display:none;
    border:1px solid #ddd; padding:4px; background:#fff;
}

.existing-img{
    width:100%; max-height:200px; object-fit:contain;
    border-radius:10px; border:1px solid #ddd;
    padding:4px; margin-bottom:6px;
}

.del-img-btn{
    display:inline-flex; align-items:center; gap:5px;
    background:#dc3545; color:#fff;
    border:none; border-radius:8px;
    padding:5px 12px; font-size:11px; font-weight:bold;
    cursor:pointer; margin-bottom:10px;
    transition:.2s;
}
.del-img-btn:hover{ background:#b91c1c; }

.change-btn{
    display:inline-flex; align-items:center; gap:5px;
    background:#198754; color:#fff;
    border-radius:8px; padding:6px 14px;
    font-size:11px; font-weight:bold;
    text-decoration:none; transition:.2s;
}
.change-btn:hover{ background:#166534; }

.modal-close{
    float:right; background:none; border:none;
    font-size:20px; cursor:pointer; color:#999; line-height:1;
}

@media(max-width:600px){
    .row{ flex-direction:column; }
    .half-btn{ width:50%; }
    .card{ padding:14px; }
}

</style>
</head>
<body>

<div class="wrapper">
<div class="card">

<div class="title">
    <h2>Edit Examination Questions</h2>
    <p>Albayan Academy Shendam</p>
</div>

<!-- Term/Session bar -->
<?php if($activeTerm && $activeSession): ?>
<div class="ts-bar">
    📅 <strong>Term:</strong> <?= htmlspecialchars($activeTerm) ?> &nbsp;&bull;&nbsp;
    🗓️ <strong>Session:</strong> <?= htmlspecialchars($activeSession) ?>
</div>
<?php else: ?>
<div class="ts-warn">
    ⚠️ No active term or session set. Please update in <strong>Settings</strong>.
</div>
<?php endif; ?>

<!-- ================= FILTER FORM ================= -->
<?php if(!$viewMode): ?>

<form method="GET">

<div class="form-group">
    <label>Select Class</label>
    <select name="class_id" required>
        <option value="">Choose Class</option>
        <?php while($c = $classes->fetch_assoc()): ?>
        <option value="<?= $c['id'] ?>" <?= $class_id==$c['id']?'selected':'' ?>>
            <?= htmlspecialchars($c['class_name']) ?>
        </option>
        <?php endwhile; ?>
    </select>
</div>

<div class="form-group">
    <label>Select Subject</label>
    <select name="subject_id" required>
        <option value="">Choose Subject</option>
        <?php while($s = $subjects->fetch_assoc()): ?>
        <option value="<?= $s['id'] ?>" <?= $subject_id==$s['id']?'selected':'' ?>>
            <?= htmlspecialchars($s['subject_name']) ?>
        </option>
        <?php endwhile; ?>
    </select>
</div>

<button type="submit" class="btn btn-purple"
    <?= (!$activeTerm||!$activeSession)?'disabled style="opacity:.5;cursor:not-allowed;"':'' ?>>
    <div class="spinner"></div>
    Load Questions
</button>

</form>

<?php else: ?>

<!-- ================= QUESTION LIST ================= -->

<div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:12px;">
    <span style="font-size:12px;color:#555;">
        <?= count($questions) ?> question(s) found
    </span>
    <a href="edit_questions.php" class="change-btn">← Change Class/Subject</a>
</div>

<div class="q-list">

<?php if(empty($questions)): ?>
<div class="no-q">No questions found for the selected class and subject.</div>
<?php endif; ?>

<?php $i=1; foreach($questions as $q): ?>

<div class="q-card" onclick="openModal('modal_<?= $q['id'] ?>')">

    <div class="q-num">Question <?= $i ?></div>

    <div class="q-text"><?= htmlspecialchars(strlen($q['question']) > 120 ? substr($q['question'], 0, 117) . '...' : $q['question']) ?></div>

    <?php if(!empty($q['image_name'])): ?>
    <img src="uploads/questions/<?= htmlspecialchars($q['image_name']) ?>" class="q-img">
    <?php endif; ?>

    <?php if(!empty($q['option_a'])): ?>
    <div class="q-opts">
        <?php if(!empty($q['option_a'])): ?><span class="q-opt">A. <?= htmlspecialchars($q['option_a']) ?></span><?php endif; ?>
        <?php if(!empty($q['option_b'])): ?><span class="q-opt">B. <?= htmlspecialchars($q['option_b']) ?></span><?php endif; ?>
        <?php if(!empty($q['option_c'])): ?><span class="q-opt">C. <?= htmlspecialchars($q['option_c']) ?></span><?php endif; ?>
    </div>
    <?php endif; ?>

    <div class="q-type">Type: <?= ucfirst(htmlspecialchars($q['question_type'])) ?></div>
    <div class="edit-hint">✏️ Tap to edit</div>

</div>

<!-- ================= MODAL ================= -->
<div class="modal" id="modal_<?= $q['id'] ?>">
<div class="modal-box">

<button class="modal-close" onclick="closeModal('modal_<?= $q['id'] ?>')">&times;</button>
<h3>✏️ Edit Question <?= $i ?></h3>

<form method="POST" enctype="multipart/form-data">
<input type="hidden" name="id"         value="<?= $q['id'] ?>">
<input type="hidden" name="class_id"   value="<?= $class_id ?>">
<input type="hidden" name="subject_id" value="<?= $subject_id ?>">
<textarea name="cropped_image" id="croppedImage_<?= $q['id'] ?>" style="display:none;"></textarea>

<!-- Question -->
<div class="form-group">
    <label>Question</label>
    <textarea name="question" required><?= htmlspecialchars($q['question']) ?></textarea>
</div>

<!-- Instruction -->
<div class="form-group">
    <label>Instruction <span style="font-weight:normal;color:#999;">(optional)</span></label>
    <textarea name="instruction" style="min-height:60px;"><?= htmlspecialchars($q['instruction'] ?? '') ?></textarea>
</div>

<!-- Question Type -->
<div class="form-group">
    <label>Question Type</label>
    <select name="question_type" id="qtype_<?= $q['id'] ?>"
        onchange="toggleType(<?= $q['id'] ?>)">
        <option value="objective" <?= $q['question_type']=='objective'?'selected':'' ?>>Objective</option>
        <option value="essay"     <?= $q['question_type']=='essay'    ?'selected':'' ?>>Essay</option>
    </select>
</div>

<!-- Objective fields -->
<div id="objFields_<?= $q['id'] ?>"
    <?= $q['question_type']=='essay'?'class="hidden"':'' ?>>

    <div class="row">
        <div class="form-group">
            <label>Option A</label>
            <input type="text" name="option_a" value="<?= htmlspecialchars($q['option_a'] ?? '') ?>">
        </div>
        <div class="form-group">
            <label>Option B</label>
            <input type="text" name="option_b" value="<?= htmlspecialchars($q['option_b'] ?? '') ?>">
        </div>
    </div>

    <div class="row">
        <div class="form-group">
            <label>Option C</label>
            <input type="text" name="option_c" value="<?= htmlspecialchars($q['option_c'] ?? '') ?>">
        </div>
        <div class="form-group">
            <label>Correct Answer</label>
            <select name="correct_option">
                <option value="A" <?= $q['correct_option']=='A'?'selected':'' ?>>A</option>
                <option value="B" <?= $q['correct_option']=='B'?'selected':'' ?>>B</option>
                <option value="C" <?= $q['correct_option']=='C'?'selected':'' ?>>C</option>
            </select>
        </div>
    </div>
</div>

<!-- Essay field -->
<div id="essayFields_<?= $q['id'] ?>"
    <?= $q['question_type']!='essay'?'class="hidden"':'' ?>>
    <div class="form-group">
        <label>Sample Answer</label>
        <textarea name="sample_answer"><?= htmlspecialchars($q['sample_answer'] ?? '') ?></textarea>
    </div>
</div>

<!-- Image section -->
<div class="form-group">
    <label>Question Image</label>

    <?php if(!empty($q['image_name'])): ?>
    <div id="existingImgWrap_<?= $q['id'] ?>">
        <img src="uploads/questions/<?= htmlspecialchars($q['image_name']) ?>" class="existing-img" id="existingImg_<?= $q['id'] ?>">
        <button type="button" class="del-img-btn"
            onclick="confirmDelImg(<?= $q['id'] ?>)">
            🗑️ Delete Image
        </button>
    </div>
    <?php endif; ?>

    <label class="custom-file-upload">
        <input type="file" id="imgInput_<?= $q['id'] ?>" accept="image/*"
            onchange="initCropper(<?= $q['id'] ?>)">
        <div class="upload-inner">
            <div class="upload-icon">📁</div>
            <div class="upload-text">
                <span>Select New Photo</span>
                <small>Crop image before saving</small>
            </div>
        </div>
    </label>

    <div id="cropContainer_<?= $q['id'] ?>" class="hidden">
        <div class="crop-box">
            <img id="cropImg_<?= $q['id'] ?>">
        </div>
        <div class="crop-buttons">
            <button type="button" class="btn btn-blue"
                style="width:auto;padding:10px 20px;"
                onclick="doCrop(<?= $q['id'] ?>)">
                Crop Image
            </button>
        </div>
    </div>

    <img id="previewImg_<?= $q['id'] ?>" class="preview-image">
</div>

<!-- Action buttons -->
<div style="display:flex;flex-direction:row;gap:10px;margin-top:4px;">
    <button type="submit" name="update_question" class="btn btn-green"
        style="flex:1;" onclick="spin(this)">
        <div class="spinner"></div>
        Update
    </button>
    <button type="submit" name="delete_question" class="btn btn-red"
        style="flex:1;" onclick="return confirm('Delete this question?')">
        <div class="spinner"></div>
        Delete
    </button>
</div>

</form>
</div>
</div>

<?php $i++; endforeach; ?>

</div><!-- end q-list -->

<?php endif; ?>

</div><!-- end card -->
</div><!-- end wrapper -->

<!-- ===== DELETE IMAGE FORMS (outside all other forms) ===== -->
<?php if($viewMode): foreach($questions as $dq): if(!empty($dq['image_name'])): ?>
<form method="POST" id="delImgForm_<?= $dq['id'] ?>" style="display:none;">
    <input type="hidden" name="action"     value="delete_img">
    <input type="hidden" name="id"         value="<?= $dq['id'] ?>">
    <input type="hidden" name="class_id"   value="<?= $class_id ?>">
    <input type="hidden" name="subject_id" value="<?= $subject_id ?>">
</form>
<?php endif; endforeach; endif; ?>

<script>

/* ── modal ── */
function openModal(id){
    document.getElementById(id).classList.add('open');
}
function closeModal(id){
    document.getElementById(id).classList.remove('open');
}
window.addEventListener('click', function(e){
    document.querySelectorAll('.modal').forEach(function(m){
        if(e.target === m) m.classList.remove('open');
    });
});

/* ── question type toggle ── */
function toggleType(qid){
    var type = document.getElementById('qtype_'    + qid).value;
    var obj  = document.getElementById('objFields_' + qid);
    var ess  = document.getElementById('essayFields_' + qid);
    if(type === 'essay'){
        obj.classList.add('hidden');
        ess.classList.remove('hidden');
    } else {
        obj.classList.remove('hidden');
        ess.classList.add('hidden');
    }
}

/* ── button spin ── */
function spin(btn){
    var s = btn.querySelector('.spinner');
    if(s) s.style.display = 'block';
}

/* ── cropper per question ── */
var croppers = {};

function initCropper(qid){
    var file = document.getElementById('imgInput_' + qid).files[0];
    if(!file) return;

    var reader = new FileReader();
    reader.onload = function(e){
        var cropImg       = document.getElementById('cropImg_' + qid);
        var cropContainer = document.getElementById('cropContainer_' + qid);

        cropImg.src = e.target.result;
        cropContainer.classList.remove('hidden');

        if(croppers[qid]){ croppers[qid].destroy(); }

        croppers[qid] = new Cropper(cropImg, {
            aspectRatio:  NaN,
            viewMode:     1,
            dragMode:     'move',
            autoCropArea: 1,
            responsive:   true,
            background:   false,
            zoomable:     true,
            scalable:     true,
            rotatable:    true,
            movable:      true
        });
    };
    reader.readAsDataURL(file);
}

function doCrop(qid){
    if(!croppers[qid]) return;

    var canvas = croppers[qid].getCroppedCanvas({
        width: 900, height: 900,
        imageSmoothingQuality: 'high'
    });

    var dataUrl = canvas.toDataURL('image/jpeg', 0.8);

    document.getElementById('previewImg_'    + qid).src     = dataUrl;
    document.getElementById('previewImg_'    + qid).style.display = 'block';
    document.getElementById('croppedImage_'  + qid).value   = dataUrl;

    // hide existing image wrap
    var wrap = document.getElementById('existingImgWrap_' + qid);
    if(wrap) wrap.style.display = 'none';

    Swal.fire({ icon:'success', title:'Image Ready', text:'Photo cropped successfully', timer:1500, showConfirmButton:false });
}

function confirmDelImg(qid){
    Swal.fire({
        icon: 'warning',
        title: 'Delete Image?',
        text: 'This will permanently remove the image from this question.',
        showCancelButton: true,
        confirmButtonColor: '#dc3545',
        cancelButtonColor: '#198754',
        confirmButtonText: 'Yes, delete it',
        cancelButtonText: 'Cancel'
    }).then(function(result){
        if(result.isConfirmed){
            document.getElementById('delImgForm_' + qid).submit();
        }
    });
}

</script>

<?php if(isset($_GET['updated'])): ?>
<script>Swal.fire({ icon:'success', title:'Updated!', text:'Question updated successfully.', confirmButtonColor:'#198754' });</script>
<?php endif; ?>

<?php if(isset($_GET['deleted'])): ?>
<script>Swal.fire({ icon:'success', title:'Deleted!', text:'Question deleted successfully.', confirmButtonColor:'#198754' });</script>
<?php endif; ?>

<?php if(isset($_GET['img_deleted'])): ?>
<script>Swal.fire({ icon:'success', title:'Image Removed!', text:'The image has been deleted.', confirmButtonColor:'#198754', timer:2000, timerProgressBar:true });</script>
<?php endif; ?>

</body>
</html>

<?php include "footer.php"; ?>
