<!-- ====================== DASHBOARD START ====================== -->
<div class="page-title text-center py-3 bg-light rounded shadow-sm mb-4 animate__animated animate__fadeInDown">
  <marquee behavior="scroll" direction="left" scrollamount="5">
    <h1 class="fw-bold text-primary mb-0"><?php echo $school_name; ?></h1>
  </marquee>
  <p class="mb-0 text-muted"><b><?php echo $current_term; ?> - <?php echo $current_session; ?> Session</b></p>
<h4 class="mt-2 text-success">Welcome, <?php echo htmlspecialchars($full_name); ?></h4>


</div>

<?php
if (isset($_SESSION['staff'])) {
    
    $userrole =  $_SESSION['role'];
    
 // ===== Total Students =====
    $query = "SELECT COUNT(*) AS total_student FROM `students` WHERE status = 'active'";
    $run_query = mysqli_query($connection, $query);
    $row = mysqli_fetch_assoc($run_query);
    $total_student = $row['total_student'];

    // ===== Total Subjects =====
    $query = "SELECT COUNT(*) AS total_subject FROM `school_subjects`";
    $run_query = mysqli_query($connection, $query);
    $row = mysqli_fetch_assoc($run_query);
    $total_subject = $row['total_subject'];

    // ===== Total Classes =====
    $query = "SELECT COUNT(*) AS total_class FROM `classes`";
    $run_query = mysqli_query($connection, $query);
    $row = mysqli_fetch_assoc($run_query);
    $total_class = $row['total_class'];

    // ===== Total Staff =====
    $query = "SELECT COUNT(*) AS total_staff FROM `staff`";
    $run_query = mysqli_query($connection, $query);
    $row = mysqli_fetch_assoc($run_query);
    $total_staff = $row['total_staff'];

function getPreviousTerm($term) {
    switch ($term) {
        case 'Third Term': return 'Second Term';
        case 'Second Term': return 'First Term';
        case 'First Term': return 'Third Term'; // roll back to last term of previous session
        default: return $term;
    }
}

function getPreviousSession($term, $session) {
    // Assume session format is "2024/2025"
    if ($term === 'First Term') {
        // go back one session
        $parts = explode('/', $session);
        if (count($parts) === 2) {
            $start = intval($parts[0]) - 1;
            $end   = intval($parts[1]) - 1;
            return $start . '/' . $end;
        }
    }
    return $session;
}
// ===== Tuition Fee (from generated invoices / fee_payment) =====

// Total fee assigned to students for current term/session
$fee_stats_total = $connection->query("
    SELECT COALESCE(SUM(total_fee), 0) AS total_fee,
           COALESCE(SUM(amount_paid), 0) AS paid_amount,
           COALESCE(SUM(student_balance), 0) AS outstanding_fee
    FROM fee_payment
    WHERE fee_term = '{$current_term}' 
      AND fee_session = '{$current_session}'
")->fetch_assoc();

$total_tuition_fee = $fee_stats_total['total_fee'];
$paid_amount       = $fee_stats_total['paid_amount'];
$outstanding_fee   = $fee_stats_total['outstanding_fee'];


// ===== Current Term/Session Fee Stats =====
$fee_stats = $connection->query("
    SELECT 
        COALESCE(SUM(student_balance), 0) AS outstanding_fee,
        COALESCE(SUM(amount_paid), 0) AS paid_amount
    FROM fee_payment
    WHERE fee_term = '{$current_term}' 
      AND fee_session = '{$current_session}'
")->fetch_assoc();

$outstanding_feeold  = $fee_stats['outstanding_fee'];
$paid_amount      = $fee_stats['paid_amount'];

$outstanding_fee = $total_tuition_fee - $paid_amount;

// ===== Arrears (All Previous Terms/Sessions) =====
// Everything before the current session/term
$arrears_stats = $connection->query("
    SELECT 
        COALESCE(SUM(CASE WHEN student_balance < 0 THEN ABS(student_balance) ELSE 0 END), 0) AS arrears_amount,
        COALESCE(SUM(student_balance), 0) AS arrears_balance
    FROM fee_payment
    WHERE (fee_session < '{$current_session}')
       OR (fee_session = '{$current_session}' AND fee_term < '{$current_term}')
")->fetch_assoc();

$arrears_amount   = $arrears_stats['arrears_amount'];
$arrears_balance  = $arrears_stats['arrears_balance'];

?>

<div class="row g-3 mb-4">

  <!-- Total Classes -->
  <div class="col-md-6 col-lg-3">
    <div class="stat-card" 
         style="background: linear-gradient(135deg, #5B72E4, #7A8CFF); color: #FFFFFF;">
      <i class="fas fa-school icon" style="color:#c1c9ff;"></i>
      <div>
        <h6>Total Classes</h6>
        <h3><?php echo $total_class; ?></h3>
      </div>
    </div>
  </div>

  <!-- Total Staff -->
  <div class="col-md-6 col-lg-3">
    <div class="stat-card" 
         style="background: linear-gradient(135deg, #6FCF97, #A7EFC9); color: #FFFFFF;">
      <i class="fas fa-user-tie icon" style="color:#d4f6e2;"></i>
      <div>
        <h6>Total Staff</h6>
        <h3><?php echo $total_staff; ?></h3>
      </div>
    </div>
  </div>

  <!-- Total Students -->
  <div class="col-md-6 col-lg-3">
    <div class="stat-card" 
         style="background: linear-gradient(135deg, #F6C23E, #FFD966); color: #2E2E2E;">
      <i class="fas fa-users icon" style="color:#FFF4C1;"></i>
      <div>
        <h6>Total Students</h6>
        <h3><?php echo $total_student; ?></h3>
      </div>
    </div>
  </div>

  <!-- Total Subjects -->
  <div class="col-md-6 col-lg-3">
    <div class="stat-card" 
         style="background: linear-gradient(135deg, #FF6B6B, #FF8F8F); color: #FFFFFF;">
      <i class="fas fa-book icon" style="color:#FFD1D1;"></i>
      <div>
        <h6>Total Subjects</h6>
        <h3><?php echo $total_subject; ?></h3>
      </div>
    </div>  
  </div> 
</div>

<br>

<?php if ($userrole === 11): ?>
<div class="row g-3 mb-4">

  <!-- Total Fee -->
  <div class="col-md-6 col-lg-3">
    <div class="stat-card" 
         style="background: linear-gradient(135deg, #4B4BFF, #6A6AFF); color: #FFFFFF;">
      <i class="fas fa-money-bill-wave icon" style="color:#AAB2FF;"></i>
      <div>
        <h6>Total Fee</h6>
        <h3>₦ <?php echo number_format($total_tuition_fee, 0); ?></h3>
      </div>
    </div>
  </div>

  <!-- Paid -->
  <div class="col-md-6 col-lg-3">
    <div class="stat-card" 
         style="background: linear-gradient(135deg, #34D399, #6EE7B7); color: #FFFFFF;">
      <i class="fas fa-check-circle icon" style="color:#B7F5D6;"></i>
      <div>
        <h6>Paid</h6>
        <h3>₦ <?php echo number_format($paid_amount, 0); ?></h3>
      </div>
    </div>
  </div>

  <!-- Outstanding -->
  <div class="col-md-6 col-lg-3">
    <div class="stat-card" 
         style="background: linear-gradient(135deg, #F59E0B, #FCD34D); color: #2E2E2E;">
      <i class="fas fa-exclamation-circle icon" style="color:#FFE8A1;"></i>
      <div>
        <h6>Outstanding</h6>
        <h3>₦ <?php echo number_format($outstanding_fee, 0); ?></h3>
      </div>
    </div>
  </div>

  <!-- Arrears Balance -->
  <div class="col-md-6 col-lg-3">
    <div class="stat-card" 
         style="background: linear-gradient(135deg, #3ABAB4, #66D9D3); color: #FFFFFF;">
      <i class="fas fa-wallet icon" style="color:#A7E6E3;"></i>
      <div>
        <h6>Arrears Balance</h6>
        <h3>₦ <?php echo number_format($arrears_balance, 0); ?></h3>
      </div>
    </div>
  </div>

</div>
<?php endif; ?>


<br>



<!-- ====== PERFORMANCE + NOTIFICATIONS ====== -->
<div class="row g-3">
  <div class="col-md-6">
    <div class="card shadow-sm border-0">
      <div class="card-header bg-primary text-white">
        <i class="fas fa-user-graduate"></i> Top Performing Students
      </div>
      <div class="card-body" style="max-height:300px; overflow-y:auto;">
        <?php
        $top_students = mysqli_query($connection, "SELECT name, reg_number, class, students_sub_average FROM positions ORDER BY students_sub_average DESC LIMIT 5");
        while ($s = mysqli_fetch_assoc($top_students)) { ?>
          <div class="student-performance">
            <strong><?php echo $s['name']; ?></strong> 
            <small class="text-muted">(<?php echo $s['class']; ?>)</small>
            <div class="progress mt-1">
              <div class="progress-bar bg-success" style="width: <?php echo $s['students_sub_average']; ?>%;"></div>
            </div>
            <small>Average: <?php echo $s['students_sub_average']; ?>%</small>
          </div>
          <hr>
        <?php } ?>
      </div>
    </div>
  </div>

  <div class="col-md-6">
    <div class="card shadow-sm border-0">
      <div class="card-header bg-danger text-white">
        <i class="fas fa-bell"></i> Staff Notifications
      </div>
      <div class="card-body" style="max-height:300px; overflow-y:auto;">
        <?php
        $notes = mysqli_query($connection, "SELECT message, created_at FROM notifications WHERE target='all' AND is_active=1 ORDER BY created_at DESC LIMIT 5");
        while ($n = mysqli_fetch_assoc($notes)) { ?>
          <div class="alert alert-light border-start border-danger">
            <small class="text-muted"><i class="far fa-clock"></i> <?= date('d M Y, h:i A', strtotime($n['created_at'])); ?></small>
            <p class="mb-1"><?= $n['message']; ?></p>
          </div>
        <?php } ?>
      </div>
    </div>
  </div>
</div>


<!-- Latest Students + Best Subject Performers -->
<div class="row mt-4">
  <!-- Latest Students -->
  <div class="col-md-6">
    <div class="card shadow-lg">
      <div class="card-header bg-info text-white">
        <h5><i class="fas fa-user-plus"></i> Latest Students Enrolled</h5>
      </div>
      <div class="card-body p-0" style="max-height: 300px; overflow-y:auto;">
        <ul class="list-group list-group-flush">
          <?php 
          $query = "SELECT firstname, othername, lastname, class, reg_number 
                    FROM students ORDER BY id DESC LIMIT 5";
          $result = mysqli_query($connection, $query);
          while ($row = mysqli_fetch_assoc($result)): ?>
          <li class="list-group-item d-flex justify-content-between align-items-center">
            <div>
              <h6 class="mb-0"><?php echo $row['firstname'].' '.$row['othername'].' '.$row['lastname']; ?></h6>
              <small class="text-muted">Reg No: <?php echo $row['reg_number']; ?> | Class: <?php echo $row['class']; ?></small>
            </div>
            <i class="fas fa-user text-primary"></i>
          </li>
          <?php endwhile; ?>
        </ul>
      </div>
    </div>
  </div>

  <!-- Best Subject Performers -->
  <div class="col-md-6">
    <div class="card shadow-lg">
      <div class="card-header bg-warning">
        <h5><i class="fas fa-star"></i> Best Subject Performers</h5>
      </div>
      <div class="card-body p-0" style="max-height: 300px; overflow-y:auto;">
        <table class="table table-hover table-sm mb-0">
          <thead class="thead-dark">
            <tr>
              <th>Student</th>
              <th>Class</th>
              <th>Subject</th>
              <th>Total</th>
            </tr>
          </thead>
          <tbody>
            <?php 
            $query = "SELECT reg_number, name, class, subjects, subject_total 
                      FROM results1 ORDER BY subject_total DESC LIMIT 5";
            $result = mysqli_query($connection, $query);
            while ($row = mysqli_fetch_assoc($result)): ?>
            <tr>
              <td><?php echo $row['name']; ?> <small class="text-muted">(<?php echo $row['reg_number']; ?>)</small></td>
              <td><?php echo $row['class']; ?></td>
              <td><?php echo $row['subjects']; ?></td>
              <td><span class="badge bg-success"><?php echo $row['subject_total']; ?></span></td>
            </tr>
            <?php endwhile; ?>
          </tbody>
        </table>
      </div>
    </div>
  </div>
</div>

<?php

if ($userrole === 11) {
    ?>
<!-- ====== FEE CHART ====== -->
<div class="card mt-4 shadow-sm border-0">
  <div class="card-header bg-gradient text-white" style="background:linear-gradient(90deg,#007bff,#00c6ff);">
    <i class="fas fa-chart-bar"></i> Term Fee Summary
  </div>
  <div class="card-body">
    <canvas id="feeChart"></canvas>
  </div>
</div>

<?php

}
    ?>

<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<script>
const ctx = document.getElementById('feeChart').getContext('2d');
new Chart(ctx, {
  type: 'bar',
  data: {
    labels: ['Total Fee', 'Paid', 'Outstanding'],
    datasets: [{
      label: 'Ã¢â€šÂ¦',
      data: [<?php echo $total_tuition_fee; ?>, <?php echo $paid_amount; ?>, <?php echo $outstanding_fee; ?>],
      backgroundColor: ['#019688', '#DFF0D8', '#A1D6AF'],
      borderRadius: 6
    }]
  },
  options: {
    responsive: true,
    scales: { y: { beginAtZero: true } },
    plugins: { legend: { display: false } }
  }
});
</script>

<style>
  .stat-card {
    display: flex;
    align-items: center;
    justify-content: flex-start;
    padding: 15px;
    border-radius: 12px;
    transition: all 0.3s ease-in-out;
    gap: 15px;
  }
  .stat-card .icon {
    font-size: 2rem;
  }
  .stat-card:hover {
    transform: translateY(-5px);
    box-shadow: 0 8px 18px rgba(0,0,0,0.1);
  }
  .student-performance {
    animation: fadeInUp 0.8s ease both;
  }
  @keyframes fadeInUp {
    from { opacity: 0; transform: translateY(10px); }
    to { opacity: 1; transform: translateY(0); }
  }
  
  .widget-small {
  border-radius: 10px;
  background: #fff;
  transition: all 0.3s ease;
  box-shadow: 0 4px 8px rgba(0,0,0,0.08);
}
.widget-small:hover {
  transform: translateY(-5px);
  box-shadow: 0 8px 16px rgba(0,0,0,0.15);
}
.widget-small .icon {
  font-size: 34px;
  color: #fff;
  border-radius: 50%;
  padding: 10px;
  margin-right: 12px;
}
.widget-content {
  display: flex;
  align-items: center;
}
.card {
  border: none;
  border-radius: 12px;
}
.card-header {
  border-top-left-radius: 12px;
  border-top-right-radius: 12px;
  font-weight: bold;
}
.list-group-item {
  border: none;
  border-bottom: 1px solid #f1f1f1;
}
.list-group-item:hover {
  background-color: #f9f9f9;
}

</style>

<?php } ?>

<?php
if (isset($_SESSION['student'])) {
    // === Get logged-in student reg number (replace with your session variable) ===
$studentreg = $student_reg_number;


  // === Fetch Fee Stats ===
  $fee_query = "
      SELECT 
          COALESCE(SUM(total_fee), 0) AS tuition_fee,
          COALESCE(SUM(student_balance), 0) AS fee_balance,
          COALESCE(SUM(amount_paid), 0) AS amount_paid
      FROM fee_payment
      WHERE reg_number = '{$studentreg}' 
        AND fee_term = '{$current_term}' 
        AND fee_session = '{$current_session}'
  ";
  $fee_result = mysqli_fetch_assoc(mysqli_query($connection, $fee_query));
  $tuition_fee = $fee_result['tuition_fee'];
  $fee_balance = $fee_result['fee_balance'];
  $amount_paid = $fee_result['amount_paid'];

  // === Fetch Total Subjects Registered ===
  $subject_query = "
      SELECT COUNT(*) AS total_subjects
      FROM subjects
      WHERE reg_number = '{$studentreg}'
        AND term = '{$current_term}'
        AND session = '{$current_session}'
  ";
  $total_subjects = mysqli_fetch_assoc(mysqli_query($connection, $subject_query))['total_subjects'] ?? 0;

  // === Fetch Total Invoice Balance ===
  $invoice_query = "
      SELECT COALESCE(SUM(balance), 0) AS invoice_balance
      FROM inventory_invoices
      WHERE reg_number = '{$studentreg}'
  ";
  $invoice_balance = mysqli_fetch_assoc(mysqli_query($connection, $invoice_query))['invoice_balance'] ?? 0;

  // === Recent Attendance Records ===
  $attendance_query = "
      SELECT date, term, session, class, roll_call, afternoonrollcall
      FROM student_attendance
      WHERE reg_number = '{$studentreg}'
      ORDER BY date DESC
      LIMIT 5
  ";
  $attendance_result = mysqli_query($connection, $attendance_query);
?>

<!-- ====== STYLES & SCRIPTS ====== -->

<script src="https://kit.fontawesome.com/a076d05399.js" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>

<style>
 a {
  text-decoration: none !important;
}
  .dashboard-header {
    background: linear-gradient(135deg, #019688, #DFF0D8);
    color: white;
    border-radius: 12px;
    padding: 20px;
  }
  .stat-card {
    transition: all 0.3s ease;
    border: none;
  }
  .stat-card:hover {
    transform: translateY(-5px);
    box-shadow: 0 8px 16px rgba(0,0,0,0.15);
  }
  .icon {
    background: rgba(255, 255, 255, 0.2);
    padding: 12px;
    border-radius: 50%;
  }
  .table thead {
    background-color: #343a40;
    color: #fff;
  }
</style>

<!-- ====== DASHBOARD CONTENT ====== -->
<div class="container-fluid mt-4">

  <!-- Header -->
  <div class="dashboard-header mb-4 shadow-sm">
    <h4><?php echo htmlspecialchars($full_name); ?> </h4>
    <p class="mb-0">Here's your current academic and financial overview for <?= $current_term; ?>, <?= $current_session; ?> session.</p>
  </div>
  <br>

  <!-- Stats Cards -->
  <div class="row g-3 mb-4">

     <div class="col-md-6 col-lg-3">
        
        
        <div class="stat-card bg-primary text-white">
      <i class="fas fa-school icon"></i>
      <div>
        <h6 class="text-uppercase mb-1">Tuition Fee</h6>
          <h3>₦<?= number_format($tuition_fee, 0); ?></h3>
      </div>
    </div>
        
     
    </div>

    <div class="col-md-6 col-lg-3">
        
        
   <div class="stat-card bg-success text-white">
      <i class="fas fa-wallet fa-2x"></i>
      <div>
          <h6 class="text-uppercase mb-1">Fee Balance</h6>
          <h3>₦<?= number_format($fee_balance, 0); ?></h3>
      </div>
    </div>
        
        
    
    </div>

    <div class="col-md-6 col-lg-3">
        
        
        <div class="stat-card bg-warning text-white">
      <i class="fas fa-book fa-2x"></i>
      <div>
          <h6 class="text-uppercase mb-1">Subjects Registered</h6>
          <h3><?= $total_subjects; ?></h3>
      </div>
    </div>
        
        
      
    </div>

    <div class="col-md-6 col-lg-3">
        
        
        <div class="stat-card bg-info text-white">
      <i class="fas fa-file-invoice-dollar fa-2x"></i>
      <div>
           <h6 class="text-uppercase mb-1">Invoice Balance</h6>
          <h3>₦<?= number_format($invoice_balance, 0); ?></h3>
      </div>
    </div>
        
 
    </div>
  </div>
  
  <br>

  <!-- Charts and Table -->
  <div class="row g-3">
    <!-- Fee Progress Chart -->
    <div class="col-md-6">
      <div class="card shadow-sm p-4 rounded-4">
        <h5 class="mb-3"><i class="fas fa-chart-pie me-2 text-primary"></i> Fee Payment Overview</h5>
        <canvas id="feeChart" height="200"></canvas>
      </div>
    </div>

    <!-- Attendance Table -->
    <div class="col-md-6">
      <div class="card shadow-sm p-4 rounded-4">
        <h5 class="mb-3"><i class="fas fa-calendar-check me-2 text-success"></i> Recent Attendance</h5>
        <div class="table-responsive">
          <table class="table table-striped table-hover align-middle">
            <thead>
              <tr>
                <th>Date</th>
                <th>Term</th>
                <th>Session</th>
                <th>Morning Roll Call</th>
                <th>Afternoon Roll Call</th>
              </tr>
            </thead>
            <tbody>
              <?php if (mysqli_num_rows($attendance_result) > 0): ?>
                <?php while ($row = mysqli_fetch_assoc($attendance_result)): ?>
                  <tr>
                    <td><?= htmlspecialchars($row['date']); ?></td>
                    <td><?= htmlspecialchars($row['term']); ?></td>
                    <td><?= htmlspecialchars($row['session']); ?></td>
                    <td><?= htmlspecialchars($row['roll_call']); ?></td>
                    <td><?= htmlspecialchars($row['afternoonrollcall']); ?></td>
                  </tr>
                <?php endwhile; ?>
              <?php else: ?>
                <tr><td colspan="5" class="text-center text-muted">No attendance records found.</td></tr>
              <?php endif; ?>
            </tbody>
          </table>
        </div>
      </div>
    </div>
  </div>
</div>

<!-- ====== CHART SCRIPT ====== -->
<script>
  const ctx = document.getElementById('feeChart').getContext('2d');
  const feeChart = new Chart(ctx, {
    type: 'doughnut',
    data: {
      labels: ['Paid', 'Balance'],
      datasets: [{
        data: [<?= $amount_paid; ?>, <?= $fee_balance; ?>],
        backgroundColor: ['#019688', '#DFF0D8'],
        borderWidth: 1
      }]
    },
    options: {
      responsive: true,
      plugins: {
        legend: { position: 'bottom' },
        title: { display: true, text: 'Tuition Payment Status' }
      }
    }
  });
</script>

<?php } ?>


<!-- ====================== DASHBOARD END ====================== -->
