<?php
// Enable full error reporting
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

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 exam creation
if (isset($_POST['create_exam'])) {
    $class = trim($_POST['class']);
    $subject_id = intval($_POST['subject']);
    $duration = intval($_POST['duration']);
     $duration2 = intval($_POST['duration2']);
    $term = trim($_POST['term']);
    $session_year = trim($_POST['session']);
    $exam_date = $_POST['exam_date'];
    $exam_type = trim($_POST['exam_type']);
    $status = 'inactive';
    $created_by = $_SESSION['staff_id'];
    
    
    $multiquestion =  $_POST['multiquestion'];
    $theoryquestion =  $_POST['theoryquestion'];
    

    
    // Normalize case for comparison
$multiquestion = strtoupper(trim($multiquestion));
$theoryquestion = strtoupper(trim($theoryquestion));

if ($multiquestion == 'YES' && $theoryquestion == 'YES') {
    $qt = 'Multi Choice and Theory Questions';
} elseif ($multiquestion == 'NO' && $theoryquestion == 'YES') {
    $qt = 'Theory Questions';
} elseif ($multiquestion == 'YES' && $theoryquestion == 'NO') {
    $qt = 'Multi Choice Questions';
} else {
    $qt = 'Non Indicated';
}

$questtype = $qt;
    
    
    

    if (!empty($class) && $subject_id > 0 && $term && $session_year && $exam_date && $exam_type) {
        // Step 1: Get or create exam group
        $groupStmt = $conn->prepare("SELECT id FROM exam_groups WHERE class = ? AND subject_id = ? AND term = ? AND session = ?");
        $groupStmt->bind_param("siss", $class, $subject_id, $term, $session_year);
        $groupStmt->execute();
        $groupResult = $groupStmt->get_result();

        if ($groupResult->num_rows > 0) {
            $exam_group_id = $groupResult->fetch_assoc()['id'];
        } else {
            $insertGroup = $conn->prepare("INSERT INTO exam_groups (class, subject_id, term, session) VALUES (?, ?, ?, ?)");
            $insertGroup->bind_param("siss", $class, $subject_id, $term, $session_year);
            $insertGroup->execute();
            $exam_group_id = $insertGroup->insert_id;
        }

        // Step 2: Check for duplicate exam type in the group
        $checkStmt = $conn->prepare("SELECT id FROM exams WHERE exam_group_id = ? AND exam_type = ? AND questtype = ? ");
        $checkStmt->bind_param("iss", $exam_group_id, $exam_type, $questtype);
        $checkStmt->execute();
        $checkStmt->store_result();

        if ($checkStmt->num_rows > 0) {
            $_SESSION['msg'] = "An exam of this type already exists for the selected class, subject, term, and session.";
            $_SESSION['type'] = "error";
            header("Location: manage_exams.php");
            exit;
        }

        // Step 3: Insert new exam
        $stmt = $conn->prepare("INSERT INTO exams (exam_group_id, class, subject_id, duration_minutes, duration_minutes2, exam_date, term, session, created_by, status, exam_type, questtype, hastheory, hasmcq) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
        $stmt->bind_param("isiiisssisssss", $exam_group_id, $class, $subject_id, $duration, $duration2, $exam_date, $term, $session_year, $created_by, $status, $exam_type, $questtype, $theoryquestion, $multiquestion);
        $stmt->execute();

        $_SESSION['msg'] = "Exam created successfully.";
        $_SESSION['type'] = "success";
        header("Location: manage_exams.php");
        exit;
    } else {
        $_SESSION['msg'] = "Please fill in all fields correctly.";
        $_SESSION['type'] = "warning";
        header("Location: manage_exams.php");
        exit;
    }
}

// Handle exam deletion
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['delete_exam'])) {
    $exam_id = intval($_POST['delete_exam']);

    $conn->query("DELETE FROM exam_results WHERE exam_id = $exam_id");
    $conn->query("DELETE FROM questions WHERE exam_id = $exam_id");
    $conn->query("DELETE FROM exams WHERE id = $exam_id");

    $_SESSION['msg'] = "Exam and related records deleted successfully.";
    $_SESSION['type'] = "success";
    header("Location: manage_exams.php");
    exit;
}

// Handle exam update
if (isset($_POST['update_exam'])) {
    $id = intval($_POST['exam_id']);
    $class = trim($_POST['class']);
    $subject_id = intval($_POST['subject']);
    $duration = intval($_POST['duration']);
    $duration2 = intval($_POST['duration2']);
    $term = trim($_POST['term']);
    $session_year = trim($_POST['session']);
    $exam_date = $_POST['exam_date'];
    $status = trim($_POST['status']);
    $exam_type = trim($_POST['exam_type']);

    // Get exam_group_id
    $groupStmt = $conn->prepare("SELECT id FROM exam_groups WHERE class = ? AND subject_id = ? AND term = ? AND session = ?");
    $groupStmt->bind_param("siss", $class, $subject_id, $term, $session_year);
    $groupStmt->execute();
    $groupResult = $groupStmt->get_result();

    if ($groupResult->num_rows > 0) {
        $exam_group_id = $groupResult->fetch_assoc()['id'];
    } else {
        $insertGroup = $conn->prepare("INSERT INTO exam_groups (class, subject_id, term, session) VALUES (?, ?, ?, ?)");
        $insertGroup->bind_param("siss", $class, $subject_id, $term, $session_year);
        $insertGroup->execute();
        $exam_group_id = $insertGroup->insert_id;
    }

    // Check for duplicate in the same group and exam type
  //  $checkStmt = $conn->prepare("SELECT id FROM exams WHERE exam_group_id = ? AND exam_type = ? AND id != ?");
   /** $checkStmt->bind_param("isi", $exam_group_id, $exam_type, $id);
    $checkStmt->execute();
    $checkStmt->store_result();

    if ($checkStmt->num_rows > 0) {
        $_SESSION['msg'] = "Another exam of this type already exists for the selected class, subject, term, and session.";
        $_SESSION['type'] = "error";
        header("Location: manage_exams.php");
        exit;
    } **/

    $stmt = $conn->prepare("UPDATE exams SET exam_group_id=?, class=?, subject_id=?, duration_minutes=?, duration_minutes2=?, term=?, session=?, exam_date=?, status=?, exam_type=? WHERE id=?");
    $stmt->bind_param("isiiisssssi", $exam_group_id, $class, $subject_id, $duration, $duration2, $term, $session_year, $exam_date, $status, $exam_type, $id);
    $stmt->execute();

    $_SESSION['msg'] = "Exam updated successfully.";
    $_SESSION['type'] = "success";
    header("Location: manage_exams.php");
    exit;
}

// Handle exam status update
if (isset($_GET['toggle_status'])) {
    $exam_id = intval($_GET['toggle_status']);
    $status_query = $conn->query("SELECT status FROM exams WHERE id = $exam_id LIMIT 1");
    if ($status_query && $status_query->num_rows > 0) {
        $current_status = $status_query->fetch_assoc()['status'];
        $new_status = $current_status === 'active' ? 'inactive' : 'active';
        $stmt = $conn->prepare("UPDATE exams SET status = ? WHERE id = ?");
        $stmt->bind_param("si", $new_status, $exam_id);
        $stmt->execute();
    }
    $_SESSION['msg'] = "Exam status updated.";
    $_SESSION['type'] = "success";
    header("Location: manage_exams.php");
    exit;
}

// Fetch supporting data
$exams = $conn->query("SELECT e.*, s.subjects FROM exams e LEFT JOIN school_subjects s ON e.subject_id = s.id ORDER BY e.created_at ASC");
$classes = $conn->query("SELECT classes FROM classes ORDER BY id ASC");
$subjects = $conn->query("SELECT id, subjects FROM school_subjects ORDER BY subjects ASC");
$sessions = $conn->query("SELECT sessions FROM sessions ORDER BY sessions DESC");
?>
<div class="content-wrapper">
  <div class="content-header">
    <div class="container-fluid">
      <h4>Manage Exams</h4>
    </div>
  </div>

  <div class="content">
    <div class="container-fluid">

      <!-- Add New Exam -->
    <div class="card mb-3">
      <div class="card-header d-flex flex-wrap justify-content-between align-items-center gap-2">
        <button class="btn btn-primary" type="button" data-bs-toggle="collapse" data-bs-target="#examFormCollapse" aria-expanded="false" aria-controls="examFormCollapse">
          + Add New Exam
        </button>
      </div>
    
      <div class="collapse" id="examFormCollapse">
        <div class="card-body border-top">
          <form method="post">
            <div class="row g-3">
              <div class="col-md-3">
                <label class="form-label">Exam Type</label>
                <select name="exam_type" class="form-control" required>
                  <option value="">--Select--</option>
                  
                  <option value="ca1">CA 1</option>
           
                  <option value="ca2">CA 2</option>
                  <option value="exam">EXAM</option>
                </select>
              </div>
    
              <div class="col-md-2">
                <label class="form-label">Class</label>
                <select name="class" class="form-control" required>
                  <option value="">--Select--</option>
                  <?php $classes->data_seek(0); while($row = $classes->fetch_assoc()): ?>
                    <option value="<?= $row['classes'] ?>"><?= $row['classes'] ?></option>
                  <?php endwhile; ?>
                </select>
              </div>
    
              <div class="col-md-3">
                <label class="form-label">Subject</label>
                <select name="subject" class="form-control" required>
                  <option value="">--Select--</option>
                  <?php $subjects->data_seek(0); while($row = $subjects->fetch_assoc()): ?>
                    <option value="<?= $row['id'] ?>"><?= $row['subjects'] ?></option>
                  <?php endwhile; ?>
                </select>
              </div>
    
              <div class="col-md-2">
                <label class="form-label">Term</label>
                <select name="term" class="form-control" required>
                  <option value="">--Select--</option>
                  <option value="First Term">First Term</option>
                  <option value="Second Term">Second Term</option>
                  <option value="Third Term">Third Term</option>
                </select>
              </div>
    
              <div class="col-md-2">
                <label class="form-label">Session</label>
                <select name="session" class="form-control" required>
                  <option value="">--Select--</option>
                  <?php $sessions->data_seek(0); while($row = $sessions->fetch_assoc()): ?>
                    <option value="<?= $row['sessions'] ?>"><?= $row['sessions'] ?></option>
                  <?php endwhile; ?>
                </select>
              </div>
              
             <!-- <div class="col-md-2">
                <label class="form-label">Question Type </label>
                <select name="questtype" class="form-control" required>
                    <option value="">--Select--</option>
                  <option value="mcq">Multi Choice</option>
                  <option value="theory">Theory</option>

                </select>
              </div> -->
              
                <div class="col-md-2">
                <label class="form-label">Has Theory Questions </label>
                <select name="theoryquestion" class="form-control" required>
                    <option value="">--Select--</option>
                  <option value="Yes">Yes</option>
                  <option value="No">No</option>

                </select>
              </div>
              <div class="col-md-2">
                <label class="form-label">Duration - Theory (mins)</label>
                <input type="number" name="duration" class="form-control" required>
              </div>
              
                <div class="col-md-2">
                <label class="form-label">Has Multichoice Questions </label>
                <select name="multiquestion" class="form-control" required>
                    <option value="">--Select--</option>
                   <option value="Yes">Yes</option>
                  <option value="No">No</option>

                </select>
              </div>
              
            <div class="col-md-2">
                <label class="form-label">Duration-Multichoice (mins)</label>
                <input type="number" name="duration2" class="form-control" required>
              </div>
    
              
    
              <div class="col-md-2">
                <label class="form-label">Date</label>
                <input type="date" name="exam_date" class="form-control" required>
              </div>
            </div>
    
            <button type="submit" name="create_exam" class="btn btn-success mt-3">
              <i class="fa fa-check"></i> Create Exam
            </button>
          </form>
        </div>
      </div>
    </div>
    
    
    <!-- All Exams Table -->
    <div class="card">
      <div class="card-header bg-dark text-white">All Exams</div>
      <div class="card-body table-responsive">
        <table class="table table-bordered table-striped align-middle" id="myTable">
          <thead>
      <tr>
        <th>Exam ID</th>
        <th>Group ID</th>
        <th>Type</th>
        <th>Class</th>
        <th>Subject</th>
        <th>Question Type</th>
                
                <th>Total No of Questions</th>
        <th>Duration Theory</th>
        <th>Duration MultiChoice</th>
        <th>Term</th>
        <th>Date</th>
        <th>Status</th>
        <th>Actions</th>
      </tr>
    </thead>
    <tbody>
      <?php $exams->data_seek(0); while($exam = $exams->fetch_assoc()):
      
      $examids = htmlspecialchars($exam['id']);
  
      
             
             // Query to count theory questions
$query3 = "
    SELECT COUNT(*) AS total_theory 
    FROM questions 
    WHERE exam_id = '$examids' 
      AND question_type = 'theory'
";

$result = mysqli_query($conn, $query3);

// Fetch and store theory count
if ($result && $row = mysqli_fetch_assoc($result)) {
    $theorycount = $row['total_theory'];
} else {
    $theorycount = 0; // default if none found
}


// Query to count multiple choice questions
$query2 = "
    SELECT COUNT(*) AS mcq 
    FROM questions 
    WHERE exam_id = '$examids' 
      AND question_type = 'mcq'
";

$result2 = mysqli_query($conn, $query2); // ✅ FIXED

// Fetch and store mcq count
if ($result2 && $row2 = mysqli_fetch_assoc($result2)) {
    $mcq = $row2['mcq'];
} else {
    $mcq = 0; // default if none found
}

              
              
              
              

$totalquest = $mcq + $theorycount;

      
      ?>
      
      
      <tr>
        <td><?= htmlspecialchars($exam['id']) ?></td>
        <td><?= htmlspecialchars($exam['exam_group_id']) ?></td>
        <td><?= ucfirst(htmlspecialchars($exam['exam_type'])) ?></td>
        <td><?= htmlspecialchars($exam['class']) ?></td>
        <td><?= htmlspecialchars($exam['subjects']) ?></td>
     <td>
<?php
// Safely extract and sanitize value, allowing for NULLs
$qtype = isset($exam['questtype']) && $exam['questtype'] !== null
    ? htmlspecialchars($exam['questtype'])
    : 'Not Available';

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

           
                
                 <td><?php echo $totalquest; ?> </td>
        <td><?= htmlspecialchars($exam['duration_minutes']) ?> mins</td>
       
        <td><?= htmlspecialchars($exam['duration_minutes2'] ?? '0') ?> mins</td>

        <td><?= htmlspecialchars($exam['term']) ?></td>
        <td><?= date('M d, Y', strtotime($exam['exam_date'])) ?></td>
        <td>
                <a href="?toggle_status=<?= $exam['id'] ?>" class="badge bg-<?= $exam['status'] === 'active' ? 'success' : 'secondary' ?>">
                  <?= ucfirst($exam['status']) ?>
                </a>
              </td>
              <td>
                <!-- Edit Button -->
                <button class="btn btn-sm btn-warning editExamBtn"
                  data-bs-toggle="modal"
                  data-bs-target="#editExamModal"
                  data-id="<?= $exam['id'] ?>"
                  data-type="<?= htmlspecialchars($exam['exam_type']) ?>"
                  data-class="<?= htmlspecialchars($exam['class']) ?>"
                  data-subject="<?= htmlspecialchars($exam['subject_id']) ?>"
                  data-duration="<?= $exam['duration_minutes'] ?>"
                  data-duration2="<?= $exam['duration_minutes2'] ?>"
                  data-term="<?= $exam['term'] ?>"
                  data-session="<?= $exam['session'] ?>"
                  data-date="<?= $exam['exam_date'] ?>"
                  data-status="<?= $exam['status'] ?>"
                  title="Edit Exam">
                  <i class="bi bi-pencil-square"></i>
                </button>
    
                <!-- Delete Form -->
                <form method="POST" style="display:inline;" onsubmit="return confirm('Delete this exam?')">
                  <input type="hidden" name="delete_exam" value="<?= $exam['id'] ?>">
                  <button type="submit" class="btn btn-sm btn-danger" title="Delete Exam">
                    <i class="fas fa-trash-alt"></i>
                  </button>
                </form>
              </td>
            </tr>
            <?php endwhile; ?>
          </tbody>
        </table>
      </div>
    </div>


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

<!-- Edit Exam Modal -->
<div class="modal fade" id="editExamModal" tabindex="-1" aria-labelledby="editExamModalLabel" aria-hidden="true">
  <div class="modal-dialog modal-lg" role="document">
    <form method="post" id="editExamForm">
      <input type="hidden" name="exam_id" id="edit_exam_id">
      <div class="modal-content">
        <div class="modal-header bg-warning">
          <h5 class="modal-title" id="editExamModalLabel">Edit Exam</h5>
          <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
        </div>
        
        <div class="modal-body row g-3">
          <div class="form-group col-md-6">
            <label for="edit_type">Exam Type</label>
            <select name="exam_type" id="edit_type" class="form-control" required>
                  <option value="ca1">CA 1</option>
                  <option value="ca2">CA 2</option>
                  <option value="exam">EXAM</option>
                  
            </select>
          </div>

          <div class="form-group col-md-6">
            <label for="edit_class">Class</label>            
            <select name="class" id="edit_class" class="form-control" required>
              <option value="">--Select--</option>
              <?php $classes->data_seek(0); while($row = $classes->fetch_assoc()): ?>
                <option value="<?= $row['classes'] ?>"><?= $row['classes'] ?></option>
              <?php endwhile; ?>
            </select>
          </div>

          <div class="form-group col-md-6">
            <label for="edit_subject">Subject</label>
            <select name="subject" id="edit_subject" class="form-control" required>
              <option value="">--Select--</option>
              <?php $subjects->data_seek(0); while($row = $subjects->fetch_assoc()): ?>
                <option value="<?= $row['id'] ?>"><?= $row['subjects'] ?></option>
              <?php endwhile; ?>
            </select>
          </div>

          <div class="form-group col-md-3">
            <label for="edit_duration">Duration Theory (mins)</label>
            <input type="number" name="duration" id="edit_duration" class="form-control" required>
          </div>
          
            <div class="form-group col-md-3">
            <label for="edit_duration2">Duration Multi choice (mins)</label>
            <input type="number" name="duration2" id="edit_duration2" class="form-control" required>
          </div>

          <div class="form-group col-md-3">
            <label for="edit_status">Status</label>
            <select name="status" id="edit_status" class="form-control" required>
              <option value="active">Active</option>
              <option value="inactive">Inactive</option>
            </select>
          </div>

          <div class="form-group col-md-4">
            <label for="edit_term">Term</label>
            <select name="term" id="edit_term" class="form-control" required>
              <option value="">--Select--</option>
              <option value="First Term">First Term</option>
              <option value="Second Term">Second Term</option>
              <option value="Third Term">Third Term</option>
            </select>
          </div>

          <div class="form-group col-md-4">
            <label for="edit_session">Session</label>
            <select name="session" id="edit_session" class="form-control" required>
              <option value="">--Select--</option>
              <?php $sessions->data_seek(0); while($row = $sessions->fetch_assoc()): ?>
                <option value="<?= $row['sessions'] ?>"><?= $row['sessions'] ?></option>
              <?php endwhile; ?>
            </select>
          </div>

          <div class="form-group col-md-4">
            <label for="edit_exam_date">Date</label>
            <input type="date" name="exam_date" id="edit_exam_date" class="form-control" required>
          </div>
        </div>

        <div class="modal-footer">
          <button type="submit" name="update_exam" class="btn btn-primary">
            <i class="fa fa-save"></i> Update
          </button>
        </div>
      </div>
    </form>
  </div>
</div>

<script>
  // Handle Edit Exam button click
  document.querySelectorAll('.editExamBtn').forEach(button => {
    button.addEventListener('click', () => {
      const modal = new bootstrap.Modal(document.getElementById('editExamModal'));
      const fields = {
        'edit_exam_id': button.dataset.id,
        'edit_type': button.dataset.type,
        'edit_class': button.dataset.class,
        'edit_subject': button.dataset.subject,
        'edit_duration': button.dataset.duration,
        'edit_duration2': button.dataset.duration2,
        'edit_term': button.dataset.term,
        'edit_session': button.dataset.session,
        'edit_exam_date': button.dataset.date,
        'edit_status': button.dataset.status
      };

      for (const [id, value] of Object.entries(fields)) {
        const field = document.getElementById(id);
        if (field) field.value = value;
      }

      modal.show();
    });
  });

  // Search Filter Logic
  const searchInput = document.getElementById('searchInput');
  if (searchInput) {
    searchInput.addEventListener('keyup', function () {
      const filter = this.value.toLowerCase();
      const rows = document.querySelectorAll('#examTable tbody tr');
      rows.forEach(row => {
        const show = Array.from(row.cells).some(cell => 
          cell.textContent.toLowerCase().includes(filter)
        );
        row.style.display = show ? '' : 'none';
      });
    });
  }
</script>
<?php include('partials/footer.php'); ?>

