<?php
session_start();
require_once __DIR__ . '/../../public/connection.php';

$action = $_GET['action'] ?? ($_POST['action'] ?? '');

// ---------- VIEW ----------
if ($action === 'view' && isset($_GET['id'])) {
    $id = intval($_GET['id']);
    $qRes = $conn->query("
        SELECT q.*, 
            CONCAT(eg.class,' - ',s.subjects,' - ',eg.term,' - ',eg.session,' - ',e.exam_type) AS exam_label
        FROM questions q
        LEFT JOIN exams e ON q.exam_id = e.id
        LEFT JOIN exam_groups eg ON e.exam_group_id = eg.id
        LEFT JOIN school_subjects s ON eg.subject_id = s.id
        WHERE q.id = $id
        LIMIT 1
    ");
    if ($q = $qRes->fetch_assoc()) {
        echo "<h5>Exam: {$q['exam_label']}</h5>";
        echo "<p><strong>Question Type:</strong> ".strtoupper($q['question_type'])."</p>";
        echo "<p><strong>Marks:</strong> {$q['marks']}</p>";
        echo "<p><strong>Question:</strong> {$q['question_text']}</p>";
        if (!empty($q['question_image'])) {
            echo "<p><img src='../{$q['question_image']}' style='max-width:100%;'></p>";
        }
        if ($q['question_type'] !== 'theory') {
            echo "<p><strong>Options:</strong></p><ul>";
            if ($q['option_a']) echo "<li>A: {$q['option_a']}</li>";
            if ($q['option_b']) echo "<li>B: {$q['option_b']}</li>";
            if ($q['option_c']) echo "<li>C: {$q['option_c']}</li>";
            if ($q['option_d']) echo "<li>D: {$q['option_d']}</li>";
            echo "</ul>";
            echo "<p><strong>Correct Answer:</strong> {$q['correct_answer']}</p>";
        }
    }
    exit;
}

// ---------- EDIT FORM ----------

if ($action === 'edit' && isset($_GET['id'])):
    $id = intval($_GET['id']);
    $qRes = $conn->query("SELECT * FROM questions WHERE id = $id LIMIT 1");
    if ($q = $qRes->fetch_assoc()):
?>
<form id="editQuestionForm" enctype="multipart/form-data">
    <input type="hidden" name="edit_question_id" value="<?= $q['id'] ?>">

    <div class="mb-3">
        <label>Question Text</label>
        <textarea name="question_text" class="form-control" required><?= htmlspecialchars($q['question_text']) ?></textarea>
    </div>

    <div class="mb-3">
        <label>Question Type</label>
        <select name="question_type" id="question-type-<?= $q['id'] ?>" class="form-select" required>
            <option value="mcq" <?= $q['question_type']=='mcq'?'selected':'' ?>>Multiple Choice</option>
            <option value="theory" <?= $q['question_type']=='theory'?'selected':'' ?>>Theory</option>
        </select>
    </div>

    <div id="mcq-options-<?= $q['id'] ?>" style="<?= $q['question_type']!='mcq'?'display:none;':'' ?>">
        <div class="mb-3"><label>Option A</label>
            <input type="text" name="option_a" class="form-control" value="<?= htmlspecialchars($q['option_a']) ?>">
        </div>
        <div class="mb-3"><label>Option B</label>
            <input type="text" name="option_b" class="form-control" value="<?= htmlspecialchars($q['option_b']) ?>">
        </div>
        <div class="mb-3"><label>Option C</label>
            <input type="text" name="option_c" class="form-control" value="<?= htmlspecialchars($q['option_c']) ?>">
        </div>
        <div class="mb-3"><label>Option D</label>
            <input type="text" name="option_d" class="form-control" value="<?= htmlspecialchars($q['option_d']) ?>">
        </div>
        <div class="mb-3"><label>Correct Answer</label>
            <input type="text" name="correct_answer" class="form-control" value="<?= htmlspecialchars($q['correct_answer']) ?>">
        </div>
    </div>

    <div class="mb-3">
        <label>Marks</label>
        <input type="number" step="0.1" name="marks" class="form-control" value="<?= $q['marks'] ?>" required>
    </div>

    <div class="mb-3">
        <label>Question Image (optional)</label>
        <input type="file" name="question_image" class="form-control">
        <?php if($q['question_image']): ?>
            <img src="../<?= $q['question_image'] ?>" width="80" class="mt-2">
        <?php endif; ?>
    </div>

    <button type="submit" class="btn btn-primary">Update Question</button>
</form>

<script>
const qid = <?= $q['id'] ?>;
const typeSelect = document.getElementById('question-type-' + qid);
const mcqBlock = document.getElementById('mcq-options-' + qid);

typeSelect.addEventListener('change', ()=>{
    if(typeSelect.value==='mcq'){
        mcqBlock.style.display='block';
    }else{
        mcqBlock.style.display='none';
    }
});

// AJAX submission
$('#editQuestionForm').submit(function(e){
    e.preventDefault();
    var formData = new FormData(this);
    formData.append('action','update');

    $.ajax({
        url:'partials/ajax_questions.php',
        type:'POST',
        data:formData,
        contentType:false,
        processData:false,
        dataType:'json',
        success:function(res){
            alert(res.message);
            $('#editQuestionModal').modal('hide');
            $('#questionsTable').DataTable().ajax.reload();
        },
        error:function(xhr){
            console.log(xhr.responseText);
            alert('Update failed!');
        }
    });
});
</script>
<?php
    endif;
    exit;
endif;


// ---------- UPDATE ----------
// ---------- UPDATE ----------
if($action==='update' && $_SERVER['REQUEST_METHOD']==='POST'){
    ob_clean();

    $id = intval($_POST['edit_question_id']);
    $question_text = $conn->real_escape_string($_POST['question_text']);
    $question_type = $_POST['question_type'];
    $marks = floatval($_POST['marks']);

    $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'] ?? '';

    // ✅ ADD YOUR NEW IMAGE UPLOAD CODE HERE
    $img_path = null;

    if(isset($_FILES['question_image']) && !empty($_FILES['question_image']['tmp_name'])){

        // Absolute server path
        $uploadDir = dirname(__DIR__, 2) . '/uploads/questions/';

        // Path stored in DB
        $webPath = 'uploads/questions/';

        // create folder if missing
        if (!is_dir($uploadDir)) {
            mkdir($uploadDir, 0755, true);
        }

        $ext = pathinfo($_FILES['question_image']['name'], PATHINFO_EXTENSION);
        $fileName = 'q_' . time() . '_' . rand(1000,9999) . '.' . $ext;

        $fullPath = $uploadDir . $fileName;
        $img_path = $webPath . $fileName;

        if (!move_uploaded_file($_FILES['question_image']['tmp_name'], $fullPath)) {
            echo json_encode([
                'status'=>'error',
                'message'=>'Image upload failed: ' . $_FILES['question_image']['error']
            ]);
            exit;
        }

        // delete old image
        $res = $conn->query("SELECT question_image FROM questions WHERE id=$id");
        if($row = $res->fetch_assoc()){
            if($row['question_image'] && file_exists(dirname(__DIR__,2).'/'.$row['question_image'])){
                unlink(dirname(__DIR__,2).'/'.$row['question_image']);
            }
        }
    }

    if($img_path){
        $stmt = $conn->prepare("UPDATE questions SET question_text=?, question_type=?, option_a=?, option_b=?, option_c=?, option_d=?, correct_answer=?, marks=?, question_image=? WHERE id=?");
        $stmt->bind_param("sssssssssi",$question_text,$question_type,$option_a,$option_b,$option_c,$option_d,$correct_answer,$marks,$img_path,$id);
    } else {
        $stmt = $conn->prepare("UPDATE questions SET question_text=?, question_type=?, option_a=?, option_b=?, option_c=?, option_d=?, correct_answer=?, marks=? WHERE id=?");
        $stmt->bind_param("ssssssssi",$question_text,$question_type,$option_a,$option_b,$option_c,$option_d,$correct_answer,$marks,$id);
    }

    if($stmt->execute()){
        echo json_encode(['status'=>'success','message'=>'Question updated successfully']);
    } else {
        echo json_encode(['status'=>'error','message'=>'Failed to update question']);
    }
    exit;
}

// ---------- DELETE ----------
if($action==='delete' && $_SERVER['REQUEST_METHOD']==='POST'){
    $id = intval($_POST['id']);
    $res = $conn->query("SELECT question_image FROM questions WHERE id=$id");
    if($row = $res->fetch_assoc()){
        if($row['question_image'] && file_exists("../".$row['question_image'])) unlink("../".$row['question_image']);
    }
    $stmt = $conn->prepare("DELETE FROM questions WHERE id=?");
    $stmt->bind_param("i",$id);
    $stmt->execute();
    echo json_encode(['message'=>'Question deleted successfully']);
    exit;
}

// ---------- BULK DELETE ----------
if($action==='bulk_delete' && $_SERVER['REQUEST_METHOD']==='POST'){
    $ids = $_POST['ids'] ?? [];
    foreach($ids as $id){
        $id = intval($id);
        $res = $conn->query("SELECT question_image FROM questions WHERE id=$id");
        if($row = $res->fetch_assoc()){
            if($row['question_image'] && file_exists("../".$row['question_image'])) unlink("../".$row['question_image']);
        }
        $stmt = $conn->prepare("DELETE FROM questions WHERE id=?");
        $stmt->bind_param("i",$id);
        $stmt->execute();
    }
    echo json_encode(['message'=>'Selected questions deleted successfully']);
    exit;
}

/// ---------- DATATABLES JSON ----------
$columns = ['id', 'exam_label', 'question_text', 'question_type', 'marks', 'question_image', 'correct_answer'];

$draw = intval($_GET['draw'] ?? 1);
$start = intval($_GET['start'] ?? 0);
$length = intval($_GET['length'] ?? 10);
$searchValue = $_GET['search']['value'] ?? '';
$exam_id = $_GET['exam_id'] ?? '';

$totalRecords = $conn->query("SELECT COUNT(*) AS total FROM questions")->fetch_assoc()['total'];

// WHERE clause
$where = "WHERE 1=1";
if($searchValue){
    $searchValue = $conn->real_escape_string($searchValue);
    $where .= " AND (q.question_text LIKE '%$searchValue%' 
                 OR q.correct_answer LIKE '%$searchValue%' 
                 OR q.question_type LIKE '%$searchValue%')";
}
if($exam_id) $where .= " AND q.exam_id=".intval($exam_id);

// Filtered count
$filteredRecords = $conn->query("
    SELECT COUNT(*) AS total 
    FROM questions q
    LEFT JOIN exams e ON q.exam_id = e.id
    LEFT JOIN exam_groups eg ON e.exam_group_id = eg.id
    LEFT JOIN school_subjects s ON eg.subject_id = s.id
    $where
")->fetch_assoc()['total'];

// Order
$orderColumnIndex = intval($_GET['order'][0]['column'] ?? 0);
$orderColumn = $columns[$orderColumnIndex] ?? 'id';
$orderDir = $_GET['order'][0]['dir'] ?? 'desc';

// Fetch data
$dataQuery = "
    SELECT q.*,
        CONCAT(eg.class,' - ',IFNULL(s.subjects,'N/A'),' - ',eg.term,' - ',eg.session,' - ',e.exam_type) AS exam_label
    FROM questions q
    LEFT JOIN exams e ON q.exam_id = e.id 
    LEFT JOIN exam_groups eg ON e.exam_group_id = eg.id 
    LEFT JOIN school_subjects s ON eg.subject_id = s.id 
    $where
    ORDER BY $orderColumn $orderDir
    LIMIT $start, $length
";
$result = $conn->query($dataQuery);

$data = [];
while($q = $result->fetch_assoc()){
    $imgHtml = (!empty($q['question_image'])) ? $q['question_image'] : '';
    $correct = ($q['question_type']=='theory') ? 'N/A' : $q['correct_answer'];
    $data[] = [
        "id" => $q['id'],
        "exam_label" => $q['exam_label'],
        "question_text" => $q['question_text'],
        "question_type" => strtoupper($q['question_type']),
        "marks" => $q['marks'],
        "question_image" => $imgHtml,
        "correct_answer" => $correct
    ];
}

echo json_encode([
    "draw" => $draw,
    "recordsTotal" => intval($totalRecords),
    "recordsFiltered" => intval($filteredRecords),
    "data" => $data
], JSON_UNESCAPED_SLASHES);
