<?php
chdir('../');
session_start();
require_once("public/connection.php");
if (!isset($_SESSION['staff_id'])) {
  header("Location: ../index.php");
  exit;
}
include('partials/header.php');
include('partials/navbar.php');
include('partials/sidebar.php');
include('partials/alert.php');

// Handle POST actions (Add/Edit/Delete)
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
  $action = $_POST['action'] ?? '';
  $exam_id = intval($_POST['exam_id']);
  $instruction = trim($_POST['instruction'] ?? '');

  if ($action === 'add' || $action === 'edit') {
    // Check for existing instruction for the same exam_id
    $stmt = $conn->prepare("SELECT COUNT(*) FROM exam_instructions WHERE exam_id = ?");
    $stmt->bind_param("i", $exam_id);
    $stmt->execute();
    $stmt->bind_result($count);
    $stmt->fetch();
    $stmt->close();

    if ($count === 0) {
      $stmt = $conn->prepare("INSERT INTO exam_instructions (exam_id, instruction) VALUES (?, ?)");
      $stmt->bind_param("is", $exam_id, $instruction);
      $stmt->execute();
      $_SESSION['msg'] = "Instruction added successfully.";
      $_SESSION['type'] = "success";
      $stmt->close();
    } else {
      // Block insertion if count is greater than 0
      $_SESSION['msg'] = "Instruction already exists for this exam.";
      $_SESSION['type'] = "error";
    }
  }

  if ($action === 'delete') {
    $stmt = $conn->prepare("DELETE FROM exam_instructions WHERE exam_id = ?");
    $stmt->bind_param("i", $exam_id);
    $stmt->execute();
    $_SESSION['msg'] = "Instruction deleted successfully.";
    $_SESSION['type'] = "success";
    $stmt->close();
  }

  header("Location: exam_instructions.php");
  exit;
}

// Fetch existing instructions
$sql = "
  SELECT exams.id AS exam_id, subjects.subjects, exams.exam_type, exams.questtype, exams.class, exams.term, exams.session, instr.instruction
  FROM exams
  LEFT JOIN school_subjects subjects ON exams.subject_id = subjects.id
  LEFT JOIN exam_instructions instr ON exams.id = instr.exam_id
  ORDER BY exams.id DESC
";
$instructions = $conn->query($sql);
// Safely extract and sanitize value, allowing for NULLs


?>


<div class="content-wrapper">
  <div class="content-header">
    <div class="container-fluid">
      <h1 class="m-0">Exam Instructions</h1>
    </div>
  </div>

  <div class="content">
    <div class="container-fluid">
      <button class="btn btn-primary mb-3" data-toggle="modal" data-target="#addModal">Add New Instruction</button>
      <table class="table table-bordered" id="mytable">
        <thead>
          <tr>
            <th>Exam</th>
            <th>Instruction</th>
            <th>Actions</th>
          </tr>
        </thead>
        <tbody>
          <?php while ($row = $instructions->fetch_assoc()): ?>
            <tr>
              <!-- Exam Info -->
              <td>
                <?php $exam_info = "{$row['subjects']} - {$row['exam_type']} - {$row['class']} - {$row['term']} - {$row['session']}"; ?>
                <span data-bs-toggle="tooltip" title="<?= htmlspecialchars($exam_info) ?>">
                  <?= substr(htmlspecialchars($exam_info), 0, 20) . (strlen($exam_info) > 10 ? '...' : '') ?>
                </span>
              </td>
            
              <!-- Instruction -->
              <td>
                <?php $instruction = $row['instruction'] ?? ''; ?>
                <span data-bs-toggle="tooltip" title="<?= htmlspecialchars($instruction) ?>">
                  <?= substr(htmlspecialchars($instruction), 0, 10) . (strlen($instruction) > 10 ? '...' : '') ?>
                </span>
              </td>
            
              <!-- Actions -->
              <td>
                <!-- View Icon -->
                <button class="btn btn-info btn-sm" data-bs-toggle="modal" data-bs-target="#viewModal<?= $row['exam_id'] ?>" title="View">
                  <i class="bi bi-eye"></i>
                </button>
            
                <!-- Edit Icon -->
                <button class="btn btn-warning btn-sm" data-bs-toggle="modal" data-bs-target="#editModal<?= $row['exam_id'] ?>" title="Edit">
                  <i class="bi bi-pencil-square"></i>
                </button>
            
                <!-- Delete Icon -->
                <form method="post" action="" style="display:inline-block;" onsubmit="return confirm('Delete this instruction?')">
                  <input type="hidden" name="exam_id" value="<?= $row['exam_id'] ?>">
                  <input type="hidden" name="action" value="delete">
                  <button type="submit" class="btn btn-danger btn-sm" title="Delete">
                    <i class="bi bi-trash"></i>
                  </button>
                </form>
              </td>
            </tr>


            <!-- View Modal -->
            <div class="modal fade" id="viewModal<?= $row['exam_id'] ?>" tabindex="-1">
              <div class="modal-dialog modal-lg">
                <div class="modal-content">
                  <div class="modal-header">
                    <h5 class="modal-title">View Instruction</h5>
                    <button type="button" class="close" data-dismiss="modal">&times;</button>
                  </div>
                  <div class="modal-body">
                    <p><?= nl2br(htmlspecialchars($row['instruction'] ?? '')) ?></p>
                  </div>
                </div>
              </div>
            </div>

            <!-- Edit Modal -->
            <div class="modal fade" id="editModal<?= $row['exam_id'] ?>" tabindex="-1">
              <div class="modal-dialog">
                <div class="modal-content">
                  <form method="post">
                    <div class="modal-header">
                      <h5 class="modal-title">Edit Instruction</h5>
                      <button type="button" class="close" data-dismiss="modal">&times;</button>
                    </div>
                    <div class="modal-body">
                      <input type="hidden" name="exam_id" value="<?= $row['exam_id'] ?>">
                      <input type="hidden" name="action" value="edit">
                      <textarea name="instruction" class="form-control" rows="6" required><?= htmlspecialchars($row['instruction'] ?? '') ?></textarea>
                    </div>
                    <div class="modal-footer">
                      <button type="submit" class="btn btn-primary">Save</button>
                    </div>
                  </form>
                </div>
              </div>
            </div>

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

      <!-- Add Modal -->
      <div class="modal fade" id="addModal" tabindex="-1">
        <div class="modal-dialog">
          <div class="modal-content">
            <form method="post">
              <div class="modal-header">
                <h5 class="modal-title">Add Instruction</h5>
                <button type="button" class="close" data-dismiss="modal">&times;</button>
              </div>
              <div class="modal-body">
                <input type="hidden" name="action" value="add">
                <div class="form-group">
                  <label>Exam</label>
                  <select name="exam_id" class="form-control" required>
                    <option value="">-- Select Exam --</option>
                    <?php
                    $exams = $conn->query("SELECT exams.id, exams.questtype, CONCAT(subjects.subjects, ' - ', exam_type, ' - ', class, ' - ', term, ' - ', session) AS title FROM exams JOIN school_subjects subjects ON exams.subject_id = subjects.id ORDER BY exams.id DESC");
                    while ($exam = $exams->fetch_assoc()): 
                    
                    // Safely extract and sanitize value, allowing for NULLs
$qtype =  htmlspecialchars($exam['questtype']);

// Display human-friendly labels
if ($qtype === 'mcq') {
    $qt = 'Multi Choice Question';
} elseif ($qtype === 'theory') {
    echo 'Theory';
} 
?>

                    
                    ?>
                    
                    
                    
                    
                    
                    
                    
                    
                      <option value="<?= $exam['id'] ?>"><?= htmlspecialchars($exam['title']) ?><?php echo $qt; ?></option>
                    <?php endwhile; ?>
                  </select>
                  
                </div>
                <div class="form-group">
                  <label>Instruction</label>
                  <textarea name="instruction" class="form-control" rows="6" required></textarea>
                </div>
              </div>
              <div class="modal-footer">
                <button type="submit" class="btn btn-primary">Add Instruction</button>
              </div>
            </form>
          </div>
        </div>
      </div>

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

<?php include('partials/footer.php'); ?>
