<?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');

$staff_id = $_SESSION['staff_id'];
$stmt = $conn->prepare("SELECT * FROM staff WHERE id = ?");
$stmt->bind_param("i", $staff_id);
$stmt->execute();
$staff = $stmt->get_result()->fetch_assoc();
$fname = explode(' ', $staff['name'])[0];
$lname = explode(' ', $staff['name'])[1] ?? '';

$my_students = $conn->query("SELECT COUNT(*) as total FROM students")->fetch_assoc()['total'] ?? 0;
$subjects = $conn->query("SELECT COUNT(*) as total FROM school_subjects")->fetch_assoc()['total'] ?? 0;
$total_exams = $conn->query("SELECT COUNT(*) as total FROM exams")->fetch_assoc()['total'] ?? 0;
$total_questions = $conn->query("SELECT COUNT(*) as total FROM questions")->fetch_assoc()['total'] ?? 0;
$total_attempts = $conn->query("SELECT COUNT(*) as total FROM student_exam_attempts")->fetch_assoc()['total'] ?? 0;

$exam_class_data = $conn->query("SELECT class, COUNT(*) as total FROM exams GROUP BY class");
$question_type_data = $conn->query("SELECT question_type, COUNT(*) as total FROM questions GROUP BY question_type");
?>

<div class="content-wrapper">
  <div class="content-header">
    <div class="container-fluid">
      <div class="row mb-2">
        <div class="col-sm-6">
          <h1 class="m-0">Dashboard</h1>
        </div>
      </div>
    </div>
  </div>

  <div class="content">
    <div class="container-fluid">
      <div class="row g-2">
        <div class="col-lg-3 col-6">
          <div class="small-box bg-info">
            <div class="inner">
              <h3><?php echo $total_exams; ?></h3>
              <p>Total Exams</p>
            </div>
            <div class="icon">
              <i class="fas fa-book"></i>
            </div>
          </div>
        </div>
        <div class="col-lg-3 col-6">
          <div class="small-box bg-success">
            <div class="inner">
              <h3><?php echo $my_students; ?></h3>
              <p>Students</p>
            </div>
            <div class="icon">
              <i class="fas fa-user-graduate"></i>
            </div>
          </div>
        </div>
        <div class="col-lg-3 col-6">
          <div class="small-box bg-warning">
            <div class="inner">
              <h3><?php echo $total_questions; ?></h3>
              <p>Questions</p>
            </div>
            <div class="icon">
              <i class="fas fa-question-circle"></i>
            </div>
          </div>
        </div>
        <div class="col-lg-3 col-6">
          <div class="small-box bg-danger">
            <div class="inner">
              <h3><?php echo $total_attempts; ?></h3>
              <p>Attempts</p>
            </div>
            <div class="icon">
              <i class="fas fa-check-circle"></i>
            </div>
          </div>
        </div>
      </div>

      <div class="row g-3 align-items-stretch">
        <div class="col-md-6">
          <div class="card h-100">
            <div class="card-header bg-dark text-white">Recently Created Exams</div>
            <div class="card-body">
              <table class="table table-sm">
<thead>
  <tr>
    <th>Exam Type</th>
    <th>Class</th>
    <th>Subject</th>
    <th>Date</th>
  </tr>
</thead>
<tbody>
  <?php
  $recent_exams = $conn->query("
    SELECT e.exam_type, e.class, e.exam_date, s.subjects 
    FROM exams e 
    LEFT JOIN school_subjects s ON e.subject_id = s.id 
    ORDER BY e.created_at DESC 
    LIMIT 5
  ");
  while($e = $recent_exams->fetch_assoc()): ?>
    <tr>
      <td><?= htmlspecialchars($e['exam_type']) ?></td>
      <td><?= htmlspecialchars($e['class']) ?></td>
      <td><?= htmlspecialchars($e['subjects']) ?></td>
      <td><?= htmlspecialchars($e['exam_date']) ?></td>
    </tr>
  <?php endwhile; ?>
</tbody>
              </table>
            </div>
          </div>
        </div>

        <div class="col-md-6">
          <div class="card h-100">
            <div class="card-header bg-info text-white">New Students</div>
            <div class="card-body">
              <ul class="list-group">
                <?php
                $students = $conn->query("SELECT firstname, lastname, othername FROM students ORDER BY id DESC LIMIT 5");
                while($s = $students->fetch_assoc()): ?>
                <li class="list-group-item">
                  <?= htmlspecialchars($s['firstname'] . ' ' . $s['othername'] . ' ' . $s['lastname']) ?>
                </li>
                <?php endwhile; ?>
              </ul>
            </div>
          </div>
        </div>
<div class="col-md-6">
<div class="card shadow-sm h-100 mb-4">
  <div class="card-header bg-primary text-white">
    <i class="fas fa-calendar-alt"></i> Exam Calendar
  </div>
  <div class="card-body">
    <div id="examCalendar"></div>
  </div>
</div>
</div>


        <div class="col-md-6">
          <div class="card h-100">
            <div class="card-header bg-primary text-white">Exams by Class</div>
            <div class="card-body">
              <canvas id="examChart" height="160"></canvas>
            </div>
          </div>
        </div>

        <div class="col-md-6">
          <div class="card h-60">
            <div class="card-header bg-success text-white">Question Types</div>
            <div class="card-body">
              <canvas id="questionTypeChart" height="90"></canvas>
            </div>
          </div>
        </div>
      </div>

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

<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<script>
  const ctx1 = document.getElementById('examChart');
  const examChart = new Chart(ctx1, {
    type: 'bar',
    data: {
      labels: [<?php $exam_class_data->data_seek(0); while($row = $exam_class_data->fetch_assoc()) echo "'{$row['class']}',"; ?>],
      datasets: [{
        label: 'Exams per Class',
        data: [<?php $exam_class_data->data_seek(0); while($row = $exam_class_data->fetch_assoc()) echo "{$row['total']},"; ?>],
        backgroundColor: 'rgba(54, 162, 235, 0.6)'
      }]
    },
    options: {
      responsive: true,
      plugins: { legend: { display: false } }
    }
  });

  const ctx2 = document.getElementById('questionTypeChart');
  const typeChart = new Chart(ctx2, {
    type: 'pie',
    data: {
      labels: [<?php $question_type_data->data_seek(0); while($row = $question_type_data->fetch_assoc()) echo "'{$row['question_type']}',"; ?>],
      datasets: [{
        data: [<?php $question_type_data->data_seek(0); while($row = $question_type_data->fetch_assoc()) echo "{$row['total']},"; ?>],
        backgroundColor: ['#007bff', '#28a745', '#ffc107', '#dc3545']
      }]
    },
    options: {
      responsive: true,
      radius: '60%', // ✅ This works in Chart.js 4+
      plugins: {
        legend: {
          position: 'bottom',
          labels: {
            font: {
              size: 10
            }
          }
        }
      }
    }
  });
</script>

<script>
  document.addEventListener('DOMContentLoaded', function() {
    const calendarEl = document.getElementById('examCalendar');
    const calendar = new FullCalendar.Calendar(calendarEl, {
      initialView: 'dayGridMonth',
      height: 500,
      events: [
        <?php
        $events = $conn->query("
          SELECT e.exam_type, e.exam_date, e.class, s.subjects 
          FROM exams e 
          LEFT JOIN school_subjects s ON e.subject_id = s.id 
          WHERE e.exam_date >= CURDATE()
        ");
        while ($e = $events->fetch_assoc()):
          $title = $e['class'] . ' - ' . $e['subjects'] . ' (' . ucfirst($e['exam_type']) . ')';
        ?>
        {
          title: "<?= addslashes($title) ?>",
          start: "<?= $e['exam_date'] ?>",
          allDay: true
        },
        <?php endwhile; ?>
      ],
      headerToolbar: {
        left: 'prev,next today',
        center: 'title',
        right: 'dayGridMonth,listWeek'
      },
      eventColor: '#007bff'
    });

    calendar.render();
  });
</script>


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

