<?php
session_start();
error_reporting(0);
include('includes/config.php');

if (strlen($_SESSION['alogin']) == 0) {
  header('location:index.php');
  exit;
}

// Block student
if (isset($_GET['inid'])) {
  $id = $_GET['inid'];
  $status = 0;
  $sql = "UPDATE tblstudents SET Status=:status WHERE id=:id";
  $query = $dbh->prepare($sql);
  $query->bindParam(':id', $id, PDO::PARAM_STR);
  $query->bindParam(':status', $status, PDO::PARAM_STR);
  $query->execute();
  $_SESSION['updatemsg'] = "Student blocked successfully";
  header('location:reg-students.php');
  exit;
}

// Approve student
if (isset($_GET['appid'])) {
  $id = $_GET['appid'];
  $status = 1;
  $sql = "UPDATE tblstudents SET Status=:status WHERE id=:id";
  $query = $dbh->prepare($sql);
  $query->bindParam(':id', $id, PDO::PARAM_STR);
  $query->bindParam(':status', $status, PDO::PARAM_STR);
  $query->execute();
  $_SESSION['updatemsg'] = "Student approved successfully";
  header('location:reg-students.php');
  exit;
}

// Activate student
if (isset($_GET['id'])) {
  $id = $_GET['id'];
  $status = 1;
  $sql = "UPDATE tblstudents SET Status=:status WHERE id=:id";
  $query = $dbh->prepare($sql);
  $query->bindParam(':id', $id, PDO::PARAM_STR);
  $query->bindParam(':status', $status, PDO::PARAM_STR);
  $query->execute();
  $_SESSION['updatemsg'] = "Student activated successfully";
  header('location:reg-students.php');
  exit;
}
?>

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8" />
  <title>Manage Registered Students | Library System</title>
  <meta name="viewport" content="width=device-width, initial-scale=1" />
  <link rel="icon" type="image/x-icon" href="../<?php echo $_SESSION['logo']; ?>">

  <!-- Bootstrap -->
  <link href="https://cdn.jsdelivr.net/npm/bootstrap@4.6.2/dist/css/bootstrap.min.css" rel="stylesheet">
  <!-- FontAwesome -->
  <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css" rel="stylesheet">
  <!-- DataTables -->
  <link href="https://cdn.datatables.net/1.13.6/css/dataTables.bootstrap4.min.css" rel="stylesheet">

  <style>
    .square-card {
      background-color: #f8f9fa;
      border: 1px solid #dee2e6;
      border-radius: 5px;
      box-shadow: 0 4px 8px rgba(0, 0, 0, 0.05);
    }

    .flash-message {
      max-width: 600px;
      margin: 0 auto 15px;
    }

    .table-wrapper {
      overflow-x: auto;
      padding: 10px;
    }

    .col-md-12 h5 {
      color: #0d6efd;
      font-size: 20px;
    }

    .dataTables_filter label {
      color: #000 !important;
      font-weight: 500;
    }

    .dataTables_filter input {
      height: 32px;
      font-size: 0.95rem;
      padding: 4px 8px;
    }

    .select2-container .select2-selection--single {
      height: 38px !important;
      display: flex;
      align-items: center;
    }

    .select2-selection__arrow {
      height: 100% !important;
    }

    .form-row>[class*="col-"] {
      margin-bottom: 0 !important;
    }

    .dataTables_length select {
      width: auto !important;
      min-width: 60px;
      padding-right: 25px;
      /* space for arrow */
    }
  </style>
</head>

<body>

  <div class="d-flex flex-column min-vh-100">
    <?php include('includes/header.php'); ?>

    <div class="main-content flex-grow-1">
      <div class="row pad-botm mb-4">
        <div class="col-md-12">
          <h5 class="header-line" style="color:#0d6efd;">MANAGE REGISTERED STUDENTS</h5>
        </div>
      </div>

      <!-- Flash Messages -->
      <div class="row justify-content-center">
        <div class="col-md-8">
          <?php foreach (['error', 'msg', 'updatemsg', 'delmsg'] as $type): ?>
            <?php if (!empty($_SESSION[$type])): ?>
              <div class="alert alert-<?php echo ($type == 'error') ? 'danger' : 'success'; ?> flash-message">
                <strong><?php echo ucfirst($type); ?> :</strong> <?php echo htmlentities($_SESSION[$type]); ?>
                <?php $_SESSION[$type] = ""; ?>
              </div>
            <?php endif; ?>
          <?php endforeach; ?>
        </div>
      </div>

      <!-- Students Table -->
      <div class="card square-card mb-5">
        <div class="card-header bg-secondary text-white">
          <i class="fa fa-users mr-2"></i> Students List
        </div>
        <div class="card-body table-wrapper">
          <!-- Filters -->
          <form method="GET" id="filterForm" class="mb-3">
            <div class="form-row align-items-end">

              <div class="col-md-3">
                <select name="department_id" class="form-control select2">
                  <option value="">All Departments</option>
                  <?php
                  $deptQuery = $dbh->query("SELECT department_id, department_name FROM tbldepartment ORDER BY department_name ASC");
                  while ($dept = $deptQuery->fetch(PDO::FETCH_ASSOC)) {
                    $selected = (isset($_GET['department_id']) && $_GET['department_id'] == $dept['department_id']) ? 'selected' : '';
                    echo "<option value='{$dept['department_id']}' $selected>{$dept['department_name']}</option>";
                  }
                  ?>
                </select>
              </div>

              <div class="col-md-2">
                <select name="degree_id" class="form-control select2">
                  <option value="">All Degrees</option>
                  <?php
                  $degreeQuery = $dbh->query("SELECT degree_id, degree_name FROM tbldegree ORDER BY degree_name ASC");
                  while ($degree = $degreeQuery->fetch(PDO::FETCH_ASSOC)) {
                    $selected = (isset($_GET['degree_id']) && $_GET['degree_id'] == $degree['degree_id']) ? 'selected' : '';
                    echo "<option value='{$degree['degree_id']}' $selected>{$degree['degree_name']}</option>";
                  }
                  ?>
                </select>
              </div>

              <div class="col-md-2">
                <select name="current_year" class="form-control select2">
                  <option value="">All Years</option>
                  <option value="I Year" <?= (!empty($_GET['current_year']) && $_GET['current_year'] == 'I Year') ? 'selected' : '' ?>>I Year</option>
                  <option value="II Year" <?= (!empty($_GET['current_year']) && $_GET['current_year'] == 'II Year') ? 'selected' : '' ?>>II Year</option>
                  <option value="III Year" <?= (!empty($_GET['current_year']) && $_GET['current_year'] == 'III Year') ? 'selected' : '' ?>>III Year</option>
                  <option value="IV Year" <?= (!empty($_GET['current_year']) && $_GET['current_year'] == 'IV Year') ? 'selected' : '' ?>>IV Year</option>
                  <option value="Completed / Alumni" <?= (!empty($_GET['current_year']) && $_GET['current_year'] == 'Completed / Alumni') ? 'selected' : '' ?>>Completed / Alumni</option>
                </select>
              </div>

              <div class="col-md-2">
                <select name="shift" class="form-control select2">
                  <option value="">All Shifts</option>
                  <option value="1" <?= (!empty($_GET['shift']) && $_GET['shift'] == '1') ? 'selected' : '' ?>>Morning
                  </option>
                  <option value="2" <?= (!empty($_GET['shift']) && $_GET['shift'] == '2') ? 'selected' : '' ?>>Evening
                  </option>
                </select>
              </div>

              <div class="col-md-2">
                <select name="student_status" class="form-control select2">
                  <option value="">All Students</option>
                  <option value="1" <?= (!empty($_GET['student_status']) && $_GET['student_status'] == '1') ? 'selected' : '' ?>>Active
                  </option>
                  <option value="2" <?= (!empty($_GET['student_status']) && $_GET['student_status'] == '2') ? 'selected' : '' ?>>Pending
                  </option>
                  <option value="0" <?= (!empty($_GET['student_status']) && $_GET['student_status'] == '0') ? 'selected' : '' ?>>Blocked
                  </option>
                </select>
              </div>

              <div class="col-md-1 d-flex justify-content-end">
                <button type="submit" class="btn btn-primary mr-2">Apply</button>
              </div>
            </div>
          </form>


          <div id="studentsTableContainer">
            <table id="studentsTable" class="table table-bordered table-hover table-sm text-dark">
              <thead class="table-theme-header">
                <tr>
                  <th>#</th>
                  <th>Student ID</th>
                  <th>Name</th>
                  <th>Department</th>
                  <th>Mobile</th>
                  <th>Academic Year</th>
                  <th>Current Year</th>
                  <th>Status</th>
                  <th>Action</th>
                </tr>
              </thead>
              <tbody>
                <?php

                $conditions = [];
                $params = [];

                if (!empty($_GET['department_id'])) {
                  $conditions[] = "s.department_id = :department_id";
                  $params[':department_id'] = $_GET['department_id'];
                }

                if (!empty($_GET['degree_id'])) {
                  $conditions[] = "s.degree_id = :degree";
                  $params[':degree'] = $_GET['degree_id'];
                }

                if (!empty($_GET['shift'])) {
                  $conditions[] = "s.shift = :shift";
                  $params[':shift'] = $_GET['shift'];
                }

                if (isset($_GET['student_status']) && $_GET['student_status'] !== '') {
                  $conditions[] = "s.Status = :status";
                  $params[':status'] = $_GET['student_status'];
                }

                // Base query
                $sql = "SELECT s.*, d.department_name FROM tblstudents s 
        LEFT JOIN tbldepartment d ON s.department_id = d.department_id";

                // Apply filters if any
                if ($conditions) {
                  $sql .= " WHERE " . implode(' AND ', $conditions);
                }

                $sql .= " ORDER BY s.FullName ASC";

                $query = $dbh->prepare($sql);
                foreach ($params as $key => $value) {
                  $query->bindValue($key, $value);
                }
                $query->execute();

                // $query = $dbh->prepare($sql);
                // $query->execute();
                $results = $query->fetchAll(PDO::FETCH_OBJ);

                $cnt = 1;
                foreach ($results as $result) {

                  // --- Normalize passed_out_year and parse start/end years ---
                  $passedOutRaw = trim($result->passed_out_year ?? '');
                  // remove spaces and common dash variants
                  $passedOut = str_replace([' ', '–', '—'], ['', '', '-', '-'], $passedOutRaw);
                  $passedOut = preg_replace('/\s+/', '', $passedOut); // extra safety
                
                  if (strpos($passedOut, '-') !== false) {
                    list($startYear, $endYear) = explode('-', $passedOut, 2);
                  } elseif ($passedOut === '') {
                    // fallback if empty
                    $startYear = $endYear = 0;
                  } else {
                    $startYear = $endYear = $passedOut;
                  }

                  $startYear = intval($startYear);
                  $endYear = intval($endYear);

                  // --- Current academic year computation (June boundary) ---
                  $currentYear = intval(date('Y'));
                  $currentMonth = intval(date('n')); // 1..12
                  $academicYear = ($currentMonth < 6) ? $currentYear - 1 : $currentYear;

                  // --- Determine year label ---
                  if ($endYear > 0 && ($academicYear > $endYear || ($academicYear == $endYear && $currentMonth >= 6))) {
                    $yearLabel = "Completed / Alumni";
                  } else {
                    $yearDiff = ($startYear > 0) ? ($academicYear - $startYear + 1) : 0;
                    switch ($yearDiff) {
                      case 1:
                        $yearLabel = "I Year";
                        break;
                      case 2:
                        $yearLabel = "II Year";
                        break;
                      case 3:
                        $yearLabel = "III Year";
                        break;
                      case 4:
                        $yearLabel = "IV Year";
                        break;
                      default:
                        $yearLabel = "Completed / Alumni";
                        break;
                    }
                  }

                  // --- Apply current_year filter (if set) BEFORE printing ANY HTML ---
                  if (!empty($_GET['current_year']) && $_GET['current_year'] != $yearLabel) {
                    continue; // skip this student entirely
                  }

                  // If passed the filter — output the row
                  ?>
                  <tr>
                    <td><?php echo htmlentities($cnt++); ?></td>
                    <td><?php echo htmlentities($result->StudentId); ?></td>
                    <td class="font-weight-bold"
                      style="color: <?php echo $_SESSION['theme_color'] ?? '#3498db'; ?> !important;">
                      <?php echo htmlentities($result->FullName); ?>
                    </td>
                    <td><?php echo htmlentities($result->department_name); ?></td>
                    <td><?php echo htmlentities($result->MobileNumber); ?></td>
                    <td><?php echo htmlentities($result->passed_out_year); ?></td>
                    <td><?php echo htmlentities($yearLabel); ?></td>
                    <td>
                      <?php
                      if ($result->Status == 1) {
                        echo '<span class="badge badge-success">Active</span>';
                      } elseif ($result->Status == 0) {
                        echo '<span class="badge badge-danger">Blocked</span>';
                      } elseif ($result->Status == 2) {
                        echo '<span class="badge badge-warning">Pending</span>';
                      }
                      ?>
                    </td>
                    <td>
                      <?php if ($result->Status == 1): ?>
                        <a href="reg-students.php?inid=<?php echo htmlentities($result->id); ?>"
                          onclick="return confirm('Are you sure you want to block this student?');"
                          class="btn btn-sm btn-danger">
                          <i class="fa fa-ban"></i> Block
                        </a>
                      <?php elseif ($result->Status == 0): ?>
                        <a href="reg-students.php?id=<?php echo htmlentities($result->id); ?>"
                          onclick="return confirm('Are you sure you want to activate this student?');"
                          class="btn btn-sm btn-primary">
                          <i class="fa fa-check"></i> Activate
                        </a>
                      <?php elseif ($result->Status == 2): ?>
                        <a href="reg-students.php?appid=<?php echo htmlentities($result->id); ?>"
                          onclick="return confirm('Are you sure you want to approve this student?');"
                          class="btn btn-sm btn-success">
                          <i class="fa fa-thumbs-up"></i> Approve
                        </a>
                      <?php endif; ?>

                      <a href="view-profile.php?sid=<?php echo htmlentities($result->StudentId); ?>"
                        class="btn btn-sm btn-info">
                        <i class="fa fa-eye"></i> View
                      </a>
                    </td>
                  </tr>
                  <?php
                } // end foreach
                

                ?>
              </tbody>
            </table>
          </div>


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

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

  <!-- Scripts -->
  <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
  <script src="https://cdn.jsdelivr.net/npm/bootstrap@4.6.2/dist/js/bootstrap.bundle.min.js"></script>
  <script src="https://cdn.datatables.net/1.13.6/js/jquery.dataTables.min.js"></script>
  <script src="https://cdn.datatables.net/1.13.6/js/dataTables.bootstrap4.min.js"></script>

  <script>
    $(document).ready(function () {
      $('#studentsTable').DataTable({
        pageLength: 10,
        lengthChange: true,
        ordering: true,
        responsive: true,
        language: {
          search: "🔍 Search students:"
        }
      });
    });
  </script>
  <script>
    $(document).ready(function () {
      const tableContainer = $('#studentsTableContainer');

      // When filter form is submitted
      $('#filterForm').on('submit', function (e) {
        e.preventDefault();
        loadTable();
      });

      // Optional: auto-submit on dropdown change
      // $('#filterForm select').change(function () {
      //   $('#filterForm').submit();
      // });

      function loadTable() {
        $.ajax({
          url: 'reg-students.php', // same page (it reloads only the table area)
          type: 'GET',
          data: $('#filterForm').serialize(),
          beforeSend: function () {
            tableContainer.html('<div class="text-center p-3">Loading...</div>');
          },
          success: function (response) {
            // Extract only the table part from returned HTML
            const tableHTML = $(response).find('#studentsTableContainer').html();
            tableContainer.html(tableHTML);

            // Reinitialize DataTable after reload
            $('#studentsTable').DataTable({
              pageLength: 10,
              lengthChange: true,
              ordering: true,
              responsive: true,
              language: { search: "🔍 Search students:" }
            });
          },
          error: function () {
            tableContainer.html('<div class="alert alert-danger">Failed to load data.</div>');
          }
        });
      }
    });

    $(document).ready(function () {
      function initTable() {
        if ($.fn.dataTable.isDataTable('#studentsTable')) {
          $('#studentsTable').DataTable().destroy();
        }
        $('#studentsTable').DataTable({
          pageLength: 10,
          lengthChange: true,
          ordering: true,
          responsive: true,
          language: { search: "🔍 Search students:" }
        });
      }

      initTable();

      // When filter form is submitted
      $('#filterForm').on('submit', function (e) {
        e.preventDefault();
        const tableContainer = $('#studentsTableContainer');
        $.ajax({
          url: 'reg-students.php',
          type: 'GET',
          data: $('#filterForm').serialize(),
          beforeSend: function () {
            tableContainer.html('<div class="text-center p-3">Loading...</div>');
          },
          success: function (response) {
            const tableHTML = $(response).find('#studentsTableContainer').html();
            tableContainer.html(tableHTML);
            initTable();
          },
          error: function () {
            tableContainer.html('<div class="alert alert-danger">Failed to load data.</div>');
          }
        });
      });
    });

  </script>

  <!-- Select2 CSS -->
  <link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet" />

  <!-- Select2 JS -->
  <script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script>

  <script>
    $(document).ready(function () {
      // Initialize select2 with placeholder and search
      $('.select2').select2({
        width: '100%',
        // placeholder: 'Select an option',
        allowClear: true
      });
    });
  </script>


</body>

</html>